Learn › MCP: Model Context Protocol — Complete Developer Guide › Building Your First MCP Server (Python)

Building Your First MCP Server (Python)

Intermediate 🕐 35 min Lesson 7 of 11
What you'll learn
  • Set up a Python MCP server project using uv and the official MCP SDK
  • Register tools using the @mcp.tool() decorator and explain how type hints generate the JSON Schema
  • Test a server with the MCP Inspector and connect it to Claude Desktop

What You Will Build

This lesson walks you through building a weather server — the same project used in the official MCP quickstart — from an empty directory to a running server connected to Claude Desktop. The server exposes two tools: one that returns weather alerts for a US state, and one that returns a forecast for a latitude and longitude. It uses the US National Weather Service public API, which requires no API key.

By the end of this lesson you will have a working MCP server you can extend, a mental model of how the Python SDK maps to the protocol concepts from earlier lessons, and the experience of debugging with the MCP Inspector.

Prerequisites

  • Python 3.10 or higher
  • uv package manager (astral.sh/uv) — a fast, modern Python package manager that handles virtual environments automatically
  • Claude Desktop installed and running

If you do not have uv, install it with:

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

Setting Up the Project

Create a new directory and initialize a uv project inside it:

uv init weather
cd weather

This creates a pyproject.toml, a sample main.py, and a .python-version file. Next, add the MCP SDK with its CLI tools:

uv add "mcp[cli]"

The [cli] extra installs the MCP Inspector and other development utilities alongside the core SDK. Create the server file:

touch weather.py

Your project structure is now:

weather/
├── pyproject.toml
├── .python-version
├── .venv/
└── weather.py

Writing the Server

Open weather.py and write the following. Read through it first; the explanation follows.

from typing import Any
import httpx
import logging
from mcp.server import MCPServer
from mcp.server.mcpserver.exceptions import ToolError

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

mcp = MCPServer("weather")

NWS_API_BASE = "https://api.weather.gov"
USER_AGENT = "weather-mcp-server/1.0"


async def make_nws_request(url: str) -> dict[str, Any] | None:
    headers = {"User-Agent": USER_AGENT, "Accept": "application/geo+json"}
    async with httpx.AsyncClient(follow_redirects=True) as client:
        try:
            response = await client.get(url, headers=headers, timeout=30.0)
            response.raise_for_status()
            return response.json()
        except Exception as e:
            logger.error("NWS request failed: %s", e)
            return None


@mcp.tool()
async def get_alerts(state: str) -> str:
    """Get active weather alerts for a US state.

    Args:
        state: Two-letter US state code (e.g. CA, NY, TX)
    """
    data = await make_nws_request(f"{NWS_API_BASE}/alerts/active?area={state}")
    if not data or "features" not in data:
        raise ToolError(f"Could not retrieve alerts for {state}.")
    features = data["features"]
    if not features:
        return f"No active alerts for {state}."
    alerts = []
    for f in features[:5]:
        p = f.get("properties", {})
        alerts.append(
            f"**{p.get('event', 'Alert')}** in {p.get('areaDesc', 'unknown area')}
"
            f"{p.get('headline', '')}"
        )
    return "

".join(alerts)


@mcp.tool()
async def get_forecast(latitude: float, longitude: float) -> str:
    """Get the weather forecast for a location.

    Args:
        latitude: Latitude of the location (-90 to 90)
        longitude: Longitude of the location (-180 to 180)
    """
    points = await make_nws_request(f"{NWS_API_BASE}/points/{latitude},{longitude}")
    if not points:
        raise ToolError(f"Could not resolve coordinates {latitude}, {longitude}.")
    forecast_url = points.get("properties", {}).get("forecast")
    if not forecast_url:
        raise ToolError("No forecast URL found for these coordinates.")
    forecast = await make_nws_request(forecast_url)
    if not forecast:
        raise ToolError("Could not retrieve forecast data.")
    periods = forecast.get("properties", {}).get("periods", [])[:3]
    if not periods:
        return "No forecast periods available."
    result = []
    for p in periods:
        result.append(f"**{p['name']}**: {p['detailedForecast']}")
    return "

".join(result)


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

Understanding the Code

MCPServer: The MCPServer("weather") call creates the server instance. The string "weather" is the server's identity — it appears in discovery responses and in log output. All tools you register on this instance are served when the server runs.

@mcp.tool(): This decorator registers the function as an MCP tool. The SDK reads the function's name, type hints, and docstring to build the tool definition automatically. The function name becomes the tool name. The type hints become the JSON Schema for inputSchema. The first paragraph of the docstring becomes the tool description. The Args: section populates per-parameter descriptions. You write idiomatic Python; the SDK handles the protocol.

ToolError: When something goes wrong during tool execution, raise ToolError with a human-readable message. The SDK catches this and returns an execution error (the isError: true content block discussed in Lesson 4). The model receives the error message and can decide how to respond. Do not use Python exceptions directly for user-facing errors — only ToolError produces the correct protocol response.

logging to stderr: The standard logging module writes to stderr by default, which is exactly where server output must go in a stdio server. Never call print() in a stdio server — it writes to stdout and corrupts the JSON-RPC message stream.

mcp.run(transport="stdio"): This call starts the server and blocks, reading requests from stdin and writing responses to stdout. The transport argument can be "stdio" (for local use) or "streamable-http" (for remote deployment).

Testing with the MCP Inspector

Before connecting to Claude Desktop, test your server with the MCP Inspector — a command-line tool that lets you send protocol messages interactively.

Run the server with the Inspector in modern protocol mode:

npx @modelcontextprotocol/inspector --cli uv run weather.py --protocol-era modern --method tools/list

You should see the two tool definitions in the output. To test a tool call:

npx @modelcontextprotocol/inspector --cli uv run weather.py --protocol-era modern --method tools/call --params '{"name":"get_alerts","arguments":{"state":"CA"}}'

The Inspector also defaults to the legacy era (2025-11-25). Run the same commands with --protocol-era legacy to verify your server handles both versions correctly. The SDK does this automatically, but it is worth confirming.

If a tool call returns an error, check the server's stderr output — that is where your log messages go. The Inspector separates stdout (protocol messages) from stderr (server logs) in its output, making it easy to debug both.

Connecting to Claude Desktop

To connect your server to Claude Desktop, edit the Claude Desktop configuration file. On macOS, this is at ~/Library/Application Support/Claude/claude_desktop_config.json. On Windows, it is at %APPDATA%Claudeclaude_desktop_config.json.

Add a mcpServers section (or add to it if it already exists):

{
  "mcpServers": {
    "weather": {
      "command": "uv",
      "args": [
        "--directory",
        "/absolute/path/to/your/weather",
        "run",
        "weather.py"
      ]
    }
  }
}

Replace /absolute/path/to/your/weather with the absolute path to your project directory. Use pwd in the terminal to find it. Claude Desktop requires absolute paths — relative paths will not work.

If uv is not in your system PATH when Claude Desktop launches (common on macOS), provide the full path instead:

"command": "/Users/yourname/.cargo/bin/uv"

Find the full path with which uv in a terminal. After editing the config, fully restart Claude Desktop — not just the window, but the application. Once it restarts, you should see a tools icon indicating the server is connected. Ask Claude about the weather in California to test the integration.

Common Mistakes

  • Using print() instead of logging: Any print() call in a stdio server corrupts the message stream. Always use the logging module.
  • Relative paths in claude_desktop_config.json: Claude Desktop resolves paths from its own working directory, not from your home directory. Always use absolute paths.
  • Not restarting Claude Desktop: Configuration changes are only read on startup. A window refresh is not enough — quit and reopen the application.
  • Catching all exceptions silently: If make_nws_request returns None and you do not handle it, the tool will return an empty string to the model, which will misinterpret it as a successful empty result. Always check for None and raise ToolError with a clear message.
  • Using uv without the --directory flag: Without --directory, uv may not find the project's virtual environment. Always specify the absolute path to the project root.
Key takeaways
  • The @mcp.tool() decorator reads type hints and docstrings to build the tool definition automatically — no hand-written JSON Schema required
  • ToolError is the correct way to report execution failures; plain Python exceptions produce protocol-level errors the model cannot recover from
  • stdio servers must never write to stdout — use the logging module, not print()
Learn more every week Get 5 hand-picked prompts + new AI tools every Monday. Free.