Skip to content

Commit e178f6e

Browse files
authored
Merge branch 'main' into tests/add-unicode-test
2 parents 855dbae + 71889d7 commit e178f6e

40 files changed

+1738
-46
lines changed

README.md

Lines changed: 150 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,7 @@
5757
- [Advanced Usage](#advanced-usage)
5858
- [Low-Level Server](#low-level-server)
5959
- [Structured Output Support](#structured-output-support)
60+
- [Pagination (Advanced)](#pagination-advanced)
6061
- [Writing MCP Clients](#writing-mcp-clients)
6162
- [Client Display Utilities](#client-display-utilities)
6263
- [OAuth Authentication for Clients](#oauth-authentication-for-clients)
@@ -515,6 +516,41 @@ def debug_error(error: str) -> list[base.Message]:
515516
_Full example: [examples/snippets/servers/basic_prompt.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/snippets/servers/basic_prompt.py)_
516517
<!-- /snippet-source -->
517518

519+
### Icons
520+
521+
MCP servers can provide icons for UI display. Icons can be added to the server implementation, tools, resources, and prompts:
522+
523+
```python
524+
from mcp.server.fastmcp import FastMCP, Icon
525+
526+
# Create an icon from a file path or URL
527+
icon = Icon(
528+
src="icon.png",
529+
mimeType="image/png",
530+
sizes="64x64"
531+
)
532+
533+
# Add icons to server
534+
mcp = FastMCP(
535+
"My Server",
536+
website_url="https://example.com",
537+
icons=[icon]
538+
)
539+
540+
# Add icons to tools, resources, and prompts
541+
@mcp.tool(icons=[icon])
542+
def my_tool():
543+
"""Tool with an icon."""
544+
return "result"
545+
546+
@mcp.resource("demo://resource", icons=[icon])
547+
def my_resource():
548+
"""Resource with an icon."""
549+
return "content"
550+
```
551+
552+
_Full example: [examples/fastmcp/icons_demo.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/fastmcp/icons_demo.py)_
553+
518554
### Images
519555

520556
FastMCP provides an `Image` class that automatically handles image data:
@@ -746,6 +782,8 @@ async def book_table(date: str, time: str, party_size: int, ctx: Context[ServerS
746782
_Full example: [examples/snippets/servers/elicitation.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/snippets/servers/elicitation.py)_
747783
<!-- /snippet-source -->
748784

785+
Elicitation schemas support default values for all field types. Default values are automatically included in the JSON schema sent to clients, allowing them to pre-populate forms.
786+
749787
The `elicit()` method returns an `ElicitationResult` with:
750788

751789
- `action`: "accept", "decline", or "cancel"
@@ -895,6 +933,8 @@ The FastMCP server instance accessible via `ctx.fastmcp` provides access to serv
895933

896934
- `ctx.fastmcp.name` - The server's name as defined during initialization
897935
- `ctx.fastmcp.instructions` - Server instructions/description provided to clients
936+
- `ctx.fastmcp.website_url` - Optional website URL for the server
937+
- `ctx.fastmcp.icons` - Optional list of icons for UI display
898938
- `ctx.fastmcp.settings` - Complete server configuration object containing:
899939
- `debug` - Debug mode flag
900940
- `log_level` - Current logging level
@@ -1737,6 +1777,116 @@ Tools can return data in three ways:
17371777

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

1780+
### Pagination (Advanced)
1781+
1782+
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.
1783+
1784+
#### Server-side Implementation
1785+
1786+
<!-- snippet-source examples/snippets/servers/pagination_example.py -->
1787+
```python
1788+
"""
1789+
Example of implementing pagination with MCP server decorators.
1790+
"""
1791+
1792+
from pydantic import AnyUrl
1793+
1794+
import mcp.types as types
1795+
from mcp.server.lowlevel import Server
1796+
1797+
# Initialize the server
1798+
server = Server("paginated-server")
1799+
1800+
# Sample data to paginate
1801+
ITEMS = [f"Item {i}" for i in range(1, 101)] # 100 items
1802+
1803+
1804+
@server.list_resources()
1805+
async def list_resources_paginated(request: types.ListResourcesRequest) -> types.ListResourcesResult:
1806+
"""List resources with pagination support."""
1807+
page_size = 10
1808+
1809+
# Extract cursor from request params
1810+
cursor = request.params.cursor if request.params is not None else None
1811+
1812+
# Parse cursor to get offset
1813+
start = 0 if cursor is None else int(cursor)
1814+
end = start + page_size
1815+
1816+
# Get page of resources
1817+
page_items = [
1818+
types.Resource(uri=AnyUrl(f"resource://items/{item}"), name=item, description=f"Description for {item}")
1819+
for item in ITEMS[start:end]
1820+
]
1821+
1822+
# Determine next cursor
1823+
next_cursor = str(end) if end < len(ITEMS) else None
1824+
1825+
return types.ListResourcesResult(resources=page_items, nextCursor=next_cursor)
1826+
```
1827+
1828+
_Full example: [examples/snippets/servers/pagination_example.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/snippets/servers/pagination_example.py)_
1829+
<!-- /snippet-source -->
1830+
1831+
#### Client-side Consumption
1832+
1833+
<!-- snippet-source examples/snippets/clients/pagination_client.py -->
1834+
```python
1835+
"""
1836+
Example of consuming paginated MCP endpoints from a client.
1837+
"""
1838+
1839+
import asyncio
1840+
1841+
from mcp.client.session import ClientSession
1842+
from mcp.client.stdio import StdioServerParameters, stdio_client
1843+
from mcp.types import Resource
1844+
1845+
1846+
async def list_all_resources() -> None:
1847+
"""Fetch all resources using pagination."""
1848+
async with stdio_client(StdioServerParameters(command="uv", args=["run", "mcp-simple-pagination"])) as (
1849+
read,
1850+
write,
1851+
):
1852+
async with ClientSession(read, write) as session:
1853+
await session.initialize()
1854+
1855+
all_resources: list[Resource] = []
1856+
cursor = None
1857+
1858+
while True:
1859+
# Fetch a page of resources
1860+
result = await session.list_resources(cursor=cursor)
1861+
all_resources.extend(result.resources)
1862+
1863+
print(f"Fetched {len(result.resources)} resources")
1864+
1865+
# Check if there are more pages
1866+
if result.nextCursor:
1867+
cursor = result.nextCursor
1868+
else:
1869+
break
1870+
1871+
print(f"Total resources: {len(all_resources)}")
1872+
1873+
1874+
if __name__ == "__main__":
1875+
asyncio.run(list_all_resources())
1876+
```
1877+
1878+
_Full example: [examples/snippets/clients/pagination_client.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/snippets/clients/pagination_client.py)_
1879+
<!-- /snippet-source -->
1880+
1881+
#### Key Points
1882+
1883+
- **Cursors are opaque strings** - the server defines the format (numeric offsets, timestamps, etc.)
1884+
- **Return `nextCursor=None`** when there are no more pages
1885+
- **Backward compatible** - clients that don't support pagination will still work (they'll just get the first page)
1886+
- **Flexible page sizes** - Each endpoint can define its own page size based on data characteristics
1887+
1888+
See the [simple-pagination example](examples/servers/simple-pagination) for a complete implementation.
1889+
17401890
### Writing MCP Clients
17411891

17421892
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):

examples/clients/simple-auth-client/README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,4 +71,4 @@ mcp> quit
7171
## Configuration
7272

7373
- `MCP_SERVER_PORT` - Server URL (default: 8000)
74-
- `MCP_TRANSPORT_TYPE` - Transport type: `streamable_http` (default) or `sse`
74+
- `MCP_TRANSPORT_TYPE` - Transport type: `streamable-http` (default) or `sse`

examples/clients/simple-auth-client/mcp_simple_auth_client/main.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -150,7 +150,7 @@ def get_state(self):
150150
class SimpleAuthClient:
151151
"""Simple MCP client with auth support."""
152152

153-
def __init__(self, server_url: str, transport_type: str = "streamable_http"):
153+
def __init__(self, server_url: str, transport_type: str = "streamable-http"):
154154
self.server_url = server_url
155155
self.transport_type = transport_type
156156
self.session: ClientSession | None = None
@@ -334,10 +334,10 @@ async def main():
334334
# Default server URL - can be overridden with environment variable
335335
# Most MCP streamable HTTP servers use /mcp as the endpoint
336336
server_url = os.getenv("MCP_SERVER_PORT", 8000)
337-
transport_type = os.getenv("MCP_TRANSPORT_TYPE", "streamable_http")
337+
transport_type = os.getenv("MCP_TRANSPORT_TYPE", "streamable-http")
338338
server_url = (
339339
f"http://localhost:{server_url}/mcp"
340-
if transport_type == "streamable_http"
340+
if transport_type == "streamable-http"
341341
else f"http://localhost:{server_url}/sse"
342342
)
343343

examples/fastmcp/icons_demo.py

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
"""
2+
FastMCP Icons Demo Server
3+
4+
Demonstrates using icons with tools, resources, prompts, and implementation.
5+
"""
6+
7+
import base64
8+
from pathlib import Path
9+
10+
from mcp.server.fastmcp import FastMCP, Icon
11+
12+
# Load the icon file and convert to data URI
13+
icon_path = Path(__file__).parent / "mcp.png"
14+
icon_data = base64.standard_b64encode(icon_path.read_bytes()).decode()
15+
icon_data_uri = f"data:image/png;base64,{icon_data}"
16+
17+
icon_data = Icon(src=icon_data_uri, mimeType="image/png", sizes="64x64")
18+
19+
# Create server with icons in implementation
20+
mcp = FastMCP("Icons Demo Server", website_url="https://github.com/modelcontextprotocol/python-sdk", icons=[icon_data])
21+
22+
23+
@mcp.tool(icons=[icon_data])
24+
def demo_tool(message: str) -> str:
25+
"""A demo tool with an icon."""
26+
return message
27+
28+
29+
@mcp.resource("demo://readme", icons=[icon_data])
30+
def readme_resource() -> str:
31+
"""A demo resource with an icon"""
32+
return "This resource has an icon"
33+
34+
35+
@mcp.prompt("prompt_with_icon", icons=[icon_data])
36+
def prompt_with_icon(text: str) -> str:
37+
"""A demo prompt with an icon"""
38+
return text
39+
40+
41+
@mcp.tool(
42+
icons=[
43+
Icon(src=icon_data_uri, mimeType="image/png", sizes="16x16"),
44+
Icon(src=icon_data_uri, mimeType="image/png", sizes="32x32"),
45+
Icon(src=icon_data_uri, mimeType="image/png", sizes="64x64"),
46+
]
47+
)
48+
def multi_icon_tool(action: str) -> str:
49+
"""A tool demonstrating multiple icons."""
50+
return "multi_icon_tool"
51+
52+
53+
if __name__ == "__main__":
54+
# Run the server
55+
mcp.run()
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
"""
2+
FastMCP Echo Server that sends log messages and progress updates to the client
3+
"""
4+
5+
import asyncio
6+
7+
from mcp.server.fastmcp import Context, FastMCP
8+
9+
# Create server
10+
mcp = FastMCP("Echo Server with logging and progress updates")
11+
12+
13+
@mcp.tool()
14+
async def echo(text: str, ctx: Context) -> str:
15+
"""Echo the input text sending log messages and progress updates during processing."""
16+
await ctx.report_progress(progress=0, total=100)
17+
await ctx.info("Starting to process echo for input: " + text)
18+
19+
await asyncio.sleep(2)
20+
21+
await ctx.info("Halfway through processing echo for input: " + text)
22+
await ctx.report_progress(progress=50, total=100)
23+
24+
await asyncio.sleep(2)
25+
26+
await ctx.info("Finished processing echo for input: " + text)
27+
await ctx.report_progress(progress=100, total=100)
28+
29+
# Progress notifications are process asynchronously by the client.
30+
# A small delay here helps ensure the last notification is processed by the client.
31+
await asyncio.sleep(0.1)
32+
33+
return text

examples/fastmcp/mcp.png

2.53 KB
Loading

examples/servers/simple-auth/README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ uv run mcp-simple-auth-rs --port=8001 --auth-server=http://localhost:9000 --tra
4343
```bash
4444
cd examples/clients/simple-auth-client
4545
# Start client with streamable HTTP
46-
MCP_SERVER_PORT=8001 MCP_TRANSPORT_TYPE=streamable_http uv run mcp-simple-auth-client
46+
MCP_SERVER_PORT=8001 MCP_TRANSPORT_TYPE=streamable-http uv run mcp-simple-auth-client
4747
```
4848

4949
## How It Works
@@ -101,7 +101,7 @@ uv run mcp-simple-auth-legacy --port=8002
101101
```bash
102102
# Test with client (will automatically fall back to legacy discovery)
103103
cd examples/clients/simple-auth-client
104-
MCP_SERVER_PORT=8002 MCP_TRANSPORT_TYPE=streamable_http uv run mcp-simple-auth-client
104+
MCP_SERVER_PORT=8002 MCP_TRANSPORT_TYPE=streamable-http uv run mcp-simple-auth-client
105105
```
106106

107107
The client will:
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.

0 commit comments

Comments
 (0)