agent-token-forensics
I built agent-token-forensics after watching my own long coding-agent sessions report 97%+ prompt-cache hit rates while still burning most of the budget on uncompacted context tails (>80k tokens), idle cache-TTL cliffs, and identical tool-retry loops. It scans local JSONL transcripts strictly read-only using pure Python 3.10+ stdlib (zero runtime dependencies, zero network calls, zero disk writes).
Zero-arg UX: Run agent-token-forensics analyze with no path to auto-discover recent local transcripts (~/.claude, ~/.codex, ~/.cursor, ~/.gemini), run agent-token-forensics analyze --demo to preview sample output, or drop a .jsonl into the 100% offline browser auditor (0 bytes uploaded).
Quick Start
Live on PyPI as agent-token-forensics. Choose uvx, pipx, pip in a .venv, or zero-install from source.
Linux / macOS (bash)
# Option 1: Zero-Install Ephemeral Run via uvx (recommended)
uvx agent-token-forensics analyze --demo
uvx agent-token-forensics analyze ./transcripts --markdown
# Option 2: Isolated CLI Install via pipx (PEP 668 safe)
pipx install agent-token-forensics
agent-token-forensics analyze ./transcripts --markdown
agent-token-forensics analyze ./session.jsonl --json
# Option 3: Isolated .venv via pip
python3 -m venv .venv
.venv/bin/python -m pip install agent-token-forensics
.venv/bin/agent-token-forensics analyze ./transcripts --markdownWindows (pwsh 7)
# Option 1: Zero-Install Ephemeral Run via uvx
uvx agent-token-forensics analyze --demo
uvx agent-token-forensics analyze .\transcripts --markdown
# Option 2: Isolated CLI Install via pipx
pipx install agent-token-forensics
agent-token-forensics analyze .\transcripts --markdown
# Option 3: Isolated .venv via pip
python -m venv .venv
.\.venv\Scripts\python.exe -m pip install agent-token-forensics
.\.venv\Scripts\agent-token-forensics.exe analyze .\transcripts --markdownRelated MCP server: context-forensics-mcp
Real Session Trace
Output on a real sanitized 232-turn coding session from my own ops repo (40.08M total context tokens, 352.7k peak context): 97.4% apparent cache hit vs 10.9% effective hit ($12.06 recoverable out of $16.01 estimated spend across 2 cache busts, 6 retry loops, and 221 turns riding above 80k tokens):
Live Demo
Verified output from agent-token-forensics analyze --demo (v0.1.1):
Architecture
What It Detects
Signal | Mechanism | Default Threshold |
Multi-Vendor JSONL Schemas | Parses Claude Code / Anthropic ( | Auto-detected per line |
Compaction Inflection Finder | Identifies the exact turn where context crosses |
|
Prompt-Cache Bust Detector | Catches turns where a warm prompt cache ( |
|
Retry-Loop & Tool-Bloat Forensics | Flags consecutive identical tool invocations and ranks tools by attributed token burn. |
|
CLI Reference
agent-token-forensics analyze [paths ...] [--demo]
[--compact-threshold N]
[--post-compact-target N]
[--loop-threshold N]
[--json | --markdown]
agent-token-forensics mcp-serveOmit
paths: auto-discovers recent local JSONL sessions (~/.claude,~/.codex,~/.cursor,~/.gemini).--demo: runs the built-in sample transcript so you can verify output before scanning local logs.--json/--markdown: emit machine-readable JSON for CI budgets or clean Markdown summary tables.mcp-serve: starts the strictly read-only JSON-RPC 2.0 MCP server overstdio.
MCP Server (stdio)
agent-token-forensics ships a zero-dependency, strictly read-only MCP JSON-RPC 2.0 server over stdio (pure Python 3.10+ stdlib, zero writes, zero telemetry, zero network calls).
Exposed Read-Only Tools:
analyze_transcripts— analyzes a JSONL transcript file or directory (path, optionalcompact_threshold,post_compact_target,output_format:"json"|"markdown") and returnscache_bust_events,compaction_inflection_points,retry_loops,top_tools_by_tokens, and cost/savings summary.forensics_about— returns version, supported transcript schemas (Claude Code/Anthropic, OpenAI/Codex/Cursor, GeminiusageMetadata, Antigravity), and zero-telemetry / read-only guarantees.
Run directly from a cloned repo or source install:
python -m agent_token_forensics.mcp_server
# or via the zero-install shim / installed CLI:
python agent_token_forensics_cli.py mcp-serve
agent-token-forensics mcp-serveClaude Code / Cursor / Antigravity MCP config (mcpServers):
{
"mcpServers": {
"agent-token-forensics": {
"command": "python",
"args": ["/path/to/agent-token-forensics/agent_token_forensics_cli.py", "mcp-serve"]
}
}
}Or if installed from PyPI / source into your environment (or via uvx --from git+https://github.com/BlackBadHope/agent-token-forensics):
{
"mcpServers": {
"agent-token-forensics": {
"command": "python",
"args": ["-m", "agent_token_forensics.mcp_server"]
}
}
}Troubleshooting & Clean Uninstall
1. Ubuntu / Debian 24.04: error: externally-managed-environment (PEP 668)
Modern Debian/Ubuntu blocks global pip install under PEP 668. Use either clean option (no --break-system-packages needed):
# Option A: Zero-install direct run (pure Python 3.10+ stdlib)
python3 agent_token_forensics_cli.py analyze ./session.jsonl --markdown
# Option B: Isolated virtual environment (zero external deps)
python3 -m venv .venv
.venv/bin/python -m pip install --no-deps .
.venv/bin/agent-token-forensics analyze ./transcripts --markdown2. Empty Directories, Zero-Turn Files, and Corrupt JSONL Lines
agent-token-forensics is strictly read-only and designed to survive messy real-world logs:
Empty directory or no
.jsonlfiles: exits0with a clean zero-turn summary (files_scanned: 0,turns: 0) rather than crashing.Truncated, malformed, or non-UTF-8 JSONL lines: invalid lines and non-usage metadata events are skipped safely (
errors="replace"), while all valid turns in the same file are still analyzed.Non-existent path: fails explicitly with exit
2and an error message onstderr.No compaction recommendations shown: your sessions stayed under
--compact-threshold(default80000tokens); lower it (e.g.--compact-threshold 40000) for smaller context windows.
3. Clean Uninstall / Reset-to-Zero
agent-token-forensics creates zero hidden state directories, caches, or background daemons. To uninstall and reset to zero:
# Linux / macOS
python3 -m pip uninstall -y agent-token-forensics 2>/dev/null || true
rm -rf ./agent-token-forensics # or remove your .venv directory# Windows (PowerShell 7)
python -m pip uninstall -y agent-token-forensics
Remove-Item -Recurse -Force ".\agent-token-forensics" -ErrorAction SilentlyContinueDevelopment & Verification
ruff check agent_token_forensics agent_token_forensics_cli.py tests agensi-skill
python -m pytest -q
# or unittest:
python -m unittest discover -s tests -p "test_*.py" -vBrowser Auditor & Related Tools
Zero-Upload Browser Auditor: integrityharness.dev/token-audit (same deterministic detector math running 100% client-side in JS; free forever).
Optional Cloud Control Plane: integrityharness.dev (if you need multi-host killswitch toggles or team alerts across machines; this CLI and MCP server remain MIT/free forever).
Integrity Harness Ecosystem
Repository | Role in the Harness | Stack |
OS process-tree killswitch & runaway execution breaker | Python stdlib · Win32 / POSIX | |
Read-only JSONL token, cache-cliff & retry-loop forensics | Python 3.10+ stdlib · MCP | |
SHA-256 digest-bound test cache & anti-loop monitor gate | Python 3.10+ stdlib · CLI | |
Multi-plane execution firewall, witness ledger & control plane | Go / Python · Hybrid | |
Multi-stage agent studio & CAS patch rail | TypeScript / Python | |
Public control-plane site & docs (integrityharness.dev) | Cloudflare Pages |
License & Disclaimer
MIT — see LICENSE. Security policy and responsible disclosure: SECURITY.md.
Independent Open-Source Project:
agent-token-forensicsis an independent open-source project maintained by BlackBadHope and is not affiliated with, endorsed by, or sponsored by Anthropic, OpenAI, Cursor, Google, or any other AI/IDE vendor whose transcript schemas are parsed for compatibility.
Available Tools
2 toolsanalyze_transcriptsARead-onlyIdempotent
Strictly read-only analysis of a JSONL transcript file or directory. Detects prompt-cache bust events, compaction inflection points, retry loops, top tools by attributed tokens, and estimated USD cost/savings. Performs zero writes and zero network calls.
Inputs: path (required), output_format, compact_threshold, post_compact_target.
forensics_aboutARead-onlyIdempotent
Return server version, supported multi-vendor JSONL transcript schemas, and strict read-only / zero-telemetry / zero-dependency guarantees.
Inputs: no named parameters.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 2 tools
The two tools have clearly distinct roles: analyze_transcripts does the actual read-only analysis, while forensics_about only returns version/schema/guarantee metadata. There is no realistic scenario in which an agent would confuse one for the other.
analyze_transcripts follows a verb_noun pattern, but forensics_about is a prefixed noun phrase with no verb. Both are snake_case and readable, but the convention is mixed rather than predictable.
Two tools is thin for a server, and one of them (forensics_about) is pure metadata that could arguably be folded into documentation or the analyzer's output. The surface is deliberately minimal but feels borderline under-scoped.
The single analysis tool covers the core forensics workflow well (cache busts, compaction points, retry loops, token attribution, cost) and handles both files and directories. Minor gaps remain, such as no cross-session comparison or configurable threshold/output reporting beyond the default summary.
Maintenance
Related MCP Connectors
Exact Claude API cost calc with real cache economics, plus a tiktoken-misuse scanner.
Free read-only Tokenomat account tools: balance, LLM prices, usage by key, bills, cost estimates.
Work journal for coding agents: worklogs, tasks, project state and costs across projects.
LLM API prices and AI agent cost estimates, verified daily. Read-only cost lookup tools.
Related MCP Servers
- AlicenseAqualityCmaintenanceLocal-first dashboard + MCP server that parses Claude Code and Codex JSONL files into a SQLite cost / token tracker. Per-MCP and per-tool breakdown, session drill-down, dedup by request_id; never talks to vendor APIs5102 npm1MIT
- AlicenseNot gradedqualityBmaintenanceEnables offline, read-only forensic analysis of Claude Code session transcripts, providing exact token usage, cost estimates, context growth, and compaction suggestions.MIT
- AlicenseAqualityBmaintenanceToken usage and estimated cost for Claude Code, Codex, Cursor and 20 more AI coding agents, read locally from their session files. No API key, no telemetry.241AGPL 3.0
- AlicenseNot gradedqualityBmaintenanceEnables AI coding agents such as Claude Code, Cursor, Codex, and OpenCode to query local token usage, costs, quotas, projects, and models through six strictly read-only tools. All data stays on the local machine, drawn from passively parsed session logs rather than uploaded telemetry.MIT