Skip to content

Commit 5d823c8

Browse files
committed
feat: add pagination examples and documentation
- Create mcp_simple_pagination example server demonstrating all three paginated endpoints - Add pagination snippets for both server and client implementations - Update README to use snippet-source pattern for pagination examples - Move mutually exclusive note to blockquote format for better visibility - Complete example shows tools, resources, and prompts pagination with different page sizes
1 parent 8e0a3d4 commit 5d823c8

File tree

10 files changed

+585
-5
lines changed

10 files changed

+585
-5
lines changed

.pre-commit-config.yaml

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -25,22 +25,22 @@ repos:
2525
hooks:
2626
- id: ruff-format
2727
name: Ruff Format
28-
entry: uv run ruff
28+
entry: uv run --frozen ruff
2929
args: [format]
3030
language: system
3131
types: [python]
3232
pass_filenames: false
3333
- id: ruff
3434
name: Ruff
35-
entry: uv run ruff
35+
entry: uv run --frozen ruff
3636
args: ["check", "--fix", "--exit-non-zero-on-fix"]
3737
types: [python]
3838
language: system
3939
pass_filenames: false
4040
exclude: ^README\.md$
4141
- id: pyright
4242
name: pyright
43-
entry: uv run pyright
43+
entry: uv run --frozen pyright
4444
language: system
4545
types: [python]
4646
pass_filenames: false
@@ -52,7 +52,7 @@ repos:
5252
pass_filenames: false
5353
- id: readme-snippets
5454
name: Check README snippets are up to date
55-
entry: uv run scripts/update_readme_snippets.py --check
55+
entry: uv run --frozen scripts/update_readme_snippets.py --check
5656
language: system
5757
files: ^(README\.md|examples/.*\.py|scripts/update_readme_snippets\.py)$
5858
pass_filenames: false

README.md

Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@
4747
- [Mounting to an Existing ASGI Server](#mounting-to-an-existing-asgi-server)
4848
- [Advanced Usage](#advanced-usage)
4949
- [Low-Level Server](#low-level-server)
50+
- [Pagination (Advanced)](#pagination-advanced)
5051
- [Writing MCP Clients](#writing-mcp-clients)
5152
- [Client Display Utilities](#client-display-utilities)
5253
- [OAuth Authentication for Clients](#oauth-authentication-for-clients)
@@ -1727,6 +1728,121 @@ Tools can return data in three ways:
17271728

17281729
When an `outputSchema` is defined, the server automatically validates the structured output against the schema. This ensures type safety and helps catch errors early.
17291730

1731+
### Pagination (Advanced)
1732+
1733+
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.
1734+
1735+
#### Server-side Implementation
1736+
1737+
<!-- snippet-source examples/snippets/servers/pagination_example.py -->
1738+
```python
1739+
"""
1740+
Example of implementing pagination with MCP server decorators.
1741+
"""
1742+
1743+
from pydantic import AnyUrl
1744+
1745+
import mcp.types as types
1746+
from mcp.server.lowlevel import Server
1747+
1748+
# Initialize the server
1749+
server = Server("paginated-server")
1750+
1751+
# Sample data to paginate
1752+
ITEMS = [f"Item {i}" for i in range(1, 101)] # 100 items
1753+
1754+
1755+
@server.list_resources_paginated()
1756+
async def list_resources_paginated(cursor: types.Cursor | None) -> types.ListResourcesResult:
1757+
"""List resources with pagination support."""
1758+
page_size = 10
1759+
1760+
# Parse cursor to get offset
1761+
start = 0 if cursor is None else int(cursor)
1762+
end = start + page_size
1763+
1764+
# Get page of resources
1765+
page_items = [
1766+
types.Resource(uri=AnyUrl(f"resource://items/{item}"), name=item, description=f"Description for {item}")
1767+
for item in ITEMS[start:end]
1768+
]
1769+
1770+
# Determine next cursor
1771+
next_cursor = str(end) if end < len(ITEMS) else None
1772+
1773+
return types.ListResourcesResult(resources=page_items, nextCursor=next_cursor)
1774+
```
1775+
1776+
_Full example: [examples/snippets/servers/pagination_example.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/snippets/servers/pagination_example.py)_
1777+
<!-- /snippet-source -->
1778+
1779+
Similar decorators are available for all list operations:
1780+
1781+
- `@server.list_tools_paginated()` - for paginating tools
1782+
- `@server.list_resources_paginated()` - for paginating resources
1783+
- `@server.list_prompts_paginated()` - for paginating prompts
1784+
1785+
#### Client-side Consumption
1786+
1787+
<!-- snippet-source examples/snippets/clients/pagination_client.py -->
1788+
```python
1789+
"""
1790+
Example of consuming paginated MCP endpoints from a client.
1791+
"""
1792+
1793+
import asyncio
1794+
1795+
from mcp.client.session import ClientSession
1796+
from mcp.client.stdio import StdioServerParameters, stdio_client
1797+
from mcp.types import Resource
1798+
1799+
1800+
async def list_all_resources() -> None:
1801+
"""Fetch all resources using pagination."""
1802+
async with stdio_client(StdioServerParameters(command="uv", args=["run", "mcp-simple-pagination"])) as (
1803+
read,
1804+
write,
1805+
):
1806+
async with ClientSession(read, write) as session:
1807+
await session.initialize()
1808+
1809+
all_resources: list[Resource] = []
1810+
cursor = None
1811+
1812+
while True:
1813+
# Fetch a page of resources
1814+
result = await session.list_resources(cursor=cursor)
1815+
all_resources.extend(result.resources)
1816+
1817+
print(f"Fetched {len(result.resources)} resources")
1818+
1819+
# Check if there are more pages
1820+
if result.nextCursor:
1821+
cursor = result.nextCursor
1822+
else:
1823+
break
1824+
1825+
print(f"Total resources: {len(all_resources)}")
1826+
1827+
1828+
if __name__ == "__main__":
1829+
asyncio.run(list_all_resources())
1830+
```
1831+
1832+
_Full example: [examples/snippets/clients/pagination_client.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/snippets/clients/pagination_client.py)_
1833+
<!-- /snippet-source -->
1834+
1835+
#### Key Points
1836+
1837+
- **Cursors are opaque strings** - the server defines the format (numeric offsets, timestamps, etc.)
1838+
- **Return `nextCursor=None`** when there are no more pages
1839+
- **Backward compatible** - clients that don't support pagination will still work (they'll just get the first page)
1840+
- **Flexible page sizes** - Each endpoint can define its own page size based on data characteristics
1841+
1842+
> **NOTE**: The paginated decorators (`list_tools_paginated()`, `list_resources_paginated()`, `list_prompts_paginated()`) are mutually exclusive with their non-paginated counterparts and cannot be used together on the same server instance.
1843+
1844+
See the [simple-pagination example](examples/servers/simple-pagination) for a complete implementation.
1845+
17301846
### Writing MCP Clients
17311847

17321848
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):
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
# MCP Simple Pagination
2+
3+
A simple MCP server demonstrating pagination for tools, resources, and prompts using cursor-based pagination.
4+
5+
## Usage
6+
7+
Start the server using either stdio (default) or SSE transport:
8+
9+
```bash
10+
# Using stdio transport (default)
11+
uv run mcp-simple-pagination
12+
13+
# Using SSE transport on custom port
14+
uv run mcp-simple-pagination --transport sse --port 8000
15+
```
16+
17+
The server exposes:
18+
19+
- 25 tools (paginated, 5 per page)
20+
- 30 resources (paginated, 10 per page)
21+
- 20 prompts (paginated, 7 per page)
22+
23+
Each paginated list returns a `nextCursor` when more pages are available. Use this cursor in subsequent requests to retrieve the next page.
24+
25+
## Example
26+
27+
Using the MCP client, you can retrieve paginated items like this using the STDIO transport:
28+
29+
```python
30+
import asyncio
31+
from mcp.client.session import ClientSession
32+
from mcp.client.stdio import StdioServerParameters, stdio_client
33+
34+
35+
async def main():
36+
async with stdio_client(
37+
StdioServerParameters(command="uv", args=["run", "mcp-simple-pagination"])
38+
) as (read, write):
39+
async with ClientSession(read, write) as session:
40+
await session.initialize()
41+
42+
# Get first page of tools
43+
tools_page1 = await session.list_tools()
44+
print(f"First page: {len(tools_page1.tools)} tools")
45+
print(f"Next cursor: {tools_page1.nextCursor}")
46+
47+
# Get second page using cursor
48+
if tools_page1.nextCursor:
49+
tools_page2 = await session.list_tools(cursor=tools_page1.nextCursor)
50+
print(f"Second page: {len(tools_page2.tools)} tools")
51+
52+
# Similarly for resources
53+
resources_page1 = await session.list_resources()
54+
print(f"First page: {len(resources_page1.resources)} resources")
55+
56+
# And for prompts
57+
prompts_page1 = await session.list_prompts()
58+
print(f"First page: {len(prompts_page1.prompts)} prompts")
59+
60+
61+
asyncio.run(main())
62+
```
63+
64+
## Pagination Details
65+
66+
The server uses simple numeric indices as cursors for demonstration purposes. In production scenarios, you might use:
67+
68+
- Database offsets or row IDs
69+
- Timestamps for time-based pagination
70+
- Opaque tokens encoding pagination state
71+
72+
The pagination implementation demonstrates:
73+
74+
- Handling `None` cursor for the first page
75+
- Returning `nextCursor` when more data exists
76+
- Gracefully handling invalid cursors
77+
- Different page sizes for different resource types

examples/servers/simple-pagination/mcp_simple_pagination/__init__.py

Whitespace-only changes.
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
import sys
2+
3+
from .server import main
4+
5+
sys.exit(main()) # type: ignore[call-arg]

0 commit comments

Comments
 (0)