MCP服务器开发教程

这是一份面向开发者的 MCP 服务器入门教程,指导用户从零搭建并连接 MCP 服务器,为 AI 助手提供可调用的自定义工具和数据服务。

  • by 004Ongoro
  • Python
  • 本地部署
  • 1 星标
  • 更新于
在 GitHub 查看 004Ongoro/learning-mcps-for-beginners

使用说明

Building Your First MCP Server: A Beginner's Tutorial

Welcome! This tutorial will teach you what the Model Context Protocol (MCP) is and guide you through creating your very first MCP server from scratch.

Table of Contents

  1. What is MCP?
  2. Why Should You Care?
  3. Prerequisites
  4. Step-by-Step Setup
  5. Understanding the Code
  6. Testing Your Server
  7. Connecting to Claude Desktop
  8. What's Next?

What is MCP?

Think of MCP (Model Context Protocol) as a way to give AI assistants like Claude superpowers.

Normally, AI assistants can only answer questions based on what they already know. But what if you want Claude to:

  • Check the weather in real-time?
  • Read files from your computer?
  • Query your database?
  • Control your smart home devices?

That's where MCP comes in! It's a standard way for AI assistants to connect to external tools and data sources that you create.

The Simple Analogy

Imagine Claude is a brilliant assistant locked in a room. MCP is like giving Claude a telephone to call different services:

  • Need weather? Call the weather service
  • Need to save a file? Call the file service
  • Need to check your calendar? Call the calendar service

You build these "services" (called MCP servers), and Claude can call them when needed.


Why Should You Care?

As a developer, MCP allows you to:

  1. Extend AI capabilities - Make AI work with your specific tools and data
  2. Maintain control - You decide what the AI can and cannot access
  3. Create reusable tools - Build once, use across any MCP-compatible AI
  4. Join a growing ecosystem - MCP is an open standard gaining widespread adoption

Prerequisites

Before we begin, make sure you have:

  • Python 3.10 or higher installed (Download here)
  • Basic Python knowledge (functions, async/await)
  • A text editor (VS Code, PyCharm, or any editor you like)
  • Terminal/Command Prompt access

Optional but helpful:

  • Claude Desktop installed (to see your server in action)
  • Node.js installed (for using the MCP Inspector testing tool)
  • UV installed (a python package manager, Download here)

Step-by-Step Setup

Step 1: Create Your Project Directory

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

Step 2: Set Up Python Environment

We'll use uv (a fast Python package manager) or traditional venv:

Option A: Using uv (Recommended - Faster)

# Install uv if you don't have it
pip install uv

# Create virtual environment
uv venv

# Activate it
# On Windows:
.venv\Scripts\activate
# On macOS/Linux:
source .venv/bin/activate

Option B: Using traditional venv

# Create virtual environment
python -m venv .venv

# Activate it
# On Windows:
.venv\Scripts\activate
# On macOS/Linux:
source .venv/bin/activate

Step 3: Install Dependencies

Create a pyproject.toml file:

[project]
name = "my-mcp-server"
version = "0.1.0"
description = "My first MCP server"
readme = "README.md"
requires-python = ">=3.10"
dependencies = [
    "httpx>=0.28.1",
    "mcp[cli]>=1.26.0",
]

Then install:

# With uv
uv pip install -e .

# With pip
pip install -e .

Step 4: Create Your First MCP Server

Create a file called main.py:

from mcp.server.fastmcp import FastMCP

# Initialize your MCP server
mcp = FastMCP("MyFirstServer")

# Define a tool that the AI can use
@mcp.tool()
async def get_weather(city: str) -> str:
    """Get the current weather for a specific city."""
    return f"The weather in {city} is currently sunny and 25°C."

# Run the server
if __name__ == "__main__":
    mcp.run()

That's it! You've created your first MCP server! 🎉


Understanding the Code

Let's break down what each part does:

1. Import FastMCP

from mcp.server.fastmcp import FastMCP

FastMCP is a framework that makes building MCP servers easy. It handles all the complex protocol details for you.

2. Initialize the Server

mcp = FastMCP("MyFirstServer")

This creates your server and gives it a name. This name will appear when AI assistants connect to it.

3. Define a Tool

@mcp.tool()
async def get_weather(city: str) -> str:
    """Get the current weather for a specific city."""
    return f"The weather in {city} is currently sunny and 25°C."

This is where the magic happens! Let's break it down:

  • @mcp.tool() - This decorator tells MCP "this function is a tool that AI can use"
  • async def - MCP uses async functions for better performance
  • city: str - The parameter the AI will provide (the city name)
  • -> str - The return type (a string with weather info)
  • Docstring - The AI reads this to understand what the tool does!

4. Run the Server

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

This starts your server and makes it ready to receive requests.


Testing Your Server

Method 1: MCP Inspector (Recommended for Learning)

The MCP Inspector is a web-based tool that lets you test your server interactively:

npx @modelcontextprotocol/inspector python main.py

This will:

  1. Start your MCP server
  2. Open a web interface in your browser
  3. Let you see all available tools
  4. Allow you to call tools and see responses

Try it: Call the get_weather tool with city="Tokyo" and see what happens!

Method 2: Run Directly

python main.py

The server will start and wait for connections. You won't see much output - that's normal! The server is waiting for an AI assistant to connect.


Connecting to Claude Desktop

Now let's connect your server to Claude so you can use it in real conversations!

Step 1: Find Your Configuration File

On Windows:

%APPDATA%\Claude\claude_desktop_config.json

(Usually: C:\Users\YourName\AppData\Roaming\Claude\claude_desktop_config.json)

On macOS:

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

Step 2: Edit the Configuration

If the file doesn't exist, create it. Add your server configuration:

{
  "mcpServers": {
    "my-first-server": {
      "command": "python",
      "args": ["C:\\Users\\YourName\\projects\\my-mcp-server\\main.py"]
    }
  }
}

Important: Replace C:\\Users\\YourName\\projects\\my-mcp-server\\main.py with the actual path to your main.py file.

On macOS/Linux, use forward slashes:

{
  "mcpServers": {
    "my-first-server": {
      "command": "python",
      "args": ["/Users/yourname/projects/my-mcp-server/main.py"]
    }
  }
}

Step 3: Restart Claude Desktop

Close and reopen Claude Desktop completely.

Step 4: Test It!

Open a conversation in Claude and try asking:

"What's the weather in Paris?"

Claude should now be able to use your tool! You'll see it call the get_weather tool and get the response.


What's Next?

Congratulations! You've built and connected your first MCP server. Here are some ideas to expand your learning:

1. Make It Real - Connect to an Actual Weather API

Replace the mock data with a real weather API:

import httpx

@mcp.tool()
async def get_weather(city: str) -> str:
    """Get the current weather for a specific city."""
    async with httpx.AsyncClient() as client:
        response = await client.get(
            f"https://api.openweathermap.org/data/2.5/weather?q={city}&appid=YOUR_API_KEY"
        )
        data = response.json()
        temp = data["main"]["temp"] - 273.15  # Convert Kelvin to Celsius
        return f"The weather in {city} is {data['weather'][0]['description']} and {temp:.1f}°C."

Get a free API key from OpenWeatherMap.

2. Add More Tools

Create additional tools for different purposes:

@mcp.tool()
async def add_numbers(a: int, b: int) -> int:
    """Add two numbers together."""
    return a + b

@mcp.tool()
async def get_random_fact() -> str:
    """Get a random interesting fact."""
    facts = [
        "Honey never spoils.",
        "Octopuses have three hearts.",
        "Bananas are berries, but strawberries aren't."
    ]
    import random
    return random.choice(facts)

3. Add Resources

Resources let AI assistants read data (like files or database entries):

@mcp.resource("config://app")
async def get_config() -> str:
    """Application configuration."""
    return "Debug mode: enabled\nVersion: 1.0.0"

4. Add Prompts

Prompts are reusable templates that users can invoke:

@mcp.prompt()
async def review_code() -> str:
    """A prompt template for code review."""
    return "Please review this code for:\n1. Bugs\n2. Performance\n3. Best practices"

5. Error Handling

Make your tools more robust:

@mcp.tool()
async def get_weather(city: str) -> str:
    """Get the current weather for a specific city."""
    try:
        if not city:
            return "Error: Please provide a city name."

        # Your weather logic here
        return f"The weather in {city} is currently sunny and 25°C."

    except Exception as e:
        return f"Error getting weather: {str(e)}"

Troubleshooting

"Module not found" error

  • Make sure your virtual environment is activated
  • Run pip install -e . again

Claude Desktop doesn't show the tool

  • Check that the path in claude_desktop_config.json is correct
  • Make sure you restarted Claude Desktop completely
  • Check the Claude Desktop logs for errors

Server won't start

  • Ensure you have Python 3.10 or higher
  • Check that all dependencies are installed
  • Look for syntax errors in your main.py

Learn More


Congratulations! 🎉

You've learned:

  • ✅ What MCP is and why it matters
  • ✅ How to set up a Python MCP server
  • ✅ How to create tools that AI assistants can use
  • ✅ How to test your server
  • ✅ How to connect your server to Claude Desktop

You're now ready to build amazing AI integrations! Start small, experiment, and have fun building!


Questions or Issues?

If you get stuck:

  1. Check the troubleshooting section above
  2. Review the MCP documentation
  3. Look at example servers in the MCP repository
  4. Try the MCP Inspector to debug your tools

Happy coding! 🚀