Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 27 additions & 14 deletions agent_core/core/impl/mcp/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -943,25 +943,38 @@ async def _discover_tools(self) -> None:
)
return

response = await self._transport.send_request("tools/list", {})
tools_data: List[Dict[str, Any]] = []
cursor: Optional[str] = None
seen_cursors = set()

if "error" in response:
error_info = response.get("error", {})
if isinstance(error_info, dict):
error_msg = error_info.get("message", str(error_info))
else:
error_msg = str(error_info)
logger.warning(
f"[MCPServer:{self.config.name}] Failed to list tools: {error_msg}"
)
return
# tools/list is paginated: keep following nextCursor until the server
# stops returning one, otherwise every tool past the first page is lost.
while True:
params: Dict[str, Any] = {"cursor": cursor} if cursor else {}
response = await self._transport.send_request("tools/list", params)

if "error" in response:
error_info = response.get("error", {})
if isinstance(error_info, dict):
error_msg = error_info.get("message", str(error_info))
else:
error_msg = str(error_info)
logger.warning(
f"[MCPServer:{self.config.name}] Failed to list tools: {error_msg}"
)
return

result = response.get("result", {})
tools_data.extend(result.get("tools", []))

result = response.get("result", {})
tools_data = result.get("tools", [])
cursor = result.get("nextCursor")
if not cursor or cursor in seen_cursors:
break
seen_cursors.add(cursor)

if not tools_data:
logger.debug(
f"[MCPServer:{self.config.name}] Server returned empty tools list. Response: {response}"
f"[MCPServer:{self.config.name}] Server returned an empty tools list"
)

self._tools = [MCPTool.from_dict(t) for t in tools_data]
Expand Down
65 changes: 65 additions & 0 deletions tests/test_mcp_tools_list_pagination.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
"""MCP tool discovery pagination.

tools/list is paginated by the MCP spec, so every page has to be fetched.
"""

import asyncio

from agent_core.core.impl.mcp.config import MCPServerConfig
from agent_core.core.impl.mcp.server import MCPServerConnection


class FakeTransport:
is_connected = True

def __init__(self, pages):
self.pages = pages
self.list_params = []

async def send_request(self, method, params=None):
if method == "tools/list":
self.list_params.append(params)
return {"result": self.pages[(params or {}).get("cursor")]}
raise AssertionError(f"unexpected method {method}")


def _connection(transport):
conn = MCPServerConnection(
MCPServerConfig(name="fake", transport="stdio", command="fake")
)
conn._transport = transport
return conn


def _tool(name):
return {"name": name, "inputSchema": {}}


def test_discover_tools_follows_next_cursor():
transport = FakeTransport(
pages={
None: {"tools": [_tool("a")], "nextCursor": "p2"},
"p2": {"tools": [_tool("b")], "nextCursor": "p3"},
"p3": {"tools": [_tool("c")]},
}
)
conn = _connection(transport)

asyncio.run(conn._discover_tools())

assert [t.name for t in conn.tools] == ["a", "b", "c"]
assert transport.list_params == [{}, {"cursor": "p2"}, {"cursor": "p3"}]


def test_discover_tools_stops_on_repeated_cursor():
transport = FakeTransport(
pages={
None: {"tools": [_tool("a")], "nextCursor": "loop"},
"loop": {"tools": [_tool("b")], "nextCursor": "loop"},
}
)
conn = _connection(transport)

asyncio.run(conn._discover_tools())

assert [t.name for t in conn.tools] == ["a", "b"]