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.

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

Tejas Chopra6e14ee0bc2dd
diff --git a/headroom/cli/wrap.py b/headroom/cli/wrap.py
index 0f751073d..3edf9703e 100644
--- a/headroom/cli/wrap.py
+++ b/headroom/cli/wrap.py
@@ -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
diff --git a/headroom/mcp_registry/antigravity.py b/headroom/mcp_registry/antigravity.py
index 6f7e76712..70f2caf81 100644
--- a/headroom/mcp_registry/antigravity.py
+++ b/headroom/mcp_registry/antigravity.py
@@ -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)
diff --git a/headroom/mcp_registry/base.py b/headroom/mcp_registry/base.py
index 3628b6925..31b4b4352 100644
--- a/headroom/mcp_registry/base.py
+++ b/headroom/mcp_registry/base.py
@@ -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)
diff --git a/headroom/mcp_registry/claude.py b/headroom/mcp_registry/claude.py
index d27d09362..09d8d7f4b 100644
--- a/headroom/mcp_registry/claude.py
+++ b/headroom/mcp_registry/claude.py
@@ -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)
diff --git a/headroom/mcp_registry/codex.py b/headroom/mcp_registry/codex.py
index 4405ea399..55e2a1f1f 100644
--- a/headroom/mcp_registry/codex.py
+++ b/headroom/mcp_registry/codex.py
@@ -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."""
-
- name = "codex"
- display_name = "OpenAI Codex CLI"
+class _TomlMarkerRegistrar(MCPRegistrar):
+ """Marker-block registrar for ``<config_dir>/config.toml``.
- 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
+ Codex and Grok both keep ``[mcp_servers.<name>]`` tables in a
+ ``config.toml`` and differ only in where the config directory lives.
+ """
- 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)
diff --git a/headroom/mcp_registry/grok.py b/headroom/mcp_registry/grok.py
index a2e888117..a5732cebc 100644
--- a/headroom/mcp_registry/grok.py
+++ b/headroom/mcp_registry/grok.py
@@ -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 .codex import _TomlMarkerRegistrar
-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 ---"
-
-
-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()
- 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
+ config_dir = Path(os.environ["GROK_HOME"]).expanduser()
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)
diff --git a/headroom/mcp_registry/opencode.py b/headroom/mcp_registry/opencode.py
index 6cd470104..7448fb271 100644
--- a/headroom/mcp_registry/opencode.py
+++ b/headroom/mcp_registry/opencode.py
@@ -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."""
diff --git a/tests/test_mcp_registry/test_grok_registrar.py b/tests/test_mcp_registry/test_grok_registrar.py
index 06c636d28..cc3a0fd69 100644
--- a/tests/test_mcp_registry/test_grok_registrar.py
+++ b/tests/test_mcp_registry/test_grok_registrar.py
@@ -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
diff --git a/tests/test_mcp_registry/test_removal_failures.py b/tests/test_mcp_registry/test_removal_failures.py
index 345746324..c8a97aedd 100644
--- a/tests/test_mcp_registry/test_removal_failures.py
+++ b/tests/test_mcp_registry/test_removal_failures.py
@@ -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"],