0
# Model Context Protocol (MCP)
1
2
The Model Context Protocol (MCP) enables agents to connect to external servers that provide tools, resources, and capabilities beyond the base SDK. MCP servers can be accessed via stdio, SSE, or streamable HTTP transports, with support for tool filtering and approval workflows.
3
4
## Capabilities
5
6
### MCP Server Types
7
8
Union type for all MCP server implementations.
9
10
```python { .api }
11
MCPServer = Union[
12
MCPServerStdio,
13
MCPServerSse,
14
MCPServerStreamableHttp
15
]
16
```
17
18
### MCP Server Stdio
19
20
MCP server connection via standard input/output.
21
22
```python { .api }
23
class MCPServerStdio:
24
"""MCP server via stdio transport."""
25
26
def __init__(params: MCPServerStdioParams):
27
"""
28
Initialize stdio MCP server.
29
30
Parameters:
31
- params: Stdio connection parameters
32
"""
33
34
async def connect():
35
"""Establish connection to MCP server."""
36
37
async def cleanup():
38
"""Clean up server connection."""
39
40
class MCPServerStdioParams:
41
"""
42
Parameters for stdio MCP server.
43
44
Attributes:
45
- command: str - Command to execute
46
- args: list[str] - Command arguments
47
- env: dict[str, str] - Environment variables
48
"""
49
```
50
51
Usage example:
52
53
```python
54
from agents import Agent
55
from agents.mcp import MCPServerStdio
56
57
# Git MCP server via stdio
58
git_server = MCPServerStdio({
59
"command": "npx",
60
"args": ["-y", "@modelcontextprotocol/server-git"],
61
"env": {}
62
})
63
64
agent = Agent(
65
name="Git Agent",
66
instructions="Help with git operations",
67
mcp_servers=[git_server]
68
)
69
```
70
71
### MCP Server SSE
72
73
MCP server connection via Server-Sent Events.
74
75
```python { .api }
76
class MCPServerSse:
77
"""MCP server via SSE transport."""
78
79
def __init__(params: MCPServerSseParams):
80
"""
81
Initialize SSE MCP server.
82
83
Parameters:
84
- params: SSE connection parameters
85
"""
86
87
async def connect():
88
"""Establish connection to MCP server."""
89
90
async def cleanup():
91
"""Clean up server connection."""
92
93
class MCPServerSseParams:
94
"""
95
Parameters for SSE MCP server.
96
97
Attributes:
98
- url: str - SSE endpoint URL
99
- headers: dict[str, str] - HTTP headers
100
"""
101
```
102
103
Usage example:
104
105
```python
106
from agents.mcp import MCPServerSse
107
108
# Remote MCP server via SSE
109
sse_server = MCPServerSse({
110
"url": "https://example.com/mcp-sse",
111
"headers": {"Authorization": "Bearer token"}
112
})
113
114
agent = Agent(
115
name="Remote Agent",
116
mcp_servers=[sse_server]
117
)
118
```
119
120
### MCP Server Streamable HTTP
121
122
MCP server connection via streamable HTTP.
123
124
```python { .api }
125
class MCPServerStreamableHttp:
126
"""MCP server via streamable HTTP transport."""
127
128
def __init__(params: MCPServerStreamableHttpParams):
129
"""
130
Initialize streamable HTTP MCP server.
131
132
Parameters:
133
- params: HTTP connection parameters
134
"""
135
136
async def connect():
137
"""Establish connection to MCP server."""
138
139
async def cleanup():
140
"""Clean up server connection."""
141
142
class MCPServerStreamableHttpParams:
143
"""
144
Parameters for streamable HTTP MCP server.
145
146
Attributes:
147
- url: str - HTTP endpoint URL
148
- headers: dict[str, str] - HTTP headers
149
"""
150
```
151
152
Usage example:
153
154
```python
155
from agents.mcp import MCPServerStreamableHttp
156
157
http_server = MCPServerStreamableHttp({
158
"url": "https://example.com/mcp-http",
159
"headers": {"X-API-Key": "key"}
160
})
161
162
agent = Agent(
163
name="HTTP Agent",
164
mcp_servers=[http_server]
165
)
166
```
167
168
### MCP Utilities
169
170
Utility functions for working with MCP.
171
172
```python { .api }
173
class MCPUtil:
174
"""MCP utilities."""
175
176
@staticmethod
177
async def get_all_function_tools(
178
servers: list[MCPServer],
179
tool_filter: ToolFilter | None = None,
180
context = None
181
) -> list[Tool]:
182
"""
183
Get all MCP tools from servers.
184
185
Parameters:
186
- servers: List of MCP servers
187
- tool_filter: Optional filter for tools
188
- context: Context object
189
190
Returns:
191
- list[Tool]: All tools from MCP servers
192
"""
193
```
194
195
### Tool Filtering
196
197
Filter which MCP tools are available to agents.
198
199
```python { .api }
200
ToolFilter = Union[ToolFilterStatic, ToolFilterCallable]
201
202
class ToolFilterStatic:
203
"""
204
Static tool filter.
205
206
Attributes:
207
- allowed_tools: list[str] | None - Allowed tool names (whitelist)
208
- denied_tools: list[str] | None - Denied tool names (blacklist)
209
"""
210
211
ToolFilterCallable = Callable[[ToolFilterContext], bool]
212
213
class ToolFilterContext:
214
"""
215
Context for tool filtering.
216
217
Attributes:
218
- tool_name: str - Name of tool being filtered
219
- server_label: str - Label of MCP server
220
"""
221
222
def create_static_tool_filter(
223
allowed_tools: list[str] | None = None,
224
denied_tools: list[str] | None = None
225
) -> ToolFilterStatic:
226
"""
227
Create static tool filter.
228
229
Parameters:
230
- allowed_tools: Whitelist of tool names
231
- denied_tools: Blacklist of tool names
232
233
Returns:
234
- ToolFilterStatic: Configured filter
235
"""
236
```
237
238
Usage example:
239
240
```python
241
from agents.mcp import create_static_tool_filter
242
243
# Whitelist specific tools
244
filter = create_static_tool_filter(
245
allowed_tools=["read_file", "list_directory"]
246
)
247
248
# Blacklist dangerous tools
249
filter = create_static_tool_filter(
250
denied_tools=["delete_file", "execute_command"]
251
)
252
253
# Custom filter function
254
def custom_filter(ctx):
255
"""Only allow read operations."""
256
return ctx.tool_name.startswith("read_") or ctx.tool_name.startswith("list_")
257
258
# Apply filter to agent
259
agent = Agent(
260
name="Safe Agent",
261
mcp_servers=[mcp_server],
262
# Filter applied via MCPConfig or tool_filter parameter
263
)
264
```
265
266
## MCP Configuration
267
268
Configure MCP behavior per agent.
269
270
```python
271
from agents import Agent, MCPConfig
272
273
config = MCPConfig(
274
convert_schemas_to_strict=True # Convert MCP tool schemas to strict mode
275
)
276
277
agent = Agent(
278
name="MCP Agent",
279
mcp_servers=[filesystem_server, git_server],
280
mcp_config=config
281
)
282
```
283
284
## Common MCP Servers
285
286
### Filesystem MCP Server
287
288
Access local filesystem.
289
290
```python
291
from agents.mcp import MCPServerStdio
292
293
filesystem_server = MCPServerStdio({
294
"command": "npx",
295
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/workspace"],
296
"env": {}
297
})
298
299
agent = Agent(
300
name="File Agent",
301
instructions="Help with file operations",
302
mcp_servers=[filesystem_server]
303
)
304
```
305
306
### Git MCP Server
307
308
Git repository operations.
309
310
```python
311
git_server = MCPServerStdio({
312
"command": "npx",
313
"args": ["-y", "@modelcontextprotocol/server-git"],
314
"env": {"GIT_REPO_PATH": "/path/to/repo"}
315
})
316
317
agent = Agent(
318
name="Git Agent",
319
instructions="Help with git operations",
320
mcp_servers=[git_server]
321
)
322
```
323
324
### Custom MCP Server
325
326
Create your own MCP server in Python:
327
328
```python
329
# server.py - Simple MCP server
330
from mcp.server import Server
331
from mcp.server.stdio import stdio_server
332
333
server = Server("my-custom-server")
334
335
@server.tool("get_weather")
336
def get_weather(city: str) -> str:
337
"""Get weather for a city."""
338
return f"Weather in {city}: Sunny"
339
340
@server.tool("calculate")
341
def calculate(expression: str) -> float:
342
"""Evaluate math expression."""
343
return eval(expression)
344
345
if __name__ == "__main__":
346
stdio_server(server)
347
```
348
349
Use custom server:
350
351
```python
352
custom_server = MCPServerStdio({
353
"command": "python",
354
"args": ["server.py"],
355
"env": {}
356
})
357
358
agent = Agent(
359
name="Custom Agent",
360
mcp_servers=[custom_server]
361
)
362
```
363
364
## Multiple MCP Servers
365
366
Use multiple MCP servers together:
367
368
```python
369
filesystem_server = MCPServerStdio({
370
"command": "npx",
371
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/workspace"]
372
})
373
374
git_server = MCPServerStdio({
375
"command": "npx",
376
"args": ["-y", "@modelcontextprotocol/server-git"]
377
})
378
379
web_server = MCPServerSse({
380
"url": "https://mcp-server.example.com/sse",
381
"headers": {}
382
})
383
384
agent = Agent(
385
name="Multi-Tool Agent",
386
instructions="Use filesystem, git, and web tools as needed",
387
mcp_servers=[filesystem_server, git_server, web_server]
388
)
389
```
390
391
## Tool Approval Workflow
392
393
Require approval for sensitive MCP tool calls:
394
395
```python
396
from agents import HostedMCPTool
397
398
async def approve_mcp_action(request):
399
"""Review and approve MCP tool calls."""
400
action = request.data.get("action")
401
tool = request.data.get("tool")
402
403
print(f"MCP tool approval request:")
404
print(f" Tool: {tool}")
405
print(f" Action: {action}")
406
407
# Check if action is safe
408
if "delete" in action.lower() or "rm" in action.lower():
409
return {
410
"approve": False,
411
"reason": "Destructive operations require manual approval"
412
}
413
414
return {"approve": True}
415
416
# Use with hosted MCP tool
417
hosted_mcp = HostedMCPTool(
418
tool_config={"server": "mcp_server_id"},
419
on_approval_request=approve_mcp_action
420
)
421
422
agent = Agent(
423
name="Safe Agent",
424
tools=[hosted_mcp]
425
)
426
```
427
428
## Best Practices
429
430
1. **Security**: Use tool filters to restrict dangerous operations
431
2. **Server Lifecycle**: Properly cleanup MCP servers after use
432
3. **Error Handling**: Handle MCP server connection failures gracefully
433
4. **Tool Discovery**: Let agents discover available MCP tools dynamically
434
5. **Approval Workflows**: Require approval for sensitive operations
435
6. **Server Selection**: Choose appropriate transport (stdio, SSE, HTTP) for use case
436
7. **Environment Variables**: Use env params for server configuration
437
8. **Multiple Servers**: Combine servers for comprehensive tool coverage
438
9. **Testing**: Test MCP integrations thoroughly before production
439
10. **Documentation**: Document available MCP tools for agent instructions
440
441
## MCP Server Examples
442
443
The official MCP server implementations provide ready-to-use servers:
444
445
- **@modelcontextprotocol/server-filesystem**: File system operations
446
- **@modelcontextprotocol/server-git**: Git repository management
447
- **@modelcontextprotocol/server-github**: GitHub API integration
448
- **@modelcontextprotocol/server-postgres**: PostgreSQL database access
449
- **@modelcontextprotocol/server-sqlite**: SQLite database operations
450
- **@modelcontextprotocol/server-slack**: Slack integration
451
- **@modelcontextprotocol/server-google-drive**: Google Drive access
452
- **@modelcontextprotocol/server-brave-search**: Web search via Brave
453
- **@modelcontextprotocol/server-puppeteer**: Browser automation
454
455
Install with npm and use via stdio transport with npx.
456