|
| 1 | +--- |
| 2 | +title: Advanced MCP Client Configuration |
| 3 | +pcx_content_type: concept |
| 4 | +tags: |
| 5 | + - MCP |
| 6 | +sidebar: |
| 7 | + order: 8 |
| 8 | +--- |
| 9 | + |
| 10 | +import { TypeScriptExample } from "~/components"; |
| 11 | + |
| 12 | +The MCP client implementation in the Agents SDK uses a modular architecture with pluggable storage adapters. This allows you to customize how MCP server connections are persisted and managed. |
| 13 | + |
| 14 | +## Storage Adapter Architecture |
| 15 | + |
| 16 | +The `MCPClientManager` uses a storage adapter pattern to decouple storage logic from the client management logic. By default, the `Agent` class provides a SQL-based storage adapter (`AgentMCPStorageAdapter`) that stores MCP server configurations in Durable Object SQL storage. |
| 17 | + |
| 18 | +### Default SQL Storage |
| 19 | + |
| 20 | +The Agent class automatically creates and manages MCP server storage using SQL: |
| 21 | + |
| 22 | +<TypeScriptExample> |
| 23 | + |
| 24 | +```ts title="src/index.ts" |
| 25 | +import { Agent } from "agents"; |
| 26 | + |
| 27 | +export class MyAgent extends Agent<Env, never> { |
| 28 | + async onRequest(request: Request): Promise<Response> { |
| 29 | + // The `this.mcp` client manager is already configured with SQL storage |
| 30 | + const { id, authUrl } = await this.addMcpServer( |
| 31 | + "Weather API", |
| 32 | + "https://weather-mcp.example.com/mcp", |
| 33 | + ); |
| 34 | + |
| 35 | + return new Response(JSON.stringify({ id, authUrl })); |
| 36 | + } |
| 37 | +} |
| 38 | +``` |
| 39 | + |
| 40 | +</TypeScriptExample> |
| 41 | + |
| 42 | +Under the hood, this creates a table named `cf_agents_mcp_servers` with the following schema: |
| 43 | + |
| 44 | +```sql |
| 45 | +CREATE TABLE IF NOT EXISTS cf_agents_mcp_servers ( |
| 46 | + id TEXT PRIMARY KEY NOT NULL, |
| 47 | + name TEXT NOT NULL, |
| 48 | + server_url TEXT NOT NULL, |
| 49 | + callback_url TEXT NOT NULL, |
| 50 | + client_id TEXT, |
| 51 | + auth_url TEXT, |
| 52 | + server_options TEXT |
| 53 | +) |
| 54 | +``` |
| 55 | + |
| 56 | +### Storage Adapter Interface |
| 57 | + |
| 58 | +If you need custom storage behavior (such as storing MCP configurations in KV, R2, or an external database), you can implement the `MCPStorageAdapter` interface: |
| 59 | + |
| 60 | +<TypeScriptExample> |
| 61 | + |
| 62 | +```ts title="src/custom-storage.ts" |
| 63 | +import type { MCPStorageAdapter, MCPServerRow } from "agents/mcp"; |
| 64 | + |
| 65 | +export class CustomStorageAdapter implements MCPStorageAdapter { |
| 66 | + constructor(private kv: KVNamespace) {} |
| 67 | + |
| 68 | + async create(): Promise<void> { |
| 69 | + // Initialize storage (if needed) |
| 70 | + } |
| 71 | + |
| 72 | + async destroy(): Promise<void> { |
| 73 | + // Clean up storage |
| 74 | + await this.kv.delete("mcp_servers"); |
| 75 | + } |
| 76 | + |
| 77 | + async saveServer(server: MCPServerRow): Promise<void> { |
| 78 | + const servers = await this.listServers(); |
| 79 | + const updated = servers.filter((s) => s.id !== server.id); |
| 80 | + updated.push(server); |
| 81 | + await this.kv.put("mcp_servers", JSON.stringify(updated)); |
| 82 | + } |
| 83 | + |
| 84 | + async removeServer(serverId: string): Promise<void> { |
| 85 | + const servers = await this.listServers(); |
| 86 | + const filtered = servers.filter((s) => s.id !== serverId); |
| 87 | + await this.kv.put("mcp_servers", JSON.stringify(filtered)); |
| 88 | + } |
| 89 | + |
| 90 | + async listServers(): Promise<MCPServerRow[]> { |
| 91 | + const data = await this.kv.get("mcp_servers", "json"); |
| 92 | + return (data as MCPServerRow[]) || []; |
| 93 | + } |
| 94 | + |
| 95 | + async getServerByCallbackUrl( |
| 96 | + callbackUrl: string, |
| 97 | + ): Promise<MCPServerRow | null> { |
| 98 | + const servers = await this.listServers(); |
| 99 | + return servers.find((s) => s.callback_url === callbackUrl) || null; |
| 100 | + } |
| 101 | + |
| 102 | + async clearOAuthCredentials(serverId: string): Promise<void> { |
| 103 | + const servers = await this.listServers(); |
| 104 | + const server = servers.find((s) => s.id === serverId); |
| 105 | + if (server) { |
| 106 | + server.callback_url = ""; |
| 107 | + server.auth_url = null; |
| 108 | + await this.saveServer(server); |
| 109 | + } |
| 110 | + } |
| 111 | +} |
| 112 | +``` |
| 113 | + |
| 114 | +</TypeScriptExample> |
| 115 | + |
| 116 | +### Using a Custom Storage Adapter |
| 117 | + |
| 118 | +To use a custom storage adapter with `MCPClientManager`, you need to instantiate the manager yourself: |
| 119 | + |
| 120 | +<TypeScriptExample> |
| 121 | + |
| 122 | +```ts title="src/index.ts" |
| 123 | +import { MCPClientManager } from "agents/mcp"; |
| 124 | +import { CustomStorageAdapter } from "./custom-storage"; |
| 125 | + |
| 126 | +type Env = { |
| 127 | + MCP_STORAGE: KVNamespace; |
| 128 | +}; |
| 129 | + |
| 130 | +export class MyAgent extends Agent<Env, never> { |
| 131 | + mcp!: MCPClientManager; |
| 132 | + |
| 133 | + constructor(ctx: AgentContext, env: Env) { |
| 134 | + super(ctx, env); |
| 135 | + |
| 136 | + // Override the default MCP client manager with custom storage |
| 137 | + this.mcp = new MCPClientManager("MyAgent", "1.0.0", { |
| 138 | + storage: new CustomStorageAdapter(env.MCP_STORAGE), |
| 139 | + }); |
| 140 | + } |
| 141 | + |
| 142 | + async onRequest(request: Request): Promise<Response> { |
| 143 | + // Use MCP client as normal |
| 144 | + const { id } = await this.addMcpServer( |
| 145 | + "Weather API", |
| 146 | + "https://weather-mcp.example.com/mcp", |
| 147 | + ); |
| 148 | + |
| 149 | + return new Response(`Connected: ${id}`); |
| 150 | + } |
| 151 | +} |
| 152 | +``` |
| 153 | + |
| 154 | +</TypeScriptExample> |
| 155 | + |
| 156 | +## OAuth Security |
| 157 | + |
| 158 | +The storage adapter plays a critical role in OAuth security. After successful OAuth authentication, the adapter's `clearOAuthCredentials()` method is called to: |
| 159 | + |
| 160 | +1. Clear the `callback_url` to prevent replay attacks from malicious second callbacks |
| 161 | +2. Clear the `auth_url` so the Agent does not continuously prompt for OAuth on reconnection |
| 162 | + |
| 163 | +This security measure is handled automatically by the `MCPClientManager` during the OAuth callback flow. |
| 164 | + |
| 165 | +## Connection Restoration |
| 166 | + |
| 167 | +When an Agent hibernates and wakes up (for example, after receiving a request), the `MCPClientManager` automatically restores MCP server connections from storage by calling `listServers()` and recreating the connection state. |
| 168 | + |
| 169 | +The restoration process: |
| 170 | + |
| 171 | +1. Calls `listServers()` to get all persisted MCP server configurations |
| 172 | +2. For servers with `auth_url` (OAuth servers), creates connections in "authenticating" state |
| 173 | +3. For servers without `auth_url` (authenticated servers), reconnects immediately |
| 174 | +4. Maintains connection state across hibernation cycles |
| 175 | + |
| 176 | +## Performance Considerations |
| 177 | + |
| 178 | +### Callback URL Caching |
| 179 | + |
| 180 | +The `MCPClientManager` maintains an in-memory cache of callback URLs to optimize the `isCallbackRequest()` check. This avoids database queries for every incoming request. |
| 181 | + |
| 182 | +The cache is: |
| 183 | + |
| 184 | +- Lazily populated on the first callback check |
| 185 | +- Automatically invalidated when servers are added or removed |
| 186 | +- Refreshed from storage when needed |
| 187 | + |
| 188 | +### Storage Adapter Design |
| 189 | + |
| 190 | +When implementing a custom storage adapter, consider: |
| 191 | + |
| 192 | +- **Read performance**: `listServers()` is called during Agent initialization/restoration |
| 193 | +- **Write performance**: `saveServer()` is called when connecting to MCP servers |
| 194 | +- **Callback lookups**: `getServerByCallbackUrl()` is called during OAuth callbacks |
| 195 | +- **Security**: `clearOAuthCredentials()` must be atomic to prevent security issues |
| 196 | + |
| 197 | +## Migration Guide |
| 198 | + |
| 199 | +If you are upgrading from a previous version of the Agents SDK and have existing MCP server connections stored in SQL, no migration is required. The default `AgentMCPStorageAdapter` uses the same SQL table schema and will work with existing data. |
| 200 | + |
| 201 | +However, note the following behavior change: |
| 202 | + |
| 203 | +- **OAuth credentials**: After successful OAuth authentication, both `callback_url` and `auth_url` are now cleared from storage. This is a security improvement to prevent replay attacks. |
| 204 | + |
| 205 | +## Related |
| 206 | + |
| 207 | +- [MCP Client API reference](/agents/model-context-protocol/mcp-client-api/) — High-level Agent methods for MCP |
| 208 | +- [OAuth handling guide](/agents/guides/oauth-mcp-client/) — Complete OAuth integration guide |
| 209 | +- [Transport options](/agents/model-context-protocol/transport/) — Transport configuration |
0 commit comments