Skip to content

The agent that grows with you

fix(acp): serialize late MCP refresh with turn start + self-sufficient agent-build wait

kshitijk4poor23c13589dd03
diff --git a/acp_adapter/server.py b/acp_adapter/server.py
index c762bbed84e..b234650de3d 100644
--- a/acp_adapter/server.py
+++ b/acp_adapter/server.py
@@ -1079,22 +1079,36 @@ class HermesACPAgent(acp.Agent):
if not join_mcp_discovery(timeout=30.0):
return
- # Session may have been closed while we waited.
- current = self.session_manager.get_session(session_id)
+ # Session may have been closed while we waited. In-memory-only
+ # lookup on purpose: ``get_session()`` falls through to a DB
+ # restore that builds a whole new AIAgent as a side effect just
+ # to decide "no-op" here (the TUI equivalent also checks its
+ # in-memory dict only).
+ with self.session_manager._lock:
+ current = self.session_manager._sessions.get(session_id)
if current is None or current.agent is not agent:
return
# Cache safety: never rebuild the tool list once the conversation
# has started — that would invalidate the cached prompt prefix.
- if (
- int(getattr(agent, "_user_turn_count", 0) or 0) > 0
- or int(getattr(agent, "_api_call_count", 0) or 0) > 0
- ):
- return
+ # Serialized with turn start: ``prompt()`` flips ``is_running``
+ # under ``runtime_lock`` before dispatching, so holding it here
+ # (and bailing when a turn is already running) closes the window
+ # where the guard passes but the first prompt starts before the
+ # refresh publishes — which would swap ``tools=`` mid-turn and
+ # break the just-created cache prefix.
+ with current.runtime_lock:
+ if current.is_running:
+ return
+ if (
+ int(getattr(agent, "_user_turn_count", 0) or 0) > 0
+ or int(getattr(agent, "_api_call_count", 0) or 0) > 0
+ ):
+ return
- from tools.mcp_tool import refresh_agent_mcp_tools
+ from tools.mcp_tool import refresh_agent_mcp_tools
- added = refresh_agent_mcp_tools(agent)
+ added = refresh_agent_mcp_tools(agent, quiet_mode=True)
if added:
logger.info(
"Session %s: late MCP refresh added %d tools: %s",
diff --git a/acp_adapter/session.py b/acp_adapter/session.py
index 65ca12cb0db..6e16016a6b3 100644
--- a/acp_adapter/session.py
+++ b/acp_adapter/session.py
@@ -655,13 +655,20 @@ class SessionManager:
# the agent snapshots tools once at build (run_agent/agent_init) and
# never re-reads the registry, so without this join a reachable-but-
# slow configured server would be invisible for the whole session.
- # Bounded by ``mcp_discovery_timeout`` (config.yaml, default ~1.5s) so a
- # dead server can't block — servers that miss the bound are picked up
- # by the automatic late-refresh (see HermesACPAgent._schedule_mcp_late_refresh).
+ # ``ensure_mcp_discovery_before_agent_build`` also (re)starts discovery
+ # when the entry.py spawn never ran or exited with zero connected
+ # servers (the retry-after-zero-connected allowance), making this
+ # construction site self-sufficient. Bounded by
+ # ``mcp_discovery_timeout`` (config.yaml, default ~1.5s) so a dead
+ # server can't block — servers that miss the bound are picked up by
+ # the automatic late-refresh (see HermesACPAgent._schedule_mcp_late_refresh).
try:
- from hermes_cli.mcp_startup import wait_for_mcp_discovery
+ from hermes_cli.mcp_startup import ensure_mcp_discovery_before_agent_build
- wait_for_mcp_discovery()
+ ensure_mcp_discovery_before_agent_build(
+ logger=logger,
+ thread_name="acp-mcp-discovery",
+ )
except Exception:
logger.debug("ACP: bounded MCP discovery wait failed", exc_info=True)
diff --git a/tests/acp_adapter/test_acp_mcp_discovery.py b/tests/acp_adapter/test_acp_mcp_discovery.py
index d190e626e41..5228f515851 100644
--- a/tests/acp_adapter/test_acp_mcp_discovery.py
+++ b/tests/acp_adapter/test_acp_mcp_discovery.py
@@ -262,3 +262,66 @@ def test_acp_late_refresh_skips_after_first_turn(monkeypatch):
time.sleep(0.5)
assert not refreshed, "late-refresh rebuilt tools after the first turn — cache broken!"
+
+
+# ---------------------------------------------------------------------------
+# Test 4 — late-refresh is serialized with turn start: skips while running
+# ---------------------------------------------------------------------------
+
+
+def test_acp_late_refresh_skips_while_turn_running(monkeypatch):
+ """A turn in flight (state.is_running) must block the rebuild even when
+ the agent's counters still read zero — closes the guard/turn-start race."""
+
+ discovery_block = threading.Event()
+
+ def _slow_discover():
+ discovery_block.wait(timeout=5.0)
+
+ monkeypatch.setitem(
+ sys.modules,
+ "hermes_cli.config",
+ _mod(
+ "hermes_cli.config",
+ read_raw_config=lambda: {"mcp_servers": {"slow": {"url": "https://mcp.example.test"}}},
+ ),
+ )
+ monkeypatch.setitem(
+ sys.modules,
+ "tools.mcp_oauth",
+ _mod("tools.mcp_oauth", suppress_interactive_oauth=lambda: nullcontext()),
+ )
+ monkeypatch.setitem(
+ sys.modules,
+ "tools.mcp_tool",
+ _mod("tools.mcp_tool", discover_mcp_tools=_slow_discover),
+ )
+
+ mcp_startup.start_background_mcp_discovery(
+ logger=SimpleNamespace(debug=lambda *_a, **_k: None),
+ thread_name="test-acp-running",
+ )
+
+ fake = FakeAgent() # counters are 0 — only is_running blocks the refresh
+ manager = SessionManager(agent_factory=lambda **_k: fake, db=NoopDb())
+ acp_agent = HermesACPAgent(session_manager=manager)
+ state = manager.create_session(cwd=".")
+ state.is_running = True # simulate: first prompt dispatched concurrently
+
+ refreshed = []
+
+ def _fake_refresh(agent, **_kw):
+ refreshed.append(agent)
+ return set()
+
+ monkeypatch.setitem(
+ sys.modules,
+ "tools.mcp_tool",
+ _mod("tools.mcp_tool", refresh_agent_mcp_tools=_fake_refresh),
+ )
+
+ acp_agent._schedule_mcp_late_refresh(state)
+ discovery_block.set()
+ time.sleep(0.5)
+
+ assert not refreshed, "late-refresh rebuilt tools while a turn was running!"