0
# FastMCP
1
2
The fast, Pythonic way to build MCP servers and clients. FastMCP is a comprehensive framework for building Model Context Protocol (MCP) servers and clients with minimal boilerplate code, providing a clean, Pythonic API for creating tools, exposing resources, defining prompts, and connecting components in the MCP ecosystem.
3
4
## Package Information
5
6
- **Package Name**: fastmcp
7
- **Language**: Python
8
- **Installation**: `pip install fastmcp`
9
- **Python Requirements**: >=3.10
10
11
## Core Imports
12
13
```python
14
from fastmcp import FastMCP, Context, Client
15
```
16
17
## Basic Usage
18
19
### Creating a Simple MCP Server
20
21
```python
22
from fastmcp import FastMCP
23
24
# Create a server instance
25
mcp = FastMCP("Demo Server")
26
27
@mcp.tool
28
def add(a: int, b: int) -> int:
29
"""Add two numbers."""
30
return a + b
31
32
@mcp.resource("config://version")
33
def get_version():
34
"""Get server version."""
35
return "1.0.0"
36
37
@mcp.prompt
38
def summarize_request(text: str) -> str:
39
"""Generate a prompt asking for a summary."""
40
return f"Please summarize the following text:\n\n{text}"
41
42
if __name__ == "__main__":
43
mcp.run() # Run with stdio transport
44
```
45
46
### Creating a Client
47
48
```python
49
from fastmcp import Client
50
51
async def main():
52
# Connect to a server via stdio
53
async with Client("server.py") as client:
54
# List available tools
55
tools = await client.list_tools()
56
57
# Call a tool
58
result = await client.call_tool("add", {"a": 5, "b": 3})
59
print(result.text)
60
61
# Read a resource
62
resource = await client.read_resource("config://version")
63
print(resource.content)
64
```
65
66
## Architecture
67
68
FastMCP is built around several core components that work together to provide a complete MCP framework:
69
70
- **FastMCP Server**: The main server class that manages tools, resources, prompts, and handles MCP protocol communication
71
- **Context**: Execution context providing capabilities like logging, LLM sampling, and HTTP requests to tools/resources/prompts
72
- **Client**: Full-featured client supporting multiple transports and authentication methods
73
- **Component System**: Modular architecture for tools, resources, and prompts with both decorator and class-based approaches
74
- **Transport Layer**: Multiple transport protocols (stdio, HTTP, SSE, WebSocket) for flexible deployment
75
- **Authentication**: Comprehensive auth system supporting OAuth, JWT, Bearer tokens, and custom providers
76
- **Middleware**: Extensible middleware system for request/response processing
77
78
## Capabilities
79
80
### Server Implementation
81
82
Core server functionality for creating MCP servers with decorators, managing components, and handling protocol communication.
83
84
```python { .api }
85
class FastMCP:
86
def __init__(
87
self,
88
name: str,
89
version: str = "0.1.0",
90
instructions: str | None = None,
91
auth_provider: AuthProvider | None = None,
92
middlewares: list[Middleware] | None = None,
93
settings: Settings | None = None
94
): ...
95
96
def tool(self, func: Callable | None = None, *, name: str | None = None) -> Callable: ...
97
def resource(self, uri: str) -> Callable: ...
98
def prompt(self, func: Callable | None = None, *, name: str | None = None) -> Callable: ...
99
def run(
100
self,
101
transport: Literal["stdio", "sse", "http"] = "stdio",
102
host: str = "127.0.0.1",
103
port: int = 8000,
104
**kwargs
105
) -> None: ...
106
```
107
108
[Server Implementation](./server.md)
109
110
### Client Library
111
112
Full-featured MCP client supporting multiple transports, authentication, and advanced features like LLM sampling.
113
114
```python { .api }
115
class Client:
116
def __init__(
117
self,
118
server_or_config: str | FastMCP | dict,
119
transport: ClientTransport | None = None,
120
auth: BearerAuth | OAuth | None = None,
121
sampling_handler: SamplingHandler | None = None,
122
elicitation_handler: ElicitationHandler | None = None
123
): ...
124
125
async def list_tools(self) -> list: ...
126
async def call_tool(self, name: str, arguments: dict | None = None): ...
127
async def list_resources(self) -> list: ...
128
async def read_resource(self, uri: str): ...
129
async def list_prompts(self) -> list: ...
130
async def get_prompt(self, name: str, arguments: dict | None = None): ...
131
```
132
133
[Client Library](./client.md)
134
135
### Tools System
136
137
Tools allow LLMs to perform actions by executing Python functions, with automatic schema generation and flexible return types.
138
139
```python { .api }
140
class Tool:
141
def __init__(
142
self,
143
name: str,
144
description: str,
145
func: Callable,
146
schema: dict | None = None
147
): ...
148
149
class FunctionTool(Tool): ...
150
151
class ToolManager:
152
def add_tool(self, tool: Tool) -> None: ...
153
def remove_tool(self, name: str) -> None: ...
154
def get_tool(self, name: str) -> Tool | None: ...
155
```
156
157
[Tools System](./tools.md)
158
159
### Resources System
160
161
Resources expose read-only data sources with support for static resources and dynamic templates with URI parameters.
162
163
```python { .api }
164
class Resource:
165
def __init__(
166
self,
167
uri: str,
168
name: str,
169
description: str,
170
mime_type: str | None = None
171
): ...
172
173
class ResourceTemplate:
174
def __init__(
175
self,
176
uri_template: str,
177
name: str,
178
description: str,
179
mime_type: str | None = None
180
): ...
181
182
class ResourceManager:
183
def add_resource(self, resource: Resource) -> None: ...
184
def add_template(self, template: ResourceTemplate) -> None: ...
185
```
186
187
[Resources System](./resources.md)
188
189
### Prompts System
190
191
Prompts define reusable message templates to guide LLM interactions with parameter support and message formatting.
192
193
```python { .api }
194
class Prompt:
195
def __init__(
196
self,
197
name: str,
198
description: str,
199
func: Callable,
200
schema: dict | None = None
201
): ...
202
203
class PromptManager:
204
def add_prompt(self, prompt: Prompt) -> None: ...
205
def get_prompt(self, name: str) -> Prompt | None: ...
206
207
def Message(
208
role: Literal["user", "assistant", "system"],
209
content: str | dict,
210
name: str | None = None
211
): ...
212
```
213
214
[Prompts System](./prompts.md)
215
216
### Context and Dependencies
217
218
Execution context providing capabilities like logging, LLM sampling, HTTP requests, and resource access to tools/resources/prompts.
219
220
```python { .api }
221
class Context:
222
async def info(self, message: str) -> None: ...
223
async def error(self, message: str) -> None: ...
224
async def debug(self, message: str) -> None: ...
225
async def sample(
226
self,
227
messages: list[dict],
228
params: dict | None = None
229
): ...
230
async def read_resource(self, uri: str): ...
231
async def http_request(
232
self,
233
method: str,
234
url: str,
235
headers: dict | None = None,
236
data: Any | None = None
237
): ...
238
async def report_progress(self, progress: int, total: int | None = None) -> None: ...
239
```
240
241
[Context and Dependencies](./context.md)
242
243
### Transport Layer
244
245
Multiple transport protocols for flexible server deployment and client connections.
246
247
```python { .api }
248
class ClientTransport: ...
249
class StdioTransport(ClientTransport): ...
250
class SSETransport(ClientTransport): ...
251
class StreamableHttpTransport(ClientTransport): ...
252
class WSTransport(ClientTransport): ...
253
class FastMCPTransport(ClientTransport): ...
254
```
255
256
[Transport Layer](./transports.md)
257
258
### Authentication
259
260
Comprehensive authentication system supporting multiple providers and tokens for secure server and client connections.
261
262
```python { .api }
263
class AuthProvider: ...
264
class OAuthProvider(AuthProvider): ...
265
class JWTVerifier(AuthProvider): ...
266
class TokenVerifier(AuthProvider): ...
267
class StaticTokenVerifier(AuthProvider): ...
268
class RemoteAuthProvider(AuthProvider): ...
269
270
class BearerAuth: ...
271
class OAuth: ...
272
class AccessToken: ...
273
```
274
275
[Authentication](./authentication.md)
276
277
### Utilities and Types
278
279
Helper classes and utility functions for enhanced functionality and type support.
280
281
```python { .api }
282
class Image:
283
def __init__(
284
self,
285
data: bytes | str,
286
mime_type: str = "image/png"
287
): ...
288
289
class Audio:
290
def __init__(
291
self,
292
data: bytes | str,
293
mime_type: str = "audio/wav"
294
): ...
295
296
class File:
297
def __init__(
298
self,
299
data: bytes | str,
300
name: str,
301
mime_type: str | None = None
302
): ...
303
304
class Settings: ...
305
class MCPConfig: ...
306
```
307
308
[Utilities and Types](./utilities.md)
309
310
## Types
311
312
```python { .api }
313
# Core types
314
from typing import Callable, Any, Literal
315
from pydantic import BaseModel
316
317
class FastMCPBaseModel(BaseModel): ...
318
319
# Function signatures for decorators
320
ToolFunction = Callable[..., Any]
321
ResourceFunction = Callable[..., str | bytes | dict]
322
PromptFunction = Callable[..., str | list[dict]]
323
324
# Transport types
325
TransportType = Literal["stdio", "sse", "http", "ws"]
326
327
# Authentication types
328
SamplingHandler = Callable[[list[dict]], Any]
329
ElicitationHandler = Callable[[dict], Any]
330
331
# Component types
332
class MCPMixin: ...
333
ComponentFn = Callable[..., Any]
334
```