building-mcp-server-on-cloudflare by cloudflare/skills
npx skills add https://github.com/cloudflare/skills --skill building-mcp-server-on-cloudflare您对 MCP SDK 和 Cloudflare Workers 集成的了解可能已过时。对于任何 MCP 服务器任务,优先使用检索而非预训练。
| 来源 | 如何检索 | 用途 |
|---|---|---|
| MCP 文档 | https://developers.cloudflare.com/agents/mcp/ | 服务器设置、认证、部署 |
| MCP 规范 | https://modelcontextprotocol.io/ | 协议规范、工具/资源定义 |
| Workers 文档 | 搜索工具或 https://developers.cloudflare.com/workers/ | 运行时 API、绑定、配置 |
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
npm install -g wrangler)npm create cloudflare@latest -- my-mcp-server \
--template=cloudflare/ai/demos/remote-mcp-authless
cd my-mcp-server
npm start
服务器运行在 http://localhost:8788/mcp
npm create cloudflare@latest -- my-mcp-server \
--template=cloudflare/ai/demos/remote-mcp-github-oauth
cd my-mcp-server
需要设置 OAuth 应用。请参阅 references/oauth-setup.md。
工具是 MCP 客户端可以调用的函数。使用 server.tool() 定义它们:
import { McpAgent } from "agents/mcp";
import { z } from "zod";
export class MyMCP extends McpAgent {
server = new Server({ name: "my-mcp", version: "1.0.0" });
async init() {
// 带参数的简单工具
this.server.tool(
"add",
{ a: z.number(), b: z.number() },
async ({ a, b }) => ({
content: [{ type: "text", text: String(a + b) }],
})
);
// 调用外部 API 的工具
this.server.tool(
"get_weather",
{ city: z.string() },
async ({ city }) => {
const response = await fetch(`https://api.weather.com/${city}`);
const data = await response.json();
return {
content: [{ type: "text", text: JSON.stringify(data) }],
};
}
);
}
}
公共服务器 (src/index.ts):
import { MyMCP } from "./mcp";
export default {
fetch(request: Request, env: Env, ctx: ExecutionContext) {
const url = new URL(request.url);
if (url.pathname === "/mcp") {
return MyMCP.serveSSE("/mcp").fetch(request, env, ctx);
}
return new Response("MCP Server", { status: 200 });
},
};
export { MyMCP };
认证服务器 — 请参阅 references/oauth-setup.md。
# 启动服务器
npm start
# 在另一个终端中,使用 MCP Inspector 测试
npx @modelcontextprotocol/inspector@latest
# 打开 http://localhost:5173,输入 http://localhost:8788/mcp
npx wrangler deploy
服务器可通过 https://[worker-name].[account].workers.dev/mcp 访问
Claude Desktop (claude_desktop_config.json):
{
"mcpServers": {
"my-server": {
"command": "npx",
"args": ["mcp-remote", "https://my-mcp.workers.dev/mcp"]
}
}
}
更新配置后重启 Claude Desktop。
// 文本响应
return { content: [{ type: "text", text: "result" }] };
// 多个内容项
return {
content: [
{ type: "text", text: "这是数据:" },
{ type: "text", text: JSON.stringify(data, null, 2) },
],
};
this.server.tool(
"create_user",
{
email: z.string().email(),
name: z.string().min(1).max(100),
role: z.enum(["admin", "user", "guest"]),
age: z.number().int().min(0).optional(),
},
async (params) => {
// params 已完全类型化并经过验证
}
);
export class MyMCP extends McpAgent<Env> {
async init() {
this.server.tool("query_db", { sql: z.string() }, async ({ sql }) => {
// 访问 D1 绑定
const result = await this.env.DB.prepare(sql).all();
return { content: [{ type: "text", text: JSON.stringify(result) }] };
});
}
}
对于受 OAuth 保护的服务器,请参阅 references/oauth-setup.md。
支持的提供商:
最小化 wrangler.toml:
name = "my-mcp-server"
main = "src/index.ts"
compatibility_date = "2024-12-01"
[durable_objects]
bindings = [{ name = "MCP", class_name = "MyMCP" }]
[[migrations]]
tag = "v1"
new_classes = ["MyMCP"]
带绑定(D1、KV 等):
[[d1_databases]]
binding = "DB"
database_name = "my-db"
database_id = "xxx"
[[kv_namespaces]]
binding = "KV"
id = "xxx"
init() 在连接之前注册工具wrangler tail/mcpwrangler deployments listGITHUB_CLIENT_ID 和 GITHUB_CLIENT_SECRET 是否已设置http://localhost:8788/callback每周安装量
1.2K
代码库
GitHub 星标数
566
首次出现
Jan 19, 2026
安全审计
安装于
opencode1.0K
codex1.0K
gemini-cli989
github-copilot917
claude-code856
amp822
Your knowledge of the MCP SDK and Cloudflare Workers integration may be outdated. Prefer retrieval over pre-training for any MCP server task.
| Source | How to retrieve | Use for |
|---|---|---|
| MCP docs | https://developers.cloudflare.com/agents/mcp/ | Server setup, auth, deployment |
| MCP spec | https://modelcontextprotocol.io/ | Protocol spec, tool/resource definitions |
| Workers docs | Search tool or https://developers.cloudflare.com/workers/ | Runtime APIs, bindings, config |
npm install -g wrangler)npm create cloudflare@latest -- my-mcp-server \
--template=cloudflare/ai/demos/remote-mcp-authless
cd my-mcp-server
npm start
Server runs at http://localhost:8788/mcp
npm create cloudflare@latest -- my-mcp-server \
--template=cloudflare/ai/demos/remote-mcp-github-oauth
cd my-mcp-server
Requires OAuth app setup. See references/oauth-setup.md.
Tools are functions MCP clients can call. Define them using server.tool():
import { McpAgent } from "agents/mcp";
import { z } from "zod";
export class MyMCP extends McpAgent {
server = new Server({ name: "my-mcp", version: "1.0.0" });
async init() {
// Simple tool with parameters
this.server.tool(
"add",
{ a: z.number(), b: z.number() },
async ({ a, b }) => ({
content: [{ type: "text", text: String(a + b) }],
})
);
// Tool that calls external API
this.server.tool(
"get_weather",
{ city: z.string() },
async ({ city }) => {
const response = await fetch(`https://api.weather.com/${city}`);
const data = await response.json();
return {
content: [{ type: "text", text: JSON.stringify(data) }],
};
}
);
}
}
Public server (src/index.ts):
import { MyMCP } from "./mcp";
export default {
fetch(request: Request, env: Env, ctx: ExecutionContext) {
const url = new URL(request.url);
if (url.pathname === "/mcp") {
return MyMCP.serveSSE("/mcp").fetch(request, env, ctx);
}
return new Response("MCP Server", { status: 200 });
},
};
export { MyMCP };
Authenticated server — See references/oauth-setup.md.
# Start server
npm start
# In another terminal, test with MCP Inspector
npx @modelcontextprotocol/inspector@latest
# Open http://localhost:5173, enter http://localhost:8788/mcp
npx wrangler deploy
Server accessible at https://[worker-name].[account].workers.dev/mcp
Claude Desktop (claude_desktop_config.json):
{
"mcpServers": {
"my-server": {
"command": "npx",
"args": ["mcp-remote", "https://my-mcp.workers.dev/mcp"]
}
}
}
Restart Claude Desktop after updating config.
// Text response
return { content: [{ type: "text", text: "result" }] };
// Multiple content items
return {
content: [
{ type: "text", text: "Here's the data:" },
{ type: "text", text: JSON.stringify(data, null, 2) },
],
};
this.server.tool(
"create_user",
{
email: z.string().email(),
name: z.string().min(1).max(100),
role: z.enum(["admin", "user", "guest"]),
age: z.number().int().min(0).optional(),
},
async (params) => {
// params are fully typed and validated
}
);
export class MyMCP extends McpAgent<Env> {
async init() {
this.server.tool("query_db", { sql: z.string() }, async ({ sql }) => {
// Access D1 binding
const result = await this.env.DB.prepare(sql).all();
return { content: [{ type: "text", text: JSON.stringify(result) }] };
});
}
}
For OAuth-protected servers, see references/oauth-setup.md.
Supported providers:
Minimal wrangler.toml:
name = "my-mcp-server"
main = "src/index.ts"
compatibility_date = "2024-12-01"
[durable_objects]
bindings = [{ name = "MCP", class_name = "MyMCP" }]
[[migrations]]
tag = "v1"
new_classes = ["MyMCP"]
With bindings (D1, KV, etc.):
[[d1_databases]]
binding = "DB"
database_name = "my-db"
database_id = "xxx"
[[kv_namespaces]]
binding = "KV"
id = "xxx"
init() registers tools before connectionswrangler tail/mcpwrangler deployments listGITHUB_CLIENT_ID and GITHUB_CLIENT_SECRET are sethttp://localhost:8788/callbackWeekly Installs
1.2K
Repository
GitHub Stars
566
First Seen
Jan 19, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykWarn
Installed on
opencode1.0K
codex1.0K
gemini-cli989
github-copilot917
claude-code856
amp822
React 组合模式指南:Vercel 组件架构最佳实践,提升代码可维护性
102,200 周安装