0
# MCP Python SDK
1
2
A comprehensive Python SDK for the Model Context Protocol (MCP), an open-source standard for connecting AI applications to external systems. The SDK enables developers to build both MCP servers that expose resources, tools, and prompts to AI systems, and MCP clients that can interact with these servers.
3
4
## Package Information
5
6
- **Package Name**: mcp
7
- **Language**: Python
8
- **Installation**: `pip install mcp`
9
10
## Core Imports
11
12
```python
13
import mcp
14
```
15
16
For client operations:
17
18
```python
19
from mcp import ClientSession, ClientSessionGroup, stdio_client, StdioServerParameters
20
```
21
22
For server operations:
23
24
```python
25
from mcp.server import FastMCP, Server
26
```
27
28
For type definitions:
29
30
```python
31
from mcp import (
32
Tool, Resource, Prompt,
33
CallToolRequest, GetPromptRequest, ReadResourceRequest,
34
McpError
35
)
36
```
37
38
## Basic Usage
39
40
### Client Example
41
42
```python
43
import asyncio
44
from mcp import ClientSession, stdio_client, StdioServerParameters
45
46
async def client_example():
47
# Connect to an MCP server
48
server_params = StdioServerParameters(command="my-mcp-server")
49
50
async with stdio_client(server_params) as (read, write):
51
async with ClientSession(read, write) as session:
52
# Initialize the session
53
await session.initialize()
54
55
# List available tools
56
tools = await session.list_tools()
57
print(f"Available tools: {[tool.name for tool in tools.tools]}")
58
59
# Call a tool
60
result = await session.call_tool("example_tool", {"param": "value"})
61
print(f"Tool result: {result}")
62
63
# List and read resources
64
resources = await session.list_resources()
65
if resources.resources:
66
content = await session.read_resource(resources.resources[0].uri)
67
print(f"Resource content: {content}")
68
69
asyncio.run(client_example())
70
```
71
72
### Server Example (FastMCP)
73
74
```python
75
from mcp.server import FastMCP
76
import asyncio
77
78
# Create server instance
79
app = FastMCP("example-server")
80
81
@app.tool()
82
async def calculate_sum(a: int, b: int) -> int:
83
"""Add two numbers together."""
84
return a + b
85
86
@app.resource("config://settings")
87
async def get_settings() -> str:
88
"""Get application settings."""
89
return "setting1=value1\nsetting2=value2"
90
91
@app.prompt()
92
async def greeting_prompt(name: str) -> str:
93
"""Generate a personalized greeting."""
94
return f"Hello, {name}! How can I help you today?"
95
96
# Run the server
97
if __name__ == "__main__":
98
app.run_stdio()
99
```
100
101
## Architecture
102
103
The MCP Python SDK is organized around several key components:
104
105
### Transport Layer
106
- **stdio**: Standard input/output transport for local process communication
107
- **HTTP/SSE**: Server-Sent Events over HTTP for web-based connections
108
- **WebSocket**: Real-time bidirectional communication
109
- **HTTP Streaming**: Streaming HTTP connections for efficient data transfer
110
111
### Session Management
112
- **ClientSession**: Manages individual client connections to servers
113
- **ClientSessionGroup**: Coordinates multiple concurrent server connections
114
- **ServerSession**: Handles server-side client connections
115
116
### Protocol Implementation
117
- **Request/Response**: Structured communication using JSON-RPC 2.0
118
- **Notifications**: One-way messages for events and updates
119
- **Capabilities**: Negotiated feature sets between clients and servers
120
- **Authentication**: OAuth 2.0 and bearer token support
121
122
### High-Level Frameworks
123
- **FastMCP**: Modern, decorator-based server framework for rapid development
124
- **Low-level Server**: Full control server implementation for advanced use cases
125
126
## Capabilities
127
128
### Client Operations
129
130
Core client functionality for connecting to and interacting with MCP servers, including session management, tool calling, resource access, and prompt handling.
131
132
```python { .api }
133
class ClientSession:
134
async def initialize(self) -> InitializeResult: ...
135
async def list_tools(self, cursor: str | None = None) -> ListToolsResult: ...
136
async def call_tool(self, name: str, arguments: dict[str, Any] | None = None) -> CallToolResult: ...
137
async def list_resources(self, cursor: str | None = None) -> ListResourcesResult: ...
138
async def read_resource(self, uri: AnyUrl) -> ReadResourceResult: ...
139
async def list_prompts(self, cursor: str | None = None) -> ListPromptsResult: ...
140
async def get_prompt(self, name: str, arguments: dict[str, str] | None = None) -> GetPromptResult: ...
141
142
class ClientSessionGroup:
143
async def connect_to_server(self, server_params: ServerParameters) -> ClientSession: ...
144
async def call_tool(self, name: str, args: dict[str, Any]) -> CallToolResult: ...
145
@property
146
def tools(self) -> dict[str, Tool]: ...
147
@property
148
def resources(self) -> dict[str, Resource]: ...
149
```
150
151
[Client Operations](./client.md)
152
153
### FastMCP Server Framework
154
155
High-level server framework using decorators for rapid MCP server development, with built-in support for tools, resources, prompts, and HTTP endpoints.
156
157
```python { .api }
158
class FastMCP:
159
def __init__(self, name: str, **kwargs): ...
160
def tool(self) -> Callable: ...
161
def resource(self, uri: str) -> Callable: ...
162
def prompt(self) -> Callable: ...
163
def get(self, path: str) -> Callable: ...
164
def post(self, path: str) -> Callable: ...
165
def run_stdio(self) -> None: ...
166
async def run_sse(self, host: str = "127.0.0.1", port: int = 8000) -> None: ...
167
168
class Context:
169
@property
170
def request_id(self) -> str: ...
171
@property
172
def client_session(self) -> ServerSession: ...
173
```
174
175
[FastMCP Server](./fastmcp-server.md)
176
177
### Low-Level Server Framework
178
179
Low-level server implementation providing full control over MCP protocol handling with decorator-based request handlers and custom lifecycle management.
180
181
```python { .api }
182
class Server:
183
def __init__(self, name: str, version: str | None = None, **kwargs): ...
184
def list_tools(self) -> Callable: ...
185
def call_tool(self) -> Callable: ...
186
def list_resources(self) -> Callable: ...
187
def read_resource(self) -> Callable: ...
188
def list_prompts(self) -> Callable: ...
189
def get_prompt(self) -> Callable: ...
190
async def run(self, read_stream, write_stream, options: InitializationOptions) -> None: ...
191
192
class NotificationOptions:
193
def __init__(self, tools_changed: bool = True, resources_changed: bool = True, **kwargs): ...
194
```
195
196
[Low-Level Server](./lowlevel-server.md)
197
198
### Transport Mechanisms
199
200
Transport layer implementations for various connection types including stdio, HTTP, WebSocket, and streaming protocols with authentication and security features.
201
202
```python { .api }
203
def stdio_client(server: StdioServerParameters) -> AsyncContextManager: ...
204
def stdio_server() -> AsyncContextManager: ...
205
206
class StdioServerParameters:
207
def __init__(self, command: str | list[str], **kwargs): ...
208
209
def websocket_client(url: str, **kwargs) -> AsyncContextManager: ...
210
def sse_client(url: str, **kwargs) -> AsyncContextManager: ...
211
def streamablehttp_client(url: str, **kwargs) -> AsyncContextManager: ...
212
```
213
214
[Transport Mechanisms](./transport.md)
215
216
### Authentication and Security
217
218
OAuth 2.0 authentication, bearer token verification, transport security settings, and middleware for protecting MCP server endpoints.
219
220
```python { .api }
221
class AuthSettings:
222
def __init__(
223
self,
224
client_id: str,
225
client_secret: str,
226
authorization_endpoint: str,
227
token_endpoint: str,
228
**kwargs
229
): ...
230
231
class TokenVerifier:
232
async def verify_token(self, token: str) -> dict[str, Any]: ...
233
234
class TransportSecuritySettings:
235
def __init__(self, dns_rebinding_protection: bool = True, **kwargs): ...
236
```
237
238
[Authentication & Security](./auth.md)
239
240
### Type System and Protocol Types
241
242
Complete MCP protocol type definitions including requests, responses, notifications, capabilities, and data models for tools, resources, and prompts.
243
244
```python { .api }
245
# Core Protocol Types
246
class InitializeRequest(BaseModel): ...
247
class InitializeResult(BaseModel): ...
248
class Tool(BaseModel): ...
249
class Resource(BaseModel): ...
250
class Prompt(BaseModel): ...
251
252
# Content Types
253
class TextContent(BaseModel): ...
254
class ImageContent(BaseModel): ...
255
class EmbeddedResource(BaseModel): ...
256
257
# Capabilities
258
class ClientCapabilities(BaseModel): ...
259
class ServerCapabilities(BaseModel): ...
260
261
# Exceptions
262
class McpError(Exception): ...
263
```
264
265
[Types and Protocol](./types.md)
266
267
### CLI Tools
268
269
Command-line interface for MCP development, testing, and debugging with tools for server inspection and protocol validation.
270
271
```python { .api }
272
# Available via CLI
273
mcp --help
274
mcp server inspect <server-command>
275
mcp client connect <server-params>
276
```
277
278
[CLI Tools](./cli.md)