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

_specs_equivalent, _diff_specs, _entry_to_spec and _spec_to_entry were copied into claude, antigravity, codex, grok and opencode. They now live once in mcp_registry/base.py. OpenCode keeps its own entry/spec converters because its format differs, and still exposes the shared names so existing imports keep working.

grok.py was a copy of the Codex marker-block registrar with a different config directory. Both now subclass _TomlMarkerRegistrar in codex.py; Grok keeps its GROK_HOME resolution. Grok gains the Codex pre-write merge guard, so an unparseable or non-table config still fails, but with a detail that says why.

Evidence: rg -no '^def (\w+)' headroom/mcp_registry showed each helper defined 4-5 times; diff codex.py grok.py showed only the directory, comments and the missing guard differ.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Assisted-by: claude-code:claude-opus-5-5
Headline-Session: 6e77a807-8dd4-4a77-a2fa-ddce6dc2515e
Headline-AI-Share: 19% strict / 19% weighted
This commit is contained in:
Tejas Chopra
2026-10-09 16:51:25 -07:00
co-authored by Claude Opus 5.5
parent a9815bbb5f
commit 9dbca0d054
8 changed files with 150 additions and 395 deletions
+1 -1
View File
@@ -7139,7 +7139,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
@@ -36,7 +36,16 @@ from typing import Any
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__)
@@ -578,54 +587,3 @@ def _write_json(path: Path, data: dict[str, Any]) -> None:
with open(path, "w", encoding="utf-8") as f:
json.dump(data, f, indent=2)
f.write("\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:
@@ -290,7 +295,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()
@@ -323,6 +328,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)
# ----------------------------------------------------------------------
@@ -378,43 +399,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 -217
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,191 +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:
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
@@ -16,7 +16,14 @@ from typing import Any
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__)
@@ -126,28 +133,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."""
@@ -119,3 +119,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