mcpField
B
building-mcp-server-on-cloudflare

building-mcp-server-on-cloudflare

github.com/cloudflare开发5.4k44 次安装今天更新
代码仓库

关于 building-mcp-server-on-cloudflare

在 Cloudflare Workers 上创建 MCP 服务的技能,面向要向 MCP 客户端开放功能的开发者。内容涵盖工具定义、可选 OAuth 身份验证、本地测试和部署。

主要功能

  1. 01定义可调用的 MCP 工具
  2. 02使用 Zod 验证输入
  3. 03配置 OAuth 身份验证
  4. 04通过 MCP Inspector 测试
  5. 05使用 Wrangler 部署

适用场景

  1. 01构建远程 MCP 服务
  2. 02向客户端开放 Worker 功能
  3. 03使用 OAuth 保护服务访问
  4. 04在本地测试 MCP 端点

MCP 相关

指导开发者实现向 MCP 客户端开放工具的 MCP 服务,涵盖公开访问和 OAuth 保护配置。

安装

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

$npx skills add https://github.com/cloudflare/cloudflare-docs --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 服务

在 Cloudflare Workers 上创建可用于生产环境的模型上下文协议服务,包含工具、身份验证和部署。

适用场景

  • 用户想要构建远程 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