ctx-profiler

MECE token-waste & context-window profiler MCP server for coding agents (Claude Code, Codex, Cline, OpenClaw); cuts avoidable context waste by 61.65%.

Documentation

ctx-profiler

cuhawk/ctx-profiler MCP server

Listed on mcpservers.org

Where did 60% of your coding-agent tokens go? Profile Claude Code, Codex & Cline logs in one command.

ctx-profiler is a zero-dependency Python CLI and stdio MCP server for context engineering and token economics. It replays real multi-turn coding-agent transcripts turn by turn, attributes every single token across 6 mutually-exclusive, collectively-exhaustive (MECE) buckets, and simulates 5 concrete compaction policies before you change a line of harness code.

ctx-profiler animated terminal demo


Why This Exists

In multi-turn coding-agent loops, context cost grows quadratically: a single 4,500-token pytest -vv traceback or redundant file read on turn 5 isn't paid once — it is re-sent in every subsequent API call for the rest of the session.

This tool directly targets the context-bloat failure modes documented across major agent harnesses:


10-Second Quickstart

Pure Python stdlib core (Python >= 3.10, zero required runtime dependencies):

# Run without installing globally (uvx)
uvx --from . ctx-profiler analyze fixtures/

# Or install editable locally
pip install -e .
ctx-profiler analyze fixtures/
ctx-profiler simulate fixtures/ --model claude-sonnet-4 --csv savings.csv

Optional visualization extras (Pillow + matplotlib) for generating PNG/GIF benchmark visuals:

pip install -e ".[viz]"
ctx-profiler bench

The 6 MECE Token Categories (Hard Golden Invariant)

Every analyzed turn, session, and corpus enforces the exact integer token invariant:

sum(category_tokens.values()) == total_session_tokens
CategoryClassificationWhat It Captures
file_rereadsWasteUnchanged file paths read again (both emission and subsequent turn replays)
tool_output_bloatWasteNon-file-read shell/grep/ls/test/MCP output exceeding --tool-bloat-threshold (default 2,000 tok) + replays
reasoning_think_replayWastePrior-turn <think>...</think> or reasoning blocks re-injected into subsequent prompts
system_and_tool_schemasOverheadRepeated system prompt + MCP/tool JSON schemas sent every turn
history_replayOverheadPrior useful conversation turns re-sent in subsequent prompts
useful_new_workUsefulFresh prompts, first-time file reads, within-threshold tool results, and newly generated completions

Waste Ratio % is defined strictly as:

Waste Ratio % = (file_rereads + tool_output_bloat + reasoning_think_replay) / total_session_tokens * 100

When API usage metadata is present in a log (Claude Code, Codex, OpenClaw, OpenAI traces), per-turn totals are reconciled to the exact reported integer count via Largest-Remainder (Hamilton) apportionment so there is zero rounding drift.


Reproducible E2 Context Waste Benchmark

Every number below is generated deterministically by running ctx-profiler bench over the 6 realistic multi-turn coding-agent fixture logs shipped in fixtures/ (raw outputs saved in benchmarks/context_waste_report.csv and benchmarks/context_waste_report.json):

E2 Context Waste Benchmark Chart

Measured Per-Session Breakdown (claude-sonnet-4: $3.00 in / $0.30 cached / $15.00 out per 1M tokens)

SessionAgent FormatTurnsTotal TokensFile Re-readsTool BloatThink ReplaySchemasHistory ReplayUseful WorkWaste %Est. Cost
01_claude_code_fastapi_debugclaude-code322,438,6031,118,883339,6914,18040,224894,31641,30959.98%$1.096
02_codex_ts_refactorcodex301,584,583481,915385,0123,85318,390660,75634,65754.95%$0.724
03_cline_multi_file_search_editcline261,287,459259,368584,64030,3730387,58025,49867.92%$0.629
04_claude_code_mcp_heavy_workspaceclaude-code301,078,884132,963133,4760364,590420,95326,90224.70%$0.475
05_openclaw_qwen_think_loopopenclaw361,193,084139,2690609,54924,913366,74552,60862.76%$0.955
06_openai_trace_monorepo_migrationopenai28918,816202,619390,73515,79570,532226,63512,50066.30%$0.440
CORPUS TOTALall (6 logs)1828,501,4292,335,0171,833,554663,750518,6492,956,985193,47456.84%$4.319

(Uncached list cost across the 6 sessions without prompt caching: $26.062; avoidable waste cost at effective cache-aware input rates: $2.070.)

Compaction Simulator Results (ctx-profiler simulate fixtures/ --model claude-sonnet-4)

PolicyBefore TokensAfter TokensTokens SavedReductionAfter Waste %Est. Savings / 100 Sessions
dedup-rereads8,501,4296,180,9142,320,51527.30%40.40%$15.779
cap-tool-output-2k8,501,4296,635,1891,866,24021.95%45.19%$13.485
strip-think-replay8,501,4297,837,682663,7477.81%53.19%$3.738
lazy-mcp-schemas8,501,4298,110,575390,8544.60%59.58%$3.377
combined-all8,501,4293,260,0755,241,35461.65%0.00%$36.379

CLI Usage

# Profile a single file or entire directory (auto-detects agent format)
ctx-profiler analyze path/to/session.jsonl
ctx-profiler analyze path/to/logs/ --format markdown --out report.md
ctx-profiler analyze path/to/logs/ --format svg --out breakdown.svg
ctx-profiler analyze path/to/logs/ --format json --model gpt-5

# Override pricing (USD / 1M tokens) — e.g. self-hosted local GPU
ctx-profiler analyze fixtures/05_openclaw_qwen_think_loop.jsonl \
  --model qwen3.8-27b --input-price 0 --cached-price 0 --output-price 0

# Simulate all 5 compaction policies + export CSV
ctx-profiler simulate fixtures/ --model claude-sonnet-4 --csv compaction.csv

# Reproduce the full E2 benchmark + PNG + GIF
ctx-profiler bench

Native MCP Server & Agent Skill

1. Run as a Stdio MCP Server (ctx-profiler mcp)

Exposes two tools over JSON-RPC 2.0 stdio (analyze_session_log and simulate_compaction). Published on the Official MCP Registry as io.github.cuhawk/ctx-profiler. Add to Claude Code, Codex, or OpenClaw MCP config:

{
  "mcpServers": {
    "ctx-profiler": {
      "command": "uvx",
      "args": ["ctx-profiler", "mcp"]
    }
  }
}

Or if installed locally (pip install ctx-profiler):

{
  "mcpServers": {
    "ctx-profiler": {
      "command": "ctx-profiler",
      "args": ["mcp"]
    }
  }
}

2. Drop-in Agent Skill

Copy skills/ctx-profiler/SKILL.md into your project or user .agents/skills/ (or ~/.claude/skills/) directory so your coding agent can profile its own transcripts automatically.


Limitations & What to Distrust

Transparency matters more than flattering charts. Read these caveats before citing numbers from any profiler — including this one:

  1. Tokenizer Approximation When API usage Is Missing: Logs without per-turn API usage metadata (notably Cline's api_conversation_history.json) rely on our deterministic pure-stdlib BPE-aligned token estimator (tokenizer.py). Expect roughly ±4–8% variance versus proprietary provider tokenizers on dense code or non-ASCII text. When API usage is present, ctx-profiler reconciles every turn to the exact reported integer token count, but the split across categories inside a turn still follows text-weighted proportions.
  2. Prompt Caching Makes Dollar Savings Smaller Than Token Savings: Deleting 60% of cached input tokens does not cut your invoice by 60% if 95% of your prompt was already hitting $0.30/1M cache reads while output tokens cost $15.00/1M. That is why ctx-profiler separates cache-aware cost ($4.319) from uncached list cost ($26.062) and reports realistic cache-aware savings ($36.38 / 100 sessions). Moreover, mid-history edits (like rewriting earlier tool results) can invalidate a provider's KV prefix cache if implemented naively — in production, compaction should happen at turn emission time (before appending to the prefix) rather than mutating cached history retroactively.
  3. Simulation Does Not Measure Task Accuracy Degradation: ctx-profiler simulate computes exact token-economy bounds under deterministic transformations (dedup-rereads, cap-tool-output-2k, strip-think-replay, lazy-mcp-schemas). It does not re-run the LLM to verify whether truncating a middle stack frame or omitting a reread would cause the agent to take an extra recovery turn. Always pair token profiling with a task pass-rate eval on your own repo.
  4. Heuristic File-Modification Tracking: If a file is modified externally outside logged write tools (e.g., via a complex shell build script whose output target isn't parsed as a direct edit), a subsequent read of that path may be flagged as file_rereads even though its contents changed on disk.
  5. Shipped Benchmark Fixtures Are Representative Synthetic Traces: The 6 sessions in fixtures/ model realistic 26–36 turn multi-agent sessions matching each harness's real wire schema (claude-code, codex, cline, openclaw, openai), not private user transcripts. Always run ctx-profiler analyze on your own real local session logs before making budget decisions.

Development

make test    # Run full pytest suite
make bench   # Re-run E2 benchmark & regenerate CSV, JSON, PNG, GIF
make demo    # Print terminal analyze + simulate tables

License

MIT — see LICENSE.