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
1 change: 1 addition & 0 deletions docs/changelog.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
31 changes: 25 additions & 6 deletions src/fim_one/core/mcp/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down Expand Up @@ -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),
Expand Down Expand Up @@ -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),
Expand Down Expand Up @@ -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),
Expand Down
118 changes: 118 additions & 0 deletions tests/test_mcp_tool_pagination.py
Original file line number Diff line number Diff line change
@@ -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"]
Loading