Spec RegistrySpec Registry

Help your agents use open-source better. Learn more.

Find usage specs for your project’s dependencies

>

pypi-fastmcp

Describes: pypipypi/fastmcp

Description
The fast, Pythonic way to build MCP servers and clients with minimal boilerplate code.
Author
tessl
Last updated

How to use

npx @tessl/cli registry install tessl/pypi-fastmcp@2.12.0

server.md docs/

1
# Server Implementation
2
3
Core server functionality for creating MCP servers with decorators, managing components, and handling protocol communication. The FastMCP server provides a high-level interface for building MCP servers with minimal boilerplate.
4
5
## Capabilities
6
7
### FastMCP Server Class
8
9
The main server class that manages tools, resources, prompts, middleware, authentication, and protocol communication.
10
11
```python { .api }
12
class FastMCP:
13
def __init__(
14
self,
15
name: str,
16
version: str = "0.1.0",
17
instructions: str | None = None,
18
auth_provider: AuthProvider | None = None,
19
middlewares: list[Middleware] | None = None,
20
settings: Settings | None = None
21
):
22
"""
23
Create a FastMCP server instance.
24
25
Parameters:
26
- name: Server name for identification
27
- version: Server version string
28
- instructions: Optional instructions for LLM interaction
29
- auth_provider: Authentication provider for server security
30
- middlewares: List of middleware for request/response processing
31
- settings: Server settings and configuration
32
"""
33
```
34
35
### Tool Registration
36
37
Register functions as tools that LLMs can call to perform actions.
38
39
```python { .api }
40
def tool(
41
self,
42
func: Callable | None = None,
43
*,
44
name: str | None = None
45
) -> Callable:
46
"""
47
Decorator to register a function as a tool.
48
49
Parameters:
50
- func: Function to register as tool
51
- name: Optional custom tool name (defaults to function name)
52
53
Returns:
54
Decorated function
55
"""
56
57
def add_tool(self, tool: Tool) -> None:
58
"""
59
Add a tool instance programmatically.
60
61
Parameters:
62
- tool: Tool instance to add
63
"""
64
65
def remove_tool(self, name: str) -> None:
66
"""
67
Remove a tool by name.
68
69
Parameters:
70
- name: Name of tool to remove
71
"""
72
```
73
74
### Resource Registration
75
76
Register functions as resources that provide read-only data access.
77
78
```python { .api }
79
def resource(self, uri: str) -> Callable:
80
"""
81
Decorator to register a function as a resource.
82
83
Parameters:
84
- uri: Resource URI, can include {parameters} for templates
85
86
Returns:
87
Decorated function
88
"""
89
90
def add_resource(self, resource: Resource) -> None:
91
"""
92
Add a resource instance programmatically.
93
94
Parameters:
95
- resource: Resource instance to add
96
"""
97
98
def add_template(self, template: ResourceTemplate) -> None:
99
"""
100
Add a resource template for dynamic resources.
101
102
Parameters:
103
- template: ResourceTemplate instance to add
104
"""
105
```
106
107
### Prompt Registration
108
109
Register functions as prompts that provide reusable message templates.
110
111
```python { .api }
112
def prompt(
113
self,
114
func: Callable | None = None,
115
*,
116
name: str | None = None
117
) -> Callable:
118
"""
119
Decorator to register a function as a prompt.
120
121
Parameters:
122
- func: Function to register as prompt
123
- name: Optional custom prompt name (defaults to function name)
124
125
Returns:
126
Decorated function
127
"""
128
129
def add_prompt(self, prompt: Prompt) -> None:
130
"""
131
Add a prompt instance programmatically.
132
133
Parameters:
134
- prompt: Prompt instance to add
135
"""
136
```
137
138
### Server Execution
139
140
Run the server with specified transport and configuration.
141
142
```python { .api }
143
def run(
144
self,
145
transport: Literal["stdio", "sse", "http"] = "stdio",
146
host: str = "127.0.0.1",
147
port: int = 8000,
148
path: str = "/mcp",
149
**kwargs
150
) -> None:
151
"""
152
Run the MCP server.
153
154
Parameters:
155
- transport: Transport protocol ("stdio", "sse", "http")
156
- host: Host address for network transports
157
- port: Port number for network transports
158
- path: URL path for HTTP transport
159
- **kwargs: Additional transport-specific options
160
"""
161
```
162
163
### Middleware and Custom Routes
164
165
Add middleware and custom HTTP routes for extended functionality.
166
167
```python { .api }
168
def add_middleware(self, middleware: Middleware) -> None:
169
"""
170
Add middleware for request/response processing.
171
172
Parameters:
173
- middleware: Middleware instance to add
174
"""
175
176
def custom_route(
177
self,
178
path: str,
179
methods: list[str] | None = None
180
) -> Callable:
181
"""
182
Decorator to add custom HTTP routes.
183
184
Parameters:
185
- path: URL path for the route
186
- methods: HTTP methods supported (defaults to ["GET"])
187
188
Returns:
189
Decorated function
190
"""
191
```
192
193
### Tool Transformations
194
195
Add transformations to modify tool behavior dynamically.
196
197
```python { .api }
198
def add_tool_transformation(self, transform: Callable) -> None:
199
"""
200
Add a tool transformation function.
201
202
Parameters:
203
- transform: Function that transforms tool calls
204
"""
205
```
206
207
### Server Properties
208
209
Access server configuration and state.
210
211
```python { .api }
212
@property
213
def name(self) -> str:
214
"""Server name."""
215
216
@property
217
def version(self) -> str:
218
"""Server version."""
219
220
@property
221
def instructions(self) -> str | None:
222
"""Server instructions for LLM interaction."""
223
224
@property
225
def settings(self) -> Settings:
226
"""Server settings and configuration."""
227
```
228
229
## Usage Examples
230
231
### Basic Server with Multiple Components
232
233
```python
234
from fastmcp import FastMCP, Context
235
236
mcp = FastMCP(
237
name="My Assistant Server",
238
version="1.0.0",
239
instructions="A helpful assistant server"
240
)
241
242
@mcp.tool
243
def calculate(expression: str) -> float:
244
"""Safely evaluate a mathematical expression."""
245
# Safe evaluation logic here
246
return eval(expression) # Note: Use safe_eval in production
247
248
@mcp.resource("config://{key}")
249
def get_config(key: str) -> dict:
250
"""Get configuration value by key."""
251
config = {"version": "1.0.0", "name": "My Server"}
252
return {"key": key, "value": config.get(key)}
253
254
@mcp.prompt
255
def analyze_data(data_description: str) -> str:
256
"""Generate analysis prompt for data."""
257
return f"Please analyze the following data: {data_description}"
258
259
# Run with different transports
260
if __name__ == "__main__":
261
# Default stdio transport
262
mcp.run()
263
264
# HTTP transport
265
# mcp.run(transport="http", port=8080)
266
267
# SSE transport
268
# mcp.run(transport="sse", port=8080)
269
```
270
271
### Server with Authentication and Middleware
272
273
```python
274
from fastmcp import FastMCP
275
from fastmcp.server.auth import JWTVerifier
276
from fastmcp.server.middleware import Middleware
277
278
# Configure authentication
279
auth_provider = JWTVerifier(
280
secret="your-secret-key",
281
algorithms=["HS256"]
282
)
283
284
# Custom middleware
285
class LoggingMiddleware(Middleware):
286
async def __call__(self, request, call_next):
287
print(f"Processing request: {request}")
288
response = await call_next(request)
289
print(f"Response: {response}")
290
return response
291
292
mcp = FastMCP(
293
name="Secure Server",
294
auth_provider=auth_provider,
295
middlewares=[LoggingMiddleware()]
296
)
297
298
@mcp.tool
299
def sensitive_operation(data: str) -> str:
300
"""Perform a sensitive operation (requires authentication)."""
301
return f"Processed: {data}"
302
303
mcp.run(transport="http", port=8080)
304
```
305
306
### Server with Context Usage
307
308
```python
309
from fastmcp import FastMCP, Context
310
311
mcp = FastMCP("Context Demo Server")
312
313
@mcp.tool
314
async def process_with_context(data: str, ctx: Context) -> str:
315
"""Process data with context capabilities."""
316
# Log to client
317
await ctx.info(f"Processing data: {data}")
318
319
# Make HTTP request
320
response = await ctx.http_request(
321
"GET",
322
"https://api.example.com/data",
323
headers={"Authorization": "Bearer token"}
324
)
325
326
# Sample from LLM
327
summary = await ctx.sample([
328
{"role": "user", "content": f"Summarize: {response}"}
329
])
330
331
# Report progress
332
await ctx.report_progress(100, 100)
333
334
return summary.text
335
336
mcp.run()
337
```