fix(mcp): load all pages of server tools before registration

This commit is contained in:
Kail Tian authored and chengyongru committed 2026-09-26 20:52:14 +08:00
1 parent 569fbd3cb4
commit f62e0da9f6
2 files changed
+107 -7

No files matched your search

+16 -5
View File
@@ -1011,7 +1011,7 @@ async def connect_mcp_servers(
entered the MCP SDK contexts alive so reconnect and shutdown can close
AnyIO cancel scopes from their owning task.
"""
from mcp import ClientSession, StdioServerParameters
from mcp import ClientSession, StdioServerParameters, types
from mcp.client.sse import sse_client
from mcp.client.stdio import stdio_client
from mcp.client.streamable_http import streamable_http_client
@@ -1139,14 +1139,25 @@ async def connect_mcp_servers(
session = await server_stack.enter_async_context(ClientSession(read, write))
await session.initialize()
tools = await session.list_tools()
# Finish discovery before registering tools so a failed page leaves no partial set.
page = await session.list_tools()
tool_defs = list(page.tools)
seen_cursors: set[str] = set()
while page.nextCursor is not None:
cursor = page.nextCursor
if cursor in seen_cursors:
raise ValueError("MCP tools/list returned a repeated pagination cursor")
seen_cursors.add(cursor)
page = await session.list_tools(params=types.PaginatedRequestParams(cursor=cursor))
tool_defs.extend(page.tools)
enabled_tools = set(cfg.enabled_tools)
allow_all_tools = "*" in enabled_tools
registered_count = 0
matched_enabled_tools: set[str] = set()
available_raw_names = [tool_def.name for tool_def in tools.tools]
available_wrapped_names = [_sanitize_mcp_tool_name(f"mcp_{name}_{tool_def.name}") for tool_def in tools.tools]
for tool_def in tools.tools:
available_raw_names = [tool_def.name for tool_def in tool_defs]
available_wrapped_names = [_sanitize_mcp_tool_name(f"mcp_{name}_{tool_def.name}") for tool_def in tool_defs]
for tool_def in tool_defs:
wrapped_name = _sanitize_mcp_tool_name(f"mcp_{name}_{tool_def.name}")
if (
not allow_all_tools