Connect to an MCP server
Your Agent can connect to external Model Context Protocol (MCP) ↗ 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.
An Agent with endpoints to:
- Connect to an MCP server
- List available tools from connected servers
- Get the connection status
An MCP server to connect to (or use the public example in this tutorial).
-
Create a new Agent project using the
hello-worldtemplate:Terminal window npm create cloudflare@latest -- my-mcp-client --template=cloudflare/ai/demos/hello-worldTerminal window yarn create cloudflare my-mcp-client --template=cloudflare/ai/demos/hello-worldTerminal window pnpm create cloudflare@latest my-mcp-client --template=cloudflare/ai/demos/hello-world -
Move into the project directory:
Terminal window cd my-mcp-clientYour Agent is ready! The template includes a minimal Agent in
src/index.ts:JavaScript import { Agent, routeAgentRequest } from "agents";export class HelloAgent extends Agent {async onRequest(request) {return new Response("Hello, Agent!", { status: 200 });}}export default {async fetch(request, env) {return ((await routeAgentRequest(request, env, { cors: true })) ||new Response("Not found", { status: 404 }));},};TypeScript import { Agent, type AgentNamespace, routeAgentRequest } from "agents";type Env = {HelloAgent: AgentNamespace<HelloAgent>;};export class HelloAgent extends Agent<Env, never> {async onRequest(request: Request): Promise<Response> {return new Response("Hello, Agent!", { status: 200 });}}export default {async fetch(request: Request, env: Env) {return ((await routeAgentRequest(request, env, { cors: true })) ||new Response("Not found", { status: 404 }));},} satisfies ExportedHandler<Env>;
-
Add an endpoint to connect to MCP servers. Update your Agent class in
src/index.ts:JavaScript export class HelloAgent extends Agent {async onRequest(request) {const url = new URL(request.url);// Connect to an MCP serverif (url.pathname.endsWith("add-mcp") && request.method === "POST") {const { serverUrl, name } = await request.json();const { id, authUrl } = await this.addMcpServer(name, serverUrl);if (authUrl) {// OAuth required - return auth URLreturn new Response(JSON.stringify({ serverId: id, authUrl }), {headers: { "Content-Type": "application/json" },});}return new Response(JSON.stringify({ serverId: id, status: "connected" }),{ headers: { "Content-Type": "application/json" } },);}return new Response("Not found", { status: 404 });}}TypeScript export class HelloAgent extends Agent<Env, never> {async onRequest(request: Request): Promise<Response> {const url = new URL(request.url);// Connect to an MCP serverif (url.pathname.endsWith("add-mcp") && request.method === "POST") {const { serverUrl, name } = (await request.json()) as {serverUrl: string;name: string;};const { id, authUrl } = await this.addMcpServer(name, serverUrl);if (authUrl) {// OAuth required - return auth URLreturn new Response(JSON.stringify({ serverId: id, authUrl }),{ headers: { "Content-Type": "application/json" } },);}return new Response(JSON.stringify({ serverId: id, status: "connected" }),{ headers: { "Content-Type": "application/json" } },);}return new Response("Not found", { status: 404 });}}
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.
-
Start your development server:
Terminal window npm start -
In a new terminal, connect to an MCP server (using a public example):
Terminal window curl -X POST http://localhost:8788/agents/hello-agent/default/add-mcp \-H "Content-Type: application/json" \-d '{"serverUrl": "https://docs.mcp.cloudflare.com/mcp","name": "Example Server"}'You should see a response with the server ID:
{"serverId": "example-server-id","status": "connected"}
-
Add an endpoint to see which tools are available from connected servers:
JavaScript export class HelloAgent extends Agent {async onRequest(request) {const url = new URL(request.url);// ... previous add-mcp endpoint ...// List MCP state (servers, tools, etc)if (url.pathname.endsWith("mcp-state") && request.method === "GET") {const mcpState = this.getMcpServers();return new Response(JSON.stringify(mcpState, null, 2), {headers: { "Content-Type": "application/json" },});}return new Response("Not found", { status: 404 });}}TypeScript export class HelloAgent extends Agent<Env, never> {async onRequest(request: Request): Promise<Response> {const url = new URL(request.url);// ... previous add-mcp endpoint ...// List MCP state (servers, tools, etc)if (url.pathname.endsWith("mcp-state") && request.method === "GET") {const mcpState = this.getMcpServers();return new Response(JSON.stringify(mcpState, null, 2), {headers: { "Content-Type": "application/json" },});}return new Response("Not found", { status: 404 });}} -
Test it:
Terminal window curl http://localhost:8788/agents/hello-agent/default/mcp-stateYou'll see all connected servers, their connection states, and available tools:
{"servers": {"example-server-id": {"name": "Example Server","state": "ready","server_url": "https://docs.mcp.cloudflare.com/mcp",...}},"tools": [{"name": "add","description": "Add two numbers","serverId": "example-server-id",...}]}
You created an Agent that can:
- Connect to external MCP servers dynamically
- Handle OAuth authentication flows when required
- List all available tools from connected servers
- Monitor connection status
Connections persist in the Agent's SQL storage, so they remain active across requests.
- Handle OAuth flows — Configure OAuth callbacks and error handling
- McpClient — API reference — Complete API documentation
Was this helpful?
- Resources
- API
- New to Cloudflare?
- Directory
- Sponsorships
- Open Source
- Support
- Help Center
- System Status
- Compliance
- GDPR
- Company
- cloudflare.com
- Our team
- Careers
- © 2025 Cloudflare, Inc.
- Privacy Policy
- Terms of Use
- Report Security Issues
- Trademark
-