Quick Start
Attach an MCP server at runtime
How It Works
Runtime-attached MCPs live in a private_mcp_servers registry on the agent. Each add_mcp_server call registers the server, appends it to self.tools, and refreshes the toolset. Removed servers call mcp.shutdown() best-effort before deregistration.
API Reference
| Method | Returns | Raises |
|---|---|---|
add_mcp_server(name, mcp) | MCP | ValueError if name is empty or already attached |
remove_mcp_server(name) | bool (False if name unknown) | — |
refresh_tools() | List[Any] | — |
list_mcp_servers() | List[str] | — |
Common Patterns
Gateway agent adds Notion mid-session
Hot-swap under the same name
ValueError("MCP server 'notion' is already attached. Call remove_mcp_server() first to replace it.").
React to tools/list_changed
refresh_tools() when an MCP server signals that its tool list changed — per-turn assembly already reads self.tools live, but this forces an immediate refresh.
Cleanup
agent.close() and await agent.aclose() both shut down every runtime-attached MCP via _shutdown_runtime_mcp_servers(). Failures on individual servers are logged and skipped so one bad shutdown does not block the rest.
remove_mcp_server() manually before closing the agent.
Best Practices
Use unique, descriptive names
Use unique, descriptive names
Attach each MCP under a stable name (
"notion", "github", "postgres") so you can list and remove servers predictably mid-session.Remove before re-attaching under the same name
Remove before re-attaching under the same name
add_mcp_server raises on duplicate names. Call remove_mcp_server(name) first when hot-swapping credentials or server commands.Tools surface on the next turn
Tools surface on the next turn
New tools are not injected into the current LLM turn. Send another message (or continue the run) after attaching so the agent sees the expanded toolset.
Rely on close()/aclose() for guaranteed cleanup
Rely on close()/aclose() for guaranteed cleanup
Long-running services should still call
close() or aclose() when the agent session ends — runtime MCPs are tracked and shut down automatically.Related
MCP
Static MCP setup at construction time
Tools
Function tools and tool registry
MCP Lifecycle
Context manager and connection cleanup
Load MCP Tools
Load MCP tools into an agent at build time

