prefix-doctor
Supports pointing OPENAI_BASE_URL at the local auto-healing proxy so OpenAI chat requests are canonicalized (sorted tools, stable JSON keys, relocated volatile metadata, cache breakpoints) and forwarded upstream, plus break-even cost modeling for OpenAI-style (no write-tax) caching.
This server does not currently have a deployable release on Glama. Follow the repository's setup instructions to install and configure it for your MCP client, including any required credentials and local dependencies.
The $100 Clock Bug: Why Your "90%-Off Prompt Cache" Is Secretly Costing You MORE
Prompt caching on Anthropic Claude, OpenAI GPT, Google Gemini, and DeepSeek discounts repeated input tokens by 90%. Yet in real-world coding agents and agent frameworks, one innocent mistake silently destroys your entire KV prefix cache on every turn:
Putting
Current time: 2026-11-24T15:44:07Zor arequest_idUUID at the top of yoursystemprompt.Passing MCP
tools[]fromObject.values(...)in non-deterministic order (busts 100% of KV cache at token 0!).Injecting dynamic RAG snippets or
git statusinsidesysteminstead of appending to the tail.Switching models mid-session (cold prefill on target model).
Worse: on write-taxed tiers (Anthropic 5m 1.25× write or 1h 2.0× write), a broken cache doesn't just give you 0% savings—it actively makes your bill 25% to 100% MORE expensive than disabling caching completely!
prefix-doctor is a zero-dependency KV Prompt-Cache Break Debugger, Lossless Prefix Canonicalizer, Static Prompt-Code Auditor, MCP Server & Live Auto-Healing Proxy built strictly in monochrome black & white (+ Green / Yellow / Red health indicators).
Related MCP server: MCPVetter
Lab Benchmarks: Real 40-Turn API Cost Breakdown
Every graph and number below comes straight from our deterministic 40-turn coding-agent benchmark (npm run bench → benchmarks/results.json) modeled on Anthropic Opus 5m TTL ($15/M input, 1.25× write, 0.10× read) across 4 real-world cache-buster scenarios:
Cache-Buster Scenario | Before Hit Rate | After | Before Cost (40 Turns) | After Cost (40 Turns) | Cost Saved | Write-Tax Loss Before? |
Timestamp + UUID in System | 0.0% | 98.9% | $5.73 (> $4.59 uncached!) | $0.75 | -87.0% ($4.99) | YES (RED) |
Shuffled MCP Tool Order | 0.0% | 99.8% | $5.70 (> $4.56 uncached!) | $0.71 | -87.6% ($4.99) | YES (RED) |
Dynamic RAG in System Prompt | 0.0% | 99.1% | $5.72 (> $4.58 uncached!) | $0.74 | -87.1% ($4.98) | YES (RED) |
Mid-Session Model Ping-Pong | 59.3% | 99.8% | $2.44 | $0.71 | -71.0% ($1.73) | No (Degraded) |
The Science: Write-Tax Break-Even Math & Wire-Order Physics
Grounded in late-2026 LLM caching research (detailed formulas in docs/CACHE_PHYSICS.md):
Don't Break the Cache (
arXiv:2601.06007) — Long-horizon agent prompt caching evaluation.Cache-Aware Prompt Compression (CAPC) (
arXiv:2607.15516) — Two-tier cost model for API caching.ShadowPrefill (
arXiv:2611.13176) — Eliminating cold-cache prefills under per-step model routing.Context Has a Price (
arXiv:2611.22238) — Prefix cache erosion when adding/mutating context in coding agents.
The Write-Tax Break-Even Formula
For write multiplier $w$ and read multiplier $r$, caching only saves money when your effective hit rate exceeds:
$$p^* = \frac{w - 1}{w - r}$$
Anthropic 5m TTL ($w = 1.25,; r = 0.10$): $p^* = \mathbf{21.7%}$
Anthropic 1h TTL ($w = 2.00,; r = 0.10$): $p^* = \mathbf{52.6%}$
OpenAI / Gemini / DeepSeek ($w = 1.00,; r = 0.10$): $p^* = \mathbf{0.0%}$
Lossless Prefix Canonicalizer & 9-Class Forensic Classifier
prefix-doctor detects 9 exact cache-breaking pathologies (VOLATILE_TIMESTAMP, VOLATILE_UUID_TRACE_ID, TOOL_SCHEMA_REORDER, JSON_KEY_JITTER, TOOL_SCHEMA_MUTATION, MUTATED_SYSTEM_PROMPT, DYNAMIC_CONTEXT_PREPEND, MISSING_CACHE_BREAKPOINT, TTL_EXPIRATION, MODEL_SWITCH_COLD_PREFILL) and heals requests with zero information loss:
Sorts
tools[]lexicographically & recursively canonicalizes JSON Schema keys.Relocates volatile clocks, UUIDs, trace IDs, and turn counters out of
systeminto a<turn_volatile_metadata>block after the final rollingcache_controlbreakpoint on the latest user turn.Injects optimal explicit
cache_control: { type: "ephemeral" }breakpoints (tools→system→ rolling history boundary).
Live Monochrome Web Clinic & CLI Preview
Quick Start & How to Use (60 Seconds)
Requirement: Node.js >= 22.5.0 (zero npm install dependencies).
git clone https://github.com/Moeraafatz/prefix-doctor.git
cd prefix-doctor
npm link
# Self-check Node 22+ & built-in cache healing engine
prefix-doctor doctor1. Diagnose & Heal Any .json / .jsonl API Trace
# Try built-in realistic broken traces immediately
prefix-doctor diagnose --demo timestamp_buster --provider anthropic_opus_5m
prefix-doctor heal --demo shuffled_mcp_tools --provider anthropic_opus_5m
# Diagnose & heal your own recorded agent session logs
prefix-doctor diagnose ./session-trace.jsonl --provider anthropic_5m
prefix-doctor heal ./session-trace.jsonl --out ./healed-trace.json2. Static Audit of Your Agent's Prompt-Builder Code (JS / TS / Python)
Catch new Date().toISOString(), randomUUID(), Object.values(tools), messages.unshift(), and missing cache_control before shipping:
prefix-doctor audit-code ./src/3. Run as a Live Auto-Healing Local Proxy (ANTHROPIC_BASE_URL / OPENAI_BASE_URL)
# Auto-heal live requests & forward transparently upstream
prefix-doctor proxy --port 4949 --heal --upstream https://api.anthropic.com
# Point your agent SDK or CLI at the local proxy
export ANTHROPIC_BASE_URL=http://127.0.0.1:49494. Launch the Optional Monochrome Web Inspector (prefix-doctor ui)
prefix-doctor ui --port 4949 --demo
# Open http://127.0.0.1:4949 — interactive Before/After Heal, turn bars & code auditor5. Install Portable SKILL.md + 5-Tool MCP Server for Coding Agents
# Installs into Claude Code, Codex CLI, Cursor, Windsurf & Antigravity
prefix-doctor init all6. Print Provider Write-Tax Break-Even Table
prefix-doctor breakevenBest-Case Use Cases
Slashing Production Agent API Bills by 70–88% Overnight: Run
prefix-doctor diagnoseon 10 recorded multi-turn sessions to catch silentCurrent time:or shuffled MCP tool bugs burning 1.25× write tax on every turn.Zero-Code Drop-In Live Proxy Healing: Place
prefix-doctor proxy --healin front of Anthropic or OpenAI during local development to canonicalize third-party MCP tool ordering automatically.CI/CD Prompt Hygiene Gate (
audit-code): Fail PRs whenever someone interpolatesDate.now()/uuid4()into a system prompt or callsmessages.unshift()on conversation history.Anthropic 5m vs. 1h TTL Decision Engineering: Check exact break-even thresholds (
21.7%vs52.6%) before enabling 2.0× 1-hour caching so long-TTL writes never backfire financially.Teaching Coding Agents Cache-Safe Architecture (
init all): Dropskills/prefix-doctor/SKILL.mdinto your repo so Claude Code, Codex CLI, and Cursor write cache-friendly prompts and MCP servers by default.
Indicator Legend (Strict Monochrome + Traffic Light)
Indicator | State | Meaning |
GREEN ( |
| Warm KV hit rate $\ge 75%$; enjoying 90%-off read multiplier. |
YELLOW ( |
| Hit rate $25% - 74%$ or approaching write-tax break-even $p^*$. |
RED ( |
| Early prefix break ($< 25%$ hit) or actively paying MORE than uncached pricing. |
Verification & Reproducibility
npm test # 9 unit & integration tests (LCP, breakpoints, canonicalizer, proxy, code audit, MCP)
npm run bench # Re-runs 40-turn multi-scenario benchmark -> benchmarks/results.json
npm run assets # Re-generates all 5 XML-valid monochrome B&W SVGs from benchmarks/results.jsonAcademic References
Don't Break the Cache: An Evaluation of Prompt Caching for Long-Horizon Agentic Tasks —
arXiv:2601.06007(Jan 2026).Cache-Aware Prompt Compression: A Two-Tier Cost Model for LLM API Caching —
arXiv:2607.15516(Jul 2026).SHADOWPREFILL: Keeping Your Next Model Warm for Per-Step Model Routing in Agentic LLM Serving —
arXiv:2611.13176(Nov 2026).Context Has a Price: Adding and Removing Context for LLM Coding Agents under Prefix Caching —
arXiv:2611.22238(Nov 2026).
License
MIT © RAFBUG (Moeraafatz)
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
This server cannot be deployed
Maintenance
Related MCP Connectors
Research-backed lint + generation for agent context files (CLAUDE.md, AGENTS.md) + prompt enhancer.
Statically audits MCP tool surfaces for token cost, schema quality, and design issues.
FixMyPrompt is a remote MCP server for coding agents. It saves the steps your agent worked out as project memories and fetches them in later sessions, scores and rewrites prompts, and checks CLAUDE.md and AGENTS.md files. Works with Claude Code, Codex and Cursor. Free plan available.
GodPrompt MCP + Agent Skill for code review, requirements, test planning, and verification.
Related MCP Servers
- AlicenseNot gradedqualityCmaintenanceEnables any MCP client to detect Claude Code configuration that is silently ignored, such as agent files that fail to load, unknown frontmatter fields, parent-folder settings, conflicting MCP server entries and drift since a baseline. Exposes read-only tools that return findings with exact edits, the fix prompt, and explanations of each check, without modifying any files.Apache 2.0
- AlicenseNot gradedqualityCmaintenanceEnables auditing MCP server configurations and tool descriptions from inside an AI assistant, surfacing poisoned tools, leaked secrets, risky launch commands, over-broad access, hidden Unicode, and silent tool changes with redacted evidence and concrete fixes.89 npmMIT
- AlicenseNot gradedqualityBmaintenanceEnables coding agents to run scope-checked probes of MCP endpoints, analyze tool definitions for poisoning and dangerous capabilities, detect definition drift, and generate reproducible evidence bundles and bounty-ready reports.1MIT
- AlicenseNot gradedqualityBmaintenanceEnables AI coding agents and CI workflows to audit instruction files, skill definitions, MCP configurations, tool schemas, and prompt-cache call sites for broken references, token-budget drift, security hazards, and payload waste. It surfaces structured findings so teams can enforce context-layer health before changes ship.MIT