Skip to content

The agent that grows with you

refactor(mcp): health — one recycle-deadline table, shared owned-deregister helper, module-level stdio liveness probe

Teknium350738246932
diff --git a/tools/mcp_tool_health.py b/tools/mcp_tool_health.py
index eb9ebab18e0..06dd2d8ce5c 100644
--- a/tools/mcp_tool_health.py
+++ b/tools/mcp_tool_health.py
@@ -4,7 +4,7 @@ import asyncio
import json
import logging
import time
-from typing import Optional
+from typing import Iterable, Optional
from tools.mcp_tool_errors import _is_method_not_found_error, _unwrap_exception_group
from tools.mcp_tool_schema import mcp_prefixed_tool_name
from tools.mcp_tool_registration import _forget_mcp_tool_server
@@ -12,6 +12,27 @@ from tools.mcp_tool_common import _core
logger = logging.getLogger("tools.mcp_tool")
+_KEEPALIVE_RPC_TIMEOUT = 30.0
+
+
+def _stdio_children_dead_impl(pids, is_http: bool) -> bool:
+ """True when every pid has exited. Best-effort: False (unknown → don't fail
+ fast) for HTTP, no captured PIDs, missing psutil, or a failed probe."""
+ if not pids or is_http:
+ return False
+ try:
+ import psutil
+ except ImportError:
+ return False
+ for pid in pids:
+ # pid_exists handles Windows without signal-permission noise.
+ try:
+ if psutil.pid_exists(pid):
+ return False
+ except Exception:
+ return False
+ return True
+
class MCPServerHealthMixin:
"""Methods of :class:`tools.mcp_tool.MCPServerTask` (mixed in; relies on its attributes)."""
@@ -36,39 +57,40 @@ class MCPServerHealthMixin:
self._last_tool_call_at = now
self._recycled_reason = None
- def _stdio_recycle_reason(self, now: Optional[float] = None) -> Optional[str]:
- """Return the stdio recycle reason if idle/age limits have elapsed."""
+ # ------------------------------------------------------- stdio recycling
+
+ def _stdio_recycle_deadlines(self):
+ """``[(deadline, reason), ...]`` for the configured lifetime/idle limits;
+ empty for HTTP servers or while an RPC holds the lock."""
if self._is_http() or self._rpc_lock.locked():
- return None
+ return []
+ deadlines = []
+ if self._max_lifetime_seconds is not None:
+ deadlines.append((self._lifecycle_started_at + self._max_lifetime_seconds, "max_lifetime_seconds"))
+ if self._idle_timeout_seconds is not None:
+ deadlines.append((self._last_tool_call_at + self._idle_timeout_seconds, "idle_timeout_seconds"))
+ return deadlines
+
+ def _stdio_recycle_reason(self, now: Optional[float] = None) -> Optional[str]:
+ """Return the stdio recycle reason if idle/age limits have elapsed (lifetime wins)."""
now = time.monotonic() if now is None else now
- if (
- self._max_lifetime_seconds is not None
- and now - self._lifecycle_started_at >= self._max_lifetime_seconds
- ):
- return "max_lifetime_seconds"
- if (
- self._idle_timeout_seconds is not None
- and now - self._last_tool_call_at >= self._idle_timeout_seconds
- ):
- return "idle_timeout_seconds"
+ for deadline, reason in self._stdio_recycle_deadlines():
+ if now >= deadline:
+ return reason
return None
def _next_stdio_recycle_deadline(self) -> Optional[float]:
"""Return the next monotonic recycle deadline for stdio, if any."""
- if self._is_http() or self._rpc_lock.locked():
- return None
- deadlines = []
- if self._max_lifetime_seconds is not None:
- deadlines.append(self._lifecycle_started_at + self._max_lifetime_seconds)
- if self._idle_timeout_seconds is not None:
- deadlines.append(self._last_tool_call_at + self._idle_timeout_seconds)
- return min(deadlines) if deadlines else None
+ deadlines = self._stdio_recycle_deadlines()
+ return min(d for d, _ in deadlines) if deadlines else None
def _mark_stdio_recycled(self, reason: str) -> None:
"""Mark a stdio session dormant before its transport finishes closing."""
self._recycled_reason = reason
self.session = None
+ # -------------------------------------------------- notifications / logs
+
async def _refresh_tools_task(self):
"""Run a dynamic tool refresh and log failures from background tasks."""
try:
@@ -147,14 +169,24 @@ class MCPServerHealthMixin:
logger.exception("Error in MCP message handler for '%s'", self.name)
return _handler
+ def _deregister_owned(self, tool_names: Iterable[str]) -> None:
+ """Deregister *tool_names* that this server's toolset still owns.
+ Never removes a colliding name currently owned by another server."""
+ from tools.registry import registry
+
+ toolset_name = f"mcp-{self.name}"
+ for tool_name in tool_names:
+ if registry.get_toolset_for_tool(tool_name) != toolset_name:
+ continue
+ registry.deregister(tool_name, scope=_core._server_registry_scope(self.name))
+ _forget_mcp_tool_server(tool_name)
+
async def _refresh_tools(self):
"""Re-fetch tools on ``tools/list_changed`` and update the registry.
The lock serializes rapid-fire notifications. After the list_tools
``await``, all mutations are synchronous — atomic on the event loop.
"""
- from tools.registry import registry
-
if not self._advertises_tools():
# Shouldn't happen, but tools/list would raise MCPError(-32601).
return
@@ -171,33 +203,19 @@ class MCPServerHealthMixin:
# 2. Remove only stale names first — no nuke-and-repave: live agent
# turns may hold tool-call IDs pointing at existing handlers, and
# in-place replacement avoids transient "tool not connected" races.
- toolset_name = f"mcp-{self.name}"
- stale_tool_names = old_tool_names - {
- mcp_prefixed_tool_name(self.name, tool.name)
- for tool in new_mcp_tools
- }
- for tool_name in stale_tool_names:
- # Never remove a colliding name currently owned by another server.
- if registry.get_toolset_for_tool(tool_name) != toolset_name:
- continue
- registry.deregister(tool_name, scope=_core._server_registry_scope(self.name))
- _forget_mcp_tool_server(tool_name)
+ self._deregister_owned(old_tool_names - {
+ mcp_prefixed_tool_name(self.name, tool.name) for tool in new_mcp_tools
+ })
# 3. Re-register; the helper may skip names ambiguous after normalization.
self._tools = new_mcp_tools
registered_names = _core._register_server_tools(
self.name, self, self._config
)
-
# A raw name can become ambiguous without changing its normalized
# name, so the pre-pass misses it: drop any old entry the final
# collision-checked registration no longer owns.
- registered_name_set = set(registered_names)
- for tool_name in old_tool_names - registered_name_set:
- if registry.get_toolset_for_tool(tool_name) != toolset_name:
- continue
- registry.deregister(tool_name, scope=_core._server_registry_scope(self.name))
- _forget_mcp_tool_server(tool_name)
+ self._deregister_owned(old_tool_names - set(registered_names))
self._registered_tool_names = registered_names
# 4. Log what changed (user-visible).
@@ -221,6 +239,8 @@ class MCPServerHealthMixin:
self.name, len(self._registered_tool_names),
)
+ # ------------------------------------------------------ keepalive / health
+
async def _keepalive_probe(self) -> None:
"""Exercise the session; raise on a genuine connection failure.
@@ -231,7 +251,7 @@ class MCPServerHealthMixin:
"""
if not self._ping_unsupported:
try:
- await asyncio.wait_for(self.session.send_ping(), timeout=30.0)
+ await asyncio.wait_for(self.session.send_ping(), timeout=_KEEPALIVE_RPC_TIMEOUT)
return
except Exception as exc:
if _is_method_not_found_error(exc):
@@ -250,7 +270,7 @@ class MCPServerHealthMixin:
# Confirm with list_tools before declaring it dead; if that
# also fails, propagate the original failure.
try:
- await asyncio.wait_for(self.session.list_tools(), timeout=30.0)
+ await asyncio.wait_for(self.session.list_tools(), timeout=_KEEPALIVE_RPC_TIMEOUT)
except Exception:
raise exc from None
# Transport alive; latch so later keepalives skip the 30s wait.
@@ -267,7 +287,7 @@ class MCPServerHealthMixin:
raise
# Fallback probe for servers without ping support.
- await asyncio.wait_for(self.session.list_tools(), timeout=30.0)
+ await asyncio.wait_for(self.session.list_tools(), timeout=_KEEPALIVE_RPC_TIMEOUT)
def _mark_session_proven(self) -> None:
"""Record that the session demonstrated real health (keepalive or tool-call success).
@@ -276,20 +296,21 @@ class MCPServerHealthMixin:
later must keep consuming ``_reconnect_retries`` so a flapping transport
still reaches the park instead of respawning forever.
"""
- if not self._session_proven:
- self._session_proven = True
- self._reconnect_retries = 0
- if self._was_parked:
- self._was_parked = False
- logger.warning(
- "MCP server '%s': revived — session healthy again after "
- "parking (state: parked → connected)",
- self.name,
- )
- # A proven fresh transport clears the one-time permanent-failure
- # grace and any race bookkeeping.
- self._permanent_grace_used = False
- self._teardown_race = False
+ if self._session_proven:
+ return
+ self._session_proven = True
+ self._reconnect_retries = 0
+ if self._was_parked:
+ self._was_parked = False
+ logger.warning(
+ "MCP server '%s': revived — session healthy again after "
+ "parking (state: parked → connected)",
+ self.name,
+ )
+ # A proven fresh transport clears the one-time permanent-failure
+ # grace and any race bookkeeping.
+ self._permanent_grace_used = False
+ self._teardown_race = False
def mark_suspect(self, reason: str) -> None:
"""Latch a suspicion (no I/O). The NEXT call verifies via
@@ -361,32 +382,11 @@ class MCPServerHealthMixin:
task.cancel()
def _stdio_children_dead(self) -> bool:
- """True when every stdio child we spawned has exited.
-
- Best-effort: False (unknown → don't fail fast) for HTTP, no captured
- PIDs, missing psutil, or a failed probe.
- """
- pids = getattr(self, "_stdio_child_pids", None)
- if not pids or self._is_http():
- return False
- try:
- import psutil
- except ImportError:
- return False
- for pid in pids:
- # pid_exists handles Windows without signal-permission noise.
- try:
- alive = psutil.pid_exists(pid)
- except Exception:
- return False
- if alive:
- return False
- return True
+ """True when every stdio child we spawned has exited (see :func:`_stdio_children_dead_impl`)."""
+ return _stdio_children_dead_impl(getattr(self, "_stdio_child_pids", None), self._is_http())
async def _watch_stdio_children(self) -> None:
"""Poll child liveness while a stdio RPC is in flight; resolves when a
tracked child dies so the caller cancels the RPC instead of waiting out the timeout."""
- while True:
- if self._stdio_children_dead():
- return
+ while not self._stdio_children_dead():
await asyncio.sleep(0.25)