fix(mcp): resolve opencode.jsonc for MCP registration (#2496)

## Description
`headroom wrap opencode` shows no headroom models and 0 savings on
setups where OpenCode's config lives in `opencode.jsonc` instead of
`opencode.json`. This is because `OpencodeRegistrar` (which writes the
`mcp.headroom` block) had its own config-path resolver that always
targets `opencode.json`, while the provider-block writer
(`providers/opencode/config.py`) already correctly prefers an existing
`opencode.jsonc`. On `.jsonc` setups this split the provider block and
the MCP registration block across two different files, and OpenCode only
reads one of them.

## Type of Change
- [x] Bug fix

## Changes Made
- `headroom/install/paths.py`: `opencode_config_path()` now also honors
`OPENCODE_HOME` for the base directory (matching the two duplicated
resolvers it replaces), in addition to its existing `OPENCODE_CONFIG`
and `.jsonc`-over-`.json` preference.
- `headroom/mcp_registry/opencode.py`: removed the local
`_opencode_config_path()`/`_opencode_home_dir()` resolvers;
`OpencodeRegistrar` now uses the shared
`install.paths.opencode_config_path()`, so it resolves to the same file
as the provider-block writer. Updated stale docstrings/error text that
assumed `opencode.json` was the only possible file.
- Added regression tests in `tests/test_install/test_paths.py`
(OPENCODE_HOME handling) and `tests/test_mcp_registry_opencode.py`
(registrar resolves `opencode.jsonc` when present, with no explicit
`config_path`).

## Testing
- [x] Added/updated tests
- [x] Ran full local test suite

```
$ python -m pytest tests/test_mcp_registry_opencode.py tests/test_install/test_paths.py tests/test_providers_opencode_config.py tests/test_providers_opencode_install.py -q
...
tests\test_mcp_registry_opencode.py .......................................... [ 43%]
tests\test_install\test_paths.py .....                                        [ 49%]
tests\test_providers_opencode_config.py ................................F.... [ 94%]
tests\test_providers_opencode_install.py .....                                [100%]
1 failed, 90 passed in 8.44s
```
The one failure (`test_build_launch_env_with_project`) is a pre-existing
Windows path-escaping assertion unrelated to this change — confirmed it
fails identically on `main` before this patch.

```
$ ruff check .
All checks passed!
$ ruff format --check .
1334 files already formatted
$ mypy headroom --ignore-missing-imports
Success: no issues found in ... source files
```

## Real Behavior Proof
- Environment: Windows 11, Python 3.13.11, local checkout of
headroomlabs-ai/headroom
- Exact command / steps: Set `OPENCODE_HOME` to a temp dir containing
only `opencode.jsonc`; construct `OpencodeRegistrar()` with no explicit
`config_path` (see new test
`test_default_config_path_prefers_existing_jsonc`); previously this
resolved to a stray `opencode.json` in the same directory, now it
resolves to the existing `opencode.jsonc`.
- Observed result: `registrar._config_path == tmp_path /
"opencode.jsonc"` (test passes); before the fix it asserted
`opencode.json` and would have registered the MCP server in the wrong
file.
- Not tested: did not manually exercise the full `headroom wrap
opencode` CLI flow end-to-end against a real OpenCode installation.

## Review Readiness
- [x] I have performed a self-review
- [x] This PR is ready for human review

Fixes #1869

---------

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
Parideboy
2026-10-01 00:16:24 -05:00
committed by GitHub
co-authored by Claude Sonnet 5
parent 9b26a49c14
commit f824a270f1
4 changed files with 125 additions and 39 deletions
+4 -2
View File
@@ -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():
+44 -36
View File
@@ -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):
raw = path.read_text(encoding="utf-8")
except OSError:
return {}
if not isinstance(data, dict):
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}); "
+22
View File
@@ -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
+55 -1
View File
@@ -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))