Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 3.8k
feat: add paginated list decorators for prompts, resources, and tools#1286
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Uh oh!
There was an error while loading. Please reload this page.
Merged
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
caeda42
feat: add paginated list decorators for prompts, resources, and tools
maxisbey 62cfab1
style: apply ruff formatting to pass pre-commit checks
maxisbey b7e6a0c
feat: add pagination examples and documentation
maxisbey 203b3ad
switch pagination to single decorator with callback inspection
maxisbey a41f972
chore: clean up inspection code to remove redundant param inspection
maxisbey dd07224
feat: change to passing requests instead of cursors for pagination
maxisbey a38351f
fix: ruff error on unit test
maxisbey a42e097
chore: rename and clarify function inspection code
maxisbey 2a592d2
feature: add type checking for passing request object
maxisbey cbb0e37
feat: change to request injection on type rather than positional
maxisbey f212f8f
fix: remove deprecation code
maxisbey File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -57,6 +57,7 @@ | ||
| - [Advanced Usage](#advanced-usage) | ||
| - [Low-Level Server](#low-level-server) | ||
| - [Structured Output Support](#structured-output-support) | ||
| - [Pagination (Advanced)](#pagination-advanced) | ||
| - [Writing MCP Clients](#writing-mcp-clients) | ||
| - [Client Display Utilities](#client-display-utilities) | ||
| - [OAuth Authentication for Clients](#oauth-authentication-for-clients) | ||
| @@ -1737,6 +1738,116 @@ Tools can return data in three ways: | ||
| When an `outputSchema` is defined, the server automatically validates the structured output against the schema. This ensures type safety and helps catch errors early. | ||
| ### Pagination (Advanced) | ||
| For servers that need to handle large datasets, the low-level server provides paginated versions of list operations. This is an optional optimization - most servers won't need pagination unless they're dealing with hundreds or thousands of items. | ||
| #### Server-side Implementation | ||
| <!-- snippet-source examples/snippets/servers/pagination_example.py --> | ||
| ```python | ||
| """ | ||
| Example of implementing pagination with MCP server decorators. | ||
| """ | ||
| from pydantic import AnyUrl | ||
| import mcp.types as types | ||
| from mcp.server.lowlevel import Server | ||
| # Initialize the server | ||
| server = Server("paginated-server") | ||
| # Sample data to paginate | ||
| ITEMS = [f"Item {i}" for i in range(1, 101)] # 100 items | ||
| @server.list_resources() | ||
| async def list_resources_paginated(request: types.ListResourcesRequest) -> types.ListResourcesResult: | ||
| """List resources with pagination support.""" | ||
| page_size = 10 | ||
| # Extract cursor from request params | ||
| cursor = request.params.cursor if request.params is not None else None | ||
| # Parse cursor to get offset | ||
| start = 0 if cursor is None else int(cursor) | ||
| end = start + page_size | ||
| # Get page of resources | ||
| page_items = [ | ||
| types.Resource(uri=AnyUrl(f"resource://items/{item}"), name=item, description=f"Description for {item}") | ||
| for item in ITEMS[start:end] | ||
| ] | ||
| # Determine next cursor | ||
| next_cursor = str(end) if end < len(ITEMS) else None | ||
| return types.ListResourcesResult(resources=page_items, nextCursor=next_cursor) | ||
| ``` | ||
| _Full example: [examples/snippets/servers/pagination_example.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/snippets/servers/pagination_example.py)_ | ||
| <!-- /snippet-source --> | ||
| #### Client-side Consumption | ||
| <!-- snippet-source examples/snippets/clients/pagination_client.py --> | ||
| ```python | ||
| """ | ||
| Example of consuming paginated MCP endpoints from a client. | ||
| """ | ||
| import asyncio | ||
| from mcp.client.session import ClientSession | ||
| from mcp.client.stdio import StdioServerParameters, stdio_client | ||
| from mcp.types import Resource | ||
| async def list_all_resources() -> None: | ||
| """Fetch all resources using pagination.""" | ||
| async with stdio_client(StdioServerParameters(command="uv", args=["run", "mcp-simple-pagination"])) as ( | ||
| read, | ||
| write, | ||
| ): | ||
| async with ClientSession(read, write) as session: | ||
| await session.initialize() | ||
| all_resources: list[Resource] = [] | ||
| cursor = None | ||
| while True: | ||
| # Fetch a page of resources | ||
| result = await session.list_resources(cursor=cursor) | ||
| all_resources.extend(result.resources) | ||
| print(f"Fetched {len(result.resources)} resources") | ||
| # Check if there are more pages | ||
| if result.nextCursor: | ||
| cursor = result.nextCursor | ||
| else: | ||
| break | ||
| print(f"Total resources: {len(all_resources)}") | ||
| if __name__ == "__main__": | ||
| asyncio.run(list_all_resources()) | ||
| ``` | ||
| _Full example: [examples/snippets/clients/pagination_client.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/snippets/clients/pagination_client.py)_ | ||
maxisbey marked this conversation as resolved.
Uh oh!There was an error while loading. Please reload this page. | ||
| <!-- /snippet-source --> | ||
| #### Key Points | ||
| - **Cursors are opaque strings** - the server defines the format (numeric offsets, timestamps, etc.) | ||
| - **Return `nextCursor=None`** when there are no more pages | ||
| - **Backward compatible** - clients that don't support pagination will still work (they'll just get the first page) | ||
| - **Flexible page sizes** - Each endpoint can define its own page size based on data characteristics | ||
| See the [simple-pagination example](examples/servers/simple-pagination) for a complete implementation. | ||
| ### Writing MCP Clients | ||
| The SDK provides a high-level client interface for connecting to MCP servers using various [transports](https://modelcontextprotocol.io/specification/2025-03-26/basic/transports): | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,77 @@ | ||
| # MCP Simple Pagination | ||
| A simple MCP server demonstrating pagination for tools, resources, and prompts using cursor-based pagination. | ||
| ## Usage | ||
| Start the server using either stdio (default) or SSE transport: | ||
| ```bash | ||
| # Using stdio transport (default) | ||
| uv run mcp-simple-pagination | ||
| # Using SSE transport on custom port | ||
| uv run mcp-simple-pagination --transport sse --port 8000 | ||
| ``` | ||
| The server exposes: | ||
| - 25 tools (paginated, 5 per page) | ||
| - 30 resources (paginated, 10 per page) | ||
| - 20 prompts (paginated, 7 per page) | ||
| Each paginated list returns a `nextCursor` when more pages are available. Use this cursor in subsequent requests to retrieve the next page. | ||
| ## Example | ||
| Using the MCP client, you can retrieve paginated items like this using the STDIO transport: | ||
| ```python | ||
| import asyncio | ||
| from mcp.client.session import ClientSession | ||
| from mcp.client.stdio import StdioServerParameters, stdio_client | ||
| async def main(): | ||
| async with stdio_client( | ||
| StdioServerParameters(command="uv", args=["run", "mcp-simple-pagination"]) | ||
| ) as (read, write): | ||
| async with ClientSession(read, write) as session: | ||
| await session.initialize() | ||
| # Get first page of tools | ||
| tools_page1 = await session.list_tools() | ||
| print(f"First page: {len(tools_page1.tools)} tools") | ||
| print(f"Next cursor: {tools_page1.nextCursor}") | ||
| # Get second page using cursor | ||
| if tools_page1.nextCursor: | ||
| tools_page2 = await session.list_tools(cursor=tools_page1.nextCursor) | ||
| print(f"Second page: {len(tools_page2.tools)} tools") | ||
| # Similarly for resources | ||
| resources_page1 = await session.list_resources() | ||
| print(f"First page: {len(resources_page1.resources)} resources") | ||
| # And for prompts | ||
| prompts_page1 = await session.list_prompts() | ||
| print(f"First page: {len(prompts_page1.prompts)} prompts") | ||
| asyncio.run(main()) | ||
| ``` | ||
| ## Pagination Details | ||
| The server uses simple numeric indices as cursors for demonstration purposes. In production scenarios, you might use: | ||
| - Database offsets or row IDs | ||
| - Timestamps for time-based pagination | ||
| - Opaque tokens encoding pagination state | ||
| The pagination implementation demonstrates: | ||
| - Handling `None` cursor for the first page | ||
| - Returning `nextCursor` when more data exists | ||
| - Gracefully handling invalid cursors | ||
| - Different page sizes for different resource types |
Empty file.
5 changes: 5 additions & 0 deletions
5 examples/servers/simple-pagination/mcp_simple_pagination/__main__.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| import sys | ||
| from .server import main | ||
| sys.exit(main()) # type: ignore[call-arg] |
Oops, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Oops, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.