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): resolve opencode.jsonc for MCP registration (#2496)

Parideboyf824a270f132
diff --git a/headroom/install/paths.py b/headroom/install/paths.py
index 6a4e7b8de..ab536da97 100644
--- a/headroom/install/paths.py
+++ b/headroom/install/paths.py
@@ -156,14 +156,16 @@ def opencode_config_path() -> Path:
"""Return the OpenCode config path.
Resolves ``~/.config/opencode/opencode.json`` when ``OPENCODE_CONFIG``
- is unset; otherwise the value of that environment variable. Checks for
+ is unset; otherwise the value of that environment variable. Honors
+ ``OPENCODE_HOME`` for the base directory, and checks for
``opencode.jsonc`` as well.
"""
env_path = os.environ.get("OPENCODE_CONFIG", "").strip()
if env_path:
return Path(env_path).expanduser()
- base_dir = Path.home() / ".config" / "opencode"
+ home_path = os.environ.get("OPENCODE_HOME", "").strip()
+ base_dir = Path(home_path).expanduser() if home_path else Path.home() / ".config" / "opencode"
jsonc_path = base_dir / "opencode.jsonc"
if jsonc_path.exists():
diff --git a/headroom/mcp_registry/opencode.py b/headroom/mcp_registry/opencode.py
index 7a71a1c98..1b0928d62 100644
--- a/headroom/mcp_registry/opencode.py
+++ b/headroom/mcp_registry/opencode.py
@@ -1,41 +1,52 @@
"""OpenCode MCP registrar.
-OpenCode stores MCP server configuration in ``~/.config/opencode/opencode.json``
-under the top-level ``mcp`` key. This registrar edits that JSON file directly.
+OpenCode stores MCP server configuration under ``~/.config/opencode/opencode.json``
+(or ``opencode.jsonc``, if present) under the top-level ``mcp`` key. This registrar
+edits that JSON file directly.
"""
from __future__ import annotations
import json
import logging
-import os
+import re
import shutil
from pathlib import Path
from typing import Any
+from headroom.install.paths import opencode_config_path
+
from .base import MCPRegistrar, RegisterResult, RegisterStatus, ServerSpec
logger = logging.getLogger(__name__)
-def _opencode_home_dir() -> Path:
- """Return the OpenCode home/config directory."""
- env_path = os.environ.get("OPENCODE_HOME", "").strip()
- if env_path:
- return Path(env_path).expanduser()
- return Path.home() / ".config" / "opencode"
+def _strip_json_line_comments(text: str) -> str:
+ """Strip ``//`` line comments from JSONC text.
+ 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.
+ """
+ cleaned = re.sub(r"^\s*//[^\n]*\n", "", text, flags=re.MULTILINE)
+ return re.sub(r",\s*//[^\n]*", ",", cleaned)
-def _opencode_config_path() -> Path:
- """Return the active OpenCode config path."""
- env_path = os.environ.get("OPENCODE_CONFIG", "").strip()
- if env_path:
- return Path(env_path).expanduser()
- return _opencode_home_dir() / "opencode.json"
+
+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:
+ try:
+ data = json.loads(_strip_json_line_comments(raw))
+ except json.JSONDecodeError:
+ return None
+ return data if isinstance(data, dict) else None
def _read_json(path: Path) -> dict[str, Any]:
- """Read a JSON file, returning empty dict if absent or unparseable.
+ """Read a JSON/JSONC file, returning empty dict if absent or unparseable.
Safe for READ-ONLY callers only. Do NOT use before a full-file rewrite:
an unparseable existing file returns ``{}`` here, and writing that back
@@ -45,13 +56,10 @@ def _read_json(path: Path) -> dict[str, Any]:
if not path.exists():
return {}
try:
- with open(path, encoding="utf-8") as f:
- data = json.load(f)
- except (OSError, json.JSONDecodeError):
- return {}
- if not isinstance(data, dict):
+ raw = path.read_text(encoding="utf-8")
+ except OSError:
return {}
- return data
+ return _parse_json_loose(raw) or {}
class _MalformedConfigError(Exception):
@@ -63,25 +71,25 @@ class _MalformedConfigError(Exception):
def _read_json_for_write(path: Path) -> dict[str, Any]:
- """Read a JSON object for a subsequent full-file rewrite.
+ """Read a JSON/JSONC 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 — ``opencode.json`` holds ``theme``/``model``/
- ``provider``/other MCP servers alongside the ``mcp`` block.
+ ``//`` line comments 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
+ OpenCode config file holds ``theme``/``model``/``provider``/other MCP
+ servers alongside the ``mcp`` block.
"""
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")
+ data = _parse_json_loose(raw)
+ if data is None:
+ raise _MalformedConfigError("not valid JSON/JSONC")
return data
@@ -147,7 +155,7 @@ class OpencodeRegistrar(MCPRegistrar):
display_name = "OpenCode"
def __init__(self, *, config_path: Path | None = None) -> None:
- self._config_path = config_path or _opencode_config_path()
+ self._config_path = config_path or opencode_config_path()
def detect(self) -> bool:
if shutil.which("opencode"):
@@ -209,8 +217,8 @@ class OpencodeRegistrar(MCPRegistrar):
mcp[spec.name] = _spec_to_entry(spec)
_write_json(self._config_path, data)
except _MalformedConfigError as exc:
- # Refuse to overwrite: opencode.json holds theme/model/provider and
- # other MCP servers that a blind rewrite would wipe.
+ # Refuse to overwrite: the config file holds theme/model/provider
+ # and other MCP servers that a blind rewrite would wipe.
return RegisterResult(
RegisterStatus.FAILED,
f"{self._config_path} exists but is not valid JSON ({exc}); "
diff --git a/tests/test_install/test_paths.py b/tests/test_install/test_paths.py
index 8c0e935ce..2ddefbdd8 100644
--- a/tests/test_install/test_paths.py
+++ b/tests/test_install/test_paths.py
@@ -69,3 +69,25 @@ def test_env_target_and_config_paths(monkeypatch, tmp_path: Path) -> None:
assert (
install_paths.opencode_config_path() == tmp_path / ".config" / "opencode" / "opencode.json"
)
+
+
+def test_opencode_config_path_honors_opencode_home(monkeypatch, tmp_path: Path) -> None:
+ monkeypatch.setattr(Path, "home", lambda: tmp_path / "unused")
+ other_home = tmp_path / "custom-opencode-home"
+ other_home.mkdir()
+ monkeypatch.setenv("OPENCODE_HOME", str(other_home))
+
+ assert install_paths.opencode_config_path() == other_home / "opencode.json"
+
+ (other_home / "opencode.jsonc").write_text("{}", encoding="utf-8")
+ assert install_paths.opencode_config_path() == other_home / "opencode.jsonc"
+
+
+def test_opencode_config_path_opencode_config_env_wins_over_home(
+ monkeypatch, tmp_path: Path
+) -> None:
+ monkeypatch.setenv("OPENCODE_HOME", str(tmp_path / "home"))
+ explicit = tmp_path / "explicit.json"
+ monkeypatch.setenv("OPENCODE_CONFIG", str(explicit))
+
+ assert install_paths.opencode_config_path() == explicit
diff --git a/tests/test_mcp_registry_opencode.py b/tests/test_mcp_registry_opencode.py
index 34ea814ba..766a5ebd2 100644
--- a/tests/test_mcp_registry_opencode.py
+++ b/tests/test_mcp_registry_opencode.py
@@ -8,7 +8,7 @@ from typing import Any
import pytest
-from headroom.mcp_registry.base import RegisterStatus
+from headroom.mcp_registry.base import RegisterStatus, ServerSpec
from headroom.mcp_registry.opencode import (
OpencodeRegistrar,
_diff_specs,
@@ -27,6 +27,60 @@ def _registrar(tmp_path: Path) -> OpencodeRegistrar:
return OpencodeRegistrar(config_path=tmp_path / "opencode.json")
+def test_default_config_path_prefers_existing_jsonc(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Regression test for #1869: MCP registration must land in opencode.jsonc
+
+ when that's the file OpenCode actually reads, matching the provider-block
+ resolution in headroom.providers.opencode.config.
+ """
+ monkeypatch.delenv("OPENCODE_CONFIG", raising=False)
+ monkeypatch.setenv("OPENCODE_HOME", str(tmp_path))
+ (tmp_path / "opencode.jsonc").write_text("{}", encoding="utf-8")
+
+ registrar = OpencodeRegistrar()
+
+ assert registrar._config_path == tmp_path / "opencode.jsonc"
+
+
+def test_register_server_merges_into_commented_jsonc(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Regression test for #1869 review feedback: real-world opencode.jsonc files
+
+ commonly contain ``//`` comments. register_server() must parse past them
+ and merge the mcp block in without dropping the user's existing settings,
+ instead of failing with "not valid JSON".
+ """
+ monkeypatch.delenv("OPENCODE_CONFIG", raising=False)
+ monkeypatch.setenv("OPENCODE_HOME", str(tmp_path))
+ config_path = tmp_path / "opencode.jsonc"
+ config_path.write_text(
+ """{
+ // user's theme preference
+ "theme": "dracula",
+ "model": "anthropic/claude-sonnet-4",
+ "provider": {
+ "anthropic": {"options": {"baseURL": "https://api.example.com"}}
+ }
+}
+""",
+ encoding="utf-8",
+ )
+
+ registrar = OpencodeRegistrar()
+ spec = ServerSpec(name="headroom", command="headroom", args=("mcp",), env={})
+ result = registrar.register_server(spec)
+
+ assert result.status == RegisterStatus.REGISTERED
+ data = json.loads(config_path.read_text(encoding="utf-8"))
+ assert data["theme"] == "dracula"
+ assert data["model"] == "anthropic/claude-sonnet-4"
+ assert data["provider"]["anthropic"]["options"]["baseURL"] == "https://api.example.com"
+ assert data["mcp"]["headroom"]["command"] == ["headroom", "mcp"]
+
+
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))