Skip to content

Skills for Claude Code CLI such as full stack dev Cloudflare, React, Tailwind v4, and AI integrations.

cloudflare-mcp-server v2.1.0 - Official templates + integrations

Jezdb0319a74a95
diff --git a/skills/cloudflare-mcp-server/.claude-plugin/plugin.json b/skills/cloudflare-mcp-server/.claude-plugin/plugin.json
index 1fbf637c..10a01d36 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 22+ common errors including URL path mismatches, transport configuration mistakes",
- "version": "2.0.0",
+ "version": "2.1.0",
"author": {
"name": "Jeremy Dawes",
"email": "[email protected]"
diff --git a/skills/cloudflare-mcp-server/README.md b/skills/cloudflare-mcp-server/README.md
index a434f0fb..e3a8ca24 100644
--- a/skills/cloudflare-mcp-server/README.md
+++ b/skills/cloudflare-mcp-server/README.md
@@ -8,7 +8,7 @@
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**: 2.0.0 | **Last Verified**: 2025-11-08
+**Version**: 2.1.0 | **Last Verified**: 2025-11-08
---
@@ -193,12 +193,52 @@ Your MCP server is live! πŸŽ‰
---
-## Included Templates
+## πŸš€ Official Cloudflare Templates (Recommended Starting Point)
+
+**Before using this skill's templates**, start with Cloudflare's official starters:
+
+```bash
+# Gold standard: Authless MCP server (50 lines, production-ready)
+npm create cloudflare@latest -- my-mcp \
+ --template=cloudflare/ai/demos/remote-mcp-authless
+
+# With GitHub OAuth + Workers AI
+npm create cloudflare@latest -- my-mcp \
+ --template=cloudflare/ai/demos/remote-mcp-github-oauth
+
+# With Google OAuth
+npm create cloudflare@latest -- my-mcp \
+ --template=cloudflare/ai/demos/remote-mcp-google-oauth
+```
+
+**12+ auth variants available** (Auth0, AuthKit, Logto, Cloudflare Access, Bearer tokens, etc.)
+
+**See SKILL.md for complete template list**
+
+---
+
+## This Skill's Templates (For Learning & Error Prevention)
+
+**Use these when you need:**
+- Comprehensive error prevention (22+ documented errors)
+- Detailed comments explaining every decision
+- Integration examples (Workers AI, D1, Bearer auth)
+- Defensive patterns and validation
### TypeScript Templates
-1. **basic-mcp-server.ts** - Simple MCP server (no auth)
-2. **mcp-oauth-proxy.ts** - GitHub OAuth integration
-3. **mcp-stateful-do.ts** - Durable Objects for state
+
+**Fundamentals:**
+1. **mcp-http-fundamentals.ts** - Minimal example (URL configuration focus)
+2. **basic-mcp-server.ts** - Production starter (comprehensive comments)
+
+**Authentication:**
+3. **mcp-bearer-auth.ts** - Bearer token authentication (NEW! v2.1)
+4. **mcp-oauth-proxy.ts** - GitHub OAuth integration
+
+**Integrations:**
+5. **mcp-with-workers-ai.ts** - Image/text generation with Workers AI (NEW! v2.1)
+6. **mcp-with-d1.ts** - Database CRUD operations with D1 (NEW! v2.1)
+7. **mcp-stateful-do.ts** - Durable Objects for session state
### Configuration Templates
1. **wrangler-basic.jsonc** - Basic Worker config
@@ -207,15 +247,24 @@ Your MCP server is live! πŸŽ‰
4. **package.json** - Dependencies
### Reference Docs
-1. **authentication.md** - Auth patterns comparison matrix
-2. **transport.md** - SSE vs HTTP technical details
-3. **oauth-providers.md** - GitHub, Google, Azure setup guides
-4. **common-issues.md** - Error troubleshooting deep-dives
-5. **official-examples.md** - Curated Cloudflare examples
+
+**Transport & Fundamentals:**
+1. **http-transport-fundamentals.md** - URL path configuration deep-dive (NEW! v2.0)
+2. **transport-comparison.md** - SSE vs HTTP technical comparison (NEW! v2.0)
+3. **debugging-guide.md** - Complete troubleshooting flowchart (NEW! v2.0)
+
+**Authentication & Integration:**
+4. **authentication.md** - Auth patterns comparison matrix
+5. **oauth-providers.md** - GitHub, Google, Azure setup guides
+6. **common-issues.md** - Error troubleshooting deep-dives
+
+**Production Examples:**
+7. **official-examples.md** - Curated Cloudflare examples
+8. **Study production servers**: https://github.com/cloudflare/mcp-server-cloudflare (15 real-world integrations)
---
-## 15 Errors Prevented
+## 22 Errors Prevented
This skill documents and prevents these common mistakes:
diff --git a/skills/cloudflare-mcp-server/SKILL.md b/skills/cloudflare-mcp-server/SKILL.md
index dbb9049e..0784b870 100644
--- a/skills/cloudflare-mcp-server/SKILL.md
+++ b/skills/cloudflare-mcp-server/SKILL.md
@@ -7,7 +7,7 @@ description: |
license: MIT
allowed-tools: ["Read", "Write", "Edit", "Bash", "Glob", "Grep"]
metadata:
- version: "2.0.0"
+ version: "2.1.0"
last_verified: "2025-11-08"
sdk_versions:
mcp_sdk: "1.21.0"
@@ -40,10 +40,107 @@ This skill teaches you to build **remote MCP servers** on Cloudflare - the ONLY
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
+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
+```
+
+**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!
+
+---
+
+### 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
---
diff --git a/skills/cloudflare-mcp-server/templates/mcp-bearer-auth.ts b/skills/cloudflare-mcp-server/templates/mcp-bearer-auth.ts
new file mode 100644
index 00000000..19ef53b0
--- /dev/null
+++ b/skills/cloudflare-mcp-server/templates/mcp-bearer-auth.ts
@@ -0,0 +1,384 @@
+/**
+ * MCP Server with Bearer Token Authentication
+ *
+ * Demonstrates Bearer token authentication pattern for custom auth systems.
+ * Shows middleware pattern for validating Authorization headers.
+ *
+ * Based on: https://github.com/cloudflare/ai/tree/main/demos/mcp-server-bearer-auth
+ *
+ * ═══════════════════════════════════════════════════════════════
+ * πŸ” BEARER TOKEN AUTHENTICATION
+ * ═══════════════════════════════════════════════════════════════
+ *
+ * This pattern is for:
+ * - Custom authentication systems
+ * - API key validation
+ * - Service-to-service communication
+ * - Integration with existing auth backends
+ *
+ * NOT for:
+ * - OAuth (use OAuth Proxy pattern instead)
+ * - Public APIs (use authless pattern)
+ * - Enterprise SSO (use Auth0/Okta integrations)
+ *
+ * ═══════════════════════════════════════════════════════════════
+ * πŸ“‹ HOW IT WORKS
+ * ═══════════════════════════════════════════════════════════════
+ *
+ * 1. Client sends request with Authorization header:
+ * Authorization: Bearer YOUR_TOKEN_HERE
+ *
+ * 2. Worker validates token (check against database, external API, etc.)
+ *
+ * 3. If valid: Pass token to MCP server via ctx.props
+ *
+ * 4. If invalid: Return 401 Unauthorized
+ *
+ * 5. MCP tools can access token via this.props.bearerToken
+ *
+ * ═══════════════════════════════════════════════════════════════
+ * πŸ”§ CONFIGURATION
+ * ═══════════════════════════════════════════════════════════════
+ *
+ * Option 1: Static token list (simple, for development)
+ * Option 2: Check against KV store (production)
+ * Option 3: Validate with external API (most flexible)
+ *
+ * This template shows all three approaches.
+ *
+ * ═══════════════════════════════════════════════════════════════
+ */
+
+import { McpAgent } from "agents/mcp";
+import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
+import { z } from "zod";
+
+type Env = {
+ // Optional: KV for token storage
+ AUTH_TOKENS?: KVNamespace;
+
+ // Optional: API endpoint for token validation
+ AUTH_API_URL?: string;
+};
+
+/**
+ * Props passed to MCP server after authentication
+ */
+type Props = {
+ bearerToken: string; // The validated token
+ userId?: string; // Optional: User ID from token
+};
+
+/**
+ * MCP Server with bearer token authentication
+ */
+export class MyMCP extends McpAgent<Env, Record<string, never>, Props> {
+ server = new McpServer({
+ name: "Bearer Auth MCP Server",
+ version: "1.0.0",
+ });
+
+ async init() {
+ // ═══════════════════════════════════════════════════════════════
+ // TOOL 1: Echo with Auth Info
+ // ═══════════════════════════════════════════════════════════════
+ // Demonstrates accessing bearer token from props
+ // ═══════════════════════════════════════════════════════════════
+ this.server.tool(
+ "echo_auth",
+ "Echo back your message along with auth info",
+ {
+ message: z.string().describe("Message to echo"),
+ },
+ async ({ message }) => {
+ // Access authenticated user info
+ const token = this.props?.bearerToken || "none";
+ const userId = this.props?.userId || "unknown";
+
+ return {
+ content: [
+ {
+ type: "text",
+ text: `Message: ${message}\n\nAuth Info:\n- Token: ${token.substring(0, 10)}...\n- User ID: ${userId}`,
+ },
+ ],
+ };
+ }
+ );
+
+ // ═══════════════════════════════════════════════════════════════
+ // TOOL 2: Protected Tool Example
+ // ═══════════════════════════════════════════════════════════════
+ // Only accessible to authenticated users
+ // ═══════════════════════════════════════════════════════════════
+ this.server.tool(
+ "protected_action",
+ "Perform a protected action (requires auth)",
+ {
+ action: z.string().describe("Action to perform"),
+ },
+ async ({ action }) => {
+ // Verify authentication (should always pass if middleware worked)
+ if (!this.props?.bearerToken) {
+ return {
+ content: [
+ {
+ type: "text",
+ text: "Error: Unauthenticated. This should never happen if middleware is working.",
+ },
+ ],
+ isError: true,
+ };
+ }
+
+ // Perform protected action
+ return {
+ content: [
+ {
+ type: "text",
+ text: `Protected action "${action}" performed successfully by user ${this.props.userId}`,
+ },
+ ],
+ };
+ }
+ );
+ }
+}
+
+/**
+ * Validate bearer token
+ *
+ * Three validation strategies (choose one):
+ * 1. Static list (development)
+ * 2. KV store lookup (production)
+ * 3. External API validation (most flexible)
+ */
+async function validateToken(
+ token: string,
+ env: Env
+): Promise<{ valid: boolean; userId?: string }> {
+ // ═══════════════════════════════════════════════════════════════
+ // Strategy 1: Static Token List (Development Only!)
+ // ═══════════════════════════════════════════════════════════════
+ // ⚠️ DON'T use in production! Tokens exposed in code.
+ // ═══════════════════════════════════════════════════════════════
+ const VALID_TOKENS = {
+ "dev-token-123": "user-1",
+ "dev-token-456": "user-2",
+ };
+
+ if (VALID_TOKENS[token]) {
+ return { valid: true, userId: VALID_TOKENS[token] };
+ }
+
+ // ═══════════════════════════════════════════════════════════════
+ // Strategy 2: KV Store Lookup (Production)
+ // ═══════════════════════════════════════════════════════════════
+ // Store tokens in KV: { "token-abc123": "user-id" }
+ // ═══════════════════════════════════════════════════════════════
+ if (env.AUTH_TOKENS) {
+ const userId = await env.AUTH_TOKENS.get(token);
+ if (userId) {
+ return { valid: true, userId };
+ }
+ }
+
+ // ═══════════════════════════════════════════════════════════════
+ // Strategy 3: External API Validation (Most Flexible)
+ // ═══════════════════════════════════════════════════════════════
+ // Validate token with external auth service
+ // ═══════════════════════════════════════════════════════════════
+ if (env.AUTH_API_URL) {
+ try {
+ const response = await fetch(`${env.AUTH_API_URL}/validate`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: `Bearer ${token}`,
+ },
+ });
+
+ if (response.ok) {
+ const data = await response.json();
+ return { valid: true, userId: data.userId };
+ }
+ } catch (error) {
+ console.error("Token validation error:", error);
+ }
+ }
+
+ // ═══════════════════════════════════════════════════════════════
+ // Token Invalid
+ // ═══════════════════════════════════════════════════════════════
+ return { valid: false };
+}
+
+/**
+ * Worker fetch handler with bearer auth middleware
+ *
+ * ═══════════════════════════════════════════════════════════════
+ * πŸ” AUTHENTICATION FLOW
+ * ═══════════════════════════════════════════════════════════════
+ *
+ * 1. Extract Authorization header
+ * 2. Validate bearer token
+ * 3. If valid: Pass to MCP server with user context
+ * 4. If invalid: Return 401 Unauthorized
+ *
+ * Client configuration:
+ * {
+ * "mcpServers": {
+ * "my-mcp": {
+ * "url": "https://YOUR-WORKER.workers.dev/sse",
+ * "headers": {
+ * "Authorization": "Bearer YOUR_TOKEN_HERE"
+ * }
+ * }
+ * }
+ * }
+ *
+ * ═══════════════════════════════════════════════════════════════
+ */
+export default {
+ async fetch(
+ request: Request,
+ env: Env,
+ ctx: ExecutionContext
+ ): Promise<Response> {
+ const { pathname } = new URL(request.url);
+
+ // ═══════════════════════════════════════════════════════════════
+ // Handle CORS Preflight (no auth required)
+ // ═══════════════════════════════════════════════════════════════
+ 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",
+ },
+ });
+ }
+
+ // ═══════════════════════════════════════════════════════════════
+ // Health Check (no auth required)
+ // ═══════════════════════════════════════════════════════════════
+ if (pathname === "/" || pathname === "/health") {
+ return new Response(
+ JSON.stringify({
+ name: "Bearer Auth MCP Server",
+ version: "1.0.0",
+ transports: {
+ sse: "/sse",
+ http: "/mcp",
+ },
+ auth: "Bearer token required",
+ status: "ok",
+ timestamp: new Date().toISOString(),
+ }),
+ {
+ headers: {
+ "Content-Type": "application/json",
+ "Access-Control-Allow-Origin": "*",
+ },
+ }
+ );
+ }
+
+ // ═══════════════════════════════════════════════════════════════
+ // Authentication Middleware
+ // ═══════════════════════════════════════════════════════════════
+ // Extract and validate bearer token before serving MCP
+ // ═══════════════════════════════════════════════════════════════
+
+ // 1. Extract Authorization header
+ const authHeader = request.headers.get("Authorization");
+
+ if (!authHeader) {
+ return new Response(
+ JSON.stringify({
+ error: "Unauthorized",
+ message: "Missing Authorization header",
+ hint: 'Include header: Authorization: Bearer YOUR_TOKEN',
+ }),
+ {
+ status: 401,
+ headers: {
+ "Content-Type": "application/json",
+ "WWW-Authenticate": 'Bearer realm="MCP Server"',
+ },
+ }
+ );
+ }
+
+ // 2. Check Bearer format
+ if (!authHeader.startsWith("Bearer ")) {
+ return new Response(
+ JSON.stringify({
+ error: "Unauthorized",
+ message: "Invalid Authorization header format",
+ hint: 'Use format: Authorization: Bearer YOUR_TOKEN',
+ }),
+ {
+ status: 401,
+ headers: {
+ "Content-Type": "application/json",
+ "WWW-Authenticate": 'Bearer realm="MCP Server"',
+ },
+ }
+ );
+ }
+
+ // 3. Extract token
+ const token = authHeader.substring(7); // Remove "Bearer " prefix
+
+ // 4. Validate token
+ const { valid, userId } = await validateToken(token, env);
+
+ if (!valid) {
+ return new Response(
+ JSON.stringify({
+ error: "Unauthorized",
+ message: "Invalid bearer token",
+ }),
+ {
+ status: 401,
+ headers: {
+ "Content-Type": "application/json",
+ "WWW-Authenticate": 'Bearer realm="MCP Server"',
+ },
+ }
+ );
+ }
+
+ // 5. Authentication successful! Set props and pass to MCP server
+ const props: Props = {
+ bearerToken: token,
+ userId,
+ };
+
+ // ═══════════════════════════════════════════════════════════════
+ // SSE Transport (with auth)
+ // ═══════════════════════════════════════════════════════════════
+ if (pathname.startsWith("/sse")) {
+ return MyMCP.serveSSE("/sse").fetch(request, env, {
+ ...ctx,
+ props,
+ });
+ }
+
+ // ═══════════════════════════════════════════════════════════════
+ // HTTP Transport (with auth)
+ // ═══════════════════════════════════════════════════════════════
+ if (pathname.startsWith("/mcp")) {
+ return MyMCP.serve("/mcp").fetch(request, env, {
+ ...ctx,
+ props,
+ });
+ }
+
+ return new Response("Not Found", { status: 404 });
+ },
+};
diff --git a/skills/cloudflare-mcp-server/templates/mcp-with-d1.ts b/skills/cloudflare-mcp-server/templates/mcp-with-d1.ts
new file mode 100644
index 00000000..40a73bb9
--- /dev/null
+++ b/skills/cloudflare-mcp-server/templates/mcp-with-d1.ts
@@ -0,0 +1,587 @@
+/**
+ * MCP Server with D1 Database Integration
+ *
+ * Demonstrates D1 (Cloudflare's SQL database) integration for persistent data storage.
+ * Shows CRUD operations, SQL queries, and error handling.
+ *
+ * ═══════════════════════════════════════════════════════════════
+ * πŸ’Ύ D1 DATABASE INTEGRATION
+ * ═══════════════════════════════════════════════════════════════
+ *
+ * This template shows:
+ * 1. D1 binding configuration
+ * 2. Schema creation and migrations
+ * 3. CRUD operations (Create, Read, Update, Delete)
+ * 4. SQL query patterns
+ * 5. Error handling for database operations
+ * 6. Prepared statements (SQL injection prevention)
+ *
+ * ═══════════════════════════════════════════════════════════════
+ * πŸ“‹ REQUIRED SETUP
+ * ═══════════════════════════════════════════════════════════════
+ *
+ * 1. Create D1 database:
+ * npx wrangler d1 create my-database
+ *
+ * 2. Add binding to wrangler.jsonc:
+ * {
+ * "d1_databases": [
+ * {
+ * "binding": "DB",
+ * "database_name": "my-database",
+ * "database_id": "YOUR_DATABASE_ID"
+ * }
+ * ]
+ * }
+ *
+ * 3. Create schema (run locally or in wrangler):
+ * npx wrangler d1 execute my-database --local --file=schema.sql
+ *
+ * schema.sql:
+ * ```sql
+ * CREATE TABLE IF NOT EXISTS users (
+ * id INTEGER PRIMARY KEY AUTOINCREMENT,
+ * name TEXT NOT NULL,
+ * email TEXT UNIQUE NOT NULL,
+ * created_at DATETIME DEFAULT CURRENT_TIMESTAMP
+ * );
+ * ```
+ *
+ * 4. Deploy:
+ * npx wrangler deploy
+ *
+ * Pricing: https://developers.cloudflare.com/d1/platform/pricing/
+ * - Free tier: 5 GB storage, 5 million reads/day
+ * - Pay-as-you-go after free tier
+ *
+ * ═══════════════════════════════════════════════════════════════
+ */
+
+import { McpAgent } from "agents/mcp";
+import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
+import { z } from "zod";
+
+type Env = {
+ DB: D1Database; // D1 binding (configured in wrangler.jsonc)
+};
+
+/**
+ * User type (matches database schema)
+ */
+type User = {
+ id: number;
+ name: string;
+ email: string;
+ created_at: string;
+};
+
+/**
+ * MCP Server with D1 database tools
+ */
+export class MyMCP extends McpAgent<Env> {
+ server = new McpServer({
+ name: "D1 Database MCP Server",
+ version: "1.0.0",
+ });
+
+ async init() {
+ // ═══════════════════════════════════════════════════════════════
+ // TOOL 1: Create User
+ // ═══════════════════════════════════════════════════════════════
+ // Demonstrates: INSERT with prepared statements
+ // ═══════════════════════════════════════════════════════════════
+ this.server.tool(
+ "create_user",
+ "Create a new user in the database",
+ {
+ name: z.string().describe("User's full name"),
+ email: z.string().email().describe("User's email address"),
+ },
+ async ({ name, email }) => {
+ try {
+ // Use prepared statement to prevent SQL injection
+ const result = await this.env.DB.prepare(
+ "INSERT INTO users (name, email) VALUES (?, ?)"
+ )
+ .bind(name, email)
+ .run();
+
+ // Check if insert was successful
+ if (!result.success) {
+ throw new Error("Failed to insert user");
+ }
+
+ return {
+ content: [
+ {
+ type: "text",
+ text: `User created successfully!\nID: ${result.meta.last_row_id}\nName: ${name}\nEmail: ${email}`,
+ },
+ ],
+ };
+ } catch (error) {
+ // Handle duplicate email error (UNIQUE constraint)
+ if (error.message.includes("UNIQUE constraint failed")) {
+ return {
+ content: [
+ {
+ type: "text",
+ text: `Error: Email "${email}" is already registered.`,
+ },
+ ],
+ isError: true,
+ };
+ }
+
+ return {
+ content: [
+ {
+ type: "text",
+ text: `Error creating user: ${error.message}`,
+ },
+ ],
+ isError: true,
+ };
+ }
+ }
+ );
+
+ // ═══════════════════════════════════════════════════════════════
+ // TOOL 2: Get User by ID
+ // ═══════════════════════════════════════════════════════════════
+ // Demonstrates: SELECT with WHERE clause
+ // ═══════════════════════════════════════════════════════════════
+ this.server.tool(
+ "get_user",
+ "Get a user by their ID",
+ {
+ id: z.number().int().positive().describe("User ID"),
+ },
+ async ({ id }) => {
+ try {
+ const user = await this.env.DB.prepare(
+ "SELECT * FROM users WHERE id = ?"
+ )
+ .bind(id)
+ .first<User>();
+
+ if (!user) {
+ return {
+ content: [
+ {
+ type: "text",
+ text: `User with ID ${id} not found.`,
+ },
+ ],
+ isError: true,
+ };
+ }
+
+ return {
+ content: [
+ {
+ type: "text",
+ text: JSON.stringify(user, null, 2),
+ },
+ ],
+ };
+ } catch (error) {
+ return {
+ content: [
+ {
+ type: "text",
+ text: `Error fetching user: ${error.message}`,
+ },
+ ],
+ isError: true,
+ };
+ }
+ }
+ );
+
+ // ═══════════════════════════════════════════════════════════════
+ // TOOL 3: List All Users
+ // ═══════════════════════════════════════════════════════════════
+ // Demonstrates: SELECT all rows with pagination
+ // ═══════════════════════════════════════════════════════════════
+ this.server.tool(
+ "list_users",
+ "List all users (with optional pagination)",
+ {
+ limit: z
+ .number()
+ .int()
+ .positive()
+ .max(100)
+ .default(10)
+ .optional()
+ .describe("Maximum number of users to return (default 10, max 100)"),
+ offset: z
+ .number()
+ .int()
+ .min(0)
+ .default(0)
+ .optional()
+ .describe("Number of users to skip (for pagination, default 0)"),
+ },
+ async ({ limit = 10, offset = 0 }) => {
+ try {
+ // Get users with pagination
+ const { results: users } = await this.env.DB.prepare(
+ "SELECT * FROM users ORDER BY created_at DESC LIMIT ? OFFSET ?"
+ )
+ .bind(limit, offset)
+ .all<User>();
+
+ // Get total count
+ const { count } = await this.env.DB.prepare(
+ "SELECT COUNT(*) as count FROM users"
+ ).first<{ count: number }>();
+
+ return {
+ content: [
+ {
+ type: "text",
+ text: JSON.stringify(
+ {
+ users,
+ pagination: {
+ total: count,
+ limit,
+ offset,
+ showing: users.length,
+ },
+ },
+ null,
+ 2
+ ),
+ },
+ ],
+ };
+ } catch (error) {
+ return {
+ content: [
+ {
+ type: "text",
+ text: `Error listing users: ${error.message}`,
+ },
+ ],
+ isError: true,
+ };
+ }
+ }
+ );
+
+ // ═══════════════════════════════════════════════════════════════
+ // TOOL 4: Update User
+ // ═══════════════════════════════════════════════════════════════
+ // Demonstrates: UPDATE with prepared statements
+ // ═══════════════════════════════════════════════════════════════
+ this.server.tool(
+ "update_user",
+ "Update a user's information",
+ {
+ id: z.number().int().positive().describe("User ID to update"),
+ name: z.string().optional().describe("New name (optional)"),
+ email: z.string().email().optional().describe("New email (optional)"),
+ },
+ async ({ id, name, email }) => {
+ try {
+ // Build dynamic UPDATE query based on provided fields
+ const updates: string[] = [];
+ const values: (string | number)[] = [];
+
+ if (name !== undefined) {
+ updates.push("name = ?");
+ values.push(name);
+ }
+ if (email !== undefined) {
+ updates.push("email = ?");
+ values.push(email);
+ }
+
+ if (updates.length === 0) {
+ return {
+ content: [
+ {
+ type: "text",
+ text: "No fields to update. Provide name or email.",
+ },
+ ],
+ isError: true,
+ };
+ }
+
+ // Add ID to values array
+ values.push(id);
+
+ // Execute UPDATE
+ const result = await this.env.DB.prepare(
+ `UPDATE users SET ${updates.join(", ")} WHERE id = ?`
+ )
+ .bind(...values)
+ .run();
+
+ if (!result.success) {
+ throw new Error("Failed to update user");
+ }
+
+ // Fetch updated user
+ const updatedUser = await this.env.DB.prepare(
+ "SELECT * FROM users WHERE id = ?"
+ )
+ .bind(id)
+ .first<User>();
+
+ return {
+ content: [
+ {
+ type: "text",
+ text: `User updated successfully!\n\n${JSON.stringify(updatedUser, null, 2)}`,
+ },
+ ],
+ };
+ } catch (error) {
+ if (error.message.includes("UNIQUE constraint failed")) {
+ return {
+ content: [
+ {
+ type: "text",
+ text: `Error: Email "${email}" is already in use.`,
+ },
+ ],
+ isError: true,
+ };
+ }
+
+ return {
+ content: [
+ {
+ type: "text",
+ text: `Error updating user: ${error.message}`,
+ },
+ ],
+ isError: true,
+ };
+ }
+ }
+ );
+
+ // ═══════════════════════════════════════════════════════════════
+ // TOOL 5: Delete User
+ // ═══════════════════════════════════════════════════════════════
+ // Demonstrates: DELETE with confirmation
+ // ═══════════════════════════════════════════════════════════════
+ this.server.tool(
+ "delete_user",
+ "Delete a user from the database (⚠️ permanent!)",
+ {
+ id: z.number().int().positive().describe("User ID to delete"),
+ },
+ async ({ id }) => {
+ try {
+ // Get user before deleting (for confirmation message)
+ const user = await this.env.DB.prepare(
+ "SELECT * FROM users WHERE id = ?"
+ )
+ .bind(id)
+ .first<User>();
+
+ if (!user) {
+ return {
+ content: [
+ {
+ type: "text",
+ text: `User with ID ${id} not found.`,
+ },
+ ],
+ isError: true,
+ };
+ }
+
+ // Delete user
+ const result = await this.env.DB.prepare(
+ "DELETE FROM users WHERE id = ?"
+ )
+ .bind(id)
+ .run();
+
+ if (!result.success) {
+ throw new Error("Failed to delete user");
+ }
+
+ return {
+ content: [
+ {
+ type: "text",
+ text: `User deleted successfully!\n\nDeleted: ${user.name} (${user.email})`,
+ },
+ ],
+ };
+ } catch (error) {
+ return {
+ content: [
+ {
+ type: "text",
+ text: `Error deleting user: ${error.message}`,
+ },
+ ],
+ isError: true,
+ };
+ }
+ }
+ );
+
+ // ═══════════════════════════════════════════════════════════════
+ // TOOL 6: Search Users
+ // ═══════════════════════════════════════════════════════════════
+ // Demonstrates: LIKE queries for text search
+ // ═══════════════════════════════════════════════════════════════
+ this.server.tool(
+ "search_users",
+ "Search users by name or email",
+ {
+ query: z.string().describe("Search term (name or email)"),
+ },
+ async ({ query }) => {
+ try {
+ const searchPattern = `%${query}%`;
+
+ const { results: users } = await this.env.DB.prepare(
+ "SELECT * FROM users WHERE name LIKE ? OR email LIKE ? ORDER BY created_at DESC"
+ )
+ .bind(searchPattern, searchPattern)
+ .all<User>();
+
+ return {
+ content: [
+ {
+ type: "text",
+ text: JSON.stringify(
+ {
+ query,
+ results: users.length,
+ users,
+ },
+ null,
+ 2
+ ),
+ },
+ ],
+ };
+ } catch (error) {
+ return {
+ content: [
+ {
+ type: "text",
+ text: `Error searching users: ${error.message}`,
+ },
+ ],
+ isError: true,
+ };
+ }
+ }
+ );
+ }
+}
+
+/**
+ * Worker fetch handler
+ *
+ * ═══════════════════════════════════════════════════════════════
+ * πŸ”§ SETUP CHECKLIST
+ * ═══════════════════════════════════════════════════════════════
+ *
+ * 1. Create D1 database:
+ * npx wrangler d1 create my-database
+ *
+ * 2. Note the database_id from output
+ *
+ * 3. Add to wrangler.jsonc:
+ * {
+ * "d1_databases": [{
+ * "binding": "DB",
+ * "database_name": "my-database",
+ * "database_id": "YOUR_ID_HERE"
+ * }]
+ * }
+ *
+ * 4. Create schema:
+ * npx wrangler d1 execute my-database --local --command \
+ * "CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, email TEXT UNIQUE NOT NULL, created_at DATETIME DEFAULT CURRENT_TIMESTAMP)"
+ *
+ * 5. Deploy:
+ * npx wrangler deploy
+ *
+ * 6. Client URL:
+ * "url": "https://YOUR-WORKER.workers.dev/sse"
+ *
+ * ═══════════════════════════════════════════════════════════════
+ */
+export default {
+ async fetch(
+ request: Request,
+ env: Env,
+ ctx: ExecutionContext
+ ): Promise<Response> {
+ const { pathname } = new URL(request.url);
+
+ // 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",
+ },
+ });
+ }
+
+ // SSE transport
+ if (pathname.startsWith("/sse")) {
+ return MyMCP.serveSSE("/sse").fetch(request, env, ctx);
+ }
+
+ // HTTP transport
+ if (pathname.startsWith("/mcp")) {
+ return MyMCP.serve("/mcp").fetch(request, env, ctx);
+ }
+
+ // Health check with DB binding info
+ if (pathname === "/" || pathname === "/health") {
+ return new Response(
+ JSON.stringify({
+ name: "D1 Database MCP Server",
+ version: "1.0.0",
+ transports: {
+ sse: "/sse",
+ http: "/mcp",
+ },
+ features: {
+ database: !!env.DB,
+ },
+ tools: [
+ "create_user",
+ "get_user",
+ "list_users",
+ "update_user",
+ "delete_user",
+ "search_users",
+ ],
+ status: "ok",
+ timestamp: new Date().toISOString(),
+ }),
+ {
+ headers: {
+ "Content-Type": "application/json",
+ "Access-Control-Allow-Origin": "*",
+ },
+ }
+ );
+ }
+
+ return new Response("Not Found", { status: 404 });
+ },
+};
diff --git a/skills/cloudflare-mcp-server/templates/mcp-with-workers-ai.ts b/skills/cloudflare-mcp-server/templates/mcp-with-workers-ai.ts
new file mode 100644
index 00000000..89f086c5
--- /dev/null
+++ b/skills/cloudflare-mcp-server/templates/mcp-with-workers-ai.ts
@@ -0,0 +1,325 @@
+/**
+ * MCP Server with Workers AI Integration
+ *
+ * Demonstrates Workers AI integration for image and text generation.
+ * Shows how to use AI binding in MCP tools.
+ *
+ * Based on: https://github.com/cloudflare/ai/tree/main/demos/remote-mcp-github-oauth
+ *
+ * ═══════════════════════════════════════════════════════════════
+ * πŸ€– WORKERS AI INTEGRATION
+ * ═══════════════════════════════════════════════════════════════
+ *
+ * This template shows:
+ * 1. AI binding configuration (wrangler.jsonc)
+ * 2. Image generation with Flux
+ * 3. Text generation with Llama
+ * 4. Error handling for AI requests
+ * 5. Streaming responses
+ *
+ * ═══════════════════════════════════════════════════════════════
+ * πŸ“‹ REQUIRED CONFIGURATION
+ * ═══════════════════════════════════════════════════════════════
+ *
+ * wrangler.jsonc:
+ * {
+ * "ai": {
+ * "binding": "AI"
+ * }
+ * }
+ *
+ * No API keys required! Workers AI is built into Cloudflare Workers.
+ *
+ * Pricing: https://developers.cloudflare.com/workers-ai/platform/pricing/
+ * - Free tier: 10,000 Neurons per day
+ * - Image generation: ~500 Neurons per image
+ * - Text generation: Varies by token count
+ *
+ * ═══════════════════════════════════════════════════════════════
+ */
+
+import { McpAgent } from "agents/mcp";
+import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
+import { z } from "zod";
+
+type Env = {
+ AI: Ai; // Workers AI binding (configured in wrangler.jsonc)
+};
+
+/**
+ * MCP Server with Workers AI tools
+ */
+export class MyMCP extends McpAgent<Env> {
+ server = new McpServer({
+ name: "Workers AI MCP Server",
+ version: "1.0.0",
+ });
+
+ async init() {
+ // ═══════════════════════════════════════════════════════════════
+ // TOOL 1: Generate Image with Flux
+ // ═══════════════════════════════════════════════════════════════
+ // Model: @cf/black-forest-labs/flux-1-schnell
+ // Fast image generation model (2-4 seconds)
+ // Input: Text prompt β†’ Output: Base64-encoded PNG
+ // ═══════════════════════════════════════════════════════════════
+ this.server.tool(
+ "generate_image",
+ "Generate an image from a text prompt using Flux AI model",
+ {
+ prompt: z
+ .string()
+ .describe("Detailed description of the image to generate"),
+ num_steps: z
+ .number()
+ .min(1)
+ .max(8)
+ .default(4)
+ .optional()
+ .describe("Number of inference steps (1-8, default 4). Higher = better quality but slower"),
+ },
+ async ({ prompt, num_steps = 4 }) => {
+ try {
+ // Call Workers AI
+ const response = await this.env.AI.run(
+ "@cf/black-forest-labs/flux-1-schnell",
+ {
+ prompt,
+ num_steps,
+ }
+ );
+
+ // Response is a base64-encoded PNG image
+ const imageBase64 = (response as { image: string }).image;
+
+ return {
+ content: [
+ {
+ type: "text",
+ text: `Generated image from prompt: "${prompt}"`,
+ },
+ {
+ type: "image",
+ data: imageBase64,
+ mimeType: "image/png",
+ },
+ ],
+ };
+ } catch (error) {
+ return {
+ content: [
+ {
+ type: "text",
+ text: `Error generating image: ${error.message}`,
+ },
+ ],
+ isError: true,
+ };
+ }
+ }
+ );
+
+ // ═══════════════════════════════════════════════════════════════
+ // TOOL 2: Generate Text with Llama
+ // ═══════════════════════════════════════════════════════════════
+ // Model: @cf/meta/llama-3.1-8b-instruct
+ // Fast text generation model
+ // Input: User message β†’ Output: AI-generated text
+ // ═══════════════════════════════════════════════════════════════
+ this.server.tool(
+ "generate_text",
+ "Generate text using Llama AI model",
+ {
+ prompt: z.string().describe("The prompt or question for the AI"),
+ max_tokens: z
+ .number()
+ .min(1)
+ .max(2048)
+ .default(512)
+ .optional()
+ .describe("Maximum number of tokens to generate (default 512)"),
+ },
+ async ({ prompt, max_tokens = 512 }) => {
+ try {
+ // Call Workers AI
+ const response = await this.env.AI.run(
+ "@cf/meta/llama-3.1-8b-instruct",
+ {
+ messages: [
+ {
+ role: "user",
+ content: prompt,
+ },
+ ],
+ max_tokens,
+ }
+ );
+
+ // Extract generated text
+ const text = (response as { response: string }).response;
+
+ return {
+ content: [
+ {
+ type: "text",
+ text,
+ },
+ ],
+ };
+ } catch (error) {
+ return {
+ content: [
+ {
+ type: "text",
+ text: `Error generating text: ${error.message}`,
+ },
+ ],
+ isError: true,
+ };
+ }
+ }
+ );
+
+ // ═══════════════════════════════════════════════════════════════
+ // TOOL 3: List Available AI Models
+ // ═══════════════════════════════════════════════════════════════
+ // Shows all models available in Workers AI
+ // Useful for discovering what's available
+ // ═══════════════════════════════════════════════════════════════
+ this.server.tool(
+ "list_ai_models",
+ "List all available Workers AI models",
+ {},
+ async () => {
+ // This is a static list, but you could dynamically fetch from CF API
+ const models = [
+ {
+ name: "@cf/black-forest-labs/flux-1-schnell",
+ type: "Image Generation",
+ description: "Fast image generation (2-4s)",
+ },
+ {
+ name: "@cf/meta/llama-3.1-8b-instruct",
+ type: "Text Generation",
+ description: "Fast text generation",
+ },
+ {
+ name: "@cf/meta/llama-3.1-70b-instruct",
+ type: "Text Generation",
+ description: "High-quality text generation (slower)",
+ },
+ {
+ name: "@cf/openai/whisper",
+ type: "Speech Recognition",
+ description: "Audio transcription",
+ },
+ {
+ name: "@cf/baai/bge-base-en-v1.5",
+ type: "Text Embeddings",
+ description: "Generate embeddings for semantic search",
+ },
+ ];
+
+ return {
+ content: [
+ {
+ type: "text",
+ text: JSON.stringify(models, null, 2),
+ },
+ ],
+ };
+ }
+ );
+ }
+}
+
+/**
+ * Worker fetch handler
+ *
+ * ═══════════════════════════════════════════════════════════════
+ * πŸ”§ CONFIGURATION NOTES
+ * ═══════════════════════════════════════════════════════════════
+ *
+ * 1. AI Binding Setup (wrangler.jsonc):
+ * {
+ * "ai": {
+ * "binding": "AI"
+ * }
+ * }
+ *
+ * 2. Deploy:
+ * npx wrangler deploy
+ *
+ * 3. Test Tools:
+ * - generate_image: Creates PNG images from prompts
+ * - generate_text: Generates text responses
+ * - list_ai_models: Shows available models
+ *
+ * 4. Client URL:
+ * "url": "https://YOUR-WORKER.workers.dev/sse"
+ *
+ * ═══════════════════════════════════════════════════════════════
+ */
+export default {
+ async fetch(
+ request: Request,
+ env: Env,
+ ctx: ExecutionContext
+ ): Promise<Response> {
+ const { pathname } = new URL(request.url);
+
+ // 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",
+ },
+ });
+ }
+
+ // SSE transport
+ if (pathname.startsWith("/sse")) {
+ return MyMCP.serveSSE("/sse").fetch(request, env, ctx);
+ }
+
+ // HTTP transport
+ if (pathname.startsWith("/mcp")) {
+ return MyMCP.serve("/mcp").fetch(request, env, ctx);
+ }
+
+ // Health check with AI binding info
+ if (pathname === "/" || pathname === "/health") {
+ return new Response(
+ JSON.stringify({
+ name: "Workers AI MCP Server",
+ version: "1.0.0",
+ transports: {
+ sse: "/sse",
+ http: "/mcp",
+ },
+ features: {
+ ai: !!env.AI,
+ },
+ models: [
+ "flux-1-schnell (image generation)",
+ "llama-3.1-8b-instruct (text generation)",
+ ],
+ status: "ok",
+ timestamp: new Date().toISOString(),
+ }),
+ {
+ headers: {
+ "Content-Type": "application/json",
+ "Access-Control-Allow-Origin": "*",
+ },
+ }
+ );
+ }
+
+ return new Response("Not Found", { status: 404 });
+ },
+};