Skip to main content
Glama

nano-headroom

Zero-dependency Python reproduction of Headroom's reversible Compress-Cache-Retrieve (CCR) context layer — featuring SmartCrusher, LogCrusher, TracebackCrusher, CacheAligner, CLI command wrapping, and a stdio MCP Server.

零外部依赖、纯 Python 标准库极简复刻近期热门开源项目 headroomlabs-ai/headroom 核心机制:可逆上下文压缩架构(Compress-Cache-Retrieve, CCR)——自动折叠巨型 JSON 数组、长终端日志与递归报错栈,100% 保留异常尖刺并支持按 Hash / JSONPath / 行号无损取回原文,内置 CLI 包装器、MCP Server 与 Claude Code Skill。

License: MIT Python 3.10+ Zero Dependencies MCP Server


Why nano-headroom? / 痛点与核心价值

When AI Coding Agents run kubectl get pods -o json, pytest -vv, docker logs, or large API queries, a single tool output can dump 20,000–80,000 tokens of repetitive boilerplate into the context window:

  • Naive truncation (head -n 50 / [:4000]) loses critical bugs: if record #289 out of 400 threw a DeadlockDetected HTTP 500, or line 733 of a 900-line log triggered an OutOfMemoryError, blind truncation silently deletes the root cause.

  • Uncompressed payloads burn tokens & degrade reasoning: flooding prompts with 397 identical status: 200 JSON objects or 50 recursive stack frames wastes money and causes "lost-in-the-middle" hallucinations.

nano-headroom solves both problems with Reversible CCR (Compress-Cache-Retrieve):

  1. Compress with Anomaly Pinning: Routes payloads to modality-specific crushers (SmartCrusher, LogCrusher, TracebackCrusher, TableCrusher) that infer schema/distributions and automatically pin 100% of errors, HTTP>=400 statuses, and statistical latency outliers while folding redundant items by 87%–98%.

  2. Cache Losslessly (ccr://<sha256>): Saves the bit-exact raw payload in a local SQLite WAL + zlib content-addressed vault—zero bytes are ever permanently lost.

  3. Retrieve Surgically On-Demand: Agents can query ccr://<hash> via CLI or MCP using json_path (items[137]), record slices (--slice 130:10), line spans (--lines 405:420), or in-vault regex grep without re-running slow commands.

传统截断式压缩会漏掉藏在第 289 条 JSON 记录里的 500 Deadlock 或第 733 行的 OOM 报错;而不压缩则会一轮吃光数万上下文 Token。nano-headroom 用零依赖纯 Python 标准库完整实现了 可逆 CCR(压缩-缓存-按需无损检索) 与 KV-Cache 前缀对齐器(CacheAligner),克隆即用,无需任何 API Key 或第三方依赖。


Related MCP server: mcp-token-optimizer

Architecture / 核心架构图

flowchart LR
    Input["Noisy Tool / CLI Output<br/>(JSON / Logs / Tracebacks / CSV)"] --> Router["ContentRouter<br/>(Deterministic Modality Detection)"]

    Router --> SC["SmartCrusher<br/>Schema + Stats + Anomaly Pinning"]
    Router --> LC["LogCrusher<br/>Drain Templates + 100% Error Windows"]
    Router --> TC["TracebackCrusher<br/>Cycle Folding + Root-Cause Dedup"]
    Router --> TBC["TableCrusher<br/>Column Ranges + Outlier Rows"]

    Input -. "zlib + SHA-256" .-> Vault[("SQLite WAL CCR Vault<br/>ccr://hash_id")]
    SC & LC & TC & TBC --> View["Compact CCR Context View<br/>(-87% to -98% Tokens)"]

    Agent["Coding Agent / CLI / MCP"] <-- "View + ccr:// Footer" --> View
    Agent -- "retrieve (json_path / slice / lines) & grep" --> Vault

Inspired By & Architecture Comparison / 致敬与架构对比

Inspired by: headroomlabs-ai/headroom (originally pioneered by chopratejas/headroom). Full credit to the Headroom authors for introducing the Compress-Cache-Retrieve (CCR), SmartCrusher, and CacheAligner concepts to AI context engineering.

nano-headroom is a clean-room, educational, local-first from-scratch Python stdlib implementation tailored for zero-dependency CLI command wrapping, MCP tool servers, and instant architectural study:

Dimension / 维度

headroomlabs-ai/headroom (Upstream)

nano-headroom (This Repo)

Positioning / 定位

Full-featured production LLM proxy, SDK & ML-assisted context optimization platform

Zero-dependency stdlib reproduction for local CLI wrapping, MCP & architectural study

Dependencies / 依赖体积

Multi-package Python ecosystem, HTTP proxy stack, optional ML/tokenizer models

0 external dependencies (json, sqlite3, zlib, re, csv, subprocess only)

JSON Compression

SmartCrusher for JSON arrays & nested structures

SmartCrusher with schema inference, status distributions, mean + 2.8σ outlier & status>=400 pinning

Logs & Stack Traces

Log/Code compressors + neural prose compression

Drain-style LogCrusher (100% severe window pinning) + TracebackCrusher (mutual recursion cycle & batch failure dedup)

Reversible CCR Store

Process/session hash store + proxy tool injection

Persistent SQLite WAL + zlib CAS vault supporting json_path, offset:limit, start:end lines & in-vault regex grep

KV-Cache Alignment

CacheAligner dynamic token isolation

CacheAligner extracting volatile ISO timestamps, UUIDs & request IDs into a deterministic tail

Integration / 接入方式

HTTP API Proxy (headroom proxy), SDK, MCP

Shell wrapper (nano-headroom exec -- <cmd>), Unix pipe filter, stdio MCP Server, & Agent Skill


Real Benchmark & Terminal Output / 真实终端运行实录

1. Multi-Modality CCR Benchmark (nano-headroom benchmark)

Tested offline across 4 realistic high-noise agent workloads containing hidden failure needles:

$ nano-headroom benchmark
=== nano-headroom Reversible Context Compression (CCR) Benchmark ===
| Workload                               | Modality  |  Raw Tok |  CCR Tok |  Savings | Needles | Lossless |
| -------------------------------------- | --------- | --------: | --------: | --------: | ------- | -------- |
| Cloud API JSON (400 pods, 3 anomalies) | json      |   20,877 |      771 |   -96.3% | PASS    | SHA-OK   |
| K8s Service Logs (900 lines, 2 errors) | log       |   48,453 |      807 |   -98.3% | PASS    | SHA-OK   |
| Pytest Recursive Tracebacks (6x cycles) | traceback |   10,100 |      302 |   -97.0% | PASS    | SHA-OK   |
| Telemetry CSV (300 rows, 2 spikes)     | csv       |    4,816 |      612 |   -87.3% | PASS    | SHA-OK   |
| -------------------------------------- | --------- | --------: | --------: | --------: | ------- | -------- |
| TOTAL / AGGREGATE                      | multi     |   84,246 |    2,492 |   -97.0% | 100%    | 100%     |

Summary: Saved 81,754 tokens (97.0% reduction) with 100% anomaly retention and bit-exact SHA-256 round-trip recovery.

2. Interactive SmartCrusher + Surgical CCR Retrieval (nano-headroom demo)

Notice how SmartCrusher compresses a 20,877-token (400-pod) JSON payload down to 749 tokens (-96.4%), automatically surfacing the exact 3 unhealthy pods (#137, #289, #341), and then retrieves items[137] or greps Deadlock|RateLimit directly from ccr://33edb9d39a51:

$ nano-headroom demo
=== nano-headroom v0.1.0 Interactive CCR Demo ===

[1] SmartCrusher on Cloud API JSON (400 pods, 3 anomalies):
### Envelope Metadata (other fields alongside `$.items`)
{
  "meta": {
    "cluster": "prod-alpha",
    "total": 400,
    "page": 1
  }
}

### JSON Envelope $.items Summary (400 total items -> 6 preserved, 394 folded)
#### Inferred Schema & Field Distributions
- `id` [str(400)/400]
- `service` [str(400)/400] — values: {checkout-worker:200, inventory-sync:200}
- `region` [str(400)/400] — values: {us-east-1:266, eu-central-1:134}
- `status` [int(400)/400] — dist: {200:397, 502:1, 500:1, 429:1}
- `latency_ms` [int(400)/400] — min=18, mean=46.01, max=4820
- `error` [null(397)|str(3)/400]

#### Stratified & Anomaly-Pinned Sample (3 total anomalies detected)
[
  {
    "__idx__": 0,
    "__sample__": "head",
    "id": "pod-0000",
    "service": "checkout-worker",
    "region": "eu-central-1",
    "status": 200,
    "latency_ms": 18,
    "error": null
  },
  {
    "__idx__": 137,
    "__sample__": "anomaly:status=502; error=UpstreamGatewayTimeout: payment-ledg; latency_ms=4820>outlier",
    "id": "pod-0137",
    "service": "inventory-sync",
    "region": "us-east-1",
    "status": 502,
    "latency_ms": 4820,
    "error": "UpstreamGatewayTimeout: payment-ledger-v2 timed out after 4800ms"
  },
  {
    "__idx__": 289,
    "__sample__": "anomaly:status=500; error=DeadlockDetected: lock wait timeout ",
    "id": "pod-0289",
    "service": "inventory-sync",
    "region": "us-east-1",
    "status": 500,
    "latency_ms": 910,
    "error": "DeadlockDetected: lock wait timeout exceeded on table orders"
  },
  ...
]

[CCR Vault ccr://33edb9d39a51 | modality=json | 20,877 -> 749 tok (-96.4%) | lossless on-demand: `nano-headroom retrieve --slice 0:20 33edb9d39a51 | grep 33edb9d39a51 <pattern>`]

[2] Surgical CCR JSON-Path Retrieval (`items[137]` from ccr://33edb9d39a51):
{
  "id": "pod-0137",
  "service": "inventory-sync",
  "region": "us-east-1",
  "status": 502,
  "latency_ms": 4820,
  "error": "UpstreamGatewayTimeout: payment-ledger-v2 timed out after 4800ms"
}

[4] CacheAligner KV-Cache Prefix Stabilization:
  Turn 1 static prefix hash : 4f76d9666d890e2a
  Turn 2 static prefix hash : 4f76d9666d890e2a (100% deterministic match: True)

30-Second Quickstart / 30 秒快速上手

Requires Python 3.10+ only (zero third-party dependencies, no API keys needed).

git clone https://github.com/nanyun818/nano-headroom.git
cd nano-headroom
pip install -e .

# 1. Run interactive demo & multi-modality benchmark immediately
nano-headroom demo
nano-headroom benchmark

Everyday CLI Workflows / 常用命令行用法

# Wrap any noisy CLI command and auto-compress stdout/stderr into CCR
nano-headroom exec -- pytest -vv
nano-headroom exec -- kubectl get pods -A -o json

# Pipe huge JSON / JSONL / logs / CSV from stdin
cat server.log | nano-headroom compress -

# Losslessly retrieve exact slices or JSON paths from local SQLite CCR vault
nano-headroom retrieve 33edb9d39a51 --json-path "items[137]"
nano-headroom retrieve 33edb9d39a51 --slice 130:10
nano-headroom retrieve 33edb9d39a51 --lines 405:425

# Regex search inside a cached raw payload without dumping all lines into context
nano-headroom grep 33edb9d39a51 "Deadlock|Timeout|ERROR"

# Stabilize system/tool prompts for 100% LLM KV-cache prefix hits
cat system_prompt.txt | nano-headroom align -

# Inspect cumulative token savings & prune old vault items
nano-headroom stats
nano-headroom stats --prune 100

MCP Server & Claude Code Skill Integration / MCP 与 Skill 接入

1. Plug into Claude Code / Cursor / Codex / Windsurf via MCP

nano-headroom includes a dual-framing (JSON-lines + Content-Length) Model Context Protocol (MCP) JSON-RPC 2.0 server over stdio:

{
  "mcpServers": {
    "nano-headroom": {
      "command": "nano-headroom-mcp",
      "args": ["--vault", ".headroom/vault.sqlite3"]
    }
  }
}

Exposed MCP Tools:

  • headroom_compress — Reversibly crush bloated JSON, JSONL, logs, tracebacks, CSV, or text into a ccr://<hash> summary.

  • headroom_retrieve — Losslessly restore full payloads, start_line..end_line, offset..limit record slices, or json_path expressions.

  • headroom_grep — Search inside a cached raw ccr://<hash> payload by regex/keyword.

  • headroom_align — Isolate volatile timestamps/UUIDs/trace IDs to preserve LLM KV-cache prefix hashes.

  • headroom_stats — Query cumulative token savings and vault metrics.

2. Claude Code / Agent Skill

Copy skills/nano-headroom/SKILL.md into .claude/skills/nano-headroom/SKILL.md (or .agents/skills/nano-headroom/SKILL.md) to teach coding agents to wrap high-output commands automatically.


Project Structure / 目录结构

nano-headroom/
├── pyproject.toml                  # Zero-dependency Python 3.10+ package manifest
├── skills/nano-headroom/SKILL.md   # Ready-to-use Agent Skill definition
├── src/nano_headroom/
│   ├── router.py                   # ContentRouter modality classifier (JSON/JSONL/Log/TB/CSV/Text)
│   ├── crushers.py                 # SmartCrusher, LogCrusher, TracebackCrusher, TableCrusher
│   ├── aligner.py                  # CacheAligner KV-cache prefix stabilizer
│   ├── store.py                    # SQLite WAL + zlib reversible CCR vault & JSONPath/grep engine
│   ├── engine.py                   # End-to-end CCR orchestrator, command wrapper & benchmark suite
│   ├── mcp_server.py               # Dual-framing stdio MCP JSON-RPC 2.0 server
│   └── cli.py                      # CLI entry point (`nano-headroom`)
└── tests/
    └── test_nano_headroom.py       # Automated unit & end-to-end MCP/CLI tests

License

MIT License — Copyright (c) 2026 nanyun818.

Available Tools

5 tools
headroom_alignA

Stabilize a prompt for LLM KV-cache prefix hits by isolating volatile timestamps, UUIDs, and request IDs into a deterministic trailing block.

Inputs: prompt (required).

headroom_compressB

Reversibly compress bloated JSON arrays, JSONL, terminal logs, stack traces, CSV, or prose using SmartCrusher/LogCrusher/TracebackCrusher and cache the exact raw payload in the CCR vault.

Inputs: content (required), force, source, modality.

headroom_grepB

Regex or keyword search inside a cached raw CCR payload without loading the full text.

Inputs: hash (required), pattern (required), max_matches, context_lines, +1 more.

headroom_retrieveA

Losslessly retrieve raw data from a ccr:// vault entry: full restoration, line-range slice (start_line/end_line), JSON record slice (offset/limit), or json_path.

Inputs: hash (required), limit, offset, end_line, +2 more.

headroom_statsA

Return cumulative token savings, modality compression ratios, and CCR vault size.

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.7/5.0

    Scored across 5 tools

    Disambiguation5/5

    Each tool targets a clearly distinct action: compress, retrieve, grep, align, and stats. The main potential overlap is retrieve vs. grep, but descriptions make it clear that retrieve fetches by ccr:// hash while grep searches inside cached payloads. No two tools appear interchangeable.

    Naming Consistency5/5

    All five tools follow a strict headroom_<verb> pattern: headroom_compress, headroom_retrieve, headroom_grep, headroom_align, headroom_stats. The convention is predictable and readable throughout.

    Tool Count5/5

    Five tools is well-scoped for a compression/caching server. Each tool earns its place by covering a distinct stage of the workflow: compress, inspect, retrieve, stabilize prompts, and report savings.

    Completeness4/5

    The core lifecycle is covered: compress into a vault, search cached payloads, retrieve full or partial data, and monitor savings. Minor gaps exist around explicitly listing or deleting/evicting vault entries, which agents may need for cache management.

    Maintenance

    ActivityMaintained
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      A
      quality
      C
      maintenance
      Provides reversible context compression for AI agents, reducing token usage while preserving the ability to retrieve original content, and serves as an MCP server for integration with tools like GitHub Copilot and Claude Code.
      3
      1
      Apache 2.0
    • F
      license
      Not graded
      quality
      Not graded
      maintenance
      Enables MCP-compatible clients and autonomous agents to dynamically compress long-horizon context by pruning verbose tool outputs, HTML boilerplate, and semantic redundancy by 40-70%. It reduces token burn and latency through deterministic, zero-dependency processing.
      -
    • A
      license
      A
      quality
      B
      maintenance
      Enables coding agents to compress JSON, CSV, and log output while preserving byte-exact originals for later slice or regex recall, and to run honesty checks and shortcut-debt audits through MCP tools over stdio JSON-RPC.
      4
      MIT