mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-11-22 13:29:19 +08:00
fix(mcp): keep other apps' tables when replacing the Codex/Grok MCP span
The ChatGPT desktop app appends its [mcp_servers.node_repl] tables (and .env) before the trailing comment of ~/.codex/config.toml. When Headroom's marker span is the last thing in the file, that trailing comment is our end marker, so the app's tables land inside the span. unregister_server deletes everything between the markers, and register_server(force=True) calls it, so `headroom mcp install --force` silently deleted the app's browser-use/computer-use MCP server. Before removing or replacing a span, move every table that is not [mcp_servers.<name>] or one of its subtables to just after the end marker, byte for byte and in order. The move is skipped if the result would parse to anything other than the original document. Grok's registrar uses the same helper. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -43,6 +43,46 @@ def _marker_end(server_name: str) -> str:
|
||||
return f"# --- end Headroom MCP server: {server_name} ---"
|
||||
|
||||
|
||||
def _evict_foreign_tables(content: str, server_name: str, start: str, end: str) -> str:
|
||||
"""Move tables Headroom does not own out of its marker span.
|
||||
|
||||
Another app's TOML writer appends a new table before the document's
|
||||
trailing comment, so when our span is last in the file (the ChatGPT app's
|
||||
``[mcp_servers.node_repl]`` in ``~/.codex/config.toml``) the table lands
|
||||
between our markers and deleting the span would delete it too. Every table
|
||||
other than ``[mcp_servers.<server_name>(.*)]`` is moved, byte for byte and
|
||||
in order, to just after the end marker. The content is returned unchanged
|
||||
if nothing needs moving or if the move would change what the file parses to.
|
||||
"""
|
||||
lines = content.splitlines(keepends=True)
|
||||
try:
|
||||
i = next(n for n, line in enumerate(lines) if line.rstrip("\r\n") == start)
|
||||
j = next(n for n in range(i + 1, len(lines)) if lines[n].rstrip("\r\n") == end)
|
||||
except StopIteration:
|
||||
return content
|
||||
owned_prefix = f"[mcp_servers.{server_name}."
|
||||
kept: list[str] = []
|
||||
foreign: list[str] = []
|
||||
in_foreign = False
|
||||
for line in lines[i + 1 : j]:
|
||||
code = line.split("#", 1)[0].strip()
|
||||
if code.startswith("[") and code.endswith("]"):
|
||||
in_foreign = code != f"[mcp_servers.{server_name}]" and not code.startswith(
|
||||
owned_prefix
|
||||
)
|
||||
(foreign if in_foreign else kept).append(line)
|
||||
if not foreign:
|
||||
return content
|
||||
end_line = lines[j] if lines[j].endswith("\n") else lines[j] + "\n"
|
||||
moved = "".join(lines[: i + 1] + kept + [end_line] + foreign + lines[j + 1 :])
|
||||
try:
|
||||
if tomllib.loads(moved) != tomllib.loads(content):
|
||||
return content
|
||||
except tomllib.TOMLDecodeError:
|
||||
return content
|
||||
return moved
|
||||
|
||||
|
||||
class CodexRegistrar(MCPRegistrar):
|
||||
"""Register MCP servers with the OpenAI Codex CLI."""
|
||||
|
||||
@@ -132,9 +172,9 @@ class CodexRegistrar(MCPRegistrar):
|
||||
# outside markers are intentionally preserved.
|
||||
if not self._config_file.exists():
|
||||
return False
|
||||
content = self._read_text()
|
||||
marker_start = _marker_start(server_name)
|
||||
marker_end = _marker_end(server_name)
|
||||
content = _evict_foreign_tables(self._read_text(), server_name, marker_start, marker_end)
|
||||
if marker_start not in content or marker_end not in content:
|
||||
return False
|
||||
try:
|
||||
@@ -207,9 +247,9 @@ class CodexRegistrar(MCPRegistrar):
|
||||
block = _render_block(spec)
|
||||
try:
|
||||
self._codex_dir.mkdir(parents=True, exist_ok=True)
|
||||
content = self._read_text()
|
||||
marker_start = _marker_start(spec.name)
|
||||
marker_end = _marker_end(spec.name)
|
||||
content = _evict_foreign_tables(self._read_text(), 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)
|
||||
|
||||
@@ -18,6 +18,7 @@ from typing import Any
|
||||
from headroom import fsutil
|
||||
|
||||
from .base import MCPRegistrar, RegisterResult, RegisterStatus, ServerSpec
|
||||
from .codex import _evict_foreign_tables
|
||||
|
||||
if sys.version_info >= (3, 11):
|
||||
import tomllib
|
||||
@@ -103,9 +104,9 @@ class GrokRegistrar(MCPRegistrar):
|
||||
def unregister_server(self, server_name: str) -> bool:
|
||||
if not self._config_file.exists():
|
||||
return False
|
||||
content = self._read_text()
|
||||
marker_start = _marker_start(server_name)
|
||||
marker_end = _marker_end(server_name)
|
||||
content = _evict_foreign_tables(self._read_text(), server_name, marker_start, marker_end)
|
||||
if marker_start not in content or marker_end not in content:
|
||||
return False
|
||||
try:
|
||||
@@ -141,9 +142,9 @@ class GrokRegistrar(MCPRegistrar):
|
||||
block = _render_block(spec)
|
||||
try:
|
||||
self._grok_dir.mkdir(parents=True, exist_ok=True)
|
||||
content = self._read_text()
|
||||
marker_start = _marker_start(spec.name)
|
||||
marker_end = _marker_end(spec.name)
|
||||
content = _evict_foreign_tables(self._read_text(), 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)
|
||||
|
||||
@@ -440,3 +440,54 @@ def test_register_preserves_non_ascii_values(tmp_path: Path) -> None:
|
||||
data = tomllib.loads(cfg.read_text(encoding="utf-8"))
|
||||
assert data["project"] == "比赛/机器人"
|
||||
assert "headroom" in data.get("mcp_servers", {})
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# Tables another app appended inside our marker span
|
||||
# ----------------------------------------------------------------------
|
||||
|
||||
# The ChatGPT app's TOML writer appends its tables before the document's
|
||||
# trailing comment, which is our end marker when our span is last.
|
||||
_APP_TABLES = (
|
||||
"\n[mcp_servers.node_repl]\n"
|
||||
'command = "/Applications/ChatGPT.app/Contents/Resources/node_repl"\n'
|
||||
"\n[mcp_servers.node_repl.env]\n"
|
||||
'NODE_REPL_MODE = "browser"\n'
|
||||
)
|
||||
|
||||
|
||||
def _app_appends_inside_span(cfg: Path) -> None:
|
||||
end = "# --- end Headroom MCP server ---"
|
||||
cfg.write_text(cfg.read_text().replace(end, _APP_TABLES.lstrip("\n") + end))
|
||||
|
||||
|
||||
def test_unregister_keeps_app_table_inside_span(tmp_path: Path) -> None:
|
||||
reg = _make_registrar(tmp_path)
|
||||
cfg = _config_path(tmp_path)
|
||||
cfg.parent.mkdir()
|
||||
cfg.write_text('model = "gpt-5"\n')
|
||||
reg.register_server(_spec())
|
||||
_app_appends_inside_span(cfg)
|
||||
|
||||
assert reg.unregister_server("headroom") is True
|
||||
|
||||
data = tomllib.loads(cfg.read_text())
|
||||
assert "headroom" not in data["mcp_servers"]
|
||||
assert data["mcp_servers"]["node_repl"]["env"] == {"NODE_REPL_MODE": "browser"}
|
||||
assert data["model"] == "gpt-5"
|
||||
|
||||
|
||||
def test_register_force_keeps_app_table_inside_span(tmp_path: Path) -> None:
|
||||
reg = _make_registrar(tmp_path)
|
||||
cfg = _config_path(tmp_path)
|
||||
reg.register_server(_spec(env={"HEADROOM_PROXY_URL": "http://127.0.0.1:9999"}))
|
||||
_app_appends_inside_span(cfg)
|
||||
|
||||
assert reg.register_server(_spec(), force=True).status == RegisterStatus.REGISTERED
|
||||
|
||||
data = tomllib.loads(cfg.read_text())
|
||||
assert data["mcp_servers"]["headroom"].get("env") is None
|
||||
assert data["mcp_servers"]["node_repl"]["env"] == {"NODE_REPL_MODE": "browser"}
|
||||
# The app's table now sits outside our span, so the next unregister keeps it too.
|
||||
assert reg.unregister_server("headroom") is True
|
||||
assert "node_repl" in tomllib.loads(cfg.read_text())["mcp_servers"]
|
||||
|
||||
@@ -41,3 +41,18 @@ def test_register_uses_grok_home_env(monkeypatch: pytest.MonkeyPatch, tmp_path:
|
||||
config = grok_home / "config.toml"
|
||||
assert config.exists()
|
||||
assert "[mcp_servers.headroom]" in config.read_text()
|
||||
|
||||
|
||||
def test_unregister_keeps_foreign_table_inside_span(tmp_path: Path) -> None:
|
||||
"""A table another writer appended before our end marker survives unregister."""
|
||||
import tomllib
|
||||
|
||||
reg = _make_registrar(tmp_path)
|
||||
reg.register_server(_spec())
|
||||
cfg = tmp_path / ".grok" / "config.toml"
|
||||
end = "# --- end Headroom MCP server ---"
|
||||
cfg.write_text(cfg.read_text().replace(end, '[mcp_servers.other]\ncommand = "other"\n' + end))
|
||||
|
||||
assert reg.unregister_server("headroom") is True
|
||||
|
||||
assert tomllib.loads(cfg.read_text())["mcp_servers"] == {"other": {"command": "other"}}
|
||||
|
||||
Reference in New Issue
Block a user