Skip to content

The agent that grows with you

fix(mcp): an idle stdio server still proves its session without a keepalive ping

kshitijk4poor3ceb40fc7726
diff --git a/tests/tools/test_mcp_capability_gating.py b/tests/tools/test_mcp_capability_gating.py
index 07b27261e42..0eb45fb709e 100644
--- a/tests/tools/test_mcp_capability_gating.py
+++ b/tests/tools/test_mcp_capability_gating.py
@@ -147,16 +147,20 @@ class TestKeepaliveInterval:
the session alive instead of hitting an expired session on every idle call.
"""
- async def _captured_interval(self, config):
- """Run one keepalive cycle and capture the ``asyncio.wait`` timeout."""
+ async def _run_lifecycle_cycles(self, config):
+ """Run two lifecycle cycles on a server with the *full* ``config``: the first
+ ``asyncio.wait`` times out (no event fired), the second is ended by shutdown.
+ Returns ``(task, [timeout_of_cycle_1, timeout_of_cycle_2])``."""
task = MCPServerTask("test")
- task._config = {"url": "https://example.test/mcp", **config}
+ task._config = config
task.session = SimpleNamespace(send_ping=AsyncMock())
- captured = {}
+ timeouts = []
real_wait = asyncio.wait
async def fake_wait(tasks, timeout=None, return_when=None):
- captured["timeout"] = timeout
+ timeouts.append(timeout)
+ if len(timeouts) == 1:
+ return set(), set(tasks) # simulate the timeout firing
task._shutdown_event.set()
return await real_wait(
tasks, timeout=0.5, return_when=return_when or asyncio.FIRST_COMPLETED
@@ -166,10 +170,16 @@ class TestKeepaliveInterval:
orig = mcp_mod.asyncio.wait
mcp_mod.asyncio.wait = fake_wait
try:
- await task._wait_for_lifecycle_event()
+ assert await task._wait_for_lifecycle_event() == "shutdown"
finally:
mcp_mod.asyncio.wait = orig
- return captured["timeout"]
+ return task, timeouts
+
+ async def _captured_interval(self, config):
+ """Capture the first ``asyncio.wait`` timeout of a remote (HTTP) server."""
+ _task, timeouts = await self._run_lifecycle_cycles(
+ {"url": "https://example.test/mcp", **config})
+ return timeouts[0]
@pytest.mark.asyncio
async def test_default_interval_when_unset(self):
@@ -188,29 +198,14 @@ class TestKeepaliveInterval:
@pytest.mark.asyncio
async def test_default_stdio_connection_waits_without_keepalive(self):
- """A healthy local pipe must not be probed solely because it is idle."""
- task = MCPServerTask("test")
- task._config = {"command": "example-mcp"}
- task.session = SimpleNamespace(send_ping=AsyncMock())
- captured = {}
- real_wait = asyncio.wait
-
- async def fake_wait(tasks, timeout=None, return_when=None):
- captured["timeout"] = timeout
- task._shutdown_event.set()
- return await real_wait(
- tasks, timeout=0.5, return_when=return_when or asyncio.FIRST_COMPLETED
- )
-
- import tools.mcp_tool as mcp_mod
- orig = mcp_mod.asyncio.wait
- mcp_mod.asyncio.wait = fake_wait
- try:
- assert await task._wait_for_lifecycle_event() == "shutdown"
- finally:
- mcp_mod.asyncio.wait = orig
+ """A healthy local pipe must not be probed solely because it is idle — but surviving a
+ full default interval idle must still prove the session (clears the rapid-drop budget);
+ once proven, the loop waits without any timeout."""
+ from tools.mcp_tool import _DEFAULT_KEEPALIVE_INTERVAL
+ task, timeouts = await self._run_lifecycle_cycles({"command": "example-mcp"})
- assert captured["timeout"] is None
+ assert timeouts == [_DEFAULT_KEEPALIVE_INTERVAL, None]
+ assert task._session_proven is True
task.session.send_ping.assert_not_called()
@pytest.mark.asyncio
diff --git a/tools/mcp_tool_health.py b/tools/mcp_tool_health.py
index fa39a6d0b8f..dbf2473362d 100644
--- a/tools/mcp_tool_health.py
+++ b/tools/mcp_tool_health.py
@@ -194,8 +194,9 @@ class MCPServerHealthMixin:
Only then is the reconnect budget cleared: a handshake that drops moments later must keep
consuming ``_reconnect_retries`` so a flapping transport still reaches the park.
- Called from the keepalive success path (session survived at least one full keepalive interval) and
- the tool-call success path. See #62212.
+ Called from the keepalive success path (session survived a full keepalive interval — for
+ stdio without a keepalive, a full default interval idle with the child alive) and the
+ tool-call success path. See #62212.
"""
if self._session_proven:
return
diff --git a/tools/mcp_tool_server_run.py b/tools/mcp_tool_server_run.py
index 54ba79a389f..97d4a9c9666 100644
--- a/tools/mcp_tool_server_run.py
+++ b/tools/mcp_tool_server_run.py
@@ -79,6 +79,10 @@ class MCPServerRunMixin:
if self._recycle_if_due():
return "recycle"
timeout = keepalive_interval
+ if timeout is None and not self._session_proven:
+ # No keepalive, but an unproven stdio session must still get its chance to
+ # prove itself: wake once after the default interval (no ping) — see below.
+ timeout = float(_core._DEFAULT_KEEPALIVE_INTERVAL)
recycle_deadline = self._next_stdio_recycle_deadline()
if recycle_deadline is not None:
recycle_timeout = max(0.0, recycle_deadline - time.monotonic())
@@ -103,6 +107,11 @@ class MCPServerRunMixin:
if self._recycle_if_due():
return "recycle"
if keepalive_interval is None:
+ # Stdio without a keepalive: idling a full default interval with the child
+ # still alive is the proof of health a successful ping gives remote
+ # transports — clear the rapid-drop budget without pinging (#62212).
+ if not self._session_proven and not self._stdio_children_dead():
+ self._mark_session_proven()
continue
# Timeout: probe for a stale session — NEVER while an RPC is in flight (a
# concurrent ping can wedge the stdio stream; a busy server is alive anyway).
diff --git a/tools/mcp_tool_transport.py b/tools/mcp_tool_transport.py
index ce3c664487b..32aa2618732 100644
--- a/tools/mcp_tool_transport.py
+++ b/tools/mcp_tool_transport.py
@@ -162,8 +162,9 @@ class MCPServerTransportMixin:
# 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).
# A completed handshake alone is NOT proof of health: a flapping transport can handshake fine and
- # drop moments later, forever (#62212). The session must prove itself (keepalive success or a
- # successful tool call) before the reconnect budget is cleared — see _mark_session_proven.
+ # drop moments later, forever (#62212). The session must prove itself (keepalive success, a
+ # successful tool call, or — stdio without a keepalive — surviving a full default interval
+ # idle with the child alive) before the reconnect budget is cleared — see _mark_session_proven.
# 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).
# Unproven until keepalive/tool-call success (#62212).