Skip to content

MCP

Agents can use Model Context Protocol (MCP) as clients. Connect an agent to external MCP servers, discover the tools those servers expose, and pass those tools into model calls.

Use MCP when you want an agent to:

  • Call tools exposed by external MCP servers.
  • Reuse tools across agents, IDEs, and other AI clients.
  • Connect to services that already expose an MCP endpoint.
  • Add OAuth or token-based authorization around external tool access.

To build an MCP server instead, refer to Model Context Protocol (MCP).

Basic pattern

Call addMcpServer() to connect to a remote MCP server, then pass this.mcp.getAITools() to the AI SDK.

JavaScript
import { Agent } from "agents";
import { generateText } from "ai";
import { createWorkersAI } from "workers-ai-provider";
export class ToolAgent extends Agent {
async onStart() {
await this.addMcpServer("github", "https://mcp.github.com/mcp");
}
async onRequest(request) {
const workersai = createWorkersAI({ binding: this.env.AI });
const response = await generateText({
model: workersai("@cf/zai-org/glm-4.7-flash"),
prompt: "Use available tools to summarize the latest issue activity.",
tools: this.mcp.getAITools(),
});
return new Response(response.text);
}
}

If the server requires OAuth, addMcpServer() returns an authentication state and authorization URL. The connection is persisted in the agent's SQL storage.

Configuration

For public MCP servers, no binding configuration is required. Store server URLs, API tokens, or OAuth settings as environment variables or secrets.

For MCP servers that require bearer tokens or Cloudflare Access headers, pass custom transport headers when connecting.

JavaScript
await this.addMcpServer("internal", this.env.MCP_SERVER_URL, {
transport: {
headers: {
Authorization: `Bearer ${this.env.MCP_TOKEN}`,
"CF-Access-Client-Id": this.env.CF_ACCESS_CLIENT_ID,
"CF-Access-Client-Secret": this.env.CF_ACCESS_CLIENT_SECRET,
},
},
});