Backtestsopenai-agents-pythonrun-20261024-184640#4085

Issue #4085 Merged fix PR #4094 Run 24 Oct 2026 · run-20261024-184640 openai/openai-agents-python

fix: MCP listing APIs do not auto-paginate across tools, prompts, and resources

Better

Our patch was judged better than the merged fix.

In this judgment, Patch B = our agent, Patch A = the merged fix.

Correctness: the issue explicitly asks for auto-pagination in four methods: list_tools, list_prompts, list_resources, and list_resource_templates. Patch A only changes list_tools and list_prompts and leaves list_resources/list_resource_templates untouched, so a server with multiple resource pages still silently drops items; the independent tests confirm this (both resource tests FAIL-ASSERT on A, PASS on B). Patch B adds a single _fetch_all_pages helper and applies it to all four methods, keeping the cursor parameter on the resource methods for backward compatibility and auto-exhausting only when cursor is None, exactly as the issue proposes. B also retries each tools page independently inside the loop (fetch_tools_page wraps _run_with_retries per page) and preserves _maybe_serialize_request per request. One caveat for B: it treats an empty-string nextCursor as end-of-list, which is a narrow edge case; A's integration server happens to use '' as a cursor, but the spec treats cursors as opaque non-empty strings in practice. A notable uncertainty: A calls session.list_tools(params=PaginatedRequestParams(...)) while B calls session.list_tools(cursor) positionally; the base code already calls session.list_resources(cursor) positionally, so B is consistent with the pinned client API as visible in the repo. Tests: B adds a focused test module covering all four methods, cache holding all pages, filter applied after accumulation, per-page retry without restart, repeated-cursor detection, single-page behaviour when a cursor is passed, and MCPUtil seeing all tools; these would fail before and pass after. A's tests are extensive for tools/prompts (including a real stdio server integration test) but necessarily omit resources since the fix omits them. Scope/craft: A adds a large amount of cursor-redaction and traceback-scrubbing machinery (del fetch_pages, clearing locals, BaseExceptionGroup wrapping) that is beyond the issue's ask and makes the core pagination loop hard to follow; B's helper is small, generic, and readable, with updated docstrings. B resolves the full reported issue; A resolves half of it.

Four judges ruled on this ticket in parallel, and the verdict comes from counting their votes. Each saw the issue and the two patches, labelled A and B in random order (two of them saw ours as A), with issue links and version numbers removed. Where tests could check the fix, they also saw the results of tests a separate agent wrote for the issue, run on both patches. None was told which patch was ours. The reasoning above is one judge's, shown verbatim.

Solve

8m 57s

Wall-clock time in the container

Full test suite

No new failures

349 passed · 0 skipped · 349 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

372vs 575 merged

Changed lines, ours vs merged

Please read this first

  • Have you read the docs?Agents SDK docs - Yes
  • Have you searched for related issues? Others may have faced similar issues. - Yes, it's not created by anyone yet.

Describe the bug

Summary

Three MCP listing methods in _MCPServerWithClientSession do not follow the
MCP pagination spec. When a server returns a nextCursor, items beyond the
first page are silently dropped.

Affected methods in src/agents/mcp/server.py

MethodAccepts cursor?Auto-paginates?
list_tools()❌ No❌ No
list_prompts()❌ No❌ No
list_resources()✅ Yes (manual, one page)❌ No
list_resource_templates()✅ Yes (manual, one page)❌ No

list_tools() and list_prompts() don't even expose a cursor parameter,
making external pagination impossible. list_resources() and
list_resource_templates() accept a cursor but leave full pagination to the
caller with no helper.

Expected behaviour

Each method should loop using nextCursor until exhausted and return the
complete result set, per the
MCP pagination spec.

Proposed fix

I intend to submit a PR that adds auto-pagination to all three methods:

  • list_tools() — loop with nextCursor, accumulate into unfiltered cache (per local MCP server lifecycle contract — unfiltered list is the cacheable value; filters applied on a copy per request)
  • list_prompts() — loop with nextCursor, return accumulated results
  • list_resources() / list_resource_templates() — loop internally, keep cursor param for backward compat but auto-exhaust when not provided

Each paginated call will be wrapped in _run_with_retries and
_maybe_serialize_request to preserve retry semantics and shared-session
serialization per iteration.

Tests will cover:

  • tests/mcp/test_caching.py — tool cache holds all pages
  • tests/mcp/test_tool_filtering.py — filters applied after full accumulation
  • tests/mcp/test_client_session_retries.py — retries per-page, not restart
  • tests/mcp/test_runner_calls_mcp.py — runner sees all tools across pages
  • New tests for paginated list_prompts() and list_resources()

Debug information

  • Agents SDK version: It's not fixed in latest one too
  • Python version - NA, its SDK associated.

Repro steps

Connect any MCP server to agents, which has pagination response supported and has enough tools to return multiple pages.
Ensure LLM can see and call the tools present in after 1st Page tool response. verify same for prompts & resources.

Expected behavior

SDK handles all the paginated mcp responses correctly and forward to LLM.

The two patches

Our patch+348 −24
src/agents/mcp/server.pyindex 168a476e..62c75e29 100644@@ -34,6 +34,8 @@ from mcp.types import (     ListPromptsResult,     ListResourcesResult,     ListResourceTemplatesResult,+    ListToolsResult,+    PaginatedResult,     ReadResourceResult, ) from typing_extensions import NotRequired, TypedDict@@ -100,6 +102,7 @@ else:   T = TypeVar("T")+PageT = TypeVar("PageT", bound=PaginatedResult)  _SAFE_EXCEPTION_GROUP_MESSAGE = "MCP request failed with additional errors." _SAFE_EXCEPTION_MESSAGE = "An additional error occurred during the MCP request."@@ -461,7 +464,10 @@ class MCPServer(abc.ABC):     async def list_prompts(         self,     ) -> ListPromptsResult:-        """List the prompts available on the server."""+        """List the prompts available on the server.++        Implementations should follow ``nextCursor`` and return every page.+        """         pass      @abc.abstractmethod@@ -477,13 +483,12 @@ class MCPServer(abc.ABC):         Args:             cursor: An opaque pagination cursor returned in a previous                 :class:`~mcp.types.ListResourcesResult` as ``nextCursor``.  Pass it-                here to fetch the next page of results.  ``None`` fetches the first-                page.+                here to fetch only that page of results.  ``None`` fetches every page. -        Returns a :class:`~mcp.types.ListResourcesResult`.  When the result contains-        a ``nextCursor`` field, call this method again with that cursor to retrieve-        the next page.  Subclasses that do not support resources may leave this-        unimplemented; it will raise :exc:`NotImplementedError` at call time.+        Returns a :class:`~mcp.types.ListResourcesResult`.  When ``cursor`` is+        ``None`` the result contains the resources from all pages.  Subclasses that+        do not support resources may leave this unimplemented; it will raise+        :exc:`NotImplementedError` at call time.         """         raise NotImplementedError(             f"MCP server '{self._error_name}' does not support list_resources. "@@ -498,14 +503,13 @@ class MCPServer(abc.ABC):         Args:             cursor: An opaque pagination cursor returned in a previous                 :class:`~mcp.types.ListResourceTemplatesResult` as ``nextCursor``.-                Pass it here to fetch the next page of results.  ``None`` fetches-                the first page.--        Returns a :class:`~mcp.types.ListResourceTemplatesResult`.  When the result-        contains a ``nextCursor`` field, call this method again with that cursor to-        retrieve the next page.  Subclasses that do not support resource templates-        may leave this unimplemented; it will raise :exc:`NotImplementedError` at-        call time.+                Pass it here to fetch only that page of results.  ``None`` fetches+                every page.++        Returns a :class:`~mcp.types.ListResourceTemplatesResult`.  When ``cursor``+        is ``None`` the result contains the resource templates from all pages.+        Subclasses that do not support resource templates may leave this+        unimplemented; it will raise :exc:`NotImplementedError` at call time.         """         raise NotImplementedError(             f"MCP server '{self._error_name}' does not support list_resource_templates. "@@ -997,6 +1001,32 @@ class _MCPServerWithClientSession(MCPServer, abc.ABC):         assert transport_error is not None         self._raise_mapped_transport_error(transport_error, None) +    async def _fetch_all_pages(+        self,+        operation: str,+        items_field: str,+        fetch_page: Callable[[str | None], Awaitable[PageT]],+    ) -> PageT:+        """Follow ``nextCursor`` until exhausted and merge every page into one result."""+        first_page = await fetch_page(None)+        next_cursor = first_page.nextCursor+        if not next_cursor:+            return first_page++        items = list(getattr(first_page, items_field))+        seen_cursors: set[str] = set()+        while next_cursor:+            if next_cursor in seen_cursors:+                raise UserError(+                    f"Failed to {operation} from MCP server '{self._error_name}': "+                    f"server returned a repeated pagination cursor."+                )+            seen_cursors.add(next_cursor)+            page = await fetch_page(next_cursor)+            items.extend(getattr(page, items_field))+            next_cursor = page.nextCursor+        return first_page.model_copy(update={items_field: items, "nextCursor": None})+     async def _run_with_retries(self, func: Callable[[], Awaitable[T]]) -> T:         attempts = 0         while True:@@ -1124,10 +1154,18 @@ class _MCPServerWithClientSession(MCPServer, abc.ABC):             if self.cache_tools_list and not self._cache_dirty and self._tools_list:                 tools = self._tools_list             else:-                # Fetch the tools from the server-                result = await self._run_with_retries(-                    lambda: self._maybe_serialize_request(lambda: session.list_tools())-                )+                # Fetch every page of tools from the server. Each page is retried and+                # serialized independently.+                def fetch_tools_page(cursor: str | None) -> Awaitable[ListToolsResult]:+                    return self._run_with_retries(+                        lambda: self._maybe_serialize_request(+                            lambda: session.list_tools()+                            if cursor is None+                            else session.list_tools(cursor)+                        )+                    )++                result = await self._fetch_all_pages("list tools", "tools", fetch_tools_page)                 self._tools_list = result.tools                 self._cache_dirty = False                 tools = self._tools_list@@ -1265,9 +1303,15 @@ class _MCPServerWithClientSession(MCPServer, abc.ABC):             raise UserError("Server not initialized. Make sure you call `connect()` first.")         session = self.session         assert session is not None++        def fetch_prompts_page(cursor: str | None) -> Awaitable[ListPromptsResult]:+            return self._maybe_serialize_request(+                lambda: session.list_prompts() if cursor is None else session.list_prompts(cursor)+            )+         return await self._run_request_with_transport_error_redaction(             "list prompts",-            lambda: self._maybe_serialize_request(lambda: session.list_prompts()),+            lambda: self._fetch_all_pages("list prompts", "prompts", fetch_prompts_page),         )      async def get_prompt(@@ -1284,27 +1328,59 @@ class _MCPServerWithClientSession(MCPServer, abc.ABC):         )      async def list_resources(self, cursor: str | None = None) -> ListResourcesResult:-        """List the resources available on the server."""+        """List the resources available on the server.++        When ``cursor`` is ``None`` every page is fetched and merged; otherwise only the+        page for ``cursor`` is returned.+        """         if not self.session:             raise UserError("Server not initialized. Make sure you call `connect()` first.")         session = self.session         assert session is not None++        def fetch_resources_page(page_cursor: str | None) -> Awaitable[ListResourcesResult]:+            return self._maybe_serialize_request(lambda: session.list_resources(page_cursor))++        if cursor is not None:+            return await self._run_request_with_transport_error_redaction(+                "list resources",+                lambda: fetch_resources_page(cursor),+            )         return await self._run_request_with_transport_error_redaction(             "list resources",-            lambda: self._maybe_serialize_request(lambda: session.list_resources(cursor)),+            lambda: self._fetch_all_pages("list resources", "resources", fetch_resources_page),         )      async def list_resource_templates(         self, cursor: str | None = None     ) -> ListResourceTemplatesResult:-        """List the resource templates available on the server."""+        """List the resource templates available on the server.++        When ``cursor`` is ``None`` every page is fetched and merged; otherwise only the+        page for ``cursor`` is returned.+        """         if not self.session:             raise UserError("Server not initialized. Make sure you call `connect()` first.")         session = self.session         assert session is not None++        def fetch_templates_page(+            page_cursor: str | None,+        ) -> Awaitable[ListResourceTemplatesResult]:+            return self._maybe_serialize_request(+                lambda: session.list_resource_templates(page_cursor)+            )++        if cursor is not None:+            return await self._run_request_with_transport_error_redaction(+                "list resource templates",+                lambda: fetch_templates_page(cursor),+            )         return await self._run_request_with_transport_error_redaction(             "list resource templates",-            lambda: self._maybe_serialize_request(lambda: session.list_resource_templates(cursor)),+            lambda: self._fetch_all_pages(+                "list resource templates", "resourceTemplates", fetch_templates_page+            ),         )      async def read_resource(self, uri: str) -> ReadResourceResult:tests/mcp/test_mcp_pagination.pynew file mode 100644index 00000000..004d011c@@ -0,0 +1,248 @@+"""Tests that MCP listing APIs follow ``nextCursor`` and return every page."""++from typing import Any, cast++import pytest+from mcp import ClientSession, Tool as MCPTool+from mcp.types import (+    ListPromptsResult,+    ListResourcesResult,+    ListResourceTemplatesResult,+    ListToolsResult,+    Prompt,+    Resource,+    ResourceTemplate,+)+from pydantic import AnyUrl++from agents import Agent+from agents.exceptions import UserError+from agents.mcp import MCPUtil, create_static_tool_filter+from agents.mcp.server import _MCPServerWithClientSession+from agents.run_context import RunContextWrapper+++def _tool(name: str) -> MCPTool:+    return MCPTool(name=name, inputSchema={"type": "object", "properties": {}})+++class PaginatedSession:+    """Fake ClientSession that serves results in pages keyed by cursor."""++    def __init__(self, fail_tool_pages: dict[str | None, int] | None = None):+        self.tool_pages: dict[str | None, ListToolsResult] = {+            None: ListToolsResult(tools=[_tool("a"), _tool("b")], nextCursor="p2"),+            "p2": ListToolsResult(tools=[_tool("c")], nextCursor="p3"),+            "p3": ListToolsResult(tools=[_tool("d")]),+        }+        self.prompt_pages: dict[str | None, ListPromptsResult] = {+            None: ListPromptsResult(prompts=[Prompt(name="p1")], nextCursor="c2"),+            "c2": ListPromptsResult(prompts=[Prompt(name="p2")]),+        }+        self.resource_pages: dict[str | None, ListResourcesResult] = {+            None: ListResourcesResult(+                resources=[Resource(uri=AnyUrl("file:///a.txt"), name="a")], nextCursor="r2"+            ),+            "r2": ListResourcesResult(resources=[Resource(uri=AnyUrl("file:///b.txt"), name="b")]),+        }+        self.template_pages: dict[str | None, ListResourceTemplatesResult] = {+            None: ListResourceTemplatesResult(+                resourceTemplates=[ResourceTemplate(uriTemplate="file:///{a}", name="a")],+                nextCursor="t2",+            ),+            "t2": ListResourceTemplatesResult(+                resourceTemplates=[ResourceTemplate(uriTemplate="file:///{b}", name="b")]+            ),+        }+        self.fail_tool_pages = dict(fail_tool_pages or {})+        self.tool_calls: list[str | None] = []+        self.prompt_calls: list[str | None] = []+        self.resource_calls: list[str | None] = []+        self.template_calls: list[str | None] = []++    async def list_tools(self, cursor: str | None = None) -> ListToolsResult:+        self.tool_calls.append(cursor)+        if self.fail_tool_pages.get(cursor, 0) > 0:+            self.fail_tool_pages[cursor] -= 1+            raise RuntimeError(f"list_tools failure on {cursor}")+        return self.tool_pages[cursor]++    async def list_prompts(self, cursor: str | None = None) -> ListPromptsResult:+        self.prompt_calls.append(cursor)+        return self.prompt_pages[cursor]++    async def list_resources(self, cursor: str | None = None) -> ListResourcesResult:+        self.resource_calls.append(cursor)+        return self.resource_pages[cursor]++    async def list_resource_templates(+        self, cursor: str | None = None+    ) -> ListResourceTemplatesResult:+        self.template_calls.append(cursor)+        return self.template_pages[cursor]+++class PaginatedServer(_MCPServerWithClientSession):+    def __init__(+        self,+        session: PaginatedSession,+        *,+        cache_tools_list: bool = False,+        retries: int = 0,+        tool_filter: Any = None,+    ):+        super().__init__(+            cache_tools_list=cache_tools_list,+            client_session_timeout_seconds=None,+            tool_filter=tool_filter,+            max_retry_attempts=retries,+            retry_backoff_seconds_base=0,+        )+        self.session = cast(ClientSession, session)++    def create_streams(self):+        raise NotImplementedError++    @property+    def name(self) -> str:+        return "paginated"+++@pytest.mark.asyncio+async def test_list_tools_returns_all_pages():+    session = PaginatedSession()+    server = PaginatedServer(session)++    tools = await server.list_tools()++    assert [t.name for t in tools] == ["a", "b", "c", "d"]+    assert session.tool_calls == [None, "p2", "p3"]+++@pytest.mark.asyncio+async def test_list_tools_cache_holds_all_pages():+    session = PaginatedSession()+    server = PaginatedServer(session, cache_tools_list=True)++    first = await server.list_tools()+    second = await server.list_tools()++    assert [t.name for t in first] == ["a", "b", "c", "d"]+    assert [t.name for t in second] == ["a", "b", "c", "d"]+    assert server.cached_tools is not None+    assert [t.name for t in server.cached_tools] == ["a", "b", "c", "d"]+    assert session.tool_calls == [None, "p2", "p3"]+++@pytest.mark.asyncio+async def test_list_tools_filter_applies_after_all_pages():+    session = PaginatedSession()+    server = PaginatedServer(+        session,+        cache_tools_list=True,+        tool_filter=create_static_tool_filter(allowed_tool_names=["a", "d"]),+    )+    run_context = RunContextWrapper(context=None)+    agent = Agent(name="agent")++    tools = await server.list_tools(run_context, agent)++    assert [t.name for t in tools] == ["a", "d"]+    # The unfiltered list is what gets cached.+    assert server.cached_tools is not None+    assert [t.name for t in server.cached_tools] == ["a", "b", "c", "d"]+++@pytest.mark.asyncio+async def test_list_tools_retries_failed_page_without_restarting():+    session = PaginatedSession(fail_tool_pages={"p2": 2})+    server = PaginatedServer(session, retries=2)++    tools = await server.list_tools()++    assert [t.name for t in tools] == ["a", "b", "c", "d"]+    assert session.tool_calls == [None, "p2", "p2", "p2", "p3"]+++@pytest.mark.asyncio+async def test_list_tools_repeated_cursor_raises():+    session = PaginatedSession()+    session.tool_pages["p3"] = ListToolsResult(tools=[_tool("d")], nextCursor="p2")+    server = PaginatedServer(session)++    with pytest.raises(UserError, match="repeated pagination cursor"):+        await server.list_tools()+++@pytest.mark.asyncio+async def test_agent_function_tools_include_tools_from_all_pages():+    session = PaginatedSession()+    server = PaginatedServer(session)+    agent = Agent(name="agent", mcp_servers=[server])++    tools = await MCPUtil.get_all_function_tools(+        [server],+        convert_schemas_to_strict=False,+        run_context=RunContextWrapper(context=None),+        agent=agent,+    )++    assert [t.name for t in tools] == ["a", "b", "c", "d"]+++@pytest.mark.asyncio+async def test_list_prompts_returns_all_pages():+    session = PaginatedSession()+    server = PaginatedServer(session)++    result = await server.list_prompts()++    assert [p.name for p in result.prompts] == ["p1", "p2"]+    assert result.nextCursor is None+    assert session.prompt_calls == [None, "c2"]+++@pytest.mark.asyncio+async def test_list_resources_returns_all_pages():+    session = PaginatedSession()+    server = PaginatedServer(session)++    result = await server.list_resources()++    assert [r.name for r in result.resources] == ["a", "b"]+    assert result.nextCursor is None+    assert session.resource_calls == [None, "r2"]+++@pytest.mark.asyncio+async def test_list_resources_with_cursor_returns_single_page():+    session = PaginatedSession()+    server = PaginatedServer(session)++    first = await server.list_resources(cursor="r2")++    assert [r.name for r in first.resources] == ["b"]+    assert session.resource_calls == ["r2"]+++@pytest.mark.asyncio+async def test_list_resource_templates_returns_all_pages():+    session = PaginatedSession()+    server = PaginatedServer(session)++    result = await server.list_resource_templates()++    assert [t.name for t in result.resourceTemplates] == ["a", "b"]+    assert result.nextCursor is None+    assert session.template_calls == [None, "t2"]+++@pytest.mark.asyncio+async def test_list_resource_templates_with_cursor_returns_single_page():+    session = PaginatedSession()+    server = PaginatedServer(session)++    result = await server.list_resource_templates(cursor="t2")++    assert [t.name for t in result.resourceTemplates] == ["b"]+    assert session.template_calls == ["t2"] 
Merged fix · PR #4094+561 −14
src/agents/mcp/server.pyindex 168a476e1..4a04aa50e 100644@@ -34,6 +34,8 @@ from mcp.types import (     ListPromptsResult,     ListResourcesResult,     ListResourceTemplatesResult,+    ListToolsResult,+    PaginatedRequestParams,     ReadResourceResult, ) from typing_extensions import NotRequired, TypedDict@@ -764,6 +766,27 @@ class _MCPServerWithClientSession(MCPServer, abc.ABC):         async with self._request_lock:             return await func() +    async def _list_tools_page(+        self, session: ClientSession, cursor: str | None = None+    ) -> ListToolsResult:+        return await self._maybe_serialize_request(+            lambda: session.list_tools()+            if cursor is None+            else session.list_tools(params=PaginatedRequestParams(cursor=cursor))+        )++    async def _list_prompts_page(+        self, session: ClientSession, cursor: str | None = None+    ) -> ListPromptsResult:+        return await self._run_request_with_transport_error_redaction(+            "list prompts",+            lambda: self._maybe_serialize_request(+                lambda: session.list_prompts()+                if cursor is None+                else session.list_prompts(params=PaginatedRequestParams(cursor=cursor))+            ),+        )+     async def _apply_tool_filter(         self,         tools: list[MCPTool],@@ -1120,17 +1143,61 @@ class _MCPServerWithClientSession(MCPServer, abc.ABC):         transport_error: UserError | None = None         transport_cause: Exception | None = None         try:+            tools: list[MCPTool]             # Return from cache if caching is enabled, we have tools, and the cache is not dirty             if self.cache_tools_list and not self._cache_dirty and self._tools_list:                 tools = self._tools_list             else:-                # Fetch the tools from the server-                result = await self._run_with_retries(-                    lambda: self._maybe_serialize_request(lambda: session.list_tools())-                )-                self._tools_list = result.tools+                tools = []+                cursor: str | None = None+                seen_cursors: set[str | None] = set()++                async def fetch_pages() -> bool:+                    nonlocal cursor+                    while True:+                        result = await self._list_tools_page(session, cursor)+                        tools.extend(result.tools)+                        seen_cursors.add(cursor)+                        next_cursor = result.nextCursor+                        if next_cursor is None:+                            return True+                        if next_cursor in seen_cursors:+                            return False+                        cursor = next_cursor++                pagination_complete = False+                pagination_failure: BaseException | None = None+                try:+                    pagination_complete = await self._run_with_retries(fetch_pages)+                except BaseException as error:+                    if cursor is None:+                        raise+                    if isinstance(error, BaseExceptionGroup):+                        pagination_failure = _credential_safe_exception_group(error)+                    elif isinstance(error, Exception):+                        pagination_failure = self._user_error_for_request_operation(+                            "list tools", error+                        )+                    else:+                        pagination_failure = _credential_safe_exception_leaf(error)++                if pagination_failure is not None or not pagination_complete:+                    cursor = None+                    seen_cursors.clear()+                    tools.clear()+                    del fetch_pages+                    if pagination_failure is not None:+                        raise pagination_failure from None+                    raise UserError(+                        f"MCP server '{self._error_name}' returned a repeated cursor while "+                        "listing tools."+                    ) from None++                cursor = None+                seen_cursors.clear()+                del fetch_pages+                self._tools_list = tools                 self._cache_dirty = False-                tools = self._tools_list              # Filter tools based on tool_filter             filtered_tools = tools@@ -1265,10 +1332,52 @@ class _MCPServerWithClientSession(MCPServer, abc.ABC):             raise UserError("Server not initialized. Make sure you call `connect()` first.")         session = self.session         assert session is not None-        return await self._run_request_with_transport_error_redaction(-            "list prompts",-            lambda: self._maybe_serialize_request(lambda: session.list_prompts()),-        )+        result = await self._list_prompts_page(session)+        if result.nextCursor is None:+            return result++        prompts = list(result.prompts)+        cursor: str | None = result.nextCursor+        seen_cursors: set[str | None] = {None}+        pagination_failure: BaseException | None = None+        repeated_cursor = False+        page: ListPromptsResult | None = None+        next_cursor: str | None = None+        while cursor is not None:+            try:+                page = await self._list_prompts_page(session, cursor)+            except BaseException as error:+                if isinstance(error, BaseExceptionGroup):+                    pagination_failure = _credential_safe_exception_group(error)+                elif isinstance(error, Exception):+                    pagination_failure = self._user_error_for_request_operation(+                        "list prompts", error+                    )+                else:+                    pagination_failure = _credential_safe_exception_leaf(error)+                break+            prompts.extend(page.prompts)+            seen_cursors.add(cursor)+            next_cursor = page.nextCursor+            if next_cursor is not None and next_cursor in seen_cursors:+                repeated_cursor = True+                break+            cursor = next_cursor++        if pagination_failure is not None or repeated_cursor:+            cursor = None+            seen_cursors.clear()+            prompts.clear()+            page = None+            next_cursor = None+            del result+            if pagination_failure is not None:+                raise pagination_failure from None+            raise UserError(+                f"MCP server '{self._error_name}' returned a repeated cursor while listing prompts."+            ) from None++        return result.model_copy(update={"prompts": prompts, "nextCursor": None})      async def get_prompt(         self, name: str, arguments: dict[str, Any] | None = Nonetests/mcp/servers/paginated.pynew file mode 100644index 000000000..06e706324@@ -0,0 +1,78 @@+from __future__ import annotations++import anyio+from mcp.server import Server+from mcp.server.stdio import stdio_server+from mcp.types import (+    ListPromptsRequest,+    ListPromptsResult,+    ListToolsRequest,+    ListToolsResult,+    Prompt,+    TextContent,+    Tool,+)++server = Server("paginated-test-server")+++@server.list_tools()  # type: ignore[misc]+async def list_tools(request: ListToolsRequest) -> ListToolsResult:+    cursor = request.params.cursor if request.params is not None else None+    if cursor is None:+        return ListToolsResult(+            tools=[+                Tool(+                    name="first_page_tool",+                    inputSchema={"type": "object", "properties": {}},+                )+            ],+            nextCursor="",+        )+    if cursor == "":+        return ListToolsResult(+            tools=[+                Tool(+                    name="second_page_tool",+                    inputSchema={"type": "object", "properties": {}},+                )+            ],+        )+    raise ValueError(f"Unexpected tools cursor: {cursor}")+++@server.list_prompts()  # type: ignore[misc]+async def list_prompts(request: ListPromptsRequest) -> ListPromptsResult:+    cursor = request.params.cursor if request.params is not None else None+    if cursor is None:+        return ListPromptsResult(+            prompts=[Prompt(name="first_page_prompt")],+            nextCursor="",+            _meta={"page": "first"},+        )+    if cursor == "":+        return ListPromptsResult(+            prompts=[Prompt(name="second_page_prompt")],+            _meta={"page": "second"},+        )+    raise ValueError(f"Unexpected prompts cursor: {cursor}")+++@server.call_tool()  # type: ignore[misc]+async def call_tool(name: str, arguments: dict[str, object] | None) -> list[TextContent]:+    if name not in {"first_page_tool", "second_page_tool"}:+        raise ValueError(f"Unexpected tool: {name}")+    return [TextContent(type="text", text=f"called:{name}")]+++async def main() -> None:+    async with stdio_server() as (read_stream, write_stream):+        await server.run(+            read_stream,+            write_stream,+            server.create_initialization_options(),+        )+++if __name__ == "__main__":+    anyio.run(main)tests/mcp/test_caching.pyindex f31cdf951..4465a5e05 100644@@ -1,7 +1,7 @@-from unittest.mock import AsyncMock, patch+from unittest.mock import AsyncMock, call, patch  import pytest-from mcp.types import ListToolsResult, Tool as MCPTool+from mcp.types import ListToolsResult, PaginatedRequestParams, Tool as MCPTool  from agents import Agent from agents.mcp import MCPServerStdio@@ -61,3 +61,36 @@ async def test_server_caching_works(         # Without invalidating the cache, calling list_tools() again should return the cached value         result_tools = await server.list_tools(run_context, agent)         assert result_tools == tools+++@pytest.mark.asyncio+@patch("mcp.client.stdio.stdio_client", return_value=DummyStreamsContextManager())+@patch("mcp.client.session.ClientSession.initialize", new_callable=AsyncMock, return_value=None)+@patch("mcp.client.session.ClientSession.list_tools")+async def test_paginated_tools_are_cached_before_filtering(+    mock_list_tools: AsyncMock, mock_initialize: AsyncMock, mock_stdio_client+):+    first_page_tool = MCPTool(name="first_page_tool", inputSchema={})+    second_page_tool = MCPTool(name="second_page_tool", inputSchema={})+    mock_list_tools.side_effect = [+        ListToolsResult(tools=[first_page_tool], nextCursor=""),+        ListToolsResult(tools=[second_page_tool]),+    ]+    server = MCPServerStdio(+        params={"command": tee},+        cache_tools_list=True,+        tool_filter={"allowed_tool_names": ["second_page_tool"]},+    )++    async with server:+        filtered_tools = await server.list_tools()+        cached_tools = server.cached_tools+        filtered_tools_again = await server.list_tools()++    assert filtered_tools == [second_page_tool]+    assert filtered_tools_again == [second_page_tool]+    assert cached_tools == [first_page_tool, second_page_tool]+    assert mock_list_tools.await_args_list == [+        call(),+        call(params=PaginatedRequestParams(cursor="")),+    ]tests/mcp/test_client_session_retries.pyindex 4187e1afb..c86879107 100644@@ -8,7 +8,15 @@ import pytest from anyio import ClosedResourceError from mcp import ClientSession, Tool as MCPTool from mcp.shared.exceptions import McpError-from mcp.types import CallToolResult, ErrorData, GetPromptResult, ListPromptsResult, ListToolsResult+from mcp.types import (+    CallToolResult,+    ErrorData,+    GetPromptResult,+    ListPromptsResult,+    ListToolsResult,+    PaginatedRequestParams,+    Prompt,+)  from agents.exceptions import UserError from agents.mcp.server import MCPServerStreamableHttp, _MCPServerWithClientSession@@ -30,7 +38,7 @@ class DummySession:             raise RuntimeError("call_tool failure")         return CallToolResult(content=[]) -    async def list_tools(self):+    async def list_tools(self, *, params: PaginatedRequestParams | None = None):         self.list_tools_attempts += 1         if self.list_tools_attempts <= self.fail_list_tools:             raise RuntimeError("list_tools failure")@@ -75,6 +83,121 @@ async def test_list_tools_unlimited_retries():     assert session.list_tools_attempts == 4  +class PaginatedRetrySession(DummySession):+    def __init__(self):+        super().__init__()+        self.cursors: list[str | None] = []+        self.second_page_attempts = 0++    async def list_tools(self, *, params: PaginatedRequestParams | None = None):+        cursor = params.cursor if params is not None else None+        self.cursors.append(cursor)+        if cursor is None:+            return ListToolsResult(+                tools=[MCPTool(name="first_page_tool", inputSchema={})],+                nextCursor="second-page",+            )++        self.second_page_attempts += 1+        if self.second_page_attempts == 1:+            raise RuntimeError("second page failure")+        return ListToolsResult(tools=[MCPTool(name="second_page_tool", inputSchema={})])+++@pytest.mark.asyncio+async def test_list_tools_retries_only_the_failed_page():+    session = PaginatedRetrySession()+    server = DummyServer(session=session, retries=1)++    tools = await server.list_tools()++    assert [tool.name for tool in tools] == ["first_page_tool", "second_page_tool"]+    assert session.cursors == [None, "second-page", "second-page"]+++class SharedRetryBudgetSession(DummySession):+    def __init__(self):+        super().__init__()+        self.cursors: list[str | None] = []++    async def list_tools(self, *, params: PaginatedRequestParams | None = None):+        cursor = params.cursor if params is not None else None+        self.cursors.append(cursor)+        if self.cursors == [None]:+            raise RuntimeError("first page failure")+        if cursor is None:+            return ListToolsResult(+                tools=[MCPTool(name="first_page_tool", inputSchema={})],+                nextCursor="second-page",+            )+        raise RuntimeError("second page failure")+++@pytest.mark.asyncio+async def test_list_tools_shares_retry_budget_across_pages():+    session = SharedRetryBudgetSession()+    server = DummyServer(session=session, retries=1)++    with pytest.raises(UserError, match="Failed to list tools.*Request failed"):+        await server.list_tools()++    assert session.cursors == [None, None, "second-page"]+++class RepeatedCursorSession(DummySession):+    def __init__(self):+        super().__init__()+        self.tool_cursors: list[str | None] = []+        self.prompt_cursors: list[str | None] = []++    async def list_tools(self, *, params: PaginatedRequestParams | None = None):+        cursor = params.cursor if params is not None else None+        self.tool_cursors.append(cursor)+        if cursor is None:+            return ListToolsResult(+                tools=[MCPTool(name="first_page_tool", inputSchema={})],+                nextCursor="tenant-secret-cursor",+            )+        return ListToolsResult(+            tools=[MCPTool(name="second_page_tool", inputSchema={})],+            nextCursor="tenant-secret-cursor",+        )++    async def list_prompts(+        self, *, params: PaginatedRequestParams | None = None+    ) -> ListPromptsResult:+        cursor = params.cursor if params is not None else None+        self.prompt_cursors.append(cursor)+        if cursor is None:+            return ListPromptsResult(+                prompts=[Prompt(name="first_page_prompt")],+                nextCursor="tenant-secret-cursor",+                _meta={"page": "first"},+            )+        return ListPromptsResult(+            prompts=[Prompt(name="second_page_prompt")],+            nextCursor="tenant-secret-cursor",+            _meta={"page": "second"},+        )+++@pytest.mark.asyncio+async def test_paginated_lists_reject_a_repeated_cursor_without_caching_partial_tools():+    session = RepeatedCursorSession()+    server = DummyServer(session=session, retries=1)++    with pytest.raises(UserError, match="repeated cursor while listing tools") as tools_error:+        await server.list_tools()+    with pytest.raises(UserError, match="repeated cursor while listing prompts") as prompts_error:+        await server.list_prompts()++    assert server.cached_tools is None+    assert session.tool_cursors == [None, "tenant-secret-cursor"]+    assert session.prompt_cursors == [None, "tenant-secret-cursor"]+    assert "tenant-secret-cursor" not in str(tools_error.value)+    assert "tenant-secret-cursor" not in str(prompts_error.value)++ @pytest.mark.asyncio async def test_call_tool_validates_required_parameters_before_remote_call():     session = DummySession()tests/mcp/test_mcp_pagination_integration.pynew file mode 100644index 000000000..30e1f03b7@@ -0,0 +1,63 @@+from __future__ import annotations++import sys+from pathlib import Path++import pytest++from agents import Agent, Runner+from agents.mcp import MCPServerStdio++from ..fake_model import FakeModel+from ..test_responses import get_function_tool_call, get_text_message++PAGINATED_SERVER_PATH = Path(__file__).parent / "servers" / "paginated.py"+++def create_paginated_server() -> MCPServerStdio:+    return MCPServerStdio(+        name="paginated-test-server",+        params={+            "command": sys.executable,+            "args": [str(PAGINATED_SERVER_PATH)],+        },+        cache_tools_list=True,+    )+++@pytest.mark.asyncio+async def test_stdio_server_auto_paginates_tools_and_prompts():+    async with create_paginated_server() as server:+        tools = await server.list_tools()+        prompts = await server.list_prompts()++    assert [tool.name for tool in tools] == ["first_page_tool", "second_page_tool"]+    assert [prompt.name for prompt in prompts.prompts] == [+        "first_page_prompt",+        "second_page_prompt",+    ]+    assert prompts.nextCursor is None+    assert prompts.meta == {"page": "first"}+++@pytest.mark.asyncio+async def test_agent_calls_tool_from_second_stdio_page():+    model = FakeModel()+    model.add_multiple_turn_outputs(+        [+            [get_function_tool_call("second_page_tool", "{}")],+            [get_text_message("done")],+        ]+    )++    async with create_paginated_server() as server:+        result = await Runner.run(+            Agent(name="test", model=model, mcp_servers=[server]),+            input="Call the second-page tool.",+        )++    tool_outputs = [+        item.output for item in result.new_items if item.type == "tool_call_output_item"+    ]+    assert result.final_output == "done"+    assert tool_outputs == [{"type": "text", "text": "called:second_page_tool"}]tests/mcp/test_server_errors.pyindex fc4d3f2a5..1b1cd3e70 100644@@ -7,6 +7,7 @@ from unittest.mock import AsyncMock, MagicMock, patch  import httpx import pytest+from mcp.types import ListPromptsResult, ListToolsResult  from agents import Agent, _debug from agents.exceptions import UserError@@ -96,6 +97,18 @@ def _assert_url_credentials_hidden_from_traceback_locals(error: BaseException) -         current = current.tb_next  +def _assert_text_hidden_from_server_traceback_locals(+    error: BaseException,+    sensitive_text: str,+) -> None:+    current = error.__traceback__+    while current is not None:+        if current.tb_frame.f_code.co_filename.endswith("/src/agents/mcp/server.py"):+            attached_values = repr(tuple(current.tb_frame.f_locals.values()))+            assert sensitive_text not in attached_values+        current = current.tb_next++ def _assert_url_credentials_hidden_from_log_record(record: logging.LogRecord) -> None:     rendered = logging.Formatter("%(levelname)s %(message)s").format(record)     attached_values = repr(@@ -326,6 +339,134 @@ async def test_prompt_request_http_status_hides_url_credentials():     _assert_url_credentials_hidden_from_traceback_locals(user_error_info.value)  +def _paginated_list_result(+    method_name: str,+    next_cursor: str,+) -> ListToolsResult | ListPromptsResult:+    if method_name == "list_tools":+        return ListToolsResult(tools=[], nextCursor=next_cursor)+    return ListPromptsResult(prompts=[], nextCursor=next_cursor)+++@pytest.mark.asyncio+@pytest.mark.parametrize("method_name", ["list_tools", "list_prompts"])+async def test_paginated_list_failure_does_not_retain_opaque_cursor(method_name: str):+    cursor = "SECRET_OPAQUE_CURSOR"+    failure_message = "SECRET_CONTINUATION_FAILURE"+    continuation_error = RuntimeError(failure_message)+    server = MCPServerStreamableHttp(params={"url": _SAFE_URL})+    session = MagicMock()+    setattr(+        session,+        method_name,+        AsyncMock(+            side_effect=[+                _paginated_list_result(method_name, cursor),+                continuation_error,+            ]+        ),+    )+    server.session = session+    server.max_retry_attempts = 0++    with pytest.raises(UserError) as user_error_info:+        await getattr(server, method_name)()++    rendered = "".join(traceback.format_exception(user_error_info.value))+    assert "Request failed" in str(user_error_info.value)+    assert cursor not in rendered+    assert failure_message not in rendered+    assert user_error_info.value.__cause__ is None+    assert user_error_info.value.__context__ is None+    _assert_not_retained_in_exception_graph(user_error_info.value, continuation_error)+    _assert_text_hidden_from_server_traceback_locals(user_error_info.value, cursor)+++@pytest.mark.asyncio+@pytest.mark.parametrize("method_name", ["list_tools", "list_prompts"])+async def test_paginated_list_cycle_does_not_retain_opaque_cursor(method_name: str):+    cursor = "SECRET_OPAQUE_CURSOR"+    server = MCPServerStreamableHttp(params={"url": _SAFE_URL})+    session = MagicMock()+    setattr(+        session,+        method_name,+        AsyncMock(+            side_effect=[+                _paginated_list_result(method_name, cursor),+                _paginated_list_result(method_name, cursor),+            ]+        ),+    )+    server.session = session+    server.max_retry_attempts = 0++    with pytest.raises(UserError, match=f"repeated cursor while listing {method_name[5:]}") as info:+        await getattr(server, method_name)()++    assert cursor not in "".join(traceback.format_exception(info.value))+    assert info.value.__cause__ is None+    assert info.value.__context__ is None+    _assert_text_hidden_from_server_traceback_locals(info.value, cursor)+    if method_name == "list_tools":+        assert server.cached_tools is None+++@pytest.mark.asyncio+@pytest.mark.parametrize("method_name", ["list_tools", "list_prompts"])+async def test_paginated_list_cancellation_preserves_control_flow_without_cursor(+    method_name: str,+):+    cursor = "SECRET_OPAQUE_CURSOR"+    cancellation = asyncio.CancelledError(cursor)+    server = MCPServerStreamableHttp(params={"url": _SAFE_URL})+    session = MagicMock()+    setattr(+        session,+        method_name,+        AsyncMock(+            side_effect=[+                _paginated_list_result(method_name, cursor),+                cancellation,+            ]+        ),+    )+    server.session = session+    server.max_retry_attempts = 0++    with pytest.raises(asyncio.CancelledError) as cancellation_info:+        await getattr(server, method_name)()++    assert str(cancellation_info.value) == ""+    assert cancellation_info.value.__cause__ is None+    assert cancellation_info.value.__context__ is None+    _assert_not_retained_in_exception_graph(cancellation_info.value, cancellation)+    _assert_text_hidden_from_server_traceback_locals(cancellation_info.value, cursor)+++@pytest.mark.asyncio+async def test_paginated_tools_clear_cursor_before_filter_failure():+    cursor = "SECRET_OPAQUE_CURSOR"+    server = MCPServerStreamableHttp(+        params={"url": _SAFE_URL},+        tool_filter=lambda context, tool: True,+    )+    session = MagicMock()+    session.list_tools = AsyncMock(+        side_effect=[+            ListToolsResult(tools=[], nextCursor=cursor),+            ListToolsResult(tools=[]),+        ]+    )+    server.session = session++    with pytest.raises(UserError, match="run_context and agent are required") as error_info:+        await server.list_tools()++    assert cursor not in "".join(traceback.format_exception(error_info.value))+    _assert_text_hidden_from_server_traceback_locals(error_info.value, cursor)++ @pytest.mark.asyncio async def test_resource_request_nested_group_replaces_ordinary_siblings_safely():     server = MCPServerStreamableHttp(params={"url": _CREDENTIALED_URL})