MCP is a standardized protocol that allows AI assistants to connect to external
systems and tools. Instead of being limited to their training data, assistants can
access real-time information and perform actions through MCP servers.
Core Components
Transport: Streamable HTTP for real-time bidirectional communication
Tools: Functions that AI assistants can call
Resources: Data sources (files, databases, APIs)
Prompts: Reusable prompt templates
How It Works
Your MCP server runs on Cloudflare Workers and exposes tools via HTTP endpoints. AI
assistants connect to your server and can call these tools to perform tasks like:
Set up a functional MCP server using Cloudflare Workers. Understand basic MCP server structure and test MCP tools using the inspector interface.
🎯 Learning Objectives
Set up a functional MCP server with Cloudflare Workers
Understand MCP server basic structure and architecture
Test MCP tools using the official inspector interface
Troubleshoot common connection and setup issues
🛠️Understanding MCP (Model Context Protocol)
MCP is an open standard that enables AI assistants to connect to external tools and data sources. Think of it as a universal interface that lets AI systems perform actions beyond their training - like reading files, calling APIs, or managing databases.
Server-Client Architecture: Your MCP server exposes tools that AI clients can discover and use
Standardized Communication: Uses Streamable HTTP for real-time bidirectional communication
Tool Discovery: AI assistants can list available tools and their parameters automatically
Global Deployment: Run on Cloudflare Workers for worldwide, low-latency access
Step 1
Create Your MCP Server
What we're building
A Cloudflare Workers-based MCP server that AI assistants can connect to and use.
Why this matters
Cloudflare Workers provide global deployment with minimal latency, making your MCP tools available worldwide.
Create Your MCP Serverbash
// Create new MCP server from template
npm create cloudflare@latest — my-mcp-server —template=cloudflare/ai/demos/remote-mcp-authless
// Navigate to your new project
cd my-mcp-server
// Install dependencies and start development server
npm install
npm run dev
You’ve created a fully functional MCP server that includes:
Tool definitions: Pre-built tools like “add” for mathematical operations
MCP endpoint: The /mcp route that AI assistants connect to
Error handling: Robust error responses for debugging
CORS support: Proper headers for cross-origin requests
Troubleshooting
npm not found: Install Node.js v20+ from nodejs.org
Template not found: Update npm: npm install -g npm@latest
Port 8787 busy: Stop other services or use npm run dev -- --port 8788
Build errors: Delete node_modules and run npm install again
Step 2: Test with MCP Inspector
What we're building
A connection between the MCP Inspector and your server to verify functionality and test tools.
Why this matters
The inspector is the easiest way to verify your MCP server is working and explore available tools.
# In a new terminal window (keep your server running)npx @modelcontextprotocol/inspector
Inspector Connection Process:
The inspector starts at http://127.0.0.1:6274
Open this URL in your browser
Select “Streamable HTTP” as the Transport Type
Enter http://localhost:8787/mcp as the Server URL
Click “Connect” to establish the connection
Navigate to the “Tools” tab to see available functions
Test the “add” tool with parameters like {"a": 5, "b": 3}
📝What You Should See
Once connected, the inspector will show:
Server Info: Basic metadata about your MCP server
Available Tools: List of tools with their descriptions and parameters
Tool Testing: Interface to call tools with custom parameters
Response Data: JSON responses from your tool executions
Successful Connectionbash
✅ Connected to MCP Server
🔧 Found 1 tool: “add”
📊 Server responding to requests
Step 3: Understanding Your MCP Server
What we're building
Understanding of your MCP server's architecture and how AI assistants interact with its tools.
Why this matters
MCP servers expose tools that AI assistants can use to perform actions and access data beyond their training.
🛠️MCP Server Architecture
Your MCP server provides a standardized interface for AI assistants to:
Discover tools: List available functions and their parameters
Execute tools: Run functions with provided arguments
Handle errors: Provide meaningful feedback when things go wrong
🔍 Common Issues & Solutions
Inspector won’t connect:
Verify your MCP server is running on http://localhost:8787 and the MCP endpoint is /mcp
No tools visible:
Check server logs for errors. The template should provide basic tools by default.
Port already in use:
Stop other services using port 8787 or modify the port in your configuration.
✅ Great work! You now have a functional MCP server that AI assistants can connect to and use. You’re ready to add custom tools in Step 2!
STEP 02
Adding Custom Tools
Create custom MCP tools with defined parameter schemas. Implement a random number generator tool.
🎯 Learning Objectives
Understand MCP tool schema definition
Implement custom tools with input validation
Test custom tools using the MCP Inspector
Handle tool execution errors gracefully
🛠️Understanding MCP Tool schema
MCP tools have a three-part structure: name, schema, and handler. The schema uses Zod for parameter validation and type safety.
Tool Name: Unique identifier for the tool
Schema: Zod object defining input parameters
Handler: Async function that processes the request
Response Format: Structured content array for AI consumption
Step 1: Open Your MCP Server Code
What we're building
A custom MCP tool with parameter validation using Zod schemas.
Why this matters
Custom tools extend AI capabilities with structured, validated functions that can be called reliably.
📝 Instructions:
Open your project in your IDE
Navigate to src/index.ts
Find the existing tool definitions
Prepare to add a new tool after the existing ones
Step 2: Add Random Number Generator Tool
What we're building
A random number generator tool that demonstrates MCP's three-part architecture with Zod validation.
Why this matters
This tool showcases parameter validation, async handlers, and proper MCP response formatting.
🚀Before You Code
Make sure your MCP server is running and you have the MCP Inspector connected before adding new tools.
src/index.tstypescript
this.server.tool(
"randomNumber",
{ a: z.number(), b: z.number() },
async ({ a, b }) => ({
content: [{
type: "text",
text: String(Math.floor(Math.random() * (b - a + 1)) + a)
}],
})
);
🛠️Understanding the Code
This tool demonstrates MCP’s three-part structure:
Tool Name: “randomNumber” - unique identifier
Schema: Zod validation for parameters a and b
Handler: Async function that processes and returns content
Response: MCP-compliant content array structure
Expected Resultbash
✅ Tool “randomNumber” registered successfully
🎲 Generates random numbers in specified range
📋 Parameters validated with Zod schemas
Step 3: Test With MCP Inspector
What we're building
A complete testing workflow to verify your new tool works correctly with the MCP Inspector.
Why this matters
Testing ensures your tools function properly before AI assistants try to use them in production.
Testing Process
# Save your changes and restart the servernpm start# In a new terminal windownpx @modelcontextprotocol/inspector
🧪 Testing Process:
The inspector opens at http://127.0.0.1:6274
Select “Streamable HTTP” as Transport Type
Enter http://localhost:8787/mcp as Server URL
Click “Connect” to establish connection
Navigate to the “Tools” tab
Find and test “randomNumber” tool
Try parameters like {"a": 1, "b": 10}
What You Should See
Once connected and testing, verify:
Tool Listed: “randomNumber” appears in tools list
Parameters Visible: Shows a and b as number inputs
Responses Work: Returns random numbers in range
Validation Works: Rejects invalid parameter types
Successful Testtext
✅ Tool “randomNumber” found and working
🎲 Returns: “7” (for input {"a": 1, "b": 10})
🔧 Parameter validation functioning
STEP 03
External API Integration
Integrate external APIs into MCP tools. Enhance the random number tool with Cloudflare's drand beacon for true randomness.
🎯 Learning Objectives
Make HTTP requests from MCP tools
Handle external API responses and errors
Implement fallback mechanisms for reliability
Process external data for AI consumption
🌐External API Integration
MCP tools can fetch data from external APIs to provide real-time information. Learn about true randomness vs pseudo-randomness and implement fallback mechanisms.
Data Processing: Converts hex randomness to usable numbers
Error Handling: try/catch ensures reliability
Graceful Fallback: Uses Math.random() if API unavailable
Enhanced Resulttext
✅ Tool enhanced with drand API integration
🎲 Now uses cryptographically secure randomness
🔄 Fallback ensures 100% reliability
🛡️ Error handling maintains functionality
Step 3: Test Enhanced Random Number Tool
What we're building
A comprehensive test of the enhanced tool to verify external API integration and fallback mechanisms work correctly.
Why this matters
Testing external API integrations ensures your tools are reliable and handle network failures gracefully.
Testing Process
# Save changes and restart servernpm start# Test the enhanced toolnpx @modelcontextprotocol/inspector
🧪 Testing Process:
Restart your server to load the enhanced tool
Open MCP Inspector at http://127.0.0.1:6274
Connect to http://localhost:8787/mcp
Navigate to the “Tools” tab
Test randomNumber multiple times with {"a": 1, "b": 10}
Observe the cryptographically secure randomness
Try disconnecting internet to test fallback (optional)
🚀What You Should Observe
The enhanced tool demonstrates advanced MCP capabilities:
External API Integration: Successfully fetches from drand
Error Resilience: Falls back gracefully if API fails
Data Processing: Transforms hex randomness to numbers
True Randomness: Better distribution than pseudo-random
Enhanced Testing Completetext
✅ Enhanced tool working with drand API
🎲 Returns: “3” (cryptographically secure)
🔄 Fallback tested and functional
🌐 External API integration successful
STEP 04
Deploy to Cloudflare Workers
Deploy your MCP server to Cloudflare Workers for global availability and test it with Cloudflare AI Playground.
🎯 Learning Objectives
Deploy MCP servers to Cloudflare Workers
Configure production environment settings
Test deployed servers with AI Playground
Monitor and debug production deployments
🛠️Global Deployment with Workers
Cloudflare Workers deploy your MCP server to a global network of edge locations, providing low-latency access worldwide.
Global Network: Deploy to 200+ cities worldwide
Edge Computing: Run close to users for minimal latency
Serverless: Automatic scaling with zero cold starts
Built-in Security: DDoS protection and secure by default
Step 1: Deploy Your MCP Server
What we're building
A globally deployed MCP server running on Cloudflare's edge network for low-latency access worldwide.
Why this matters
Production deployment makes your MCP server accessible to AI assistants and provides real-world testing capabilities.
Deployment Process
Deploy to Cloudflare Workersbash
// Login to Cloudflare (if not already done)
wrangler login
// Deploy to Workers
npm run deploy
🚀 Deployment Process:
Ensure you’re logged into Cloudflare with npx wrangler login
Run npm run deploy to build and deploy
Wait for deployment to complete (usually 30-60 seconds)
Add your MCP server URL: https://your-worker.workers.dev/mcp
Click “Connect” and verify tools are loaded
Test your tools by asking the AI to use them
Example: “Generate a random number between 1 and 100”
📝What You Should See
In the AI Playground, you should be able to:
Connect Successfully: Your MCP server loads without errors
Tool Discovery: AI can see and understand your tools
Tool Execution: AI can call your tools and get responses
Natural Integration: Tools work seamlessly in conversation
AI Playground Successtext
✅ MCP server connected to AI Playground
🎲 AI successfully used randomNumber tool
🔧 Tools are discoverable and functional
🌍 Production integration working
STEP 05
Cloudflare KV Storage
Set up Cloudflare KV for persistent data storage. Create tools that can store and retrieve data across sessions.
🎯 Learning Objectives
Create and configure Cloudflare KV namespaces
Implement data persistence in MCP tools
Handle storage operations and errors
Build stateful applications with KV
📝Persistent Storage with KV
Cloudflare KV provides global, low-latency key-value storage for your MCP tools, enabling persistent data across sessions.
Global Distribution: Data replicated across Cloudflare’s network
Eventually Consistent: Fast reads with eventual consistency
Generous Limits: 1GB storage and 100,000 operations daily on free tier
Data Modeling: Structured data with timestamps and metadata
Unique IDs: Generate unique identifiers for tasks
Filtering: List completed vs pending tasks
Step 1: Add Todo Management Tools
What we're building
Complete CRUD functionality for a todo application with addTodo, listTodos, and completeTodo tools.
Why this matters
Demonstrates how AI assistants can create and manage persistent, stateful applications users can interact with over time.
this.server.tool( "addTodo", "Add a new task to your todo list", { task: z.string().describe("Task description") }, async ({ task }) => { await this.env.TODO_STORE.put(task, JSON.stringify({ completed: false, createdAt: new Date().toISOString() })); return { content: [{ type: "text", text: `Added task: ${task}` }] }; });this.server.tool( "listTodos", "List all tasks in your todo list", {}, async () => { const list = await this.env.TODO_STORE.list(); const tasks = []; for (const key of list.keys) { const value = await this.env.TODO_STORE.get(key.name); if (value) { const taskData = JSON.parse(value); tasks.push(`${taskData.completed ? '✅' : '📋'} ${key.name}`); } } if (tasks.length === 0) { return { content: [{ type: "text", text: "No tasks found. Add some tasks first!" }] }; } return { content: [{ type: "text", text: `Todo List:\n${tasks.join('\n')}` }] }; });this.server.tool( "completeTodo", "Mark a task as completed", { task: z.string().describe("Task to mark as completed") }, async ({ task }) => { const value = await this.env.TODO_STORE.get(task); if (!value) { return { content: [{ type: "text", text: `Task "${task}" not found` }] }; } const taskData = JSON.parse(value); taskData.completed = true; await this.env.TODO_STORE.put(task, JSON.stringify(taskData)); return { content: [{ type: "text", text: `Completed task: ${task}` }] }; });
📝Data Structure Design
Each todo item is stored as:
Key: Task description (unique identifier)
Value: JSON object with completed status and creation time
Operations: Create, list, and update completion status
Consistency: Atomic updates ensure data integrity
Todo App Readybash
✅ addTodo tool created
📋 listTodos tool created
✔️ completeTodo tool created
💾 Persistent todo app functional
Step 2: Test the Todo Application
What we're building
A comprehensive test of all todo functionality to verify persistence and state management works correctly.
Why this matters
Testing CRUD operations ensures the application maintains state properly across different AI interactions.
🧪 Complete Testing Workflow:
Deploy your updated server: npm run deploy
Connect to AI Playground with your deployment URL
Test adding tasks: “Add a task to buy groceries”
Test listing: “Show me my todo list”
Test completion: “Mark ‘buy groceries’ as completed”
Test persistence: Refresh and list tasks again
📝Expected Behavior
Your todo app should demonstrate:
Persistence: Tasks survive page refreshes and new conversations
State Management: Completion status updates correctly
User Experience: Natural interaction through AI conversation
Data Integrity: No duplicate or corrupted entries
Todo App Testedtext
✅ Tasks persist across sessions
📋 List functionality working
✔️ Completion status updates
🎉 Stateful AI application complete!
STEP 07
Customize Your MCP Server with AI Assistance
Use AI coding assistants to create unique, custom tools that extend your MCP server with creative functionality.
🎯 Learning Objectives
Leverage AI assistants for rapid development
Design and implement custom tool ideas
Integrate external APIs and services
Deploy and share your unique MCP server
🚀AI-Assisted Development
Use AI coding assistants to accelerate development and create innovative tools for your MCP server.
Rapid Prototyping: Generate tool concepts and implementations quickly
API Integration: Connect to external services and data sources
Creative Solutions: Explore unique use cases and applications
Best Practices: Learn proper error handling and optimization
Step 1: Choose Your Custom Tool Idea
What we're building
A unique, custom tool that showcases creativity and demonstrates practical MCP server capabilities.
Why this matters
Custom tools differentiate your MCP server and provide real value to AI assistant users.
💡Tool Ideas
Consider these concepts or create your own:
Weather Tool: Current conditions and forecasts
Translation Service: Multi-language text translation
QR Code Generator: Create QR codes for text/URLs
Password Generator: Secure password creation
URL Shortener: Create short links
Base64 Encoder/Decoder: Text encoding utilities
Color Palette: Generate color schemes
Joke Generator: Programming or dad jokes
🎯 Selection Process:
Choose a tool idea that interests you
Consider what external API (if any) you’ll need
Think about the parameters your tool will accept
Plan the response format for AI consumption
Prepare to use an AI assistant for implementation
Step 2: Implement with AI Assistance
What we're building
A complete tool implementation using AI coding assistants for rapid development and best practices.
Why this matters
AI-assisted development accelerates learning and helps implement complex functionality efficiently.
🤖 AI Development Process:
Open your preferred AI coding assistant (Claude Code, Cursor, Copilot)
Describe your tool idea and requirements
Ask for MCP tool implementation with Zod schemas
Request error handling and edge cases
Add the generated code to your src/index.ts
Test and iterate with AI assistance
📝Example AI Prompt
Try this prompt structure:
“I’m building an MCP server tool that [your idea]. It should accept [parameters] and return [response type]. Please implement this as a Zod-validated MCP tool with proper error handling for Cloudflare Workers.”
Custom Tool Created
✅ Custom tool implemented with AI assistance🛠️ Proper error handling included📋 Zod validation configured🎨 Unique functionality added
Step 3: Deploy and Share Your Creation
What we're building
A production deployment of your custom MCP server, ready to share with the community.
Why this matters
Sharing your work contributes to the MCP ecosystem and showcases your learning achievements.
Deploy Your Custom MCP Serverbash
// Deploy your custom MCP server
npm run deploy
// Test your unique tools
npx @modelcontextprotocol/inspector
🚀 Deployment & Sharing:
Deploy your server: npm run deploy
Test all tools in AI Playground
Document your custom tools and their usage
💡Showcase Ideas
Ways to share your work:
Social Media: Post screenshots and descriptions
GitHub: Create a repository with your code
Blog Post: Write about your learning journey
Video Demo: Record your tools in action
Workshop Complete! 🎉bash
✅ Custom MCP server deployed
🌍 Tools accessible globally
🤖 AI assistants can use your tools
🎊 Ready to build the future of AI!
Learning Resources
Essential resources for mastering MCP development and building powerful AI tools.
📖 MCP Documentation
Official Model Context Protocol documentation with API references and best practices