context-doctor

io.github.KushalP1由 GitHub 帳號 KushalP1 發布v0.44.0更新於 Nov 7, 2026

Cut LLM agent token use in Claude Code, Cursor, Codex, Gemini CLI. Local, no API key. gAI Ventures.

已驗證STDIO僅桌面開發者工具AI 與機器學習

概覽

AI 產生的概覽

本機 MCP 伺服器,用來分析 AI 代理的上下文、削減浪費的 token、依需求打包大型檔案並儲存對話交接。

可以做什麼
  • 分析對話的 token 組成、最大區塊與浪費的上下文,並在可行時換算成費用
  • 改寫對話以回收 token:去重、裁掉過期的工具輸出、移除 base64,並回傳精簡結果與節省量
  • 在 token 預算內只讀取大型文字、程式碼、PDF、Word、PowerPoint 或 ODT 檔案中與問題相關的片段,也可先取得大綱
  • 儲存供新對話接續使用的交接摘要,並搜尋本次工作階段磁碟紀錄中的早期內容
  • 取得維持上下文精簡與提示可快取的檢查清單,可依供應商區分
適用情境
當長時間工作階段、大量貼上或大檔案推高 token 成本並拖慢回應時,可用它取得可量化的壓縮、裁剪與打包建議。也適合把上下文帶進新的對話。
執行需求
透過 npx 以本機 stdio 程序執行(需 Node 20 以上);未宣告需要 API 金鑰、帳號或環境變數。僅限桌面端,無法在網頁中執行。部分命令列功能會讀取本機工作階段紀錄並寫入用戶端設定檔。
安裝前請注意
最佳化工具可能裁剪對話歷史,此操作具破壞性,伺服器自身說明也要求僅在使用者同意時進行;儲存交接同樣應經使用者同意。可選的安裝與修復指令會修改用戶端設定檔與掛鉤,雖稱可還原。工作階段紀錄在本機磁碟讀取,聲稱不上傳遙測資料。

安裝

在 SourceWeft 中

  1. 開啟 儀表板中的 context-doctor,將其新增到工作區。
  2. 為需要使用其工具的對話啟用該服務。

Desktop only,透過 STDIO。 STDIO 服務會啟動本機處理程序,因此需要 SourceWeft 桌面主機。

其他 MCP 客戶端

參照 儲存庫 中的啟動說明。

README

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.

bash
npx context-doctor savings     # what your recent sessions cost, and what each fix would have savednpx context-doctor fix         # the fixes ranked by dollars; applies only the ones you say yes tonpx context-doctor spend       # one bill across Claude Code, Codex, Gemini CLI and Cursor
[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.

You useDo this
Claude Code (terminal, IDE, desktop app)Inside Claude Code: /plugin marketplace add KushalP1/context-doctor, then /plugin install context-doctor@context-doctor. You get the every-prompt check, the compaction hook, the MCP tools and /context-doctor:fix, :spend, :savings, :checkup, :overhead, :pack, :autopilot, :compact-window
Everything on this machine at oncenpm install -g context-doctor && context-doctor install wires Claude Code, Claude Desktop, Cursor, Codex, Gemini CLI, Google Antigravity and GitHub Copilot: MCP server, skill and hooks (what it writes). context-doctor doctor checks it; context-doctor uninstall removes it. Then, for Claude Code in a terminal or IDE, context-doctor autopilot on
Claude Desktop, Cursor or any MCP clientAdd the server to the client's MCP config (or install the one-click .mcpb from the latest release in Claude Desktop):
{"mcpServers": {"context-doctor": {"command": "npx", "args": ["-y", "context-doctor", "mcp"]}}}
claude.ai, ChatGPT, phone appsnpx context-doctor instructions --copy, then paste into the app's personal preferences (it tells you where). ChatGPT can also reach the MCP server at a URL (how)
Your own app on an LLM APIRun npx context-doctor proxy --autopilot and point ANTHROPIC_BASE_URL, OPENAI_BASE_URL (add /v1) or GOOGLE_GEMINI_BASE_URL at the proxy on 127.0.0.1:8787, plain HTTP (exact values). No proxy possible? Wrap the SDK client: withContextDoctor(new Anthropic()) (library)
Python / RAG pipelinespip install "git+https://github.com/KushalP1/context-doctor#subdirectory=python" (PyPI release coming), then pack_documents(retrieved_docs, question, budget=4000) trims LangChain or LlamaIndex results to the chunks that matter. Python README
GitHub pull requestsuses: KushalP1/[email protected] comments how much a PR grows CLAUDE.md, AGENTS.md and rules, and can fail over a budget (setup)

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.

Net saving had you run /compact after the first reply$2,993 (about $675 a month)
Returns where it paid off342 of 479
Worst single case−$1.79 (a session left a few messages later)

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:

Without autopilotWith autopilotSaved
Input cost at API list price$11,347$9,905$1,442 (12.7%, about $325 a month)
Sessions made more expensive0 of 67

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:

WindowInput cost, last 30 daysSavedCompactions a week
as now (~970k)$3,6484.7
600k$2,242$1,405 (39%)6.5
400k$1,814$1,833 (50%)14.2
300k$1,664$1,983 (54%)25.2
200k$1,501$2,146 (59%)48.1

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

Where you workAutomatic, every requestWhat you get on top
Claude Code in the terminal, VS Code or JetBrainsAutopilot clears stale tool output (cold cache only, never more expensive). Hook on every prompt: real context size, largest waste, and a /compact offer when you return to a large session after the cache expired. Compaction hook on every compaction. compact-window, if you set oneInstall via npm or as a plugin. Status bar context meter, /context-doctor:savings, session, watch, report, dashboard, MCP tools
Claude Code in the desktop app's Code tabHooks, as above, the cold-resume /compact offer shown to you as well as the model. compact-window, if you set one: Claude Code compacts earlier by itself. Not autopilot: the app sets its own API address and ignores the one in settingsSame as above
Cursor (agent)A native after-tool-call hook (~/.cursor/hooks.json): in a heavy chat the agent gets the same hygiene guidance and the largest waste, once per 40% of growth. (Cursor's prompt hook can only allow or block a prompt, so this is the event where guidance reaches the model)MCP tools, editor status bar extension, cursor profiler. With your own OpenAI key, autopilot too via a tokened tunnel (how)
Codex (ChatGPT app's Codex tab, IDE extension, CLI)Every-prompt hook with the API's own token countsMCP tools, skill, session reads Codex rollouts. On an API key, autopilot too (autopilot on sets openai_base_url in ~/.codex/config.toml; Codex no longer reads OPENAI_BASE_URL)
Gemini CLIEvery-prompt hook (BeforeAgent) with the API's own token counts. On an API key, autopilot too: GOOGLE_GEMINI_BASE_URL set to the proxy on 127.0.0.1:8787, plain HTTP (Google sign-in traffic goes elsewhere)MCP tools, session and watch read its chats, overhead sizes GEMINI.md
GitHub Copilot (Copilot CLI, the Copilot app, VS Code agent sessions)A session-start hook (~/.copilot/hooks/context-doctor.json) gives every new or resumed session the standing rules. No size check: Copilot passes a transcript only to hooks that cannot add contextMCP tools (~/.copilot/mcp-config.json, which VS Code's Copilot sessions read too)
Your own apps on the Anthropic, OpenAI or Gemini APIAutopilot on /v1/messages, /v1/chat/completions, /v1/responses and Gemini's generateContent (ANTHROPIC_BASE_URL / OPENAI_BASE_URL / GOOGLE_GEMINI_BASE_URL), or the optimizing proxy (which can cost more on cached traffic); no proxy possible (serverless, edge)? withContextDoctor(client) runs autopilot inside the SDK clientExact usage and cache hit rates in /stats, prompt-cache placement advice (proxy)
Claude Desktop chatThe six standing rules below, sent to every chat (whether classic Chat shows them to the model is unverified, why); one cheap profile_context call the model makes once at ~30 turns and on any cost question; pack_context instead of reading a big local file whole; a handoff offered once a chat is long, since a chat's history cannot be cut and a new chat canOne-click .mcpb install, context_checkup, handoff and ask_file prompts, handoff://latest to attach in the next chat (handoff)
claude.ai, ChatGPT, the phone appsYour account's standing preferences, pasted once (Quick start)Profile an exported chat with analyze or session. ChatGPT developer mode: the MCP tools at a URL, uploads into pack_context (how)
CIanalyze --fail-over-budget fails a build whose prompts outgrow a budget; the GitHub Action gates memory-file growth.contextdoctorrc budgets and presets (CI)

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):

  1. 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.
  2. When a chat grows long, offer a handoff once (save_handoff): only a new chat cuts its history.
  3. Summarize any paste or tool result over ~2k tokens into the points you need.
  4. Refer to earlier content by name; never re-quote it or inline base64.
  5. For a big file you won't edit, call pack_context with the question; don't read it whole.
  6. 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

CommandWhat it does
context-doctor install / uninstallWire (or remove) everything it finds: the MCP server for Claude Desktop, Claude Code, Cursor, Codex, Gemini CLI, Google Antigravity and GitHub Copilot; the Agent Skill (Claude Code, Codex, Antigravity); the every-prompt hook (Claude Code, Codex, Gemini CLI's BeforeAgent, Cursor's postToolUse, postToolUseFailure and sessionStart); Claude Code's PreCompact, SessionStart, PreToolUse (the subagent price) and, on 2.1.251+, PreModelSwitch hooks; Copilot's sessionStart (the standing rules). --statusline adds the status bar line (details)
context-doctor fix [--apply ids|all] [--share] / fix undoEvery lever ranked by what it would have saved on your last 30 days (compact earlier, the cache lifetime, autopilot, MCP tool search, unused servers, the subagents' model, long Bash output to a file, Codex's auto-compact limit), with what each costs in quality; applies one only on a yes (the subagents' model only when named), fix undo reverts exactly what it changed, later runs show what each saved since (details)
context-doctor spend [--days n] [--share]One bill across every tool on this machine: Claude Code (main conversation and subagents), Codex, Gemini CLI and Cursor (an estimate: no cache split), by tool, project, model and day, with what drives it (docs)
context-doctor budget [<$>/day|<$>/week [--block]|off]A spend budget the every-prompt hook applies: a line at 50%, 80% and 100%, and with --block prompts over it are held until you raise it or turn it off (docs)
context-doctor doctorSelf-check the whole installation — one pasteable ✓/✗ diagnosis with fixes, including which surfaces autopilot can reach and any other program on its port
context-doctor savings [--days n] [--share [--copy]]What your recent Claude Code sessions cost, and what /compact at cold resumes, autopilot and an earlier auto-compact window would save, replayed through the shipped code against your actual billed usage. --share prints totals only (no project names or paths) to post. A bare context-doctor in a terminal shows the same
context-doctor autopilot on|off|pause|resume|statusEvery new Claude Code session started in a terminal or IDE goes through the local proxy, which clears stale tool output only when the prompt cache is cold: measured 12.7% less input cost, no session worse (details)
context-doctor proxy --autopilotLocal proxy for your own Anthropic, OpenAI and Gemini API apps: clears stale tool output only when the prompt cache is cold, so it never costs more. Plain proxy runs the optimizing strategies (dedupe, trim, strip base64), which can cost more on cached traffic. --token for a public URL; /stats for cumulative savings (details)
context-doctor compact-window [status|off|<size>]Replay your last 30 days at auto-compact windows from 200k to 800k: input cost, saving, and how many more compactions each means. 400k (or 250000, 0.4m) sets Claude Code's autoCompactWindow, with a backup; off removes it. Works in every Claude Code surface, the desktop app included
context-doctor cache-ttl [status|1h|5m|off] [--subagents]The main conversation's (or subagents') prompt cache lifetime: what 5 minutes and 1 hour would each have cost on your last 30 days, then set or remove promptCacheTtl / subagentPromptCacheTtl (Claude Code 2.1.243+, every surface). Price only: the same content is sent (details)
context-doctor instructions [--copy]The ~190-token standing rules (~130 on GPT) for claude.ai / ChatGPT preferences, for web and phones where no server runs
context-doctor handoff [list|show <id>|latest] [--copy]Handoffs saved from chat apps (the handoff prompt or save_handoff): list them, print one, or copy it to paste as a new chat's first message (handoff)
context-doctor mcp [--http]The MCP server as a subcommand, for clients and registries that launch npx -y context-doctor mcp
context-doctor-mcpThe MCP server itself — stdio by default (what the installer wires); --http [--port 8808] [--host H] [--allowed-hosts names] [--allowed-origins list] [--store-handoffs] serves streamable HTTP at /mcp for URL-based clients like ChatGPT developer-mode connectors (only for the host names it knows: behind a tunnel, pass its name to --allowed-hosts)
context-doctor session [file]Profile a Claude Code session: live context, findings, measured tokens and prompt-cache economics, where the wall clock went per tool, output's and reasoning's share of the cost, repeated identical (polling) tool calls priced, and what its subagents cost (their own windows, your bill; never in the parent's profile). Also reads Codex rollouts, Gemini CLI chats and ChatGPT data exports (conversations.json); --list to browse
context-doctor watch [file]Live monitor of a growing session transcript or agent trace (Claude Code / Codex JSONL, or a plain OpenAI/Anthropic conversation JSON file): token/cost line per change, findings as they appear
context-doctor cursor [--list]Profile a chat from Cursor's local history (both storage formats)
context-doctor analyze <file>Profile a conversation: token breakdown, findings, cost + latency estimates. --exact adds a true count; --fail-over-budget exits 1 on a breach, for CI
context-doctor optimize <file>Apply the safe fixes; add --strategy trim-tool-calls for big inline file writes, --strategy prune-history for consented lossy compaction (what each does)
context-doctor diff <before> <after>Compare two profiles: what moved by category, which findings were resolved or introduced, and what it saves in money and latency
context-doctor overhead [--days n] [--mcp]What every request re-reads before your message: measured first-request size (Claude Code, Codex and Gemini CLI sessions), each memory file (CLAUDE.md and imports, rules, auto memory, AGENTS.md, Cursor rules, GEMINI.md) priced per month, MCP calls per server; --mcp sizes each configured server's tool definitions and flags unused ones
context-doctor overhead prune [--days n] [--write] [--undo]Per project, the MCP servers and skills its sessions never used in n days; --write switches them off for this folder's project in its .claude/settings.local.json (backup kept, every entry recorded), --undo takes exactly those out. Never the app's connectors, plugins, or context-doctor itself
context-doctor overhead split <file> [--min-tokens n] [--write]Move a memory file's big or code-heavy sections word for word to <name>.reference.md, leaving pointers; indexes stay. A plan until --write, which backs up first
context-doctor pack <files|dirs|-> -q "…"Only the chunks of big documents, logs or code a question needs, ranked and fit to --max-tokens (default 4000). No query: an outline; --ids a#2,b#5 picks chunks from it. --semantic also ranks by meaning with a local Ollama model. Offline, no key
context-doctor recall "<query>" [--session <id|path>]Search this session's own transcript on disk (Claude Code or Codex; turns before a compaction and tool output cleared from the context included) and print the best excerpts with time and position, secrets masked. Never another project's session unless named with --session. Also the recall MCP tool
context-doctor tasks [--days n]Cost per commit, per project: each session priced from its recorded usage against the commits it made
context-doctor reads [--days n] [--limit n]Files read into session after session: reads, tokens, cost, and whether a CLAUDE.md summary or pack pays
context-doctor subagents [--days n]Which subagents paid for themselves: each one's bill vs the same steps run in the parent session
context-doctor compactions [--days n]Do sessions work worse right after compacting? Re-reads, tool errors and your corrections, before vs after each compaction
context-doctor cache-misses [--days n]Requests that re-wrote the prompt cache within its lifetime (no compaction between, previous context over 20k, over 60% of it written again): priced above the cache-read rate, by model and context size, with the cause where visible and the model versions that miss less; by Claude Code version, with step changes after an upgrade flagged (the 1-hour cache share, the first request's size, a model's miss rate); --json per model and version
context-doctor limits [--days n]Your plan's limits in their own unit: each window's %, pace and run-out time (Claude's 5-hour and weekly windows from the status line's readings, Codex's from its rollouts), and % of the limit per 1M tokens of input, cache read, cache write and output, fitted on your readings with the fit's error; too-thin data is said to be thin, never quoted
context-doctor cache-plan <request.json> [--calls n] [--out file] [--explicit]Where an Anthropic API request should carry cache_control (top-level automatic caching for the moving end, unless --explicit), and what it saves over n calls; --out writes it applied
context-doctor accuracyHow much of what you are billed for is visible in your transcript (the fixed harness baseline, per-turn injected content), plus a tokenizer check: real chars/token per model from the API's own counts, next to the ratio the estimator uses
context-doctor reportMachine-wide impact report (proxy savings persist across restarts): exact proxy savings, hook activity, how often the cold-resume /compact offer was followed by a compaction, recoverable waste in recent sessions
context-doctor dashboardLocal savings dashboard on 127.0.0.1: tokens saved per day, sessions by context in use vs recoverable, budget status
context-doctor ci [--base <ref>] [--max-tokens n] [--max-increase n] [--markdown]Memory files (CLAUDE.md, AGENTS.md, GEMINI.md, rules, their imports) at HEAD vs a base commit; exit 1 over budget. What the GitHub Action runs (details)
context-doctor init [preset]Write a .contextdoctorrc from a preset (chat, agent, batch) — a budget you can adopt in one command and tune later
context-doctor experiment --task "…"Run one task twice from the same commit, in a fresh session and forked from an --existing one, same model and tools; compare bill, cache split, wall clock, and whether --check passed. The only command here that spends money, so it caps spend per arm and refuses a dirty tree (details)
context-doctor ab [--lever …] [--yes]Does a lever cost quality? Eight small coding tasks, each a tiny repository scored by a hidden check, run with and without the standing rules, autopilot's clearing, pack_context or the PreCompact instructions through the Messages API; pass counts, tokens and cost side by side. Bills ANTHROPIC_API_KEY: prints the estimate, sends nothing without --yes, stops at --budget (details)
context-doctor statuslineClaude Code status bar: live context vs window, cache share, cost, and (Claude Code 2.1.251+) until when the cache is warm and what the next turn costs once it is cold. Wired by install --statusline; never overwrites a statusLine you already have (details)
context-doctor hookThe every-prompt hook (Claude Code, Codex, Gemini CLI, Cursor) and Claude Code's compaction hook, registered by install; hook copilot is GitHub Copilot's session-start hook; you never run these yourself. Warning threshold tunable via CONTEXT_DOCTOR_WARN_TOKENS (default 80000)
context-doctor --versionPrint the installed version. --help lists every flag

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

來源:README.md,提交 6103c35

工具

6

profile_context

Profile context

Profile a conversation's context: token breakdown, largest blocks, wasted context. Pass `conversation` (JSON or text) or, in a chat app, a `sketch` (~120 tokens). Call it when the user asks about tokens, cost, speed or limits, and once past ~30 turns or 3+ large pastes. Act on the top finding.

輸入參數modelsketchconversation

optimize_context

Optimize context

Rewrite a conversation to reclaim tokens (dedupe, trim stale tool results, strip base64; prune-history is lossy). Returns slimmed JSON and the savings. Use after profile_context finds waste the user wants fixed; prune-history only with the user's consent, then write the summary the result asks for.

輸入參數strategieskeep_recentconversation必填max_tool_result_tokens

pack_context

Pack context

Read only the parts of large files a question needs: the chunks that best match `query` within `max_tokens`, with ids and line ranges. No query: an outline; pick with `ids`. Use instead of reading a big doc, log or folder whole when not editing it. Text, code, PDF, Word, PowerPoint, ODT.

輸入參數idstextmodelpathsquerysemanticmax_tokens

save_handoff

Save handoff

Save a handoff for continuing in a new chat (a chat's history cannot be cut; a new chat can). Write `brief` yourself (≤400 tokens: goal, decisions, state, open items, identifiers); put what must stay exact in `verbatim`. Only when the user agrees.

輸入參數brief必填modeltitleturnsverbatimchat_tokens

recall

Recall

Search this session's transcript on disk (compacted turns, cleared tool output) for `query`: best excerpts with time and position. Use before asking the user again.

輸入參數query必填max_tokens

context_best_practices

Context best practices

Checklist for keeping context lean and prompts cacheable, optionally per provider.

輸入參數provider

版本歷史

23
  1. v0.44.0最新Nov 6, 2026
  2. v0.43.0Nov 4, 2026
  3. v0.42.0Nov 3, 2026
  4. v0.41.0Nov 3, 2026
  5. v0.40.0Oct 30, 2026
  6. v0.39.0Oct 29, 2026
  7. v0.37.0Oct 26, 2026
  8. v0.35.1Oct 23, 2026
  9. v0.35.0Oct 20, 2026
  10. v0.34.0Oct 18, 2026
  11. v0.33.0Oct 17, 2026
  12. v0.32.0Oct 13, 2026
  13. v0.31.1Oct 12, 2026
  14. v0.31.0Oct 12, 2026
  15. v0.29.0Oct 10, 2026
  16. v0.28.0Oct 9, 2026
  17. v0.27.0Oct 8, 2026
  18. v0.26.0Oct 6, 2026
  19. v0.25.0Oct 5, 2026
  20. v0.24.0Oct 3, 2026
  21. v0.23.1Oct 1, 2026
  22. v0.22.0Sep 29, 2026
  23. v0.21.0Sep 28, 2026

評分

已滿足適用檢查項的 90%

該評分衡量此收錄條目的完整程度,依據註冊中心條目、端點與公開來源計算得出。它不是對伺服器本身的評價,也不表示伺服器安全或目前可用:可連通性是帶日期的檢查結果,評分也不包含安裝量或使用者評價。

  • 近 30 天內可連通25 分
  • 已宣告認證方式10 分

    請在註冊中心條目中宣告憑證請求標頭,或保持端點能夠回應探測,以便判定其認證方式。

  • 已列出工具必需15 分
  • 描述必需15 分
  • 圖示10 分
  • 文件15 分
  • 授權條款10 分