Skip to content

Commit 54eeb1c

Browse files
docs: Add MCP storage adapter documentation for PR #652
This PR introduces a storage adapter architecture for the MCP client manager, allowing custom storage backends for MCP server configurations. Changes: - Created advanced-client-api.mdx documenting the MCPStorageAdapter interface - Added security section to oauth-mcp-client.mdx about callback URL clearing - Updated mcp-client-api.mdx to link to advanced configuration guide These docs explain the new storage adapter pattern, OAuth security improvements, and provide examples for implementing custom storage backends. Related: cloudflare/agents#652
1 parent b3a1020 commit 54eeb1c

File tree

3 files changed

+233
-0
lines changed

3 files changed

+233
-0
lines changed

src/content/docs/agents/guides/oauth-mcp-client.mdx

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -409,7 +409,26 @@ export default {
409409

410410
</TypeScriptExample>
411411

412+
## Security considerations
413+
414+
The Agents SDK implements several security measures for OAuth flows:
415+
416+
### Callback URL clearing
417+
418+
After successful OAuth authentication, the SDK automatically clears both the `callback_url` and `auth_url` from storage. This prevents malicious actors from reusing callback URLs to impersonate authenticated connections.
419+
420+
### State parameter validation
421+
422+
The SDK validates that OAuth state parameters match the expected values during callback processing, preventing CSRF attacks.
423+
424+
### Token storage
425+
426+
OAuth tokens are stored securely in Durable Object storage and are never exposed to the client. The SDK handles token refresh automatically when needed.
427+
428+
For advanced security configurations or custom storage implementations, refer to the [Advanced MCP Client Configuration](/agents/model-context-protocol/advanced-client-api/) guide.
429+
412430
## Related
413431

414432
- [Connect to an MCP server](/agents/guides/connect-mcp-client) — Get started tutorial (no OAuth)
415433
- [McpClient — API reference](/agents/model-context-protocol/mcp-client-api/) — Complete API documentation
434+
- [Advanced MCP Client Configuration](/agents/model-context-protocol/advanced-client-api/) — Custom storage and security
Lines changed: 209 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,209 @@
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

src/content/docs/agents/model-context-protocol/mcp-client-api.mdx

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -272,7 +272,12 @@ export class MyAgent extends Agent<Env, never> {
272272

273273
</TypeScriptExample>
274274

275+
## Advanced Configuration
276+
277+
The MCP client implementation uses a modular storage adapter architecture. By default, the Agent class handles storage automatically using Durable Object SQL. For advanced use cases such as custom storage backends or fine-grained control over connection management, refer to the [Advanced MCP Client Configuration](/agents/model-context-protocol/advanced-client-api/) guide.
278+
275279
## Next Steps
276280

277281
- [Connect your first MCP server](/agents/guides/connect-mcp-client) — Tutorial to get started
278282
- [Handle OAuth flows](/agents/guides/oauth-mcp-client) — Complete OAuth integration guide
283+
- [Advanced MCP Client Configuration](/agents/model-context-protocol/advanced-client-api/) — Custom storage adapters and internal architecture

0 commit comments

Comments
 (0)