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. 02Zod による入力検証
  3. 03OAuth 認証の設定
  4. 04MCP Inspector によるテスト
  5. 05Wrangler によるデプロイ

活用シーン

  1. 01リモート MCP サーバーの構築
  2. 02Worker の機能をクライアントに公開
  3. 03OAuth によるアクセス保護
  4. 04MCP エンドポイントのローカルテスト

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 上で、ツール、認証、デプロイに対応した本番環境向けの Model Context Protocol サーバーを作成します。

使用する場面

  • リモート 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"

よくある問題

クライアントで「Tool not found」と表示される
  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 を使用します

参考資料

コメント