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.
Python agentaianthropicclaude-codecompressioncontext-engineeringcontext-windowcursorfastapilangchainllmmcpopenaiprompt-engineeringproxypythonragtoken-optimizationtokenstypescript
fix: sync Codex MCP proxy config during wrap
Tejas Chopraac1d11c9a2a9
diff --git a/headroom/cli/wrap.py b/headroom/cli/wrap.pyindex 0d4019520..ea54e4d76 100644--- a/headroom/cli/wrap.py+++ b/headroom/cli/wrap.py@@ -242,7 +242,9 @@ def _setup_rtk(verbose: bool = False) -> Path | None:return rtk_path-def _setup_headroom_mcp(registrar: Any, port: int, *, verbose: bool = False) -> None:+def _setup_headroom_mcp(+ registrar: Any, port: int, *, verbose: bool = False, force: bool = False+) -> None:"""Register the headroom MCP server with the given agent (idempotent).The proxy compresses tool_result payloads and emits ``[Retrieve more:@@ -261,7 +263,7 @@ def _setup_headroom_mcp(registrar: Any, port: int, *, verbose: bool = False) ->proxy_url = f"http://127.0.0.1:{port}"spec = build_headroom_spec(proxy_url)- result = registrar.register_server(spec)+ result = registrar.register_server(spec, force=force)line = format_result(registrar.name,@@ -1797,7 +1799,10 @@ def codex(if not no_mcp:from headroom.mcp_registry import CodexRegistrar- _setup_headroom_mcp(CodexRegistrar(), port, verbose=verbose)+ # Codex starts a long-lived local MCP subprocess from config.toml.+ # If a previous wrap used another port, retrieval can silently point+ # at the wrong proxy while model traffic uses the right one.+ _setup_headroom_mcp(CodexRegistrar(), port, verbose=verbose, force=True)elif verbose:click.echo(" Skipping MCP retrieve tool (--no-mcp)")diff --git a/headroom/mcp_registry/codex.py b/headroom/mcp_registry/codex.pyindex 460f7e5e5..5dcd4771e 100644--- a/headroom/mcp_registry/codex.py+++ b/headroom/mcp_registry/codex.py@@ -75,7 +75,19 @@ class CodexRegistrar(MCPRegistrar):return RegisterResult(RegisterStatus.MISMATCH, _diff_specs(existing, spec))if existing is not None and force:- # Drop any prior block (ours or user's) before re-writing.+ content = self._read_text()+ if _MARKER_START not in content:+ # Even force=True is only allowed to replace blocks that+ # Headroom owns. Otherwise appending our table would create a+ # duplicate [mcp_servers.<name>] TOML section and may clobber a+ # user-managed integration.+ return RegisterResult(+ RegisterStatus.MISMATCH,+ "user-managed [mcp_servers."+ f"{spec.name}] entry outside Headroom markers; "+ f"{_diff_specs(existing, spec)}",+ )+ # Drop any prior Headroom block before re-writing.self.unregister_server(spec.name)return self._write_block(spec)diff --git a/headroom/proxy/handlers/openai.py b/headroom/proxy/handlers/openai.pyindex 943994881..8a40e8d60 100644--- a/headroom/proxy/handlers/openai.py+++ b/headroom/proxy/handlers/openai.py@@ -2068,6 +2068,14 @@ class OpenAIHandlerMixin:if session_handle is not None:session_handle.upstream_url = upstream_url+ logger.info(+ "[%s] WS /v1/responses accepted (route=%s, auth_mode=%s, subprotocols=%s)",+ request_id,+ "chatgpt_subscription" if is_chatgpt_auth else "openai_api",+ classify_auth_mode(ws_headers).value,+ client_subprotocols,+ )+# Ensure Authorization header is present — fall back to OPENAI_API_KEY env var.# Safety net for clients that don't forward auth headers via WebSocket upgrade.if "authorization" not in _lower_headers:@@ -2442,6 +2450,15 @@ class OpenAIHandlerMixin:_ws_auth_mode.value,transforms_applied,)+ else:+ logger.info(+ "[%s] WS /v1/responses first frame passthrough "+ "(%d bytes, auth_mode=%s, model=%s)",+ request_id,+ len(_inner_bytes),+ _ws_auth_mode.value,+ _model or "unknown",+ )except Exception as _ce:logger.warning(f"[{request_id}] WS /v1/responses compression failed; "diff --git a/tests/test_cli/test_wrap_codex.py b/tests/test_cli/test_wrap_codex.pyindex b5e612232..b04168acd 100644--- a/tests/test_cli/test_wrap_codex.py+++ b/tests/test_cli/test_wrap_codex.py@@ -358,6 +358,34 @@ def test_wrap_codex_prepare_only_creates_backup_and_config(assert backup.read_text() == original+def test_wrap_codex_prepare_only_updates_stale_mcp_proxy_url(+ runner: CliRunner, monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ _set_test_home(monkeypatch, tmp_path)+ config_file = tmp_path / ".codex" / "config.toml"+ config_file.parent.mkdir(parents=True)+ config_file.write_text(+ "# --- Headroom MCP server ---\n"+ "[mcp_servers.headroom]\n"+ 'command = "headroom"\n'+ 'args = ["mcp", "serve"]\n'+ "\n"+ "[mcp_servers.headroom.env]\n"+ 'HEADROOM_PROXY_URL = "http://127.0.0.1:9000"\n'+ "# --- end Headroom MCP server ---\n"+ )++ with patch("headroom.cli.wrap._ensure_rtk_binary", return_value=None):+ result = runner.invoke(main, ["wrap", "codex", "--prepare-only", "--port", "8787"])++ assert result.exit_code == 0, result.output+ content = config_file.read_text()+ assert "[mcp_servers.headroom]" in content+ assert 'command = "headroom"' in content+ assert 'args = ["mcp", "serve"]' in content+ assert "http://127.0.0.1:9000" not in content++def test_unwrap_codex_restores_prior_config_end_to_end(runner: CliRunner, monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:diff --git a/tests/test_mcp_registry/test_codex_registrar.py b/tests/test_mcp_registry/test_codex_registrar.pyindex 53ad0761e..aca53f89e 100644--- a/tests/test_mcp_registry/test_codex_registrar.py+++ b/tests/test_mcp_registry/test_codex_registrar.py@@ -178,6 +178,21 @@ def test_register_force_overwrites_block(tmp_path: Path) -> None:assert "9999" not in text+def test_register_force_preserves_user_managed_entry(tmp_path: Path) -> None:+ cfg = _config_path(tmp_path)+ cfg.parent.mkdir()+ cfg.write_text(+ '[mcp_servers.headroom]\ncommand = "/usr/local/bin/custom-headroom"\nargs = ["serve"]\n'+ )++ result = _make_registrar(tmp_path).register_server(_spec(), force=True)++ assert result.status == RegisterStatus.MISMATCH+ assert "user-managed" in (result.detail or "").lower()+ assert "/usr/local/bin/custom-headroom" in cfg.read_text()+ assert cfg.read_text().count("[mcp_servers.headroom]") == 1++def test_register_mismatch_when_user_managed_outside_markers(tmp_path: Path) -> None:cfg = _config_path(tmp_path)cfg.parent.mkdir()