building-mcp-server-on-cloudflare
Cloudflare Workers上にリモートMCP(Model Context Protocol)サーバーを構築します。ツール、OAuth認証、本番環境デプロイに対応しており、サーバーコードの生成、認証プロバイダーの設定、Workersへのデプロイを実行します。 以下の場合に使用できます:「MCPサーバーを構築したい」「MCPツールを作成したい」「リモートMCP」「MCPをデプロイしたい」「MCPにOAuthを追加したい」などのご要望、またはCloudflareでのModel Context Protocolについてのご相談。「MCP認証」や「MCPデプロイメント」に関するお問い合わせの場合も自動的に対応します。
description の原文を見る
Builds remote MCP (Model Context Protocol) servers on Cloudflare Workers with tools, OAuth authentication, and production deployment. Generates server code, configures auth providers, and deploys to Workers. Use when: user wants to "build MCP server", "create MCP tools", "remote MCP", "deploy MCP", add "OAuth to MCP", or mentions Model Context Protocol on Cloudflare. Also triggers on "MCP authentication" or "MCP deployment".
SKILL.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() {
// パラメータを持つシンプルなツール
this.server.tool(
"add",
{ a: z.number(), b: z.number() },
async ({ a, b }) => ({
content: [{ type: "text", text: String(a + b) }],
}),
);
// 外部 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: ローカルでのテスト
# サーバーを起動
npm start
# 別のターミナルで MCP Inspector を使用してテスト
npx @modelcontextprotocol/inspector@latest
# http://localhost:5173 を開き、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 を再起動してください。
ツールパターン
戻り値の型
// テキストレスポンス
return { content: [{ type: "text", text: "result" }] };
// 複数のコンテンツアイテム
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 は完全に型付けされ、検証されています
},
);
環境/バインディングへのアクセス
export class MyMCP extends McpAgent<Env> {
async init() {
this.server.tool("query_db", { sql: z.string() }, async ({ sql }) => {
// D1 バインディングにアクセス
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 — エラーコードと修正方法
ライセンス: MIT(寛容ライセンスのため全文を引用しています) · 原本リポジトリ
詳細情報
- 作者
- involvex
- ライセンス
- MIT
- 最終更新
- 2026/5/7
Source: https://github.com/involvex/youtube-music-cli / ライセンス: MIT