context-doctor 🩺
[CI] [npm] [npm downloads] [MCP Registry] [AgentHub 已收录:context-doctor] [license: MIT] [macOS | Linux | Windows]
See where your AI agent's tokens go, and stop paying for the ones that do nothing.
AI agents re-send their whole context on every message: old tool output, pasted files, long instructions. A 500k-token session pays for all of it again each time, and at full price after a coffee break, when the prompt cache has expired. context-doctor measures that waste on your own sessions, in dollars, and removes it at the moments it pays: before it enters the context, while it sits there, and on every request. It runs on your machine, needs no API key, sends no telemetry, and works with Claude Code (terminal, IDE, desktop app), Claude Desktop, ChatGPT, Codex, Cursor, Gemini CLI, GitHub Copilot, any app on the Anthropic, OpenAI or Gemini API, and CI. MIT licensed, Node 20+, macOS, Linux and Windows.
[npx context-doctor savings: input billed, what /compact at cold resumes, autopilot and an earlier auto-compact window would have saved]
Which context-doctor is this? Several projects share the name. This one is context-doctor on npm and io.github.KushalP1/context-doctor in the official MCP Registry (see the entry). The registry is a service, not a list in a GitHub repo: the modelcontextprotocol/servers repository holds only reference servers and points to the registry for the rest. Built and maintained by gAI Ventures.
Quick start
Pick where you work. Each takes about a minute and is fully reversible.
What it does
Measure, in dollars, on your own history (profiling)
spend: one bill across Claude Code (subagents and workflow agents included), Codex, Gemini CLI and Cursor, by tool, project, model and day, at list prices (spend and budget).
savings: what your recent Claude Code sessions cost and what each fix below would have saved, replayed request by request against what you were billed.
overhead: what every request re-reads before your message (system prompt, tools, MCP servers, CLAUDE.md, rules, memory), each file priced per month.
tasks, reads, subagents, compactions: cost per commit; files read into session after session; whether each subagent was cheaper than the same steps in the parent; whether sessions work worse after compacting.
cache-misses: requests that re-wrote the prompt cache while it should still have been warm, priced, by model and context size, with the cause where the transcript shows one.
limits: your plan's 5-hour and weekly windows (Claude Pro/Max, recorded by the status line) and Codex's, the pace and when each runs out, and what 1M tokens of each kind cost in % of the limit, fitted on your own readings with the error shown.
cache-plan <request.json>: where an Anthropic API request should carry cache_control, and what it saves over N calls.
session, watch, analyze, report, dashboard: token breakdown and wasted-context findings for any session, conversation file or agent trace.
Keep waste out of the context (pack and overhead)
pack (and the pack_context MCP tool): only the chunks of a big document, PDF, log or codebase that a question needs, within a token budget, instead of the whole thing.
recall (and the recall MCP tool): the few lines of this session's own transcript a question needs, including turns a compaction summarised away and tool output autopilot cleared, with their time and position; secrets masked.
overhead split: turns a heavy CLAUDE.md or memory file into a lean one plus a reference file the agent opens when needed, word for word, nothing lost.
ci and the GitHub Action: review memory-file growth like any other cost.
Remove waste automatically
- A model-switch warning (
PreModelSwitch, Claude Code 2.1.251+) shows what a /model switch costs before it happens: the whole context re-written into the new model's cache.
- A subagent price (
PreToolUse on the Agent tool) shows what a subagent costs before it starts, at your own median for that type (the author's: $3.99 for general-purpose, $1.43 for Explore, 422 runs in 30 days), with the Sonnet price where it would run on Opus or Fable, and a total when launches bunch up. It never blocks.
- A compaction hook (
PreCompact) tells each Claude Code compaction what the session cannot lose (files changed, open tasks, your instructions, failing tests), so compacting saves tokens without losing the thread.
- An every-prompt hook (Claude Code, Codex, Gemini CLI; Cursor after each tool call) tells the model its real context size and the largest waste, and offers
/compact when you return to a big session after the cache expired.
- A session's own price: once a session passes $25, $100 and $500 (subagents included), the every-prompt hook tells you what it has cost and what each message now costs, and that
/compact or a fresh session cuts it (docs).
budget 50/day (or /week): the every-prompt hook in Claude Code, Codex and Gemini CLI says when today's spend passes 50%, 80% and 100% of it, and with --block holds prompts over budget; the status line shows $12/$50 today.
compact-window: sets Claude Code's own auto-compact window, measured on your history first. Works in the desktop app too.
cache-ttl: replays your own pauses at a 5-minute and a 1-hour prompt cache and sets Claude Code's promptCacheTtl to the cheaper one (the author's: 7% less main-conversation input at 1 hour; 22% less than the 5-minute default an API key gets). Same content either way, so no quality cost (fixes).
- Autopilot: a local proxy (or SDK wrapper) that clears stale tool output only when the prompt cache is cold, so a request never costs more.
What it saves
Measured, not modelled, on every Claude Code session on the author's machine (mostly Opus 5 and Fable 5 with the 1M window), priced the way the prompt cache bills it (cached reads at each model's read rate, 2.5-10% of input; writes 1.25x input for the 5-minute cache, 2x for the hour) at API list prices. Re-measured on 2026-10-13 with each request at its own model and current prices (Opus 5.5 is $4 per million input tokens with $0.20 reads). context-doctor savings runs the same measurement on yours.
1. Compacting when you come back (every Claude Code surface, desktop app included). 133 days, 479 returns to a session over 150k tokens after its prompt cache expired (65 idle minutes on the 1-hour cache, 10 on the 5-minute one that Claude Code 2.1.295 often writes); median context at the return, 522k tokens.
Each return counts only the messages up to the next return, and the compaction request is charged as a cost. Not counted: files the model may re-read after compacting, and what the summary leaves out. That is why this is advice with the numbers attached, not something done for you.
2. Autopilot (Claude Code in a terminal or IDE, API apps). 133 days, 67 sessions, replayed through the shipped autopilot code with real timestamps:
30 of 67 sessions save something, the best 34.9%: long sessions that go idle are where the money is. These sessions ran in the desktop app, which autopilot cannot reach, so for the author this is what the same sessions would have saved in a terminal; context-doctor savings separates the two for you. How it works →
3. Compacting earlier (automatic, every Claude Code surface, desktop app included). The offer in 1 is advice, and on the author's machine it was followed 1 time in 33. Claude Code has a native setting that needs nobody to follow anything: autoCompactWindow in ~/.claude/settings.json makes it compact as if the window were that size. context-doctor compact-window replays each session request by request at several sizes, priced as the cache bills (each simulated compaction pays its own request and a 20k-token summary at the output rate), and changes nothing until you pick one:
41 sessions. The cost is real: each compaction replaces the session's history with a summary, so a smaller window trades detail for money. That is why the command shows the table first and sets a window only when you name one (context-doctor compact-window 400k; off undoes it, and a backup of settings.json is kept).
Also measured:
- pack: 9 of 10 questions about this repository answered from 0.6% of its tokens. How →
- Counting Claude correctly: current Claude models pack 2.75 characters per token on prose (2.4 on code), not the 4 most tools assume: Claude counts about 40% more tokens than the usual 4-characters rule (~45% on prose, ~33% on code).
context-doctor accuracy re-checks the ratio on your own sessions. Why →
On a Claude subscription you do not pay list price; the same tokens come out of your usage limit instead. Anthropic does not publish how limits weight cached tokens, so read the dollars as the size of the effect, not as your bill.
Where it works
Not claimed, because no process on your machine sends those requests: trimming inside Claude Desktop chat, claude.ai, ChatGPT, Cursor's own subscription models, or Codex signed in with ChatGPT. Those get the rules and the measurements above, not autopilot.
The MCP server hands these standing rules, verbatim, to every chat where it is enabled (Cursor and Claude Code put them in front of the model; for Claude Desktop's classic Chat that is unverified):
- When asked about tokens, cost, speed or limits, and once at ~30 turns or 3+ large pastes: call profile_context BEFORE answering; in a chat app pass a
sketch. Act on its top finding. Do not estimate token counts yourself.
- When a chat grows long, offer a handoff once (save_handoff): only a new chat cuts its history.
- Summarize any paste or tool result over ~2k tokens into the points you need.
- Refer to earlier content by name; never re-quote it or inline base64.
- For a big file you won't edit, call pack_context with the question; don't read it whole.
- If optimize_context returns a pruned-turns digest, write its ≤150-token summary.
Rules 1-4 end exactly at character 512, the part ChatGPT's guide says must stand alone.
Commands
Privacy: everything runs on your machine. No API key is needed for anything core, nothing is sent anywhere, and no telemetry is collected; the proxy forwards your app's own credentials untouched and holds none of its own.
Speed: the history reports read each transcript once per run and keep what they took from it (token counts, times, ids, no message text) in ~/.cache/context-doctor, so a second fix or savings answers in under a second and later runs read only what was appended. CONTEXT_DOCTOR_NO_CACHE=1 keeps nothing; uninstall removes it (details).
What's new
- 0.44 Workflow agents on the bill, current prices, and an audit: Claude Code's workflow agents were in no report: on the author's last 30 days $1,494 of $5,542.
spend, the budget, a session's price, subagents and fix now count them, and spend equals an independent sum of every transcript to the cent. Prices re-read from each provider (Sonnet 5.5's cache read $0.10, gpt-5.5 $5/$30, the gpt-6 family); estimates are labelled. An audit fixed overhead --mcp launching a cloned repository's unapproved MCP servers, pack_context returning the agents' sign-in files, and more (details).
- 0.43 Long tool output,
fix for Codex, and a session's price: every Bash result stays in the conversation and is re-read on every later message until a compaction; fix now replays them at lower caps and, on a yes, sets Claude Code's bashOutputMaxChars, so longer output goes to a file the model can still open after a 2,000-character preview (the author's 30 days: $323 less at 8k, 9% of input). fix also works for Codex: it replays your rollouts at earlier auto-compact limits and sets model_auto_compact_token_limit in config.toml, on a machine with only Codex too. And the every-prompt hook now tells you once when a session passes $25, $100 and $500, with what each message costs from there (the author's: 15 sessions passed $25 in 30 days and spent $3,369 after).
- 0.42 An audit of 0.41: each Codex request counts once (forks repeat their parent's), the budget no longer double-counts a reply streamed across midnight, unpriced models show as such instead of $0, Cursor is read after it quits, and
CODEX_HOME is followed everywhere. fix's subagent lever reads agent files the way Claude Code merges them, and every writer of settings.json takes one lock, so concurrent runs lose nothing (details).
- 0.41 One bill, a budget, and the subagents' model:
context-doctor spend puts Claude Code (subagents included), Codex, Gemini CLI and Cursor on one bill by tool, project, model and day. context-doctor budget 50/day has the every-prompt hook tell you at 50%, 80% and 100%, and with --block holds prompts over budget; the status line shows $12/$50 today, at about 5 ms a prompt. fix gains subagent-model: subagents run on your main conversation's model (Opus or Fable included), and CLAUDE_CODE_SUBAGENT_MODEL set to Sonnet 5.5 would have cost the author $632 less in 30 days (38% of the subagents' $1,658); it changes the model, so it is applied only when you name it, and fix undo reverts it.
- 0.40 Reports in under a second:
fix, savings, compact-window, cache-ttl, cache-misses and overhead read each transcript once and keep what they took from it in ~/.cache/context-doctor, so a second run reads only what was appended: fix 23.5 s → 0.4 s, savings 41 s → 0.6 s on the author's 2.7 GB history, every figure unchanged (details). Also from a QA pass on 0.39: install then uninstall gives every config back byte for byte, and doctor warns about an out-of-date skill.
- 0.39
fix, the cache lifetime, the cache clock, and Antigravity: context-doctor fix turns the measurements into changes: every lever ranked by what it would have saved on your own sessions, with what each costs in quality, applied only on a yes, undone with fix undo, and re-measured afterwards (/context-doctor:fix in the plugin). cache-ttl replays your pauses at a 5-minute and a 1-hour prompt cache and sets Claude Code's promptCacheTtl to the cheaper one, a price-only change. On Claude Code 2.1.251+ the status line says until when the cache is warm and what going cold costs, cache-misses explains misses in Claude Code's own words, and install wires Google Antigravity.
- 0.38 Your limits in their own unit, regressions after upgrades, recall, and a subagent price:
context-doctor limits shows each plan window's %, pace and run-out time (Claude Pro/Max through the status line, Codex from its rollouts) and what 1M tokens cost in % of it, fitted on your readings with the error; savings then speaks in your limit too. cache-misses flags step changes after a Claude Code upgrade, recall searches the session's own transcript (compacted turns included), a hook prices a subagent before it starts (never blocking), and overhead prune switches off unused MCP servers and skills per project, reversibly. OpenAI caches count as warm for up to 24 hours. An independent QA pass's findings were fixed before the release.
- 0.37 Desktop chat apps: a handoff, uploads, compact results, and a security pass: a chat app's history cannot be edited, so the
handoff prompt (Claude Desktop's + menu) has the model write a ≤400-token brief and save it with save_handoff (secrets masked, handoff://latest to attach in the next chat, the per-turn saving reported: a 52k-token chat drops to ~600). ask_file answers from a big file through pack_context, which over --http also takes ChatGPT uploads; ChatGPT gets compact results. An independent QA pass's eleven findings were fixed with tests; behind a tunnel, --http now needs --allowed-hosts <tunnel host> (handoff).
Every release, with the details: docs/whats-new.md.
Documentation
- What
install does: every file it writes, what runs in each session after, and when you need MCP
- Autopilot: how it clears stale tool output, and why it never costs more
- Fixes:
fix (one plan, applied with consent, undone in one step, re-measured), cache-ttl and the subagents' model
- Spend and budget: one bill across every tool, and a budget the every-prompt hook applies
- The proxy: autopilot and the optimizing mode for your API apps,
/stats, cache advice, a public URL for Cursor
- Chat apps: Claude Desktop, ChatGPT, claude.ai and the phone apps; what acts by itself and what only nudges; the MCP tools, prompts and resources
- Handoff: continue a long chat in a new one from a ≤400-token brief
- Profiling: sessions, prompt-cache economics, subagents,
tasks, reads, compactions, cache-misses, limits, report
- Pack and overhead:
pack, recall, overhead, overhead split and overhead prune
- Detectors and fixes: what the profiler finds and what each optimizer strategy changes
- Library:
profileConversation, optimizeConversation, packContext, withContextDoctor
- Budgets and CI: the GitHub Action and
.contextdoctorrc
- Editor and status line: the VS Code / Cursor extension and Claude Code's status bar
- Token counts: why counts are "~", how the Claude ratios were measured, exact counts
- Performance: what context-doctor itself costs (its six MCP tool definitions: at most ~2,344 tokens)
- Experiment and A/B suite: does a smaller context help, and does a lever cost quality? Measured on real tasks
- What's new, Roadmap, Python package
Contributing
Issues and PRs welcome — see CONTRIBUTING.md for the rules that keep this tool trustworthy, how to run the checks, and how releases are made. What comes next is in ROADMAP.md: the research items and the steps waiting on the owner's accounts (PyPI, the editor extension's marketplaces, a signed Desktop bundle, the Glama listing).
License
MIT © gAI Ventures