Skip to content

Commit feec1a6

Browse files
Add basic MCP client documentation (#26276)
* Add MCP client documentation The Agent class provides public APIs for connecting to MCP servers but these were completely undocumented. This adds API reference documentation, a tutorial for first connection, and a guide for handling OAuth flows with MCP servers. * Use Cloudflare Observability MCP as example * PCX edit --------- Co-authored-by: Jun Lee <[email protected]>
1 parent ca4f7f4 commit feec1a6

File tree

4 files changed

+950
-0
lines changed

4 files changed

+950
-0
lines changed

src/content/docs/agents/api-reference/agents-api.mdx

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -580,6 +580,40 @@ Visit the [state management API documentation](/agents/api-reference/store-and-s
580580

581581
:::
582582

583+
### MCP Client API
584+
585+
The Agents SDK allows your Agent to act as an MCP (Model Context Protocol) client, connecting to remote MCP servers and using their tools, resources, and prompts.
586+
587+
<TypeScriptExample>
588+
589+
```ts
590+
class Agent<Env, State = unknown> {
591+
// Connect to an MCP server
592+
async addMcpServer(
593+
serverName: string,
594+
url: string,
595+
callbackHost?: string,
596+
agentsPrefix?: string,
597+
options?: MCPClientOptions
598+
): Promise<{ id: string; authUrl: string | undefined }>;
599+
600+
// Disconnect from an MCP server
601+
async removeMcpServer(id: string): Promise<void>;
602+
603+
// Get state of all connected MCP servers
604+
getMcpServers(): MCPServersState;
605+
}
606+
```
607+
608+
</TypeScriptExample>
609+
610+
When your Agent connects to MCP servers, it can dynamically discover and use tools provided by those servers, enabling powerful integrations with external services.
611+
612+
:::note
613+
614+
For complete MCP client API documentation, including OAuth configuration and advanced usage, refer to the [Agent — MCP Client API](/agents/model-context-protocol/mcp-client-api/).
615+
616+
:::
583617

584618
### Client API
585619

Lines changed: 223 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,223 @@
1+
---
2+
title: Connect to an MCP server
3+
pcx_content_type: tutorial
4+
tags:
5+
- MCP
6+
sidebar:
7+
order: 5
8+
---
9+
10+
import { Render, TypeScriptExample, PackageManagers, Steps } from "~/components";
11+
12+
Your Agent can connect to external [Model Context Protocol (MCP)](https://modelcontextprotocol.io) servers to access their tools and extend your Agent's capabilities. In this tutorial, you'll create an Agent that connects to an MCP server and uses one of its tools.
13+
14+
## What you will build
15+
16+
An Agent with endpoints to:
17+
- Connect to an MCP server
18+
- List available tools from connected servers
19+
- Get the connection status
20+
21+
## Prerequisites
22+
23+
An MCP server to connect to (or use the public example in this tutorial).
24+
25+
## 1. Create a basic Agent
26+
27+
<Steps>
28+
29+
1. Create a new Agent project using the `hello-world` template:
30+
31+
<PackageManagers
32+
type="create"
33+
pkg="cloudflare@latest"
34+
args={"my-mcp-client --template=cloudflare/ai/demos/hello-world"}
35+
/>
36+
37+
2. Move into the project directory:
38+
39+
```sh
40+
cd my-mcp-client
41+
```
42+
43+
Your Agent is ready! The template includes a minimal Agent in `src/index.ts`:
44+
45+
<TypeScriptExample>
46+
47+
```ts title="src/index.ts"
48+
import { Agent, type AgentNamespace, routeAgentRequest } from "agents";
49+
50+
type Env = {
51+
HelloAgent: AgentNamespace<HelloAgent>;
52+
};
53+
54+
export class HelloAgent extends Agent<Env, never> {
55+
async onRequest(request: Request): Promise<Response> {
56+
return new Response("Hello, Agent!", { status: 200 });
57+
}
58+
}
59+
60+
export default {
61+
async fetch(request: Request, env: Env) {
62+
return (
63+
(await routeAgentRequest(request, env, { cors: true })) ||
64+
new Response("Not found", { status: 404 })
65+
);
66+
},
67+
} satisfies ExportedHandler<Env>;
68+
```
69+
</TypeScriptExample>
70+
</Steps>
71+
72+
## 2. Add MCP connection endpoint
73+
74+
<Steps>
75+
76+
1. Add an endpoint to connect to MCP servers. Update your Agent class in `src/index.ts`:
77+
78+
<TypeScriptExample>
79+
80+
```ts title="src/index.ts"
81+
export class HelloAgent extends Agent<Env, never> {
82+
async onRequest(request: Request): Promise<Response> {
83+
const url = new URL(request.url);
84+
85+
// Connect to an MCP server
86+
if (url.pathname.endsWith("add-mcp") && request.method === "POST") {
87+
const { serverUrl, name } = (await request.json()) as {
88+
serverUrl: string;
89+
name: string;
90+
};
91+
92+
const { id, authUrl } = await this.addMcpServer(name, serverUrl);
93+
94+
if (authUrl) {
95+
// OAuth required - return auth URL
96+
return new Response(
97+
JSON.stringify({ serverId: id, authUrl }),
98+
{ headers: { "Content-Type": "application/json" } },
99+
);
100+
}
101+
102+
return new Response(
103+
JSON.stringify({ serverId: id, status: "connected" }),
104+
{ headers: { "Content-Type": "application/json" } },
105+
);
106+
}
107+
108+
return new Response("Not found", { status: 404 });
109+
}
110+
}
111+
```
112+
113+
</TypeScriptExample>
114+
</Steps>
115+
116+
The `addMcpServer()` method connects to an MCP server. If the server requires OAuth authentication, it returns an `authUrl` that users must visit to complete authorization.
117+
118+
## 3. Test the connection
119+
120+
<Steps>
121+
122+
1. Start your development server:
123+
124+
```sh
125+
npm start
126+
```
127+
128+
2. In a new terminal, connect to an MCP server (using a public example):
129+
130+
```sh
131+
curl -X POST http://localhost:8788/agents/hello-agent/default/add-mcp \
132+
-H "Content-Type: application/json" \
133+
-d '{
134+
"serverUrl": "https://docs.mcp.cloudflare.com/mcp",
135+
"name": "Example Server"
136+
}'
137+
```
138+
139+
You should see a response with the server ID:
140+
141+
```json
142+
{
143+
"serverId": "example-server-id",
144+
"status": "connected"
145+
}
146+
```
147+
148+
</Steps>
149+
150+
## 4. List available tools
151+
152+
<Steps>
153+
154+
1. Add an endpoint to see which tools are available from connected servers:
155+
156+
<TypeScriptExample>
157+
158+
```ts title="src/index.ts"
159+
export class HelloAgent extends Agent<Env, never> {
160+
async onRequest(request: Request): Promise<Response> {
161+
const url = new URL(request.url);
162+
163+
// ... previous add-mcp endpoint ...
164+
165+
// List MCP state (servers, tools, etc)
166+
if (url.pathname.endsWith("mcp-state") && request.method === "GET") {
167+
const mcpState = this.getMcpServers();
168+
169+
return new Response(JSON.stringify(mcpState, null, 2), {
170+
headers: { "Content-Type": "application/json" },
171+
});
172+
}
173+
174+
return new Response("Not found", { status: 404 });
175+
}
176+
}
177+
```
178+
</TypeScriptExample>
179+
180+
2. Test it:
181+
182+
```sh
183+
curl http://localhost:8788/agents/hello-agent/default/mcp-state
184+
```
185+
186+
You'll see all connected servers, their connection states, and available tools:
187+
188+
```json
189+
{
190+
"servers": {
191+
"example-server-id": {
192+
"name": "Example Server",
193+
"state": "ready",
194+
"server_url": "https://docs.mcp.cloudflare.com/mcp",
195+
...
196+
}
197+
},
198+
"tools": [
199+
{
200+
"name": "add",
201+
"description": "Add two numbers",
202+
"serverId": "example-server-id",
203+
...
204+
}
205+
]
206+
}
207+
```
208+
</Steps>
209+
210+
## Summary
211+
212+
You created an Agent that can:
213+
- Connect to external MCP servers dynamically
214+
- Handle OAuth authentication flows when required
215+
- List all available tools from connected servers
216+
- Monitor connection status
217+
218+
Connections persist in the Agent's [SQL storage](/agents/api-reference/store-and-sync-state/), so they remain active across requests.
219+
220+
## Next steps
221+
222+
- [Handle OAuth flows](/agents/guides/oauth-mcp-client) — Configure OAuth callbacks and error handling
223+
- [McpClient — API reference](/agents/model-context-protocol/mcp-client-api/) — Complete API documentation

0 commit comments

Comments
 (0)