Heuristic:Openai Openai agents python MCP Server Lifecycle Management
| Knowledge Sources | |
|---|---|
| Domains | MCP, Resource_Management |
| Last Updated | 2026-02-11 14:00 GMT |
Overview
MCP server connections must be manually managed; tools are fetched dynamically per run, not cached at agent construction.
Description
Unlike regular function tools that are defined statically on the agent, MCP tools are fetched dynamically from connected MCP servers on every agent run. This means:
- Users must explicitly call `server.connect()` before passing an MCP server to an agent
- Users must call `server.cleanup()` when the server is no longer needed
- The `MCPServerManager` context manager is the recommended way to handle this lifecycle
Failure to clean up servers can leak subprocesses (for Stdio servers) or HTTP connections (for SSE/StreamableHttp servers).
Usage
Follow this heuristic whenever using `mcp_servers` on an Agent:
- Always wrap MCP usage in `MCPServerManager` or manual connect/cleanup calls
- Be aware that tool lists can change between runs if the remote server adds/removes tools
- Server cleanup warnings are non-fatal but indicate resource leaks
The Insight (Rule of Thumb)
- Action: Use `MCPServerManager` as an async context manager to automatically handle connect/cleanup. Alternatively, bracket usage with explicit `server.connect()` and `server.cleanup()` calls.
- Value: N/A (lifecycle pattern, not a numeric setting).
- Trade-off: Dynamic tool fetching adds latency to each run (network round-trip to list tools) but ensures the agent always has the latest tool definitions. Caching is available via `MCPServer` configuration.
Reasoning
MCP servers are external processes or services with their own lifecycle. The SDK deliberately does not assume ownership of these resources. The docstring on `Agent.mcp_servers` explicitly states this responsibility. Server cleanup errors are caught and logged as warnings rather than raised, to avoid masking the actual agent execution result.
Code evidence from `agent.py:165-175`:
mcp_servers: list[MCPServer] = field(default_factory=list)
"""A list of Model Context Protocol servers that the agent can use. Every time
the agent runs, it will include tools from these servers in the list of
available tools.
NOTE: You are expected to manage the lifecycle of these servers. Specifically,
you must call `server.connect()` before passing it to the agent, and
`server.cleanup()` when the server is no longer needed. Consider using
`MCPServerManager` from `agents.mcp` to keep connect/cleanup in the same task.
"""
Cleanup error handling from `mcp/server.py:546-548`:
except Exception as cleanup_error:
logger.warning(
"Error during cleanup of MCP server '%s': %s", self.name, cleanup_error
)