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)
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
| Category | Classification | What It Captures |
|---|---|---|
file_rereads |
Waste | Unchanged file paths read again (both emission and subsequent turn replays) |
tool_output_bloat |
Waste | Non-file-read shell/grep/ls/test/MCP output exceeding --tool-bloat-threshold (default 2,000 tok) + replays |
reasoning_think_replay |
Waste | Prior-turn <think>...</think> or reasoning blocks re-injected into subsequent prompts |
system_and_tool_schemas |
Overhead | Repeated system prompt + MCP/tool JSON schemas sent every turn |
history_replay |
Overhead | Prior useful conversation turns re-sent in subsequent prompts |
useful_new_work |
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 * 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):
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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
01_claude_code_fastapi_debug |
claude-code |
32 | 2,438,603 | 1,118,883 | 339,691 | 4,180 | 40,224 | 894,316 | 41,309 | 59.98% | $1.096 |
02_codex_ts_refactor |
codex |
30 | 1,584,583 | 481,915 | 385,012 | 3,853 | 18,390 | 660,756 | 34,657 | 54.95% | $0.724 |
03_cline_multi_file_search_edit |
cline |
26 | 1,287,459 | 259,368 | 584,640 | 30,373 | 0 | 387,580 | 25,498 | 67.92% | $0.629 |
04_claude_code_mcp_heavy_workspace |
claude-code |
30 | 1,078,884 | 132,963 | 133,476 | 0 | 364,590 | 420,953 | 26,902 | 24.70% | $0.475 |
05_openclaw_qwen_think_loop |
openclaw |
36 | 1,193,084 | 139,269 | 0 | 609,549 | 24,913 | 366,745 | 52,608 | 62.76% | $0.955 |
06_openai_trace_monorepo_migration |
openai |
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 |
|---|---|---|---|---|---|---|
dedup-rereads |
8,501,429 | 6,180,914 | 2,320,515 | 27.30% | 40.40% | $15.779 |
cap-tool-output-2k |
8,501,429 | 6,635,189 | 1,866,240 | 21.95% | 45.19% | $13.485 |
strip-think-replay |
8,501,429 | 7,837,682 | 663,747 | 7.81% | 53.19% | $3.738 |
lazy-mcp-schemas |
8,501,429 | 8,110,575 | 390,854 | 4.60% | 59.58% | $3.377 |
combined-all |
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 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). 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 tables
License
MIT — see LICENSE.
Metadata
Release files for ctx-profiler 0.1.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| ctx_profiler-0.1.0.tar.gz | 53.6 kB | With provenance | Details for ctx_profiler-0.1.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| ctx_profiler-0.1.0-py3-none-any.whl | Python 3 | none | any | Details for ctx_profiler-0.1.0-py3-none-any.whl |
Total release size: 102.4 kB
Release files / ctx_profiler-0.1.0.tar.gz
| Download URL | ctx_profiler-0.1.0.tar.gz |
|---|---|
| Size | 53.6 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
507b7e43352cc155c0289d5975b5c629a2b85db080aa2ed8e4806fb5e9d9aa43
|
|
BLAKE2b-256 checksum How to use checksums |
0a2f911767e6bd98b2bd3ec2017e0f6bbdfae1c362c79bff23f7a4ff1c36fef6
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 30, 2026.
Transparency logRelease files / ctx_profiler-0.1.0-py3-none-any.whl
| Download URL | ctx_profiler-0.1.0-py3-none-any.whl |
|---|---|
| Size | 48.7 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
b6a36aafbadfbd0337defb5abc8239914f86839f72208ecc5c2430c66b06b94e
|
|
BLAKE2b-256 checksum How to use checksums |
c55184d0eaf532677f1cd1020796c3fbddbd65b9adf3468f2bc5f1c5060e178a
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 30, 2026.
Transparency logSecurity for ctx-profiler 0.1.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for ctx_profiler-0.1.0.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 30, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.