mcpField
C
cloudflare-mcp-server

cloudflare-mcp-server

github.com/ovachieverクラウド・DevOps5650 回インストール48 週間前に更新
リポジトリ

cloudflare-mcp-server について

cloudflare-mcp-serverは、Cloudflare Workers上でTypeScriptのMCPサーバーを構築する開発者向けスキルです。トランスポート、認証、状態管理、Cloudflareサービス連携の実装パターンとデプロイ手順を紹介します。

主な機能

  1. 01TypeScript MCPサーバーの実装パターン
  2. 02SSEとStreamable HTTPのガイド
  3. 03OAuthとベアラートークン認証
  4. 04Durable Objectsによるセッション状態
  5. 05Cloudflareサービス連携の例
  6. 06デプロイとトラブルシューティングのガイド

活用シーン

  1. 01WorkersでのリモートMCPサーバーの開始
  2. 02OAuthまたはベアラートークン認証の追加
  3. 03セッション状態を持つサーバーの構築
  4. 04トランスポートパスやデプロイエラーの調査

MCP 対応

Cloudflare Workers上でリモートMCPサーバーを構築・デプロイする方法を解説します。ツール、HTTPトランスポート、認証、デプロイ済みサーバーへのMCPクライアント接続を扱います。

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/ovachiever/droid-tings --skill cloudflare-mcp-server

インストール後、Claude Code で/cloudflare-mcp-serverを入力して読み込まれたか確認します。

同梱ファイル

SKILL.md と一緒にインストールされる参考資料やスクリプト。

README.md
.claude-plugin/
plugin.json
references/
authentication.md
common-issues.md
debugging-guide.md
http-transport-fundamentals.md
oauth-providers.md
official-examples.md
transport-comparison.md
transport.md
templates/
basic-mcp-server.ts
claude_desktop_config.json
mcp-bearer-auth.ts
mcp-http-fundamentals.ts
mcp-oauth-proxy.ts
mcp-stateful-do.ts
mcp-with-d1.ts
mcp-with-workers-ai.ts
package.json
wrangler-basic.jsonc
wrangler-oauth.jsonc

詳細

Cloudflare MCP サーバースキル

TypeScript を使用して、Cloudflare Workers 上でModel Context Protocol(MCP)サーバーを構築、デプロイします。


このスキルについて

このスキルでは、2025 年時点で公式のリモート MCP サポートを提供する唯一のプラットフォームである Cloudflare 上で、リモート MCP サーバーを構築する方法を学びます。

このスキルは、次のような場合に使用します:

  • TypeScript(@modelcontextprotocol/sdk)で MCP サーバーを構築する
  • リモート MCP サーバーを Cloudflare Workers にデプロイする
  • OAuth 認証(GitHub、Google、Azure、カスタム)を実装する
  • Durable Objects を使用してステートフルな MCP サーバーを作成する
  • WebSocket ハイバネーションでコストを最適化する
  • SSE と Streamable HTTP の両方のトランスポートをサポートする
  • 22 件以上のよくある MCP + Cloudflare のエラー(特に URL パスの不一致)を回避する

学べる内容:

  1. HTTP トランスポートの基礎(URL パスの設定、ルーティング)
  2. トランスポートの選択(SSE と Streamable HTTP の比較)
  3. McpAgent クラスのパターンとツール定義
  4. OAuth の統合(5 つの認証パターンすべて)
  5. Cloudflare サービスとの統合(Workers AI、D1、Vectorize など)
  6. セッションごとの状態管理に使用する Durable Objects
  7. WebSocket ハイバネーション API
  8. デプロイの完全なワークフロー

🚀 Cloudflare 公式テンプレート(まずはこちら!)

このスキルのテンプレートを使用する前に、Cloudflare が npm create で公式スターターテンプレートを提供していることを確認してください。

おすすめの出発点

ほとんどのプロジェクトでは、Cloudflare の公式な認証なしテンプレートから始めてください。

npm create cloudflare@latest -- my-mcp-server \
  --template=cloudflare/ai/demos/remote-mcp-authless

cd my-mcp-server
npm install
npm run dev

含まれるもの:

  • ✅ 最小限の構成で動作する MCP サーバー(約 50 行)
  • ✅ 2 種類のトランスポートをサポート(SSE + Streamable HTTP)
  • ✅ 設定済みの wrangler.jsonc
  • ✅ すぐにデプロイ可能

その後、このスキルのパターンを使ってカスタマイズし、22 件以上のよくあるエラーを回避しましょう!


Cloudflare で利用できるすべてのテンプレート

Cloudflare は 14 種類以上の公式 MCP テンプレートを管理しています。出発点としてご利用ください。

基本テンプレート
テンプレートコマンド用途使用する場面
--template=cloudflare/ai/demos/remote-mcp-authless標準となるスターター - 認証なし、シンプルなツール新しいプロジェクト、学習、パブリック API
--template=cloudflare/ai/demos/remote-mcp-github-oauthGitHub OAuth + Workers AI開発者向けツール、GitHub との統合
--template=cloudflare/ai/demos/remote-mcp-google-oauthGoogle OAuthGoogle Workspace との統合
高度な認証テンプレート
テンプレートコマンド認証方式ユースケース
--template=cloudflare/ai/demos/remote-mcp-auth0Auth0エンタープライズ SSO
--template=cloudflare/ai/demos/remote-mcp-authkitWorkOS AuthKitB2B SaaS アプリケーション
--template=cloudflare/ai/demos/remote-mcp-logtoLogtoオープンソース認証
--template=cloudflare/ai/demos/remote-mcp-cf-accessCloudflare Access社内向けツール
--template=cloudflare/ai/demos/mcp-server-bearer-authベアラートークンカスタム認証システム
統合の例
テンプレートコマンド説明する内容Cloudflare サービス
--template=cloudflare/ai/demos/remote-mcp-server-autoragRAG(検索拡張生成)Workers AI + Vectorize
--template=cloudflare/ai/demos/python-workers-mcpPython MCP サーバーPython Workers

このスキルのテンプレートを使う場面

このスキルのテンプレートは、次のような場合に使用します。

  • URL パスの仕組みを学びたい(mcp-http-fundamentals.ts を使用)
  • エラーを包括的に防止したい(すべてのテンプレートに警告が含まれています)
  • すべての判断について詳しいコメントを確認したい
  • 複雑な統合(Workers AI、D1、ベアラー認証)を構築する

このスキルのテンプレートは、Cloudflare のテンプレートよりも学習に適しています(コメントが多く、防御的なパターンやエラー処理が含まれています)。

Cloudflare のテンプレートは、すばやく始めるのに適しています(最小限の構成で、本番環境に対応しています)。

おすすめの方法:まず Cloudflare のテンプレートから始め、その後、このスキルを参考にしてエラーを回避しましょう!


本番環境の MCP サーバー(これらを学びましょう!)

Cloudflare は、実際の統合パターンを示す 15 個の本番環境向け MCP サーバーを管理しています。

学習におすすめのサーバー:

  • workers-bindings - D1、KV、R2、AI、Durable Objects の使用方法
  • browser-rendering - ウェブスクレイピングとスクリーンショットのツール
  • autorag - Vectorize RAG パターン
  • ai-gateway - Workers AI Gateway の分析
  • docs - Cloudflare ドキュメントの検索

リポジトリ:https://github.com/cloudflare/mcp-server-cloudflare

なぜこれらを学ぶのですか? 次のような本番環境対応のパターンを確認できます。

  • エラー処理
  • レート制限
  • キャッシュ戦略
  • 実際の API 統合
  • セキュリティのベストプラクティス

🎯 クイックスタートのワークフロー(ステップごとのガイド)

次の MCP サーバーでは、このワークフローに従ってエラーを避け、すばやくリリースしましょう。


ステップ 1:開始用テンプレートを選ぶ

判断フロー:

What are you building?

├─ 🆓 Public/dev server (no auth needed)
│  └─> Use: remote-mcp-authless ⭐ RECOMMENDED FOR MOST PROJECTS
│
├─ 🔐 GitHub integration
│  └─> Use: remote-mcp-github-oauth (includes Workers AI example)
│
├─ 🔐 Google Workspace integration
│  └─> Use: remote-mcp-google-oauth
│
├─ 🏢 Enterprise SSO (Auth0, Okta, etc.)
│  └─> Use: remote-mcp-auth0 or remote-mcp-authkit
│
├─ 🔑 Custom auth system / API keys
│  └─> Start with authless, then add bearer auth (see Step 3)
│
└─ 🏠 Internal company tool
   └─> Use: remote-mcp-cf-access (Cloudflare Zero Trust)

迷った場合は? remote-mcp-authless から始めましょう。認証は後から追加できます!


ステップ 2:テンプレートから作成する
# Replace [TEMPLATE] with your choice from Step 1
npm create cloudflare@latest -- my-mcp-server \
  --template=cloudflare/ai/demos/[TEMPLATE]

# Example: authless template (most common)
npm create cloudflare@latest -- my-mcp-server \
  --template=cloudflare/ai/demos/remote-mcp-authless

# Navigate and install
cd my-mcp-server
npm install

# Start dev server
npm run dev

MCP サーバーが次の URL で起動しました:http://localhost:8788/sse


ステップ 3:このスキルのパターンを使ってカスタマイズする

このスキルのパターンをコピーして、機能を追加しましょう。

Workers AI(画像/テキスト生成)が必要ですか?
# Copy our Workers AI template
cp ~/.claude/skills/cloudflare-mcp-server/templates/mcp-with-workers-ai.ts src/my-ai-tools.ts

# Add AI binding to wrangler.jsonc:
# { "ai": { "binding": "AI" } }

使用できるツール:generate_image、generate_text、list_ai_models


データベース(D1)が必要ですか?
# Copy our D1 template
cp ~/.claude/skills/cloudflare-mcp-server/templates/mcp-with-d1.ts src/my-db-tools.ts

# Create D1 database:
npx wrangler d1 create my-database

# Add binding to wrangler.jsonc

使用できるツール:create_user、get_user、list_users、update_user、delete_user、search_users


ベアラートークン認証が必要ですか?
# Copy our bearer auth template
cp ~/.claude/skills/cloudflare-mcp-server/templates/mcp-bearer-auth.ts src/index.ts

# Add token validation (KV, external API, or static)

追加される機能:Authorization ヘッダーのミドルウェア、トークンの検証、認証が必要なツール


ステップ 4:Cloudflare にデプロイする
# Login (first time only)
npx wrangler login

# Deploy to production
npx wrangler deploy

出力にデプロイ済み URL が表示されます:

✨ Deployment complete!
https://my-mcp-server.YOUR_ACCOUNT.workers.dev

⚠️ 重要:この URL を控えてください。ステップ 5 で必要になります!


ステップ 5:クライアントをテストして設定する
A. curl でテストする(エラーの 80%を防止できます!)
# Test the exact URL you'll use in client config
curl https://my-mcp-server.YOUR_ACCOUNT.workers.dev/sse

期待されるレスポンス:

{
  "name": "My MCP Server",
  "version": "1.0.0",
  "transports": ["/sse", "/mcp"]
}

404 が返されましたか? → クライアントの URL が間違っています!下の「HTTP トランスポートの基本」を参照してください。


B. Claude Desktop の設定を更新する

Linux/Mac:~/.config/claude/claude_desktop_config.json Windows:%APPDATA%/Claude/claude_desktop_config.json

認証なしのサーバーの場合:

{
  "mcpServers": {
    "my-mcp": {
      "url": "https://my-mcp-server.YOUR_ACCOUNT.workers.dev/sse"
    }
  }
}

⚠️ 重要:URL はステップ 5A で成功した curl コマンドと一致している必要があります!

OAuth を使用する場合:

{
  "mcpServers": {
    "my-mcp": {
      "url": "https://my-mcp-server.YOUR_ACCOUNT.workers.dev/sse",
      "auth": {
        "type": "oauth",
        "authorizationUrl": "https://my-mcp-server.YOUR_ACCOUNT.workers.dev/authorize",
        "tokenUrl": "https://my-mcp-server.YOUR_ACCOUNT.workers.dev/token"
      }
    }
  }
}

3 つの URL すべてで同じドメインを使用する必要があります!


C. Claude Desktop を再起動する

設定が読み込まれるのは起動時のみです。

  1. Claude Desktop を完全に終了します
  2. 再度開きます
  3. ツール一覧に MCP サーバーが表示されていることを確認します

ステップ 6:動作を確認する

ツールの呼び出しをテストします。

  1. Claude Desktop を開きます
  2. 「利用可能な MCP ツールを一覧表示して」と入力します
  3. サーバーのツールが表示されるはずです
  4. 次のように入力して、ツールの呼び出しを試します:「add ツールを使って 5 + 3 を計算して」

ツールが表示されない場合 → references/ の「デバッグガイド」を参照してください。


デプロイ後のチェックリスト

成功と判断する前に、次の項目を確認してください。

  • curl https://worker.dev/sse でサーバー情報が返される(404 ではない)
  • クライアント設定の URL が curl の URL と完全に一致している
  • 設定の更新後に Claude Desktop を再起動した
  • Claude Desktop にツールが表示されている
  • ツールの呼び出しに成功する
  • (OAuth のみ)3 つの URL すべてで同じドメインを使用している
  • npx wrangler tail のログにエラーがない

すべてチェックできましたか? 🎉 MCP サーバーが稼働中です!


よくある次のステップ

機能を追加しますか?

  1. ツールを追加する - McpAgent クラスの init() メソッドに追加します
  2. Workers AI - mcp-with-workers-ai.ts のパターンをコピーします
  3. データベース - mcp-with-d1.ts のパターンをコピーします
  4. 認証 - mcp-bearer-auth.ts または mcp-oauth-proxy.ts のパターンをコピーします
  5. Durable Objects の状態 - mcp-stateful-do.ts のパターンをコピーします

エラーを避けたいですか?

  • 下の「HTTP トランスポートの基本」を読む(URL パスのエラーを防止できます)
  • 「22 個の既知のエラー」を読む(よくある間違いをすべて防止できます)
  • 行き詰まった場合は references/debugging-guide.md を確認する

要約 - 5 分でできるワークフロー
# 1. Create from template (30 seconds)
npm create cloudflare@latest -- my-mcp \
  --template=cloudflare/ai/demos/remote-mcp-authless
cd my-mcp && npm install

# 2. Customize (optional, 2 minutes)
# Copy patterns from this skill if needed

# 3. Deploy (30 seconds)
npx wrangler deploy

# 4. Test (30 seconds)
curl https://YOUR-WORKER.workers.dev/sse

# 5. Configure client (1 minute)
# Update claude_desktop_config.json with URL from step 4
# Restart Claude Desktop

# 6. Verify (30 seconds)
# Test a tool call in Claude Desktop

所要時間:何もない状態から、動作する MCP サーバーの完成まで約 5 分です!🚀


⚠️ 重要:HTTP トランスポートの基本

MCP サーバーが接続に失敗する最大の原因は、URL パスの設定ミスです。

URL パス設定の詳細

MCP サーバーを特定のパスで提供する場合、クライアントの URL は完全に一致している必要があります。

例 1:/sse で提供する場合

// src/index.ts
export default {
  fetch(request: Request, env: Env, ctx: ExecutionContext) {
    const { pathname } = new URL(request.url);

    if (pathname.startsWith("/sse")) {
      return MyMCP.serveSSE("/sse").fetch(request, env, ctx);  // ← Base path is "/sse"
    }

    return new Response("Not Found", { status: 404 });
  }
};

クライアント設定には必ず /sse を含めてください:

{
  "mcpServers": {
    "my-mcp": {
      "url": "https://my-mcp.workers.dev/sse"  // ✅ Correct
    }
  }
}

❌ 誤ったクライアント設定:

"url": "https://my-mcp.workers.dev"      // Missing /sse → 404
"url": "https://my-mcp.workers.dev/"     // Missing /sse → 404
"url": "http://localhost:8788"           // Wrong after deploy

例 2:/(ルート)で提供する場合

export default {
  fetch(request: Request, env: Env, ctx: ExecutionContext) {
    return MyMCP.serveSSE("/").fetch(request, env, ctx);  // ← Base path is "/"
  }
};

クライアント設定:

{
  "mcpServers": {
    "my-mcp": {
      "url": "https://my-mcp.workers.dev"  // ✅ Correct (no /sse)
    }
  }
}

ベースパスがツールの URL に与える影響

serveSSE("/sse") を呼び出す場合、MCP ツールは次の場所で提供されます:

https://my-mcp.workers.dev/sse/tools/list
https://my-mcp.workers.dev/sse/tools/call
https://my-mcp.workers.dev/sse/resources/list

serveSSE("/") を呼び出す場合、MCP ツールは次の場所で提供されます:

https://my-mcp.workers.dev/tools/list
https://my-mcp.workers.dev/tools/call
https://my-mcp.workers.dev/resources/list

ベースパスは、すべての MCP エンドポイントの先頭に自動的に追加されます。


リクエスト/レスポンスのライフサイクル
1. Client connects to: https://my-mcp.workers.dev/sse
                                ↓
2. Worker receives request: { url: "https://my-mcp.workers.dev/sse", ... }
                                ↓
3. Your fetch handler: const { pathname } = new URL(request.url)
                                ↓
4. pathname === "/sse" → Check passes
                                ↓
5. MyMCP.serveSSE("/sse").fetch() → MCP server handles request
                                ↓
6. Tool calls routed to: /sse/tools/call

クライアントが https://my-mcp.workers.dev に接続する場合(/sse がありません):

pathname === "/" → Check fails → 404 Not Found

URL 設定のテスト

ステップ 1:MCP サーバーをデプロイする

npx wrangler deploy
# Output: Deployed to https://my-mcp.YOUR_ACCOUNT.workers.dev

ステップ 2:curl でベースパスをテストする

# If serving at /sse, test this URL:
curl https://my-mcp.YOUR_ACCOUNT.workers.dev/sse

# Should return MCP server info (not 404)

ステップ 3:テストした URL と完全に一致するようにクライアント設定を更新する

{
  "mcpServers": {
    "my-mcp": {
      "url": "https://my-mcp.YOUR_ACCOUNT.workers.dev/sse"  // Match curl URL
    }
  }
}

ステップ 4:Claude Desktop を再起動する


デプロイ後のチェックリスト

デプロイ後、次の項目を確認してください:

  • curl https://worker.dev/sse が MCP サーバー情報を返す(404 ではない)
  • クライアント設定の URL がデプロイ済みの URL と完全に一致している
  • URL に入力ミスがない(よくある例:workers.dev ではなく workes.dev)
  • デプロイ済みの Workers では https:// を使用している(http:// ではない)
  • OAuth を使用している場合、リダイレクト URI も更新されている

トランスポートの選択ガイド

MCP は 2 つのトランスポート方式をサポートします:SSE(レガシー)と Streamable HTTP(2025 年標準)。

SSE(Server-Sent Events)

最適な用途:幅広いクライアントとの互換性(2024 年のクライアント)、レガシーサポート

提供方法:

MyMCP.serveSSE("/sse").fetch(request, env, ctx)

クライアント設定:

{
  "url": "https://my-mcp.workers.dev/sse"
}

メリット:

  • ✅ すべての MCP クライアントでサポートされる(2024 年以降)
  • ✅ デバッグが簡単(プレーンな HTTP)
  • ✅ MCP Inspector で動作する

デメリット:

  • ❌ HTTP ストリーミングより効率が低い
  • ❌ 2025 年に非推奨となる予定

Streamable HTTP

最適な用途:最新のクライアント(2025 年以降)、パフォーマンスの向上

提供方法:

MyMCP.serve("/mcp").fetch(request, env, ctx)

クライアント設定:

{
  "url": "https://my-mcp.workers.dev/mcp"
}

メリット:

  • ✅ SSE より効率が高い
  • ✅ 2025 年標準
  • ✅ ストリーミングのサポートが優れている

デメリット:

  • ❌ 新しいクライアントのみ
  • ❌ ツールの成熟度が低い

両方をサポートする(推奨)

互換性を最大限に高めるには、両方のトランスポートを提供してください:

export default {
  fetch(request: Request, env: Env, ctx: ExecutionContext) {
    const { pathname } = new URL(request.url);

    // SSE transport (legacy)
    if (pathname.startsWith("/sse")) {
      return MyMCP.serveSSE("/sse").fetch(request, env, ctx);
    }

    // HTTP transport (2025 standard)
    if (pathname.startsWith("/mcp")) {
      return MyMCP.serve("/mcp").fetch(request, env, ctx);
    }

    // Health check endpoint (optional but recommended)
    if (pathname === "/" || pathname === "/health") {
      return new Response(
        JSON.stringify({
          name: "My MCP Server",
          version: "1.0.0",
          transports: {
            sse: "/sse",
            http: "/mcp"
          },
          status: "ok",
          timestamp: new Date().toISOString()
        }),
        {
          headers: { "Content-Type": "application/json" },
          status: 200
        }
      );
    }

    return new Response("Not Found", { status: 404 });
  }
};

これが機能する理由:

  • SSE クライアントは /sse に接続する
  • HTTP クライアントは /mcp に接続する
  • ヘルスチェックは / または /health で利用できる
  • トランスポート間の競合がない

重要:パスを正しく照合するには pathname.startsWith() を使用してください!


クイックスタート(5 分)

URL 設定について理解したところで、最初の MCP サーバーを作成しましょう。

オプション 1:最小テンプレートをコピーする

mcp-http-fundamentals.ts テンプレートを使用します。最もシンプルな動作例です。

# Copy minimal template
cp ~/.claude/skills/cloudflare-mcp-server/templates/mcp-http-fundamentals.ts src/index.ts

# Install dependencies
npm install

# Start dev server
npm run dev

# Test connection
curl http://localhost:8788/sse
# Should return: {"name":"My MCP Server","version":"1.0.0",...}
オプション 2:Cloudflare テンプレートからデプロイする
# Create new MCP server from official template
npm create cloudflare@latest -- my-mcp-server \
  --template=cloudflare/ai/demos/remote-mcp-authless

cd my-mcp-server
npm install
npm run dev

MCP サーバーは http://localhost:8788/sse で稼働しています。

MCP Inspector でテストする
# In a new terminal
npx @modelcontextprotocol/inspector@latest

# Open http://localhost:5173
# Enter: http://localhost:8788/sse
# Click "Connect" and test tools
Cloudflare にデプロイする
# Deploy
npx wrangler deploy

# Output shows your URL:
# https://my-mcp-server.YOUR_ACCOUNT.workers.dev

# ⚠️ REMEMBER: Update client config with this URL + /sse!

基本概念

1. McpAgent クラス

Cloudflare の Agents SDK が提供する McpAgent 基底クラスには、次の機能があります:

  • Durable Objects との自動統合
  • SQL データベースを使用した組み込みの状態管理
  • ツール、リソース、プロンプトの登録
  • トランスポート処理(SSE + HTTP)

基本パターン:

import { McpAgent } from "agents/mcp";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod";

export class MyMCP extends McpAgent<Env> {
  server = new McpServer({
    name: "My MCP Server",
    version: "1.0.0"
  });

  async init() {
    // Register tools here
    this.server.tool(
      "tool_name",
      "Tool description",
      { param: z.string() },
      async ({ param }) => ({
        content: [{ type: "text", text: "Result" }]
      })
    );
  }
}
2. ツール定義

ツールは、MCP クライアントが呼び出せる関数です。パラメーターの検証には Zod を使用します。

パターン:

this.server.tool(
  "tool_name",           // Tool identifier
  "Tool description",    // What it does (for LLM)
  {                      // Parameters (Zod schema)
    param1: z.string().describe("Parameter description"),
    param2: z.number().optional()
  },
  async ({ param1, param2 }) => {  // Handler
    // Your logic here
    return {
      content: [{ type: "text", text: "Result" }]
    };
  }
);

ベストプラクティス:

  • 詳細な説明:LLM がツールの目的を理解しやすくします
  • パラメーターの説明:想定される値と制約を説明します
  • エラー処理:失敗時には { isError: true } を返します
  • 少数の用途を絞ったツール:細分化された多数のツールより効果的です

認証パターン

Cloudflare MCP サーバーは 4 つの認証パターンをサポートします:

パターン 1:認証なし

ユースケース:内部ツール、開発、公開 API

テンプレート:templates/mcp-http-fundamentals.ts

セットアップ:不要

セキュリティ:⚠️ 誰でも MCP サーバーにアクセスできます


パターン 2:トークン検証(JWTVerifier)

ユースケース:事前認証済みのクライアント、カスタム認証システム

仕組み:クライアントが Bearer トークンを送信し、サーバーが検証します

テンプレート:カスタム JWTVerifier ミドルウェアを作成します

セットアップ:

import { JWTVerifier } from "agents/mcp";

const verifier = new JWTVerifier({
  secret: env.JWT_SECRET,
  issuer: "your-auth-server"
});

// Validate token before serving MCP requests

セキュリティ:✅ トークンが適切に管理されていれば安全です


パターン 3:OAuth プロキシ(workers-oauth-provider)

ユースケース:GitHub、Google、Azure の OAuth 統合

仕組み:Cloudflare Worker が OAuth をサードパーティプロバイダーにプロキシします

テンプレート:templates/mcp-oauth-proxy.ts

セットアップ:

import { OAuthProvider, GitHubHandler } from "@cloudflare/workers-oauth-provider";

export default new OAuthProvider({
  authorizeEndpoint: "/authorize",
  tokenEndpoint: "/token",
  clientRegistrationEndpoint: "/register",

  defaultHandler: new GitHubHandler({
    clientId: (env) => env.GITHUB_CLIENT_ID,
    clientSecret: (env) => env.GITHUB_CLIENT_SECRET,
    scopes: ["repo", "user:email"],

    context: async (accessToken) => {
      // Fetch user info from GitHub
      const octokit = new Octokit({ auth: accessToken });
      const { data: user } = await octokit.rest.users.getAuthenticated();

      return {
        login: user.login,
        email: user.email,
        accessToken
      };
    }
  }),

  kv: (env) => env.OAUTH_KV,
  apiHandlers: {
    "/sse": MyMCP.serveSSE("/sse"),
    "/mcp": MyMCP.serve("/mcp")
  },

  allowConsentScreen: true,
  allowDynamicClientRegistration: true
});

必須バインディング:

{
  "kv_namespaces": [
    { "binding": "OAUTH_KV", "id": "YOUR_KV_ID" }
  ]
}

⚠️ 重要な OAuth URL 設定:OAuth を使用する場合、リダイレクト URI は必ず次と一致させてください:

{
  "mcpServers": {
    "my-mcp": {
      "url": "https://my-mcp.YOUR_ACCOUNT.workers.dev/sse",
      "auth": {
        "type": "oauth",
        "authorizationUrl": "https://my-mcp.YOUR_ACCOUNT.workers.dev/authorize",
        "tokenUrl": "https://my-mcp.YOUR_ACCOUNT.workers.dev/token"
      }
    }
  }
}

すべての URL で同じドメインとプロトコル(https://)を使用する必要があります。

セキュリティ:✅✅ 安全で、本番環境に対応しています


パターン 4:DCR を使用したリモート OAuth

ユースケース:完全な OAuth プロバイダー、カスタム同意画面

仕組み:Worker が OAuth プロバイダーになります

テンプレート:Cloudflare の remote-mcp-authkit デモを参照してください

セットアップ:複雑です。OAuth 2.1 の完全な実装が必要です

セキュリティ:✅✅✅ 最も安全で、完全な制御が可能です


Durable Objects を使用したステートフル MCP サーバー

MCP サーバーで次の機能が必要な場合は、Durable Objects を使用してください:

  • セッションごとの永続状態
  • 会話履歴
  • ゲームの状態(チェス、三目並べ)
  • API レスポンスのキャッシュ
  • ユーザー設定
ストレージ API パターン

テンプレート:templates/mcp-stateful-do.ts

値の保存:

await this.state.storage.put("key", "value");
await this.state.storage.put("user_prefs", { theme: "dark" });

値の取得:

const value = await this.state.storage.get<string>("key");
const prefs = await this.state.storage.get<object>("user_prefs");

キーの一覧表示:

const allKeys = await this.state.storage.list();

キーの削除:

await this.state.storage.delete("key");
設定

wrangler.jsonc:

{
  "durable_objects": {
    "bindings": [
      {
        "name": "MY_MCP",
        "class_name": "MyMCP",
        "script_name": "my-mcp-server"
      }
    ]
  },

  "migrations": [
    { "tag": "v1", "new_classes": ["MyMCP"] }
  ]
}

重要:初回デプロイ時にはマイグレーションが必要です!


WebSocket ハイバネーションによるコスト最適化

問題:長時間の WebSocket 接続には CPU 時間のコストがかかります

解決策:WebSocket ハイバネーション API は、アイドル状態の接続を一時停止します

パターン

メタデータのシリアライズ(ハイバネーション中もデータを保持します):

webSocket.serializeAttachment({
  userId: "123",
  sessionId: "abc",
  connectedAt: Date.now()
});

復帰時の取得:

const metadata = webSocket.deserializeAttachment();
console.log(metadata.userId); // "123"

永続状態のストレージ:

// ❌ DON'T: In-memory state lost on hibernation
this.userId = "123";

// ✅ DO: Use storage API
await this.state.storage.put("userId", "123");
コスト削減

ハイバネーションを使用しない場合:

  • 同時接続 WebSocket 1000 件 × CPU 時間 10ms/秒 = 10 CPU 秒/秒
  • コスト:約 $0.50/日

ハイバネーションを使用する場合:

  • メッセージの処理時のみ CPU を使用(アイドル時間の 99% は一時停止)
  • コスト:約 $0.01/日(50 分の 1 に削減!)

一般的なパターン

API プロキシ MCP サーバー

ユースケース:外部 API を MCP ツールでラップします

パターン:

this.server.tool(
  "search_wikipedia",
  "Search Wikipedia for a topic",
  { query: z.string() },
  async ({ query }) => {
    const response = await fetch(
      `https://en.wikipedia.org/api/rest_v1/page/summary/${encodeURIComponent(query)}`
    );
    const data = await response.json();

    return {
      content: [{
        type: "text",
        text: data.extract
      }]
    };
  }
);
データベース連携ツール

ユースケース:D1、KV、または外部データベースにクエリを実行します

パターン:

this.server.tool(
  "get_user",
  "Get user details from database",
  { userId: z.string() },
  async ({ userId }) => {
    // Query Durable Objects storage
    const user = await this.state.storage.get<User>(`user:${userId}`);

    // Or query D1 database
    const result = await env.DB.prepare(
      "SELECT * FROM users WHERE id = ?"
    ).bind(userId).first();

    return {
      content: [{
        type: "text",
        text: JSON.stringify(user || result, null, 2)
      }]
    };
  }
);
複数ツールの連携

ユースケース:ほかのツールを呼び出すツール

パターン:

// Store result from first tool
await this.state.storage.put("last_search", result);

// Second tool reads it
const lastSearch = await this.state.storage.get("last_search");
キャッシュ戦略

ユースケース:コストの高い API 呼び出しをキャッシュします

パターン:

this.server.tool(
  "get_weather",
  "Get weather (cached 5 minutes)",
  { city: z.string() },
  async ({ city }) => {
    const cacheKey = `weather:${city}`;
    const cached = await this.state.storage.get<CachedWeather>(cacheKey);

    // Check cache freshness
    if (cached && Date.now() - cached.timestamp < 5 * 60 * 1000) {
      return {
        content: [{ type: "text", text: cached.data }]
      };
    }

    // Fetch fresh data
    const weather = await fetchWeatherAPI(city);

    // Cache it
    await this.state.storage.put(cacheKey, {
      data: weather,
      timestamp: Date.now()
    });

    return {
      content: [{ type: "text", text: weather }]
    };
  }
);
Durable Objects によるレート制限

ユースケース:不正利用を防止し、上流のレート制限を遵守します

パターン:

async rateLimit(key: string, maxRequests: number, windowMs: number): Promise<boolean> {
  const now = Date.now();
  const requests = await this.state.storage.get<number[]>(`ratelimit:${key}`) || [];

  // Remove old requests outside window
  const recentRequests = requests.filter(ts => now - ts < windowMs);

  if (recentRequests.length >= maxRequests) {
    return false; // Rate limited
  }

  // Add this request
  recentRequests.push(now);
  await this.state.storage.put(`ratelimit:${key}`, recentRequests);

  return true; // Allowed
}

// Use in tool
if (!await this.rateLimit(userId, 10, 60 * 1000)) {
  return {
    content: [{ type: "text", text: "Rate limit exceeded (10 requests/minute)" }],
    isError: true
  };
}

既知のエラー 22 件(解決策付き)

1. McpAgent クラスがエクスポートされていない

エラー:TypeError: Cannot read properties of undefined (reading 'serve')

原因:McpAgent クラスのエクスポートを忘れています

解決策:

export class MyMCP extends McpAgent { ... }  // ✅ Must export
export default { fetch() { ... } }

2. ベースパスの設定不一致(最もよくあるエラー!)

エラー:404 Not Found または Connection failed

原因:serveSSE("/sse") を使用しているのに、クライアントが https://worker.dev(/sse が欠落)に設定されています

解決策:ベースパスを完全に一致させます

// Server serves at /sse
MyMCP.serveSSE("/sse").fetch(...)

// Client MUST include /sse
{ "url": "https://worker.dev/sse" }  // ✅ Correct
{ "url": "https://worker.dev" }      // ❌ Wrong - 404

デバッグ手順:

  1. サーバーが使用しているパスを確認します:serveSSE("/sse") と serveSSE("/") のどちらか
  2. curl でテストします:curl https://worker.dev/sse
  3. curl の URL に一致するようにクライアント設定を更新します

3. トランスポートタイプの混同

エラー:Connection failed: Unexpected response format

原因:クライアントが SSE を想定しているのに HTTP エンドポイントへ接続している(またはその逆)

解決策:トランスポートタイプを一致させます

// SSE transport
MyMCP.serveSSE("/sse")  // Client URL: https://worker.dev/sse

// HTTP transport
MyMCP.serve("/mcp")     // Client URL: https://worker.dev/mcp

ベストプラクティス:両方のトランスポートをサポートします(「トランスポート選択ガイド」を参照してください)


4. pathname.startsWith() のロジックエラー

エラー:/sse と /mcp の両方のルートで失敗する、または競合する

原因:パスの照合ロジックが正しくありません

解決策:startsWith() を正しく使用してください

// ✅ CORRECT
if (pathname.startsWith("/sse")) {
  return MyMCP.serveSSE("/sse").fetch(...);
}
if (pathname.startsWith("/mcp")) {
  return MyMCP.serve("/mcp").fetch(...);
}

// ❌ WRONG: Exact match breaks sub-paths
if (pathname === "/sse") {  // Breaks /sse/tools/list
  return MyMCP.serveSSE("/sse").fetch(...);
}

5. ローカル URL とデプロイ後の URL の不一致

エラー:開発時は動作するが、デプロイ後に失敗する

原因:クライアントの設定に localhost の URL が残っています

解決策:デプロイ後にクライアントの設定を更新してください

// Development
{ "url": "http://localhost:8788/sse" }

// ⚠️ MUST UPDATE after npx wrangler deploy
{ "url": "https://my-mcp.YOUR_ACCOUNT.workers.dev/sse" }

デプロイ後のチェックリスト:

  • npx wrangler deploy を実行し、出力された URL を記録する
  • デプロイ後の URL でクライアントの設定を更新する
  • curl でテストする
  • Claude Desktop を再起動する

6. OAuth リダイレクト URI の不一致

エラー:OAuth error: redirect_uri does not match

原因:OAuth のリダイレクト URI がデプロイ後の URL と一致していません

解決策:デプロイ後にすべての OAuth URL を更新してください

{
  "url": "https://my-mcp.YOUR_ACCOUNT.workers.dev/sse",
  "auth": {
    "type": "oauth",
    "authorizationUrl": "https://my-mcp.YOUR_ACCOUNT.workers.dev/authorize",  // Must match deployed domain
    "tokenUrl": "https://my-mcp.YOUR_ACCOUNT.workers.dev/token"
  }
}

重要:すべての URL で同じプロトコルとドメインを使用する必要があります!


7. OPTIONS ハンドラーの不足(CORS プリフライト)

エラー:Access to fetch at '...' blocked by CORS policy または Method Not Allowed

原因:ブラウザーのクライアントは CORS プリフライトのために OPTIONS リクエストを送信しますが、サーバーがそれを処理していません

解決策:OPTIONS ハンドラーを追加してください

export default {
  fetch(request: Request, env: Env, ctx: ExecutionContext) {
    // Handle CORS preflight
    if (request.method === "OPTIONS") {
      return new Response(null, {
        status: 204,
        headers: {
          "Access-Control-Allow-Origin": "*",
          "Access-Control-Allow-Methods": "GET, POST, OPTIONS",
          "Access-Control-Allow-Headers": "Content-Type, Authorization",
          "Access-Control-Max-Age": "86400"
        }
      });
    }

    // ... rest of your fetch handler
  }
};

必要な場合:ブラウザーベースの MCP クライアント(ブラウザー内の MCP Inspector など)


8. リクエスト本文の検証不足

エラー:TypeError: Cannot read properties of undefined または JSON の解析時に Unexpected token

原因:クライアントが不正な JSON を送信していますが、サーバーが解析前に検証していません

解決策:リクエスト処理を try/catch で囲んでください

export default {
  async fetch(request: Request, env: Env, ctx: ExecutionContext) {
    try {
      // Your MCP server logic
      return await MyMCP.serveSSE("/sse").fetch(request, env, ctx);
    } catch (error) {
      console.error("Request handling error:", error);
      return new Response(
        JSON.stringify({
          error: "Invalid request",
          details: error.message
        }),
        {
          status: 400,
          headers: { "Content-Type": "application/json" }
        }
      );
    }
  }
};

9. 環境変数の検証不足

エラー:TypeError: env.API_KEY is undefined、またはエラーが表示されないまま失敗する(ツールが空のデータを返す)

原因:必要な環境変数が設定されていないか、実行時に不足しています

解決策:起動時の検証を追加してください

export class MyMCP extends McpAgent<Env> {
  async init() {
    // Validate required environment variables
    if (!this.env.API_KEY) {
      throw new Error("API_KEY environment variable not configured");
    }
    if (!this.env.DATABASE_URL) {
      throw new Error("DATABASE_URL environment variable not configured");
    }

    // Continue with tool registration
    this.server.tool(...);
  }
}

設定チェックリスト:

  • 開発環境:.dev.vars に追加します(ローカルのみ、gitignore 対象)
  • 本番環境:wrangler.jsonc の vars に追加する(公開情報の場合)か、wrangler secret を使用します(機密情報の場合)

ベストプラクティス:

# .dev.vars (local development, gitignored)
API_KEY=dev-key-123
DATABASE_URL=http://localhost:3000

# wrangler.jsonc (public config)
{
  "vars": {
    "ENVIRONMENT": "production",
    "LOG_LEVEL": "info"
  }
}

# wrangler secret (production secrets)
npx wrangler secret put API_KEY
npx wrangler secret put DATABASE_URL

10. McpAgent と McpServer の混同

エラー:TypeError: server.registerTool is not a function または this.server is undefined

原因:McpAgent クラスでスタンドアロン SDK のパターンを使用しようとしています

解決策:McpAgent の this.server.tool() パターンを使用してください

// ❌ WRONG: Mixing standalone SDK with McpAgent
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";

const server = new McpServer({ name: "My Server" });
server.registerTool(...);  // Not compatible with McpAgent!

export class MyMCP extends McpAgent { /* no server property */ }

// ✅ CORRECT: McpAgent pattern
export class MyMCP extends McpAgent<Env> {
  server = new McpServer({
    name: "My MCP Server",
    version: "1.0.0"
  });

  async init() {
    this.server.tool("tool_name", ...);  // Use this.server
  }
}

主な違い:McpAgent には this.server プロパティがありますが、スタンドアロン SDK にはありません。


11. WebSocket のハイバネーションによる状態の消失

エラー:「state not found」と表示され、再接続後にツールの呼び出しが失敗する

原因:ハイバネーション時にインメモリの状態がクリアされます

解決策:インスタンスのプロパティではなく、this.state.storage を使用してください

// ❌ DON'T: Lost on hibernation
this.userId = "123";

// ✅ DO: Persists through hibernation
await this.state.storage.put("userId", "123");

12. Durable Objects バインディングの不足

エラー:TypeError: Cannot read properties of undefined (reading 'idFromName')

原因:wrangler.jsonc に DO バインディングを追加し忘れています

解決策:バインディングを追加してください(ステートフル MCP サーバーのセクションを参照)

{
  "durable_objects": {
    "bindings": [
      {
        "name": "MY_MCP",
        "class_name": "MyMCP",
        "script_name": "my-mcp-server"
      }
    ]
  }
}

13. マイグレーションが定義されていない

エラー:Error: Durable Object class MyMCP has no migration defined

原因:最初の DO のデプロイにはマイグレーションが必要です

解決策:

{
  "migrations": [
    { "tag": "v1", "new_classes": ["MyMCP"] }
  ]
}

14. serializeAttachment() が使用されていない

エラー:ハイバネーションから復帰すると WebSocket のメタデータが失われる

原因:接続のメタデータを保持するために serializeAttachment() を使用していません

解決策:WebSocket のハイバネーションのセクションを参照してください


15. OAuth 同意画面が無効になっている

セキュリティリスク:ユーザーに、付与する権限が表示されません

原因:本番環境で allowConsentScreen: false に設定されています

解決策:本番環境では常に有効にしてください

export default new OAuthProvider({
  allowConsentScreen: true,  // ✅ Always true in production
  // ...
});

16. JWT 署名キーの不足

エラー:Error: JWT_SIGNING_KEY environment variable not set

原因:OAuth Provider がトークンの署名キーを必要としています

解決策:

# Generate secure key
openssl rand -base64 32

# Add to wrangler secret
npx wrangler secret put JWT_SIGNING_KEY

17. ツールスキーマの検証エラー

エラー:ZodError: Invalid input type

原因:クライアントが文字列を送信していますが、スキーマでは数値を想定しています(またはその逆)

解決策:Zod の変換を使用してください

// Accept string, convert to number
param: z.string().transform(val => parseInt(val, 10))

// Or: Accept both types
param: z.union([z.string(), z.number()]).transform(val =>
  typeof val === "string" ? parseInt(val, 10) : val
)

18. 複数のトランスポートエンドポイントの競合

エラー:/mcp を追加した後、/sse が 404 を返す

原因:パスのマッチングが正しくありません(startsWith() がありません)

解決策:startsWith() を使用するか、完全一致で正しくマッチさせてください(エラー #4 を参照)


19. Miniflare の制限によるローカルテストの問題

エラー:ローカル開発環境で OAuth フローに失敗する、または Durable Objects の動作が異なる

原因:Miniflare はすべての DO 機能をサポートしていません

解決策:すべての DO 機能をサポートするには、npx wrangler dev --remote を使用してください

# Local simulation (faster but limited)
npm run dev

# Remote DOs (slower but accurate)
npx wrangler dev --remote

20. クライアント設定形式のエラー

エラー:Claude Desktop がサーバーを認識しない

原因:claude_desktop_config.json の JSON 形式が正しくありません

解決策:正しい形式については「Claude Desktop の接続」セクションを参照してください

よくある間違い:

// ❌ WRONG: Missing "mcpServers" wrapper
{
  "my-mcp": {
    "url": "https://worker.dev/sse"
  }
}

// ❌ WRONG: Trailing comma
{
  "mcpServers": {
    "my-mcp": {
      "url": "https://worker.dev/sse",  // ← Remove comma
    }
  }
}

// ✅ CORRECT
{
  "mcpServers": {
    "my-mcp": {
      "url": "https://worker.dev/sse"
    }
  }
}

21. ヘルスチェックエンドポイントがない

問題:Worker が実行中か、URL が正しいかを確認できない

影響:接続の問題のデバッグに時間がかかります

解決策:ヘルスチェックエンドポイントを追加してください(「トランスポート選択ガイド」を参照)

テスト:

curl https://my-mcp.workers.dev/health
# Should return: {"status":"ok","transports":{...}}

22. CORS ヘッダーがない

エラー:Access to fetch at '...' blocked by CORS policy

原因:MCP サーバーがクロスオリジンリクエストに対して CORS ヘッダーを返していません

解決策:すべてのレスポンスに CORS ヘッダーを追加してください

// Manual CORS (if not using OAuthProvider)
const corsHeaders = {
  "Access-Control-Allow-Origin": "*",  // Or specific origin
  "Access-Control-Allow-Methods": "GET, POST, OPTIONS",
  "Access-Control-Allow-Headers": "Content-Type, Authorization"
};

// Add to responses
return new Response(body, {
  headers: {
    ...corsHeaders,
    "Content-Type": "application/json"
  }
});

注:OAuthProvider が CORS を自動的に処理します!


デプロイとテスト

ローカル開発
# Start dev server (uses Miniflare for local DOs)
npm run dev

# Start dev server with remote Durable Objects (more accurate)
npx wrangler dev --remote

アクセス先:http://localhost:8788/sse

MCP Inspector でテストする
npx @modelcontextprotocol/inspector@latest
  1. http://localhost:5173 を開きます
  2. MCP サーバーの URL を入力します
  3. 「Connect」をクリックします
  4. 「List Tools」を使用して、利用可能なツールを確認します
  5. パラメーターを指定してツール呼び出しをテストします
Cloudflare にデプロイする
# First time: Login
npx wrangler login

# Deploy
npx wrangler deploy

# Output shows your deployed URL:
# https://my-mcp-server.YOUR_ACCOUNT.workers.dev

# ⚠️ CRITICAL: Update client config with this URL!

# Check deployment logs
npx wrangler tail
Claude Desktop に接続する

~/.config/claude/claude_desktop_config.json(Linux/Mac):

{
  "mcpServers": {
    "my-mcp": {
      "url": "https://my-mcp-server.YOUR_ACCOUNT.workers.dev/sse"
    }
  }
}

%APPDATA%/Claude/claude_desktop_config.json(Windows)

OAuth を使用する場合:

{
  "mcpServers": {
    "my-mcp": {
      "url": "https://my-mcp-oauth.YOUR_ACCOUNT.workers.dev/sse",
      "auth": {
        "type": "oauth",
        "authorizationUrl": "https://my-mcp-oauth.YOUR_ACCOUNT.workers.dev/authorize",
        "tokenUrl": "https://my-mcp-oauth.YOUR_ACCOUNT.workers.dev/token"
      }
    }
  }
}

⚠️ 忘れずに:設定を変更した後は Claude Desktop を再起動してください!


設定リファレンス

完全な wrangler.jsonc(すべての機能)
{
  "name": "my-mcp-server",
  "main": "src/index.ts",
  "compatibility_date": "2025-01-01",
  "compatibility_flags": ["nodejs_compat"],
  "account_id": "YOUR_ACCOUNT_ID",

  "vars": {
    "ENVIRONMENT": "production",
    "GITHUB_CLIENT_ID": "optional-pre-configured-id"
  },

  "kv_namespaces": [
    {
      "binding": "OAUTH_KV",
      "id": "YOUR_KV_ID",
      "preview_id": "YOUR_PREVIEW_KV_ID"
    }
  ],

  "durable_objects": {
    "bindings": [
      {
        "name": "MY_MCP",
        "class_name": "MyMCP",
        "script_name": "my-mcp-server"
      }
    ]
  },

  "migrations": [
    { "tag": "v1", "new_classes": ["MyMCP"] }
  ],

  "node_compat": true
}
完全な package.json

templates/package.json を参照してください

完全な claude_desktop_config.json

templates/claude_desktop_config.json を参照してください


Worker と Durable Objects の基本

単独で使用できる自己完結型のセクションです

Worker のエクスポートパターン

Workers は fetch ハンドラーをエクスポートする必要があります:

export default {
  fetch(request: Request, env: Env, ctx: ExecutionContext): Response | Promise<Response> {
    // Handle request
    return new Response("Hello");
  }
};
Durable Objects のクラス構造

MCP サーバーでは、DO は McpAgent を継承します:

export class MyMCP extends McpAgent<Env> {
  constructor(state: DurableObjectState, env: Env) {
    super(state, env);
  }

  // Your methods here
}
バインディングの設定

環境バインディングを使用すると、Workers からリソースにアクセスできます:

{
  "kv_namespaces": [{ "binding": "MY_KV", "id": "..." }],
  "durable_objects": {
    "bindings": [{ "name": "MY_DO", "class_name": "MyDO" }]
  },
  "r2_buckets": [{ "binding": "MY_BUCKET", "bucket_name": "..." }]
}

コード内でのアクセス:

env.MY_KV.get("key");
env.MY_DO.idFromName("session-123").getStub(env);
env.MY_BUCKET.get("file.txt");

追加リソース

公式ドキュメント
公式サンプル
ツール
このスキルのリソース
  • references/http-transport-fundamentals.md - URL パスとルーティングの詳細解説
  • references/transport-comparison.md - SSE と HTTP の技術的な詳細
  • references/debugging-guide.md - よくある接続の問題と解決策
  • references/authentication.md - 認証パターンの比較
  • references/oauth-providers.md - GitHub、Google、Azure の設定
  • references/common-issues.md - エラーの詳細なトラブルシューティング
  • references/official-examples.md - Cloudflare のサンプルへの厳選リンク

このスキルを使用しない場合

次の場合は、このスキルを使用しないでください:

  • Python の MCP サーバーを構築する場合(代わりに fastmcp スキルを使用してください)
  • ローカル専用の MCP サーバーを構築する場合(代わりに typescript-mcp スキルを使用してください)
  • Cloudflare 以外のホスティング(AWS Lambda、GCP など)が必要な場合
  • Claude.ai のウェブインターフェース用スキルを扱う場合(MCP とは異なります)

このスキルを使用する対象:TypeScript + Cloudflare Workers + リモート MCP


バージョン情報

  • @modelcontextprotocol/sdk: 1.21.0
  • @cloudflare/workers-oauth-provider: 0.0.13
  • agents (Cloudflare Agents SDK): 0.2.20
  • 最終検証日: 2025-11-08

本番環境でのテスト済み:Cloudflare の公式 MCP サーバー(mcp-server-cloudflare、workers-mcp)に基づいています


トークン効率

このスキルを使用しない場合:

  • 散在するドキュメントの調査:約10kトークン
  • URL パスの問題のデバッグ:約15kトークン
  • その他の21件のエラーのデバッグ:約30kトークン
  • 合計:約55kトークン

このスキルを使用する場合:

  • スキルの基本事項を読む:約4kトークン
  • テンプレートをコピーする:約1kトークン
  • クイックリファレンス:約1kトークン
  • 合計:約6kトークン

削減率:約88%(55k → 6k トークン)

防止できるエラー:22件(防止率100%)

コメント