Skip to content

Add MCP-compliant pagination support#2903

Merged
jlowin merged 3 commits intomainfrom
feature/pagination-support
Jan 18, 2026
Merged

Add MCP-compliant pagination support#2903
jlowin merged 3 commits intomainfrom
feature/pagination-support

Conversation

@jlowin
Copy link
Copy Markdown
Member

@jlowin jlowin commented Jan 18, 2026

Closes #540, closes #211, closes #1465

Adds pagination support for tools/list, resources/list, resources/templates/list, and prompts/list operations per the MCP spec.

Server: Opt-in by setting list_page_size:

server = FastMCP("MyServer", list_page_size=50)

Results are chunked with opaque cursors. When not configured, behavior is unchanged (all results in one response).

Client: Convenience methods auto-fetch all pages transparently:

async with Client(server) as client:
    # Returns all tools, fetching pages as needed
    tools = await client.list_tools()
    
    # Manual pagination for large result sets
    result = await client.list_tools_mcp()
    first_page = result.tools
    if result.nextCursor:
        next_page = await client.list_tools_mcp(cursor=result.nextCursor)

Server authors opt-in by setting list_page_size on FastMCP.
Client convenience methods auto-fetch all pages transparently.
Use _mcp methods with cursor parameter for manual pagination.
@marvin-context-protocol marvin-context-protocol Bot added enhancement Improvement to existing functionality. For issues and smaller PR improvements. server Related to FastMCP server implementation or server-side functionality. client Related to the FastMCP client SDK or client-side functionality. labels Jan 18, 2026
Copy link
Copy Markdown

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 96d4b1b606

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/fastmcp/utilities/pagination.py
Comment thread src/fastmcp/utilities/pagination.py
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Jan 18, 2026

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

Walkthrough

This pull request adds cursor-based pagination across FastMCP client and server list operations. It introduces pagination utilities (base64-encoded opaque cursors), a configurable list_page_size constructor parameter for FastMCP, paginated MCP list handlers that return nextCursor, client _mcp methods that accept a cursor for manual iteration, and convenience client methods that auto-fetch all pages. Documentation pages and navigation entries for server pagination are also added.

Possibly related PRs

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Add MCP-compliant pagination support' clearly and concisely summarizes the primary change—implementing MCP-spec pagination for list operations.
Description check ✅ Passed The PR description includes issue closure references, clear explanation of server/client features with code examples, and closes linked issues. However, it lacks the Contributors/Review Checklist items from the template.
Linked Issues check ✅ Passed The code changes fully implement pagination requirements across all linked issues: #540 (MCP-compliant pagination), #211 (server-side pagination with backward compatibility), and #1465 (context length mitigation via chunked responses).
Out of Scope Changes check ✅ Passed All changes are directly scoped to implementing pagination support as required by linked issues. Documentation updates, new pagination utilities, server/client modifications, and examples are all within scope.
Docstring Coverage ✅ Passed Docstring coverage is 89.66% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/fastmcp/server/context.py (1)

343-361: Context.list_resources() and list_prompts() return incomplete results when pagination is enabled.

These methods call the paginated MCP handlers but don't loop through pages. When list_page_size is configured, they return only the first page. The docstrings claim "List all available resources/prompts," which is misleading—they should either fetch all pages like the Client methods do, or update the docstrings to clarify they return only the first page.

This has real impact: the tool injection middleware in src/fastmcp/server/middleware/tool_injection.py (lines 56, 90) uses these methods to create tools that get injected into the server. When pagination is enabled, users would get incomplete lists from those tools.

Consider either:

  1. Loop through all pages to match Client behavior and docstring promises
  2. Update docstrings to clarify pagination behavior
  3. Add pagination tests for Context methods to prevent regression
🧹 Nitpick comments (1)
docs/servers/pagination.mdx (1)

41-66: Make the client examples runnable with an async entrypoint and basic error handling.

These snippets rely on an implicit async context and omit error handling; consider adding an entrypoint and a minimal try/except. Apply a similar pattern to the manual pagination block.

♻️ Proposed update (apply similarly to the manual pagination block)
-from fastmcp import Client
-
-async with Client(server) as client:
-    # Returns all 200 tools, fetching pages automatically
-    tools = await client.list_tools()
-    print(f"Total tools: {len(tools)}")  # 200
+import asyncio
+from fastmcp import Client
+
+async def main() -> None:
+    async with Client(server) as client:
+        try:
+            # Returns all 200 tools, fetching pages automatically
+            tools = await client.list_tools()
+        except Exception as exc:
+            print(f"Failed to list tools: {exc}")
+            return
+        print(f"Total tools: {len(tools)}")  # Expected: 200
+
+if __name__ == "__main__":
+    asyncio.run(main())

Please run the updated snippet to confirm the expected output. As per coding guidelines, examples should be runnable and include error handling.

Comment thread docs/servers/pagination.mdx
Comment thread src/fastmcp/server/server.py
Comment thread src/fastmcp/utilities/pagination.py
@jlowin jlowin merged commit 2eac7ab into main Jan 18, 2026
11 checks passed
@jlowin jlowin deleted the feature/pagination-support branch January 18, 2026 01:03
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

client Related to the FastMCP client SDK or client-side functionality. enhancement Improvement to existing functionality. For issues and smaller PR improvements. server Related to FastMCP server implementation or server-side functionality.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Exceed model's maximum context length Add pagination support Add optional page and limit parameters to list_tools for server‑side pagination

1 participant