Skip to content

The agent that grows with you

fix(mcp): skip dynamic tool refresh when the server session is already gone (#109824)

salch-cred1c82c22eb69c
diff --git a/tests/tools/test_mcp_dynamic_discovery.py b/tests/tools/test_mcp_dynamic_discovery.py
index 76fcb907a43..20ff2f39099 100644
--- a/tests/tools/test_mcp_dynamic_discovery.py
+++ b/tests/tools/test_mcp_dynamic_discovery.py
@@ -104,6 +104,24 @@ class TestRefreshTools:
assert "mcp__live_srv__new_tool" in resolve_toolset("live_srv")
assert server._registered_tool_names == ["mcp__live_srv__new_tool"]
+ @pytest.mark.asyncio
+ async def test_refresh_skips_when_session_is_none(self, mock_registry):
+ """#109824: a queued refresh can fire while the server is parked / mid-reconnect,
+ before the replacement ClientSession is assigned. The refresh must skip cleanly
+ (pre-fix: AttributeError 'NoneType' has no attribute 'list_tools' once per profile
+ on every gateway restart with a slow-to-connect MCP server) and leave the owned
+ tool names untouched so the next refresh cycle still knows what it owns."""
+ server = MCPServerTask("parked_srv")
+ server._refresh_lock = asyncio.Lock()
+ server._config = {}
+ server._registered_tool_names = ["mcp__parked_srv__old_tool"]
+ server.session = None # parked before the cycle: snapshot must observe None
+
+ with patch("tools.registry.registry", mock_registry):
+ await server._refresh_tools() # must not raise, must not call list_tools
+
+ assert server._registered_tool_names == ["mcp__parked_srv__old_tool"]
+
class TestMessageHandler:
"""Tests for MCPServerTask._make_message_handler dispatch."""
diff --git a/tools/mcp_tool_health.py b/tools/mcp_tool_health.py
index 110544a6225..ee7b4545300 100644
--- a/tools/mcp_tool_health.py
+++ b/tools/mcp_tool_health.py
@@ -137,7 +137,16 @@ class MCPServerHealthMixin:
async with self._refresh_lock:
old_tool_names = set(self._registered_tool_names)
async with self._rpc_lock:
- new_mcp_tools = await _core._paginate_full_list(self.session.list_tools, "tools", self.name)
+ # Snapshot the session only once the RPC lock is held: run() resets self.session
+ # to None on every transport teardown (reconnect, backoff, park, cancel) outside
+ # both locks, so a refresh queued behind the lock can wake up mid-restart
+ # (#109824). Skipping is correct — the reconnect's own discovery re-lists tools
+ # and the next tools/list_changed re-arms this refresh against the live session.
+ session = self.session
+ if session is None:
+ logger.debug("MCP server '%s': skipping dynamic tool refresh; session not connected", self.name)
+ return
+ new_mcp_tools = await _core._paginate_full_list(session.list_tools, "tools", self.name)
# Remove only stale names first — no nuke-and-repave: live turns may hold tool-call
# IDs pointing at existing handlers; in-place replacement avoids "not connected" races.
self._deregister_owned(old_tool_names - {mcp_prefixed_tool_name(self.name, tool.name) for tool in new_mcp_tools})