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