3. Output Compression: CLI & Tool Output
Tool outputs, shell command results, test logs, and database query responses share a structural problem: they contain 70–95% boilerplate. A passing test suite logs hundreds of success lines for the one failure you care about. A git log dumps metadata for every commit when you need three fields. This noise enters the context window verbatim unless intercepted.
RTK (Rust Token Killer)
RTK is a CLI proxy that intercepts command output before it reaches Claude's context, applying purpose-built filters that surface signal and discard noise. It integrates via a Claude Code hook, so standard commands are transparently rewritten.
| Attribute | Details |
|---|---|
| Source | github.com/rtk-ai/rtk |
| Install | brew install rtk-ai/tap/rtk or cargo install rtk |
| Stars | 69,042 (GitHub API, 2026-07-07), up from 446 in March 2026 and 24,397 in April 2026 |
| Integration | Claude Code hook via rtk init --global |
A roughly 2.8x jump in under three months is a steep curve for a CLI proxy. It is plausible given the tool's growing bundling into other agents' default setups (see below), but treat the figure as unverified against the full star-history graph rather than confirmed growth, and re-check before quoting it in a high-stakes context.
Measured savings across command categories:
| Command | Reduction |
|---|---|
rtk git log | 92% |
rtk git status | 76% |
rtk vitest run | 99%+ |
rtk cargo test | 89% avg |
rtk pnpm outdated | 70–85% |
The design philosophy: suppress successful output, surface failures. A test suite that passes 300 tests and fails 2 should show 2 lines, not 302. This matches how a developer reads output. Context should match that cognitive model.
RTK supports custom filters via TOML DSL (.rtk/filters.toml) for project-specific output patterns without writing Rust. See Third-Party Tools: RTK for the complete feature reference.
Real-world cost impact: Real-world billing data from the codepointer substack ($926 API bill, analyzed) shows that bash output accounts for roughly 12% of total token usage in a typical Claude Code session, not the dominant source. File reads represent approximately 65%. At 60-90% compression on bash output alone, RTK's real API cost impact is in the range of 6-10% of the total bill, not 60-90%. The per-command savings are genuine; the headline "60-90% savings" refers to the compression ratio on the commands RTK processes, not to overall session cost reduction. For total context efficiency, pair RTK with a file-read compression tool like lean-ctx or tilth (see below).
Headroom
Headroom compresses what enters the context from tool outputs, structured data, and conversation history. Its output shaper also reduces what comes back from the model, making it one of the few tools that operates on both sides of the LLM call.
| Attribute | Details |
|---|---|
| Source | GitHub: headroomlabs-ai/headroom |
| Docs | headroom-docs.vercel.app |
| Stars | 62,778 (GitHub API, 2026-07-27), 4,754 forks (was 57,223 / 4,205 on 2026-07-07) |
| Author | Tejas Chopra (Senior Engineer, Netflix) |
| License | Apache 2.0 |
| Install | pip install "headroom-ai[all]" or npm install headroom-ai |
| Version | v0.25.0 (June 2026, latest verified) |
URL correction: Earlier versions of this guide linked
headroom.ai(unrelated domain) and latergithub.com/chopratejas/headroom(the author's personal fork). The project has since moved to theheadroomlabs-aiorg; the old personal slug now redirects, a standard GitHub org transfer.
Reported cost impact: the maintainer cites aggregate savings of "~$700K across 200B tokens processed." This is self-reported with no third-party audit found. Treat it as a marketing signal, not a verified figure, distinct from the per-workload benchmark numbers below, which do publish methodology.
Five deployment modes:
- Python library:
compress(messages)directly in application code - TypeScript/npm:
withHeadroom()/compress() - HTTP proxy:
headroom proxy --port 8787, then setANTHROPIC_BASE_URL=http://localhost:8787 - MCP server:
headroom mcp install(exposesheadroom_compress,headroom_retrieve,headroom_stats) - Agent wrap:
headroom wrap claude|codex|cursor|aider|copilot
Compress-Cache-Retrieve (CCR): Instead of sending verbose tool output to the model, Headroom replaces it with a <code v-pre>{{HEADROOM_TAG_N}}</code> placeholder, stores the original in a local SQLite store (HNSW vector index + FTS5 full-text index), and registers a retrieval handle. The model calls headroom_retrieve(tag) when it needs the original data. Multiple agents (Claude + Codex) can share the same SQLite store for cross-agent context handoff.
Output shaper (HEADROOM_OUTPUT_SHAPER=1): appends a brevity instruction at the end of the system prompt (cache prefix is preserved) and reduces model effort on turns that follow successful tool results. Savings are reported as "estimated" using a 10% holdout control group with 95% confidence intervals.
Benchmark scope: The published token reductions (code search 92%, SRE debugging 92%, GitHub triage 73%) are measured on specific structured content types under optimal conditions, not full-session spend. An independent measurement found approximately 47% full-session reduction. Accuracy benchmarks (GSM8K 0.870 to 0.870, TruthfulQA +0.030) are N=100 samples, run on v0.5.18, not independently reproduced. Reproduction command: python -m headroom.evals suite --tier 1.
Known issues (June 2026, check the issue tracker for current resolution status):
- Issue #714: CCR originals expire after 5 minutes (LRU TTL). Long-running agent jobs that pause between steps will hit retrieval failures when the cache expires. No persistent fallback is documented for this case.
- Issue #1158:
headroom wrap claudesilently caps context at 200K for Claude Max subscribers (thecontext-1m-2025-08-07beta header is dropped). Claude Max users should useheadroom mcp installinstead ofwrap. - Issue #1227 (security, unresolved as of June 2026): CCR endpoints lack loopback protection and use permissive CORS. A local web page can read cached tool outputs without authentication. Avoid CCR if the host runs alongside untrusted local web content.
- Issue #1209: In some configurations, CCR stores the <code v-pre>{{HEADROOM_TAG_N}}</code> placeholder as the original, so
headroom_retrievereturns the placeholder rather than the actual data. PR #1208 filed. - Issue #1233:
CodeAwareCompressorgenerates invalid Python syntax on roughly 28% of real files containing modern syntax (match/case, walrus operator, nested async). Silent fallback to uncompressed output in those cases.
When to choose Headroom over RTK: RTK handles unstructured CLI text and drops content you definitively do not need. Headroom is the right choice for structured data (JSON payloads, database results, API responses) where you cannot predict upfront which parts the model will need, and where lossless retrieval is a requirement. The two tools complement each other; RTK operates at the shell output layer, Headroom at the structured data layer.
Production note: Core compression is functional. CCR has reliability issues under bugs #714 and #1209 above. For Claude Max users, prefer MCP mode over headroom wrap.
pxpipe
pxpipe is the first production tool built on optical/visual context compression specifically for Claude Code and the Anthropic API: instead of shrinking text, it rewrites large context blocks as images before the request leaves the machine. See Context Engineering: Optical and Visual Context Compression for the research lineage (DeepSeek-OCR, AgentOCR, Glyph, VIST).
| Attribute | Details |
|---|---|
| Source | github.com/teamchong/pxpipe |
| License | MIT, TypeScript |
| Stars | 4,277 (GitHub API, 2026-07-07), up from 586 at launch in May 2026, roughly 7x in under two months |
| Install | npx pxpipe-proxy |
Mechanism: a local proxy intercepts /v1/messages calls and, above a computed cost-effectiveness threshold, rewrites large tool_result blocks, already-collapsed older turns, and the static system-prompt/tool-doc block into PNG images (1928px-wide columns, roughly 92,000 characters per page, roughly 4,761 vision tokens per page). It never touches model output, recent turns, or sparse prose, where text stays cheaper per character. The text-vs-image break-even is around 19 characters per token; the maintainer's observed Claude Code traffic averages 1.91 characters per token, so most large content is worth imaging. Exact-byte content (passwords, hashes, IDs) is explicitly excluded from rendering and flagged in the README as a documented lossy-recall risk, not a solved problem.
npx pxpipe-proxy
ANTHROPIC_BASE_URL=http://127.0.0.1:47821 claudeBenchmarks: 59 to 70% end-to-end bill reduction, measured per-request via a parallel counterfactual count_tokens call logged to ~/.pxpipe/events.jsonl and cross-checked against actual billed usage, a reproducible methodology rather than a marketing estimate. SWE-bench Lite pilot: 10/10 passing in both arms at -65% request size (small n, disclosed as such in the README). Verbatim recall of hex strings: 13/15 correct on Fable 5, 0/15 on Opus, numbers the README states plainly rather than hides.
Model allowlist: defaults to claude-fable-5 and gpt-5.6. Opus 4.7/4.8 and GPT-5.5 are opt-in because of measured higher misread rates on rendered images.
When to choose pxpipe over Headroom: same API-gateway layer, different modality. Headroom compresses text to text (reversible, retrieval-based); pxpipe rasterizes text to images (lossy on exact strings, not retrieval-based). They complement rather than compete: pxpipe is Claude Code/Anthropic-API-specific with limited GPT support, not a multi-agent generalist tool like Headroom.
tilth
tilth is an MCP server for code navigation that targets the largest single source of token usage in Claude Code sessions: file reads. Rather than returning full file contents, it provides structural navigation via tree-sitter, so the model reads shapes and relationships instead of raw text.
| Attribute | Details |
|---|---|
| Source | github.com/jahala/tilth |
| Install | cargo install tilth then tilth install claude-code |
| Architecture | MCP server, installs into Claude Code |
| Parser | tree-sitter (multi-language) |
The core tools it exposes:
- File read with auto-outline: for large files, instead of the full text, returns a structural skeleton with section names and line ranges. The model requests specific ranges on demand.
- Symbol search: definitions, usages, and resolved callees in a single call, replacing the grep-then-read loop.
--callers: all call sites of a symbol, structurally, not via text search.--deps: imports and dependents of a file, useful before a refactor to understand blast radius.grok <symbol>: everything about one symbol in one call: signature, callers, callees, sibling functions, associated tests.- Structural diff: change summary at the function level, not the line level.
- Session dedup: symbols already shown in the session are marked
[shown earlier]rather than re-expanded.
Benchmarks (160 runs across 4 real repositories, metric = cost per correct answer):
| Model | Without tilth | With tilth | Cost change | Accuracy change |
|---|---|---|---|---|
| Sonnet 4.6 | baseline | tilth | -44% | 84% → 94% |
| Opus 4.6 | baseline | tilth | -39% | 91% → 92% |
| Haiku 4.5 | baseline | tilth | -38% | 54% → 73% |
| Average | -40% | 76% → 86% |
The "cost per correct answer" framing is meaningful: it captures both the efficiency gain and the accuracy improvement simultaneously. A tool that saves tokens but degrades output quality is not useful. tilth shows gains on both dimensions.
Why file reads are the right target: they represent about 65% of total token usage in a real Claude Code session (versus ~12% for bash output). Compressing the larger pool produces proportionally larger savings on the total bill.
Install:
cargo install tilth
tilth install claude-code # registers the MCP server in Claude CodeNo per-project configuration is needed after global install.
Comparison with lean-ctx: Both tilth and lean-ctx use tree-sitter to compress file reads. lean-ctx operates as a hook-level redirect (intercepts native Read calls at the MCP layer), while tilth exposes explicit navigation tools the model calls directly. lean-ctx is more transparent and requires no change to how the model requests files. tilth gives the model more control over what it fetches but requires it to use the tilth tools rather than standard read operations. On teams that want the model to actively navigate code structure rather than have reads compressed passively, tilth's explicit tools fit better.
Token Savior
Token Savior is a three-in-one MCP server: structural code navigation by symbol (replacing full-file reads), Bash output compaction for 34 common CLI tools, and persistent cross-session memory via SQLite with FTS5.
| Attribute | Details |
|---|---|
| Source | GitHub: Mibayy/token-savior |
| Install | pip install "token-savior-recall[mcp]" then ts init --agent claude --yes |
| Stars | ~1,000 (June 2026) |
| Language | Python 3.11+ |
| Last commit | April 2026 (C99/C11 and GLSL support added) |
Core navigation tools (via the optimized profile, 15+ tools):
find_symbol(name)- locate functions and classes across the indexed codebaseget_function_source(name)- retrieve implementation without loading the full fileget_full_context(identifier)- extended context around a symbolget_change_impact(identifier)- dependency chain for blast-radius analysis before refactoringbuild_commit_summary- recent git changes without reading every filememory_index/memory_search- store and retrieve session learnings across runsts_discover()- scan past transcripts for missed optimization opportunities
Bash compaction: 34 output compactors for git, pytest, jest, kubectl, and similar tools, activated via TS_BASH_COMPACT=1 and PostToolUse hooks. Outputs above 4KB fall back to full capture. This feature is opt-in and accounts for a significant share of the reported gains; skipping it reduces the savings substantially.
6 tool profiles (controls how many tools the model sees, useful when manifest budget is constrained): full, core, nav, lean, ultra, tiny. The tiny profile exposes 6 tools; roughly 60 others are reachable via ts_search on demand.
Language support: Python, TypeScript/JavaScript, Go, Rust, C#, C/C99/C11, GLSL, plus config formats (JSON, YAML, TOML, INI, ENV, HCL/Terraform, Dockerfile, Markdown).
tsbench results (Claude Opus 4.7, 96 tasks, synthetic 2,000-line codebase, --seed 42, author-created benchmark):
| Metric | Without Token Savior | With Token Savior |
|---|---|---|
| Task completion | 78.3% | 97.9% |
| Active tokens/task | ~16,800 | ~3,929 (-77%) |
| Wall time/task | ~111s | ~26.6s (-76%) |
The project separately reports 97% reduction in characters injected across 170+ real sessions. No independent third-party reproduction of the benchmark has been published. Behavior on large codebases (100K+ lines) has not been benchmarked under controlled conditions.
# Recommended install
pip install "token-savior-recall[mcp]"
ts init --agent claude --yes # merges hooks into ~/.claude/settings.json
# Or without global install
WORKSPACE_ROOTS=/your/project uvx token-saviorComparison with tilth: tilth (Rust, 14 languages, controlled benchmark across 4 real repositories) focuses on structural code navigation and file outlines. Token Savior adds Bash output compaction and persistent cross-session memory, features tilth does not have. Choose tilth for a faster, independently benchmarked code navigation layer. Choose Token Savior if you also need Bash compaction and memory persistence across sessions.
context-mode
context-mode is an MCP server that operates at the boundary between tools and context, intercepting tool call outputs before they reach the conversation window and applying compression or selective retrieval. It also implements a session tracking layer using SQLite with FTS5 full-text search, enabling semantic retrieval of earlier session content after /compact discards raw history.
| Attribute | Details |
|---|---|
| Source | GitHub: mksglu/context-mode |
| Stars | 18,654 (GitHub API, 2026-07-07), up from 14,149 in May 2026 (+32% in about 2 months) |
| License | ELv2 (commercial SaaS planned) |
| Platforms | Claude Code plugin, Gemini CLI, Copilot, Cursor, Kiro, Zed, and 11 others (17 total, up from 12 in May 2026) |
| Claims | 98% MCP output compression, 65–75% response compression |
The growth rate reads as consolidation of an already-mature tool rather than a new-entrant spike: other projects now cite context-mode as a dependency or reference, a sign of an ecosystem forming around it rather than just end users adopting it.
How the MCP output sandbox works: Instead of routing raw tool call output directly into the conversation, context-mode intercepts the result, applies compression, and injects a summary with a retrieval handle. The full output is accessible on demand if the model requests it, similar in spirit to Headroom's lossless architecture but operating specifically on MCP tool boundaries.
Session memory after /compact: context-mode uses SQLite + FTS5 to index session history. When /compact runs and discards raw conversation history, the SQLite index persists. Subsequent retrieval queries use BM25 ranking to surface relevant earlier context without reloading the full transcript.
"Think in Code" pattern: context-mode v1.0.64 documented a pattern where, instead of reading files to answer an exploratory question, the model writes and executes a script that queries or counts, then reads only the result. This is covered in depth as a named technique in the context engineering guide.
When to choose context-mode: If you run Claude Code alongside other platforms (Cursor, Gemini CLI) and want a single context management layer that works across all of them. Also useful when MCP tool outputs are large and structured, and you need post-compact session retrieval beyond what /compact alone provides.
Comparison with RTK and Headroom: RTK operates at the shell command level (CLI output), Headroom at the structured data/API response level. context-mode operates specifically at the MCP tool boundary and adds session persistence. These tools are complementary.
stacklit
stacklit generates a machine-readable index of a repository's package structure, exported symbols, and dependencies. An agent reads this index in a single call (~250 tokens) instead of spending 50,000+ tokens exploring files to understand the codebase structure.
| Attribute | Details |
|---|---|
| Source | GitHub: glincker/stacklit |
| Install | npm install -g stacklit |
| Integration | Auto-configures Claude Code, Cursor, and Aider via stacklit setup |
| Claimed reduction | 50,000+ tokens of exploration compressed to ~250 tokens |
How it works: stacklit generate-json scans the repository and writes stacklit.json, a structured map of packages, exports with type signatures, dependency graph, git activity heatmap, and framework hints. stacklit setup injects a compact codebase map into agent configuration files automatically. stacklit diff detects when the index is stale after file additions or deletions.
# One-time setup per repository
stacklit generate-json # create the index
stacklit setup # inject into Claude Code / Cursor / Aider config
# Maintenance
stacklit diff # check if index is stale
stacklit generate-json # re-index after structure changesWorktree compatibility: generates per-repository indexes with no centralized state. Unlike grepai (which requires a local embedding index) or Serena (which connects to a language server), stacklit produces a static JSON file that works in git worktrees and ephemeral CI environments without additional setup.
Comparison with RTK and context-mode: RTK intercepts CLI output during a session. context-mode intercepts MCP tool output in real time. stacklit eliminates exploration-phase token spend before the session starts, by making the repo structure known from the first message. The three tools target different moments in a session's lifecycle and are complementary.
Cloudflare Code Mode MCP
A different category of tool-schema cost: an MCP server with hundreds or thousands of endpoints loads a schema per tool, and that schema overhead can dwarf the actual task. Cloudflare's Code Mode MCP (cloudflare/mcp) addresses this at the API-surface level rather than the output level.
Instead of exposing one MCP tool per endpoint, it exposes exactly two meta-tools, search() and execute(), backed by a typed SDK. The model writes and runs JavaScript in a sandboxed V8 instance (Dynamic Worker Loader) that calls the typed SDK, rather than receiving a schema definition for every possible endpoint upfront. For Cloudflare's full API surface (2,500+ endpoints), this drops the schema-loading cost from roughly 1.17M tokens to about 1,000, a 99.9% reduction on that specific dimension.
This is a shipped production feature at a major infrastructure vendor, not a side project or a research prototype. It generalizes a pattern worth naming: when a tool surface is large and mostly unused per session, exposing a code-execution interface over the API instead of one MCP tool per endpoint moves the token cost from "loaded upfront for every session" to "paid only for the endpoints actually called." See MCP Servers Ecosystem for how this interacts with Claude Code's MCP tool-count guidance (Progressive Disclosure in the core context engineering guide recommends fewer than 80 total tools across active servers; a code-execution MCP server sidesteps that ceiling entirely by exposing 2 tools regardless of API surface size).
Zero-install approach: claude-token-efficient
claude-token-efficient (5,884 stars, verified 2026-07-27) is a single CLAUDE.md file that instructs Claude to generate concise responses. No binary, no MCP server, no hooks.
The creator claims approximately 63% output token reduction. No methodology is published for that figure. The approach works within a real but narrow scope: if verbose model output is your primary cost driver, a style instruction in CLAUDE.md costs nothing to try. It cannot compress shell output, file reads, or tool responses. Those require tools like RTK, lean-ctx, Headroom, or tilth. The near-6K star count reflects genuine demand for zero-config options, not validated performance across diverse workloads.
Use it as a starting point. When you hit the ceiling, the tools above address what a CLAUDE.md file cannot.