跳转到内容
本站为社区维护的非官方中文翻译,与 Cloudflare, Inc. 无关联。本站不提供账户登录,请勿在任何非官方站点输入您的 Cloudflare 账户信息。官方文档:developers.cloudflare.com

MCP 客户端

最后更新 查看 MarkdownAgent 设置

将代理连接到外部 Model Context Protocol (MCP)服务器,以使用其工具、资源和提示。Agents SDK v0.20.0 使用 @modelcontextprotocol/client,并自动协商无状态或旧版行为。MCP 客户端不需要 @modelcontextprotocol/sdk 或 @modelcontextprotocol/server。

有关软件包、类型、OAuth 提供程序和发布流程的变更,请参阅迁移到 MCP SDK v2。

概述

MCP 客户端功能允许你的代理:

  • 连接到外部 MCP 服务器 - GitHub、Slack、数据库和 AI 服务
  • 使用服务器工具 - 调用 MCP 服务器公开的函数
  • 访问资源 - 读取 MCP 服务器中的数据
  • 使用提示 - 利用预先构建的提示模板

快速入门

import { Agent } from "agents";

export class MyAgent extends Agent {
	async onRequest(request) {
		// Add an MCP server
		const result = await this.addMcpServer(
			"github",
			"https://mcp.github.com/mcp",
		);

		if (result.state === "authenticating") {
			// Server requires OAuth - redirect user to authorize
			return Response.redirect(result.authUrl);
		}

		// Server is ready - tools are now available
		const state = this.getMcpServers();
		console.log(`Connected! ${state.tools.length} tools available`);

		return new Response("MCP server connected");
	}
}
import { Agent } from "agents";

export class MyAgent extends Agent {
    async onRequest(request: Request) {
        // Add an MCP server
        const result = await this.addMcpServer(
            "github",
            "https://mcp.github.com/mcp",
        );

        if (result.state === "authenticating") {
            // Server requires OAuth - redirect user to authorize
            return Response.redirect(result.authUrl);
        }

        // Server is ready - tools are now available
        const state = this.getMcpServers();
        console.log(`Connected! ${state.tools.length} tools available`);

        return new Response("MCP server connected");
    }
}

连接会持久保存在代理的 SQL 存储中;代理连接到 MCP 服务器后,该服务器的所有工具都会自动可用。

添加 MCP 服务器

使用 addMcpServer() 连接到 MCP 服务器。对于非 OAuth 服务器,无需提供选项:

// Non-OAuth server — no options required
await this.addMcpServer("notion", "https://mcp.notion.so/mcp");

// OAuth server — callbackHost is auto-derived from the incoming request,
// but you can set it explicitly if needed (e.g. custom domains)
await this.addMcpServer("github", "https://mcp.github.com/mcp", {
	callbackHost: "https://my-worker.workers.dev",
});
// Non-OAuth server — no options required
await this.addMcpServer("notion", "https://mcp.notion.so/mcp");

// OAuth server — callbackHost is auto-derived from the incoming request,
// but you can set it explicitly if needed (e.g. custom domains)
await this.addMcpServer("github", "https://mcp.github.com/mcp", {
    callbackHost: "https://my-worker.workers.dev",
});

稳定的服务器 ID

默认情况下,每个连接都会分配一个生成的 nanoid(8) ID。对于连接器式集成,请传入 id,这样工具会显示为易读的键,而不是不透明的连接 ID。

await this.addMcpServer("GitHub", env.MCP_SESSION, {
	id: "github",
	props: { token: "..." },
});
// tools surface as `tool_github_<name>`
await this.addMcpServer("GitHub", env.MCP_SESSION, {
    id: "github",
    props: { token: "..." },
});
// tools surface as `tool_github_<name>`

提供 id 后,它会取代生成的值,成为存储、恢复、listServers()、listTools()、getAITools() 和 OAuth 状态中的服务器 ID。提供的 ID 会通过导出的 normalizeServerId 辅助函数进行规范化,因此像 "GitHub MCP!" 这样的值会变为 "github-mcp",确保 ID 可安全用于 AI SDK 工具名称和存储键。

稳定 ID 完全向后兼容,不会破坏现有代码。如果你在某个服务器的 addMcpServer 调用中添加 { id: "github" },而该服务器此前已使用自动生成的 ID 注册,SDK 会透明地将现有存储行、内存中的连接以及 OAuth 相关存储键迁移到新的稳定 ID。无需执行 removeMcpServer。只有在确实存在模糊冲突时,addMcpServer 才会抛出错误:同一稳定 ID 已属于另一个 不同的 (name, url) 服务器。

传输选项

MCP 支持多种传输类型:

await this.addMcpServer("server", "https://mcp.example.com/mcp", {
	transport: {
		type: "streamable-http",
	},
});
await this.addMcpServer("server", "https://mcp.example.com/mcp", {
    transport: {
        type: "streamable-http",
    },
});
传输方式 说明
auto 根据服务器响应自动检测(默认)
streamable-http 支持流式传输的 HTTP
sse Server-Sent Events - 旧版/兼容性传输方式

RPC 传输

addMcpServer() 也可以通过 Durable Object 绑定连接到 McpAgent,而无需使用 URL。消息通过 Workers RPC传递,因此服务器无需 HTTP 端点。

export class MyAgent extends Agent {
	async onStart() {
		// env.MyMCP is the Durable Object binding for an McpAgent class
		await this.addMcpServer("my-mcp", this.env.MyMCP, {
			props: { userId: "user-123", role: "admin" },
		});
	}
}
export class MyAgent extends Agent<Env> {
    async onStart() {
        // env.MyMCP is the Durable Object binding for an McpAgent class
        await this.addMcpServer("my-mcp", this.env.MyMCP, {
            props: { userId: "user-123", role: "admin" },
        });
    }
}
  • 无需身份验证。 RPC 传输没有 OAuth 流程。请在 props 中传递用户上下文。McpAgent 会通过 this.props 读取它。
  • 休眠后恢复。 绑定名称和 props 会被存储,因此连接无需额外代码即可恢复。
  • 按名称去重。 如果某个名称已有活动 RPC 连接,再次调用 addMcpServer() 会返回现有连接,因此可以安全地在 onStart() 中调用。
  • Agent 端无需 MCP SDK v1。 连接时不需要 @modelcontextprotocol/sdk。请从 agents/mcp/client 导入 RPCClientTransport 和 RPC_DO_PREFIX,而不是从会加载 v1 SDK 的 agents/mcp 导入。

有关服务器端配置(包括绑定和工具超时),请参阅 McpAgent 参考中的 RPC 传输。

自定义标头

适用于受身份验证保护(例如使用 Cloudflare Access)或使用 bearer token 的服务器:

await this.addMcpServer("internal", "https://internal-mcp.example.com/mcp", {
	transport: {
		headers: {
			Authorization: "Bearer my-token",
			"CF-Access-Client-Id": "...",
			"CF-Access-Client-Secret": "...",
		},
	},
});
await this.addMcpServer("internal", "https://internal-mcp.example.com/mcp", {
    transport: {
        headers: {
            Authorization: "Bearer my-token",
            "CF-Access-Client-Id": "...",
            "CF-Access-Client-Secret": "...",
        },
    },
});

URL 安全性

连接前会验证 MCP 服务器 URL,以防止服务器端请求伪造 (SSRF)。以下 URL 目标会被阻止:

  • 专用/内部 IP 范围(RFC 1918:10.x、172.16-31.x、192.168.x)
  • 未指定地址(0.0.0.0、[::])
  • 链路本地地址(169.254.x、fe80::)
  • IPv6 唯一本地地址(fc00::/7)
  • 映射到私有范围的 IPv4-mapped IPv6 地址(例如 [::ffff:10.0.0.1])
  • 云元数据端点(metadata.google.internal)

回环地址(localhost、127.x.x.x、[::1])允许用于本地开发。

返回值

addMcpServer() 会返回连接状态:

  • ready - 服务器已连接并已发现工具
  • authenticating - 服务器需要 OAuth;请将用户重定向到 authUrl

OAuth 身份验证

许多 MCP 服务器需要 OAuth 身份验证。代理会自动处理 OAuth 流程。

工作原理

sequenceDiagram
    participant Client
    participant Agent
    participant MCPServer

    Client->>Agent: addMcpServer(name, url)
    Agent->>MCPServer: Connect
    MCPServer-->>Agent: Requires OAuth
    Agent-->>Client: state: authenticating, authUrl
    Client->>MCPServer: User authorizes
    MCPServer->>Agent: Callback with code
    Agent->>MCPServer: Exchange for token
    Agent-->>Client: onMcpUpdate (ready)

在代理中处理 OAuth

class MyAgent extends Agent {
	async onRequest(request) {
		const result = await this.addMcpServer(
			"github",
			"https://mcp.github.com/mcp",
		);

		if (result.state === "authenticating") {
			// Redirect the user to the OAuth authorization page
			return Response.redirect(result.authUrl);
		}

		return Response.json({ status: "connected", id: result.id });
	}
}
class MyAgent extends Agent {
    async onRequest(request: Request) {
        const result = await this.addMcpServer(
            "github",
            "https://mcp.github.com/mcp",
        );

        if (result.state === "authenticating") {
            // Redirect the user to the OAuth authorization page
            return Response.redirect(result.authUrl);
        }

        return Response.json({ status: "connected", id: result.id });
    }
}

OAuth 回调

回调 URL 会自动构造:

https://{host}/{agentsPrefix}/{agent-name}/{instance-name}/callback

例如:https://my-worker.workers.dev/agents/my-agent/default/callback

OAuth token 会安全地存储在 SQLite 中,并在代理重启后保留。

在 OAuth 回调中保护实例名称

使用 sendIdentityOnConnect: false 隐藏敏感实例名称(例如会话 ID 或用户 ID)时,默认 OAuth 回调 URL 会暴露实例名称。为避免此安全问题,必须提供自定义 callbackPath。

import { Agent, routeAgentRequest, getAgentByName } from "agents";

export class SecureAgent extends Agent {
	static options = { sendIdentityOnConnect: false };

	async onRequest(request) {
		// callbackPath is required when sendIdentityOnConnect is false
		const result = await this.addMcpServer(
			"github",
			"https://mcp.github.com/mcp",
			{
				callbackPath: "mcp-oauth-callback", // Custom path without instance name
			},
		);

		if (result.state === "authenticating") {
			return Response.redirect(result.authUrl);
		}

		return new Response("Connected!");
	}
}

// Route the custom callback path to the agent
export default {
	async fetch(request, env) {
		const url = new URL(request.url);

		// Route custom MCP OAuth callback to agent instance
		if (url.pathname.startsWith("/mcp-oauth-callback")) {
			// Implement this to extract the instance name from your session/auth mechanism
			const instanceName = await getInstanceNameFromSession(request);

			const agent = await getAgentByName(env.SecureAgent, instanceName);
			return agent.fetch(request);
		}

		// Standard agent routing
		return (
			(await routeAgentRequest(request, env)) ??
			new Response("Not found", { status: 404 })
		);
	},
};
import { Agent, routeAgentRequest, getAgentByName } from "agents";

export class SecureAgent extends Agent {
    static options = { sendIdentityOnConnect: false };

    async onRequest(request: Request) {
        // callbackPath is required when sendIdentityOnConnect is false
        const result = await this.addMcpServer(
            "github",
            "https://mcp.github.com/mcp",
            {
                callbackPath: "mcp-oauth-callback", // Custom path without instance name
            },
        );

        if (result.state === "authenticating") {
            return Response.redirect(result.authUrl);
        }

        return new Response("Connected!");
    }
}

// Route the custom callback path to the agent
export default {
    async fetch(request: Request, env: Env) {
        const url = new URL(request.url);

        // Route custom MCP OAuth callback to agent instance
        if (url.pathname.startsWith("/mcp-oauth-callback")) {
            // Implement this to extract the instance name from your session/auth mechanism
            const instanceName = await getInstanceNameFromSession(request);

            const agent = await getAgentByName(env.SecureAgent, instanceName);
            return agent.fetch(request);
        }

        // Standard agent routing
        return (
            (await routeAgentRequest(request, env)) ??
            new Response("Not found", { status: 404 })
        );
    },
} satisfies ExportedHandler<Env>;

自定义 OAuth 回调处理

配置 OAuth 完成后的处理方式。默认情况下,身份验证成功后会重定向到应用的源站;失败时则显示 HTML 错误页面。

export class MyAgent extends Agent {
	onStart() {
		this.mcp.configureOAuthCallback({
			// Redirect after successful auth
			successRedirect: "https://myapp.com/success",

			// Redirect on error with error message in query string
			errorRedirect: "https://myapp.com/error",

			// Or use a custom handler
			customHandler: () => {
				// Close popup window after auth completes
				return new Response("<script>window.close();</script>", {
					headers: { "content-type": "text/html" },
				});
			},
		});
	}
}
export class MyAgent extends Agent {
    onStart() {
        this.mcp.configureOAuthCallback({
            // Redirect after successful auth
            successRedirect: "https://myapp.com/success",

            // Redirect on error with error message in query string
            errorRedirect: "https://myapp.com/error",

            // Or use a custom handler
            customHandler: () => {
                // Close popup window after auth completes
                return new Response("<script>window.close();</script>", {
                    headers: { "content-type": "text/html" },
                });
            },
        });
    }
}

使用 MCP 功能

连接后,可以访问服务器的功能:

获取可用工具

使用 listTools() 检查原始 MCP 目录,而不必为 AI SDK 模型调用预先准备工具:

const tools = this.mcp.listTools();

for (const tool of tools) {
	console.log(`Tool: ${tool.name}`);
	console.log(`  From server: ${tool.serverId}`);
	console.log(`  Title: ${tool.title ?? tool.annotations?.title ?? tool.name}`);
	console.log(`  Description: ${tool.description}`);
}
const tools = this.mcp.listTools();

for (const tool of tools) {
    console.log(`Tool: ${tool.name}`);
    console.log(`  From server: ${tool.serverId}`);
    console.log(`  Title: ${tool.title ?? tool.annotations?.title ?? tool.name}`);
    console.log(`  Description: ${tool.description}`);
}

getMcpServers().tools 会在完整 MCP 客户端状态中返回相同的原始工具记录。这两个 API 都不会转换工具架构。

与 AI SDK 集成

要将 MCP 工具与 AI SDK 搭配使用,请调用 this.mcp.getAITools() 将 MCP 工具转换为 AI SDK 格式:

import { generateText } from "ai";
import { createAI } from "agents/models/ai-sdk";

export class MyAgent extends Agent {
	async onRequest(request) {
		const ai = createAI({ binding: this.env.AI });
		const response = await generateText({
			model: ai("@cf/zai-org/glm-4.7-flash"),
			prompt: "What's the weather in San Francisco?",
			tools: this.mcp.getAITools(),
		});

		return new Response(response.text);
	}
}
import { generateText } from "ai";
import { createAI } from "agents/models/ai-sdk";

export class MyAgent extends Agent<Env> {
    async onRequest(request: Request) {
        const ai = createAI({ binding: this.env.AI });
        const response = await generateText({
            model: ai("@cf/zai-org/glm-4.7-flash"),
            prompt: "What's the weather in San Francisco?",
            tools: this.mcp.getAITools(),
        });

        return new Response(response.text);
    }
}

资源和提示

const state = this.getMcpServers();

// Available resources
for (const resource of state.resources) {
	console.log(`Resource: ${resource.name} (${resource.uri})`);
}

// Available prompts
for (const prompt of state.prompts) {
	console.log(`Prompt: ${prompt.name}`);
}
const state = this.getMcpServers();

// Available resources
for (const resource of state.resources) {
    console.log(`Resource: ${resource.name} (${resource.uri})`);
}

// Available prompts
for (const prompt of state.prompts) {
    console.log(`Prompt: ${prompt.name}`);
}

用户征询

MCP 服务器在处理其他操作时可以请求用户输入。在无状态路径中,用户征询会返回 input_required,并通过多轮往返请求 (MRTR) 完成。在旧版路径中,服务器会推送 elicitation/create 请求。两种路径都支持表单和 URL 模式。

在 onStart() 中为 Agent 支持的每种模式注册处理程序。同一组处理程序适用于两种路径:

import { Agent } from "agents";

class MyAgent extends Agent {
	onStart() {
		this.mcp.configureElicitationHandlers({
			form: (request, serverId) =>
				this.forwardElicitationToBrowser(request, serverId),
			url: (request, serverId) =>
				this.forwardElicitationToBrowser(request, serverId),
		});
	}

	forwardElicitationToBrowser(request, serverId) {
		// Forward the request to your UI and resolve after the user responds.
		// A complete implementation appears in Forward elicitation to a UI.
		throw new Error(
			`Implement elicitation for ${serverId}: ${request.params.message}`,
		);
	}
}
import { Agent } from "agents";
import type { ElicitRequest, ElicitResult } from "agents/mcp/client";

class MyAgent extends Agent<Env> {
    onStart() {
        this.mcp.configureElicitationHandlers({
            form: (request, serverId) =>
                this.forwardElicitationToBrowser(request, serverId),
            url: (request, serverId) =>
                this.forwardElicitationToBrowser(request, serverId),
        });
    }

    private forwardElicitationToBrowser(
        request: ElicitRequest,
        serverId: string,
    ): Promise<ElicitResult> {
        // Forward the request to your UI and resolve after the user responds.
        // A complete implementation appears in Forward elicitation to a UI.
        throw new Error(
            `Implement elicitation for ${serverId}: ${request.params.message}`,
        );
    }
}

serverId 用于标识发送请求的连接。你可以用它告知用户哪个服务器正在请求输入,并应用针对该服务器的策略。

能力协商和休眠

SDK 只会声明已配置处理程序的模式。旧版路径上的连接会在 initialize 期间声明这些模式。无状态路径上的请求会通过请求能力携带这些模式。仅有表单处理程序时会声明表单模式;仅有 URL 处理程序时会声明 URL 模式。没有处理程序的连接不会声明用户征询能力,因此服务器可以使用回退方式。

SDK 会将已声明的模式与每项服务器注册信息一起存储。因此,Durable Object 休眠后恢复的连接重新连接时,也能声明相同的模式。回调函数会保留在内存中,并在运行 onStart() 时重新附加。

添加服务器时,你可以明确缩小所声明模式的范围:

await this.addMcpServer("portal", "https://portal.example.com/mcp", {
	client: {
		capabilities: {
			elicitation: { form: {} },
		},
	},
});
await this.addMcpServer("portal", "https://portal.example.com/mcp", {
    client: {
        capabilities: {
            elicitation: { form: {} },
        },
    },
});

显式设置的 client.capabilities.elicitation 优先于根据处理程序推导的模式,并会随服务器注册信息持久保存。不要声明没有对应处理程序的模式。如果服务器发送了该模式,连接会因无法处理请求而返回错误。

表单模式

表单模式会在客户端收集结构化的非敏感数据。请求会在 requestedSchema 中包含受限的 JSON Schema。用户提交表单后,返回 action: "accept",并提供匹配的 content:

this.mcp.configureElicitationHandlers({
	form: async (request) => {
		const content = await showFormToUser(request.params.requestedSchema);
		return content ? { action: "accept", content } : { action: "cancel" };
	},
});
this.mcp.configureElicitationHandlers({
    form: async (request) => {
        const content = await showFormToUser(request.params.requestedSchema);
        return content ? { action: "accept", content } : { action: "cancel" };
    },
});

提交前允许用户查看和编辑值。根据 requestedSchema 验证接受的内容。不要使用表单模式请求密码、API 密钥、访问 token、支付凭据或其他秘密信息。

URL 模式

URL 模式会要求用户打开外部页面。可将其用于可能会收集秘密信息的带外交互,例如第三方授权或付款。请将 URL 保留在专用的用户征询路径中,不要放入模型可见的消息或工具结果文本。

URL 处理程序应当:

  1. 显示发送请求的 MCP 服务器。
  2. 显示请求消息、目标主机和完整 URL。
  3. 打开 URL 前征求用户同意。
  4. 在 Agent 和模型无法检查的浏览器上下文中打开页面。
  5. 征得同意后,返回不含 content 的 action: "accept"。
  6. 提供彼此独立的拒绝和取消控件。

不要预取 URL 或其元数据。将 URL 视为不可信输入。生产环境中的服务器应发送 HTTPS URL。

在 URL 模式中,accept 表示用户同意打开 URL,并不表示外部交互已经完成。服务器之后可能会发送带有请求 elicitationId 的 notifications/elicitation/complete。

响应操作

两种模式都支持以下三种操作:

操作 含义
accept 用户提交了表单或同意打开 URL。
decline 用户明确拒绝请求。
cancel 用户关闭请求但未明确选择。

仅在接受表单响应时包含 content。对于 URL、拒绝和取消响应,请省略该字段。

将用户征询转发到 UI

处理程序会返回一个 promise,但响应通常来自浏览器。将请求广播给已连接的客户端,然后通过 @callable 方法解析该 promise:

import { Agent, callable } from "agents";

class MyAgent extends Agent {
	pendingElicitations = new Map();

	onStart() {
		this.mcp.configureElicitationHandlers({
			form: (request, serverId) => this.forward(request, serverId),
			url: (request, serverId) => this.forward(request, serverId),
		});
	}

	forward(request, serverId) {
		const id = crypto.randomUUID();

		const result = new Promise((resolve) => {
			const timeout = setTimeout(() => {
				if (this.pendingElicitations.delete(id)) {
					resolve({ action: "cancel" });
				}
			}, 55_000);
			this.pendingElicitations.set(id, { resolve, timeout });
		});

		this.broadcast(
			JSON.stringify({
				type: "mcp-elicitation",
				id,
				serverId,
				params: request.params,
			}),
		);

		return result;
	}

	@callable()
	respondToElicitation(id, result) {
		const pending = this.pendingElicitations.get(id);
		if (!pending) return;

		this.pendingElicitations.delete(id);
		clearTimeout(pending.timeout);
		pending.resolve(result);
	}
}
import { Agent, callable } from "agents";
import type { ElicitRequest, ElicitResult } from "agents/mcp/client";

type PendingResolver = {
    resolve: (result: ElicitResult) => void;
    timeout: ReturnType<typeof setTimeout>;
};

class MyAgent extends Agent<Env> {
    private pendingElicitations = new Map<string, PendingResolver>();

    onStart() {
        this.mcp.configureElicitationHandlers({
            form: (request, serverId) => this.forward(request, serverId),
            url: (request, serverId) => this.forward(request, serverId),
        });
    }

    private forward(
        request: ElicitRequest,
        serverId: string,
    ): Promise<ElicitResult> {
        const id = crypto.randomUUID();

        const result = new Promise<ElicitResult>((resolve) => {
            const timeout = setTimeout(() => {
                if (this.pendingElicitations.delete(id)) {
                    resolve({ action: "cancel" });
                }
            }, 55_000);
            this.pendingElicitations.set(id, { resolve, timeout });
        });

        this.broadcast(
            JSON.stringify({
                type: "mcp-elicitation",
                id,
                serverId,
                params: request.params,
            }),
        );

        return result;
    }

    @callable()
    respondToElicitation(id: string, result: ElicitResult) {
        const pending = this.pendingElicitations.get(id);
        if (!pending) return;

        this.pendingElicitations.delete(id);
        clearTimeout(pending.timeout);
        pending.resolve(result);
    }
}

示例使用 55 秒超时,因为 MCP SDK 请求的默认超时为 60 秒。如果客户端调用设置了更长的请求超时,请相应调整此超时,使其先结束。

浏览器实现请参阅 mcp-client 示例 ↗。mcp-elicitation-mrtr ↗ 展示了无状态用户征询。

服务器端实现请参阅通过无状态处理程序进行用户征询。

管理服务器

MCP 服务器注册信息会在 Agent 重启后保留。SDK 会将服务器配置存储在 SQLite 中,安全保存 OAuth token,并在 Agent 唤醒时恢复连接。

列出所有服务器

const state = this.getMcpServers();

for (const [id, server] of Object.entries(state.servers)) {
	console.log(`${id}: ${server.name} (${server.server_url})`);
}
const state = this.getMcpServers();

for (const [id, server] of Object.entries(state.servers)) {
    console.log(`${id}: ${server.name} (${server.server_url})`);
}

获取服务器状态

使用服务器 ID 检查单个连接:

const state = this.getMcpServers();
const server = state.servers[serverId];

if (server) {
	console.log(`${server.name}: ${server.state}`);
	// state: "ready" | "authenticating" | "connecting" | "connected" | "discovering" | "failed"
}
const state = this.getMcpServers();
const server = state.servers[serverId];

if (server) {
    console.log(`${server.name}: ${server.state}`);
    // state: "ready" | "authenticating" | "connecting" | "connected" | "discovering" | "failed"
}

移除服务器

await this.removeMcpServer(serverId);
await this.removeMcpServer(serverId);

此操作会断开与服务器的连接,并将其从存储中移除。

客户端集成

已连接的客户端会通过 WebSocket 接收 MCP 实时更新:

import { useAgent } from "agents/react";
import { useState } from "react";

function Dashboard() {
	const [tools, setTools] = useState([]);
	const [servers, setServers] = useState({});

	const agent = useAgent({
		agent: "MyAgent",
		onMcpUpdate: (mcpState) => {
			setTools(mcpState.tools);
			setServers(mcpState.servers);
		},
	});

	return (
		<div>
			<h2>Connected Servers</h2>
			{Object.entries(servers).map(([id, server]) => (
				<div key={id}>
					{server.name}: {server.state}
				</div>
			))}

			<h2>Available Tools ({tools.length})</h2>
			{tools.map((tool) => (
				<div key={`${tool.serverId}-${tool.name}`}>{tool.name}</div>
			))}
		</div>
	);
}
import { useAgent } from "agents/react";
import { useState } from "react";

function Dashboard() {
    const [tools, setTools] = useState([]);
    const [servers, setServers] = useState({});

    const agent = useAgent({
        agent: "MyAgent",
        onMcpUpdate: (mcpState) => {
            setTools(mcpState.tools);
            setServers(mcpState.servers);
        },
    });

    return (
        <div>
            <h2>Connected Servers</h2>
            {Object.entries(servers).map(([id, server]) => (
                <div key={id}>
                    {server.name}: {server.state}
                </div>
            ))}

            <h2>Available Tools ({tools.length})</h2>
            {tools.map((tool) => (
                <div key={`${tool.serverId}-${tool.name}`}>{tool.name}</div>
            ))}
        </div>
    );
}

API 参考

addMcpServer()

添加与 MCP 服务器的连接,并让代理可以使用其工具。

当服务器名称和 URL 都与现有活动连接匹配时,调用 addMcpServer 具有幂等性:它会返回现有连接,而不会创建重复连接。因此,可以安全地在 onStart() 中调用,而无需担心重启时出现重复连接。

如果调用 addMcpServer 时名称相同但 URL不同,则会创建新连接。两个连接都会保持活动状态,其工具会合并到 getAITools() 中。要替换服务器,请先调用 removeMcpServer(oldId)。

比较前会规范化 URL(处理尾部斜杠、默认端口和主机名大小写),因此 https://MCP.Example.com 与 https://mcp.example.com/ 会被视为同一 URL。

// HTTP transport (Streamable HTTP, SSE)
async addMcpServer(
  serverName: string,
  url: string,
  options?: {
    id?: string;
    callbackHost?: string;
    callbackPath?: string;
    agentsPrefix?: string;
    client?: McpClientOptions;
    transport?: {
      headers?: HeadersInit;
      type?: "sse" | "streamable-http" | "auto";
    };
    retry?: RetryOptions;
  }
): Promise<
  | { id: string; state: "authenticating"; authUrl: string }
  | { id: string; state: "ready" }
>

// RPC transport (Durable Object binding for an McpAgent)
async addMcpServer(
  serverName: string,
  binding: DurableObjectNamespace<McpAgent>,
  options?: {
    id?: string;
    props?: Record<string, unknown>;
  }
): Promise<{ id: string; state: "ready" }>

参数(HTTP 传输)

  • serverName(字符串,必填)— MCP 服务器的显示名称
  • url(字符串,必填)— MCP 服务器端点的 URL
  • options(对象,可选)— 连接配置:
    • id — 可选的稳定 ID,由调用方为连接器类集成提供。设置后,该 ID 会在存储、listServers()、listTools()、getAITools()(因此工具键会变得易读,例如 tool_github_create_pull_request)和 OAuth state 中取代生成的 nanoid(8)。请参阅稳定服务器 ID
    • callbackHost — OAuth 回调 URL 的主机。仅 OAuth 身份验证服务器需要此项。如果省略,将从传入请求或 WebSocket 连接 URI 自动推导。通常无需设置,除非你使用的自定义域与 Worker 主机名不同
    • callbackPath — 自定义回调 URL 路径,用于替代默认的 /agents/{class}/{name}/callback 构造方式。sendIdentityOnConnect 为 false 时必须设置,以免泄露实例名称。设置后,回调 URL 将变为 {callbackHost}/{callbackPath}。你必须通过 getAgentByName 将此路径路由到代理实例
    • agentsPrefix — OAuth 回调路径的 URL 前缀。默认值:"agents"。设置 callbackPath 后会忽略此项
    • client — Agents 支持的 @modelcontextprotocol/client 中 McpClientOptions 子集。默认验证器在 Workers 中支持 JSON Schema 2020-12 和旧版 draft-07 架构
    • transport — 传输层配置:
      • headers — 用于身份验证的自定义 HTTP 标头
      • type — 传输类型:"auto"(默认值)、"streamable-http" 或 "sse"
    • retry — 连接和重新连接尝试的重试选项。在休眠后或 OAuth 完成后恢复连接时会保留并使用这些选项。默认值:最多尝试 3 次,基础延迟 500ms,最大延迟 5s。详情请参阅 Retries 中的 RetryOptions。

参数(RPC 传输)

  • serverName(字符串,必填)— MCP 服务器的显示名称
  • binding(DurableObjectNamespace,必需)— McpAgent 类的 Durable Object 绑定
  • options(对象,可选):
    • id — 可选的稳定服务器 ID,由调用方提供。请参阅稳定服务器 ID
    • props — 传递给 McpAgent 并可通过 this.props 使用的数据,例如用户上下文

RPC 传输仅连接到已弃用的 McpAgent。建议使用 HTTP 传输和 createMcpHandler 服务器。请参阅 RPC 传输。

返回值

返回一个 Promise,其解析结果是根据连接状态区分的联合类型:

  • 当 state 为 "authenticating" 时:
    • id(字符串)— 此服务器连接的唯一标识符
    • state("authenticating")— 服务器正在等待 OAuth 授权
    • authUrl(字符串)— 用于用户身份验证的 OAuth 授权 URL
  • 当 state 为 "ready" 时:
    • id(字符串)— 此服务器连接的唯一标识符
    • state("ready")— 服务器已完全连接并可正常运行

removeMcpServer()

断开与 MCP 服务器的连接并清理其资源。

async removeMcpServer(id: string): Promise<void>

参数

  • id(字符串,必需)— addMcpServer() 返回的服务器连接 ID

getMcpServers()

获取所有 MCP 服务器连接的当前状态。

getMcpServers(): MCPServersState

返回值

type MCPServersState = {
    servers: Record<
        string,
        {
            name: string;
            server_url: string;
            auth_url: string | null;
            state:
                | "authenticating"
                | "connecting"
                | "connected"
                | "discovering"
                | "ready"
                | "failed";
            capabilities: ServerCapabilities | null;
            instructions: string | null;
            error: string | null;
        }
    >;
    tools: Array<Tool & { serverId: string }>;
    prompts: Array<Prompt & { serverId: string }>;
    resources: Array<Resource & { serverId: string }>;
    resourceTemplates: Array<ResourceTemplate & { serverId: string }>;
};

state 字段表示连接生命周期:

  • authenticating — 等待 OAuth 授权完成
  • connecting — 正在建立传输连接
  • connected — 已建立传输连接
  • discovering — 正在发现服务器功能(工具、资源、提示)
  • ready — 已完全连接并可正常运行
  • failed — 连接失败(详情请参阅 error 字段)

当 state 为 "failed" 时,error 字段包含错误消息。系统会自动转义外部 OAuth 提供商的错误消息以防止 XSS 攻击,因此可以直接在 UI 中安全显示。

configureOAuthCallback()

为需要身份验证的 MCP 服务器配置 OAuth 回调行为。此方法可用于自定义用户完成 OAuth 授权后的处理方式。

this.mcp.configureOAuthCallback(options: {
  successRedirect?: string;
  errorRedirect?: string;
  customHandler?: () => Response | Promise<Response>;
}): void

参数

  • options(对象,必需)— OAuth 回调配置:
    • successRedirect(字符串,可选)— 身份验证成功后要重定向到的 URL
    • errorRedirect(字符串,可选)— 身份验证失败后要重定向到的 URL。错误消息会作为 ?error=<message> 查询参数附加
    • customHandler(函数,可选)— 用于完全自定义回调响应的处理程序。必须返回 Response

默认行为

未提供配置时:

  • 成功:重定向到应用程序源站
  • 失败:显示包含错误消息的 HTML 错误页面

如果 OAuth 失败,连接状态会变为 "failed",错误消息会存储在 server.error 字段中,以便在 UI 中显示。

使用

在任何 OAuth 流程开始前,于 onStart() 中进行配置:

export class MyAgent extends Agent {
	onStart() {
		// Option 1: Simple redirects
		this.mcp.configureOAuthCallback({
			successRedirect: "/dashboard",
			errorRedirect: "/auth-error",
		});

		// Option 2: Custom handler (e.g., for popup windows)
		this.mcp.configureOAuthCallback({
			customHandler: () => {
				return new Response("<script>window.close();</script>", {
					headers: { "content-type": "text/html" },
				});
			},
		});
	}
}
export class MyAgent extends Agent {
    onStart() {
        // Option 1: Simple redirects
        this.mcp.configureOAuthCallback({
            successRedirect: "/dashboard",
            errorRedirect: "/auth-error",
        });

        // Option 2: Custom handler (e.g., for popup windows)
        this.mcp.configureOAuthCallback({
            customHandler: () => {
                return new Response("<script>window.close();</script>", {
                    headers: { "content-type": "text/html" },
                });
            },
        });
    }
}

configureElicitationHandlers()

为无状态 elicitation 和旧版 elicitation/create 请求配置处理程序。为 Agent 支持的每种 elicitation 模式添加处理程序。

this.mcp.configureElicitationHandlers(handlers?: {
  form?: (
    request: ElicitRequest,
    serverId: string,
    signal?: AbortSignal,
  ) => Promise<ElicitResult>;
  url?: (
    request: ElicitRequest,
    serverId: string,
    signal?: AbortSignal,
  ) => Promise<ElicitResult>;
}): void

参数

  • handlers(对象,可选)— 按模式分类的 elicitation 处理程序:
    • form(函数,可选)— 处理用于结构化、非敏感输入的表单模式请求。
    • url(函数,可选)— 处理带外交互的 URL 模式请求。
  • request(ElicitRequest)— MCP elicitation 请求。检查 request.params.mode 中特定模式的字段。
  • serverId(字符串)— 发送请求的 MCP 服务器连接 ID。
  • signal(AbortSignal,可选)— 发起的 MCP 操作取消时会触发中止。

每个处理程序都会返回包含 ElicitResult 的 Promise。返回 accept、decline 或 cancel。接受的表单响应包含与 requestedSchema 匹配的 content。URL 响应不包含 content。

传入 undefined 会清除所有已配置的处理程序。

功能协商行为

客户端在旧版协商和无状态请求中,只会公布已配置处理程序的模式。处理程序更改会立即应用于现有连接,但服务器会在这些连接重新连接后收到更新后的已公布模式。

SDK 会在每个 MCP 服务器注册信息中存储由处理程序决定的模式。Durable Object 休眠后恢复的连接会公布这些模式,并在运行 onStart() 时重新附加回调。

使用

在 onStart() 中配置处理程序:

import { Agent } from "agents";

export class MyAgent extends Agent {
	onStart() {
		this.mcp.configureElicitationHandlers({
			form: (request, serverId) =>
				this.forwardElicitationToBrowser(request, serverId),
			url: (request, serverId) =>
				this.forwardElicitationToBrowser(request, serverId),
		});
	}

	forwardElicitationToBrowser(request, serverId) {
		// Forward the request to your UI and resolve after the user responds.
		throw new Error(
			`Implement elicitation for ${serverId}: ${request.params.message}`,
		);
	}
}
import { Agent } from "agents";
import type { ElicitRequest, ElicitResult } from "agents/mcp/client";

export class MyAgent extends Agent<Env> {
    onStart() {
        this.mcp.configureElicitationHandlers({
            form: (request, serverId) =>
                this.forwardElicitationToBrowser(request, serverId),
            url: (request, serverId) =>
                this.forwardElicitationToBrowser(request, serverId),
        });
    }

    private forwardElicitationToBrowser(
        request: ElicitRequest,
        serverId: string,
    ): Promise<ElicitResult> {
        // Forward the request to your UI and resolve after the user responds.
        throw new Error(
            `Implement elicitation for ${serverId}: ${request.params.message}`,
        );
    }
}

完整的浏览器转发模式和特定模式要求请参阅 Elicitation。

自定义 OAuth 提供程序

在 Agent 类中实现 createMcpOAuthProvider(),即可覆盖连接 MCP 服务器时使用的默认 OAuth 提供程序。这样便可使用预先注册的客户端凭据或 mTLS 等自定义身份验证策略,而不仅限于内置的动态客户端注册。

此覆盖实现既用于新连接(addMcpServer),也用于 Durable Object 重启后恢复的连接。

import { Agent } from "agents";

export class MyAgent extends Agent {
	createMcpOAuthProvider(callbackUrl) {
		const env = this.env;
		return {
			get redirectUrl() {
				return callbackUrl;
			},
			get clientMetadata() {
				return {
					client_id: env.MCP_CLIENT_ID,
					client_secret: env.MCP_CLIENT_SECRET,
					redirect_uris: [callbackUrl],
				};
			},
			clientInformation() {
				return {
					client_id: env.MCP_CLIENT_ID,
					client_secret: env.MCP_CLIENT_SECRET,
				};
			},
		};
	}
}
import { Agent } from "agents";
import type { AgentMcpOAuthProvider } from "agents";

export class MyAgent extends Agent<Env> {
    createMcpOAuthProvider(callbackUrl: string): AgentMcpOAuthProvider {
        const env = this.env;
        return {
            get redirectUrl() {
                return callbackUrl;
            },
            get clientMetadata() {
                return {
                    client_id: env.MCP_CLIENT_ID,
                    client_secret: env.MCP_CLIENT_SECRET,
                    redirect_uris: [callbackUrl],
                };
            },
            clientInformation() {
                return {
                    client_id: env.MCP_CLIENT_ID,
                    client_secret: env.MCP_CLIENT_SECRET,
                };
            },
        };
    }
}

如果不覆盖此方法,Agent 会使用默认提供程序,通过 MCP 服务器执行 OAuth 2.0 动态客户端注册 ↗。

自定义存储后端

若要保留内置 OAuth 逻辑(CSRF 状态、PKCE、nonce 生成和令牌管理),同时将令牌存储路由到其他后端,请导入 DurableObjectOAuthClientProvider 并传入自己的存储适配器:

import { Agent, DurableObjectOAuthClientProvider } from "agents";

export class MyAgent extends Agent {
	createMcpOAuthProvider(callbackUrl) {
		return new DurableObjectOAuthClientProvider(
			myCustomStorage, // any DurableObjectStorage-compatible adapter
			this.name,
			callbackUrl,
		);
	}
}
import { Agent, DurableObjectOAuthClientProvider } from "agents";
import type { AgentMcpOAuthProvider } from "agents";

export class MyAgent extends Agent {
    createMcpOAuthProvider(callbackUrl: string): AgentMcpOAuthProvider {
        return new DurableObjectOAuthClientProvider(
            myCustomStorage, // any DurableObjectStorage-compatible adapter
            this.name,
            callbackUrl,
        );
    }
}

高级用法:MCPClientManager

如需更精细的控制,请直接使用 this.mcp:

分步建立连接

// 1. Register the server (saves to storage and creates in-memory connection)
const id = "my-server";
await this.mcp.registerServer(id, {
	url: "https://mcp.example.com/mcp",
	name: "My Server",
	callbackUrl: "https://my-worker.workers.dev/agents/my-agent/default/callback",
	transport: { type: "auto" },
});

// 2. Connect (initializes transport, handles OAuth if needed)
const connectResult = await this.mcp.connectToServer(id);

if (connectResult.state === "failed") {
	console.error("Connection failed:", connectResult.error);
	return;
}

if (connectResult.state === "authenticating") {
	console.log("OAuth required:", connectResult.authUrl);
	return;
}

// 3. Discover capabilities (transitions from "connected" to "ready")
if (connectResult.state === "connected") {
	const discoverResult = await this.mcp.discoverIfConnected(id);

	if (!discoverResult?.success) {
		console.error("Discovery failed:", discoverResult?.error);
	}
}
// 1. Register the server (saves to storage and creates in-memory connection)
const id = "my-server";
await this.mcp.registerServer(id, {
    url: "https://mcp.example.com/mcp",
    name: "My Server",
    callbackUrl: "https://my-worker.workers.dev/agents/my-agent/default/callback",
    transport: { type: "auto" },
});

// 2. Connect (initializes transport, handles OAuth if needed)
const connectResult = await this.mcp.connectToServer(id);

if (connectResult.state === "failed") {
    console.error("Connection failed:", connectResult.error);
    return;
}

if (connectResult.state === "authenticating") {
    console.log("OAuth required:", connectResult.authUrl);
    return;
}

// 3. Discover capabilities (transitions from "connected" to "ready")
if (connectResult.state === "connected") {
    const discoverResult = await this.mcp.discoverIfConnected(id);

    if (!discoverResult?.success) {
        console.error("Discovery failed:", discoverResult?.error);
    }
}

订阅事件

// Listen for state changes (onServerStateChanged is an Event<void>)
const disposable = this.mcp.onServerStateChanged(() => {
	console.log("MCP server state changed");
	this.broadcastMcpServers(); // Notify connected clients
});

// Clean up the subscription when no longer needed
// disposable.dispose();
// Listen for state changes (onServerStateChanged is an Event<void>)
const disposable = this.mcp.onServerStateChanged(() => {
    console.log("MCP server state changed");
    this.broadcastMcpServers(); // Notify connected clients
});

// Clean up the subscription when no longer needed
// disposable.dispose();

生命周期方法

this.mcp.registerServer()

注册服务器,但不立即连接。

async registerServer(
  id: string,
  options: {
    url: string;
    name: string;
    callbackUrl: string;
    clientOptions?: ClientOptions;
    transportOptions?: TransportOptions;
  }
): Promise<string>

this.mcp.connectToServer()

连接到之前注册的服务器。

async connectToServer(id: string): Promise<MCPConnectionResult>

type MCPConnectionResult =
  | { state: "failed"; error: string }
  | { state: "authenticating"; authUrl: string }
  | { state: "connected" }

this.mcp.discoverIfConnected()

连接处于活动状态时,检查服务器功能。

async discoverIfConnected(
  serverId: string,
  options?: { timeoutMs?: number }
): Promise<MCPDiscoverResult | undefined>

type MCPDiscoverResult = {
  success: boolean;
  state: MCPConnectionState;
  error?: string;
}

this.mcp.waitForConnections()

等待所有进行中的 MCP 连接和发现操作完成。当 Agent 从休眠状态唤醒后,你需要 this.mcp.getAITools() 立即返回完整工具集时,这会很有用。

// Wait indefinitely
await this.mcp.waitForConnections();

// Wait with a timeout (milliseconds)
await this.mcp.waitForConnections({ timeout: 10_000 });

this.mcp.closeConnection()

关闭与特定服务器的连接,同时保留其注册信息。

async closeConnection(id: string): Promise<void>

this.mcp.closeAllConnections()

关闭所有活动服务器连接,同时保留注册信息。

async closeAllConnections(): Promise<void>

this.mcp.listTools()

获取原始 MCP 工具记录,不将其架构转换为 Zod。

listTools(filter?: MCPServerFilter): Array<Tool & { serverId: string }>

使用此方法发现和检查目录。传入 MCPServerFilter,将返回的工具限制为特定连接。

this.mcp.getAITools()

以兼容 AI SDK 的格式获取所有已发现的 MCP 工具。

getAITools(filter?: MCPServerFilter): ToolSet

工具会自动按服务器 ID 添加命名空间,以防多个 MCP 服务器公开同名工具时发生冲突。

getAITools() 会在每个活动连接上重复使用当前目录的转换后架构。当发现结果替换目录或活动连接更改后,它会重新转换架构。每次调用都会返回新的工具记录和 execute 函数。如果只需要原始目录,请使用 this.mcp.listTools()。

传入 MCPServerFilter,将返回的工具限定为已连接服务器的子集:

// Tools from a specific server only
const githubTools = this.mcp.getAITools({ serverId: "github" });

// Tools from multiple servers
const tools = this.mcp.getAITools({ serverId: ["github", "notion"] });

// Tools from servers matching a name
const tools = this.mcp.getAITools({ serverName: "GitHub" });

// Only tools from servers that are ready
const tools = this.mcp.getAITools({ state: "ready" });
// Tools from a specific server only
const githubTools = this.mcp.getAITools({ serverId: "github" });

// Tools from multiple servers
const tools = this.mcp.getAITools({ serverId: ["github", "notion"] });

// Tools from servers matching a name
const tools = this.mcp.getAITools({ serverName: "GitHub" });

// Only tools from servers that are ready
const tools = this.mcp.getAITools({ state: "ready" });

可从 agents/mcp/client 导入过滤器类型:

import type { MCPServerFilter } from "agents/mcp/client";

type MCPServerFilter = {
    serverId?: string | string[];
    serverName?: string | string[];
    state?: MCPConnectionState | MCPConnectionState[];
};

所有指定的过滤条件都必须同时满足。listTools()、listPrompts()、listResources() 和 listResourceTemplates() 也接受相同的过滤器参数。

错误处理

使用错误检测工具处理连接错误:

import { isUnauthorized, isTransportNotImplemented } from "agents";

export class MyAgent extends Agent {
	async onRequest(request) {
		try {
			await this.addMcpServer("Server", "https://mcp.example.com/mcp");
		} catch (error) {
			if (isUnauthorized(error)) {
				return new Response("Authentication required", { status: 401 });
			} else if (isTransportNotImplemented(error)) {
				return new Response("Transport not supported", { status: 400 });
			}
			throw error;
		}
	}
}
import { isUnauthorized, isTransportNotImplemented } from "agents";

export class MyAgent extends Agent {
    async onRequest(request: Request) {
        try {
            await this.addMcpServer("Server", "https://mcp.example.com/mcp");
        } catch (error) {
            if (isUnauthorized(error)) {
                return new Response("Authentication required", { status: 401 });
            } else if (isTransportNotImplemented(error)) {
                return new Response("Transport not supported", { status: 400 });
            }
            throw error;
        }
    }
}

后续步骤

这篇文档对您有帮助吗?