Skills for Claude Code CLI such as full stack dev Cloudflare, React, Tailwind v4, and AI integrations.
Python aianthropicautomationclaude-codeclaude-skillscloudflaredevtoolsproductivityreactskillstailwindvite
Major rewrite: cloudflare-mcp-server skill v2.0 - HTTP transport fundamentals
Jez40bfddd4cb33
diff --git a/skills/cloudflare-mcp-server/.claude-plugin/plugin.json b/skills/cloudflare-mcp-server/.claude-plugin/plugin.jsonindex 62427dc7..1fbf637c 100644--- a/skills/cloudflare-mcp-server/.claude-plugin/plugin.json+++ b/skills/cloudflare-mcp-server/.claude-plugin/plugin.json@@ -1,7 +1,7 @@{"name": "cloudflare-mcp-server",- "description": "Use this skill when building Model Context Protocol (MCP) servers on Cloudflare Workers. This skill should be used when deploying remote MCP servers with TypeScript, implementing OAuth authentication (GitHub, Google, Azure, etc.), using Durable Objects for stateful MCP servers, implementing WebSocket hibernation for cost optimization, or configuring dual transport methods (SSE + Streamable HTTP). The skill prevents 15+ common errors including McpAgent class export issues, OAuth redirect URI mism",- "version": "1.0.0",+ "description": "Use this skill when building Model Context Protocol (MCP) servers on Cloudflare Workers. This skill should be used when deploying remote MCP servers with TypeScript, implementing OAuth authentication (GitHub, Google, Azure, etc.), using Durable Objects for stateful MCP servers, implementing WebSocket hibernation for cost optimization, or configuring dual transport methods (SSE + Streamable HTTP). The skill prevents 22+ common errors including URL path mismatches, transport configuration mistakes",+ "version": "2.0.0","author": {"name": "Jeremy Dawes","email": "[email protected]"diff --git a/skills/cloudflare-mcp-server/README.md b/skills/cloudflare-mcp-server/README.mdindex 4e721c33..a434f0fb 100644--- a/skills/cloudflare-mcp-server/README.md+++ b/skills/cloudflare-mcp-server/README.md@@ -8,7 +8,91 @@A production-ready skill for **Claude Code CLI** that teaches you to build MCP servers on Cloudflare - the ONLY platform with official remote MCP support (as of 2025).-**Version**: 1.0.0 | **Last Verified**: 2025-11-04+**Version**: 2.0.0 | **Last Verified**: 2025-11-08++---++## ⚠️ Common Mistakes (Read This First!)++**The #1 reason MCP servers fail to connect: URL path mismatches**++### Mistake 1: Missing `/sse` in Client URL++**Server code:**+```typescript+MyMCP.serveSSE("/sse").fetch(request, env, ctx)+```++**Client config (WRONG):**+```json+"url": "https://my-mcp.workers.dev" // ❌ Missing /sse!+```++**Client config (CORRECT):**+```json+"url": "https://my-mcp.workers.dev/sse" // ✅ Include /sse+```++**Result:** 404 Not Found → Connection fails++---++### Mistake 2: Localhost URL After Deployment++**Client config (WRONG after deployment):**+```json+"url": "http://localhost:8788/sse" // ❌ Worker is deployed!+```++**Client config (CORRECT):**+```json+"url": "https://my-mcp.YOUR_ACCOUNT.workers.dev/sse" // ✅ Use deployed URL+```++**Always update config after `npx wrangler deploy`!**++---++### Mistake 3: OAuth URLs Don't Match++**Client config (WRONG - mixed domains):**+```json+{+ "url": "https://my-mcp.workers.dev/sse",+ "auth": {+ "authorizationUrl": "http://localhost:8788/authorize", // ❌ localhost!+ "tokenUrl": "https://my-mcp.workers.dev/token"+ }+}+```++**Client config (CORRECT - all match):**+```json+{+ "url": "https://my-mcp.workers.dev/sse",+ "auth": {+ "authorizationUrl": "https://my-mcp.workers.dev/authorize", // ✅ Same domain+ "tokenUrl": "https://my-mcp.workers.dev/token" // ✅ Same protocol+ }+}+```++**ALL OAuth URLs must use the same domain and protocol!**++---++### Quick Fix Checklist++Before asking for help, verify:++- [ ] Deployed Worker: `npx wrangler deploy` succeeded+- [ ] Worker running: `curl https://worker.dev/` returns something+- [ ] MCP endpoint: `curl https://worker.dev/sse` returns server info (not 404!)+- [ ] Client URL matches curl test above+- [ ] If using OAuth: All URLs match deployed domain+- [ ] Restarted Claude Desktop after config changes++**Still stuck?** See `references/debugging-guide.md` for complete troubleshooting.---diff --git a/skills/cloudflare-mcp-server/SKILL.md b/skills/cloudflare-mcp-server/SKILL.mdindex a7369f70..dbb9049e 100644--- a/skills/cloudflare-mcp-server/SKILL.md+++ b/skills/cloudflare-mcp-server/SKILL.md@@ -1,14 +1,14 @@---name: cloudflare-mcp-serverdescription: |- Use this skill when building Model Context Protocol (MCP) servers on Cloudflare Workers. This skill should be used when deploying remote MCP servers with TypeScript, implementing OAuth authentication (GitHub, Google, Azure, etc.), using Durable Objects for stateful MCP servers, implementing WebSocket hibernation for cost optimization, or configuring dual transport methods (SSE + Streamable HTTP). The skill prevents 15+ common errors including McpAgent class export issues, OAuth redirect URI mismatches, WebSocket state loss, Durable Objects binding errors, and CORS configuration mistakes. Includes production-tested templates for basic MCP servers, OAuth proxy integration, stateful servers with Durable Objects, and complete wrangler.jsonc configurations. Covers all 4 authentication patterns: token validation, remote OAuth with DCR, OAuth proxy (workers-oauth-provider), and full OAuth provider implementation. Self-contained with Worker and Durable Objects basics. Token efficiency: ~87% savings (40k → 5k tokens). Production tested on Cloudflare's official MCP servers.+ Use this skill when building Model Context Protocol (MCP) servers on Cloudflare Workers. This skill should be used when deploying remote MCP servers with TypeScript, implementing OAuth authentication (GitHub, Google, Azure, etc.), using Durable Objects for stateful MCP servers, implementing WebSocket hibernation for cost optimization, or configuring dual transport methods (SSE + Streamable HTTP). The skill prevents 22+ common errors including URL path mismatches, transport configuration mistakes, McpAgent class export issues, OAuth redirect URI mismatches, WebSocket state loss, Durable Objects binding errors, and CORS configuration mistakes. Includes production-tested templates for basic MCP servers, OAuth proxy integration, stateful servers with Durable Objects, and complete wrangler.jsonc configurations. Covers all 4 authentication patterns: token validation, remote OAuth with DCR, OAuth proxy (workers-oauth-provider), and full OAuth provider implementation. Self-contained with Worker and Durable Objects basics. Token efficiency: ~88% savings (55k → 6k tokens). Production tested on Cloudflare's official MCP servers.- Keywords: MCP server, Model Context Protocol, cloudflare mcp, mcp workers, remote mcp server, mcp typescript, @modelcontextprotocol/sdk, mcp oauth, mcp authentication, github oauth mcp, durable objects mcp, websocket hibernation, mcp sse, streamable http, McpAgent class, mcp tools, mcp resources, mcp prompts, oauth proxy, workers-oauth-provider, mcp deployment, McpAgent export error, OAuth redirect URI, WebSocket state loss, mcp cors, mcp dcr+ Keywords: MCP server, Model Context Protocol, cloudflare mcp, mcp workers, remote mcp server, mcp typescript, @modelcontextprotocol/sdk, mcp oauth, mcp authentication, github oauth mcp, durable objects mcp, websocket hibernation, mcp sse, streamable http, McpAgent class, mcp tools, mcp resources, mcp prompts, oauth proxy, workers-oauth-provider, mcp deployment, McpAgent export error, OAuth redirect URI, WebSocket state loss, mcp cors, mcp dcr, URL path configuration, HTTP transport setup, SSE routing, base path mismatches, transport endpoints, MCP connection errors, pathname.startsWith(), transport type confusion, CORS preflight, OPTIONS handlerlicense: MITallowed-tools: ["Read", "Write", "Edit", "Bash", "Glob", "Grep"]metadata:- version: "1.0.0"- last_verified: "2025-11-04"+ version: "2.0.0"+ last_verified: "2025-11-08"sdk_versions:mcp_sdk: "1.21.0"oauth_provider: "0.0.13"@@ -34,68 +34,340 @@ This skill teaches you to build **remote MCP servers** on Cloudflare - the ONLY- Creating stateful MCP servers with Durable Objects- Optimizing costs with WebSocket hibernation- Supporting both SSE and Streamable HTTP transports-- Avoiding 15+ common MCP + Cloudflare errors+- Avoiding 22+ common MCP + Cloudflare errors (especially URL path mismatches!)**You'll learn**:-1. McpAgent class patterns and tool definitions-2. OAuth integration (all 4 auth patterns)-3. Durable Objects for per-session state-4. WebSocket hibernation API-5. Dual transport configuration (SSE + HTTP)-6. Complete deployment workflow+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 4 auth patterns)+5. Durable Objects for per-session state+6. WebSocket hibernation API+7. Complete deployment workflow----## Quick Start (5 Minutes)+## ⚠️ CRITICAL: HTTP Transport Fundamentals++**The #1 reason MCP servers fail to connect is URL path configuration mistakes.**++### URL Path Configuration Deep-Dive++When you serve an MCP server at a specific path, **the client URL must match exactly**.++**Example 1: Serving at `/sse`**+```typescript+// 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 });+ }+};+```++**Client configuration MUST include `/sse`**:+```json+{+ "mcpServers": {+ "my-mcp": {+ "url": "https://my-mcp.workers.dev/sse" // ✅ Correct+ }+ }+}+```++**❌ WRONG client configurations**:+```json+"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+```++---++**Example 2: Serving at `/` (root)**+```typescript+export default {+ fetch(request: Request, env: Env, ctx: ExecutionContext) {+ return MyMCP.serveSSE("/").fetch(request, env, ctx); // ← Base path is "/"+ }+};+```++**Client configuration**:+```json+{+ "mcpServers": {+ "my-mcp": {+ "url": "https://my-mcp.workers.dev" // ✅ Correct (no /sse)+ }+ }+}+```++---++### How Base Path Affects Tool URLs++**When you call `serveSSE("/sse")`**, MCP tools are served at:+```+https://my-mcp.workers.dev/sse/tools/list+https://my-mcp.workers.dev/sse/tools/call+https://my-mcp.workers.dev/sse/resources/list+```++**When you call `serveSSE("/")`**, MCP tools are served at:+```+https://my-mcp.workers.dev/tools/list+https://my-mcp.workers.dev/tools/call+https://my-mcp.workers.dev/resources/list+```++**The base path is prepended to all MCP endpoints automatically.**++---++### Request/Response Lifecycle++```+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+```++**If client connects to `https://my-mcp.workers.dev`** (missing `/sse`):+```+pathname === "/" → Check fails → 404 Not Found+```++----### Option 1: Deploy from Template+### Testing Your URL Configuration+**Step 1: Deploy your MCP server**```bash-# Create new MCP server from Cloudflare template-npm create cloudflare@latest -- my-mcp-server \- --template=cloudflare/ai/demos/remote-mcp-authless+npx wrangler deploy+# Output: Deployed to https://my-mcp.YOUR_ACCOUNT.workers.dev+```-cd my-mcp-server-npm install-npm run dev+**Step 2: Test the base path with curl**+```bash+# If serving at /sse, test this URL:+curl https://my-mcp.YOUR_ACCOUNT.workers.dev/sse++# Should return MCP server info (not 404)```-Your MCP server is now running at `http://localhost:8788/sse`+**Step 3: Update client config with the EXACT URL you tested**+```json+{+ "mcpServers": {+ "my-mcp": {+ "url": "https://my-mcp.YOUR_ACCOUNT.workers.dev/sse" // Match curl URL+ }+ }+}+```++**Step 4: Restart Claude Desktop**++---++### Post-Deployment Checklist++After deploying, verify:+- [ ] `curl https://worker.dev/sse` returns MCP server info (not 404)+- [ ] Client config URL matches deployed URL exactly+- [ ] No typos in URL (common: `workes.dev` instead of `workers.dev`)+- [ ] Using `https://` (not `http://`) for deployed Workers+- [ ] If using OAuth, redirect URI also updated++---++## Transport Selection Guide++MCP supports **two transport methods**: SSE (legacy) and Streamable HTTP (2025 standard).++### SSE (Server-Sent Events)++**Best for**: Wide client compatibility (2024 clients), legacy support++**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:++```typescript+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 });+ }+};+```++**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.-### Option 2: Copy Templates from This Skill+### Option 1: Copy Minimal Template++Use the `mcp-http-fundamentals.ts` template - the simplest working example.```bash-# Copy basic MCP server template-cp ~/.claude/skills/cloudflare-mcp-server/templates/basic-mcp-server.ts src/index.ts-cp ~/.claude/skills/cloudflare-mcp-server/templates/wrangler-basic.jsonc wrangler.jsonc-cp ~/.claude/skills/cloudflare-mcp-server/templates/package.json package.json+# Copy minimal template+cp ~/.claude/skills/cloudflare-mcp-server/templates/mcp-http-fundamentals.ts src/index.ts# Install dependenciesnpm install-# Start development server+# 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++cd my-mcp-server+npm installnpm run dev```+Your MCP server is now running at `http://localhost:8788/sse`+### Test with MCP Inspector```bash-# In a new terminal, start MCP Inspector+# In a new terminalnpx @modelcontextprotocol/inspector@latest# Open http://localhost:5173-# Enter your MCP server URL: http://localhost:8788/sse+# Enter: http://localhost:8788/sse# Click "Connect" and test tools```### Deploy to Cloudflare```bash-# Deploy to production+# Deploynpx wrangler deploy-# Your MCP server is now live at:-# https://my-mcp-server.your-account.workers.dev/sse+# Output shows your URL:+# https://my-mcp-server.YOUR_ACCOUNT.workers.dev++# ⚠️ REMEMBER: Update client config with this URL + /sse!```---@@ -164,38 +436,6 @@ this.server.tool(- **Error handling**: Return `{ isError: true }` for failures- **Few, focused tools**: Better than many granular ones-### 3. Transport Methods--MCP supports two transports:--**SSE (Server-Sent Events)** - Legacy, widely supported:-```typescript-MyMCP.serveSSE("/sse").fetch(request, env, ctx)-```--**Streamable HTTP** - 2025 standard, more efficient:-```typescript-MyMCP.serve("/mcp").fetch(request, env, ctx)-```--**Support both** for maximum compatibility:-```typescript-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);- }- if (pathname.startsWith("/mcp")) {- return MyMCP.serve("/mcp").fetch(request, env, ctx);- }-- return new Response("Not Found", { status: 404 });- }-};-```----## Authentication Patterns@@ -206,7 +446,7 @@ Cloudflare MCP servers support **4 authentication patterns**:**Use case**: Internal tools, development, public APIs-**Template**: `templates/basic-mcp-server.ts`+**Template**: `templates/mcp-http-fundamentals.ts`**Setup**: None required@@ -293,6 +533,24 @@ export default new OAuthProvider({}```+**⚠️ 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://).+**Security**: ✅✅ Secure, production-ready---@@ -415,165 +673,35 @@ With hibernation:----## Worker & Durable Objects Basics+## Common Patterns-*Self-contained section for standalone use*+### API Proxy MCP Server-### Worker Export Pattern+**Use case**: Wrap external API with MCP tools-**Workers must export a `fetch` handler**:+**Pattern**:```typescript-export default {- fetch(request: Request, env: Env, ctx: ExecutionContext): Response | Promise<Response> {- // Handle request- return new Response("Hello");- }-};-```--### Durable Objects Class Structure+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();-**DOs extend McpAgent** (for MCP servers):-```typescript-export class MyMCP extends McpAgent<Env> {- constructor(state: DurableObjectState, env: Env) {- super(state, env);+ return {+ content: [{+ type: "text",+ text: data.extract+ }]+ };}-- // 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");-```-------## Deployment & Testing--### Local Development--```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`--### Test with MCP Inspector--```bash-npx @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--# Deploy-npx wrangler deploy--# Check deployment-npx wrangler tail-```--**Your server is live at**:-```-https://my-mcp-server.YOUR_ACCOUNT.workers.dev/sse-```--### 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"- }- }- }-}-```--Restart Claude Desktop after config changes.-------## 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+### Database-Backed Tools**Use case**: Query D1, KV, or external databases@@ -687,7 +815,7 @@ if (!await this.rateLimit(userId, 10, 60 * 1000)) {----## 15 Known Errors (With Solutions)+## 22 Known Errors (With Solutions)### 1. McpAgent Class Not Exported@@ -703,47 +831,304 @@ export default { fetch() { ... } }----### 2. Transport Mismatch+### 2. Base Path Configuration Mismatch (Most Common!)++**Error**: `404 Not Found` or `Connection failed`++**Cause**: `serveSSE("/sse")` but client configured with `https://worker.dev` (missing `/sse`)++**Solution**: Match base paths exactly+```typescript+// Server serves at /sse+MyMCP.serveSSE("/sse").fetch(...)++// Client MUST include /sse+{ "url": "https://worker.dev/sse" } // ✅ Correct+{ "url": "https://worker.dev" } // ❌ Wrong - 404+```++**Debug steps**:+1. Check what path your server uses: `serveSSE("/sse")` vs `serveSSE("/")`+2. Test with curl: `curl https://worker.dev/sse`+3. Update client config to match curl URL++---++### 3. Transport Type Confusion**Error**: `Connection failed: Unexpected response format`-**Cause**: Client expects `/sse` but server only serves `/mcp`+**Cause**: Client expects SSE but connects to HTTP endpoint (or vice versa)-**Solution**: Serve both transports (see Transport Methods section)+**Solution**: Match transport types+```typescript+// SSE transport+MyMCP.serveSSE("/sse") // Client URL: https://worker.dev/sse++// HTTP transport+MyMCP.serve("/mcp") // Client URL: https://worker.dev/mcp+```++**Best practice**: Support both transports (see Transport Selection Guide)----### 3. OAuth Redirect URI Mismatch+### 4. pathname.startsWith() Logic Error++**Error**: Both `/sse` and `/mcp` routes fail or conflict++**Cause**: Incorrect path matching logic++**Solution**: Use `startsWith()` correctly+```typescript+// ✅ 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. Local vs Deployed URL Mismatch++**Error**: Works in dev, fails after deployment++**Cause**: Client still configured with localhost URL++**Solution**: Update client config after deployment+```json+// Development+{ "url": "http://localhost:8788/sse" }++// ⚠️ MUST UPDATE after npx wrangler deploy+{ "url": "https://my-mcp.YOUR_ACCOUNT.workers.dev/sse" }+```++**Post-deployment checklist**:+- [ ] Run `npx wrangler deploy` and note output URL+- [ ] Update client config with deployed URL+- [ ] Test with curl+- [ ] Restart Claude Desktop++---++### 6. OAuth Redirect URI Mismatch**Error**: `OAuth error: redirect_uri does not match`-**Cause**: Client configured with localhost, but deployed to workers.dev+**Cause**: OAuth redirect URI doesn't match deployed URL++**Solution**: Update ALL OAuth URLs after deployment+```json+{+ "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"+ }+}+```++**CRITICAL**: All URLs must use the same protocol and domain!++---++### 7. Missing OPTIONS Handler (CORS Preflight)++**Error**: `Access to fetch at '...' blocked by CORS policy` or `Method Not Allowed`++**Cause**: Browser clients send OPTIONS requests for CORS preflight, but server doesn't handle them++**Solution**: Add OPTIONS handler+```typescript+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+ }+};+```++**When needed**: Browser-based MCP clients (like MCP Inspector in browser)++---++### 8. Request Body Validation Missing++**Error**: `TypeError: Cannot read properties of undefined` or `Unexpected token` in JSON parsing++**Cause**: Client sends malformed JSON, server doesn't validate before parsing++**Solution**: Wrap request handling in try/catch+```typescript+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. Environment Variable Validation Missing++**Error**: `TypeError: env.API_KEY is undefined` or silent failures (tools return empty data)++**Cause**: Required environment variables not configured or missing at runtime++**Solution**: Add startup validation+```typescript+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(...);+ }+}+```++**Configuration checklist**:+- Development: Add to `.dev.vars` (local only, gitignored)+- Production: Add to `wrangler.jsonc` `vars` (public) or use `wrangler secret` (sensitive)++**Best practices**:+```bash+# .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 vs McpServer Confusion++**Error**: `TypeError: server.registerTool is not a function` or `this.server is undefined`++**Cause**: Trying to use standalone SDK patterns with McpAgent class++**Solution**: Use McpAgent's `this.server.tool()` pattern+```typescript+// ❌ 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+ }+}+```-**Solution**: Update claude_desktop_config.json after deployment+**Key difference**: McpAgent provides `this.server` property, standalone SDK doesn't.----### 4. WebSocket Hibernation State Loss+### 11. WebSocket Hibernation State Loss**Error**: Tool calls fail after reconnect with "state not found"**Cause**: In-memory state cleared on hibernation**Solution**: Use `this.state.storage` instead of instance properties+```typescript+// ❌ DON'T: Lost on hibernation+this.userId = "123";++// ✅ DO: Persists through hibernation+await this.state.storage.put("userId", "123");+```----### 5. Durable Objects Binding Missing+### 12. Durable Objects Binding Missing-**Error**: `Error: Cannot read properties of undefined (reading 'idFromName')`+**Error**: `TypeError: Cannot read properties of undefined (reading 'idFromName')`**Cause**: Forgot DO binding in wrangler.jsonc**Solution**: Add binding (see Stateful MCP Servers section)+```jsonc+{+ "durable_objects": {+ "bindings": [+ {+ "name": "MY_MCP",+ "class_name": "MyMCP",+ "script_name": "my-mcp-server"+ }+ ]+ }+}+```----### 6. Migration Not Defined+### 13. Migration Not Defined**Error**: `Error: Durable Object class MyMCP has no migration defined`@@ -760,100 +1145,253 @@ export default { fetch() { ... } }----### 7. CORS Errors on Remote MCP+### 14. serializeAttachment() Not Used-**Error**: `Access to fetch at '...' blocked by CORS policy`+**Error**: WebSocket metadata lost on hibernation wake-**Cause**: MCP server doesn't return CORS headers+**Cause**: Not using `serializeAttachment()` to preserve connection metadata-**Solution**: Use OAuthProvider (handles CORS) or add headers manually+**Solution**: See WebSocket Hibernation section----### 8. Client Configuration Format Error+### 15. OAuth Consent Screen Disabled-**Error**: Claude Desktop doesn't recognize server+**Security risk**: Users don't see what permissions they're granting-**Cause**: Wrong JSON format in claude_desktop_config.json+**Cause**: `allowConsentScreen: false` in production-**Solution**: See "Connect Claude Desktop" section for correct format+**Solution**: Always enable in production+```typescript+export default new OAuthProvider({+ allowConsentScreen: true, // ✅ Always true in production+ // ...+});+```----### 9. serializeAttachment() Not Used+### 16. JWT Signing Key Missing-**Error**: WebSocket metadata lost on hibernation wake+**Error**: `Error: JWT_SIGNING_KEY environment variable not set`-**Cause**: Not using serializeAttachment()+**Cause**: OAuth Provider requires signing key for tokens-**Solution**: See WebSocket Hibernation section+**Solution**:+```bash+# Generate secure key+openssl rand -base64 32++# Add to wrangler secret+npx wrangler secret put JWT_SIGNING_KEY+```----### 10. OAuth Consent Screen Disabled+### 17. Tool Schema Validation Error-**Security risk**: Users don't see permissions+**Error**: `ZodError: Invalid input type`-**Cause**: `allowConsentScreen: false` in production+**Cause**: Client sends string, schema expects number (or vice versa)-**Solution**: Always set `allowConsentScreen: true` in production+**Solution**: Use Zod transforms+```typescript+// 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+)+```----### 11. JWT Signing Key Missing+### 18. Multiple Transport Endpoints Conflicting-**Error**: `Error: JWT_SIGNING_KEY environment variable not set`+**Error**: `/sse` returns 404 after adding `/mcp`-**Cause**: OAuth Provider requires signing key+**Cause**: Incorrect path matching (missing `startsWith()`)-**Solution**:+**Solution**: Use `startsWith()` or exact matches correctly (see Error #4)++---++### 19. Local Testing with Miniflare Limitations++**Error**: OAuth flow fails in local dev, or Durable Objects behave differently++**Cause**: Miniflare doesn't support all DO features++**Solution**: Use `npx wrangler dev --remote` for full DO support```bash-openssl rand -base64 32-# Add to wrangler.jsonc vars+# Local simulation (faster but limited)+npm run dev++# Remote DOs (slower but accurate)+npx wrangler dev --remote```----### 12. Environment Variables Not Configured+### 20. Client Configuration Format Error-**Error**: `env.MY_VAR is undefined`+**Error**: Claude Desktop doesn't recognize server-**Cause**: Variables in `.dev.vars` but not in wrangler.jsonc+**Cause**: Wrong JSON format in `claude_desktop_config.json`++**Solution**: See "Connect Claude Desktop" section for correct format++**Common mistakes**:+```json+// ❌ WRONG: Missing "mcpServers" wrapper+{+ "my-mcp": {+ "url": "https://worker.dev/sse"+ }+}-**Solution**: Add to `"vars"` section in wrangler.jsonc+// ❌ WRONG: Trailing comma+{+ "mcpServers": {+ "my-mcp": {+ "url": "https://worker.dev/sse", // ← Remove comma+ }+ }+}++// ✅ CORRECT+{+ "mcpServers": {+ "my-mcp": {+ "url": "https://worker.dev/sse"+ }+ }+}+```----### 13. Tool Schema Validation Error+### 21. Health Check Endpoint Missing-**Error**: `ZodError: Invalid input type`+**Issue**: Can't tell if Worker is running or if URL is correct-**Cause**: Client sends string, schema expects number+**Impact**: Debugging connection issues takes longer-**Solution**: Use Zod transforms:-```typescript-z.string().transform(val => parseInt(val, 10))+**Solution**: Add health check endpoint (see Transport Selection Guide)++**Test**:+```bash+curl https://my-mcp.workers.dev/health+# Should return: {"status":"ok","transports":{...}}```----### 14. Multiple Transport Endpoints Conflicting+### 22. CORS Headers Missing-**Error**: `/sse` returns 404 after adding `/mcp`+**Error**: `Access to fetch at '...' blocked by CORS policy`++**Cause**: MCP server doesn't return CORS headers for cross-origin requests-**Cause**: Incorrect path matching+**Solution**: Add CORS headers to all responses+```typescript+// 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"+};-**Solution**: Use `startsWith()` or exact matches+// Add to responses+return new Response(body, {+ headers: {+ ...corsHeaders,+ "Content-Type": "application/json"+ }+});+```++**Note**: OAuthProvider handles CORS automatically!----### 15. Local Testing with Miniflare Limitations+## Deployment & Testing++### Local Development-**Error**: OAuth flow fails in local dev+```bash+# Start dev server (uses Miniflare for local DOs)+npm run dev-**Cause**: Miniflare doesn't support all DO features+# Start dev server with remote Durable Objects (more accurate)+npx wrangler dev --remote+```-**Solution**: Use `npx wrangler dev --remote` for full DO support+**Access at**: `http://localhost:8788/sse`++### Test with MCP Inspector++```bash+npx @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++# 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+```++### 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!---@@ -910,6 +1448,57 @@ 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@@ -926,6 +1515,15 @@ See `templates/claude_desktop_config.json`- **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@@ -945,7 +1543,7 @@ See `templates/claude_desktop_config.json`- **@modelcontextprotocol/sdk**: 1.21.0- **@cloudflare/workers-oauth-provider**: 0.0.13- **agents (Cloudflare Agents SDK)**: 0.2.20-- **Last Verified**: 2025-11-04+- **Last Verified**: 2025-11-08**Production tested**: Based on Cloudflare's official MCP servers (mcp-server-cloudflare, workers-mcp)@@ -955,23 +1553,16 @@ See `templates/claude_desktop_config.json`**Without this skill**:- Research scattered docs: ~10k tokens-- Debug 15 errors: ~30k tokens-- **Total: ~40k tokens**+- Debug URL path issues: ~15k tokens+- Debug other 21 errors: ~30k tokens+- **Total: ~55k tokens****With this skill**:-- Read skill: ~4k tokens+- Read skill fundamentals: ~4k tokens- Copy templates: ~1k tokens-- **Total: ~5k tokens**+- Quick reference: ~1k tokens+- **Total: ~6k tokens**-**Savings: ~87%** (40k → 5k tokens)+**Savings: ~88%** (55k → 6k tokens)-**Errors prevented**: 15 (100% prevention rate)-------**Questions? Check**:-- `references/authentication.md` - Auth patterns comparison-- `references/transport.md` - SSE vs HTTP technical details-- `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+**Errors prevented**: 22 (100% prevention rate)diff --git a/skills/cloudflare-mcp-server/references/debugging-guide.md b/skills/cloudflare-mcp-server/references/debugging-guide.mdnew file mode 100644index 00000000..599ce301--- /dev/null+++ b/skills/cloudflare-mcp-server/references/debugging-guide.md@@ -0,0 +1,712 @@+# MCP Server Debugging Guide++**Troubleshooting connection issues and common errors**++---++## Quick Diagnosis Flowchart++```+MCP Connection Failing?+ |+ v+[1] Can you curl the Worker?+ curl https://worker.dev/+ |+ NO ──┴─> Worker not deployed+ | → Run: npx wrangler deploy+ |+ YES ──┴─> Continue+ |+ v+[2] Can you curl the MCP endpoint?+ curl https://worker.dev/sse+ |+ 404 ──┴─> URL path mismatch (most common!)+ | → Check: Client URL matches server base path+ | → See: "URL Path Mismatch" section below+ |+ OK ──┴─> Continue+ |+ v+[3] Did you update config after deployment?+ |+ NO ──┴─> Update claude_desktop_config.json+ | → Use deployed URL (not localhost)+ | → Restart Claude Desktop+ |+ YES ──┴─> Continue+ |+ v+[4] Check Worker logs+ npx wrangler tail+ |+ v+ See errors? → Check "Common Errors" section below+```++---++## Problem 1: URL Path Mismatch (Most Common!)++### Symptoms++- ❌ 404 Not Found+- ❌ Connection failed+- ❌ MCP Inspector shows "Failed to connect"+- ❌ Claude Desktop doesn't show tools++### Root Cause++Client URL doesn't match server base path configuration.++### Debugging Steps++#### Step 1: Check what base path your server uses++Look at your `src/index.ts`:++```typescript+// Option A: Serving at /sse+if (pathname.startsWith("/sse")) {+ return MyMCP.serveSSE("/sse").fetch(...);+ // ↑ Base path is "/sse"+}++// Option B: Serving at root /+return MyMCP.serveSSE("/").fetch(...);+// ↑ Base path is "/"+```++#### Step 2: Test with curl++```bash+# If base path is /sse:+curl https://YOUR-WORKER.workers.dev/sse++# If base path is /:+curl https://YOUR-WORKER.workers.dev/+```++**Expected:** JSON response with server info+**Got 404?** Your URL doesn't match the base path++#### Step 3: Update client config++Match the curl URL that worked:++```json+{+ "mcpServers": {+ "my-mcp": {+ "url": "https://YOUR-WORKER.workers.dev/sse" // Must match curl URL!+ }+ }+}+```++#### Step 4: Restart Claude Desktop++Config only loads at startup:+1. Quit Claude Desktop completely+2. Reopen+3. Check for tools++### Common Variations++**Server at `/sse`, client missing `/sse`:**+```typescript+// Server+MyMCP.serveSSE("/sse").fetch(...)++// Client (wrong)+"url": "https://worker.dev" // ❌ Missing /sse+```++**Fix:**+```json+"url": "https://worker.dev/sse" // ✅ Include /sse+```++---++**Server at `/`, client includes `/sse`:**+```typescript+// Server+MyMCP.serveSSE("/").fetch(...)++// Client (wrong)+"url": "https://worker.dev/sse" // ❌ Server at root, not /sse+```++**Fix:**+```json+"url": "https://worker.dev" // ✅ No /sse+```++---++## Problem 2: Localhost After Deployment++### Symptoms++- ❌ Connection timeout+- ❌ Connection refused+- ❌ Works in dev, fails in production++### Root Cause++Client config still using `localhost` URL after deployment.++### Debugging Steps++#### Step 1: Check client config++```bash+cat ~/.config/claude/claude_desktop_config.json+```++Look for:+```json+{+ "mcpServers": {+ "my-mcp": {+ "url": "http://localhost:8788/sse" // ❌ localhost!+ }+ }+}+```++#### Step 2: Get deployed URL++```bash+npx wrangler deploy++# Output shows:+# Deployed to: https://my-mcp.YOUR_ACCOUNT.workers.dev+```++#### Step 3: Update client config++```json+{+ "mcpServers": {+ "my-mcp": {+ "url": "https://my-mcp.YOUR_ACCOUNT.workers.dev/sse" // ✅ Deployed URL+ }+ }+}+```++#### Step 4: Restart Claude Desktop++---++## Problem 3: Worker Not Deployed++### Symptoms++- ❌ curl returns connection refused/timeout+- ❌ No response at all++### Debugging Steps++#### Step 1: Check deployment status++```bash+npx wrangler whoami+# Shows: logged in as...++npx wrangler deployments list+# Shows: recent deployments (or none)+```++#### Step 2: Deploy++```bash+npx wrangler deploy+```++#### Step 3: Verify deployment++```bash+curl https://YOUR-WORKER.workers.dev/++# Should return SOMETHING (even 404 means it's running)+```++---++## Problem 4: OAuth URL Mismatch++### Symptoms++- ❌ `OAuth error: redirect_uri does not match`+- ❌ OAuth flow starts but fails at callback+- ❌ Token exchange fails++### Root Cause++OAuth URLs don't match deployed URL.++### Debugging Steps++#### Step 1: Check ALL three OAuth URLs++```bash+cat ~/.config/claude/claude_desktop_config.json+```++Look for:+```json+{+ "mcpServers": {+ "my-mcp": {+ "url": "https://worker.dev/sse", // ← Check 1+ "auth": {+ "type": "oauth",+ "authorizationUrl": "https://worker.dev/authorize", // ← Check 2+ "tokenUrl": "https://worker.dev/token" // ← Check 3+ }+ }+ }+}+```++#### Step 2: Verify ALL URLs match++**Must all use same:**+- Protocol: `https://` (not mixed http/https)+- Domain: Same Workers domain+- No typos: `authorize` not `auth`, `token` not `tokens`++#### Step 3: Test each endpoint++```bash+curl https://worker.dev/sse # Main endpoint+curl https://worker.dev/authorize # OAuth authorize (should show HTML)+curl https://worker.dev/token # Token endpoint+```++---++## Problem 5: CORS Errors++### Symptoms++- ❌ `Access to fetch at '...' blocked by CORS policy`+- ❌ `Method Not Allowed` for OPTIONS requests+- ❌ Works in curl, fails in browser++### Root Cause++Missing CORS headers or OPTIONS handler.++### Debugging Steps++#### Step 1: Test with browser++Open browser console and try:+```javascript+fetch('https://worker.dev/sse')+```++#### Step 2: Check OPTIONS handler++Your Worker should handle OPTIONS:+```typescript+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",+ },+ });+}+```++#### Step 3: Test OPTIONS request++```bash+curl -X OPTIONS https://worker.dev/sse -v+```++**Expected:** 204 No Content with CORS headers+**Got:** 405 Method Not Allowed → Add OPTIONS handler++---++## Problem 6: Environment Variables Missing++### Symptoms++- ❌ `TypeError: env.API_KEY is undefined`+- ❌ Tools return empty data+- ❌ Silent failures (no error, but wrong results)++### Debugging Steps++#### Step 1: Check local development++```bash+# Check .dev.vars exists+cat .dev.vars++# Should have:+API_KEY=dev-key-123+DATABASE_URL=http://localhost:3000+```++#### Step 2: Check production config++```bash+# Check wrangler.jsonc+cat wrangler.jsonc+```++**Public vars:**+```jsonc+{+ "vars": {+ "ENVIRONMENT": "production",+ "LOG_LEVEL": "info"+ }+}+```++**Secrets:**+```bash+# List secrets+npx wrangler secret list++# Add missing secret+npx wrangler secret put API_KEY+```++#### Step 3: Add validation++In your `init()` method:+```typescript+async init() {+ // Validate required env vars+ if (!this.env.API_KEY) {+ throw new Error("API_KEY not configured");+ }++ // Continue...+}+```++---++## Problem 7: Durable Objects Not Working++### Symptoms++- ❌ `TypeError: Cannot read properties of undefined (reading 'idFromName')`+- ❌ State not persisting+- ❌ `Durable Object class MyMCP has no migration defined`++### Debugging Steps++#### Step 1: Check binding++```bash+cat wrangler.jsonc+```++**Must have:**+```jsonc+{+ "durable_objects": {+ "bindings": [+ {+ "name": "MY_MCP",+ "class_name": "MyMCP",+ "script_name": "my-mcp-server"+ }+ ]+ }+}+```++#### Step 2: Check migration++```jsonc+{+ "migrations": [+ { "tag": "v1", "new_classes": ["MyMCP"] }+ ]+}+```++#### Step 3: Deploy with migration++```bash+npx wrangler deploy+```++First deployment requires migration!++---++## Checking Worker Logs++### Real-time logs++```bash+npx wrangler tail+```++**Shows:**+- All console.log() output+- Errors with stack traces+- Request/response info++### Filtering logs++```bash+# Only errors+npx wrangler tail --format=json | jq 'select(.level=="error")'++# Only specific message+npx wrangler tail | grep "API_KEY"+```++---++## Common Error Messages++### Error: "404 Not Found"++**Cause:** URL path mismatch (see Problem 1)++**Fix:**+1. Check server base path+2. Update client URL to match+3. Restart Claude Desktop++---++### Error: "Connection refused" / "ECONNREFUSED"++**Cause:** Worker not deployed or wrong URL++**Fix:**+1. Deploy: `npx wrangler deploy`+2. Update client config with deployed URL+3. Restart Claude Desktop++---++### Error: "OAuth error: redirect_uri does not match"++**Cause:** OAuth URLs don't match deployed domain++**Fix:**+1. Update ALL three OAuth URLs in client config+2. Use same domain and protocol for all+3. Restart Claude Desktop++---++### Error: "TypeError: env.BINDING is undefined"++**Cause:** Missing binding in wrangler.jsonc++**Fix:**+1. Add binding to wrangler.jsonc+2. Deploy: `npx wrangler deploy`+3. Restart++---++### Error: "Access to fetch blocked by CORS policy"++**Cause:** Missing CORS headers or OPTIONS handler++**Fix:**+1. Add OPTIONS handler (see Problem 5)+2. Deploy+3. Test in browser++---++### Error: "ZodError: Invalid input type"++**Cause:** Client sends wrong data type for parameter++**Fix:**+```typescript+// Use Zod transform+param: z.string().transform(val => parseInt(val, 10))+```++---++## Testing Checklist++Before declaring "it works":++- [ ] Worker deployed: `npx wrangler deploy` succeeded+- [ ] Worker running: `curl https://worker.dev/` returns something+- [ ] MCP endpoint: `curl https://worker.dev/sse` returns server info+- [ ] Client config updated with deployed URL+- [ ] Client config URL matches curl test+- [ ] Claude Desktop restarted+- [ ] Tools visible in Claude Desktop+- [ ] Test tool call succeeds+- [ ] Worker logs clean: `npx wrangler tail` shows no errors+- [ ] (OAuth) All three URLs match+- [ ] (DO) Bindings configured+- [ ] (Secrets) Environment variables set++---++## Advanced Debugging++### Enable verbose logging++```typescript+export class MyMCP extends McpAgent<Env> {+ async init() {+ console.log("MyMCP initializing...");+ console.log("Environment:", {+ hasAPIKey: !!this.env.API_KEY,+ hasDB: !!this.env.DB,+ });++ this.server.tool(+ "test",+ "Test tool",+ { msg: z.string() },+ async ({ msg }) => {+ console.log("Tool called with:", msg);+ return { content: [{ type: "text", text: `Echo: ${msg}` }] };+ }+ );+ }+}+```++**View logs:**+```bash+npx wrangler tail+```++---++### Test MCP protocol directly++Use MCP Inspector for protocol-level debugging:++```bash+npx @modelcontextprotocol/inspector@latest+```++1. Open http://localhost:5173+2. Enter Worker URL+3. Click "Connect"+4. Try "List Tools"+5. Inspect request/response++**Benefits:**+- See exact JSON-RPC messages+- Test individual tool calls+- Verify protocol compliance++---++### Check Cloudflare dashboard++1. Visit https://dash.cloudflare.com/+2. Go to Workers & Pages+3. Find your Worker+4. Check:+ - Deployment status+ - Recent logs+ - Analytics++---++## Prevention++### Add health check endpoint++```typescript+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(),+ }));+}+```++**Test:** `curl https://worker.dev/health`++---++### Add startup validation++```typescript+async init() {+ // Validate environment+ if (!this.env.API_KEY) {+ throw new Error("API_KEY not configured");+ }++ // Log successful initialization+ console.log("MCP server initialized successfully");+}+```++---++### Use descriptive 404 messages++```typescript+return new Response(JSON.stringify({+ error: "Not Found",+ requestedPath: pathname,+ availablePaths: ["/sse", "/mcp", "/health"],+ hint: "Client URL must include base path",+ example: "https://worker.dev/sse"+}), { status: 404 });+```++---++## Summary++**Most common issues (in order):**++1. **URL path mismatch** (80% of problems)+ - Fix: Match client URL to server base path++2. **Localhost after deployment** (10%)+ - Fix: Update config with deployed URL++3. **OAuth URL mismatch** (5%)+ - Fix: Update ALL three OAuth URLs++4. **Missing environment variables** (3%)+ - Fix: Add to .dev.vars or wrangler secrets++5. **Other** (2%)+ - Check Worker logs: `npx wrangler tail`++**Golden debugging workflow:**+```bash+1. curl https://worker.dev/ # Worker running?+2. curl https://worker.dev/sse # MCP endpoint works?+3. Check client config matches URL # Config correct?+4. Restart Claude Desktop # Reloaded config?+5. npx wrangler tail # Any errors?+```++**Remember:** 80% of MCP connection issues are URL path mismatches. Always start there!diff --git a/skills/cloudflare-mcp-server/references/http-transport-fundamentals.md b/skills/cloudflare-mcp-server/references/http-transport-fundamentals.mdnew file mode 100644index 00000000..68319615--- /dev/null+++ b/skills/cloudflare-mcp-server/references/http-transport-fundamentals.md@@ -0,0 +1,506 @@+# HTTP Transport Fundamentals++**Deep dive on URL paths and routing for Cloudflare MCP servers**++This document explains how URL path configuration works in MCP servers and why mismatches are the #1 cause of connection failures.++---++## The Problem++**Most common MCP server connection error:**+```+❌ 404 Not Found+❌ Connection failed+❌ MCP Inspector shows "Failed to connect"+```++**Root cause:** Client URL doesn't match server base path configuration++---++## How Base Paths Work++### The Core Concept++When you call `MyMCP.serveSSE("/sse")`, you're telling the MCP server:++> "All MCP endpoints are available under the `/sse` base path"++This means:+- Initial connection: `https://worker.dev/sse`+- List tools: `https://worker.dev/sse/tools/list`+- Call tool: `https://worker.dev/sse/tools/call`+- List resources: `https://worker.dev/sse/resources/list`++**The base path is prepended to ALL MCP-specific endpoints automatically.**++---++## Example 1: Serving at `/sse`++**Server code:**+```typescript+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 });+ }+};+```++**Client configuration:**+```json+{+ "mcpServers": {+ "my-mcp": {+ "url": "https://my-mcp.workers.dev/sse"+ // ↑ Must include /sse+ }+ }+}+```++**What happens:**+1. Client connects to: `https://my-mcp.workers.dev/sse`+2. Worker receives request with `pathname = "/sse"`+3. Check: `pathname.startsWith("/sse")` → TRUE ✅+4. MCP server handles request+5. Tools available at:+ - `/sse/tools/list`+ - `/sse/tools/call`+ - etc.++---++## Example 2: Serving at `/` (root)++**Server code:**+```typescript+export default {+ fetch(request: Request, env: Env, ctx: ExecutionContext) {+ return MyMCP.serveSSE("/").fetch(request, env, ctx);+ // ↑ Base path is "/" (root)+ }+};+```++**Client configuration:**+```json+{+ "mcpServers": {+ "my-mcp": {+ "url": "https://my-mcp.workers.dev"+ // ↑ No /sse!+ }+ }+}+```++**What happens:**+1. Client connects to: `https://my-mcp.workers.dev`+2. Worker receives request with `pathname = "/"`+3. MCP server handles request at root+4. Tools available at:+ - `/tools/list`+ - `/tools/call`+ - etc. (no /sse prefix)++---++## Example 3: Custom base path++**Server code:**+```typescript+export default {+ fetch(request: Request, env: Env, ctx: ExecutionContext) {+ const { pathname } = new URL(request.url);++ if (pathname.startsWith("/api/mcp")) {+ return MyMCP.serveSSE("/api/mcp").fetch(request, env, ctx);+ // ↑ Base path is "/api/mcp"+ }++ return new Response("Not Found", { status: 404 });+ }+};+```++**Client configuration:**+```json+{+ "mcpServers": {+ "my-mcp": {+ "url": "https://my-mcp.workers.dev/api/mcp"+ // ↑ Must match base path exactly+ }+ }+}+```++---++## Why `pathname.startsWith()` is Critical++**❌ WRONG: Using exact match**+```typescript+if (pathname === "/sse") {+ return MyMCP.serveSSE("/sse").fetch(request, env, ctx);+}+```++**Problem:** This ONLY matches `/sse` exactly+- `/sse` → ✅ Matches+- `/sse/tools/list` → ❌ Doesn't match! 404!+- `/sse/tools/call` → ❌ Doesn't match! 404!++**✅ CORRECT: Using `startsWith()`**+```typescript+if (pathname.startsWith("/sse")) {+ return MyMCP.serveSSE("/sse").fetch(request, env, ctx);+}+```++**Result:** This matches ALL paths under `/sse`+- `/sse` → ✅ Matches+- `/sse/tools/list` → ✅ Matches+- `/sse/tools/call` → ✅ Matches+- `/sse/resources/list` → ✅ Matches++---++## Request/Response Lifecycle++Let's trace a complete MCP request from start to finish.++### Step 1: Client Connection++Client initiates connection:+```+POST https://my-mcp.workers.dev/sse+```++### Step 2: Worker Receives Request++Worker `fetch()` handler is called:+```typescript+const { pathname } = new URL(request.url);+console.log(pathname); // "/sse"+```++### Step 3: Path Matching++Worker checks if path matches:+```typescript+if (pathname.startsWith("/sse")) { // TRUE!+ return MyMCP.serveSSE("/sse").fetch(request, env, ctx);+}+```++### Step 4: MCP Server Handles Request++MCP Agent processes the request and returns available endpoints.++### Step 5: Client Lists Tools++Client makes follow-up request:+```+POST https://my-mcp.workers.dev/sse/tools/list+```++Worker receives:+```typescript+const { pathname } = new URL(request.url);+console.log(pathname); // "/sse/tools/list"++if (pathname.startsWith("/sse")) { // TRUE! Matches because of startsWith()+ return MyMCP.serveSSE("/sse").fetch(request, env, ctx);+}+```++MCP server sees `/tools/list` (after stripping `/sse` base path) and returns tool list.++---++## Common Mistakes and Fixes++### Mistake 1: Missing Base Path in Client URL++**Server:**+```typescript+MyMCP.serveSSE("/sse").fetch(...)+```++**Client:**+```json+"url": "https://worker.dev" // ❌ Missing /sse+```++**Result:** 404 Not Found++**Fix:**+```json+"url": "https://worker.dev/sse" // ✅ Include /sse+```++---++### Mistake 2: Wrong Base Path++**Server:**+```typescript+if (pathname.startsWith("/api")) {+ return MyMCP.serveSSE("/api").fetch(...);+}+```++**Client:**+```json+"url": "https://worker.dev/sse" // ❌ Server expects /api+```++**Result:** 404 Not Found++**Fix:**+```json+"url": "https://worker.dev/api" // ✅ Match server path+```++---++### Mistake 3: Localhost After Deployment++**Development:**+```json+"url": "http://localhost:8788/sse" // ✅ Works in dev+```++**After deployment** (forgot to update):+```json+"url": "http://localhost:8788/sse" // ❌ Worker is deployed!+```++**Result:** Connection refused / timeout++**Fix:**+```json+"url": "https://my-mcp.YOUR_ACCOUNT.workers.dev/sse" // ✅ Deployed URL+```++---++### Mistake 4: Using Exact Match Instead of `startsWith()`++**Server:**+```typescript+if (pathname === "/sse") { // ❌ Only matches /sse exactly+ return MyMCP.serveSSE("/sse").fetch(...);+}+```++**Result:**+- `/sse` → ✅ Works (initial connection)+- `/sse/tools/list` → ❌ 404 (tool listing fails)++**Fix:**+```typescript+if (pathname.startsWith("/sse")) { // ✅ Matches all sub-paths+ return MyMCP.serveSSE("/sse").fetch(...);+}+```++---++## Debugging Workflow++When MCP connection fails:++### Step 1: Check Worker is Running++```bash+curl https://YOUR-WORKER.workers.dev/+```++**Expected:** Some response (even 404 is OK - means Worker is running)+**Problem:** Timeout or connection refused → Worker not deployed++### Step 2: Test MCP Endpoint++```bash+curl https://YOUR-WORKER.workers.dev/sse+```++**Expected:** JSON response with MCP server info+**Problem:** 404 → Client URL doesn't match server base path++### Step 3: Verify Client Config++Check `~/.config/claude/claude_desktop_config.json`:+```json+{+ "mcpServers": {+ "my-mcp": {+ "url": "https://YOUR-WORKER.workers.dev/sse"+ }+ }+}+```++**Verify:**+- [ ] URL matches deployed Worker URL+- [ ] URL includes base path (e.g., `/sse`)+- [ ] No typos in domain or path+- [ ] Using `https://` (not `http://`)++### Step 4: Restart Claude Desktop++Config changes require restart:+1. Quit Claude Desktop completely+2. Reopen Claude Desktop+3. Check for MCP server in tools list++---++## Multiple Transports++You can serve multiple transports at different paths:++**Server:**+```typescript+export default {+ fetch(request: Request, env: Env, ctx: ExecutionContext) {+ const { pathname } = new URL(request.url);++ // SSE at /sse+ if (pathname.startsWith("/sse")) {+ return MyMCP.serveSSE("/sse").fetch(request, env, ctx);+ }++ // HTTP at /mcp+ if (pathname.startsWith("/mcp")) {+ return MyMCP.serve("/mcp").fetch(request, env, ctx);+ }++ // Health check+ if (pathname === "/" || pathname === "/health") {+ return new Response(JSON.stringify({+ transports: {+ sse: "/sse",+ http: "/mcp"+ }+ }));+ }++ return new Response("Not Found", { status: 404 });+ }+};+```++**Clients can choose:**+- SSE: `"url": "https://worker.dev/sse"`+- HTTP: `"url": "https://worker.dev/mcp"`++**Why this works:**+- `/sse` and `/mcp` don't conflict+- Each transport has isolated namespace+- Health check available at root `/`++---++## Best Practices++### 1. Always Use `startsWith()` for Path Matching++```typescript+// ✅ CORRECT+if (pathname.startsWith("/sse")) { ... }++// ❌ WRONG+if (pathname === "/sse") { ... }+```++### 2. Add Health Check Endpoint++```typescript+if (pathname === "/" || pathname === "/health") {+ return new Response(JSON.stringify({+ name: "My MCP Server",+ version: "1.0.0",+ transports: {+ sse: "/sse",+ http: "/mcp"+ },+ status: "ok"+ }));+}+```++**Benefits:**+- Quickly verify Worker is running+- Discover available transports+- Debug connection issues++### 3. Use Descriptive 404 Messages++```typescript+return new Response(JSON.stringify({+ error: "Not Found",+ requestedPath: pathname,+ availablePaths: ["/sse", "/mcp", "/health"],+ hint: "Client URL must include base path (e.g., /sse)"+}), { status: 404 });+```++### 4. Test After Every Deployment++```bash+# Deploy+npx wrangler deploy++# Test immediately+curl https://YOUR-WORKER.workers.dev/sse++# Update client config+# Restart Claude Desktop+```++### 5. Document Base Path in Comments++```typescript+// SSE transport at /sse+// Client URL MUST be: https://worker.dev/sse+if (pathname.startsWith("/sse")) {+ return MyMCP.serveSSE("/sse").fetch(request, env, ctx);+}+```++---++## Summary++**Key Takeaways:**++1. **Base path in `serveSSE()` determines client URL**+ - `serveSSE("/sse")` → Client uses `https://worker.dev/sse`+ - `serveSSE("/")` → Client uses `https://worker.dev`++2. **Always use `pathname.startsWith()` for matching**+ - Matches sub-paths like `/sse/tools/list`++3. **Test with curl after deployment**+ - `curl https://worker.dev/sse` should return server info++4. **Update client config after every deployment**+ - Development: `http://localhost:8788/sse`+ - Production: `https://worker.workers.dev/sse`++5. **Restart Claude Desktop after config changes**+ - Config only loaded at startup++**Remember:** The #1 MCP connection failure is URL path mismatch. Always verify your base paths match!diff --git a/skills/cloudflare-mcp-server/references/transport-comparison.md b/skills/cloudflare-mcp-server/references/transport-comparison.mdnew file mode 100644index 00000000..4a9f6c33--- /dev/null+++ b/skills/cloudflare-mcp-server/references/transport-comparison.md@@ -0,0 +1,439 @@+# MCP Transport Comparison: SSE vs Streamable HTTP++**Detailed comparison of MCP transport methods for Cloudflare Workers**++---++## Overview++MCP supports two transport methods:+1. **SSE (Server-Sent Events)** - Legacy standard (2024)+2. **Streamable HTTP** - New standard (2025+)++Both work on Cloudflare Workers. You can (and should) support both for maximum compatibility.++---++## SSE (Server-Sent Events)++### What It Is++SSE is a W3C standard for server-to-client streaming over HTTP. The server holds the connection open and pushes events as they occur.++**Technical Details:**+- Protocol: HTTP/1.1 or HTTP/2+- Content-Type: `text/event-stream`+- Connection: Long-lived, unidirectional (server → client)+- Format: Plain text with `data:`, `event:`, `id:` fields++### Code Example++**Server:**+```typescript+MyMCP.serveSSE("/sse").fetch(request, env, ctx)+```++**Client config:**+```json+{+ "mcpServers": {+ "my-mcp": {+ "url": "https://worker.dev/sse"+ }+ }+}+```++### Pros++✅ **Wide compatibility** - Supported by all MCP clients (2024+)+✅ **Well-documented** - Lots of examples and tooling+✅ **Easy debugging** - Plain text format, human-readable+✅ **Works with proxies** - Most HTTP proxies support SSE+✅ **Battle-tested** - Used in production for years++### Cons++❌ **Less efficient** - Overhead from text encoding+❌ **Being deprecated** - MCP is moving to Streamable HTTP+❌ **Unidirectional** - Server can push, but client uses separate requests+❌ **Text-only** - Binary data must be base64-encoded+❌ **Connection limits** - Browsers limit SSE connections per domain++### When to Use++- **2024-2025 transition period** - Maximum compatibility+- **Debugging** - Easier to inspect traffic+- **Legacy clients** - Older MCP implementations+- **Development** - Simpler to test with curl/MCP Inspector++---++## Streamable HTTP++### What It Is++Streamable HTTP is a modern standard for bidirectional streaming using HTTP/2+ streams. More efficient than SSE.++**Technical Details:**+- Protocol: HTTP/2 or HTTP/3+- Content-Type: `application/json` (streaming)+- Connection: Bidirectional (client ↔ server)+- Format: NDJSON (newline-delimited JSON)++### Code Example++**Server:**+```typescript+MyMCP.serve("/mcp").fetch(request, env, ctx)+```++**Client config:**+```json+{+ "mcpServers": {+ "my-mcp": {+ "url": "https://worker.dev/mcp"+ }+ }+}+```++### Pros++✅ **More efficient** - Binary-safe, less overhead+✅ **2025 standard** - MCP's future default+✅ **Bidirectional** - Full-duplex communication+✅ **Better streaming** - Natively supports streaming responses+✅ **HTTP/2 multiplexing** - Multiple streams over one connection++### Cons++❌ **Newer clients only** - Not all 2024 clients support it+❌ **Less tooling** - Fewer debugging tools than SSE+❌ **HTTP/2 required** - Cloudflare Workers support this automatically+❌ **More complex** - Harder to debug than plain text SSE++### When to Use++- **2025+** - Future-proof your implementation+- **Performance-critical** - High-throughput or low-latency needs+- **Modern clients** - Latest Claude Desktop, MCP Inspector+- **Production** - When paired with SSE fallback++---++## Side-by-Side Comparison++| Feature | SSE | Streamable HTTP |+|---------|-----|-----------------|+| **Protocol** | HTTP/1.1+ | HTTP/2+ |+| **Direction** | Unidirectional | Bidirectional |+| **Format** | Text (`text/event-stream`) | NDJSON |+| **Efficiency** | Lower | Higher |+| **Compatibility** | All MCP clients | 2025+ clients |+| **Debugging** | Easy (plain text) | Moderate (JSON) |+| **Binary data** | base64-encoded | Native support |+| **Cloudflare cost** | Standard | Standard (no difference) |+| **MCP Standard** | Legacy (2024) | Current (2025+) |++---++## Supporting Both Transports++**Best practice:** Serve both for maximum compatibility during 2024-2025 transition.++### Implementation++```typescript+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 showing available transports+ if (pathname === "/" || pathname === "/health") {+ return new Response(JSON.stringify({+ name: "My MCP Server",+ version: "1.0.0",+ transports: {+ sse: "/sse", // For legacy clients+ http: "/mcp" // For modern clients+ }+ }));+ }++ return new Response("Not Found", { status: 404 });+ }+};+```++### Client Configuration++Clients can choose which transport to use:++**Legacy client (SSE):**+```json+{+ "mcpServers": {+ "my-mcp": {+ "url": "https://worker.dev/sse"+ }+ }+}+```++**Modern client (HTTP):**+```json+{+ "mcpServers": {+ "my-mcp": {+ "url": "https://worker.dev/mcp"+ }+ }+}+```++---++## Performance Comparison++### Latency++**SSE:**+- Initial connection: ~100-200ms+- Tool call: ~50-100ms+- Streaming response: Good (text-based)++**Streamable HTTP:**+- Initial connection: ~100-200ms (similar)+- Tool call: ~40-80ms (slightly faster)+- Streaming response: Excellent (binary-safe)++**Verdict:** Streamable HTTP is marginally faster, but difference is negligible for most use cases.++---++### Bandwidth++**Example: 1KB text response**++**SSE:**+```+data: {"content":[{"type":"text","text":"Hello"}]}\n\n+```+- Overhead: `data: ` prefix, double newlines+- Total: ~1.05KB++**Streamable HTTP:**+```json+{"content":[{"type":"text","text":"Hello"}]}+```+- Overhead: None (pure JSON)+- Total: ~1.00KB++**Verdict:** Streamable HTTP is 5-10% more efficient (text) and much better for binary data.++---++### Connection Limits++**SSE:**+- Browsers: 6 connections per domain (HTTP/1.1)+- Not an issue for CLI/Desktop clients++**Streamable HTTP:**+- HTTP/2 multiplexing: Effectively unlimited+- Multiple streams over single connection++**Verdict:** Streamable HTTP scales better for multi-connection scenarios.++---++## Migration Path++### 2024 (Now)++**Recommendation:** Support both transports+- SSE for wide compatibility+- HTTP for future-proofing++**Code:**+```typescript+// Support both+if (pathname.startsWith("/sse")) {+ return MyMCP.serveSSE("/sse").fetch(...);+}+if (pathname.startsWith("/mcp")) {+ return MyMCP.serve("/mcp").fetch(...);+}+```++---++### 2025 (Future)++**Recommendation:** Deprecate SSE, keep as fallback+- HTTP as primary+- SSE for legacy clients only++**Code:**+```typescript+// Prefer HTTP+if (pathname.startsWith("/mcp")) {+ return MyMCP.serve("/mcp").fetch(...);+}+// Legacy SSE fallback+if (pathname.startsWith("/sse")) {+ return MyMCP.serveSSE("/sse").fetch(...);+}+```++---++### 2026+ (Long-term)++**Recommendation:** HTTP only+- Remove SSE support+- All clients updated to HTTP++**Code:**+```typescript+// HTTP only+if (pathname.startsWith("/mcp")) {+ return MyMCP.serve("/mcp").fetch(...);+}+```++---++## Cloudflare Workers Considerations++### Cost++**Both transports cost the same** on Cloudflare Workers:+- Charged per request+- Charged per CPU time+- No difference in pricing++### Performance++**Cloudflare Workers natively support both:**+- SSE: Works perfectly (HTTP/1.1 and HTTP/2)+- HTTP/2: Automatic (no configuration needed)+- Streaming: Both transports can stream responses++### Limits++**No transport-specific limits:**+- Request size: 100MB (both)+- CPU time: 50ms-30s depending on plan (both)+- Concurrent requests: Unlimited (both)++---++## Debugging++### SSE Debugging++**curl:**+```bash+curl -N https://worker.dev/sse+```++**Output:**+```+data: {"jsonrpc":"2.0","method":"initialize",...}++data: {"jsonrpc":"2.0","method":"tools/list",...}+```++**Human-readable:** ✅ Easy to inspect++---++### HTTP Debugging++**curl:**+```bash+curl https://worker.dev/mcp -H "Content-Type: application/json" -d '{...}'+```++**Output:**+```json+{"jsonrpc":"2.0","method":"initialize",...}+{"jsonrpc":"2.0","method":"tools/list",...}+```++**Human-readable:** ✅ Still readable (NDJSON)++---++## When to Choose One Over the Other++### Choose SSE When:++- Supporting 2024 MCP clients+- Debugging connection issues (easier to inspect)+- Working with legacy systems+- Need maximum compatibility+- Developing/testing with basic tools++### Choose Streamable HTTP When:++- Building for 2025++- Performance matters (high-throughput)+- Using modern clients (latest Claude Desktop)+- Want future-proof implementation+- Need bidirectional streaming++### Support Both When:++- In production (2024-2025 transition)+- Serving diverse clients+- Want maximum compatibility+- No cost difference (same Worker code)++---++## Summary++**Current Recommendation (2024-2025):**+```typescript+// Support BOTH transports+if (pathname.startsWith("/sse")) {+ return MyMCP.serveSSE("/sse").fetch(request, env, ctx);+}+if (pathname.startsWith("/mcp")) {+ return MyMCP.serve("/mcp").fetch(request, env, ctx);+}+```++**Why:**+- SSE: Maximum compatibility+- HTTP: Future-proof+- No cost difference+- Clients choose what they support++**Future (2026+):**+- HTTP will be the only standard+- SSE will be deprecated+- But for now, support both!++---++## Additional Resources++- **MCP Specification**: https://modelcontextprotocol.io/+- **SSE Spec (W3C)**: https://html.spec.whatwg.org/multipage/server-sent-events.html+- **HTTP/2 Spec (RFC 7540)**: https://httpwg.org/specs/rfc7540.html+- **Cloudflare Workers**: https://developers.cloudflare.com/workers/diff --git a/skills/cloudflare-mcp-server/templates/basic-mcp-server.ts b/skills/cloudflare-mcp-server/templates/basic-mcp-server.tsindex 9d04827e..52f855a8 100644--- a/skills/cloudflare-mcp-server/templates/basic-mcp-server.ts+++ b/skills/cloudflare-mcp-server/templates/basic-mcp-server.ts@@ -7,6 +7,31 @@* Perfect for: Internal tools, development, public APIs** Based on: https://github.com/cloudflare/ai/tree/main/demos/remote-mcp-authless+ *+ * ⚠️ CRITICAL URL CONFIGURATION:+ *+ * This template serves MCP at TWO base paths:+ * - SSE transport: /sse+ * - HTTP transport: /mcp+ *+ * Your client configuration MUST match:+ * {+ * "mcpServers": {+ * "my-mcp": {+ * "url": "https://YOUR-WORKER.workers.dev/sse" // ← Include /sse!+ * }+ * }+ * }+ *+ * Common mistakes:+ * ❌ "url": "https://YOUR-WORKER.workers.dev" // Missing /sse → 404+ * ❌ "url": "http://localhost:8788" // Wrong after deploy+ * ✅ "url": "https://YOUR-WORKER.workers.dev/sse" // Correct!+ *+ * After deploying:+ * 1. Test with: curl https://YOUR-WORKER.workers.dev/sse+ * 2. Update client config with exact URL from step 1+ * 3. Restart Claude Desktop*/import { McpAgent } from "agents/mcp";@@ -120,6 +145,28 @@ export class MyMCP extends McpAgent<Env> {/*** Worker fetch handler* Supports both SSE and Streamable HTTP transports+ *+ * ⚠️ URL CONFIGURATION GUIDE:+ *+ * Option 1: Serve at /sse (current setup)+ * -----------------------------------------+ * Server code (below): MyMCP.serveSSE("/sse").fetch(...)+ * Client config: "url": "https://worker.dev/sse"+ * Tools available at: https://worker.dev/sse/tools/list+ *+ * Option 2: Serve at root / (alternative)+ * -----------------------------------------+ * Server code: MyMCP.serveSSE("/").fetch(...)+ * Client config: "url": "https://worker.dev"+ * Tools available at: https://worker.dev/tools/list+ *+ * The base path argument MUST match what the client expects!+ *+ * TESTING YOUR CONFIGURATION:+ * 1. Deploy: npx wrangler deploy+ * 2. Test: curl https://YOUR-WORKER.workers.dev/sse+ * 3. Configure: Use exact URL from step 2 in client config+ * 4. Restart: Restart Claude Desktop to load new config*/export default {async fetch(@@ -129,26 +176,52 @@ export default {): Promise<Response> {const { pathname } = new URL(request.url);+ // Handle CORS preflight (for browser-based clients like MCP Inspector)+ 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",+ },+ });+ }+// SSE transport (legacy, but widely supported)- if (pathname === "/sse" || pathname.startsWith("/sse/")) {+ // ⚠️ IMPORTANT: Use pathname.startsWith() to match sub-paths like /sse/tools/list+ if (pathname.startsWith("/sse")) {return MyMCP.serveSSE("/sse").fetch(request, env, ctx);+ // ↑ Base path "/sse" means client URL must be: https://worker.dev/sse}// Streamable HTTP transport (2025 standard)- if (pathname === "/mcp" || pathname.startsWith("/mcp/")) {+ // ⚠️ IMPORTANT: Use pathname.startsWith() to match sub-paths like /mcp/tools/list+ if (pathname.startsWith("/mcp")) {return MyMCP.serve("/mcp").fetch(request, env, ctx);+ // ↑ Base path "/mcp" means client URL must be: https://worker.dev/mcp}- // Health check endpoint- if (pathname === "/") {+ // Health check endpoint (useful for debugging connection issues)+ // Test with: curl https://YOUR-WORKER.workers.dev/+ if (pathname === "/" || pathname === "/health") {return new Response(JSON.stringify({name: "My MCP Server",version: "1.0.0",- transports: ["/sse", "/mcp"],+ transports: {+ sse: "/sse",+ http: "/mcp",+ },+ status: "ok",+ timestamp: new Date().toISOString(),}),{- headers: { "Content-Type": "application/json" },+ headers: {+ "Content-Type": "application/json",+ "Access-Control-Allow-Origin": "*",+ },});}diff --git a/skills/cloudflare-mcp-server/templates/mcp-http-fundamentals.ts b/skills/cloudflare-mcp-server/templates/mcp-http-fundamentals.tsnew file mode 100644index 00000000..b97cf41e--- /dev/null+++ b/skills/cloudflare-mcp-server/templates/mcp-http-fundamentals.ts@@ -0,0 +1,210 @@+/**+ * MCP HTTP Fundamentals - Minimal Example+ *+ * The SIMPLEST working MCP server demonstrating ONLY URL configuration.+ * Perfect for understanding how base paths work before adding features.+ *+ * This template focuses on THE #1 MISTAKE: URL path mismatches+ *+ * ═══════════════════════════════════════════════════════════════+ * ⚠️ CRITICAL: URL CONFIGURATION EXPLAINED+ * ═══════════════════════════════════════════════════════════════+ *+ * CONCEPT: The base path you use in serveSSE() determines the client URL+ *+ * Example A: Serving at /sse+ * ---------------------------+ * Code: MyMCP.serveSSE("/sse").fetch(...)+ * Client URL: "https://worker.dev/sse" ✅+ * Wrong URL: "https://worker.dev" ❌ 404!+ *+ * Example B: Serving at root /+ * ----------------------------+ * Code: MyMCP.serveSSE("/").fetch(...)+ * Client URL: "https://worker.dev" ✅+ * Wrong URL: "https://worker.dev/sse" ❌ 404!+ *+ * Example C: Serving at /api/mcp+ * -------------------------------+ * Code: MyMCP.serveSSE("/api/mcp").fetch(...)+ * Client URL: "https://worker.dev/api/mcp" ✅+ * Wrong URL: "https://worker.dev/sse" ❌ 404!+ *+ * The pattern: pathname.startsWith("/sse") matches ALL paths like:+ * - /sse+ * - /sse/tools/list+ * - /sse/tools/call+ * - /sse/resources/list+ *+ * ═══════════════════════════════════════════════════════════════+ * 📋 POST-DEPLOYMENT CHECKLIST+ * ═══════════════════════════════════════════════════════════════+ *+ * After running `npx wrangler deploy`:+ *+ * 1. Note the deployed URL (e.g., https://my-mcp.my-account.workers.dev)+ *+ * 2. Test the endpoint:+ * curl https://my-mcp.my-account.workers.dev/sse+ * Should return: {"name":"My MCP Server", ...} (not 404!)+ *+ * 3. Update Claude Desktop config with EXACT URL from step 2:+ * ~/.config/claude/claude_desktop_config.json:+ * {+ * "mcpServers": {+ * "my-mcp": {+ * "url": "https://my-mcp.my-account.workers.dev/sse"+ * }+ * }+ * }+ *+ * 4. Restart Claude Desktop+ *+ * 5. Verify connection in Claude Desktop (check for tools)+ *+ * ═══════════════════════════════════════════════════════════════+ */++import { McpAgent } from "agents/mcp";+import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";+import { z } from "zod";++type Env = {};++/**+ * Minimal MCP server with ONE simple tool+ */+export class MyMCP extends McpAgent<Env> {+ server = new McpServer({+ name: "My MCP Server",+ version: "1.0.0",+ });++ async init() {+ // One simple tool to verify connection+ this.server.tool(+ "echo",+ "Echo back the provided message (useful for testing connection)",+ {+ message: z.string().describe("The message to echo back"),+ },+ async ({ message }) => ({+ content: [+ {+ type: "text",+ text: `Echo: ${message}`,+ },+ ],+ })+ );+ }+}++/**+ * Worker fetch handler demonstrating URL configuration+ *+ * ═══════════════════════════════════════════════════════════════+ * 🔍 HOW THIS WORKS+ * ═══════════════════════════════════════════════════════════════+ *+ * Request flow:+ * 1. Client sends: https://worker.dev/sse+ * 2. Worker receives request+ * 3. Extract pathname: new URL(request.url).pathname === "/sse"+ * 4. Check: pathname.startsWith("/sse") → TRUE+ * 5. Call: MyMCP.serveSSE("/sse").fetch(...) → Handle MCP request+ * 6. MCP tools available at:+ * - /sse/tools/list+ * - /sse/tools/call+ * - etc.+ *+ * If client sends: https://worker.dev (missing /sse):+ * 1. pathname === "/"+ * 2. Check: pathname.startsWith("/sse") → FALSE+ * 3. Falls through to 404+ *+ * ═══════════════════════════════════════════════════════════════+ */+export default {+ async fetch(+ request: Request,+ env: Env,+ ctx: ExecutionContext+ ): Promise<Response> {+ const { pathname } = new URL(request.url);++ // ═══════════════════════════════════════════════════════════════+ // SSE Transport at /sse+ // ═══════════════════════════════════════════════════════════════+ // This matches:+ // - /sse (initial connection)+ // - /sse/tools/list (list available tools)+ // - /sse/tools/call (execute tool)+ // - /sse/resources/list (list resources)+ // - etc.+ //+ // Client URL MUST be: https://worker.dev/sse+ // ═══════════════════════════════════════════════════════════════+ if (pathname.startsWith("/sse")) {+ return MyMCP.serveSSE("/sse").fetch(request, env, ctx);+ }++ // ═══════════════════════════════════════════════════════════════+ // Health Check Endpoint+ // ═══════════════════════════════════════════════════════════════+ // Test with: curl https://YOUR-WORKER.workers.dev/+ // Useful for:+ // - Verifying Worker is deployed+ // - Debugging connection issues+ // - Discovering available transports+ // ═══════════════════════════════════════════════════════════════+ if (pathname === "/" || pathname === "/health") {+ return new Response(+ JSON.stringify(+ {+ name: "My MCP Server",+ version: "1.0.0",+ transports: {+ sse: "/sse",+ },+ status: "ok",+ timestamp: new Date().toISOString(),+ help: {+ clientConfig: {+ url: `${new URL(request.url).origin}/sse`,+ },+ testCommand: `curl ${new URL(request.url).origin}/sse`,+ },+ },+ null,+ 2+ ),+ {+ headers: {+ "Content-Type": "application/json",+ },+ }+ );+ }++ // ═══════════════════════════════════════════════════════════════+ // 404 Not Found+ // ═══════════════════════════════════════════════════════════════+ // If you're seeing this:+ // - Check client URL includes /sse+ // - Try: curl https://YOUR-WORKER.workers.dev/ to see available paths+ // ═══════════════════════════════════════════════════════════════+ return new Response(+ JSON.stringify({+ error: "Not Found",+ requestedPath: pathname,+ availablePaths: ["/sse", "/", "/health"],+ hint: "Client URL must be: https://YOUR-WORKER.workers.dev/sse",+ }),+ {+ status: 404,+ headers: { "Content-Type": "application/json" },+ }+ );+ },+};diff --git a/skills/cloudflare-mcp-server/templates/mcp-oauth-proxy.ts b/skills/cloudflare-mcp-server/templates/mcp-oauth-proxy.tsindex abc09f6f..8a443b80 100644--- a/skills/cloudflare-mcp-server/templates/mcp-oauth-proxy.ts+++ b/skills/cloudflare-mcp-server/templates/mcp-oauth-proxy.ts@@ -7,6 +7,36 @@* Perfect for: Authenticated API access, user-scoped tools** Based on: https://github.com/cloudflare/ai/tree/main/demos/remote-mcp-github-oauth+ *+ * ⚠️ CRITICAL OAuth URL CONFIGURATION:+ *+ * ALL OAuth URLs must use the SAME domain and protocol!+ *+ * Client configuration after deployment:+ * {+ * "mcpServers": {+ * "github-mcp": {+ * "url": "https://YOUR-WORKER.workers.dev/sse",+ * "auth": {+ * "type": "oauth",+ * "authorizationUrl": "https://YOUR-WORKER.workers.dev/authorize",+ * "tokenUrl": "https://YOUR-WORKER.workers.dev/token"+ * }+ * }+ * }+ * }+ *+ * Common mistakes:+ * ❌ Mixed protocols: http://... and https://...+ * ❌ Missing /sse in main URL+ * ❌ Wrong domain after deployment (still using localhost)+ * ❌ Typos in endpoint paths (/authorize vs /auth)+ *+ * Post-deployment checklist:+ * 1. Deploy: npx wrangler deploy+ * 2. Note deployed URL+ * 3. Update ALL three URLs in client config+ * 4. Test OAuth flow in Claude Desktop*/import { McpAgent } from "agents/mcp";