ctx-profiler
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.
ctx-profiler
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.

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:
Claude Code — oversized tool output & repeated file reads filling context windows (anthropics/claude-code#16157, anthropics/claude-code#38335)
OpenAI Codex CLI — quadratic session replay, verbose shell logs, and reasoning overhead (openai/codex#41220)
Cline / Roo —
api_conversation_history.jsongrowth from recursive search dumps, repeated<read_file>calls, and retained<thinking>blocks (cline/cline#4389)
Related MCP server: tokencut
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.csvOptional visualization extras (Pillow + matplotlib) for generating PNG/GIF benchmark visuals:
pip install -e ".[viz]"
ctx-profiler benchThe 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_tokensCategory | Classification | What It Captures |
| Waste | Unchanged file paths read again (both emission and subsequent turn replays) |
| Waste | Non-file-read shell/grep/ls/test/MCP output exceeding |
| Waste | Prior-turn |
| Overhead | Repeated system prompt + MCP/tool JSON schemas sent every turn |
| Overhead | Prior useful conversation turns re-sent in subsequent prompts |
| Useful | Fresh 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 * 100When 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):

Measured Per-Session Breakdown (claude-sonnet-4: $3.00 in / $0.30 cached / $15.00 out per 1M tokens)
Session | Agent Format | Turns | Total Tokens | File Re-reads | Tool Bloat | Think Replay | Schemas | History Replay | Useful Work | Waste % | Est. Cost |
|
| 32 | 2,438,603 | 1,118,883 | 339,691 | 4,180 | 40,224 | 894,316 | 41,309 | 59.98% | $1.096 |
|
| 30 | 1,584,583 | 481,915 | 385,012 | 3,853 | 18,390 | 660,756 | 34,657 | 54.95% | $0.724 |
|
| 26 | 1,287,459 | 259,368 | 584,640 | 30,373 | 0 | 387,580 | 25,498 | 67.92% | $0.629 |
|
| 30 | 1,078,884 | 132,963 | 133,476 | 0 | 364,590 | 420,953 | 26,902 | 24.70% | $0.475 |
|
| 36 | 1,193,084 | 139,269 | 0 | 609,549 | 24,913 | 366,745 | 52,608 | 62.76% | $0.955 |
|
| 28 | 918,816 | 202,619 | 390,735 | 15,795 | 70,532 | 226,635 | 12,500 | 66.30% | $0.440 |
CORPUS TOTAL | all (6 logs) | 182 | 8,501,429 | 2,335,017 | 1,833,554 | 663,750 | 518,649 | 2,956,985 | 193,474 | 56.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)
Policy | Before Tokens | After Tokens | Tokens Saved | Reduction | After Waste % | Est. Savings / 100 Sessions |
| 8,501,429 | 6,180,914 | 2,320,515 | 27.30% | 40.40% | $15.779 |
| 8,501,429 | 6,635,189 | 1,866,240 | 21.95% | 45.19% | $13.485 |
| 8,501,429 | 7,837,682 | 663,747 | 7.81% | 53.19% | $3.738 |
| 8,501,429 | 8,110,575 | 390,854 | 4.60% | 59.58% | $3.377 |
| 8,501,429 | 3,260,075 | 5,241,354 | 61.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 benchNative 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). Add to Claude Code, Codex, or OpenClaw MCP config:
{
"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:
Tokenizer Approximation When API
usageIs Missing: Logs without per-turn API usage metadata (notably Cline'sapi_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 APIusageis present,ctx-profilerreconciles every turn to the exact reported integer token count, but the split across categories inside a turn still follows text-weighted proportions.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/1Mcache reads while output tokens cost$15.00/1M. That is whyctx-profilerseparates 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.Simulation Does Not Measure Task Accuracy Degradation:
ctx-profiler simulatecomputes 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.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_rereadseven though its contents changed on disk.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 runctx-profiler analyzeon 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 tablesLicense
MIT — see LICENSE.
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
Cuts coding agent token burn up to 72% continuously via contradiction-free memory & verification.
Up to 90% fewer tokens: deterministic, declared tool calls, each with a receipt and an audit trail.
See, price, and control every tool call your AI agents make: policy checks, cost, and audit tools.
Work journal for coding agents: worklogs, tasks, project state and costs across projects.
Related MCP Servers
- AlicenseAqualityCmaintenanceEnables AI coding agents to reduce token usage by condensing source code into AST skeletons, extracting specific symbols, compressing logs, and estimating token budgets.4MIT
- AlicenseNot gradedqualityBmaintenanceEnables AI coding agents to compress terminal output and file context in real time, preserving full error tracebacks while reducing token consumption by 60-85%.43MIT
- AlicenseAqualityBmaintenanceEnables coding agents to reduce prompt token usage by extracting code skeletons and symbols, compressing test and command output, generating compact diffs, and tracking session token health to avoid rate-limit lockouts.61MIT
- AlicenseNot gradedqualityBmaintenanceEnables users to analyze AI agent tool-call logs for redundant calls, retry loops, and duplicate reasoning, returning quantified estimates of wasted tokens and dollars so fixes can be prioritized by ROI.MIT