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