Skip to content

EnkrateiaLucca/mcp-course

Repository files navigation

Building AI Agents with MCP: Complete Course Materials

A comprehensive 2-day bootcamp on the Model Context Protocol (MCP) - the standardized way to connect AI agents to external tools, data sources, and systems.

πŸŽ“ O'Reilly Live Training: "MCP Bootcamp: Building AI Agents with Model Context Protocol"

🎯 What is MCP?

The Model Context Protocol (MCP) is an open standard that provides a universal way to connect AI applications to data sources and tools - like a "USB-C port for AI." Instead of building custom integrations for each tool, MCP provides:

  • Standardized Communication: A single protocol for all AI-tool interactions
  • Tool Discovery: Agents can discover and understand available capabilities dynamically
  • Resource Access: Structured access to data sources (files, databases, APIs)
  • Prompt Templates: Reusable, versioned prompts that agents can leverage
  • Cross-Platform: Works with any AI model (Claude, GPT, local models, etc.)

Why It Matters: MCP enables a future where AI agents can seamlessly integrate with any tool or data source, just as USB-C standardized hardware connectivity.

πŸ“š Course Overview

This hands-on course takes you from MCP fundamentals to production deployment through 8 comprehensive demos:

What You'll Learn

  • βœ… MCP Fundamentals: Architecture, protocol concepts, and tool/resource patterns
  • βœ… Building MCP Servers: Using FastMCP to create custom tool providers
  • βœ… Claude Agents SDK: Building production-grade agents with in-process MCP
  • βœ… Chat Applications: Building full-featured chat apps with Claude tool use and MCP
  • βœ… Real-World Applications: Data queries, automation, and deployment
  • βœ… Security & Permissions: Tool authorization, input validation, and best practices
  • βœ… Production Deployment: Serverless deployment to Vercel with both SDKs

Prerequisites

  • Python 3.10+ (Python 3.12+ recommended for latest features)
  • Basic async/await understanding
  • API keys:
    • Anthropic API key (for Claude demos) - Get one here
    • Replicate API key (OPTIONAL - for image generation demo) - Get one here

πŸš€ Quick Start

Using UV Package Manager (Recommended)

UV is a fast Python package manager that handles dependencies automatically:

# Install UV
curl -LsSf https://astral.sh/uv/install.sh | sh

# Run any demo directly (UV handles dependencies automatically)
cd demos/01-introduction-to-mcp
uv run mcp_server.py

# Or test with MCP Inspector
mcp dev mcp_server.py

Benefits of UV:

  • βœ… No virtual environment management
  • βœ… Automatic dependency resolution from script metadata
  • βœ… Faster than pip
  • βœ… Consistent across all demos

Traditional Setup (Alternative)

# Clone and navigate to the repository
git clone https://github.com/EnkrateiaLucca/mcp-course.git
cd mcp-course

# Create virtual environment
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

# Install base dependencies
pip install -r requirements/requirements.txt

Environment Setup

Create a .env file in the root directory:

# Required for Claude Agents SDK demos
ANTHROPIC_API_KEY=your-anthropic-api-key-here

# Required for OpenAI demos
OPENAI_API_KEY=your-openai-api-key-here

# Optional: for image generation demo
REPLICATE_API_TOKEN=your-replicate-token-here

πŸ“ Course Structure

Demo 00: Introduction to AI Agents

Path: demos/00-intro-agents/

What it covers: Foundational concepts of AI agents before diving into MCP.

Key Files:

  • intro-agents-cld.ipynb - Jupyter notebook with agent architecture and patterns

Learning Objectives:

  • Understand agent components (perception, reasoning, action)
  • Learn agent decision-making patterns
  • Grasp the difference between simple LLM calls and agentic systems

Run it:

cd demos/00-intro-agents
jupyter notebook intro-agents-cld.ipynb

Demo 01: Introduction to MCP

Path: demos/01-introduction-to-mcp/

What it covers: MCP fundamentals, server implementation with FastMCP, and client interaction.

Key Files:

  • mcp_server.py - Basic MCP server with time, math, and file tools
  • mcp_client.py - Test client for server interaction
  • mcp_host.py - Host/client integration example
  • walkthrough.md - Step-by-step guide
  • documents.txt - Sample data

Learning Objectives:

  • Understand MCP architecture (client/server/host)
  • Create tools with @mcp.tool() decorator
  • Handle stdio transport communication
  • Test servers with MCP Inspector

Run it:

cd demos/01-introduction-to-mcp

# Run the server
uv run mcp_server.py

# Or test interactively
mcp dev mcp_server.py

β˜… Insight ───────────────────────────────────── MCP uses a client-server architecture where:

  • MCP Host: Your AI application (coordinates everything)
  • MCP Client: Maintains connection to a single server
  • MCP Server: Provides tools, resources, and prompts

Think of it like a restaurant: the Host seats you, Clients take orders from specific tables, and Servers (kitchen stations) provide specific capabilities. ─────────────────────────────────────────────────


Demo 02: MCP Chat Application Study Case

Path: demos/02-study-case-anthropic-tools-resources-prompts-chat-app/

What it covers: Complete chat application integrating Claude tool use with MCP capabilities.

Key Files:

  • chat_app.py - Full-featured chat interface with Claude tool use
  • mcp_server.py - MCP server with file operations
  • mcp_client.py - MCP client wrapper for Anthropic integration
  • README.md - Detailed documentation

Learning Objectives:

  • Bridge Claude tool use with MCP tools
  • Convert MCP schemas to Claude tool definitions
  • Build production-ready chat applications with @file mentions
  • Handle tool execution and multi-turn conversations

Run it:

cd demos/02-study-case-anthropic-tools-resources-prompts-chat-app

export ANTHROPIC_API_KEY="your-key"
uv run chat_app.py

Example Interaction:

You> Create a file called notes.md with "Hello MCP"
[Calling tool: write_doc...]
βœ… File created successfully

You> What's in notes.md?
[Calling tool: read_doc...]
Content: Hello MCP

Demo 03: Claude Agents SDK - Filesystem Agent

Path: demos/03-claude-agents-sdk-filesystem-agent/

What it covers: Building agents with the Claude Agents SDK using in-process MCP servers for filesystem operations.

Key Files:

  • file_reader_agent.py - Complete file reader agent implementation
  • simple_claude_agent_files.py - Simplified starter example
  • examples/ - Individual topic examples
    • example_mcp_server.py - MCP server setup patterns
    • example_tool_permissions.py - Permission callbacks and security
    • example_response_handling.py - Processing agent responses
    • example_error_handling.py - Error handling strategies
  • README.md - Comprehensive learning guide

Learning Objectives:

  • Create in-process MCP servers (no subprocess overhead)
  • Implement tool permissions and security callbacks
  • Handle streaming responses with async/await
  • Use PreToolUse/PostToolUse hooks for validation
  • Mix in-process and external MCP servers

Run it:

cd demos/03-claude-agents-sdk-filesystem-agent

export ANTHROPIC_API_KEY="your-key"

# Run the simplified example
uv run simple_claude_agent_files.py

# Run individual topic examples
uv run examples/example_mcp_server.py
uv run examples/example_tool_permissions.py

# Run complete file reader agent
uv run file_reader_agent.py

β˜… Insight ───────────────────────────────────── In-Process MCP (Claude Agents SDK approach):

  • Tools run directly in your Python process
  • No subprocess management needed
  • Better performance, simpler debugging
  • Single deployment artifact

External MCP (Traditional approach):

  • Separate server process via stdio/HTTP
  • Language-agnostic server implementation
  • Better isolation, can restart independently ─────────────────────────────────────────────────

Demo 04: Query Tabular Data

Path: demos/04-query-tabular-data/

What it covers: MCP server for CSV/tabular data queries with both Claude and OpenAI agent implementations.

Key Files:

  • csv_query_mcp_server.py - MCP server with 7 CSV query tools
  • claude_agents_sdk_demo.py - ⭐ Recommended: In-process tools with Claude SDK
  • claude_agents_csv_demo.ipynb - Claude Agents SDK notebook demo
  • sample_data.csv - Product database (15 products)

Learning Objectives:

  • Create specialized MCP tools for data analysis
  • Compare in-process vs external MCP patterns
  • Use Claude SDK's @tool decorator
  • Integrate AI with image generation APIs
  • Handle complex multi-step queries

Run it:

cd demos/04-query-tabular-data

export ANTHROPIC_API_KEY="your-key"

# Claude Agents SDK approach (recommended)
uv run claude_agents_sdk_demo.py

# Or explore with Jupyter
jupyter notebook claude_agents_csv_demo.ipynb

Available Tools:

  1. get_all_products - Browse entire catalog
  2. search_products_by_category - Filter by category (Electronics, Furniture)
  3. search_products_by_price_range - Find products in price range
  4. get_product_by_name - Get specific product details
  5. get_top_rated_products - Find highest-rated items
  6. get_products_in_stock - Check inventory
  7. get_category_statistics - Analytics and summaries

Example Queries:

"What electronics do we have?"
"Show me products between $50 and $150"
"What are the top 3 highest-rated products?"
"I need office equipment: keyboard (check ratings), furniture under $200"

Demo 05: Automation Agent

Path: demos/05-automations-agent/

What it covers: An AI agent that writes, tests, and runs Python automation scripts using Claude Agent SDK + an MCP server that provides sandboxed script execution.

Key Files:

  • automation_agent.py - Interactive Claude Agent (CLI)
  • automation_mcp_server.py - MCP server with sandboxed script tools
  • generated_scripts/ - Where scripts are saved and executed
  • WALKTHROUGH.md - Full architecture explanation

Learning Objectives:

  • Use MCP as a capability boundary (constrained, auditable tools)
  • Build agentic writeβ†’testβ†’fix loops
  • Connect Claude Agent SDK to an external MCP server via stdio
  • Implement sandboxed script execution with timeouts

Architecture:

User Request ("Create a CSV converter")
    ↓
Automation Agent (Claude Agent SDK)
    ↓ writes code, calls MCP tools
MCP Server (script-sandbox)
    - save_script(name, code)
    - run_script(name, args)  ← 30s timeout
    - list_scripts / read_script / delete_script
    ↓
generated_scripts/  (sandboxed directory)

Run it:

cd demos/05-automations-agent

export ANTHROPIC_API_KEY="your-key"
uv run automation_agent.py

Example Workflow:

You: Create a script that finds duplicate files in a folder
Agent: [Writes Python script β†’ saves via MCP β†’ runs to test β†’ fixes errors β†’ reports back]
      βœ… Saved: generated_scripts/find_duplicates.py
      βœ… Tested successfully

You: List my scripts
Agent: [Calls list_scripts tool]
      - find_duplicates.py

You: Run find_duplicates.py /tmp/test
Agent: [Calls run_script with args β†’ shows output]

Demo 06: Deploy to Vercel (Serverless)

Path: demos/06-deploy-simple-agent-mcp-vercel/

What it covers: Production deployment of AI agents with MCP to Vercel serverless platform. Includes two complete implementations:

  1. OpenAI Agents SDK (Stateless) - main.py
  2. Claude Agents SDK (Sandboxed) - main_claude.py

Key Files:

  • main.py - OpenAI Agents SDK implementation
  • main_claude.py - Claude Agents SDK with sandbox
  • claude_agent_sandbox.py - Agent code for sandbox execution
  • mcp_fetch_server.py - MCP server with HTTP transport (FastMCP)
  • static/index.html - Beautiful chat interface
  • requirements.txt / requirements_claude.txt - Dependencies
  • vercel.json - Vercel configuration
  • deployment_agents_sdk_vercel.md - OpenAI deployment guide
  • deployment_claude_agents_sdk_vercel.md - Claude deployment guide
  • README.md - Overview and comparison

Learning Objectives:

  • Deploy MCP servers with HTTP transport (not just stdio)
  • Use MCPServerStreamableHttp from OpenAI Agents SDK
  • Build with official MCP Python SDK (mcp[cli])
  • Compare stateless vs sandboxed architectures
  • Implement production security patterns
  • Create FastAPI wrappers for agent endpoints
  • Deploy to serverless platforms

Architecture Comparison:

Feature OpenAI (main.py) Claude (main_claude.py)
Model Stateless serverless Sandboxed containers
Complexity Low ⭐ Medium ⭐⭐⭐
File Operations Limited Full (sandboxed)
Command Execution No Yes (in sandbox)
Best For Chat apps Complex agents
Cost API only API + sandbox compute

Run Locally (OpenAI):

cd demos/06-deploy-simple-agent-mcp-vercel

cp .env.example .env
# Add OPENAI_API_KEY to .env

# Terminal 1: MCP Server
python mcp_fetch_server.py

# Terminal 2: Main App
python main.py

# Open http://localhost:8000

Run Locally (Claude):

export ANTHROPIC_API_KEY="your-key"
python main_claude.py

Deploy to Vercel:

# Install Vercel CLI
npm install -g vercel

# Login and configure
vercel login
vercel env add OPENAI_API_KEY  # or ANTHROPIC_API_KEY

# Deploy
vercel --prod

Example Queries:

"Fetch content from https://modelcontextprotocol.io"
"What's the latest on the OpenAI blog?"
"Read https://github.com/anthropics/claude-agent-sdk-python and summarize"

β˜… Insight ───────────────────────────────────── MCP HTTP Transport (New in this demo):

  • MCP traditionally uses stdio (standard input/output)
  • HTTP transport enables serverless deployment
  • FastMCP supports both stdio and HTTP via transport="sse"
  • OpenAI SDK uses MCPServerStreamableHttp to connect ─────────────────────────────────────────────────

Demo 07: Hacks, Tips, Tools & Workflows

Path: demos/07-hacks-tips-tools-workflows/

What it covers: Curated collection of practical tips, tools, and workflow patterns demonstrated live during the training session.

Key Files:

  • mcp-builder-skill/ - Claude skill for building MCP servers
    • SKILL.md - Skill definition and usage guide
    • reference/ - Reference implementations
    • scripts/ - Helper scripts

Learning Objectives:

  • Discover useful MCP ecosystem tools and integrations
  • Learn workflow shortcuts for MCP development
  • Use Claude skills to accelerate MCP server creation
  • Explore tips and tricks shared during live sessions

Assets & Resources

Path: demos/assets-resources/

What it contains: Reference materials, diagrams, and cheatsheets used throughout the course.

Key Files:

  • MCP_TECHNICAL_CHEATSHEET.md - Quick reference for MCP concepts and patterns
  • mcp_server_prompt_templates.md - Prompt templates for building MCP servers
  • mcp_security_report.pdf - Security analysis and best practices
  • diagram.excalidraw - Editable architecture diagrams
  • mcp-course.md - Comprehensive course reference document
  • Various .png files - Architecture diagrams, agent loops, market maps

🎨 Architecture Patterns

Pattern 1: In-Process MCP Tools (Claude Agents SDK)

Used in: Demos 03, 04, 05

from agents import tool
from agents.extensions.mcp import create_sdk_mcp_server

@tool("query_data", "Query the database", {"query": str})
async def query_data(args: dict) -> dict:
    result = execute_query(args["query"])
    return {"content": [{"type": "text", "text": result}]}

# Create in-process MCP server
server = create_sdk_mcp_server(
    name="data-tools",
    version="1.0.0",
    tools=[query_data]
)

# Agent has direct access
agent = Agent(
    name="assistant",
    instructions="You help query data",
    mcp_servers={"data": server},
    model="claude-sonnet-4-5-20250929"
)

Pros: Fast, simple deployment, easy debugging Cons: All in one process, Python-only


Pattern 2: External MCP Server (Traditional)

Used in: Demos 01, 02, 04 (external server version)

# Server (FastMCP)
from mcp.server.fastmcp import FastMCP

mcp = FastMCP("tool-server")

@mcp.tool()
def process_data(input: str) -> str:
    return f"Processed: {input}"

if __name__ == "__main__":
    mcp.run(transport="stdio")

# Client connects via subprocess
from agents.mcp import MCPServerConfig

config = MCPServerConfig(
    command="uv",
    args=["run", "server.py"]
)

agent = Agent(mcp_servers=[config])

Pros: Language-agnostic, isolated, restartable Cons: Subprocess overhead, more complex deployment


Pattern 3: HTTP Transport (Serverless)

Used in: Demo 06

# Server with HTTP transport
mcp = FastMCP("web-tools")

@mcp.tool()
def fetch_url(url: str) -> str:
    return httpx.get(url).text

if __name__ == "__main__":
    mcp.run(transport="sse")  # Server-Sent Events transport

# Client via HTTP
from agents_mcp import MCPServerStreamableHttp

agent = Agent(
    mcp_servers=[
        MCPServerStreamableHttp(
            name="web",
            url="http://localhost:8001/sse"
        )
    ]
)

Pros: Serverless-friendly, scalable, network-accessible Cons: Network latency, requires HTTP infrastructure


πŸ› οΈ Development Tools

MCP Inspector

Interactively test any MCP server:

# Run inspector on your server
mcp dev path/to/your_server.py

# Opens web UI at http://localhost:5173
# - List available tools
# - Test tool calls with parameters
# - View resources and prompts
# - See full request/response logs

Claude Desktop Integration

Configure MCP servers in Claude Desktop:

macOS/Linux: ~/.config/Claude/claude_desktop_config.json Windows: %APPDATA%\Claude\claude_desktop_config.json

{
  "mcpServers": {
    "csv-query": {
      "command": "uv",
      "args": ["run", "/absolute/path/to/csv_query_mcp_server.py"]
    },
    "automation-tools": {
      "command": "uv",
      "args": ["run", "/absolute/path/to/automation_mcp_server.py"]
    }
  }
}

After adding, restart Claude Desktop. Tools appear in the tool selector.

Makefile Commands

Automate common tasks:

make conda-create     # Create conda environment
make env-setup        # Setup with pip-tools and UV
make notebook-setup   # Install Jupyter kernel
make env-update       # Update dependencies
make freeze           # Freeze current dependencies
make clean            # Remove environments

πŸͺŸ Windows Setup Guide

Prerequisites

Enable Developer Mode

  1. Settings β†’ Update & Security β†’ For developers
  2. Select Developer mode
  3. Restart computer

PowerShell Execution Policy

Open PowerShell as Administrator:

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser

Setup

# Clone repository
git clone https://github.com/EnkrateiaLucca/mcp-course.git
cd mcp-course

# Create virtual environment
python -m venv venv
venv\Scripts\activate

# Install dependencies
pip install -r requirements/requirements.txt

Environment Variables

Create .env file:

ANTHROPIC_API_KEY=your-key
OPENAI_API_KEY=your-key
# Use forward slashes in paths
MCP_DEMO_PATH=C:/path/to/files

Or set in Command Prompt:

set ANTHROPIC_API_KEY=your-key

Or PowerShell:

$env:ANTHROPIC_API_KEY="your-key"

Claude Desktop Config (Windows)

Location: %APPDATA%\Claude\claude_desktop_config.json

cd %APPDATA%\Claude
notepad claude_desktop_config.json

Use absolute paths with forward slashes:

{
  "mcpServers": {
    "demo": {
      "command": "C:/path/to/venv/Scripts/python.exe",
      "args": ["C:/path/to/mcp_server.py"]
    }
  }
}

Windows Command Reference

Linux/macOS Windows (CMD) Windows (PowerShell)
source venv/bin/activate venv\Scripts\activate venv\Scripts\Activate.ps1
export VAR=value set VAR=value $env:VAR="value"
~/.config/Claude/ %APPDATA%\Claude\ $env:APPDATA\Claude\
python3 python python

Common Windows Issues

"python not found"

  • Reinstall Python with "Add to PATH" checked

PowerShell script errors

Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope Process

Long path issues

  • Enable in Group Policy: gpedit.msc β†’ Computer Configuration β†’ Administrative Templates β†’ System β†’ Filesystem β†’ Enable Win32 long paths

πŸ› Troubleshooting

"Module not found" errors

# With UV
uv pip install mcp model-context-protocol

# With pip
pip install mcp model-context-protocol

API Key Issues

Claude SDK:

export ANTHROPIC_API_KEY="your-key"
# Or add to .env file

OpenAI:

export OPENAI_API_KEY="your-key"
# Or add to .env file

Claude Desktop Not Recognizing Servers

  1. βœ… Use absolute paths in config
  2. βœ… Verify UV is in PATH: which uv
  3. βœ… Test server independently: uv run mcp_server.py
  4. βœ… Check server logs for errors
  5. βœ… Restart Claude Desktop after config changes

Permission Denied

chmod +x script.py

MCP Server Connection Issues

Test independently:

mcp dev path/to/server.py

Check if running:

ps aux | grep mcp_server  # Linux/macOS
tasklist | findstr python  # Windows

Rate Limiting

  • Check API quota in your provider dashboard
  • Implement exponential backoff
  • Add request delays in loops
  • Use cheaper models for testing (gpt-4o-mini, claude-haiku)

πŸ“– Learning Resources

Official Documentation

Community Resources

Course Materials

  • presentation/presentation.html - Interactive HTML course slides
  • presentation/presentation-mcp-updated.pdf - PDF version of slides
  • walkthrough_for_beginners.md - Comprehensive beginner's guide
  • demos/assets-resources/MCP_TECHNICAL_CHEATSHEET.md - Quick reference cheatsheet
  • CLAUDE.md - Project development guidelines

πŸŽ“ Course Instructor

Lucas Soares

πŸ“š Blog πŸ”— LinkedIn 🐦 Twitter/X πŸ“Ί YouTube - Automata Learning Lab πŸ“§ lucasenkrateia@gmail.com


🀝 Contributing

Contributions are welcome! To contribute:

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature/your-feature
  3. Make your changes with clear commits
  4. Test thoroughly across demos
  5. Submit a pull request

πŸ“ License

This course material is provided for educational purposes as part of the O'Reilly Live Training series.


πŸš€ Next Steps

  1. βœ… Start with Demo 00 - Understand AI agent fundamentals
  2. βœ… Build MCP basics (Demo 01) - Create your first server
  3. βœ… Build a chat app (Demo 02) - Connect Claude tool use with MCP
  4. βœ… Master the Claude Agents SDK (Demos 03, 04, 05) - In-process tools, data queries, automation
  5. βœ… Deploy to production (Demo 06) - Vercel serverless deployment with both SDKs
  6. βœ… Level up (Demo 07) - Explore hacks, tips, and workflow tools
  7. βœ… Build your own - Create custom MCP servers for your use cases

The Model Context Protocol is revolutionizing how AI agents connect to the world. This course gives you the practical skills to build with it today.

Happy building! πŸŽ‰

About

MCP Course OReilly

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors