context-doctor
Profiles and optimizes OpenAI chat conversation contexts, providing token breakdowns, duplicate content removal, base64 stripping, and in-flight API request optimization via a proxy for GPT and ChatGPT.
Click on "Install Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@context-doctorProfile this conversation and suggest what to trim to save tokens."
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
context-doctor š©ŗ
See what's eating your LLM context window ā and fix it.
Every long-running LLM conversation slowly fills up with junk: duplicated documents, 10k-token tool outputs nobody reads again, base64 blobs, stale history. You pay for those tokens on every single call, and model quality drops as the window fills.
context-doctor is a zero-config profiler + optimizer for LLM contexts. It works with Claude, GPT, Gemini message formats, and plugs into Claude Desktop, ChatGPT (developer mode), Cursor, Claude Code ā any MCP-capable app ā or runs standalone from the terminal.
Where the tokens go
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
Tool results āāāāāāāāāāāāāāāāāāāāāāāāāāāā 57% ~41k
System prompt āāāāāāāāāāāāāāāāāāāāāāāāāāāā 21% ~15k
Assistant replies āāāāāāāāāāāāāāāāāāāāāāāāāāāā 13% ~9.4k
User messages āāāāāāāāāāāāāāāāāāāāāāāāāāāā 9% ~6.5k
Findings (4)
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
ā Message #12 contains a base64/binary blob (~8.2k tokens). [save ~7.4k]
ā Never put base64 in text content ā use the provider's file/image APIs.
ā² Tool result at message #7 (web_search) is ~6.1k tokens. [save ~4.9k]
ā Truncate or summarize large tool outputs before they enter history.Quick start (30 seconds)
No install needed:
npx context-doctor analyze conversation.json --model claude-sonnet-5Apply the safe fixes:
npx context-doctor optimize conversation.json --out slimmed.jsonInput is any of: OpenAI chat format, Anthropic messages format (with system and content blocks), or a bare [{role, content}] array. Use - to pipe from stdin.
Related MCP server: CostGate
Always-on: optimize every request automatically
Run the proxy and every Anthropic/OpenAI API call your apps make gets optimized in flight ā no code changes:
npx context-doctor proxyThen point your app or SDK at it:
export ANTHROPIC_BASE_URL=http://localhost:8787 # Anthropic SDKs / tools
export OPENAI_BASE_URL=http://localhost:8787/v1 # OpenAI SDKs / toolsThe proxy dedupes repeated content, trims stale tool results, and strips base64 blobs from the message history of each request, then forwards it to the real API. Your API key passes through in headers untouched, streaming (SSE) works unchanged, and per-request savings are logged:
[context-doctor] POST /v1/messages ā 200 | optimized 7.3k ā 518 tokens (2 changes)Because prompt caching matches byte-identical prefixes, deterministic strategies are chosen so repeated requests stay stable ā but if you rely on aggressive cache prefixes, start with --strategy strip-base64 --strategy dedupe and add more as you verify.
Note on desktop chat apps: Claude Desktop and the ChatGPT app talk to their own backends ā no tool can sit in that path. For those, use the MCP integration below and add a line to your custom instructions like: "When a conversation gets long or includes large pasted content, proactively use context-doctor's profile_context tool and tell me what to trim." The model will then invoke it on its own.
Use it inside your AI app (MCP)
context-doctor ships an MCP server, so the AI itself can profile and slim context on demand.
Claude Desktop ā add to claude_desktop_config.json (Settings ā Developer ā Edit Config):
{
"mcpServers": {
"context-doctor": {
"command": "npx",
"args": ["-y", "context-doctor-mcp"]
}
}
}ChatGPT desktop (developer mode), Cursor, Claude Code (claude mcp add context-doctor -- npx -y context-doctor-mcp), and any other MCP client: same command, their config syntax.
Then just ask: "profile this conversation with context-doctor" or paste an exported chat and say "what's eating my context?"
MCP tools
Tool | What it does |
| Token breakdown by category, largest messages, findings with estimated savings |
| Rewrites the conversation: dedupe, trim stale tool results, strip base64, optional history pruning |
| Curated checklist, optionally specialized for Anthropic / OpenAI |
Use it as a library
import { parseConversation, profileConversation, optimizeConversation } from "context-doctor";
const profile = profileConversation(parseConversation(chatJson), "claude-sonnet-5");
console.log(profile.totalTokens, profile.findings);
const { conversation, tokensBefore, tokensAfter } = optimizeConversation(chatJson, {
strategies: ["dedupe", "trim-tool-results", "strip-base64"],
});What it detects
Oversized tool results ā the #1 context killer in agent loops
Duplicate content ā the same doc/result pasted twice
Repeated identical tool calls ā a signal your agent forgot earlier results
Base64 / binary blobs in text content
Long history past the point where models track the middle
Cache-hostile ordering ā volatile content before stable content breaks prompt caching (Anthropic
cache_control, OpenAI automatic prefix caching)Window pressure ā usage % against the target model's real context window
What it fixes (deterministically ā no LLM calls, no API keys)
Strategy | Lossy? | Default |
| No | ā |
| Mostly no | ā |
| No (for the model) | ā |
| Yes | opt-in |
Everything the optimizer does is inspectable: it prints exactly which messages changed and how many tokens each change saved.
Why token counts are "~"
Exact counts require each provider's private tokenizer. context-doctor uses a calibrated chars-per-token heuristic (denser for code/JSON) that lands within ~10% ā plenty accurate for finding what's heavy and measuring savings, and it keeps the tool fully offline with zero configuration.
Roadmap
LLM-powered summarization strategy (bring your own key) for
prune-historystubsProxy: per-route strategy config + response token accounting
context-doctor watchā live profiling of an agent's JSONL traceExact tokenizer adapters (tiktoken, Anthropic count-tokens API) as optional plugins
Session import from Claude Code / Cursor transcript formats
Contributions welcome ā this project is small on purpose. Open an issue before a big PR.
License
MIT
This server cannot be installed
Maintenance
Resources
Unclaimed servers have limited discoverability.
Looking for Admin?
If you are the server author, to access and configure the admin panel.
Related MCP Servers
- Alicense-qualityCmaintenanceProvides context compression via the tokenslim engine, enabling MCP hosts to reduce token usage while preserving key information. Offers compress, retrieve, and stats tools for managing compressed content.Apache 2.0
- Alicense-qualityCmaintenanceReduces AI token consumption by optimizing MCP tool definitions and responses, with a probe for measurement and a gate for filtered tool exposure and cost reduction.MIT
- Alicense-qualityDmaintenanceEnables analyzing and optimizing context window token usage by measuring, compressing, and eliminating waste from MCP tool definitions.46MIT
- AlicenseAqualityCmaintenanceLets Claude Desktop, Cursor, Cline, Windsurf, Zed, or any other MCP client estimate token counts and fit a chat history into a model's context budget on demand.3541MIT
Related MCP Connectors
A paid remote MCP for OpenAI Codex context compressor, built to return verdicts, receipts, usage log
AI Reasoning Cache & Consensus Layer with 11 MCP tools via Streamable HTTP.
Hosted MCP server for LLM cost estimation, model comparison, and budget-aware routing.
Latest Blog Posts
- Who's Calling? MCP Hosts Are an Identity Blind Spot (And the Spec Knows It)By Om-Shree-0709 on .mcpAgent IdentityOAuth 2.1
- Your AI Chatbot Just Exposed Your CEO's Salary to an InternBy Om-Shree-0709 on .Agent IdentityMCP SecurityOAuth Delegation
- Why MCP Servers Need Execution Sandboxing (And Why Your Current Stack Isn't Enough)By Om-Shree-0709 on .Agentic AiPrompt InjectionWebAssembly
MCP directory API
We provide all the information about MCP servers via our MCP API.
curl -X GET 'https://glama.ai/api/mcp/v1/servers/KushalP1/context-doctor'
If you have feedback or need assistance with the MCP directory API, please join our Discord server