Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.
Python agentaianthropicclaude-codecompressioncontext-engineeringcontext-windowcursorfastapilangchainllmmcpopenaiprompt-engineeringproxypythonragtoken-optimizationtokenstypescript
fix(mcp): price headroom_read file content in tokens, not words (#3688)
sxh558b066b3d51
diff --git a/headroom/ccr/mcp_server.py b/headroom/ccr/mcp_server.pyindex 8294c0e21..f013e092e 100644--- a/headroom/ccr/mcp_server.py+++ b/headroom/ccr/mcp_server.py@@ -31,13 +31,16 @@ import osimport timefrom dataclasses import dataclass, fieldfrom pathlib import Path-from typing import Any+from typing import TYPE_CHECKING, Anyfrom headroom import paths as _pathsfrom headroom import savings_ledgerfrom headroom.cache.compression_store import format_retrieval_miss_detailfrom headroom.telemetry import session as telemetry_session+if TYPE_CHECKING:+ from headroom.tokenizers.estimator import EstimatingTokenCounter+# fcntl is Unix-only; on Windows we skip file locking (stats are best-effort).# Keep the module typed as Any so Windows mypy runs don't try to resolve Unix-only attrs.fcntl: Any = None@@ -377,6 +380,7 @@ class HeadroomMCPServer:self._http_client: httpx.AsyncClient | None = None # type: ignore[assignment]self._stats = SessionStats()self._local_store: Any = None # Lazy-initialized CompressionStore+ self._token_estimator: EstimatingTokenCounter | None = Noneself._compressor_initialized = False# File read cache: path → (content_hash, ccr_hash, line_count, token_count)self._file_cache: dict[str, tuple[str, str, int, int]] = {}@@ -401,6 +405,23 @@ class HeadroomMCPServer:self._local_store = get_compression_store()return self._local_store+ def _estimate_tokens(self, text: str) -> int:+ """Price file content in tokens, the way the rest of the pipeline does.++ Whitespace splitting is a word count, not a token count. Measured on+ real files it under-reports by 1.43x on prose, 1.30x on source, and+ 691x for the 2.2 KB single-line JSON array in the regression test -- a+ compact document has no spaces, so the whole file is one "word". That+ figure is stored as ``original_tokens`` (which the savings totals sum+ over) and echoed back to the agent as ``~N tokens`` in the+ already-in-context note it uses to decide whether to re-read the file.+ """+ if self._token_estimator is None:+ from headroom.tokenizers.estimator import EstimatingTokenCounter++ self._token_estimator = EstimatingTokenCounter()+ return max(1, self._token_estimator.count_text(text))+def _compress_content(self, content: str) -> dict[str, Any]:"""Compress content using Headroom's pipeline.@@ -1029,16 +1050,16 @@ class HeadroomMCPServer:# Fresh read: store in CCR and cache the hashstore = self._get_local_store()+ token_estimate = self._estimate_tokens(content)ccr_hash = store.store(original=content,compressed=f"[File: {path.name}, {line_count} lines]",- original_tokens=len(content.split()),+ original_tokens=token_estimate,compressed_tokens=5,tool_name="headroom_read",ttl=MCP_SESSION_TTL,)- token_estimate = len(content.split())self._file_cache[str_path] = (content_hash, ccr_hash, line_count, token_estimate)# Return full content with line numbers (like Claude Code's Read tool)diff --git a/tests/test_ccr_mcp_server.py b/tests/test_ccr_mcp_server.pyindex cf9fa1afd..cf54e174e 100644--- a/tests/test_ccr_mcp_server.py+++ b/tests/test_ccr_mcp_server.py@@ -11,6 +11,7 @@ from headroom.cache.compression_store import (get_compression_store,reset_compression_store,)+from headroom.tokenizers.estimator import EstimatingTokenCounterfrom tests._mcp_stub import import_module_with_mcp_stubmcp_server = import_module_with_mcp_stub("headroom.ccr.mcp_server")@@ -93,6 +94,50 @@ def test_compress_savings_percent_tracks_token_counts(fresh_store) -> None:assert result["savings_percent"] > 0.0+def _compact_json(tmp_path):+ """A single-line JSON file: one whitespace-separated word, thousands of tokens."""+ path = tmp_path / "payload.json"+ path.write_text(+ json.dumps(+ [{"id": i, "status": "ok", "kind": "run"} for i in range(60)],+ separators=(",", ":"),+ ),+ encoding="utf-8",+ )+ return path+++def test_read_tool_prices_files_in_tokens_not_words(fresh_store, tmp_path) -> None:+ """``headroom_read`` caches a token estimate and stores it as the entry's+ ``original_tokens``. It used to be ``len(content.split())`` — a word count+ in a token field, which is 1 for a single-line JSON document that is+ thousands of tokens long."""+ path = _compact_json(tmp_path)+ content = path.read_text(encoding="utf-8")+ server = mcp_server.HeadroomMCPServer(check_proxy=False)++ asyncio.run(server._handle_read({"file_path": str(path), "fresh": True}))++ estimated = next(iter(server._file_cache.values()))[3]+ assert estimated == EstimatingTokenCounter().count_text(content)+ assert estimated > len(content.split())+++def test_read_tool_cache_note_reports_tokens(fresh_store, tmp_path) -> None:+ """The 'already in your context' note is read by the agent to decide whether+ to re-read the file, so its ``~N tokens`` figure has to be a token count."""+ path = _compact_json(tmp_path)+ content = path.read_text(encoding="utf-8")+ server = mcp_server.HeadroomMCPServer(check_proxy=False)++ asyncio.run(server._handle_read({"file_path": str(path)}))+ response = asyncio.run(server._handle_read({"file_path": str(path)}))+ payload = json.loads(response[0].kwargs["text"])++ assert payload["status"] == "cached"+ assert f"~{EstimatingTokenCounter().count_text(content)} tokens" in payload["note"]++def test_mcp_compress_surfaces_unreachable_proxy(fresh_store) -> None:server = mcp_server.HeadroomMCPServer(proxy_url="http://127.0.0.1:9",