context-forensics-mcp
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.
context-forensics-mcp
Forensic analysis of Claude Code sessions: where your tokens went, what it cost, and where to compact.
An MCP server that reads the JSONL transcripts Claude Code already writes to ~/.claude/projects/ and answers with exact numbers — no estimates where the transcript already recorded the truth, no API keys, no network.
Session baf896a6 — 13 MB transcript, analyzed in 95 ms
Turns: 527 assistant / 338 user / 0 sidechain
Models: claude-fable-5-1 ×527
Tokens: input 15,052 | cache read 213,344,398 | cache write 5m 0 / 1h 3,341,571 | output 2,604,644 (thinking 799,980)
Cost: $250.5503 (pricing 2026-09-20)
Peak: 628,101 tokens at turn 863 (62.8% of window)
Top hogs:
Read: ~1,229,048 tokens, 19 call(s), 96.3%
Bash: ~29,437 tokens, 126 call(s), 2.3%
mcp__plugin_playwright_playwright__browser_snapshot: ~4,968 tokens, 6 call(s), 0.4%
Findings:
[high] Read result ~158223 tokens at turn 500 — file .../report-full.png
[high] Read result ~129573 tokens at turn 471 — file .../decision-dialog.png
[high] Read result ~118104 tokens at turn 509 — file .../evidence-sheet.pngThat session spent $53 on cache reads alone and 96% of its tool output was 19 PNG screenshots read as base64. You would never see that from inside the session.
Why
Every agent session has a context window that fills up, a bill that grows, and tools that quietly return more than they should. Claude Code records all of it — model, usage buckets, cache hits, every tool call and result — but nothing reads it back. This server does, and hands the result to the agent itself, so it can inspect its own sessions and adjust.
Related MCP server: tokenscope
Install
Requires Node 20+.
Claude Code
claude mcp add context-forensics -- npx -y context-forensics-mcpClaude Desktop / Cursor / any MCP client — add to your MCP config:
{
"mcpServers": {
"context-forensics": {
"command": "npx",
"args": ["-y", "context-forensics-mcp"]
}
}
}Then ask: "Analyze my latest session", "What ate the context in session abc123?", "How much did the my-app project cost this month?"
CLI (no MCP client needed)
npx -p context-forensics-mcp context-forensics report latest
npx -p context-forensics-mcp context-forensics list my-projectTools
Every tool returns { ok: true, summary, data } or { ok: false, error, hint }. summary is one line for humans; data is compact JSON for the agent.
Tool | Input | What you get |
|
| Sessions newest first: id, project, dates, turn count, models, title. Start here to find a session id. |
|
| Everything at once: turns, models, exact token buckets, USD cost, peak context and % of window, top 3 hogs, top 3 findings. |
|
| What filled the context, ranked. Bytes are exact; tokens ≈ bytes/4. |
|
| USD by model and by bucket: input, cache read, 5m cache write, 1h cache write, output. Project mode aggregates every matching session. |
|
| Turn-by-turn context size, the delta, the tool result that caused each jump, and the turns where 80% / 90% of the window were crossed. |
|
| Findings with evidence and estimated savings (see below). |
session accepts a session id (uuid), an absolute .jsonl path inside the allowed roots, or "latest".
Compaction heuristics
Kind | Fires when | Severity |
| One tool result over ~20k tokens | high |
| Context crossed 80% of the model's window | high |
| Same file read 3+ times (savings = every read after the first) | medium / high |
| Images or base64 blobs in tool results | medium |
| 5+ Bash results over ~5k tokens each | medium |
| Thinking tokens > 5× visible output across the session | low |
Configuration
Env var | Default | Purpose |
|
| Directories the server may read, separated by |
| bundled table | Path to a JSON file merged over the bundled prices. Partial entries are fine. |
Pricing override example — bump one price and add a new model:
{
"asOf": "2026-12-01",
"models": {
"claude-sonnet-5": { "input": 3, "output": 15 },
"claude-new-model": { "input": 4, "cacheRead": 0.4, "cacheWrite5m": 5, "cacheWrite1h": 8, "output": 20, "contextWindow": 1000000 }
}
}Accuracy
Exact: every token count in
tokens,costanddiff_context_growthcomes straight from theusageblock Claude Code recorded per turn — input, cache read, cache creation split by 5-minute / 1-hour TTL, output, thinking.Approximate: per-tool and per-file sizes are measured in bytes of the serialized result and converted at 4 bytes/token. They are labelled
approxTokenseverywhere. For images this overstates real image tokens (base64 is large, image tokens are not).Pricing: bundled from Anthropic's pricing page, dated in
pricingAsOf. Unknown models getcost: nullfor that model and are listed inunknownModels— never guessed.Context size at a turn =
input + cacheRead + cacheCreate5m + cacheCreate1h. Sidechain (subagent) turns are counted but excluded from the growth timeline.
Privacy
Read-only. No network calls, no writes, no telemetry, no child_process. The only files it opens are .jsonl transcripts under the allowed roots. Nothing leaves your machine.
Development
npm install
npm test # vitest, 59 tests
npm run test:coverage # thresholds: 80% lines / 70% branches
npm run typecheck
npm run build
npm run dev # run the stdio server from sourcetests/fixtures/real-anonymized.jsonl is a real transcript with every string replaced by same-length filler and every path hashed (scripts/anonymize.ts). Structure and usage numbers are untouched, which is what the parser and cost tests need.
Layout: src/parser (streaming JSONL → typed turns) → src/analysis (pure functions) → src/server (MCP tools with Zod schemas). src/discovery finds and gates transcript files; src/pricing owns the price table.
License
MIT
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
Exact Claude API cost calc with real cache economics, plus a tiktoken-misuse scanner.
Free, read-only context retention review for RAG and agent workflows. Supply sanitized text with stable source IDs and a token budget; receive a source-linked context pack, token estimates, and exact excerpt-retention results. No web fetching, account access, model calls or payments. Checks text selection, not factual truth or semantic completeness. No API key required.
Count tokens (o200k/cl100k), truncate to a budget, chunk text for RAG and estimate LLM cost.
Research-backed lint + generation for agent context files (CLAUDE.md, AGENTS.md) + prompt enhancer.
Related MCP Servers
- FlicenseNot gradedqualityNot gradedmaintenanceProvides intelligent analysis of token usage patterns and optimization recommendations to improve efficiency and reduce costs in Claude Code sessions. Offers real-time analysis, cost metrics, and actionable insights for better context window and tool usage optimization.3 npm-
- AlicenseNot gradedqualityCmaintenanceAnalyzes Claude Code session token usage and cost locally — where spend actually lands across cache-read, cache-write and output, and what is consuming the context window. Read-only and offline: it parses your own session files and exposes analyze_claude_cost, get_cost_benchmark and tokenscope_share_summary.54 npm4MIT
- AlicenseBqualityBmaintenanceLets a coding agent inspect its own run efficiency mid-session from local Claude Code transcripts, exposing the share of paid tokens that became model output versus context re-reading. Ships two stdio tools — one returning the shares as structured data and one returning the full cost-weighted report — with no network calls.2MIT
- AlicenseAqualityBmaintenanceAnalyzes local Claude Code logs to measure subscription value, waste, and rate-limit usage, including chat share and current limits, without uploading data.4MIT