refactor(mcp_registry): share spec helpers and fold GrokRegistrar onto the Codex TOML registrar (#4121)

## Description

`_specs_equivalent`, `_diff_specs`, `_entry_to_spec` and
`_spec_to_entry` were copied into four or five registrar modules. This
PR moves them once into `headroom/mcp_registry/base.py`. OpenCode keeps
its own entry/spec converters because its format really is different,
and it still exposes `_specs_equivalent` and `_diff_specs` so existing
imports keep working.

`grok.py` was a copy of the Codex marker-block registrar with a
different config directory. Both registrars now subclass a shared
`_TomlMarkerRegistrar` in `codex.py`. Grok keeps its own `name`,
`display_name` and `GROK_HOME` resolution, the same markers, file name
and messages.

One visible change: Grok now runs the same pre-write merge guard as
Codex. For an unparseable or non-table `config.toml`, `register_server`
still returns FAILED and still leaves the file untouched, but the detail
now says why (for example "... is not valid TOML (...)") instead of the
generic "does not parse, or the Headroom block holds entries ...".

Evidence: `rg -no '^def (\w+)' headroom/mcp_registry` showed each helper
defined 4-5 times. `diff codex.py grok.py` showed only the directory
resolution, comments and the missing merge guard differ. `rg` for
`_codex_dir`/`_grok_dir` across headroom, tests, docs, plugins, sdk and
the consumer repos found only one comment in `cli/wrap.py`, now updated.

Refs #4136

## Type of Change

- [ ] 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
- [x] Code refactoring (no functional changes)

## Changes Made

- `mcp_registry/base.py`: add the four shared spec helpers.
- `claude.py`, `antigravity.py`, `codex.py`: drop their copies and
import from `base`.
- `opencode.py`: drop its copies of `_specs_equivalent` and
`_diff_specs`, import them from `base`; keep its own `_entry_to_spec`
and `_spec_to_entry`.
- `codex.py`: extract `_TomlMarkerRegistrar(config_dir)` holding all
marker-block logic; `CodexRegistrar` only resolves `$CODEX_HOME`. The
directory attribute is now `_config_dir`; `_config_file`, `_read_text`,
`_load_toml` and the other private methods tests use keep their names.
- `grok.py`: `GrokRegistrar` subclasses `_TomlMarkerRegistrar` and only
resolves `GROK_HOME` / `~/.grok`.
- `cli/wrap.py`: update one comment that named `_codex_dir`.
- `tests/test_mcp_registry/test_grok_registrar.py`: add
`test_register_refuses_unparseable_config` (fails on main only on the
detail text; status was already FAILED).

## Testing

- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .`)
- [x] Type checking passes (`mypy headroom`)
- [x] New tests added for new functionality
- [ ] Manual testing performed

### Test Output

```text
$ pytest -q tests/test_mcp_registry tests/test_mcp_registry_grok.py tests/test_mcp_registry_antigravity.py tests/test_mcp_registry_opencode.py tests/test_cli/test_port_alignment.py tests/test_cli/test_wrap_codex.py tests/test_cli/test_mcp.py tests/test_cli/test_serena_disable.py tests/test_cli/test_wrap_opencode.py tests/test_cli/test_unwrap_claude.py tests/test_cli/test_serena_scope.py tests/test_cli/test_tokensave_scope.py
547 passed in 8.85s
$ uvx ruff@0.16.8 check <touched files>
All checks passed!
$ mypy headroom/mcp_registry/ --ignore-missing-imports
Success: no issues found in 11 source files
# New grok test against origin/main product code:
E   AssertionError: assert 'not valid TOML' in '... does not parse, or the Headroom block holds entries Headroom could not move out safely; refusing to rewrite it.'
1 failed, 8 passed
```

## Real Behavior Proof

- Environment: macOS, Python from the repo `.venv`, worktree off
origin/main.
- Exact command / steps: ran the registrar and CLI wrap/mcp test files
above, which drive `CodexRegistrar` and `GrokRegistrar` against real
temp `config.toml` files (register, force re-register, unregister,
foreign-table eviction, control-char escaping, GROK_HOME/CODEX_HOME
resolution).
- Observed result: all pass; Grok on an unparseable config returns
FAILED with "is not valid TOML" and the file bytes are unchanged.
- Smoke harness (real proxy started from this checkout against a local
fake upstream; temp HOME and workspace, offline):

```text
branch: cleanup/cli-integrations-mcp-registry-shared-helpers @ 9dbca0d0
health: 200
POST /v1/messages        -> HTTP200 smoke-ok
POST /v1/chat/completions -> HTTP200 smoke-ok
stats: requests=2 failed=0 tokens_saved=13574 savings_percent=99.82
proxy.log WARNING/ERROR lines (<tmp>/ws/logs/proxy-63555.log):
   2 headroom.proxy - WARNING - event=proxy_offline_mode air-gap active — every connection Headroom initiates is refused (telemetry, update check, license reporter, model/tokenizer/binary/dataset downloads, remote Kompress, OTLP/Langfuse export, Copilot auth, subscription polling, OpenAI embedders, Headroom Cloud compression). Still allowed on purpose: forwarding your requests to the upstream you configured, operator-configured local endpoints, loopback health probes.
   4 headroom.transforms.kompress_compressor - WARNING - Kompress: artifact prefetch found no usable file for chopratejas/kompress-v2-base
   4 headroom.transforms.kompress_compressor - WARNING - Kompress: artifact prefetch refused for chopratejas/kompress-v2-base (HEADROOM_OFFLINE is set): HEADROOM_OFFLINE is set: refusing outbound network access for HuggingFace download of chopratejas/kompress-v2-base/onnx/kompress-int8-wo.onnx to huggingface.co. Unset HEADROOM_OFFLINE, or turn off the feature that needs this connection.
(smoke dir: <tmp>)
```
- Direct runtime command on this PR's own path (temp HOME,
HEADROOM_WORKSPACE_DIR and CODEX_HOME):

```text
$ HOME=<tmp>/home HEADROOM_WORKSPACE_DIR=<tmp>/ws CODEX_HOME=<tmp>/codex headroom mcp install --agent codex --agent grok
exit=0
--- stdout
Installing Headroom MCP server...
  codex: registered (restart the agent if it was already running)
  grok: registered (restart the agent if it was already running)

Next steps:
  1. Start the Headroom proxy (if not running): headroom proxy
  2. Start your agent (e.g.) ANTHROPIC_BASE_URL=http://127.0.0.1:8787 claude
  3. Restart any agent that was already running so it picks up the new MCP server.
--- stderr
--- <tmp>/home/.grok/config.toml
# --- Headroom MCP server ---
[mcp_servers.headroom]
command = "<venv>/bin/python"
args = ["-m", "headroom.cli", "mcp", "serve"]
# --- end Headroom MCP server ---
--- <tmp>/codex/config.toml (head)
# --- Headroom MCP server ---
[mcp_servers.headroom]
command = "<venv>/bin/python"
args = ["-m", "headroom.cli", "mcp", "serve"]
# --- end Headroom MCP server ---
$ HOME=<tmp>/home HEADROOM_WORKSPACE_DIR=<tmp>/ws CODEX_HOME=<tmp>/codex headroom mcp uninstall
exit=0
--- stdout
✓ OpenAI Codex CLI: removed headroom MCP server(s)
✓ Grok CLI: removed headroom MCP server(s)
--- stderr
--- after uninstall: grok bytes=       0 codex bytes=       0
```
- Not tested: running the real Codex or Grok CLIs against the written
config.

## Runtime Rollout Safety

- Rollout-managed feature(s): None; CLI-side MCP registration code only.
- Minimum rollout channel: N/A, no rollout-gated behaviour.
- Stable/default behavior changed: No, except the more specific FAILED
detail for unmergeable Grok configs.
- Kill switch / disable path: N/A; revert the commit.
- Unsafe override required: No.
- Qualification impact: None.
- Rollback path: revert this single 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)

## Screenshots (if applicable)

N/A

## Additional Notes

Part of maintainer-requested cleanup #4136 (dead code, duplication,
debuggability), split into small PRs for review.

No docs change needed: `docs/content/docs/grok-build.mdx` names
`GrokRegistrar`, which keeps its name and import path. This PR and the
`fix(mcp_registry): atomic config writes ...` PR both touch `grok.py`
and `claude.py`; whichever merges second needs a small rebase (the
failed-removal warning in `grok.py` then lives only in the shared
`codex.py` base).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- devin-review-badge-begin -->

---

<a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/4121"
target="_blank"><picture><source media="(prefers-color-scheme: dark)"
srcset="https://static.devin.ai/assets/gh-devin-review-dark.svg?v=4"><img
src="https://static.devin.ai/assets/gh-devin-review-light.svg?v=4"
alt="Devin Review"></picture></a>
<!-- devin-review-badge-end -->
This commit is contained in:
Tejas Chopra
2026-10-12 18:59:19 -07:00
committed by GitHub
parent f30d330682
commit 6e14ee0bc2
9 changed files with 152 additions and 397 deletions
+1 -1
View File
@@ -7057,7 +7057,7 @@ def _prepare_codex_wrap_state(
) -> None:
"""Prepare the active Codex home for a wrap or prepare-only invocation."""
# Ensure the Codex home exists before anything tries to detect or write it.
# ``CodexRegistrar.detect()`` is just ``self._codex_dir.is_dir()``, and until
# ``CodexRegistrar.detect()`` is just ``self._config_dir.is_dir()``, and until
# now the directory was created as a *side effect* of injecting the rtk
# guidance into ``$CODEX_HOME/AGENTS.md``. With the CLI context tools removed
# nothing creates it, so on a machine where Codex is installed but has never
+10 -45
View File
@@ -36,7 +36,16 @@ from typing import Any
from headroom import fsutil
from .base import MCPRegistrar, RegisterResult, RegisterStatus, ServerSpec
from .base import (
MCPRegistrar,
RegisterResult,
RegisterStatus,
ServerSpec,
_diff_specs,
_entry_to_spec,
_spec_to_entry,
_specs_equivalent,
)
logger = logging.getLogger(__name__)
@@ -202,47 +211,3 @@ class AntigravityRegistrar(MCPRegistrar):
except (json.JSONDecodeError, OSError, UnicodeDecodeError):
return None
return data if isinstance(data, dict) else None
def _entry_to_spec(name: str, entry: dict[str, Any]) -> ServerSpec:
args_value = entry.get("args", [])
args = tuple(str(x) for x in args_value) if isinstance(args_value, list) else ()
env_value = entry.get("env", {})
env = {str(k): str(v) for k, v in env_value.items()} if isinstance(env_value, dict) else {}
return ServerSpec(
name=name,
command=str(entry.get("command", "")),
args=args,
env=env,
)
def _spec_to_entry(spec: ServerSpec) -> dict[str, Any]:
entry: dict[str, Any] = {"command": spec.command}
if spec.args:
entry["args"] = list(spec.args)
if spec.env:
entry["env"] = dict(spec.env)
return entry
def _specs_equivalent(a: ServerSpec, b: ServerSpec) -> bool:
return (
a.name == b.name
and a.command == b.command
and tuple(a.args) == tuple(b.args)
and dict(a.env) == dict(b.env)
)
def _diff_specs(existing: ServerSpec, requested: ServerSpec) -> str:
parts: list[str] = []
if existing.command != requested.command:
parts.append(f"command {existing.command!r} -> {requested.command!r}")
if tuple(existing.args) != tuple(requested.args):
parts.append(f"args {list(existing.args)} -> {list(requested.args)}")
if dict(existing.env) != dict(requested.env):
parts.append(f"env {dict(existing.env)} -> {dict(requested.env)}")
if not parts:
return "spec differs in unidentified field(s)"
return "; ".join(parts)
+59
View File
@@ -16,6 +16,7 @@ from __future__ import annotations
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
from enum import Enum
from typing import Any
class RegisterStatus(str, Enum):
@@ -104,3 +105,61 @@ class MCPRegistrar(ABC):
@abstractmethod
def unregister_server(self, server_name: str) -> bool:
"""Remove the named server. Returns True on success."""
# ----------------------------------------------------------------------
# Spec helpers shared by the registrars whose entries use the common
# ``{"command", "args", "env"}`` shape (Claude, Antigravity, Codex, Grok).
# OpenCode has its own entry format and keeps its own converters.
# ----------------------------------------------------------------------
def _spec_to_entry(spec: ServerSpec) -> dict[str, Any]:
entry: dict[str, Any] = {"command": spec.command}
if spec.args:
entry["args"] = list(spec.args)
if spec.env:
entry["env"] = dict(spec.env)
return entry
def _entry_to_spec(name: str, entry: dict[str, Any]) -> ServerSpec:
args_value = entry.get("args", [])
if isinstance(args_value, list):
args = tuple(str(x) for x in args_value)
else:
args = ()
env_value = entry.get("env", {})
env: dict[str, str] = {}
if isinstance(env_value, dict):
env = {str(k): str(v) for k, v in env_value.items()}
return ServerSpec(
name=name,
command=str(entry.get("command", "")),
args=args,
env=env,
)
def _specs_equivalent(a: ServerSpec, b: ServerSpec) -> bool:
"""Two specs match when every field is equal."""
return (
a.name == b.name
and a.command == b.command
and tuple(a.args) == tuple(b.args)
and dict(a.env) == dict(b.env)
)
def _diff_specs(existing: ServerSpec, requested: ServerSpec) -> str:
"""Render the difference between two specs for human consumption."""
parts: list[str] = []
if existing.command != requested.command:
parts.append(f"command {existing.command!r} -> {requested.command!r}")
if tuple(existing.args) != tuple(requested.args):
parts.append(f"args {list(existing.args)} -> {list(requested.args)}")
if dict(existing.env) != dict(requested.env):
parts.append(f"env {dict(existing.env)} -> {dict(requested.env)}")
if not parts:
return "spec differs in unidentified field(s)"
return "; ".join(parts)
+10 -52
View File
@@ -37,7 +37,16 @@ from typing import Any
from headroom import fsutil
from headroom._subprocess import run
from .base import MCPRegistrar, RegisterResult, RegisterStatus, ServerSpec
from .base import (
MCPRegistrar,
RegisterResult,
RegisterStatus,
ServerSpec,
_diff_specs,
_entry_to_spec,
_spec_to_entry,
_specs_equivalent,
)
logger = logging.getLogger(__name__)
@@ -579,54 +588,3 @@ def _read_json_for_write(path: Path) -> dict[str, Any]:
def _write_json(path: Path, data: dict[str, Any]) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
fsutil.write_text(path, json.dumps(data, indent=2) + "\n")
def _spec_to_entry(spec: ServerSpec) -> dict[str, Any]:
entry: dict[str, Any] = {"command": spec.command}
if spec.args:
entry["args"] = list(spec.args)
if spec.env:
entry["env"] = dict(spec.env)
return entry
def _entry_to_spec(name: str, entry: dict[str, Any]) -> ServerSpec:
args_value = entry.get("args", [])
if isinstance(args_value, list):
args = tuple(str(x) for x in args_value)
else:
args = ()
env_value = entry.get("env", {})
env: dict[str, str] = {}
if isinstance(env_value, dict):
env = {str(k): str(v) for k, v in env_value.items()}
return ServerSpec(
name=name,
command=str(entry.get("command", "")),
args=args,
env=env,
)
def _specs_equivalent(a: ServerSpec, b: ServerSpec) -> bool:
"""Two specs match when every field is equal."""
return (
a.name == b.name
and a.command == b.command
and tuple(a.args) == tuple(b.args)
and dict(a.env) == dict(b.env)
)
def _diff_specs(existing: ServerSpec, requested: ServerSpec) -> str:
"""Render the difference between two specs for human consumption."""
parts: list[str] = []
if existing.command != requested.command:
parts.append(f"command {existing.command!r} -> {requested.command!r}")
if tuple(existing.args) != tuple(requested.args):
parts.append(f"args {list(existing.args)} -> {list(requested.args)}")
if dict(existing.env) != dict(requested.env):
parts.append(f"env {dict(existing.env)} -> {dict(requested.env)}")
if not parts:
return "spec differs in unidentified field(s)"
return "; ".join(parts)
+38 -57
View File
@@ -6,7 +6,8 @@ Codex stores MCP server config in ``$CODEX_HOME/config.toml`` when
sub-tables). There is no general-purpose CLI for adding entries, so we
edit the file in place — using marker-delimited blocks so we can
idempotently inject, replace, and remove our entry without disturbing
anything else the user has configured.
anything else the user has configured. The Grok registrar reuses the
same marker-block logic.
"""
from __future__ import annotations
@@ -18,7 +19,15 @@ from typing import Any
from headroom import fsutil
from .base import MCPRegistrar, RegisterResult, RegisterStatus, ServerSpec
from .base import (
MCPRegistrar,
RegisterResult,
RegisterStatus,
ServerSpec,
_diff_specs,
_entry_to_spec,
_specs_equivalent,
)
if sys.version_info >= (3, 11):
import tomllib
@@ -118,27 +127,23 @@ def _only_server_changed(old: str, new: str, server_name: str) -> bool:
return _without_server(before, server_name) == _without_server(after, server_name)
class CodexRegistrar(MCPRegistrar):
"""Register MCP servers with the OpenAI Codex CLI."""
class _TomlMarkerRegistrar(MCPRegistrar):
"""Marker-block registrar for ``<config_dir>/config.toml``.
name = "codex"
display_name = "OpenAI Codex CLI"
Codex and Grok both keep ``[mcp_servers.<name>]`` tables in a
``config.toml`` and differ only in where the config directory lives.
"""
def __init__(self, *, home_dir: Path | None = None) -> None:
if home_dir is not None:
self._codex_dir = home_dir / ".codex"
else:
from headroom.install.paths import codex_home_dir
self._codex_dir = codex_home_dir()
self._config_file = self._codex_dir / "config.toml"
def __init__(self, config_dir: Path) -> None:
self._config_dir = config_dir
self._config_file = config_dir / "config.toml"
# ------------------------------------------------------------------
# MCPRegistrar interface
# ------------------------------------------------------------------
def detect(self) -> bool:
return self._codex_dir.is_dir()
return self._config_dir.is_dir()
def get_server(self, server_name: str) -> ServerSpec | None:
data = self._load_toml()
@@ -189,7 +194,7 @@ class CodexRegistrar(MCPRegistrar):
# _write_block appends a `[mcp_servers.<name>]` table, so appending into
# an unparseable file corrupts it further, and appending alongside a
# non-table entry creates a duplicate `[mcp_servers.<name>]` key that
# tomllib/codex then reject — destroying a previously-valid user config.
# tomllib and the CLI then reject — destroying a previously-valid user config.
# Refuse rather than clobber, mirroring the claude (#1660) / opencode
# (#1661) guards.
if existing is None:
@@ -291,7 +296,7 @@ class CodexRegistrar(MCPRegistrar):
def _write_block(self, spec: ServerSpec) -> RegisterResult:
block = _render_block(spec)
try:
self._codex_dir.mkdir(parents=True, exist_ok=True)
self._config_dir.mkdir(parents=True, exist_ok=True)
marker_start = _marker_start(spec.name)
marker_end = _marker_end(spec.name)
original = self._read_text()
@@ -324,6 +329,22 @@ class CodexRegistrar(MCPRegistrar):
return RegisterResult(RegisterStatus.REGISTERED, f"wrote to {self._config_file}")
class CodexRegistrar(_TomlMarkerRegistrar):
"""Register MCP servers with the OpenAI Codex CLI."""
name = "codex"
display_name = "OpenAI Codex CLI"
def __init__(self, *, home_dir: Path | None = None) -> None:
if home_dir is not None:
config_dir = home_dir / ".codex"
else:
from headroom.install.paths import codex_home_dir
config_dir = codex_home_dir()
super().__init__(config_dir)
# ----------------------------------------------------------------------
# TOML rendering / parsing helpers (kept module-private)
# ----------------------------------------------------------------------
@@ -379,43 +400,3 @@ def _toml_str(s: str) -> str:
else:
out.append(ch)
return '"' + "".join(out) + '"'
def _entry_to_spec(name: str, entry: dict[str, Any]) -> ServerSpec:
args_value = entry.get("args", [])
if isinstance(args_value, list):
args = tuple(str(x) for x in args_value)
else:
args = ()
env_value = entry.get("env", {})
env: dict[str, str] = {}
if isinstance(env_value, dict):
env = {str(k): str(v) for k, v in env_value.items()}
return ServerSpec(
name=name,
command=str(entry.get("command", "")),
args=args,
env=env,
)
def _specs_equivalent(a: ServerSpec, b: ServerSpec) -> bool:
return (
a.name == b.name
and a.command == b.command
and tuple(a.args) == tuple(b.args)
and dict(a.env) == dict(b.env)
)
def _diff_specs(existing: ServerSpec, requested: ServerSpec) -> str:
parts: list[str] = []
if existing.command != requested.command:
parts.append(f"command {existing.command!r} -> {requested.command!r}")
if tuple(existing.args) != tuple(requested.args):
parts.append(f"args {list(existing.args)} -> {list(requested.args)}")
if dict(existing.env) != dict(requested.env):
parts.append(f"env {dict(existing.env)} -> {dict(requested.env)}")
if not parts:
return "spec differs in unidentified field(s)"
return "; ".join(parts)
+9 -218
View File
@@ -4,46 +4,20 @@ Grok stores MCP server config in ``$GROK_HOME/config.toml`` (default
``~/.grok/config.toml``) as ``[mcp_servers.<name>]`` tables. There is no
general-purpose CLI for adding entries, so we edit the file in place using
marker-delimited blocks so we can idempotently inject, replace, and remove
our entry without disturbing anything else the user has configured.
our entry without disturbing anything else the user has configured. The
file format matches Codex's, so the marker-block logic lives in
:mod:`headroom.mcp_registry.codex`.
"""
from __future__ import annotations
import logging
import os
import sys
from pathlib import Path
from typing import Any
from headroom import fsutil
from .base import MCPRegistrar, RegisterResult, RegisterStatus, ServerSpec
from .codex import _evict_foreign_tables, _only_server_changed, _toml_str
if sys.version_info >= (3, 11):
import tomllib
else: # pragma: no cover — exercised only on 3.10
import tomli as tomllib # type: ignore[no-redef]
logger = logging.getLogger(__name__)
_MARKER_START = "# --- Headroom MCP server ---"
_MARKER_END = "# --- end Headroom MCP server ---"
from .codex import _TomlMarkerRegistrar
def _marker_start(server_name: str) -> str:
if server_name == "headroom":
return _MARKER_START
return f"# --- Headroom MCP server: {server_name} ---"
def _marker_end(server_name: str) -> str:
if server_name == "headroom":
return _MARKER_END
return f"# --- end Headroom MCP server: {server_name} ---"
class GrokRegistrar(MCPRegistrar):
class GrokRegistrar(_TomlMarkerRegistrar):
"""Register MCP servers with the Grok CLI."""
name = "grok"
@@ -51,192 +25,9 @@ class GrokRegistrar(MCPRegistrar):
def __init__(self, *, home_dir: Path | None = None) -> None:
if home_dir is not None:
self._grok_dir = home_dir / ".grok"
config_dir = home_dir / ".grok"
elif os.environ.get("GROK_HOME"):
self._grok_dir = Path(os.environ["GROK_HOME"]).expanduser()
config_dir = Path(os.environ["GROK_HOME"]).expanduser()
else:
self._grok_dir = Path.home() / ".grok"
self._config_file = self._grok_dir / "config.toml"
def detect(self) -> bool:
return self._grok_dir.is_dir()
def get_server(self, server_name: str) -> ServerSpec | None:
data = self._load_toml()
servers = data.get("mcp_servers", {})
if not isinstance(servers, dict):
return None
entry = servers.get(server_name)
if not isinstance(entry, dict):
return None
return _entry_to_spec(server_name, entry)
def register_server(self, spec: ServerSpec, *, force: bool = False) -> RegisterResult:
existing = self.get_server(spec.name)
if existing is not None and _specs_equivalent(existing, spec):
return RegisterResult(RegisterStatus.ALREADY, "matches current configuration")
if existing is not None and not force:
content = self._read_text()
if _marker_start(spec.name) not in content:
return RegisterResult(
RegisterStatus.MISMATCH,
"user-managed [mcp_servers."
f"{spec.name}] entry outside Headroom markers; "
f"{_diff_specs(existing, spec)}",
)
return RegisterResult(RegisterStatus.MISMATCH, _diff_specs(existing, spec))
if existing is not None and force:
content = self._read_text()
if _marker_start(spec.name) not in content:
return RegisterResult(
RegisterStatus.MISMATCH,
"user-managed [mcp_servers."
f"{spec.name}] entry outside Headroom markers; "
f"{_diff_specs(existing, spec)}",
)
self.unregister_server(spec.name)
return self._write_block(spec)
def unregister_server(self, server_name: str) -> bool:
if not self._config_file.exists():
return False
marker_start = _marker_start(server_name)
marker_end = _marker_end(server_name)
original = self._read_text()
content = _evict_foreign_tables(original, server_name, marker_start, marker_end)
if marker_start not in content or marker_end not in content:
return False
try:
start = content.index(marker_start)
end = content.index(marker_end) + len(marker_end)
except ValueError:
return False
before = content[:start].rstrip("\n")
after = content[end:].lstrip("\n")
if before and after:
new_content = before + "\n\n" + after
else:
new_content = (before or after).rstrip("\n") + ("\n" if (before or after) else "")
if not _only_server_changed(original, new_content, server_name):
logger.warning(
"Not removing the Headroom block for %s from %s: the file does not parse, "
"or the block holds entries Headroom could not move out safely.",
server_name,
self._config_file,
)
return False
try:
fsutil.write_text(self._config_file, new_content)
except OSError as exc:
logger.warning("could not remove %r from %s: %s", server_name, self._config_file, exc)
return False
return True
def _load_toml(self) -> dict[str, Any]:
if not self._config_file.exists():
return {}
try:
data = tomllib.loads(fsutil.read_text(self._config_file))
except (tomllib.TOMLDecodeError, OSError):
return {}
return data if isinstance(data, dict) else {}
def _read_text(self) -> str:
return fsutil.read_text(self._config_file, default="")
def _write_block(self, spec: ServerSpec) -> RegisterResult:
block = _render_block(spec)
try:
self._grok_dir.mkdir(parents=True, exist_ok=True)
marker_start = _marker_start(spec.name)
marker_end = _marker_end(spec.name)
original = self._read_text()
content = _evict_foreign_tables(original, spec.name, marker_start, marker_end)
if marker_start in content and marker_end in content:
start = content.index(marker_start)
end = content.index(marker_end) + len(marker_end)
content = (
content[:start].rstrip("\n")
+ ("\n\n" if content[:start].rstrip("\n") else "")
+ block
+ "\n"
+ content[end:].lstrip("\n")
)
elif content.strip():
content = content.rstrip("\n") + "\n\n" + block + "\n"
else:
content = block + "\n"
if not _only_server_changed(original, content, spec.name):
return RegisterResult(
RegisterStatus.FAILED,
f"{self._config_file} does not parse, or the Headroom block holds "
"entries Headroom could not move out safely; refusing to rewrite it.",
)
fsutil.write_text(self._config_file, content)
except OSError as exc:
return RegisterResult(
RegisterStatus.FAILED, f"could not write {self._config_file}: {exc}"
)
return RegisterResult(RegisterStatus.REGISTERED, f"wrote to {self._config_file}")
def _render_block(spec: ServerSpec) -> str:
lines: list[str] = [
_marker_start(spec.name),
f"[mcp_servers.{spec.name}]",
f"command = {_toml_str(spec.command)}",
]
if spec.args:
items = ", ".join(_toml_str(a) for a in spec.args)
lines.append(f"args = [{items}]")
if spec.env:
lines.append("")
lines.append(f"[mcp_servers.{spec.name}.env]")
for k, v in spec.env.items():
lines.append(f"{k} = {_toml_str(v)}")
lines.append(_marker_end(spec.name))
return "\n".join(lines)
def _entry_to_spec(name: str, entry: dict[str, Any]) -> ServerSpec:
args_value = entry.get("args", [])
if isinstance(args_value, list):
args = tuple(str(x) for x in args_value)
else:
args = ()
env_value = entry.get("env", {})
env: dict[str, str] = {}
if isinstance(env_value, dict):
env = {str(k): str(v) for k, v in env_value.items()}
return ServerSpec(
name=name,
command=str(entry.get("command", "")),
args=args,
env=env,
)
def _specs_equivalent(a: ServerSpec, b: ServerSpec) -> bool:
return (
a.name == b.name
and a.command == b.command
and tuple(a.args) == tuple(b.args)
and dict(a.env) == dict(b.env)
)
def _diff_specs(existing: ServerSpec, requested: ServerSpec) -> str:
parts: list[str] = []
if existing.command != requested.command:
parts.append(f"command {existing.command!r} -> {requested.command!r}")
if tuple(existing.args) != tuple(requested.args):
parts.append(f"args {list(existing.args)} -> {list(requested.args)}")
if dict(existing.env) != dict(requested.env):
parts.append(f"env {dict(existing.env)} -> {dict(requested.env)}")
if not parts:
return "spec differs in unidentified field(s)"
return "; ".join(parts)
config_dir = Path.home() / ".grok"
super().__init__(config_dir)
+8 -23
View File
@@ -17,7 +17,14 @@ from typing import Any
from headroom import fsutil
from headroom.install.paths import opencode_config_path
from .base import MCPRegistrar, RegisterResult, RegisterStatus, ServerSpec
from .base import (
MCPRegistrar,
RegisterResult,
RegisterStatus,
ServerSpec,
_diff_specs,
_specs_equivalent,
)
logger = logging.getLogger(__name__)
@@ -128,28 +135,6 @@ def _spec_to_entry(spec: ServerSpec) -> dict[str, Any]:
return entry
def _specs_equivalent(a: ServerSpec, b: ServerSpec) -> bool:
return (
a.name == b.name
and a.command == b.command
and tuple(a.args) == tuple(b.args)
and dict(a.env) == dict(b.env)
)
def _diff_specs(existing: ServerSpec, requested: ServerSpec) -> str:
parts: list[str] = []
if existing.command != requested.command:
parts.append(f"command {existing.command!r} -> {requested.command!r}")
if tuple(existing.args) != tuple(requested.args):
parts.append(f"args {list(existing.args)} -> {list(requested.args)}")
if dict(existing.env) != dict(requested.env):
parts.append(f"env {dict(existing.env)} -> {dict(requested.env)}")
if not parts:
return "spec differs in unidentified field(s)"
return "; ".join(parts)
class OpencodeRegistrar(MCPRegistrar):
"""Register MCP servers with OpenCode."""
@@ -140,3 +140,18 @@ def test_register_escapes_control_chars_in_env_value(tmp_path: Path) -> None:
parsed = tomllib.loads(reg._config_file.read_text())
assert parsed["mcp_servers"]["headroom"]["env"]["PEM"] == pem
assert reg.get_server("headroom").env["PEM"] == pem
def test_register_refuses_unparseable_config(tmp_path: Path) -> None:
"""Grok shares the codex merge guard: an unparseable config.toml is refused
with a reason that names the file, and left byte-for-byte untouched."""
cfg = tmp_path / ".grok" / "config.toml"
cfg.parent.mkdir()
original = "this = is = not = valid\n"
cfg.write_text(original)
result = _make_registrar(tmp_path).register_server(_spec())
assert result.status == RegisterStatus.FAILED
assert "not valid TOML" in result.detail
assert cfg.read_text() == original
@@ -33,7 +33,8 @@ def _no_space(fd: int) -> None:
(
lambda home: GrokRegistrar(home_dir=home),
".grok/config.toml",
"headroom.mcp_registry.grok",
# Grok shares the marker-block registrar, and its logger, with Codex.
"headroom.mcp_registry.codex",
),
],
ids=["claude", "codex", "grok"],