Agent 可作为 Model Context Protocol (MCP) 的客户端。将 Agent 连接到外部 MCP 服务器,发现这些服务器暴露的工具,并将这些工具传入模型调用。
在以下场景使用 MCP:
- 调用外部 MCP 服务器暴露的工具。
- 在 Agent、IDE 和其他 AI 客户端之间复用工具。
- 连接到已暴露 MCP 端点的服务。
- 为外部工具访问添加 OAuth 或基于 token 的授权。
若要构建 MCP 服务器,请参阅 Model Context Protocol (MCP)。
调用 addMcpServer() 连接到远程 MCP 服务器,然后将 this.mcp.getAITools() 传给 AI SDK。
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);
}
}import { Agent } from "agents";
import { generateText } from "ai";
import { createWorkersAI } from "workers-ai-provider";
export class ToolAgent extends Agent<Env> {
async onStart() {
await this.addMcpServer("github", "https://mcp.github.com/mcp");
}
async onRequest(request: 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);
}
}若服务器需要 OAuth,addMcpServer() 会返回身份验证状态和授权 URL。连接会持久化到 Agent 的 SQL 存储 中。
对于公开 MCP 服务器,无需 binding 配置。将服务器 URL、API token 或 OAuth 设置存储为环境变量或 secret。
对于需要 bearer token 或 Cloudflare Access 头的 MCP 服务器,连接时传入自定义传输头。
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,
},
},
});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,
},
},
});McpClient API
将 Agent 连接到外部 MCP 服务器并使用其工具、资源和 prompt。
连接到 MCP 服务器
创建连接到外部 MCP 服务器并使用其工具的 Agent。
在 Code Mode 中使用 MCP 工具
对 MCP 工具使用渐进式发现、基于代码的组合和持久化审批。
Model Context Protocol 规范
了解连接 AI 应用与外部工具和数据的开放协议。