mcpField
B
building-mcp-server-on-cloudflare

building-mcp-server-on-cloudflare

github.com/cloudflare开发3.2k3.4k 次安装今天更新
代码仓库

关于 building-mcp-server-on-cloudflare

为 Cloudflare Workers 编写远程 MCP 服务的开发技能,面向需要构建、认证、测试和部署 MCP 服务的开发者。内容强调先查阅最新文档,并提供从定义工具到部署的流程。

主要功能

  1. 01查阅 MCP、Workers 文档与规范
  2. 02创建公开或 OAuth 认证服务
  3. 03定义工具并验证输入
  4. 04本地测试与部署至 Workers
  5. 05配置绑定并排查常见问题

适用场景

  1. 01在 Workers 上搭建远程 MCP 服务
  2. 02为 MCP 工具添加 OAuth 认证
  3. 03本地测试并部署 MCP 服务
  4. 04排查工具注册或连接故障

MCP 相关

指导开发者构建可供 MCP 客户端调用的服务,涵盖工具定义、服务端点、认证、测试和部署。

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/cloudflare/skills --skill building-mcp-server-on-cloudflare

安装后在 Claude Code 中输入/building-mcp-server-on-cloudflare确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

references/
examples.md
oauth-setup.md
troubleshooting.md

详细介绍

在 Cloudflare 上构建 MCP 服务

你对 MCP SDK 和 Cloudflare Workers 集成的了解可能已经过时。对于任何 MCP 服务任务,优先检索,而非依赖预训练知识。

检索来源

来源检索方式适用内容
MCP 文档https://developers.cloudflare.com/agents/mcp/服务设置、身份验证、部署
MCP 规范https://modelcontextprotocol.io/协议规范、工具/资源定义
Workers 文档搜索工具或 https://developers.cloudflare.com/workers/运行时 API、绑定、配置

适用场景

  • 用户想要构建远程 MCP 服务
  • 用户需要通过 MCP 提供工具
  • 用户询问 MCP 身份验证或 OAuth
  • 用户想要将 MCP 部署到 Cloudflare Workers

前提条件

  • 已启用 Workers 的 Cloudflare 账户
  • Node.js 18+ 和 npm/pnpm/yarn
  • Wrangler CLI(npm install -g wrangler)

快速入门

选项 1:公开服务(无需身份验证)
npm create cloudflare@latest -- my-mcp-server \
  --template=cloudflare/ai/demos/remote-mcp-authless
cd my-mcp-server
npm start

服务运行在 http://localhost:8788/mcp

选项 2:经过身份验证的服务(OAuth)
npm create cloudflare@latest -- my-mcp-server \
  --template=cloudflare/ai/demos/remote-mcp-github-oauth
cd my-mcp-server

需要设置 OAuth 应用。参见 references/oauth-setup.md。

核心工作流

步骤 1:定义工具

工具是 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() {
    // 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) }],
        };
      }
    );
  }
}
步骤 2:配置入口点

公开服务(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。

步骤 3:在本地测试
# Start server
npm start

# In another terminal, test with MCP Inspector
npx @modelcontextprotocol/inspector@latest
# Open http://localhost:5173, enter http://localhost:8788/mcp
步骤 4:部署
npx wrangler deploy

服务可通过 https://[worker-name].[account].workers.dev/mcp 访问

步骤 5:连接客户端

Claude Desktop(claude_desktop_config.json):

{
  "mcpServers": {
    "my-server": {
      "command": "npx",
      "args": ["mcp-remote", "https://my-mcp.workers.dev/mcp"]
    }
  }
}

更新配置后重启 Claude Desktop。

工具模式

返回类型
// 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) },
  ],
};
使用 Zod 验证输入
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) }] };
    });
  }
}

身份验证

关于受 OAuth 保护的服务,请参见 references/oauth-setup.md。

支持的提供商:

  • GitHub
  • Google
  • Auth0
  • Stytch
  • WorkOS
  • 任何符合 OAuth 2.0 标准的提供商

Wrangler 配置

最简 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"

常见问题

客户端中显示“未找到工具”
  1. 确认工具名称完全匹配(区分大小写)
  2. 确保 init() 在建立连接前注册工具
  3. 查看服务日志:wrangler tail
连接失败
  1. 确认端点路径为 /mcp
  2. 如果使用基于浏览器的客户端,请检查 CORS
  3. 确认 Worker 已部署:wrangler deployments list
OAuth 重定向错误
  1. 回调 URL 必须与 OAuth 应用配置完全一致
  2. 检查是否已设置 GITHUB_CLIENT_ID 和 GITHUB_CLIENT_SECRET
  3. 本地开发时,使用 http://localhost:8788/callback

参考资料

评论

支持 Markdown