The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(tools): stop treating a post-registration reconnect drop as an initial-connect failure
chelsealongc7673f322bb9
diff --git a/tests/tools/test_mcp_tool.py b/tests/tools/test_mcp_tool.pyindex fb90614fe22..46ddf6db453 100644--- a/tests/tools/test_mcp_tool.py+++ b/tests/tools/test_mcp_tool.py@@ -1421,6 +1421,73 @@ class TestReconnection:asyncio.run(_test())+ def test_reconnect_failures_after_initial_success_use_reconnect_budget(self):+ """A server that already registered tools must not be re-classified+ as "never connected" just because a later reconnect attempt fails+ while ``_ready`` is momentarily clear (#94654).++ ``_MAX_INITIAL_CONNECT_RETRIES`` is 3 and ``_MAX_RECONNECT_RETRIES``+ is 5. Four consecutive post-success reconnect failures exceed the+ (buggy) initial-connect ladder but not the reconnect budget, so this+ distinguishes the two code paths.+ """+ from tools.mcp_tool import MCPServerTask++ run_count = 0+ target_server = None++ async def patched_run_stdio(self_srv, config):+ nonlocal run_count, target_server+ run_count += 1+ if target_server is not self_srv:+ return None+ if run_count == 1:+ # Initial connection succeeds and registers tools. Setting+ # ``_ever_connected`` mirrors what the real ``_run_stdio``+ # does right after a successful ``_discover_tools()`` call;+ # guarded because the pre-fix class has no such slot.+ self_srv.session = MagicMock()+ self_srv._tools = []+ self_srv._ready.set()+ try:+ self_srv._ever_connected = True+ except AttributeError:+ pass+ return "reconnect"+ if run_count <= 5:+ # Four consecutive failures on later reconnect attempts --+ # a flapping transport, not a server that never connected.+ raise ConnectionError("reconnect attempt failed")+ self_srv._shutdown_event.set()+ await self_srv._shutdown_event.wait()++ async def patched_wait_parked(self_srv, timeout=None):+ # If the code under test parks early, unblock immediately+ # instead of waiting out the real park interval.+ self_srv._shutdown_event.set()+ return "shutdown"++ async def _test():+ nonlocal target_server+ server = MCPServerTask("test_srv")+ target_server = server++ with patch.object(MCPServerTask, "_run_stdio", patched_run_stdio), \+ patch.object(+ MCPServerTask, "_wait_for_reconnect_or_shutdown",+ patched_wait_parked,+ ), \+ patch("asyncio.sleep", new_callable=AsyncMock):+ await server.run({"command": "test"})++ assert server._was_parked is False, (+ "server parked after only 4 reconnect failures following a "+ "successful initial connection -- it was misclassified as "+ "never having connected and re-entered the initial-connect "+ "ladder instead of the (larger) reconnect budget"+ )++ asyncio.run(_test())def test_preflight_probe_runs_on_initial_http_connect(self):"""The content-type preflight probe fires on the first HTTP connect."""diff --git a/tools/mcp_tool.py b/tools/mcp_tool.pyindex 13e304bbd24..4f9078aaaa6 100644--- a/tools/mcp_tool.py+++ b/tools/mcp_tool.py@@ -2396,6 +2396,7 @@ class MCPServerTask:"_reconnect_retries", "_session_proven", "_was_parked","_inflight_tasks", "_reconnecting", "_suspect_reason","_teardown_race", "_permanent_grace_used", "_stdio_child_pids",+ "_ever_connected",)def __init__(self, name: str):@@ -2426,6 +2427,12 @@ class MCPServerTask:# keeps getting charged and still reaches the park instead of# hot-cycling respawns forever.self._session_proven: bool = False+ # Set once tools have ever been registered and never cleared again,+ # unlike ``_ready`` (which is cleared on every reconnect cycle). Used+ # to tell a genuine first-connection failure from a later reconnect+ # failure that merely happens to occur while ``_ready`` is+ # momentarily clear — see the ``initial_retries`` ladder in run().+ self._ever_connected: bool = False# True while parked (reconnect budget exhausted) or after a park,# until the session proves healthy again — used to log the# parked→revived transition exactly once.@@ -3335,6 +3342,7 @@ class MCPServerTask:self._mark_lifecycle_started()await self._discover_tools()self._ready.set()+ self._ever_connected = True# Session is live again: clear any breaker state from a# prior outage so the first call after recovery isn't# gated on a stale consecutive-failure count (#16788).@@ -3706,6 +3714,7 @@ class MCPServerTask:self.session = sessionawait self._discover_tools()self._ready.set()+ self._ever_connected = True# Session is live again: clear any breaker state from a# prior outage so the first call after recovery isn't# gated on a stale consecutive-failure count (#16788).@@ -3771,6 +3780,7 @@ class MCPServerTask:self.session = sessionawait self._discover_tools()self._ready.set()+ self._ever_connected = True# Session is live again: clear any breaker state from# a prior outage so the first call after recovery# isn't gated on a stale failure count (#16788).@@ -3818,6 +3828,7 @@ class MCPServerTask:self.session = sessionawait self._discover_tools()self._ready.set()+ self._ever_connected = True# Session is live again: clear any breaker state from a# prior outage so the first call after recovery isn't# gated on a stale consecutive-failure count (#16788).@@ -4116,9 +4127,14 @@ class MCPServerTask:# If this is the first connection attempt, retry with backoff# before giving up. A transient DNS/network blip at startup- # should not permanently kill the server.+ # should not permanently kill the server. Gated on+ # ``_ever_connected`` rather than ``_ready`` — ``_ready`` is+ # cleared on every reconnect cycle (see below), so a server+ # that already registered tools once and then dropped would+ # otherwise be misclassified as never having connected and+ # re-enter this initial-connect ladder (#94654).# (Ported from Kilo Code's MCP resilience fix.)- if not self._ready.is_set():+ if not self._ever_connected:if failure_class == "permanent":# Deterministic failure (bad command, non-MCP URL,# 401/403): every retry hits the same wall. Park