How to Build an MCP Server in Python: A Working Example

Female software engineer developing and testing a custom Python MCP server in a modern office

To learn how to build an MCP server in Python, you define standard type-annotated functions decorated with tools, resources, or prompts using the official Model Context Protocol Python SDK. The lightweight framework automatically generates JSON Schema definitions, handles JSON-RPC 2.0 communication over standard input/output (stdio), and exposes your custom capabilities directly to AI hosts. In less than twenty lines of code, you can build a production-ready server that connects Claude Desktop, Claude Code, Cursor, or VS Code to your local tools and data sources.

The Model Context Protocol (MCP) acts as an open standard for connecting large language models to external data and executables. If you are new to the core architecture, read our breakdown of what an MCP server is and how it replaces fragmented API wrappers. In this tutorial, you will build a functional Python MCP server from scratch, test it interactively with the MCP Inspector, and attach it to your everyday developer hosts.

Prerequisites

Ensure your environment satisfies these baseline requirements:

  • Python 3.11+: The MCP Python SDK requires modern async and typing primitives.
  • uv package manager: We recommend uv for fast, deterministic dependency isolation.
  • An MCP-compatible host: Claude Desktop, Claude Code, Cursor, or VS Code with GitHub Copilot.

Verify Python and install uv:

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

Step 1: Set Up the Project Environment

Create a dedicated workspace directory and initialize a Python project managed by uv. Installing mcp[cli] provides the server SDK and developer CLI tools like mcp dev and mcp install.

mkdir weather-mcp-server
cd weather-mcp-server
uv init
uv add "mcp[cli]" httpx

This generates a clean virtual environment and installs the required packages alongside httpx for outgoing HTTP requests.

Step 2: Write the Complete MCP Server in Python

Create a file named server.py in your project root. In this practical example, our server provides three core MCP primitives: an executable tool that fetches real weather data, a static documentation resource, and a reusable prompt template.

import httpx
from mcp.server import MCPServer
from mcp.server.mcpserver.exceptions import ToolError

mcp = MCPServer("WeatherAssistant")

@mcp.tool()
async def get_current_weather(city: str) -> str:
    """Fetch current temperature and weather conditions for a city.
    
    Args:
        city: The name of the city (e.g. London, Berlin, Austin).
    """
    if not city.strip():
        raise ToolError("City name cannot be empty.")
    
    async with httpx.AsyncClient() as client:
        geo_url = f"https://geocoding-api.open-meteo.com/v1/search?name={city}&count=1&format=json"
        res = await client.get(geo_url, timeout=10.0)
        results = res.json().get("results")
        if not results:
            raise ToolError(f"Coordinates not found for {city!r}.")
        
        lat, lon = results[0]["latitude"], results[0]["longitude"]
        w_url = f"https://api.open-meteo.com/v1/forecast?latitude={lat}&longitude={lon}¤t_weather=true"
        w_res = await client.get(w_url, timeout=10.0)
        curr = w_res.json().get("current_weather", {})
        return f"{city.title()}: {curr.get('temperature')}°C, wind {curr.get('windspeed')} km/h"

@mcp.resource("docs://weather/guidelines")
def weather_guidelines() -> str:
    """Guidelines and data usage policies for the weather service."""
    return (
        "Weather Data Guidelines:\n"
        "- Forecast data is sourced from public meteorological stations.\n"
        "- Temperatures are reported in Celsius.\n"
        "- Cached readings expire every 15 minutes."
    )

@mcp.prompt()
def weather_briefing(city: str) -> str:
    """Generate a structured weather briefing prompt for the user."""
    return (
        f"Please check the current weather in {city} using the get_current_weather tool, "
        f"and provide a practical summary including outfit advice and outdoor recommendations."
    )

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

Understanding the Primitives

Notice how straightforward this implementation is compared to manual API frameworks:

  • No explicit JSON schemas: Type hints like city: str and function docstrings are automatically parsed by the SDK into standard JSON Schema parameters for the AI host.
  • Tools vs. Resources: The @mcp.tool() decorator registers an executable function called autonomously by the model. The @mcp.resource() decorator exposes context data loaded into the prompt context by the host.
  • Transport execution: The mcp.run() call runs a stdio server that communicates over stdin and stdout. If you want to containerize services later, review our guide on running MCP servers in Docker.

Step 3: Test Interactively with MCP Inspector

Never connect an untested server directly to your daily AI desktop client. The SDK includes a built-in testing harness called the MCP Inspector. It launches an isolated web interface where you can inspect capabilities, run tool calls, and review raw JSON-RPC traffic.

Run the inspector from your project folder:

uv run mcp dev server.py

Open the printed localhost URL in your browser:

  1. Navigate to the Tools tab. You will see get_current_weather listed with a description and an input field for city.
  2. Enter Berlin and click Call Tool. Confirm that the function executes and returns live meteorological data.
  3. Click the Resources tab and read docs://weather/guidelines to confirm static text resolves properly.
  4. Review the Prompts tab to verify parameter substitution.

Press Ctrl+C in your terminal when testing is complete.

Step 4: Connect the Server to AI Hosts

An MCP server communicates over standard input and output streams. The AI application (the host) launches your Python script as a child process and reads its responses. To understand how client applications negotiate protocols under the hood, explore how MCP clients connect to servers.

Connecting to Claude Desktop

The Python SDK provides an automated command to register your server inside Claude Desktop without editing JSON files by hand:

uv run mcp install server.py

This command resolves absolute file paths and writes the launch entry directly into claude_desktop_config.json (located at ~/Library/Application Support/Claude/ on macOS or %APPDATA%\Claude\ on Windows). For manual setup, add the server to mcpServers with command uv and args ["run", "--with", "mcp[cli]", "mcp", "run", "/absolute/path/to/server.py"]. Fully quit Claude Desktop and reopen it; a hammer icon confirms active tools.

Connecting to Claude Code, Cursor, and VS Code

For Claude Code CLI, register the server via terminal:

claude mcp add weather -- uv run --with "mcp[cli]" mcp run /absolute/path/to/weather-mcp-server/server.py

For Cursor and VS Code, add the launch command to your project configuration file (.cursor/mcp.json under mcpServers or .vscode/mcp.json under servers with "type": "stdio"):

{
  "mcpServers": {
    "weather": {
      "command": "uv",
      "args": ["run", "--with", "mcp[cli]", "mcp", "run", "/absolute/path/to/weather-mcp-server/server.py"]
    }
  }
}

Step 5: Verify the Execution Result

To verify that your server works inside the host:

  1. Open a chat session in Claude Desktop or your IDE assistant.
  2. Prompt the model: “What is the current weather in Tokyo right now?”
  3. Observe the assistant invoking get_current_weather(city="Tokyo").
  4. The assistant receives the structured output and answers with live meteorological readings.

Common Pitfalls and How to Avoid Them

When developing custom MCP servers, developers frequently encounter three specific failure modes:

1. Standard Output (stdout) Pollution

When using the stdio transport, standard output is reserved strictly for JSON-RPC 2.0 messages. If you write raw print("Debug info") statements or an external library prints to stdout, the host JSON parser crashes immediately with protocol errors.

Fix: Direct all debugging and application logs to standard error using the standard Python logging module or sys.stderr.write():

import sys
import logging

logging.basicConfig(stream=sys.stderr, level=logging.INFO)
logging.info("Server started successfully.")

2. Relative File Paths in Host Configurations

AI desktop applications do not launch your server script from your project directory. They spawn subprocesses from their own application root. If you configure server.py instead of /home/user/projects/server.py, the process fails with a FileNotFoundError.

Fix: Always specify absolute file paths to both the executable (uv or python) and your server script in your host configuration JSON.

3. Forgetting to Fully Restart the AI Host

Hosts load configuration files only once at startup. Closing the window on macOS or minimizing to the Windows system tray keeps background processes running without reloading edited configs.

Fix: Force-close the application via Activity Monitor, Task Manager, or the menu bar explicit Quit action before testing updates.

Comparison: Stdio vs. Streamable HTTP Transport

The MCP Python SDK supports multiple transport mechanisms depending on your deployment target:

Feature stdio Transport Streamable HTTP Transport
Execution Model Local subprocess managed by host Standalone web service or daemon
Network Overhead Zero latency, direct pipe communication HTTP/JSON overhead across network
Security Model OS-level user process permissions Requires OAuth 2.0 or bearer tokens
Multi-User Support Single local user only Scalable across teams and microservices
Best For Local CLI tools, IDEs, desktop agents Enterprise APIs, cloud deployments, shared tools

Frequently Asked Questions

Can I see a minimal MCP server Python example without external dependencies?

Yes. A minimal working MCP server Python example requires only the mcp package and standard library primitives:

from mcp.server import MCPServer

mcp = MCPServer("MinimalDemo")

@mcp.tool()
def calculate_sum(a: int, b: int) -> int:
    """Calculate the sum of two integers."""
    return a + b

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

Save this code as minimal.py and execute uv run --with "mcp[cli]" mcp dev minimal.py to inspect it immediately without creating a project.

What is the difference between an MCP tool and an MCP resource?

The primary distinction lies in control and side effects. An MCP tool is model-controlled: the LLM decides autonomously when to call it to execute an action or perform a calculation. An MCP resource is application-controlled: the host application loads structured data or file content directly into the model context window as background information, functioning similarly to a read-only HTTP GET request.

How do I deploy a Python MCP server over HTTP instead of stdio?

You can serve the exact same MCPServer instance over Streamable HTTP using the built-in runner command: uv run mcp run server.py --transport streamable-http --port 8000. This exposes an endpoint at http://localhost:8000/mcp that remote clients can query using token authentication.

Conclusion

Building an MCP server in Python requires minimal boilerplate thanks to the modern official SDK. By defining type-hinted functions and decorating them with @mcp.tool() or @mcp.resource(), you immediately turn Python scripts into secure capabilities that any modern AI assistant can utilize. Start by developing local tools with the stdio transport, test them with the MCP Inspector, and plug them into Claude or your preferred IDE to automate your engineering workflows.