Skip to content

The agent that grows with you

fix(cli): no MCP, hook, webhook or maintenance work in the classic CLI process

Teknium46a5a6278e80
diff --git a/cli.py b/cli.py
index 375f42661d3..541e03dfc43 100644
--- a/cli.py
+++ b/cli.py
@@ -441,36 +441,20 @@ def _mark_tui_input_modes_active() -> None:
def _prepare_deferred_agent_startup() -> None:
- """Run Termux-deferred agent discovery before the first real agent turn."""
+ """Run Termux-deferred plugin discovery before the first real agent turn. MCP servers, shell
+ hooks and outbound webhooks belong to the gateway that runs the turn (session policy)."""
global _deferred_agent_startup_done
if _deferred_agent_startup_done:
return
if os.environ.get("HERMES_DEFER_AGENT_STARTUP") != "1":
return
_deferred_agent_startup_done = True
- _accept_hooks = os.environ.get("HERMES_ACCEPT_HOOKS", "").lower() in {"1", "true", "yes", "on"}
try:
from hermes_cli.plugins import discover_plugins
discover_plugins()
except Exception:
logger.warning("plugin discovery failed at deferred CLI startup", exc_info=True)
- try:
- from hermes_cli.mcp_startup import start_background_mcp_discovery
-
- start_background_mcp_discovery(logger=logger, thread_name="termux-cli-mcp-discovery")
- except Exception:
- logger.debug("MCP tool discovery failed at deferred CLI startup", exc_info=True)
- try:
- from agent.shell_hooks import register_from_config
- from agent.outbound_webhooks import register_from_config as register_outbound_webhooks
- from hermes_cli.config import load_config
-
- _hooks_cfg = load_config()
- register_from_config(_hooks_cfg, accept_hooks=_accept_hooks)
- register_outbound_webhooks(_hooks_cfg)
- except Exception:
- logger.debug("shell-hook registration failed at deferred CLI startup", exc_info=True)
_signal_watchdog_armed = False
diff --git a/hermes_cli/cli_agent_setup_mixin.py b/hermes_cli/cli_agent_setup_mixin.py
index 17e5e66cc3e..837614a04ff 100644
--- a/hermes_cli/cli_agent_setup_mixin.py
+++ b/hermes_cli/cli_agent_setup_mixin.py
@@ -637,9 +637,7 @@ class CLIAgentSetupMixin:
self._install_tool_callbacks()
if not self._ensure_runtime_credentials():
return False
- from hermes_cli.mcp_startup import ensure_mcp_discovery_before_agent_build
- ensure_mcp_discovery_before_agent_build(
- logger=logger, single_query=getattr(self, "_single_query_mode", False))
+ # No MCP discovery here: the gateway session that runs the turn owns its MCP servers.
from hermes_cli.cli_chat_error_copy import agent_init_failure_message
if self._session_db is None:
try:
diff --git a/hermes_cli/cli_init_mixin.py b/hermes_cli/cli_init_mixin.py
index 6858814e042..ffa9377479d 100644
--- a/hermes_cli/cli_init_mixin.py
+++ b/hermes_cli/cli_init_mixin.py
@@ -320,8 +320,7 @@ class CLIInitMixin:
self._init_ui_state()
def _init_session_store(self):
- """Open the session store early (so /title works before the first message) + opportunistic maintenance."""
- from cli import _run_checkpoint_auto_maintenance, _run_state_db_auto_maintenance
+ """Open the session store early (so /title works before the first message)."""
self._session_db = None
self._session_db_unavailable = False
try:
@@ -353,8 +352,7 @@ class CLIInitMixin:
# Same automatic diagnostic the gateway gates for its home channel (run_notifications).
from gateway.warning_notifications import render_notification
render_notification(_present_store_warning, platform="cli")
- _run_state_db_auto_maintenance(self._session_db)
- _run_checkpoint_auto_maintenance()
+ # No state.db / checkpoint maintenance here: the gateway (the single writer) runs both.
def _ensure_gateway_session(self):
"""Create (or resume) this CLI's gateway session and adopt the id it returns, before the banner
diff --git a/hermes_cli/cli_shutdown.py b/hermes_cli/cli_shutdown.py
index 74d45bc5bfc..724a7aba9d9 100644
--- a/hermes_cli/cli_shutdown.py
+++ b/hermes_cli/cli_shutdown.py
@@ -148,10 +148,11 @@ def _shutdown_cached_aux_clients() -> None:
# Ordered teardown steps (attribute names, resolved at call time so tests can patch them)
# and the exception class each swallows.
+# Async delegations and MCP servers live in the gateway, which owns their lifetime: a CLI exit
+# neither interrupts the delegations nor tears down MCP servers.
_CLEANUP_STEPS = (
("_stop_cli_wake_word", Exception), ("_cleanup_all_terminals", Exception),
- ("_interrupt_async_delegations", Exception), ("_cleanup_all_browsers", Exception),
- ("_shutdown_mcp_servers", BaseException), ("_shutdown_cached_aux_clients", Exception),
+ ("_cleanup_all_browsers", Exception), ("_shutdown_cached_aux_clients", Exception),
)
diff --git a/hermes_cli/main.py b/hermes_cli/main.py
index a228ab23307..38415a366b8 100644
--- a/hermes_cli/main.py
+++ b/hermes_cli/main.py
@@ -3004,6 +3004,10 @@ def _prepare_agent_startup(args) -> None:
"MCP tool discovery failed at CLI startup",
exc_info=True,
)
+ if _chat_runs_at_gateway(args):
+ # Shell hooks and outbound webhooks fire where the tools run: the gateway session registers
+ # them from its policy (``accept_hooks`` rides on session.create).
+ return
try:
from hermes_cli.config import load_config
from agent.shell_hooks import register_from_config
diff --git a/tests/hermes_cli/test_cli_startup_trim.py b/tests/hermes_cli/test_cli_startup_trim.py
new file mode 100644
index 00000000000..9c044247491
--- /dev/null
+++ b/tests/hermes_cli/test_cli_startup_trim.py
@@ -0,0 +1,108 @@
+"""Startup/exit work that belongs to the gateway never runs in the classic CLI's process.
+
+Rewired, every chat turn executes in the gateway session, which owns MCP servers, shell hooks,
+outbound webhooks, state.db / checkpoint maintenance and async delegations. The CLI process must
+not spawn a second copy of an MCP server, register hooks that never fire, run VACUUM as a second
+writer, or tear any of those down on exit.
+"""
+import sys
+import types
+from argparse import Namespace
+
+import pytest
+
+
+def _args(command):
+ return Namespace(accept_hooks=True, command=command, cron_command=None, gateway_command=None,
+ mcp_action=None, tui=False, yolo=False, safe_mode=False, ignore_user_config=False)
+
+
[email protected]("command", [None, "chat"])
+def test_chat_launch_registers_no_shell_hooks_or_webhooks(monkeypatch, command):
+ from hermes_cli import main as main_mod
+ calls = []
+ monkeypatch.setattr(main_mod, "_resolve_use_tui", lambda _a: False)
+ monkeypatch.setattr(main_mod, "_bypass_chat_launch", lambda _a: False, raising=False)
+ monkeypatch.setattr(main_mod, "_guard_noninteractive_user_config", lambda _a: None)
+ monkeypatch.setitem(sys.modules, "hermes_cli.plugins", types.SimpleNamespace(
+ discover_plugins=lambda: None, start_background_plugin_discovery=lambda: None))
+ monkeypatch.setitem(sys.modules, "agent.shell_hooks", types.SimpleNamespace(
+ register_from_config=lambda *a, **k: calls.append("hooks")))
+ monkeypatch.setitem(sys.modules, "agent.outbound_webhooks", types.SimpleNamespace(
+ register_from_config=lambda *a, **k: calls.append("webhooks")))
+ main_mod._prepare_agent_startup(_args(command))
+ assert calls == []
+
+
+def test_non_chat_agent_command_still_registers_hooks(monkeypatch):
+ from hermes_cli import main as main_mod
+ calls = []
+ monkeypatch.setitem(sys.modules, "hermes_cli.plugins", types.SimpleNamespace(
+ discover_plugins=lambda: None, start_background_plugin_discovery=lambda: None))
+ monkeypatch.setitem(sys.modules, "hermes_cli.config", types.SimpleNamespace(
+ load_config=dict, read_raw_config=dict))
+ monkeypatch.setitem(sys.modules, "agent.shell_hooks", types.SimpleNamespace(
+ register_from_config=lambda *a, **k: calls.append("hooks")))
+ monkeypatch.setitem(sys.modules, "agent.outbound_webhooks", types.SimpleNamespace(
+ register_from_config=lambda *a, **k: calls.append("webhooks")))
+ from hermes_cli import mcp_startup
+ monkeypatch.setattr(mcp_startup, "start_background_mcp_discovery", lambda **k: None)
+ main_mod._prepare_agent_startup(_args("rl"))
+ assert calls == ["hooks", "webhooks"]
+
+
+def test_deferred_startup_spawns_no_mcp_and_registers_no_hooks(monkeypatch):
+ import cli as cli_mod
+ calls = []
+ monkeypatch.setenv("HERMES_DEFER_AGENT_STARTUP", "1")
+ monkeypatch.setattr(cli_mod, "_deferred_agent_startup_done", False)
+ monkeypatch.setitem(sys.modules, "hermes_cli.plugins", types.SimpleNamespace(
+ discover_plugins=lambda: calls.append("plugins")))
+ from hermes_cli import mcp_startup
+ monkeypatch.setattr(mcp_startup, "start_background_mcp_discovery", lambda **k: calls.append("mcp"))
+ monkeypatch.setitem(sys.modules, "agent.shell_hooks", types.SimpleNamespace(
+ register_from_config=lambda *a, **k: calls.append("hooks")))
+ monkeypatch.setitem(sys.modules, "agent.outbound_webhooks", types.SimpleNamespace(
+ register_from_config=lambda *a, **k: calls.append("webhooks")))
+ cli_mod._prepare_deferred_agent_startup()
+ assert calls == ["plugins"]
+
+
+def test_init_agent_runs_no_mcp_discovery(monkeypatch):
+ import cli as cli_mod
+ from hermes_cli import gateway_agent
+ from hermes_cli import mcp_startup
+ calls = []
+ monkeypatch.setattr(mcp_startup, "ensure_mcp_discovery_before_agent_build", lambda **k: calls.append("mcp"))
+ monkeypatch.setattr(mcp_startup, "start_background_mcp_discovery", lambda **k: calls.append("mcp-bg"))
+ monkeypatch.setattr(gateway_agent, "GatewayAgent", lambda *_a, **_k: types.SimpleNamespace())
+ cli = cli_mod.HermesCLI(compact=True)
+ cli._session_db = object()
+ cli._resumed = False
+ cli.conversation_history = []
+ cli._install_tool_callbacks = lambda: None
+ cli._ensure_runtime_credentials = lambda: True
+ cli._ensure_gateway_session = lambda: None
+ assert cli._init_agent() is True
+ assert calls == []
+
+
+def test_session_store_open_runs_no_state_db_or_checkpoint_maintenance(monkeypatch):
+ import cli as cli_mod
+ from cli import HermesCLI
+ calls = []
+ monkeypatch.setattr(cli_mod, "_run_state_db_auto_maintenance", lambda db: calls.append("state.db"))
+ monkeypatch.setattr(cli_mod, "_run_checkpoint_auto_maintenance", lambda: calls.append("checkpoints"))
+ import tools.checkpoint_maintenance as ckpt
+ monkeypatch.setattr(ckpt, "auto_prune_from_config", lambda *a, **k: calls.append("checkpoints"))
+ cli = types.SimpleNamespace()
+ HermesCLI._init_session_store(cli)
+ assert calls == []
+
+
+def test_exit_cleanup_leaves_gateway_owned_mcp_and_delegations_alone():
+ from hermes_cli.cli_shutdown import _CLEANUP_STEPS
+ names = {name for name, _exc in _CLEANUP_STEPS}
+ assert "_shutdown_mcp_servers" not in names
+ assert "_interrupt_async_delegations" not in names
+ assert {"_cleanup_all_terminals", "_shutdown_cached_aux_clients"} <= names
diff --git a/tests/hermes_cli/test_mcp_discovery_timing.py b/tests/hermes_cli/test_mcp_discovery_timing.py
index bd4d7b9e5af..2c3fa5658a5 100644
--- a/tests/hermes_cli/test_mcp_discovery_timing.py
+++ b/tests/hermes_cli/test_mcp_discovery_timing.py
@@ -153,64 +153,8 @@ def test_ensure_helper_swallows_errors(monkeypatch):
# Should not raise
mcp_startup.ensure_mcp_discovery_before_agent_build(logger=logger)
-# ── oneshot ordering: discovery before AIAgent ──────────────────────────────
-
-# ── _init_agent ordering: discovery before AIAgent (CLI path) ───────────────
-
-def test_init_agent_forwards_single_query_flag(monkeypatch):
- """Single-query mode forwards single_query=True to the discovery wait."""
- import cli as cli_mod
-
- cli = cli_mod.HermesCLI(compact=True)
- cli._session_db = object()
- cli._resumed = False
- cli.conversation_history = []
- cli._install_tool_callbacks = lambda: None
- cli._ensure_runtime_credentials = lambda: True
- cli._single_query_mode = True
-
- seen = {}
-
- def _fake_ensure(*, logger, timeout=None, single_query=False, **_kw):
- seen["single_query"] = single_query
-
- monkeypatch.setattr(
- mcp_startup,
- "ensure_mcp_discovery_before_agent_build",
- _fake_ensure,
- )
- from hermes_cli import gateway_agent
- monkeypatch.setattr(gateway_agent, "GatewayAgent", lambda *_a, **_k: types.SimpleNamespace())
-
- assert cli._init_agent() is True
- assert seen.get("single_query") is True
-
-def test_init_agent_defaults_to_interactive(monkeypatch):
- """Without _single_query_mode, the helper uses interactive (short) bound."""
- import cli as cli_mod
-
- cli = cli_mod.HermesCLI(compact=True)
- cli._session_db = object()
- cli._resumed = False
- cli.conversation_history = []
- cli._install_tool_callbacks = lambda: None
- cli._ensure_runtime_credentials = lambda: True
-
- seen = {}
-
- def _fake_ensure(*, logger, timeout=None, single_query=False, **_kw):
- seen["single_query"] = single_query
-
- monkeypatch.setattr(
- mcp_startup,
- "ensure_mcp_discovery_before_agent_build",
- _fake_ensure,
- )
- from hermes_cli import gateway_agent
- monkeypatch.setattr(gateway_agent, "GatewayAgent", lambda *_a, **_k: types.SimpleNamespace())
-
- assert cli._init_agent() is True
- assert seen.get("single_query") is False
+# The classic CLI's _init_agent no longer waits on MCP discovery: the gateway session owns MCP
+# (tests/hermes_cli/test_cli_startup_trim.py).
# ── bounded wait: slow server doesn't freeze startup ────────────────────────