shutdown() so subprocesses, streams, and sockets close reliably.
Quick Start
How It Works
| Phase | What happens |
|---|---|
| 1. Enter | The with block opens the MCP connection |
| 2. Use | The agent calls MCP-provided tools |
| 3. Exit | shutdown() closes subprocesses, streams, and sockets |
Manual Cleanup
For cases where a context manager is not suitable:Lifecycle Methods
Authenticating the HTTP transport
Whenapi_key is configured on the MCP HTTP-stream server, all of GET, POST, and DELETE require:
hmac.compare_digest (timing-attack resistant). Missing or wrong tokens return 401 Unauthorized with {"error": "Unauthorized"}. DELETE returning 401 instead of 405 prevents information disclosure about whether sessions exist.
__enter__ / __exit__
Context manager protocol for automatic resource management:
shutdown()
Explicitly close all connections and cleanup resources:
__del__
Destructor ensures cleanup even if shutdown() was not called:
Connection Types
MCP supports multiple connection types, all with proper cleanup:Best Practices
Always use a context manager
Always use a context manager
Prefer
with MCP(...) as mcp: — cleanup runs even when an exception is raised.Handle exceptions inside the block
Handle exceptions inside the block
Wrap tool calls in
try/except inside the with block; __exit__ still closes the connection.Nest multiple MCP instances carefully
Nest multiple MCP instances carefully
Open each MCP in its own
with block or nest them — both instances shut down in reverse order.Pass secrets via env, not inline
Pass secrets via env, not inline
Use the
env= parameter with os.getenv(...) rather than hard-coding API keys in recipe files.Related
MCP CLI
Run and inspect MCP servers from the terminal
MCP Transports
Stdio, SSE, HTTP stream, and WebSocket options

