The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(mcp): respawn and retry once when a stdio child died
NATHAN Menkinb82862447977
diff --git a/tests/tools/test_mcp_stdio_fastfail_reconnect.py b/tests/tools/test_mcp_stdio_fastfail_reconnect.pyindex 80ae5119811..7b9a934a529 100644--- a/tests/tools/test_mcp_stdio_fastfail_reconnect.py+++ b/tests/tools/test_mcp_stdio_fastfail_reconnect.py@@ -1,16 +1,23 @@-"""Regression tests for stdio fast-fail reconnect signaling (#95626 salvage).+"""Regression tests for dead stdio subprocess recovery (#95626 salvage).The #81995 fast-fail gate detects a dead stdio subprocess but the transportfailure never cleared ``server.session``, so the transport-down reconnect path(which only fires when the session is gone/not-ready) never ran. The callfailed fast — correctly — but nothing asked the server task to respawn the-subprocess, so every subsequent call kept failing until the idle keepalive-probe eventually noticed. Both fast-fail sites must signal a reconnect:+subprocess (#95626 added the reconnect signal).-- pre-call gate (children already dead when the call arrives): return a clean- "reconnecting" tool error and set ``_reconnect_event``;-- mid-call watcher race (children die while the RPC is in flight): raise the- fast-fail TimeoutError and set ``_reconnect_event``.+Signalling alone still lost the call: a gateway restart kills every MCP stdio+child, and the first call from a surviving agent session (or a cron run+spanning the restart) failed in 0.00s while the subprocess was respawned+seconds later. Both fast-fail sites now respawn AND retry once:++- pre-call gate (children already dead when the call arrives);+- mid-call watcher race (children die while the RPC is in flight).++Both must recover transparently, and both must stop after ONE retry so a+server that keeps dying parks via run()'s rapid-drop budget instead of+hot-cycling respawns forever. The error text must never claim a timeout —+that wording is what misdirected the original investigation."""import asyncio@@ -23,10 +30,26 @@ import pytestpytest.importorskip("mcp")+def _success_result():+ result = MagicMock()+ result.is_error = False+ block = MagicMock()+ block.text = "ok"+ result.content = [block]+ result.structured_content = None+ result.meta = None+ return result++def _install_stub_server(mcp_tool_module, name: str, call_tool_impl,- *, children_dead):+ *, children_dead, on_reconnect=None):"""Fake MCP server with real-bool stdio liveness and a countable- reconnect event (mirrors tests/tools/test_mcp_circuit_breaker.py)."""+ reconnect event (mirrors tests/tools/test_mcp_circuit_breaker.py).++ ``on_reconnect`` runs on the MCP loop thread when the reconnect event is+ set — the hook tests use to simulate the server task respawning the+ subprocess and publishing a fresh session.+ """server = MagicMock()server.name = namesession = MagicMock()@@ -42,6 +65,8 @@ def _install_stub_server(mcp_tool_module, name: str, call_tool_impl,def set(self):self.set_calls += 1+ if on_reconnect is not None:+ on_reconnect(server)server._reconnect_event = _ReconnectAdapter()server._ready = ready_flag@@ -64,63 +89,171 @@ def _cleanup(mcp_tool_module, name: str) -> None:mcp_tool_module._server_breaker_opened_at.pop(name, None)-def test_precall_dead_children_signal_reconnect(monkeypatch, tmp_path):- """Dead-at-call-time subprocess → clean reconnecting error + reconnect- signal, instead of a bare fast-fail that leaves the server dead."""+def test_precall_dead_children_respawn_and_retry(monkeypatch, tmp_path):+ """Dead-at-call-time subprocess (the gateway-restart case): respawn,+ retry once, and hand the model a normal result — no error at all."""monkeypatch.setenv("HERMES_HOME", str(tmp_path))from tools import mcp_toolfrom tools.mcp_tool import _make_tool_handlercalled = {"n": 0}+ alive = {"v": False}async def _call_tool(*a, **kw):called["n"] += 1- return MagicMock(is_error=False, content=[])+ return _success_result()++ def _respawn(server):+ # What the server task does after a gateway restart: fresh child,+ # fresh session object, _ready re-armed.+ alive["v"] = True+ new_session = MagicMock()+ new_session.call_tool = _call_tool+ server.session = new_session+ server._ready.set()server = _install_stub_server(- mcp_tool, "srv-dead", _call_tool, children_dead=lambda: True+ mcp_tool, "srv-dead", _call_tool,+ children_dead=lambda: not alive["v"],+ on_reconnect=_respawn,)mcp_tool._ensure_mcp_loop()try:handler = _make_tool_handler("srv-dead", "tool1", 10.0)- result = handler({})- parsed = json.loads(result)- assert "error" in parsed, parsed- assert "reconnect" in parsed["error"].lower(), parsed+ parsed = json.loads(handler({}))+ assert "error" not in parsed, parsed+ assert parsed["result"] == "ok", parsedassert server._reconnect_event.set_calls == 1- assert called["n"] == 0, "RPC must not be attempted on a dead transport"- # The error payload flows through the handler's JSON parse, which- # bumps the breaker exactly once (no double-bump at the gate).- assert mcp_tool._server_error_counts.get("srv-dead", 0) == 1+ assert called["n"] == 1, "exactly one RPC — the retry after respawn"+ assert mcp_tool._server_error_counts.get("srv-dead", 0) == 0finally:_cleanup(mcp_tool, "srv-dead")-def test_midcall_child_exit_signals_reconnect(monkeypatch, tmp_path):- """Subprocess dies while the RPC is in flight → fast-fail error AND a- reconnect signal so the next call lands on a respawned transport."""+def test_midcall_child_exit_respawn_and_retry(monkeypatch, tmp_path):+ """Subprocess dies while the RPC is in flight → respawn and retry once,+ so the caller still gets its result."""monkeypatch.setenv("HERMES_HOME", str(tmp_path))from tools import mcp_toolfrom tools.mcp_tool import _make_tool_handler+ alive = {"v": True}+async def _hanging_call(*a, **kw):await asyncio.sleep(30)- server = _install_stub_server(- mcp_tool, "srv-midcall", _hanging_call, children_dead=lambda: False- )+ async def _good_call(*a, **kw):+ return _success_result()async def _watch_children():- return # children die immediately → watcher resolves first+ # Resolves immediately while the child is dead; never while alive.+ while alive["v"]:+ await asyncio.sleep(0.05)++ def _respawn(server):+ alive["v"] = True+ new_session = MagicMock()+ new_session.call_tool = _good_call+ server.session = new_session+ server._ready.set()+ server = _install_stub_server(+ mcp_tool, "srv-midcall", _hanging_call,+ children_dead=lambda: not alive["v"],+ on_reconnect=_respawn,+ )server._watch_stdio_children = _watch_childrenmcp_tool._ensure_mcp_loop()try:handler = _make_tool_handler("srv-midcall", "tool1", 10.0)- result = handler({})- parsed = json.loads(result)- assert "error" in parsed, parsed- assert "exited mid-call" in parsed["error"], parsed+ # The child dies once the RPC is in flight.+ alive["v"] = False+ parsed = json.loads(handler({}))+ assert "error" not in parsed, parsed+ assert parsed["result"] == "ok", parsedassert server._reconnect_event.set_calls == 1finally:_cleanup(mcp_tool, "srv-midcall")+++def test_dead_child_never_returning_is_not_reported_as_a_timeout(+ monkeypatch, tmp_path,+):+ """No fresh session inside the respawn window → a clean error that says+ the subprocess exited, never that something timed out (the+ old "failing the call fast instead of waiting 300s" wording sent the+ investigation into a healthy remote backend)."""+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ from tools import mcp_tool+ from tools.mcp_tool import _make_tool_handler++ monkeypatch.setattr(mcp_tool, "_STDIO_RESPAWN_WAIT_SEC", 1.0)+ called = {"n": 0}++ async def _call_tool(*a, **kw):+ called["n"] += 1+ return _success_result()++ server = _install_stub_server(+ mcp_tool, "srv-gone", _call_tool, children_dead=lambda: True,+ )+ mcp_tool._ensure_mcp_loop()+ try:+ handler = _make_tool_handler("srv-gone", "tool1", 300.0)+ parsed = json.loads(handler({}))+ assert "error" in parsed, parsed+ message = parsed["error"]+ assert "exited" in message, message+ for forbidden in ("TimeoutError", "300s", "timed out"):+ assert forbidden not in message, message+ assert server._reconnect_event.set_calls == 1+ assert called["n"] == 0, "RPC must not be attempted on a dead transport"+ assert mcp_tool._server_error_counts.get("srv-gone", 0) == 1+ finally:+ _cleanup(mcp_tool, "srv-gone")+++def test_child_dying_again_after_respawn_does_not_hot_cycle(+ monkeypatch, tmp_path,+):+ """A server whose child dies immediately after every respawn gets ONE+ retry per call, not an endless respawn loop — run()'s rapid-drop budget+ is what parks it, and this path must not fight that."""+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ from tools import mcp_tool+ from tools.mcp_tool import _make_tool_handler++ monkeypatch.setattr(mcp_tool, "_STDIO_RESPAWN_WAIT_SEC", 1.0)+ called = {"n": 0}++ async def _call_tool(*a, **kw):+ called["n"] += 1+ return _success_result()++ def _respawn_then_die(server):+ # Fresh session object (so the readiness wait succeeds) whose child+ # is already dead again by the time the retry dispatches.+ new_session = MagicMock()+ new_session.call_tool = _call_tool+ server.session = new_session+ server._ready.set()++ server = _install_stub_server(+ mcp_tool, "srv-flap", _call_tool,+ children_dead=lambda: True,+ on_reconnect=_respawn_then_die,+ )+ mcp_tool._ensure_mcp_loop()+ try:+ handler = _make_tool_handler("srv-flap", "tool1", 10.0)+ parsed = json.loads(handler({}))+ assert "error" in parsed, parsed+ assert "exited again" in parsed["error"], parsed+ assert "do NOT retry" in parsed["error"], parsed+ assert server._reconnect_event.set_calls == 1, (+ "one respawn request per tool call — never a retry loop"+ )+ assert called["n"] == 0+ assert mcp_tool._server_error_counts.get("srv-flap", 0) == 1+ finally:+ _cleanup(mcp_tool, "srv-flap")diff --git a/tools/mcp_tool.py b/tools/mcp_tool.pyindex bbd7f9a484b..0c3aeb8a181 100644--- a/tools/mcp_tool.py+++ b/tools/mcp_tool.py@@ -588,6 +588,13 @@ _MAX_BACKOFF_SECONDS = 60# can ever reach the circuit-breaker half-open probe or _signal_reconnect._PARKED_RETRY_INTERVAL = 300 # seconds between parked self-probes_RECYCLED_RECONNECT_TIMEOUT = 15.0+# How long a tool call waits for a respawned stdio child after its subprocess+# was found dead — a gateway restart kills every MCP stdio child,+# and the next call from a still-live session would otherwise fail for no real+# reason). Bounded: when the wait elapses the call reports the dead transport+# instead of looping, so a genuinely broken server still parks via the+# rapid-drop budget in run() rather than hot-cycling respawns.+_STDIO_RESPAWN_WAIT_SEC = 15.0# Jitter applied to reconnect backoff sleeps. Without it, every server that# lost the same backend retries in lockstep (thundering herd) and log lines# from N servers land in synchronized bursts.@@ -5234,6 +5241,123 @@ def _handle_session_expired_and_retry(return None+class _StdioChildExited(RuntimeError):+ """A server's stdio subprocess was gone when (or while) a call ran.++ Deliberately NOT a TimeoutError: nothing timed out — the child was+ already dead, usually because a gateway restart killed every MCP stdio+ subprocess out from under a still-live agent session. The old wording+ ("failing the call fast instead of waiting 300s") sent an investigation+ into the remote server for an afternoon; the server was healthy.++ Handled by :func:`_handle_stdio_child_exited_and_retry`, which respawns+ and retries the call once before any error reaches the model.+ """+++def _handle_stdio_child_exited_and_retry(+ server_name: str,+ exc: Exception,+ retry_call,+ op_description: str,+):+ """Respawn a dead stdio child and retry the call once.++ A gateway restart kills every MCP stdio subprocess. An agent session that+ outlives the restart still holds the dead child, so its next tool call+ used to fail in 0.00s — before anything reached the network — while the+ subprocess was respawned seconds later. Cron runs spanning a restart lost+ tool calls this way, silently.++ Why retrying here cannot hot-cycle respawns: this function never spawns+ anything. It sets ``_reconnect_event`` (one signal, same as before) and+ waits for the server task to publish a fresh session. Spawn frequency+ stays governed entirely by ``run()``'s rapid-drop budget, which parks a+ transport that keeps dropping without proving healthy (#62212). The retry+ is single-shot: a child that dies again immediately reports and stops,+ so a genuinely broken server converges on the park instead of looping.++ Returns:+ A JSON string when this was a dead-stdio failure (retry result, or a+ clean error), or ``None`` when ``exc`` is something else and the+ caller should use its generic error path.+ """+ if not isinstance(exc, _StdioChildExited):+ return None++ with _lock:+ srv = _servers.get(server_name)++ reconnected = False+ if srv is not None and hasattr(srv, "_reconnect_event"):+ logger.info(+ "MCP server '%s': %s found the stdio subprocess dead (%s); "+ "respawning and retrying once.",+ server_name, op_description, exc,+ )+ loop = _mcp_loop+ if loop is not None and loop.is_running():+ reconnected = _signal_reconnect_and_wait(+ server_name,+ srv,+ op_description=op_description,+ timeout=_STDIO_RESPAWN_WAIT_SEC,+ )+ else:+ # No MCP loop to wait on (non-async adapters, tests) — still ask+ # for the respawn so the next call lands on a live transport.+ _signal_reconnect(srv)++ if reconnected:+ try:+ result = retry_call()+ except _StdioChildExited as retry_exc:+ # Respawned and died again straight away: this is a broken+ # server, not a restart artifact. Stop here — run()'s budget+ # takes it to the park.+ logger.warning(+ "MCP server '%s': %s stdio subprocess exited again right "+ "after respawn (%s); not retrying further.",+ server_name, op_description, retry_exc,+ )+ _bump_server_error(server_name)+ return tool_error(+ f"MCP server '{server_name}' respawned its stdio subprocess "+ f"and it exited again immediately. The server is not "+ f"starting cleanly — do NOT retry this tool; ask the user to "+ f"check the server's command and its stderr log."+ )+ except Exception as retry_exc:+ logger.warning(+ "MCP %s/%s retry after stdio respawn failed: %s",+ server_name, op_description, retry_exc,+ )+ _bump_server_error(server_name)+ return tool_error(_sanitize_error(+ f"MCP call failed after respawning the stdio subprocess for "+ f"'{server_name}': {type(retry_exc).__name__}: "+ f"{_exc_str(retry_exc)}"+ ))+ try:+ parsed = json.loads(result)+ if "error" not in parsed:+ _reset_server_error(server_name)+ else:+ _bump_server_error(server_name)+ except (json.JSONDecodeError, TypeError):+ _reset_server_error(server_name)+ return result++ _bump_server_error(server_name)+ return tool_error(+ f"MCP server '{server_name}' stdio subprocess had exited (this is "+ f"not a timeout — the call never reached the server). A respawn was "+ f"requested but no fresh session came back within "+ f"{_STDIO_RESPAWN_WAIT_SEC:.0f}s. Wait a few seconds before retrying; "+ f"if it keeps failing the server is not starting and needs the user."+ )++# Exact raw server names whose ``supports_parallel_tool_calls`` config is True.# Raw identity matters: distinct names such as ``foo-bar`` and ``foo_bar`` both# sanitize to ``foo_bar`` but must not share policy.@@ -6181,21 +6305,13 @@ def _make_tool_handler(server_name: str, tool_name: str, tool_timeout: float):and _stdio_dead_result):# Dead children but stale server.session, so the- # transport-down path above never fired — signal the- # server task to respawn and return a clean- # reconnecting error. No explicit _bump_server_error:- # the error return flows through the handler's JSON- # parse, which already bumps once.- if _signal_reconnect(server):- return tool_error(- f"MCP server '{server_name}' stdio subprocess is "- f"dead and reconnect was requested. Do NOT retry "- f"immediately — give it a few seconds to respawn."- )- raise TimeoutError(- f"MCP stdio subprocess for '{server_name}' has "- f"exited; failing the call fast instead of "- f"waiting {float(tool_timeout):.0f}s"+ # transport-down path above never fired. Hand this to+ # the handler's respawn-and-retry path —+ # it is not a timeout, and a gateway restart that+ # killed the child must not cost the caller a call.+ raise _StdioChildExited(+ f"MCP stdio subprocess for '{server_name}' had "+ f"already exited when the call was dispatched")_call_coro = server.session.call_tool(tool_name, arguments=args)_watch_children = getattr(server, "_watch_stdio_children", None)@@ -6231,16 +6347,13 @@ def _make_tool_handler(server_name: str, tool_name: str, tool_timeout: float):# Same stale-session problem as the pre-call# gate above: the subprocess died mid-call but# nothing clears server.session, so without a- # reconnect signal the server would stay dead- # until the idle keepalive probe notices.- _signal_reconnect(server)- raise TimeoutError(- f"MCP stdio subprocess for '{server_name}' "- f"exited mid-call; failing the call fast "- f"instead of waiting "- f"{float(tool_timeout):.0f}s; reconnect "- f"requested — give it a few seconds to "- f"respawn before retrying"+ # reconnect the server would stay dead until+ # the idle keepalive probe notices. The+ # handler's respawn-and-retry path owns the+ # reconnect signal.+ raise _StdioChildExited(+ f"MCP stdio subprocess for "+ f"'{server_name}' exited mid-call")result = await rpc_taskfinally:@@ -6400,6 +6513,16 @@ def _make_tool_handler(server_name: str, tool_name: str, tool_timeout: float):except InterruptedError:return _interrupted_call_result()except Exception as exc:+ # Dead stdio child: respawn and retry once before any+ # error reaches the model — a gateway restart kills every MCP+ # subprocess, and the call it lands on is not really a failure.+ recovered = _handle_stdio_child_exited_and_retry(+ server_name, exc, _call_once,+ f"tools/call {tool_name}",+ )+ if recovered is not None:+ return recovered+# Auth-specific recovery path: consult the manager, signal# reconnect if viable, retry once. Returns None to fall# through for non-auth exceptions.