エージェントは Model Context Protocol(MCP) をクライアントとして使えます。エージェントを外部 MCP サーバーに接続し、サーバーが公開するツールを発見し、そのツールをモデル呼び出しへ渡せます。
MCP は、次をしたいときに使います。
- 外部 MCP サーバーが公開するツールを呼ぶ。
- エージェント、IDE、その他の AI クライアント間でツールを再利用する。
- すでに MCP エンドポイントを公開しているサービスへ接続する。
- 外部ツールアクセスに OAuth またはトークンベースの認可を付ける。
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 を返します。接続はエージェントの SQL ストレージ に永続化されます。
公開 MCP サーバーでは、バインディング設定は不要です。サーバー URL、API トークン、OAuth 設定は、環境変数またはシークレットとして保存します。
Bearer トークンや 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
エージェントを外部 MCP サーバーに接続し、ツール、リソース、プロンプトを使います。
MCP サーバーへ接続する
外部 MCP サーバーに接続し、そのツールを使うエージェントを作成します。
Code Mode で MCP ツールを使う
MCP ツールで、段階的な発見、コードによる合成、耐久性のある承認を使います。
Model Context Protocol 仕様
AI アプリケーションを外部のツールやデータに接続するオープンプロトコルを確認します。