Skip to content

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.

fix(mcp/claude): don't clobber an unparseable Claude config on register (#1660)

Abhay Singhbc24e258b11f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4b4765c38..e6589a60d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -168,6 +168,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
* **cli/proxy:** honor `HEADROOM_MIN_TOKENS=0` / `HEADROOM_MAX_ITEMS=0`. The Click `proxy` command built these with `_get_env_int_optional(name) or 500`/`or 50`, so an explicit `0` — a legitimate value (`min_tokens_to_crush=0` means "crush every item") — was treated as falsy and silently replaced with the default. The `headroom proxy` argparse path already preserved `0` via `_get_env_int`, so the two entry points disagreed. The Click path now uses the same None-checking helper.
* **proxy:** strip the inbound `Content-Encoding`/`Transfer-Encoding` request headers on the Anthropic `/v1/messages` and OpenAI `/v1/chat/completions` paths before forwarding upstream. `read_request_json_with_bytes` already decompresses the inbound body (zstd/gzip/deflate/br), so the bytes forwarded upstream are plain JSON — but these two handlers left the original `content-encoding` header in place, so a client (or an edge proxy like a Cloudflare Worker) that sent a compressed body got its request rejected with upstream HTTP 400 because the provider tried to decompress already-decoded JSON. The `/v1/responses` handler already carried this fix (#1542); it is now applied to the messages and chat paths too.
* **models:** fix the model registry's prefix fallback silently returning the wrong context window. `ModelRegistry.get` accepted any registered name as a `str.startswith` prefix and returned the *first* match, so `gpt-4-32k-0613` resolved to `gpt-4` (8192) instead of `gpt-4-32k` (32768), and unregistered ids like `gpt-4.1`/`gpt-4.5` inherited `gpt-4`'s 8192-token window — making the proxy think a nearly-empty context was almost full and compress far too aggressively. The fallback now requires the registered name to end at a version boundary in the query (so `gpt-4.1` no longer matches `gpt-4`) and picks the longest qualifying name (so `gpt-4-32k-0613` → `gpt-4-32k`).
+* **mcp/claude:** stop the file-based MCP registrar from destroying an existing but unparseable Claude config. When the `claude` CLI is unavailable, `_register_via_file` read `~/.claude/.claude.json` via a helper that returns `{}` on `JSONDecodeError`, then rewrote the whole file with only `{"mcpServers": {...}}` — wiping unrelated Claude state (`projects`, `oauthAccount`, session history) if the file was momentarily corrupt or hand-edited. The write path now refuses to overwrite a present-but-invalid config and returns a `FAILED` result with an actionable message; an absent or empty file still registers fresh, and a valid file still merges with all other keys preserved.
* **install:** stop `resolve_targets` from rejecting valid `--providers all`/`auto` installs under provider scope. The provider-scope "unsupported targets" validation ran before the mode dispatch, so `headroom install apply --scope provider --providers all --target cursor` raised `ClickException` even though `all`/`auto` ignore the requested target list entirely (user scope silently ignores the same input). The check now runs only on the manual path that actually consults the requested list.
* **mcp/opencode:** stop the OpenCode MCP registrar from destroying an existing but unparseable `opencode.json`. `_write_entry` read the config via a helper that returns `{}` on `JSONDecodeError`, then rewrote the whole file with only `{"mcp": {...}}` — wiping the user's `theme`/`model`/`provider` and any other MCP servers (OpenCode configs are commonly JSONC / hand-edited). The write path now refuses to overwrite a present-but-invalid config and returns a `FAILED` result; absent/empty files still register fresh and valid files still merge with all other keys preserved. (Same class of fix as the Claude registrar.)
* **proxy:** include the system prompt, tools, and the response-shaping request fields in the SemanticCache key. `_compute_key` hashed only `{model, messages}`, so two non-streaming requests with identical messages but a different top-level `system` prompt, tool set, sampling config, or output-shaping field collided on one key and the second caller was served the first's cached response — generated under different request semantics, in the default config (`cache_enabled` defaults on). The key now folds the request fields that shape generation — `temperature`/`top_p`/`top_k`/`max_tokens`/`stop`, plus OpenAI `tool_choice`/`response_format`/`parallel_tool_calls`/`seed`/`presence_penalty`/`frequency_penalty`/`logit_bias`/`n`/`logprobs`/`top_logprobs`/`reasoning_effort`/`verbosity`/`modalities` and Anthropic `thinking`/`tool_choice`/`output_config` — canonicalizing `system`/`tools` so a moved `cache_control` breakpoint does not fragment it, and the handlers snapshot the fields once at the cache read and reuse them at write so a body mutated by the pipeline cannot diverge the key. Non-streaming path only.
diff --git a/headroom/mcp_registry/claude.py b/headroom/mcp_registry/claude.py
index b27823887..7acbc02fb 100644
--- a/headroom/mcp_registry/claude.py
+++ b/headroom/mcp_registry/claude.py
@@ -164,12 +164,20 @@ class ClaudeRegistrar(MCPRegistrar):
try:
target.parent.mkdir(parents=True, exist_ok=True)
- config = _read_json(target)
+ config = _read_json_for_write(target)
servers = config.get("mcpServers")
if not isinstance(servers, dict):
config["mcpServers"] = servers = {}
servers[spec.name] = _spec_to_entry(spec)
_write_json(target, config)
+ except _MalformedConfigError as exc:
+ # Refuse to overwrite: the file holds unrelated Claude state
+ # (projects, oauthAccount, history) that a blind rewrite would wipe.
+ return RegisterResult(
+ RegisterStatus.FAILED,
+ f"{target} exists but is not valid JSON ({exc}); refusing to overwrite. "
+ "Fix or remove the file, then re-run.",
+ )
except OSError as exc:
return RegisterResult(RegisterStatus.FAILED, f"could not write {target}: {exc}")
return RegisterResult(RegisterStatus.REGISTERED, f"wrote to {target}")
@@ -242,7 +250,13 @@ def _resolve_claude_config_dir(
def _read_json(path: Path) -> dict[str, Any]:
- """Read a JSON file, returning empty dict if absent or unparseable."""
+ """Read a JSON file, returning empty dict if absent or unparseable.
+
+ Safe for READ-ONLY callers. Do NOT use before a full-file rewrite: an
+ unparseable existing file returns ``{}`` here, and writing that back would
+ destroy the user's other config. Use :func:`_read_json_for_write` on the
+ write path instead.
+ """
if not path.exists():
return {}
try:
@@ -255,6 +269,37 @@ def _read_json(path: Path) -> dict[str, Any]:
return data
+class _MalformedConfigError(Exception):
+ """The target config file exists but is not a parseable JSON object.
+
+ Raised on the write path so we refuse to clobber a file we can't safely
+ merge into, rather than silently overwriting the user's state.
+ """
+
+
+def _read_json_for_write(path: Path) -> dict[str, Any]:
+ """Read a JSON object for a subsequent full-file rewrite.
+
+ Returns ``{}`` only when the file is absent or empty (safe to start fresh).
+ If the file exists with content but does not parse as a JSON object, raise
+ :class:`_MalformedConfigError` so the caller aborts instead of overwriting
+ unrelated user config (e.g. ``~/.claude/.claude.json`` holds ``projects``,
+ ``oauthAccount``, and session history alongside ``mcpServers``).
+ """
+ if not path.exists():
+ return {}
+ raw = path.read_text(encoding="utf-8") # OSError propagates to the caller
+ if not raw.strip():
+ return {}
+ try:
+ data = json.loads(raw)
+ except json.JSONDecodeError as exc:
+ raise _MalformedConfigError(str(exc)) from exc
+ if not isinstance(data, dict):
+ raise _MalformedConfigError("top-level JSON is not an object")
+ return data
+
+
def _write_json(path: Path, data: dict[str, Any]) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
with open(path, "w", encoding="utf-8") as f:
diff --git a/tests/test_mcp_registry/test_claude_registrar.py b/tests/test_mcp_registry/test_claude_registrar.py
index f64fc87d8..3601b3318 100644
--- a/tests/test_mcp_registry/test_claude_registrar.py
+++ b/tests/test_mcp_registry/test_claude_registrar.py
@@ -471,3 +471,41 @@ def test_register_robust_to_non_dict_mcp_servers(tmp_path: Path, mcp_servers: st
assert result.status == RegisterStatus.REGISTERED
data = json.loads(cfg.read_text())
assert data["mcpServers"]["headroom"]["command"] == _RESOLVED_COMMAND[0]
+
+
[email protected]("contents", ["not json", "{", '{"projects": }', "[]"])
+def test_register_via_file_preserves_malformed_config(tmp_path: Path, contents: str) -> None:
+ """Registering must NOT clobber an existing but unparseable config.
+
+ ~/.claude.json holds unrelated Claude state (projects, oauthAccount,
+ session history). Before the fix a malformed file was read as {} and then
+ overwritten with only {"mcpServers": ...}, destroying everything else."""
+ cfg = tmp_path / ".claude.json"
+ cfg.write_text(contents, encoding="utf-8")
+ reg = _make_registrar(tmp_path, cli=None)
+
+ result = reg.register_server(_spec())
+
+ assert result.status == RegisterStatus.FAILED
+ assert "not valid JSON" in result.detail
+ # The original bytes are untouched — nothing was overwritten.
+ assert cfg.read_text(encoding="utf-8") == contents
+
+
+def test_register_via_file_merges_into_existing_valid_config(tmp_path: Path) -> None:
+ """The happy path still merges: unrelated keys are preserved and mcpServers
+ gains the headroom entry."""
+ cfg = tmp_path / ".claude.json"
+ cfg.write_text(
+ json.dumps({"projects": {"/x": {"y": 1}}, "oauthAccount": {"id": "abc"}}),
+ encoding="utf-8",
+ )
+ reg = _make_registrar(tmp_path, cli=None)
+
+ result = reg.register_server(_spec())
+
+ assert result.status == RegisterStatus.REGISTERED
+ data = json.loads(cfg.read_text(encoding="utf-8"))
+ assert data["projects"] == {"/x": {"y": 1}}
+ assert data["oauthAccount"] == {"id": "abc"}
+ assert "headroom" in data["mcpServers"]