A lightweight PostToolUse hook for Claude Code that tracks token consumption and warns you before hitting the context window limit.
Without this hook, Claude Code sessions can silently exhaust their context window, causing automatic compression that loses conversation history. This monitor gives you advance warning so you can save state and restart cleanly.
After every tool call, the hook reads the session transcript to find the latest token count from the API response metadata. When usage crosses a configurable threshold, it injects a warning into the conversation:
- Warning (default 225K tokens): "Start wrapping up — save state and prepare for session restart."
- Critical (default 256K tokens): "STOP and restart the session NOW."
# Create hooks directory if it doesn't exist
mkdir -p ~/.claude/hooks
# Copy the script
cp context_window_monitor.py ~/.claude/hooks/
chmod +x ~/.claude/hooks/context_window_monitor.pyOpen your Claude Code settings file (~/.claude/settings.json) and add the hook:
{
"hooks": {
"PostToolUse": [
{
"matcher": "",
"hooks": [
{
"type": "command",
"command": "python3 ~/.claude/hooks/context_window_monitor.py"
}
]
}
]
}
}Or add it via the CLI:
claude settings add-hook PostToolUse \
--command "python3 ~/.claude/hooks/context_window_monitor.py"Start a new Claude Code session and use a few tools. As you approach the warning threshold, you'll see context injection messages appear.
Set environment variables to customize thresholds:
| Variable | Default | Description |
|---|---|---|
CONTEXT_WARN_THRESHOLD |
225000 |
Token count that triggers the "wrap up" warning |
CONTEXT_CRITICAL_THRESHOLD |
256000 |
Token count that triggers the "stop now" warning |
For the 200K context window (Sonnet):
export CONTEXT_WARN_THRESHOLD=175000
export CONTEXT_CRITICAL_THRESHOLD=200000For the 1M context window (Opus):
export CONTEXT_WARN_THRESHOLD=900000
export CONTEXT_CRITICAL_THRESHOLD=1000000You can set these in your shell profile (~/.bashrc, ~/.zshrc) or in your Claude Code settings.
The hook reads the session transcript JSONL file located at:
~/.claude/projects/<project-hash>/<session-id>.jsonl
Each API response in the transcript includes a usage object:
{
"message": {
"usage": {
"cache_read_input_tokens": 180000,
"input_tokens": 5000,
"cache_creation_input_tokens": 20000
}
}
}The hook sums these three fields to determine total context usage. It reads only the last 50KB of the transcript for efficiency.
- Python 3.10+
- Claude Code CLI
No external dependencies required.
MIT