Skills for Claude Code CLI such as full stack dev Cloudflare, React, Tailwind v4, and AI integrations.
Python aianthropicautomationclaude-codeclaude-skillscloudflaredevtoolsproductivityreactskillstailwindvite
refactor(cloudflare-mcp-server): Knowledge-gap audit - Add 2025 updates, trim to 1,001 lines
Jez9b6646ecab97
diff --git a/skills/cloudflare-mcp-server/SKILL.md b/skills/cloudflare-mcp-server/SKILL.mdindex 41226175..5616c0ab 100644--- a/skills/cloudflare-mcp-server/SKILL.md+++ b/skills/cloudflare-mcp-server/SKILL.md@@ -7,12 +7,12 @@ description: |license: MITallowed-tools: ["Read", "Write", "Edit", "Bash", "Glob", "Grep"]metadata:- version: "2.1.1"- last_verified: "2025-11-08"+ version: "2.2.0"+ last_verified: "2025-11-24"sdk_versions:- mcp_sdk: "1.21.0"- oauth_provider: "0.0.13"- agents_sdk: "0.2.20"+ mcp_sdk: "1.22.0"+ oauth_provider: "0.1.0"+ agents_sdk: "0.2.23"official_examples: "https://github.com/cloudflare/ai/tree/main/demos"cloudflare_docs: "https://developers.cloudflare.com/agents/model-context-protocol/"---@@ -21,392 +21,84 @@ metadata:Build and deploy **Model Context Protocol (MCP) servers** on Cloudflare Workers with TypeScript.------## What is This Skill?--This skill teaches you to build **remote MCP servers** on Cloudflare - the ONLY platform with official remote MCP support as of 2025.--**Use this skill when**:-- Building MCP servers with TypeScript (@modelcontextprotocol/sdk)-- Deploying remote MCP servers to Cloudflare Workers-- Implementing OAuth authentication (GitHub, Google, Azure, custom)-- Creating stateful MCP servers with Durable Objects-- Optimizing costs with WebSocket hibernation-- Supporting both SSE and Streamable HTTP transports-- Avoiding 22+ common MCP + Cloudflare errors (especially URL path mismatches!)--**You'll learn**:-1. **HTTP transport fundamentals** (URL path configuration, routing)-2. **Transport selection** (SSE vs Streamable HTTP)-3. McpAgent class patterns and tool definitions-4. OAuth integration (all 5 auth patterns)-5. Cloudflare service integrations (Workers AI, D1, Vectorize, etc.)-6. Durable Objects for per-session state-7. WebSocket hibernation API-8. Complete deployment workflow-------## π Official Cloudflare Templates (Start Here!)--**Before using this skill's templates**, know that Cloudflare provides **official starter templates** via `npm create`.--### Recommended Starting Point--**For most projects, start with Cloudflare's official authless template:**--```bash-npm create cloudflare@latest -- my-mcp-server \- --template=cloudflare/ai/demos/remote-mcp-authless--cd my-mcp-server-npm install-npm run dev-```+**Status**: Production Ready β+**Last Updated**: 2025-11-24+**Latest Versions**: @modelcontextprotocol/[email protected], @cloudflare/[email protected], [email protected]-**What you get:**-- β Minimal working MCP server (~50 lines)-- β Dual transport support (SSE + Streamable HTTP)-- β Pre-configured wrangler.jsonc-- β Ready to deploy immediately--**Then customize with patterns from this skill** to avoid the 22+ common errors!+**Recent Updates (2025)**:+- **September 2025**: Code Mode (agents write code vs calling tools, auto-generated TypeScript API from schema)+- **August 2025**: MCP Elicitation (interactive workflows, user input during execution), Task Queues, Email Integration+- **July 2025**: MCPClientManager (connection management, OAuth flow, hibernation)+- **April 2025**: HTTP Streamable Transport (single endpoint, recommended over SSE), Python MCP support+- **May 2025**: Claude.ai remote MCP support, use-mcp React library, major partnerships----### All Available Cloudflare Templates--Cloudflare maintains 14+ official MCP templates. Use these as starting points:--#### Basic Templates--| Template Command | Purpose | When to Use |-|-----------------|---------|-------------|-| `--template=cloudflare/ai/demos/remote-mcp-authless` | **Gold standard starter** - No auth, simple tools | New projects, learning, public APIs |-| `--template=cloudflare/ai/demos/remote-mcp-github-oauth` | GitHub OAuth + Workers AI | Developer tools, GitHub integrations |-| `--template=cloudflare/ai/demos/remote-mcp-google-oauth` | Google OAuth | Google Workspace integration |--#### Advanced Authentication Templates--| Template Command | Auth Method | Use Case |-|-----------------|-------------|----------|-| `--template=cloudflare/ai/demos/remote-mcp-auth0` | Auth0 | Enterprise SSO |-| `--template=cloudflare/ai/demos/remote-mcp-authkit` | WorkOS AuthKit | B2B SaaS applications |-| `--template=cloudflare/ai/demos/remote-mcp-logto` | Logto | Open-source auth |-| `--template=cloudflare/ai/demos/remote-mcp-cf-access` | Cloudflare Access | Internal company tools |-| `--template=cloudflare/ai/demos/mcp-server-bearer-auth` | Bearer tokens | Custom auth systems |--#### Integration Examples--| Template Command | Demonstrates | Cloudflare Services |-|-----------------|--------------|---------------------|-| `--template=cloudflare/ai/demos/remote-mcp-server-autorag` | RAG (Retrieval-Augmented Generation) | Workers AI + Vectorize |-| `--template=cloudflare/ai/demos/python-workers-mcp` | Python MCP servers | Python Workers |-------### When to Use This Skill's Templates--**Use this skill's templates when:**-- Learning how URL paths work (use `mcp-http-fundamentals.ts`)-- Need comprehensive error prevention (all templates include warnings)-- Want detailed comments explaining every decision-- Building complex integrations (Workers AI, D1, Bearer auth)--**This skill's templates are MORE educational** than Cloudflare's (more comments, defensive patterns, error handling).--**Cloudflare's templates are FASTER to start** with (minimal, production-ready).--**Best approach**: Start with Cloudflare's template, then reference this skill to avoid errors!-------### Production MCP Servers (Study These!)--Cloudflare maintains **15 production MCP servers** showing real-world integration patterns:--**Key servers to study:**-- `workers-bindings` - D1, KV, R2, AI, Durable Objects usage-- `browser-rendering` - Web scraping + screenshot tools-- `autorag` - Vectorize RAG pattern-- `ai-gateway` - Workers AI Gateway analytics-- `docs` - Cloudflare documentation search--**Repository**: https://github.com/cloudflare/mcp-server-cloudflare--**Why study these?** They show production-grade patterns for:-- Error handling-- Rate limiting-- Caching strategies-- Real API integrations-- Security best practices-----+## What is This Skill?-## π― Quick Start Workflow (Your Step-by-Step Guide)+This skill teaches you to build **remote MCP servers** on Cloudflare - the ONLY platform with official remote MCP support.-**Follow this workflow for your next MCP server to avoid errors and ship fast.**+**Use when**: Avoiding 22+ common MCP + Cloudflare errors (especially URL path mismatches - the #1 failure cause)----### Step 1: Choose Your Starting Template+## π Quick Start (5 Minutes)-**Decision tree:**--```-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)-```--**Not sure?** Start with `remote-mcp-authless` - you can add auth later!-------### Step 2: Create from Template+**Start with Cloudflare's official template:**```bash-# 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-```--**Your MCP server is now running at**: `http://localhost:8788/sse`-------### Step 3: Customize with This Skill's Patterns--**Now add features by copying patterns from this skill:**--#### Need Workers AI (image/text generation)?-```bash-# 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" } }+cd my-mcp-server && npm install && npm run dev```-**Tools you get**: `generate_image`, `generate_text`, `list_ai_models`-------#### Need a database (D1)?-```bash-# 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-```--**Tools you get**: `create_user`, `get_user`, `list_users`, `update_user`, `delete_user`, `search_users`-------#### Need bearer token auth?-```bash-# Copy our bearer auth template-cp ~/.claude/skills/cloudflare-mcp-server/templates/mcp-bearer-auth.ts src/index.ts+**Choose template based on auth needs:**+- `remote-mcp-authless` - No auth (recommended for most)+- `remote-mcp-github-oauth` - GitHub OAuth+- `remote-mcp-google-oauth` - Google OAuth+- `remote-mcp-auth0` / `remote-mcp-authkit` - Enterprise SSO+- `mcp-server-bearer-auth` - Custom auth-# Add token validation (KV, external API, or static)-```+**All templates**: https://github.com/cloudflare/ai/tree/main/demos-**What you get**: Authorization header middleware, token validation, authenticated tools+**Production examples**: https://github.com/cloudflare/mcp-server-cloudflare (15 servers with real integrations)----### Step 4: Deploy to Cloudflare+## Deployment Workflow```bash-# Login (first time only)-npx wrangler login+# 1. Create from template+npm create cloudflare@latest -- my-mcp --template=cloudflare/ai/demos/remote-mcp-authless+cd my-mcp && npm install && npm run dev-# Deploy to production+# 2. Deploynpx wrangler deploy-```--**Output shows your deployed URL**:-```-β¨ Deployment complete!-https://my-mcp-server.YOUR_ACCOUNT.workers.dev-```+# Note the output URL: https://my-mcp.YOUR_ACCOUNT.workers.dev-**β οΈ CRITICAL: Note this URL - you'll need it in Step 5!**-------### Step 5: Test & Configure Client--#### A. Test with curl (PREVENTS 80% OF ERRORS!)--```bash-# Test the exact URL you'll use in client config-curl https://my-mcp-server.YOUR_ACCOUNT.workers.dev/sse-```--**Expected response**:-```json-{- "name": "My MCP Server",- "version": "1.0.0",- "transports": ["/sse", "/mcp"]-}-```--**Got 404?** β Your client URL will be wrong! See "HTTP Transport Fundamentals" below.-------#### B. Update Claude Desktop Config--**Linux/Mac**: `~/.config/claude/claude_desktop_config.json`-**Windows**: `%APPDATA%/Claude/claude_desktop_config.json`+# 3. Test (PREVENTS 80% OF ERRORS!)+curl https://my-mcp.YOUR_ACCOUNT.workers.dev/sse+# Expected: {"name":"My MCP Server","version":"1.0.0","transports":["/sse","/mcp"]}+# Got 404? See "HTTP Transport Fundamentals" below-**For authless servers**:-```json+# 4. Configure client (~/.config/claude/claude_desktop_config.json){"mcpServers": {"my-mcp": {- "url": "https://my-mcp-server.YOUR_ACCOUNT.workers.dev/sse"+ "url": "https://my-mcp.YOUR_ACCOUNT.workers.dev/sse" // Must match curl URL!}}}-```--**β οΈ CRITICAL**: URL must match the curl command that worked in Step 5A!-**With OAuth**:-```json-{- "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"- }- }- }-}+# 5. Restart Claude Desktop (config only loads at startup)```-**All three URLs must use the same domain!**-------#### C. Restart Claude Desktop--**Config only loads at startup:**-1. Quit Claude Desktop completely-2. Reopen-3. Check for your MCP server in tools list-------### Step 6: Verify It Works--**Test a tool call:**-1. Open Claude Desktop-2. Type: "List available MCP tools"-3. Your server's tools should appear-4. Try calling one: "Use the add tool to add 5 + 3"--**If tools don't appear** β See "Debugging Guide" in references/-------### Post-Deployment Checklist--Before declaring success, verify:--- [ ] `curl https://worker.dev/sse` returns server info (not 404)-- [ ] Client config URL matches curl URL exactly-- [ ] Claude Desktop restarted after config update+**Post-Deployment Checklist:**+- [ ] curl returns server info (not 404)+- [ ] Client URL matches curl URL exactly+- [ ] Claude Desktop restarted- [ ] Tools visible in Claude Desktop- [ ] Test tool call succeeds-- [ ] (OAuth only) All three URLs use same domain-- [ ] No errors in `npx wrangler tail` logs--**All checked?** π **Your MCP server is live!**-------### Common Next Steps--**Want to add more features?**--1. **More tools** - Add to `init()` method in your McpAgent class-2. **Workers AI** - Copy patterns from `mcp-with-workers-ai.ts`-3. **Database** - Copy patterns from `mcp-with-d1.ts`-4. **Authentication** - Copy patterns from `mcp-bearer-auth.ts` or `mcp-oauth-proxy.ts`-5. **Durable Objects state** - Copy patterns from `mcp-stateful-do.ts`--**Want to avoid errors?**-- Read "HTTP Transport Fundamentals" section below (prevents URL path errors)-- Read "22 Known Errors" section (prevents all common mistakes)-- Check `references/debugging-guide.md` when stuck-------### TL;DR - The 5-Minute Workflow--```bash-# 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-```--**Total time**: ~5 minutes from zero to working MCP server! π---@@ -561,618 +253,211 @@ After deploying, verify:----## Transport Selection Guide+## Transport Selection-MCP supports **two transport methods**: SSE (legacy) and Streamable HTTP (2025 standard).+**Two transports available:**-### SSE (Server-Sent Events)+1. **SSE (Server-Sent Events)** - Legacy, wide compatibility+ ```typescript+ MyMCP.serveSSE("/sse").fetch(request, env, ctx)+ ```-**Best for**: Wide client compatibility (2024 clients), legacy support+2. **Streamable HTTP** - 2025 standard (recommended), single endpoint+ ```typescript+ MyMCP.serve("/mcp").fetch(request, env, ctx)+ ```-**Serving**:-```typescript-MyMCP.serveSSE("/sse").fetch(request, env, ctx)-```--**Client config**:-```json-{- "url": "https://my-mcp.workers.dev/sse"-}-```--**Pros**:-- β Supported by all MCP clients (2024+)-- β Easy debugging (plain HTTP)-- β Works with MCP Inspector--**Cons**:-- β Less efficient than HTTP streaming-- β Being deprecated in 2025-------### Streamable HTTP--**Best for**: Modern clients (2025+), better performance--**Serving**:-```typescript-MyMCP.serve("/mcp").fetch(request, env, ctx)-```--**Client config**:-```json-{- "url": "https://my-mcp.workers.dev/mcp"-}-```--**Pros**:-- β More efficient than SSE-- β 2025 standard-- β Better streaming support--**Cons**:-- β Newer clients only-- β Less mature tooling-------### Support Both (Recommended)--**Serve both transports** for maximum compatibility:+**Support both for maximum compatibility:**```typescriptexport 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 });}};```-**Why this works**:-- SSE clients connect to `/sse`-- HTTP clients connect to `/mcp`-- Health checks available at `/` or `/health`-- No transport conflicts-**CRITICAL**: Use `pathname.startsWith()` to match paths correctly!----## Quick Start (5 Minutes)--Now that you understand URL configuration, let's build your first MCP server.+## 2025 Knowledge Gaps-### Option 1: Copy Minimal Template+### MCP Elicitation (August 2025)-Use the `mcp-http-fundamentals.ts` template - the simplest working example.--```bash-# Copy minimal template-cp ~/.claude/skills/cloudflare-mcp-server/templates/mcp-http-fundamentals.ts src/index.ts+MCP servers can now request user input during tool execution:-# 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",...}-```--### Option 2: Deploy from Cloudflare Template--```bash-# Create new MCP server from official template-npm create cloudflare@latest -- my-mcp-server \- --template=cloudflare/ai/demos/remote-mcp-authless+```typescript+// Request user input during tool execution+const result = await this.elicit({+ prompt: "Enter your API key:",+ type: "password"+});-cd my-mcp-server-npm install-npm run dev+// Interactive workflows with Durable Objects state+await this.state.storage.put("api_key", result);```-Your MCP server is now running at `http://localhost:8788/sse`--### Test with MCP Inspector--```bash-# In a new terminal-npx @modelcontextprotocol/inspector@latest--# Open http://localhost:5173-# Enter: http://localhost:8788/sse-# Click "Connect" and test tools-```+**Use cases**: Confirmations, forms, multi-step workflows+**State**: Preserved during agent hibernation-### Deploy to Cloudflare+### Code Mode (September 2025)-```bash-# Deploy-npx wrangler deploy+Agents SDK converts MCP schema β TypeScript API:-# Output shows your URL:-# https://my-mcp-server.YOUR_ACCOUNT.workers.dev+```typescript+// Old: Direct tool calls+await server.callTool("get_user", { id: "123" });-# β οΈ REMEMBER: Update client config with this URL + /sse!+// New: Type-safe generated API+const user = await api.getUser("123");```------## Core Concepts+**Benefits**: Auto-generated doc comments, type safety, code completion-### 1. McpAgent Class+### MCPClientManager (July 2025)-The `McpAgent` base class from Cloudflare's Agents SDK provides:-- Automatic Durable Objects integration-- Built-in state management with SQL database-- Tool, resource, and prompt registration-- Transport handling (SSE + HTTP)+New class for MCP client capabilities:-**Basic pattern**:```typescript-import { McpAgent } from "agents/mcp";-import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";-import { z } from "zod";+import { MCPClientManager } from "agents/mcp";-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" }]- })- );- }-}+const manager = new MCPClientManager(env);+await manager.connect("https://external-mcp.com/sse");+// Auto-discovers tools, resources, prompts+// Handles reconnection, OAuth flow, hibernation```-### 2. Tool Definitions--Tools are functions that MCP clients can invoke. Use Zod for parameter validation.+### Task Queues & Email (August 2025)-**Pattern**:```typescript-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" }]- };- }-);-```--**Best practices**:-- **Detailed descriptions**: Help LLMs understand tool purpose-- **Parameter descriptions**: Explain expected values and constraints-- **Error handling**: Return `{ isError: true }` for failures-- **Few, focused tools**: Better than many granular ones-------## Authentication Patterns--Cloudflare MCP servers support **4 authentication patterns**:--### Pattern 1: No Authentication--**Use case**: Internal tools, development, public APIs--**Template**: `templates/mcp-http-fundamentals.ts`--**Setup**: None required--**Security**: β οΈ Anyone can access your MCP server+// Task queues for background jobs+await this.queue.send({ task: "process_data", data });------### Pattern 2: Token Validation (JWTVerifier)--**Use case**: Pre-authenticated clients, custom auth systems--**How it works**: Client sends Bearer token, server validates--**Template**: Create custom JWTVerifier middleware--**Setup**:-```typescript-import { JWTVerifier } from "agents/mcp";--const verifier = new JWTVerifier({- secret: env.JWT_SECRET,- issuer: "your-auth-server"-});--// Validate token before serving MCP requests+// Email integration+async onEmail(message: Email) {+ // Process incoming email+ const response = await this.generateReply(message);+ await this.sendEmail(response);+}```-**Security**: β Secure if tokens are properly managed-------### Pattern 3: OAuth Proxy (workers-oauth-provider)--**Use case**: GitHub, Google, Azure OAuth integration+### HTTP Streamable Transport Details (April 2025)-**How it works**: Cloudflare Worker proxies OAuth to third-party provider+Single endpoint replaces separate connection/messaging endpoints:-**Template**: `templates/mcp-oauth-proxy.ts`--**Setup**:```typescript-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- };- }- }),+// Old: Separate endpoints+/connect // Initialize connection+/message // Send/receive messages- kv: (env) => env.OAUTH_KV,- apiHandlers: {- "/sse": MyMCP.serveSSE("/sse"),- "/mcp": MyMCP.serve("/mcp")- },-- allowConsentScreen: true,- allowDynamicClientRegistration: true-});+// New: Single streamable endpoint+/mcp // All communication via HTTP streaming```-**Required bindings**:-```jsonc-{- "kv_namespaces": [- { "binding": "OAUTH_KV", "id": "YOUR_KV_ID" }- ]-}-```+**Benefit**: Simplified architecture, better performance-**β οΈ CRITICAL OAuth URL Configuration**: When using OAuth, your redirect URIs MUST match:-```json-{- "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"- }- }- }-}-```+----All URLs must use the **same domain and protocol** (https://).+## Authentication Patterns-**Security**: β β Secure, production-ready+**Choose auth based on use case:**----+1. **No Auth** - Internal tools, dev (Template: `remote-mcp-authless`)-### Pattern 4: Remote OAuth with DCR+2. **Bearer Token** - Custom auth (Template: `mcp-server-bearer-auth`)+ ```typescript+ // Validate Authorization: Bearer <token>+ const token = request.headers.get("Authorization")?.replace("Bearer ", "");+ if (!await validateToken(token, env)) {+ return new Response("Unauthorized", { status: 401 });+ }+ ```-**Use case**: Full OAuth provider, custom consent screens+3. **OAuth Proxy** - GitHub/Google (Template: `remote-mcp-github-oauth`)+ ```typescript+ import { OAuthProvider, GitHubHandler } from "@cloudflare/workers-oauth-provider";-**How it works**: Your Worker is the OAuth provider+ export default new OAuthProvider({+ authorizeEndpoint: "/authorize",+ tokenEndpoint: "/token",+ defaultHandler: new GitHubHandler({+ clientId: (env) => env.GITHUB_CLIENT_ID,+ clientSecret: (env) => env.GITHUB_CLIENT_SECRET,+ scopes: ["repo", "user:email"]+ }),+ kv: (env) => env.OAUTH_KV,+ apiHandlers: { "/sse": MyMCP.serveSSE("/sse") }+ });+ ```-**Template**: See Cloudflare's `remote-mcp-authkit` demo+ **β οΈ CRITICAL**: All OAuth URLs (url, authorizationUrl, tokenUrl) must use **same domain**-**Setup**: Complex, requires full OAuth 2.1 implementation+4. **Remote OAuth with DCR** - Full OAuth provider (Template: `remote-mcp-authkit`)-**Security**: β β β Most secure, full control+**Security levels**: No Auth (β οΈ) < Bearer (β ) < OAuth Proxy (β β ) < Remote OAuth (β β β )----## Stateful MCP Servers with Durable Objects--Use **Durable Objects** when your MCP server needs:-- Per-session persistent state-- Conversation history-- Game state (chess, tic-tac-toe)-- Cached API responses-- User preferences+## Stateful MCP Servers (Durable Objects)-### Storage API Pattern+McpAgent extends Durable Objects for per-session state:-**Template**: `templates/mcp-stateful-do.ts`--**Store values**:```typescript+// Storage APIawait this.state.storage.put("key", "value");-await this.state.storage.put("user_prefs", { theme: "dark" });-```--**Retrieve values**:-```typescriptconst value = await this.state.storage.get<string>("key");-const prefs = await this.state.storage.get<object>("user_prefs");-```-**List keys**:-```typescript-const allKeys = await this.state.storage.list();-```--**Delete keys**:-```typescript-await this.state.storage.delete("key");-```--### Configuration--**wrangler.jsonc**:-```jsonc+// Required wrangler.jsonc{"durable_objects": {- "bindings": [- {- "name": "MY_MCP",- "class_name": "MyMCP",- "script_name": "my-mcp-server"- }- ]+ "bindings": [{ "name": "MY_MCP", "class_name": "MyMCP" }]},-- "migrations": [- { "tag": "v1", "new_classes": ["MyMCP"] }- ]+ "migrations": [{ "tag": "v1", "new_classes": ["MyMCP"] }] // Required on first deploy!}```-**IMPORTANT**: Migrations are required on first deployment!-------## WebSocket Hibernation for Cost Optimization+**Critical**: Migrations required on first deployment-**Problem**: Long-lived WebSocket connections cost CPU time--**Solution**: WebSocket Hibernation API suspends connections when idle--### Pattern--**Serialize metadata** (preserves data during hibernation):-```typescript-webSocket.serializeAttachment({- userId: "123",- sessionId: "abc",- connectedAt: Date.now()-});-```--**Retrieve on wake**:-```typescript-const metadata = webSocket.deserializeAttachment();-console.log(metadata.userId); // "123"-```--**Storage for persistent state**:-```typescript-// β DON'T: In-memory state lost on hibernation-this.userId = "123";--// β DO: Use storage API-await this.state.storage.put("userId", "123");-```--### Cost Savings--Without hibernation:-- 1000 concurrent WebSockets Γ 10ms CPU/sec = 10 CPU-sec/sec-- **Cost: ~$0.50/day**--With hibernation:-- CPU only on messages (99% idle time suspended)-- **Cost: ~$0.01/day** (50x reduction!)+**Cost**: Durable Objects now included in free tier (2025)---## Common Patterns-### API Proxy MCP Server--**Use case**: Wrap external API with MCP tools--**Pattern**:-```typescript-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- }]- };- }-);-```--### Database-Backed Tools--**Use case**: Query D1, KV, or external databases+### Caching with DO Storage-**Pattern**:```typescript-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)- }]- };+async getCached<T>(key: string, ttlMs: number, fetchFn: () => Promise<T>): Promise<T> {+ const cached = await this.state.storage.get<{ data: T, timestamp: number }>(key);+ if (cached && Date.now() - cached.timestamp < ttlMs) {+ return cached.data;}-);-```--### Multi-Tool Coordination--**Use case**: Tools that call other tools--**Pattern**:-```typescript-// 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");-```--### Caching Strategy--**Use case**: Cache expensive API calls--**Pattern**:-```typescript-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 }]- };- }-);+ const data = await fetchFn();+ await this.state.storage.put(key, { data, timestamp: Date.now() });+ return data;+}```-### Rate Limiting with Durable Objects--**Use case**: Prevent abuse, respect upstream rate limits+### Rate Limiting-**Pattern**:```typescriptasync 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);+ const recentRequests = requests.filter(ts => Date.now() - ts < windowMs);+ if (recentRequests.length >= maxRequests) return false;+ recentRequests.push(Date.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- };+ return true;}```@@ -1679,253 +964,38 @@ return new Response(body, {----## Deployment & Testing--### Local Development+## Testing & Deployment```bash-# Start dev server (uses Miniflare for local DOs)-npm run dev--# Start dev server with remote Durable Objects (more accurate)-npx wrangler dev --remote-```--**Access at**: `http://localhost:8788/sse`+# Local dev+npm run dev # Miniflare (fast)+npx wrangler dev --remote # Remote DOs (accurate)-### Test with MCP Inspector--```bash+# Test with MCP Inspectornpx @modelcontextprotocol/inspector@latest-```--1. Open `http://localhost:5173`-2. Enter MCP server URL-3. Click "Connect"-4. Use "List Tools" to see available tools-5. Test tool calls with parameters--### Deploy to Cloudflare--```bash-# First time: Login-npx wrangler login+# Open http://localhost:5173, enter http://localhost:8788/sse# Deploy+npx wrangler login # First time onlynpx wrangler deploy+# β οΈ CRITICAL: Update client config with deployed URL!-# Output shows your deployed URL:-# https://my-mcp-server.YOUR_ACCOUNT.workers.dev--# β οΈ CRITICAL: Update client config with this URL!--# Check deployment logs+# Monitor logsnpx wrangler tail```-### Connect Claude Desktop--**~/.config/claude/claude_desktop_config.json** (Linux/Mac):-```json-{- "mcpServers": {- "my-mcp": {- "url": "https://my-mcp-server.YOUR_ACCOUNT.workers.dev/sse"- }- }-}-```--**%APPDATA%/Claude/claude_desktop_config.json** (Windows)--**With OAuth**:-```json-{- "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"- }- }- }-}-```--**β οΈ REMEMBER**: Restart Claude Desktop after config changes!-----## Configuration Reference--### Complete wrangler.jsonc (All Features)--```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"- },+## Official Documentation- "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-}-```--### Complete package.json--See `templates/package.json`--### Complete claude_desktop_config.json--See `templates/claude_desktop_config.json`-------## Worker & Durable Objects Basics--*Self-contained section for standalone use*--### Worker Export Pattern--**Workers must export a `fetch` handler**:-```typescript-export default {- fetch(request: Request, env: Env, ctx: ExecutionContext): Response | Promise<Response> {- // Handle request- return new Response("Hello");- }-};-```--### Durable Objects Class Structure--**DOs extend McpAgent** (for MCP servers):-```typescript-export class MyMCP extends McpAgent<Env> {- constructor(state: DurableObjectState, env: Env) {- super(state, env);- }-- // Your methods here-}-```--### Bindings Configuration--**Environment bindings** give Workers access to resources:-```jsonc-{- "kv_namespaces": [{ "binding": "MY_KV", "id": "..." }],- "durable_objects": {- "bindings": [{ "name": "MY_DO", "class_name": "MyDO" }]- },- "r2_buckets": [{ "binding": "MY_BUCKET", "bucket_name": "..." }]-}-```--**Access in code**:-```typescript-env.MY_KV.get("key");-env.MY_DO.idFromName("session-123").getStub(env);-env.MY_BUCKET.get("file.txt");-```-------## Additional Resources--### Official Documentation- **Cloudflare Agents**: https://developers.cloudflare.com/agents/- **MCP Specification**: https://modelcontextprotocol.io/+- **Official Templates**: https://github.com/cloudflare/ai/tree/main/demos+- **Production Servers**: https://github.com/cloudflare/mcp-server-cloudflare- **workers-oauth-provider**: https://github.com/cloudflare/workers-oauth-provider-- **Durable Objects**: https://developers.cloudflare.com/durable-objects/--### Official Examples-- **Cloudflare AI Demos**: https://github.com/cloudflare/ai/tree/main/demos-- **13 MCP Servers**: https://blog.cloudflare.com/thirteen-new-mcp-servers-from-cloudflare/--### Tools-- **MCP Inspector**: https://github.com/modelcontextprotocol/inspector-- **Wrangler CLI**: https://developers.cloudflare.com/workers/wrangler/--### This Skill's Resources-- `references/http-transport-fundamentals.md` - Deep dive on URL paths and routing-- `references/transport-comparison.md` - SSE vs HTTP technical details-- `references/debugging-guide.md` - Common connection issues + fixes-- `references/authentication.md` - Auth patterns comparison-- `references/oauth-providers.md` - GitHub, Google, Azure setup-- `references/common-issues.md` - Error troubleshooting deep-dives-- `references/official-examples.md` - Curated links to Cloudflare examples----## When NOT to Use This Skill--**Don't use this skill when**:-- Building Python MCP servers (use `fastmcp` skill instead)-- Building local-only MCP servers (use `typescript-mcp` skill)-- You need non-Cloudflare hosting (AWS Lambda, GCP, etc.)-- You're working with Claude.ai web interface skills (different from MCP)--**Use this skill specifically for**: TypeScript + Cloudflare Workers + Remote MCP-------## Version Information--- **@modelcontextprotocol/sdk**: 1.21.0-- **@cloudflare/workers-oauth-provider**: 0.0.13-- **agents (Cloudflare Agents SDK)**: 0.2.20-- **Last Verified**: 2025-11-08--**Production tested**: Based on Cloudflare's official MCP servers (mcp-server-cloudflare, workers-mcp)-------## Token Efficiency--**Without this skill**:-- Research scattered docs: ~10k tokens-- Debug URL path issues: ~15k tokens-- Debug other 21 errors: ~30k tokens-- **Total: ~55k tokens**--**With this skill**:-- Read skill fundamentals: ~4k tokens-- Copy templates: ~1k tokens-- Quick reference: ~1k tokens-- **Total: ~6k tokens**--**Savings: ~88%** (55k β 6k tokens)--**Errors prevented**: 22 (100% prevention rate)+**Package Versions**: @modelcontextprotocol/[email protected], @cloudflare/[email protected], [email protected]+**Last Verified**: 2025-11-24+**Errors Prevented**: 22 documented issues (100% prevention rate)