MCP Tutorial

Setup for MCP (Model Context Protocol)


📚 Table of Contents

  1. What is MCP?
  2. Prerequisites
  3. System Requirements
  4. Installation Options
  5. Environment Setup with uv (Recommended)
  6. Environment Setup with pip (Alternative)
  7. Claude Desktop Integration
  8. Your First MCP Server
  9. Testing Your Setup
  10. Troubleshooting
  11. Key Takeaways
  12. Additional Resources

What is MCP?

The Model Context Protocol (MCP) is an open standard developed by Anthropic that enables Large Language Models (LLMs) to interact seamlessly with external tools, data sources, and applications. Think of it as a universal adapter that connects AI assistants like Claude to the outside world.

Core MCP Concepts

MCP provides three main primitives:

Primitive Description Example
🔧 Tools Functions that LLMs can call (with user approval) Fetch weather data, query databases
📁 Resources File-like data that clients can read API responses, file contents
📝 Prompts Pre-written templates for specific tasks Code review template, analysis prompt

How MCP Works

┌─────────────────┐       ┌─────────────────┐       ┌─────────────────┐
│                 │       │                 │       │                 │
│   LLM Client    │◄─────►│   MCP Server    │◄─────►│  External API   │
│  (e.g., Claude) │  MCP  │  (Your Code)    │ HTTP  │  (Weather, DB)  │
│                 │       │                 │       │                 │
└─────────────────┘       └─────────────────┘       └─────────────────┘

Prerequisites

Before setting up MCP, ensure you have the following:

Required Knowledge

  • ✅ Basic Python programming
  • ✅ Understanding of command line/terminal usage
  • ✅ Familiarity with virtual environments
  • ✅ Basic understanding of LLMs (like Claude)

Required Software

  • Python 3.10+ installed on your system
  • ✅ A code editor (VS Code recommended)
  • Claude Desktop (for testing with Claude) - Download here

System Requirements

Component Minimum Requirement
Python 3.10 or higher
MCP SDK 1.2.0 or higher
OS Windows, macOS, or Linux
RAM 4GB (8GB recommended)

Check Your Python Version

python --version
# Should output: Python 3.10.x or higher

If you need to install Python, visit python.org


Installation Options

MCP provides two main installation methods:

Method Best For Package Manager
uv (Recommended) New projects, faster installs uv add "mcp[cli]"
pip Existing projects pip install mcp

uv is a fast Python package installer and resolver, recommended by the official MCP documentation.

Step 1: Install uv

On macOS/Linux:

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

On Windows (PowerShell):

powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"

Step 2: Create a New MCP Project

# Create a new directory for your project
uv init my-mcp-server
cd my-mcp-server

# Create and activate virtual environment
uv venv

# On macOS/Linux:
source .venv/bin/activate

# On Windows:
.venv\Scripts\activate

Step 3: Install MCP Dependencies

# Install MCP with CLI tools and HTTP client
uv add "mcp[cli]" httpx

# Verify installation
# On Linux
uv pip list | grep mcp

# On Windows
uv pip list | Select-String mcp

Project Structure After Setup

my-mcp-server/
├── .venv/                  # Virtual environment
├── .python-version         # Python version file
├── hello.py                # Sample file (created by uv init)
├── pyproject.toml          # Project configuration
├── README.md               # Project readme (created by uv init)
├── uv.lock                 # Dependency lock file
└── server.py               # Your MCP server (create this)

Environment Setup with pip (Alternative)

If you prefer using traditional pip and venv:

Step 1: Create Virtual Environment

# Create project directory
mkdir my-mcp-server
cd my-mcp-server

# Create virtual environment(if not created by uv)
python -m venv .venv

# Activate virtual environment
# On macOS/Linux:
source .venv/bin/activate

# On Windows:
.venv\Scripts\activate

Step 2: Install MCP Package

# Install MCP
pip install mcp

# Install additional dependencies for HTTP requests
pip install httpx

# Verify installation
pip show mcp

📦 Package Info: The MCP package is available on PyPI as mcp.


Claude Desktop Integration

To use your MCP server with Claude Desktop, you need to configure the claude_desktop_config.json file.

Step 1: Locate the Config File

Operating System Config File Location
macOS ~/Library/Application Support/Claude/claude_desktop_config.json
Windows %APPDATA%\Claude\claude_desktop_config.json
Linux ~/.config/claude/claude_desktop_config.json

Step 2: Create/Edit the Config File

Open the config file with your favorite editor:

macOS (with VS Code):

code ~/Library/Application\ Support/Claude/claude_desktop_config.json

Windows (PowerShell):

code "$env:APPDATA\Claude\claude_desktop_config.json"

Step 3: Configure Your MCP Server

Add your server configuration:

{
  "mcpServers": {
    "my-server": {
      "command": "uv",
      "args": [
        "--directory",
        "C:/path/to/your/my-mcp-server",
        "run",
        "server.py"
      ]
    }
  }
}

⚠️ Important Notes:

  • Use absolute paths for the directory
  • On Windows, use forward slashes (/) or escaped backslashes (\\)
  • The command should be the full path to uv if not in PATH

Getting the Correct Paths

# Find uv location
# On macOS/Linux:
which uv

# On Windows:
where uv

# Get current directory path (for --directory argument)
# On macOS/Linux:
pwd

# On Windows:
cd

Your First MCP Server

Let's create a simple MCP server that provides a greeting tool.

Create server.py

"""
My First MCP Server
A simple server that demonstrates MCP tool creation.
"""

from mcp.server.fastmcp import FastMCP

# Initialize the FastMCP server with a name
mcp = FastMCP("greeting-server")


@mcp.tool()
def greet(name: str) -> str:
    """
    Generate a friendly greeting.
    
    Args:
        name: The name of the person to greet
    
    Returns:
        A personalized greeting message
    """
    return f"Hello, {name}! Welcome to the world of MCP! 🎉"


@mcp.tool()
def add_numbers(a: float, b: float) -> float:
    """
    Add two numbers together.
    
    Args:
        a: First number
        b: Second number
    
    Returns:
        The sum of the two numbers
    """
    return a + b


@mcp.tool()
def get_current_time() -> str:
    """
    Get the current date and time.
    
    Returns:
        Current date and time as a formatted string
    """
    from datetime import datetime
    return datetime.now().strftime("%Y-%m-%d %H:%M:%S")


def main():
    """Run the MCP server with stdio transport."""
    mcp.run(transport="stdio")


if __name__ == "__main__":
    main()

Key Components Explained

Component Purpose
FastMCP("name") Initialize server with a unique name
@mcp.tool() Decorator to register a function as an MCP tool
docstring Describes the tool for the LLM
type hints Define input/output types for validation
mcp.run(transport="stdio") Start server with stdio communication

Testing Your Setup

Method 1: Run Directly (You need a client to communicate with it)

# With uv:
uv run server.py

# With pip:
python server.py

Method 2: Test with Claude Desktop

  1. Restart Claude Desktop after configuring claude_desktop_config.json
  2. Look for the Connectors in the Claude interface
  3. Your server should appear in the list of connected servers or else config it manually inside Manage Connectors.
  4. Try asking Claude: "Can you greet me using the greeting tool?"

Troubleshooting

Common Issues and Solutions

❌ Python Version Too Old

Error: Python 3.10+ is required

Solution: Install Python 3.10 or higher from python.org

❌ MCP Package Not Found

ModuleNotFoundError: No module named 'mcp'

Solution: Ensure you've installed MCP in your virtual environment:

pip install mcp
# or
uv add mcp

❌ Claude Desktop Not Detecting Server

Solutions:

  1. Restart Claude Desktop completely
  2. Verify the config file is valid JSON (use a JSON validator)
  3. Check that paths are absolute and correct
  4. Ensure the server file exists at the specified location

❌ Logging Issues with stdio Transport

Important: When using stdio transport, avoid print() statements!

Why? MCP uses stdout for communication. Regular print statements interfere with the protocol.

# ❌ Bad - Don't do this!
print("Processing request...")

# ✅ Good - Use logging instead
import logging
logging.basicConfig(level=logging.INFO, stream=sys.stderr)
logger = logging.getLogger(__name__)
logger.info("Processing request...")

❌ Windows Path Issues

If your paths contain backslashes, escape them properly:

{
  "mcpServers": {
    "my-server": {
      "command": "uv",
      "args": [
        "--directory",
        "C:\\Users\\username\\projects\\my-mcp-server",
        "run",
        "server.py"
      ]
    }
  }
}

Or use forward slashes (works on Windows too):

"C:/Users/username/projects/my-mcp-server"

Key Takeaways

  • What is MCP? Open standard for connecting LLMs to external tools and data
  • Core Primitives Tools, Resources, and Prompts
  • Python Requirement Python 3.10+ required
  • Recommended Setup Use uv for faster, modern package management
  • Server Creation Use FastMCP class and @mcp.tool() decorator
  • Transport Use stdio for Claude Desktop integration
  • Logging Never use print() with stdio; use logging to stderr

Additional Resources

Official Documentation

Quick Links