fix(mcp): accept the JSONC opencode config that wrap and install already accept (#4297)

## Description

`headroom mcp install` registers the Headroom MCP server in OpenCode's
`opencode.json` / `opencode.jsonc`. Its registrar
(`headroom/mcp_registry/opencode.py`) has its own JSONC fallback, which
strips only two comment shapes:

```python
cleaned = re.sub(r"^\s*//[^\n]*\n", "", text, flags=re.MULTILINE)   # whole-line // comments
return re.sub(r",\s*//[^\n]*", ",", cleaned)                        # comments right after a comma
```

Any other JSONC that OpenCode itself accepts fails to parse, and since
#1661 the registrar (correctly) refuses to overwrite a file it can't
parse. So with

- a trailing `// comment` on the **last** key (no comma before it),
- a `/* block */` comment,
- a trailing comma,

`headroom mcp install` stops with `opencode.jsonc exists but is not
valid JSON (not valid JSON/JSONC); refusing to overwrite. Fix or remove
the file`, and the MCP server isn't installed. That's a normal
hand-edited `opencode.jsonc`. Meanwhile
`headroom/providers/opencode/config.py` (used by `headroom wrap
opencode` and `install`) already parses these files with a string-aware
stripper, so one command accepts the user's config and the other rejects
it.

Closes: N/A (no matching issue found)

## Type of Change

- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Performance improvement
- [ ] Code refactoring (no functional changes)

## Changes Made

- `headroom/mcp_registry/opencode.py`: `_parse_json_loose()` keeps its
contract: standard JSON first, `None` for anything that still isn't a
JSON object, so `_read_json_for_write` still refuses to clobber a
malformed file. The fallback now runs the provider module's
`_strip_jsonc_comments` + `_strip_jsonc_trailing_commas`, which handle
`//` and `/* */` comments and trailing commas without touching string
contents such as `https://` URLs. The import is inside the function
because `headroom.providers.opencode` imports `headroom.mcp_registry` at
package load, and a module-level import is circular. The now-unused
`_strip_json_line_comments` and `import re` are removed. Because that
stripper treats an unterminated `/*` as running to end of file, the
registrar first checks for one and returns `None`, so such a file is
still refused instead of being rewritten without its tail (added after
review).
- `tests/test_mcp_registry_opencode.py`:
`test_register_server_accepts_other_jsonc_syntax`, parametrized over a
trailing line comment, a block comment and a trailing comma, checks
`register_server()` returns `REGISTERED`, merges the `mcp` block, and
keeps `theme`/`model`. `test_register_server_preserves_malformed_config`
gains an unterminated-`/*` case; it and the existing cases (`not json`,
`{`, `{"theme": }`, `[]`) fail closed and leave the file byte-identical.

## Testing

- [x] Unit tests pass (`pytest`): `tests/test_mcp_registry_opencode.py`,
`tests/test_mcp_registry/`, `tests/test_providers_opencode_config.py`,
`tests/test_cli/test_wrap_opencode.py`, not the full suite
- [x] Linting passes (`ruff check .`): on the changed files
- [ ] Type checking passes (`mypy headroom`): not run
- [x] New tests added for new functionality
- [x] Manual testing performed

### Test Output

New test on `main` (fix reverted, test kept):

```text
$ python -m pytest tests/test_mcp_registry_opencode.py -q
E   AssertionError: .../opencode.jsonc exists but is not valid JSON (not valid JSON/JSONC); refusing to overwrite. Fix or remove the file, then re-run.
E   assert <RegisterStat...LED: 'failed'> == <RegisterStat... 'registered'>
FAILED tests/test_mcp_registry_opencode.py::test_register_server_accepts_other_jsonc_syntax[trailing-line-comment]
FAILED tests/test_mcp_registry_opencode.py::test_register_server_accepts_other_jsonc_syntax[block-comment]
FAILED tests/test_mcp_registry_opencode.py::test_register_server_accepts_other_jsonc_syntax[trailing-comma]
========================= 3 failed, 42 passed in 1.77s =========================
```

With the fix:

```text
$ python -m pytest tests/test_mcp_registry_opencode.py tests/test_mcp_registry tests/test_providers_opencode_config.py tests/test_cli/test_wrap_opencode.py -q
============================= 399 passed in 5.90s ==============================

$ ruff check headroom/mcp_registry/opencode.py tests/test_mcp_registry_opencode.py
All checks passed!
$ ruff format --check headroom/mcp_registry/opencode.py tests/test_mcp_registry_opencode.py
2 files already formatted
```

## Real Behavior Proof

- Environment: macOS 27.0.1 (arm64), Python 3.12.11, source tree on this
branch (native `headroom._core` from the 0.41.0 wheel), `HOME` pointed
at a fresh temp dir, `HEADROOM_OFFLINE=1`
- Exact command / steps: wrote `~/.config/opencode/opencode.jsonc` as
  ```jsonc
  {
    "$schema": "https://opencode.ai/config.json",
    "theme": "dracula", // keep my theme
    "model": "anthropic/claude-sonnet-4-5" // default model
  }
  ```
then ran `python -m headroom.cli mcp install --agent opencode` and
printed the file afterwards, on `main` and on this branch.
- Observed result: on `main` the install fails and the file is
unchanged. On this branch the `mcp.headroom` entry is merged in, and
`$schema`, `theme` and `model` are kept. As before, a rewrite drops the
comments; the docstring already says so.

  ```text
  == main
  Installing Headroom MCP server...
opencode: install failed (failed): .../.config/opencode/opencode.jsonc
exists but is not valid JSON (not valid JSON/JSONC); refusing to
overwrite. Fix or remove the file, then re-run.
  == this branch
  Next steps:
    1. Start the Headroom proxy (if not running): headroom proxy
  -- opencode.jsonc after:
  {
    "$schema": "https://opencode.ai/config.json",
    "theme": "dracula",
    "model": "anthropic/claude-sonnet-4-5",
    "mcp": {
      "headroom": {
        "type": "local",
        "command": ["<python>", "-m", "headroom.cli", "mcp", "serve"],
        "enabled": true
      }
    }
  }
  ```
(`command` shortened here; it is the absolute interpreter path of the
run.)
- Not tested: a real OpenCode binary reading the rewritten file; Windows
paths. Preserving comments on rewrite is out of scope; that limitation
is unchanged.

## Runtime Rollout Safety

- Rollout-managed feature(s): none
- Minimum rollout channel: N/A
- Stable/default behavior changed: `headroom mcp install` / `uninstall`
for OpenCode now accept the JSONC that `headroom wrap opencode` already
accepts. Malformed files are still refused, and the existing fail-closed
tests pass unchanged.
- Kill switch / disable path: N/A
- Unsafe override required: no
- Qualification impact: none
- Rollback path: revert this commit

## Review Readiness

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

## Checklist

- [x] My code follows the project's style guidelines
- [x] I have performed a self-review of my code
- [x] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] New and existing unit tests pass locally with my changes
- [x] I did **not** edit `CHANGELOG.md` — it is generated by
release-please from my Conventional Commit PR title (a CI guard enforces
this)

## Additional Notes

This removes the second, weaker JSONC parser in favour of the one the
OpenCode provider already ships, so the MCP and wrap/install paths can't
disagree about what a valid `opencode.jsonc` is.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
This commit is contained in:
Rudy Mizrahi Celekli
2026-10-24 08:44:36 -07:00
committed by GitHub
co-authored by Claude Opus 5.5 JerrettDavis
parent 37654390b6
commit 9202948c1e
2 changed files with 63 additions and 18 deletions
+23 -17
View File
@@ -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.
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 _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."""
"""Parse JSON or JSONC text, returning ``None`` if it can't be parsed as an object.
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.
"""
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
+40 -1
View File
@@ -81,6 +81,35 @@ def test_register_server_merges_into_commented_jsonc(
assert data["mcp"]["headroom"]["command"] == ["headroom", "mcp"]
@pytest.mark.parametrize(
"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:
}
@pytest.mark.parametrize("contents", ["not json", "{", '{"theme": }', "[]"])
@pytest.mark.parametrize(
"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.