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): accept the JSONC opencode config that wrap and install already accept (#4297)

Rudy Mizrahi Celekli9202948c1e57
diff --git a/headroom/mcp_registry/opencode.py b/headroom/mcp_registry/opencode.py
index 7448fb271..1b120f958 100644
--- a/headroom/mcp_registry/opencode.py
+++ b/headroom/mcp_registry/opencode.py
@@ -9,7 +9,6 @@ from __future__ import annotations
import json
import logging
-import re
import shutil
from pathlib import Path
from typing import Any
@@ -29,25 +28,32 @@ from .base import (
logger = logging.getLogger(__name__)
-def _strip_json_line_comments(text: str) -> str:
- """Strip ``//`` line comments from JSONC text.
+def _parse_json_loose(raw: str) -> dict[str, Any] | None:
+ """Parse JSON or JSONC text, returning ``None`` if it can't be parsed as an object.
- Tries standard JSON first (via the caller) so URLs containing ``//`` are
- never mangled; this is only invoked as a fallback once plain
- ``json.loads`` has already failed. Two-pass: (1) remove comment-only
- lines, (2) strip inline trailing comments that follow a comma.
+ Standard JSON is tried first so URLs containing ``//`` are never touched.
+ The JSONC fallback reuses the OpenCode provider's string-aware stripping
+ of ``//`` and ``/* */`` comments and trailing commas, so this accepts the
+ same files ``headroom wrap``/``install`` already edit.
"""
- cleaned = re.sub(r"^\s*//[^\n]*\n", "", text, flags=re.MULTILINE)
- return re.sub(r",\s*//[^\n]*", ",", cleaned)
-
-
-def _parse_json_loose(raw: str) -> dict[str, Any] | None:
- """Parse JSON or JSONC text, returning ``None`` if it can't be parsed as an object."""
try:
data = json.loads(raw)
except json.JSONDecodeError:
+ # Imported here: headroom.providers.opencode imports this package.
+ from headroom.providers.opencode.config import (
+ _strip_jsonc_comments,
+ _strip_jsonc_trailing_commas,
+ )
+
+ # The stripper treats an unterminated ``/*`` as running to EOF. That is
+ # malformed input, and accepting what precedes it would let the write
+ # path drop the rest of the file. A ``*/`` appended after a newline
+ # survives stripping unless it closes such a comment.
+ if not _strip_jsonc_comments(raw + "\n*/").endswith("*/"):
+ return None
+ cleaned = _strip_jsonc_trailing_commas(_strip_jsonc_comments(raw))
try:
- data = json.loads(_strip_json_line_comments(raw))
+ data = json.loads(cleaned)
except json.JSONDecodeError:
return None
return data if isinstance(data, dict) else None
@@ -82,8 +88,8 @@ def _read_json_for_write(path: Path) -> dict[str, Any]:
"""Read a JSON/JSONC object for a subsequent full-file rewrite.
Returns ``{}`` only when the file is absent or empty (safe to start fresh).
- ``//`` line comments are stripped before parsing, matching the loose JSONC
- handling used by the OpenCode provider-block writer — note the rewritten
+ JSONC comments and trailing commas are stripped before parsing, matching
+ the loose JSONC handling used by the OpenCode provider-block writer — note the rewritten
file loses any comments it had. If the file exists with content but still
does not parse as a JSON object, raise :class:`_MalformedConfigError` so
the caller aborts instead of overwriting unrelated user config — the
diff --git a/tests/test_mcp_registry_opencode.py b/tests/test_mcp_registry_opencode.py
index 004aea04b..05d0a5526 100644
--- a/tests/test_mcp_registry_opencode.py
+++ b/tests/test_mcp_registry_opencode.py
@@ -81,6 +81,35 @@ def test_register_server_merges_into_commented_jsonc(
assert data["mcp"]["headroom"]["command"] == ["headroom", "mcp"]
+ "contents",
+ [
+ # trailing comment on the last key (no comma before the //)
+ '{\n "theme": "dracula",\n "model": "anthropic/claude-sonnet-4" // default model\n}\n',
+ # block comment
+ '{\n /* user settings */\n "theme": "dracula",\n "model": "anthropic/claude-sonnet-4"\n}\n',
+ # trailing comma, which JSONC allows
+ '{\n "theme": "dracula",\n "model": "anthropic/claude-sonnet-4",\n}\n',
+ ],
+ ids=["trailing-line-comment", "block-comment", "trailing-comma"],
+)
+def test_register_server_accepts_other_jsonc_syntax(tmp_path: Path, contents: str) -> None:
+ """Every JSONC form OpenCode itself reads must merge, not fail as "not valid JSON"."""
+ config_path = tmp_path / "opencode.jsonc"
+ config_path.write_text(contents, encoding="utf-8")
+ registrar = OpencodeRegistrar(config_path=config_path)
+
+ spec = ServerSpec(name="headroom", command="headroom", args=("mcp",), env={})
+ result = registrar.register_server(spec)
+
+ assert result.status == RegisterStatus.REGISTERED, result.detail
+ data = json.loads(config_path.read_text(encoding="utf-8"))
+ assert data["theme"] == "dracula"
+ assert data["model"] == "anthropic/claude-sonnet-4"
+ assert data["mcp"]["headroom"]["command"] == ["headroom", "mcp"]
+ assert registrar.get_server("headroom") is not None
+
+
def test_detect_when_binary_present(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
"""Detection succeeds when the opencode binary is in PATH."""
monkeypatch.setenv("PATH", str(tmp_path))
@@ -150,7 +179,17 @@ def test_register_server_creates_config_when_missing(tmp_path: Path) -> None:
}
[email protected]("contents", ["not json", "{", '{"theme": }', "[]"])
+ "contents",
+ [
+ "not json",
+ "{",
+ '{"theme": }',
+ "[]",
+ # An unterminated block comment must not be read as "comment to EOF".
+ '{"theme": "dark"}\n/* unfinished notes\n"keep": "me"\n',
+ ],
+)
def test_register_server_preserves_malformed_config(tmp_path: Path, contents: str) -> None:
"""Registering must NOT clobber an existing but unparseable opencode.json.