MCP 工具是 MCP 服务器公开供客户端调用的函数。LLM 可以调用工具查询数据、进行计算或调用 API。MCP 服务器执行工具并返回结果。
在来自 @modelcontextprotocol/server 的 McpServer 上定义工具,并使用 createMcpHandler 提供服务。
WebMCP 示例
在无状态的 McpServer 实例上使用 server.registerTool() 注册工具。每个工具都有名称、描述、由 Zod ↗ 或 Valibot ↗ 等架构库定义的输入架构,以及处理函数。
import { McpServer } from "@modelcontextprotocol/server";
import { createMcpHandler } from "agents/mcp/server";
import { z } from "zod";
function createServer() {
const server = new McpServer({ name: "Math", version: "1.0.0" });
server.registerTool(
"add",
{
description: "Add two numbers together",
inputSchema: { a: z.number(), b: z.number() },
outputSchema: { sum: z.number() },
},
async ({ a, b }) => {
const result = { sum: a + b };
return {
structuredContent: result,
content: [{ type: "text", text: JSON.stringify(result) }],
};
},
);
return server;
}
const handler = createMcpHandler(createServer);
export default {
fetch(request, env, ctx) {
return handler(request, env, ctx);
},
};import { McpServer } from "@modelcontextprotocol/server";
import { createMcpHandler } from "agents/mcp/server";
import { z } from "zod";
function createServer() {
const server = new McpServer({ name: "Math", version: "1.0.0" });
server.registerTool(
"add",
{
description: "Add two numbers together",
inputSchema: { a: z.number(), b: z.number() },
outputSchema: { sum: z.number() },
},
async ({ a, b }) => {
const result = { sum: a + b };
return {
structuredContent: result,
content: [{ type: "text", text: JSON.stringify(result) }],
};
},
);
return server;
}
const handler = createMcpHandler(createServer);
export default {
fetch(request, env, ctx) {
return handler(request, env, ctx);
},
} satisfies ExportedHandler<Env>;Tool handler 接收已验证输入,必须返回带 content 数组的对象。每个 content 项有 type(通常为 "text")及对应数据。
Tool 结果以 content part 数组返回。最常见类型为 text,也可返回 image 与 embedded resource。
import { McpServer } from "@modelcontextprotocol/server";
import { createMcpHandler } from "agents/mcp/server";
import { env } from "cloudflare:workers";
import { z } from "zod";
function createServer() {
const server = new McpServer({ name: "Users", version: "1.0.0" });
server.registerTool(
"lookup",
{
description: "Look up a user by ID",
inputSchema: { userId: z.string() },
},
async ({ userId }) => {
const user = await env.USERS.get(userId, "json");
if (!user) {
return {
isError: true,
content: [{ type: "text", text: `User ${userId} not found` }],
};
}
return {
content: [{ type: "text", text: JSON.stringify(user, null, 2) }],
};
},
);
return server;
}
const handler = createMcpHandler(createServer);
export default {
fetch(request, env, ctx) {
return handler(request, env, ctx);
},
};import { McpServer } from "@modelcontextprotocol/server";
import { createMcpHandler } from "agents/mcp/server";
import { env } from "cloudflare:workers";
import { z } from "zod";
function createServer() {
const server = new McpServer({ name: "Users", version: "1.0.0" });
server.registerTool(
"lookup",
{
description: "Look up a user by ID",
inputSchema: { userId: z.string() },
},
async ({ userId }) => {
const user = await env.USERS.get(userId, "json");
if (!user) {
return {
isError: true,
content: [{ type: "text", text: `User ${userId} not found` }],
};
}
return {
content: [{ type: "text", text: JSON.stringify(user, null, 2) }],
};
},
);
return server;
}
const handler = createMcpHandler(createServer);
export default {
fetch(request, env, ctx) {
return handler(request, env, ctx);
},
} satisfies ExportedHandler<Env>;设置 isError: true 表示 tool 调用失败。LLM 收到 error 消息并决定如何继续。
description 参数至关重要 — LLM 读取它来决定是否及何时调用 tool。描述应:
- 具体 说明 tool 做什么:「获取城市当前天气」优于「天气 tool」
- 清楚说明输入:「需要城市名字符串」帮助 LLM 正确格式化调用
- 诚实说明限制:「仅支持美国城市」防止 LLM 用不支持的输入调用
Tool 输入定义为 Zod schema,handler 运行前自动验证。用 Zod 的 .describe() 为 LLM 提供每个参数的上下文。
import { McpServer } from "@modelcontextprotocol/server";
import { createMcpHandler } from "agents/mcp/server";
import { z } from "zod";
const DOCUMENTS = [
{ title: "Getting started", category: "docs" },
{ title: "Release notes", category: "blog" },
{ title: "REST reference", category: "api" },
];
function createServer() {
const server = new McpServer({ name: "Search", version: "1.0.0" });
server.registerTool(
"search",
{
description: "Search for documents by title",
inputSchema: {
query: z.string().describe("Text to look for in document titles"),
limit: z
.number()
.min(1)
.max(100)
.default(10)
.describe("Maximum number of results to return"),
category: z
.enum(["docs", "blog", "api"])
.optional()
.describe("Only return documents in this category"),
},
},
async ({ query, limit, category }) => {
const results = DOCUMENTS.filter(
(doc) =>
doc.title.toLowerCase().includes(query.toLowerCase()) &&
(!category || doc.category === category),
).slice(0, limit);
return {
content: [{ type: "text", text: JSON.stringify(results) }],
};
},
);
return server;
}
const handler = createMcpHandler(createServer);
export default {
fetch(request, env, ctx) {
return handler(request, env, ctx);
},
};import { McpServer } from "@modelcontextprotocol/server";
import { createMcpHandler } from "agents/mcp/server";
import { z } from "zod";
const DOCUMENTS = [
{ title: "Getting started", category: "docs" },
{ title: "Release notes", category: "blog" },
{ title: "REST reference", category: "api" },
];
function createServer() {
const server = new McpServer({ name: "Search", version: "1.0.0" });
server.registerTool(
"search",
{
description: "Search for documents by title",
inputSchema: {
query: z.string().describe("Text to look for in document titles"),
limit: z
.number()
.min(1)
.max(100)
.default(10)
.describe("Maximum number of results to return"),
category: z
.enum(["docs", "blog", "api"])
.optional()
.describe("Only return documents in this category"),
},
},
async ({ query, limit, category }) => {
const results = DOCUMENTS.filter(
(doc) =>
doc.title.toLowerCase().includes(query.toLowerCase()) &&
(!category || doc.category === category),
).slice(0, limit);
return {
content: [{ type: "text", text: JSON.stringify(results) }],
};
},
);
return server;
}
const handler = createMcpHandler(createServer);
export default {
fetch(request, env, ctx) {
return handler(request, env, ctx);
},
} satisfies ExportedHandler<Env>;对无状态 MCP 服务器,在 factory 函数内定义 tool 并将 server 传给 createMcpHandler:
import { McpServer } from "@modelcontextprotocol/server";
import { createMcpHandler } from "agents/mcp/server";
function createServer() {
const server = new McpServer({ name: "My Tools", version: "1.0.0" });
server.registerTool(
"ping",
{ description: "Check if the server is alive" },
async () => ({
content: [{ type: "text", text: "pong" }],
}),
);
return server;
}
const handler = createMcpHandler(createServer);
export default {
fetch(request, env, ctx) {
return handler(request, env, ctx);
},
};import { McpServer } from "@modelcontextprotocol/server";
import { createMcpHandler } from "agents/mcp/server";
function createServer() {
const server = new McpServer({ name: "My Tools", version: "1.0.0" });
server.registerTool(
"ping",
{ description: "Check if the server is alive" },
async () => ({
content: [{ type: "text", text: "pong" }],
}),
);
return server;
}
const handler = createMcpHandler(createServer);
export default {
fetch(request, env, ctx) {
return handler(request, env, ctx);
},
} satisfies ExportedHandler<Env>;createMcpHandler 会为每个请求创建一个新服务器,因此工具无法在多次调用之间将数据保存在内存中。请改为使用 cloudflare:workers 中的 env 读取和写入绑定:
import { McpServer } from "@modelcontextprotocol/server";
import { createMcpHandler, getMcpAuthContext } from "agents/mcp/server";
import { env } from "cloudflare:workers";
function createServer() {
const server = new McpServer({ name: "Counter", version: "1.0.0" });
server.registerTool(
"incrementCounter",
{ description: "Increment and return your counter" },
async () => {
// props are set by OAuthProvider. Without it, every caller shares "anonymous".
const userId = String(getMcpAuthContext()?.props.userId ?? "anonymous");
const count = Number((await env.COUNTERS.get(userId)) ?? 0) + 1;
await env.COUNTERS.put(userId, String(count));
return {
content: [{ type: "text", text: `Counter: ${count}` }],
};
},
);
return server;
}
const handler = createMcpHandler(createServer);
export default {
fetch(request, env, ctx) {
return handler(request, env, ctx);
},
};import { McpServer } from "@modelcontextprotocol/server";
import { createMcpHandler, getMcpAuthContext } from "agents/mcp/server";
import { env } from "cloudflare:workers";
function createServer() {
const server = new McpServer({ name: "Counter", version: "1.0.0" });
server.registerTool(
"incrementCounter",
{ description: "Increment and return your counter" },
async () => {
// props are set by OAuthProvider. Without it, every caller shares "anonymous".
const userId = String(getMcpAuthContext()?.props.userId ?? "anonymous");
const count = Number((await env.COUNTERS.get(userId)) ?? 0) + 1;
await env.COUNTERS.put(userId, String(count));
return {
content: [{ type: "text", text: `Counter: ${count}` }],
};
},
);
return server;
}
const handler = createMcpHandler(createServer);
export default {
fetch(request, env, ctx) {
return handler(request, env, ctx);
},
} satisfies ExportedHandler<Env>;要添加 OAuthProvider 和每位用户的 props,请参阅授权。对于需要事务或按用户处理逻辑的数据,请从工具中调用 Durable Object 或 Agent。