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 サーバーを構築する開発スキルです。セットアップ、認証、テスト、デプロイを行う開発者向けに、最新ドキュメントを参照しながらツール定義からデプロイまでを案内します。

主な機能

  1. 01MCP と Workers の資料を参照
  2. 02公開型または OAuth 認証付きサーバーの作成
  3. 03ツール定義と入力検証
  4. 04ローカルテストと Workers へのデプロイ
  5. 05バインディング設定と問題の調査

活用シーン

  1. 01Workers 上でリモート MCP サーバーを構築
  2. 02MCP ツールに OAuth 認証を追加
  3. 03MCP サーバーをテストしてデプロイ
  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"

よくある問題

クライアントで「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 を使用します

参考資料

コメント