The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(mcp): avoid default keepalive on stdio servers
fangliquanflq967bbf25d5ed
diff --git a/tests/tools/test_mcp_capability_gating.py b/tests/tools/test_mcp_capability_gating.pyindex f2dede282f5..5a67e06afcb 100644--- a/tests/tools/test_mcp_capability_gating.py+++ b/tests/tools/test_mcp_capability_gating.py@@ -110,6 +110,7 @@ class TestKeepaliveProbe:async def test_keepalive_uses_ping_for_prompt_only_server(self):task = MCPServerTask("test")+ task._config = {"url": "https://example.test/mcp"}task.initialize_result = _caps(prompts=SimpleNamespace())task.session = SimpleNamespace(list_tools=AsyncMock(),@@ -126,6 +127,7 @@ class TestKeepaliveProbe:async def test_keepalive_uses_ping_legacy_fallback(self):"""No captured capabilities → still pings (no spurious list_tools)."""task = MCPServerTask("test")+ task._config = {"url": "https://example.test/mcp"}assert task.initialize_result is Nonetask.session = SimpleNamespace(list_tools=AsyncMock(),@@ -148,7 +150,7 @@ class TestKeepaliveInterval:async def _captured_interval(self, config):"""Run one keepalive cycle and capture the ``asyncio.wait`` timeout."""task = MCPServerTask("test")- task._config = config+ task._config = {"url": "https://example.test/mcp", **config}task.session = SimpleNamespace(send_ping=AsyncMock())captured = {}real_wait = asyncio.wait@@ -184,6 +186,33 @@ class TestKeepaliveInterval:== _MIN_KEEPALIVE_INTERVAL)+ @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++ assert captured["timeout"] is None+ task.session.send_ping.assert_not_called()+def _mcp_error(code, message="boom"):"""Build a real MCPError carrying a JSON-RPC error code.diff --git a/tools/mcp_tool.py b/tools/mcp_tool.pyindex f0dd90813fb..13562c0d275 100644--- a/tools/mcp_tool.py+++ b/tools/mcp_tool.py@@ -240,8 +240,9 @@ _PARKED_RETRY_INTERVAL = 300# Bounded wait for a respawned stdio child when a call finds it dead (gateway restarts kill# every MCP child); bounded so a broken server still parks via run()'s rapid-drop budget._STDIO_RESPAWN_WAIT_SEC = 15.0-# The client MUST ping faster than the server's idle-session TTL (short-TTL servers need a-# smaller configured ``keepalive_interval``); the floor stops a tiny interval busy-looping.+# Remote clients MUST ping faster than the server's idle-session TTL (short-TTL servers need a+# smaller configured ``keepalive_interval``); stdio only opts in explicitly because local pipes+# have no remote session TTL. The floor stops a tiny interval busy-looping._DEFAULT_KEEPALIVE_INTERVAL, _MIN_KEEPALIVE_INTERVAL = 180, 5# One bounded cancellation cycle at final shutdown so resistant tasks cannot hang exit._MCP_LOOP_DRAIN_TIMEOUT = 3.0diff --git a/tools/mcp_tool_server_run.py b/tools/mcp_tool_server_run.pyindex 6767526ac22..ae008a19f9d 100644--- a/tools/mcp_tool_server_run.py+++ b/tools/mcp_tool_server_run.py@@ -53,17 +53,20 @@ class MCPServerRunMixin:async def _wait_for_lifecycle_event(self) -> str:"""Serve until a lifecycle event: ``"shutdown"`` (exits run), ``"reconnect"`` (session torndown, transport re-entered; event cleared first) or ``"recycle"`` (stdio idle/lifetime- limit; restarts lazily on next call). Shutdown wins a tie. A keepalive (``ping``,- list_tools fallback) runs every ``keepalive_interval`` (must stay below the server's- session TTL); a failure triggers a reconnect.+ limit; restarts lazily on next call). Shutdown wins a tie. Remote transports run a+ keepalive (``ping``, list_tools fallback) every ``keepalive_interval`` (which must stay+ below the server's session TTL); stdio does so only when explicitly configured. A+ keepalive failure triggers a reconnect.Periodically sends a lightweight keepalive (``ping``, with a ``list_tools`` fallback for serversthat don't implement the optional ping utility — see :meth:`_keepalive_probe`) to preventTCP/session state from going stale during idle periods (#17003)."""- keepalive_interval = max(- _core._MIN_KEEPALIVE_INTERVAL,- float(self._config.get("keepalive_interval", _core._DEFAULT_KEEPALIVE_INTERVAL)))+ keepalive_interval = None+ if self._is_http() or "keepalive_interval" in self._config:+ keepalive_interval = max(+ _core._MIN_KEEPALIVE_INTERVAL,+ float(self._config.get("keepalive_interval", _core._DEFAULT_KEEPALIVE_INTERVAL)))shutdown_task, reconnect_task = self._event_waiters()try:while True:@@ -72,13 +75,16 @@ class MCPServerRunMixin:timeout = keepalive_intervalrecycle_deadline = self._next_stdio_recycle_deadline()if recycle_deadline is not None:- timeout = max(0.0, min(timeout, recycle_deadline - time.monotonic()))+ recycle_timeout = max(0.0, recycle_deadline - time.monotonic())+ timeout = recycle_timeout if timeout is None else min(timeout, recycle_timeout)done, _pending = await asyncio.wait({shutdown_task, reconnect_task}, timeout=timeout, return_when=asyncio.FIRST_COMPLETED)if done:breakif self._recycle_if_due():return "recycle"+ if keepalive_interval is None:+ 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).# Timeout — no lifecycle event fired. See #48069.