building-mcp-server-on-cloudflare について
Cloudflare Workers でリモート MCP サーバーを構築する開発スキルです。セットアップ、認証、テスト、デプロイを行う開発者向けに、最新ドキュメントを参照しながらツール定義からデプロイまでを案内します。
主な機能
- 01MCP と Workers の資料を参照
- 02公開型または OAuth 認証付きサーバーの作成
- 03ツール定義と入力検証
- 04ローカルテストと Workers へのデプロイ
- 05バインディング設定と問題の調査
活用シーン
- 01Workers 上でリモート MCP サーバーを構築
- 02MCP ツールに OAuth 認証を追加
- 03MCP サーバーをテストしてデプロイ
- 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.mdoauth-setup.mdtroubleshooting.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
- 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」と表示される
- ツール名が完全に一致していることを確認します(大文字と小文字は区別されます)
- 接続前に
init()でツールが登録されていることを確認します - サーバーログを確認します:
wrangler tail
接続に失敗する
- エンドポイントのパスが
/mcpであることを確認します - ブラウザベースのクライアントの場合は CORS を確認します
- Worker がデプロイされていることを確認します:
wrangler deployments list
OAuth リダイレクトエラー
- コールバック URL が OAuth アプリの設定と完全に一致している必要があります
GITHUB_CLIENT_IDとGITHUB_CLIENT_SECRETが設定されていることを確認します- ローカル開発では
http://localhost:8788/callbackを使用します
参考資料
- references/examples.md — 公式テンプレートと本番環境の例
- references/oauth-setup.md — OAuth プロバイダーの設定
- references/tool-patterns.md — ツールの応用例
- references/troubleshooting.md — エラーコードと解決方法