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.

fix(mcp): keep other apps' tables when replacing the Codex/Grok MCP span (#3877)

gglucassd0fd56e4910c
diff --git a/headroom/mcp_registry/codex.py b/headroom/mcp_registry/codex.py
index 2c4bdd591..2718ebf56 100644
--- a/headroom/mcp_registry/codex.py
+++ b/headroom/mcp_registry/codex.py
@@ -43,6 +43,81 @@ def _marker_end(server_name: str) -> str:
return f"# --- end Headroom MCP server: {server_name} ---"
+def _table_path(line: str) -> list[str] | None:
+ """Key path of a ``[table]`` or ``[[array]]`` header line, else ``None``.
+
+ Parsed by tomllib so quoted keys (``[mcp_servers."foo#bar"]``) and trailing
+ comments are read as TOML reads them. Only a header line starts with ``[``
+ and parses on its own; a continuation line of a multi-line array does not.
+ """
+ if not line.lstrip().startswith("["):
+ return None
+ try:
+ node: Any = tomllib.loads(line)
+ except tomllib.TOMLDecodeError:
+ return None
+ path: list[str] = []
+ while isinstance(node, dict) and node:
+ key, node = next(iter(node.items()))
+ path.append(key)
+ return path
+
+
+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>`` and its subtables is moved, byte
+ for byte and in order, to just after the end marker. This is a line-level
+ move, so a header-like line inside a multi-line string can split a table
+ wrongly; callers must check the final result with ``_only_server_changed``.
+ """
+ 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
+ kept: list[str] = []
+ foreign: list[str] = []
+ in_foreign = False
+ for line in lines[i + 1 : j]:
+ path = _table_path(line)
+ if path is not None:
+ in_foreign = path[:2] != ["mcp_servers", server_name]
+ (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"
+ return "".join(lines[: i + 1] + kept + [end_line] + foreign + lines[j + 1 :])
+
+
+def _without_server(data: dict[str, Any], server_name: str) -> dict[str, Any]:
+ servers = data.get("mcp_servers")
+ if not isinstance(servers, dict):
+ return data
+ rest = {k: v for k, v in data.items() if k != "mcp_servers"}
+ others = {k: v for k, v in servers.items() if k != server_name}
+ return {**rest, "mcp_servers": others} if others else rest
+
+
+def _only_server_changed(old: str, new: str, server_name: str) -> bool:
+ """True when ``new`` parses to ``old`` apart from ``mcp_servers.<server_name>``.
+
+ The fail-closed guard for every rewrite of the marker span: a foreign table
+ that could not be moved out of the span, or a file that does not parse,
+ makes this False and the rewrite is refused instead of written.
+ """
+ try:
+ before, after = tomllib.loads(old), tomllib.loads(new)
+ except tomllib.TOMLDecodeError:
+ return False
+ return _without_server(before, server_name) == _without_server(after, server_name)
+
+
class CodexRegistrar(MCPRegistrar):
"""Register MCP servers with the OpenAI Codex CLI."""
@@ -132,9 +207,10 @@ 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)
+ 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:
@@ -148,6 +224,14 @@ class CodexRegistrar(MCPRegistrar):
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:
@@ -207,9 +291,10 @@ 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)
+ 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)
@@ -224,6 +309,12 @@ class CodexRegistrar(MCPRegistrar):
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(
diff --git a/headroom/mcp_registry/grok.py b/headroom/mcp_registry/grok.py
index 37ee764c8..b7363ab0c 100644
--- a/headroom/mcp_registry/grok.py
+++ b/headroom/mcp_registry/grok.py
@@ -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, _only_server_changed
if sys.version_info >= (3, 11):
import tomllib
@@ -103,9 +104,10 @@ 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)
+ 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:
@@ -119,6 +121,14 @@ class GrokRegistrar(MCPRegistrar):
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:
@@ -141,9 +151,10 @@ 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)
+ 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)
@@ -158,6 +169,12 @@ class GrokRegistrar(MCPRegistrar):
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(
diff --git a/tests/test_mcp_registry/test_codex_registrar.py b/tests/test_mcp_registry/test_codex_registrar.py
index efe3cb58f..008dfac92 100644
--- a/tests/test_mcp_registry/test_codex_registrar.py
+++ b/tests/test_mcp_registry/test_codex_registrar.py
@@ -440,3 +440,87 @@ 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, tables: str = _APP_TABLES.lstrip("\n")) -> None:
+ end = "# --- end Headroom MCP server ---"
+ cfg.write_text(cfg.read_text().replace(end, tables + end))
+
+
+# A foreign multi-line string holding a line that reads as our header: the
+# line-level move splits the table wrongly, so the rewrite must be refused.
+_UNSPLITTABLE = '[notes]\ntext = """\n[mcp_servers.headroom.env]\n"""\n'
+
+
+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"]
+
+
+def test_unregister_keeps_quoted_key_table_inside_span(tmp_path: Path) -> None:
+ # The `#` in a quoted key is not a comment.
+ reg = _make_registrar(tmp_path)
+ cfg = _config_path(tmp_path)
+ reg.register_server(_spec())
+ _app_appends_inside_span(cfg, '[mcp_servers."foo#bar"]\ncommand = "foreign"\n')
+ assert set(tomllib.loads(cfg.read_text())["mcp_servers"]) == {"headroom", "foo#bar"}
+
+ assert reg.unregister_server("headroom") is True
+
+ assert tomllib.loads(cfg.read_text())["mcp_servers"] == {"foo#bar": {"command": "foreign"}}
+
+
[email protected]("inside_span", [_UNSPLITTABLE, "broken =\n"])
+def test_refuses_span_rewrite_that_would_change_other_entries(
+ tmp_path: Path, inside_span: str
+) -> 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, inside_span)
+ before = cfg.read_text()
+
+ assert reg.unregister_server("headroom") is False
+ assert reg.register_server(_spec(), force=True).status == RegisterStatus.FAILED
+ assert cfg.read_text() == before
diff --git a/tests/test_mcp_registry/test_grok_registrar.py b/tests/test_mcp_registry/test_grok_registrar.py
index c09058917..72a2e3d37 100644
--- a/tests/test_mcp_registry/test_grok_registrar.py
+++ b/tests/test_mcp_registry/test_grok_registrar.py
@@ -41,3 +41,55 @@ 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"}}
+
+
+def _insert_before_end(cfg: Path, text: str) -> None:
+ end = "# --- end Headroom MCP server ---"
+ cfg.write_text(cfg.read_text().replace(end, text + end))
+
+
+def test_unregister_keeps_quoted_key_table_inside_span(tmp_path: Path) -> None:
+ import tomllib
+
+ reg = _make_registrar(tmp_path)
+ reg.register_server(_spec())
+ cfg = tmp_path / ".grok" / "config.toml"
+ _insert_before_end(cfg, '[mcp_servers."foo#bar"]\ncommand = "foreign"\n')
+
+ assert reg.unregister_server("headroom") is True
+
+ assert tomllib.loads(cfg.read_text())["mcp_servers"] == {"foo#bar": {"command": "foreign"}}
+
+
+ "inside_span",
+ ['[notes]\ntext = """\n[mcp_servers.headroom.env]\n"""\n', "broken =\n"],
+)
+def test_refuses_span_rewrite_that_would_change_other_entries(
+ tmp_path: Path, inside_span: str
+) -> None:
+ reg = _make_registrar(tmp_path)
+ reg.register_server(_spec())
+ cfg = tmp_path / ".grok" / "config.toml"
+ _insert_before_end(cfg, inside_span)
+ before = cfg.read_text()
+
+ assert reg.unregister_server("headroom") is False
+ moved = ServerSpec(name="headroom", command="/opt/python", args=_spec().args)
+ assert reg.register_server(moved, force=True).status == RegisterStatus.FAILED
+ assert cfg.read_text() == before