From 2b047c06c7255ad653dfaa896663a8816e6ad2e9 Mon Sep 17 00:00:00 2001 From: Alex Date: Fri, 27 Nov 2026 11:05:54 -0400 Subject: [PATCH] fix(mcp): load every page of tools/list --- docs/changelog.mdx | 1 + src/fim_one/core/mcp/client.py | 31 ++++++-- tests/test_mcp_tool_pagination.py | 118 ++++++++++++++++++++++++++++++ 3 files changed, 144 insertions(+), 6 deletions(-) create mode 100644 tests/test_mcp_tool_pagination.py diff --git a/docs/changelog.mdx b/docs/changelog.mdx index 37af940b9..b2dfc4c0f 100644 --- a/docs/changelog.mdx +++ b/docs/changelog.mdx @@ -148,6 +148,7 @@ Format follows [Keep a Changelog](https://keepachangelog.com/). Versions corresp ### Fixed +- **MCP servers that return their tool list in pages now expose all their tools.** Only the first page of `tools/list` was loaded, so the remaining tools were missing from agents and workflows. - **DeepSeek V4 / flash and Kimi K2 agents no longer fail after the first tool call.** The reasoning text these models return next to a tool call was dropped from the history, and DeepSeek answers a request without it with a 400. It is now sent back on later turns for `deepseek-v4*`, `deepseek-flash` and `kimi-k2*` models. - **"Test connection" on a stdio MCP server shows why it was refused.** For a stdio server whose owner is not an administrator the endpoint answered `stdio_mcp_admin_only`, while the server list and every start-time refusal say `stdio_mcp_owner_not_admin`; it now answers `stdio_mcp_owner_not_admin` (and `stdio_mcp_disabled` when stdio is off), and the card shows the refusal on its result line instead of nothing (the error went to the browser console). - **Asking for a verification code again within a minute no longer uses up the day's codes.** A request refused by the one-code-a-minute rule was still counted against the address, so four requests within a minute used up the 3 codes a day issued without a wait. Only a code that is issued is counted now, in the same atomic step that applies the one-minute rule; of requests arriving together one gets a code. The answer is the same whether or not the address has an account. diff --git a/src/fim_one/core/mcp/client.py b/src/fim_one/core/mcp/client.py index b6aeb0e3b..76b333742 100644 --- a/src/fim_one/core/mcp/client.py +++ b/src/fim_one/core/mcp/client.py @@ -47,6 +47,25 @@ def _tool_def_from_mcp(tool: Any) -> dict[str, Any]: } +async def _list_all_tools(session: Any) -> list[Any]: + """Every tool of the server: ``tools/list`` may answer in pages.""" + result = await session.list_tools() + # By name, so that a server repeating a page does not list a tool twice. + tools = {tool.name: tool for tool in result.tools} + seen: set[str] = set() + # Only an absent cursor ends the listing; an empty string is a cursor. + while (cursor := getattr(result, "next_cursor", None)) is not None: + if cursor in seen: + logger.warning("MCP server repeated a tools/list cursor; listing stopped there") + break + seen.add(cursor) + from mcp.types import PaginatedRequestParams + + result = await session.list_tools(params=PaginatedRequestParams(cursor=cursor)) + tools.update((tool.name, tool) for tool in result.tools) + return list(tools.values()) + + class _Contexts: """The transports and sessions a client has open, closed last-in first-out. @@ -305,13 +324,13 @@ async def connect_stdio( self._sessions[name] = session # Discover tools exposed by the server. - tools_result = await session.list_tools() + server_tools = await _list_all_tools(session) except BaseException as exc: await self._give_up_connecting(name, mark, exc, previous) raise adapters: list[Tool] = [] - for tool in tools_result.tools: + for tool in server_tools: adapter = MCPToolAdapter( server_name=name, tool_def=_tool_def_from_mcp(tool), @@ -383,13 +402,13 @@ async def connect_sse( await session.initialize() self._sessions[name] = session - tools_result = await session.list_tools() + server_tools = await _list_all_tools(session) except BaseException as exc: await self._give_up_connecting(name, mark, exc, previous) raise adapters: list[Tool] = [] - for tool in tools_result.tools: + for tool in server_tools: adapter = MCPToolAdapter( server_name=name, tool_def=_tool_def_from_mcp(tool), @@ -474,13 +493,13 @@ async def connect_streamable_http( await session.initialize() self._sessions[name] = session - tools_result = await session.list_tools() + server_tools = await _list_all_tools(session) except BaseException as exc: await self._give_up_connecting(name, mark, exc, previous) raise adapters: list[Tool] = [] - for tool in tools_result.tools: + for tool in server_tools: adapter = MCPToolAdapter( server_name=name, tool_def=_tool_def_from_mcp(tool), diff --git a/tests/test_mcp_tool_pagination.py b/tests/test_mcp_tool_pagination.py new file mode 100644 index 000000000..31f954c3a --- /dev/null +++ b/tests/test_mcp_tool_pagination.py @@ -0,0 +1,118 @@ +"""A server that pages ``tools/list`` has every page loaded. + +The MCP spec lets a server answer ``tools/list`` with part of its tools and a +``nextCursor``. The client read the first answer only, so the rest of the +server's tools never reached the agent, with nothing logged. +""" + +from __future__ import annotations + +from typing import Any + +import pytest + +pytest.importorskip("mcp") + +import mcp +from mcp.client import sse, stdio, streamable_http +from mcp.types import ListToolsResult, PaginatedRequestParams, Tool + +from fim_one.core.mcp import MCPClient +from fim_one.core.mcp import client as client_module + + +def _page(*names: str, next_cursor: str | None = None) -> ListToolsResult: + return ListToolsResult( + tools=[Tool(name=name, input_schema={"type": "object"}) for name in names], + next_cursor=next_cursor, + ) + + +class _Transport: + async def __aenter__(self) -> tuple[None, None]: + return None, None + + async def __aexit__(self, *exc: object) -> None: + return None + + +def _serve(monkeypatch: pytest.MonkeyPatch, pages: dict[str | None, ListToolsResult]) -> None: + """Answer ``tools/list`` from *pages*, keyed by the cursor asked for.""" + + class _Session: + def __init__(self, read: Any, write: Any) -> None: + self.asked: list[str | None] = [] + + async def __aenter__(self) -> _Session: + return self + + async def __aexit__(self, *exc: object) -> None: + return None + + async def initialize(self) -> None: + return None + + async def list_tools( + self, *, params: PaginatedRequestParams | None = None + ) -> ListToolsResult: + cursor = params.cursor if params else None + assert cursor not in self.asked, "the same page was asked for twice" + self.asked.append(cursor) + return pages[cursor] + + async def call_tool(self, *args: object, **kwargs: object) -> None: + return None + + monkeypatch.setattr(mcp, "ClientSession", _Session) + for module, name in ( + (stdio, "stdio_client"), + (sse, "sse_client"), + (streamable_http, "streamable_http_client"), + ): + monkeypatch.setattr(module, name, lambda *args, **kwargs: _Transport()) + monkeypatch.setattr(client_module, "_validate_url", lambda url: None) + + +async def _connect(client: MCPClient, transport: str) -> list[str]: + if transport == "stdio": + tools = await client.connect_stdio("srv", "npx") + elif transport == "sse": + tools = await client.connect_sse("srv", "https://mcp.example.com/sse") + else: + tools = await client.connect_streamable_http("srv", "https://mcp.example.com/mcp") + return [tool.name for tool in tools] + + +@pytest.mark.parametrize("transport", ["stdio", "sse", "streamable_http"]) +async def test_every_page_of_tools_is_loaded( + monkeypatch: pytest.MonkeyPatch, transport: str +) -> None: + # An empty string is a cursor too: only an absent one ends the listing. + _serve( + monkeypatch, + { + None: _page("a", "b", next_cursor="page-2"), + "page-2": _page("c", next_cursor=""), + "": _page("d"), + }, + ) + + async with MCPClient() as client: + names = await _connect(client, transport) + + assert names == ["srv__a", "srv__b", "srv__c", "srv__d"] + + +async def test_a_repeated_cursor_ends_the_listing(monkeypatch: pytest.MonkeyPatch) -> None: + _serve( + monkeypatch, + { + None: _page("a", next_cursor="again"), + "again": _page("a", "b", next_cursor="again"), + }, + ) + + async with MCPClient() as client: + names = await _connect(client, "sse") + + assert names == ["srv__a", "srv__b"]