Skip to main content
Glama

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).

NOTE

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 --markdown

Windows (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 --markdown

Related 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 (usage.input_tokens, cache_read_input_tokens), OpenAI / Codex / Cursor (prompt_tokens, prompt_tokens_details.cached_tokens), Gemini (usageMetadata), and Antigravity flat transcripts.

Auto-detected per line

Compaction Inflection Finder

Identifies the exact turn where context crosses --compact-threshold and estimates realistic token & USD savings from compacting to --post-compact-target.

80,000 tokens

Prompt-Cache Bust Detector

Catches turns where a warm prompt cache (>=70% hit ratio) suddenly collapses (<30%), exposing silent prefix mutations or idle TTL evictions.

>=70% -> <30%

Retry-Loop & Tool-Bloat Forensics

Flags consecutive identical tool invocations and ranks tools by attributed token burn.

>=3 consecutive calls (--loop-threshold)


CLI Reference

agent-token-forensics analyze [paths ...] [--demo]
                              [--compact-threshold N]
                              [--post-compact-target N]
                              [--loop-threshold N]
                              [--json | --markdown]

agent-token-forensics mcp-serve
  • Omit 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 over stdio.


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, optional compact_threshold, post_compact_target, output_format: "json" | "markdown") and returns cache_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, Gemini usageMetadata, 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-serve

Claude 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 --markdown

2. 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 .jsonl files: exits 0 with 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 2 and an error message on stderr.

  • No compaction recommendations shown: your sessions stayed under --compact-threshold (default 80000 tokens); 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 SilentlyContinue

Development & 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" -v

  • 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

BlackBadHope/agent-killswitch

OS process-tree killswitch & runaway execution breaker

Python stdlib · Win32 / POSIX

BlackBadHope/agent-token-forensics

Read-only JSONL token, cache-cliff & retry-loop forensics

Python 3.10+ stdlib · MCP

BlackBadHope/evidence-gate

SHA-256 digest-bound test cache & anti-loop monitor gate

Python 3.10+ stdlib · CLI

BlackBadHope/integrity-platform

Multi-plane execution firewall, witness ledger & control plane

Go / Python · Hybrid

BlackBadHope/neon-studio

Multi-stage agent studio & CAS patch rail

TypeScript / Python

BlackBadHope/integrity-landing

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-forensics is 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 tools
analyze_transcriptsA
Read-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_aboutA
Read-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

    A3.9/5.0

    Scored across 2 tools

    Disambiguation5/5

    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.

    Naming Consistency3/5

    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.

    Tool Count3/5

    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.

    Completeness4/5

    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

    ActivityMaintained
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      A
      quality
      C
      maintenance
      Local-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 APIs
      5
      102 npm
      1
      MIT
    • A
      license
      Not graded
      quality
      B
      maintenance
      Enables 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