diff --git a/agent/codex_runtime.py b/agent/codex_runtime.py index c1e46e8a46042..6f22cde0bf942 100644 --- a/agent/codex_runtime.py +++ b/agent/codex_runtime.py @@ -396,8 +396,23 @@ def run_codex_app_server_turn( except Exception: logger.debug("codex tool-progress callback raised", exc_info=True) + codex_extra_args: list[str] = [] + try: + from hermes_cli.config import load_config + from hermes_cli.codex_runtime_plugin_migration import ( + build_runtime_mcp_enable_args, + ) + + codex_extra_args = build_runtime_mcp_enable_args(load_config()) + except Exception: + logger.debug( + "codex app-server: failed to build scoped MCP overrides", + exc_info=True, + ) + agent._codex_session = CodexAppServerSession( cwd=cwd, + extra_args=codex_extra_args, approval_callback=approval_callback, request_routing=_ServerRequestRouting( auto_approve_exec=auto_approve_requests, diff --git a/agent/transports/codex_app_server_session.py b/agent/transports/codex_app_server_session.py index e7600f3be0dd5..b1dbc17d46fce 100644 --- a/agent/transports/codex_app_server_session.py +++ b/agent/transports/codex_app_server_session.py @@ -204,6 +204,7 @@ class CodexAppServerSession: cwd: Optional[str] = None, codex_bin: str = "codex", codex_home: Optional[str] = None, + extra_args: Optional[list[str]] = None, permission_profile: Optional[str] = None, approval_callback: Optional[Callable[..., str]] = None, on_event: Optional[Callable[[dict], None]] = None, @@ -213,6 +214,7 @@ class CodexAppServerSession: self._cwd = cwd or os.getcwd() self._codex_bin = codex_bin self._codex_home = codex_home + self._extra_args = list(extra_args or []) self._permission_profile = ( permission_profile or _HERMES_TO_CODEX_PERMISSION_PROFILE.get( os.environ.get("HERMES_TERMINAL_SECURITY_MODE", "auto"), @@ -245,7 +247,9 @@ class CodexAppServerSession: return self._thread_id if self._client is None: self._client = self._client_factory( - codex_bin=self._codex_bin, codex_home=self._codex_home + codex_bin=self._codex_bin, + codex_home=self._codex_home, + extra_args=self._extra_args, ) self._client.initialize( client_name="hermes", diff --git a/hermes_cli/codex_runtime_plugin_migration.py b/hermes_cli/codex_runtime_plugin_migration.py index 4b30d3ebf261d..219c20b275b64 100644 --- a/hermes_cli/codex_runtime_plugin_migration.py +++ b/hermes_cli/codex_runtime_plugin_migration.py @@ -614,6 +614,7 @@ def migrate( discover_plugins: bool = True, default_permission_profile: Optional[str] = ":workspace", expose_hermes_tools: bool = True, + enable_mcp_by_default: bool = True, ) -> MigrationReport: """Translate Hermes mcp_servers config + Codex curated plugins into ~/.codex/config.toml. @@ -640,6 +641,11 @@ def migrate( memory, skills, etc.) as an MCP server in ~/.codex/config.toml so the codex subprocess can call back into Hermes for tools codex doesn't have built in. Set False to opt out. + enable_mcp_by_default: when False, write Hermes-managed MCP entries + disabled in the shared Codex config. Hermes' own app-server + subprocess enables only those entries with scoped ``-c`` + overrides, preventing unrelated Codex Desktop tasks from + spawning and retaining Hermes MCP subprocesses. """ report = MigrationReport(dry_run=dry_run) codex_home = codex_home or Path.home() / ".codex" @@ -662,6 +668,8 @@ def migrate( ) continue translated[str(name)] = out + if not enable_mcp_by_default: + out["enabled"] = False if skipped: report.skipped_keys_per_server[str(name)] = skipped report.migrated.append(str(name)) @@ -695,6 +703,8 @@ def migrate( # and is launched on demand by codex (stdio MCP). if expose_hermes_tools: translated["hermes-tools"] = _build_hermes_tools_mcp_entry() + if not enable_mcp_by_default: + translated["hermes-tools"]["enabled"] = False if "hermes-tools" not in report.migrated: report.migrated.append("hermes-tools") @@ -755,3 +765,34 @@ def migrate( except Exception as exc: report.errors.append(f"could not write {target}: {exc}") return report + + +def build_runtime_mcp_enable_args( + hermes_config: dict, + *, + expose_hermes_tools: bool = True, +) -> list[str]: + """Return Codex ``-c`` overrides for MCPs owned by a Hermes runtime. + + The shared ``~/.codex/config.toml`` keeps these entries disabled so + Codex Desktop tasks do not inherit Hermes' process-heavy MCP surface. + A Hermes-owned app-server process opts back into the enabled subset. + """ + names: set[str] = set() + servers = (hermes_config or {}).get("mcp_servers") or {} + if isinstance(servers, dict): + for raw_name, cfg in servers.items(): + if not isinstance(cfg, dict) or cfg.get("enabled") is False: + continue + translated, _skipped = _translate_one_server(str(raw_name), cfg) + if translated is not None: + names.add(str(raw_name)) + if expose_hermes_tools: + names.add("hermes-tools") + + args: list[str] = [] + for name in sorted(names): + args.extend( + ["-c", f"mcp_servers.{_quote_key(name)}.enabled=true"] + ) + return args diff --git a/hermes_cli/codex_runtime_switch.py b/hermes_cli/codex_runtime_switch.py index 06bff58e2e1d7..92dcac98d6d74 100644 --- a/hermes_cli/codex_runtime_switch.py +++ b/hermes_cli/codex_runtime_switch.py @@ -206,13 +206,14 @@ def apply( if ok: msg_lines.append(f"codex CLI: {ver}") # Auto-migrate Hermes' MCP servers + Codex's installed curated - # plugins into ~/.codex/config.toml so the spawned codex subprocess - # sees the same tool surface AND can call back into Hermes for - # browser/web/delegate_task/vision/memory tools (#7 fix). + # plugins into ~/.codex/config.toml. Hermes-owned MCP entries are + # disabled in this shared config so unrelated Codex Desktop tasks do + # not spawn them; Hermes' own app-server process enables the scoped + # subset with per-process config overrides. # Failures are non-fatal — the runtime change still proceeds. try: from hermes_cli.codex_runtime_plugin_migration import migrate - mig_report = migrate(config) + mig_report = migrate(config, enable_mcp_by_default=False) # Tools/MCP servers (excluding the hermes-tools callback, # which is internal plumbing — surface separately). user_servers = [ diff --git a/tests/agent/transports/test_codex_app_server_session.py b/tests/agent/transports/test_codex_app_server_session.py index 6c620ec595196..c1c29ee30f1dd 100644 --- a/tests/agent/transports/test_codex_app_server_session.py +++ b/tests/agent/transports/test_codex_app_server_session.py @@ -113,6 +113,26 @@ def make_session(client: FakeClient, **kwargs) -> CodexAppServerSession: ) +def test_session_forwards_scoped_codex_args_to_client_factory(): + client = FakeClient() + captured = {} + + def factory(**kwargs): + captured.update(kwargs) + return client + + session = CodexAppServerSession( + cwd="/tmp", + extra_args=["-c", "mcp_servers.hermes-tools.enabled=true"], + client_factory=factory, + ) + session.ensure_started() + + assert captured["extra_args"] == [ + "-c", "mcp_servers.hermes-tools.enabled=true" + ] + + # ---- choice mapping ---- class TestApprovalChoiceMapping: diff --git a/tests/hermes_cli/test_codex_runtime_plugin_migration.py b/tests/hermes_cli/test_codex_runtime_plugin_migration.py index fc6df86c852c3..d1a6b95aac747 100644 --- a/tests/hermes_cli/test_codex_runtime_plugin_migration.py +++ b/tests/hermes_cli/test_codex_runtime_plugin_migration.py @@ -9,6 +9,7 @@ from hermes_cli.codex_runtime_plugin_migration import ( MIGRATION_MARKER, MIGRATION_END_MARKER, _build_hermes_tools_mcp_entry, + build_runtime_mcp_enable_args, _format_toml_value, _looks_like_test_tempdir, _strip_existing_managed_block, @@ -309,6 +310,37 @@ class TestStripExistingManagedBlock: # ---- end-to-end migrate(, expose_hermes_tools=False) ---- class TestMigrate: + def test_shared_config_can_disable_hermes_mcp_defaults(self, tmp_path): + migrate( + {"mcp_servers": {"custom": {"command": "custom-mcp"}}}, + codex_home=tmp_path, + discover_plugins=False, + default_permission_profile=None, + expose_hermes_tools=True, + enable_mcp_by_default=False, + ) + text = (tmp_path / "config.toml").read_text() + assert "[mcp_servers.custom]" in text + assert "[mcp_servers.hermes-tools]" in text + assert text.count("enabled = false") == 2 + + def test_runtime_overrides_enable_only_valid_enabled_hermes_mcps(self): + args = build_runtime_mcp_enable_args( + { + "mcp_servers": { + "alpha": {"command": "alpha-mcp"}, + "disabled": {"command": "disabled-mcp", "enabled": False}, + "broken": {"description": "no transport"}, + "quoted.name": {"command": "quoted-mcp"}, + } + } + ) + assert args == [ + "-c", "mcp_servers.alpha.enabled=true", + "-c", "mcp_servers.hermes-tools.enabled=true", + "-c", 'mcp_servers."quoted.name".enabled=true', + ] + def test_no_servers_no_plugins_no_perms_writes_placeholder(self, tmp_path): report = migrate({}, codex_home=tmp_path, discover_plugins=False, diff --git a/tests/run_agent/test_codex_app_server_integration.py b/tests/run_agent/test_codex_app_server_integration.py index c88d45c483af1..5fd4ca2984f98 100644 --- a/tests/run_agent/test_codex_app_server_integration.py +++ b/tests/run_agent/test_codex_app_server_integration.py @@ -377,6 +377,40 @@ class TestRunConversationCodexPath: assert captured["cwd"] == str(tmp_path) + def test_codex_session_receives_scoped_hermes_mcp_overrides(self, monkeypatch): + from agent.transports.codex_app_server_session import ( + CodexAppServerSession, TurnResult, + ) + + captured = {} + + def fake_init(self, **kwargs): + captured.update(kwargs) + self._thread_id = "thread-stub-1" + + def fake_run_turn(self, user_input: str, **kwargs): + return TurnResult( + final_text="ok", + projected_messages=[{"role": "assistant", "content": "ok"}], + turn_id="turn-stub-1", + thread_id="thread-stub-1", + ) + + monkeypatch.setattr(CodexAppServerSession, "__init__", fake_init) + monkeypatch.setattr(CodexAppServerSession, "run_turn", fake_run_turn) + monkeypatch.setattr( + "hermes_cli.codex_runtime_plugin_migration.build_runtime_mcp_enable_args", + lambda config: ["-c", "mcp_servers.hermes-tools.enabled=true"], + ) + + agent = _make_codex_agent() + with patch.object(agent, "_spawn_background_review", return_value=None): + agent.run_conversation("hi") + + assert captured["extra_args"] == [ + "-c", "mcp_servers.hermes-tools.enabled=true" + ] + def _capture_routing_agent(self, monkeypatch): """Build a codex agent with a CodexAppServerSession stub that captures the request_routing passed at construction time, so we can assert how @@ -769,4 +803,3 @@ class TestCodexToolProgressBridge: assert "on_event" in captured_init and captured_init["on_event"] is not None assert ("tool.started", "exec_command", "pytest") in events -