Skip to content

Step-by-step: build an MCP server in Python (MCPServer)

Each step has a Goal, what to Do, and how to Verify it. Track progress with the MCP checklist. The finished server is the Python template: download it from the templates page.

The official mcp package (v2) provides MCPServer (from mcp.server.mcpserver import MCPServer). It turns type hints and docstrings into tool schemas automatically, and it serves both current 2026-07-28 clients and legacy 2025 clients (see Protocol versions).

Renamed in v2: in mcp 1.x this class was called FastMCP (from mcp.server.fastmcp import FastMCP). The decorators (@mcp.tool(), @mcp.resource(), @mcp.prompt()) and mcp.run() keep the same syntax, but some behaviour changed: for example, a raised ValueError no longer shows its message to the model (see Step 5). The separate third-party fastmcp package is a different project. If you must keep v1 code running, pin mcp<2. Migration guide: https://py.sdk.modelcontextprotocol.io/v2/migration/.


  • Goal: A short list of task-shaped tools.
  • Do: The same as in the TypeScript guide, Step 1. One tool per user job, fewer than about 10 tools (this guide’s rule of thumb), and each one marked as read-only or not.
  • Verify: Every tool maps to a real request.
  • Goal: An isolated, reproducible environment.

  • Do:

    Terminal window
    # install uv once: https://docs.astral.sh/uv/ (Windows: winget install astral-sh.uv)
    uv init notes-server
    cd notes-server
    uv add "mcp[cli]"

    If you use pip instead: python -m venv .venv, activate it, then pip install "mcp[cli]".

  • Verify: uv run python -c "import mcp; print('ok')" prints ok.

  • Goal: A server that connects over stdio.

  • Do: In server.py:

    import sys
    from mcp.server.mcpserver import MCPServer
    mcp = MCPServer("notes", version="0.1.0")
    # tools, resources, prompts go here
    if __name__ == "__main__":
    print("notes MCP server starting on stdio", file=sys.stderr) # stderr, never stdout
    mcp.run() # stdio by default
  • Verify: uv run mcp dev server.py opens the Inspector and connects.

  • Goal: Type-safe tools with good descriptions.

  • Do:

    1. Add the storage helpers near the top of server.py. They read and write a JSON file, and search sorts matches newest first:

      import json
      import os
      from datetime import datetime, timezone
      from pathlib import Path
      NOTES_FILE = Path(os.environ.get("NOTES_FILE", str(Path.home() / ".notes-mcp.json")))
      def load_notes() -> list[dict]:
      if not NOTES_FILE.exists():
      return []
      return json.loads(NOTES_FILE.read_text(encoding="utf-8"))
      def save_notes(notes: list[dict]) -> None:
      NOTES_FILE.write_text(json.dumps(notes, indent=2), encoding="utf-8")
      def now_iso() -> str:
      return datetime.now(timezone.utc).isoformat()
      def search(notes: list[dict], query: str, limit: int) -> list[dict]:
      q = query.lower()
      hits = [n for n in notes if q in f"{n['title']} {n['body']}".lower()]
      return sorted(hits, key=lambda n: n["created"], reverse=True)[:limit] # newest first
    2. Add the tool. The docstring becomes the description and the type hints become the schema:

      from typing import Annotated
      from mcp.types import ToolAnnotations
      from pydantic import Field
      @mcp.tool(annotations=ToolAnnotations(readOnlyHint=True, openWorldHint=False))
      def search_notes(
      query: Annotated[str, Field(min_length=1, description="Keyword or phrase, case-insensitive")],
      limit: Annotated[int, Field(ge=1, le=20, description="Maximum results (1-20)")] = 5,
      ) -> str:
      """Search saved notes by keyword in title or body. Returns up to `limit`
      matches, newest first. Use before add_note to avoid duplicates."""
      hits = search(load_notes(), query, limit)
      if not hits:
      return f'No notes match "{query}". Try a broader keyword.'
      return "\n".join(f"- {n['title']} ({n['created']}): {n['body'][:200]}" for n in hits)
  • Verify: In the Inspector, the tool’s schema shows query (required) and limit (default 5), and running it works.

  • Goal: The model can recover from failures.

  • Do: For expected failures, raise ToolError with an actionable message. MCPServer returns it to the model as a tool error (isError: true) with your message:

    from mcp.server.mcpserver.exceptions import ToolError
    @mcp.tool(annotations=ToolAnnotations(readOnlyHint=False, destructiveHint=False, idempotentHint=False, openWorldHint=False))
    def add_note(
    title: Annotated[str, Field(min_length=1, max_length=120, description="Unique note title")],
    body: Annotated[str, Field(min_length=1, max_length=10_000, description="Note content (Markdown allowed)")],
    ) -> str:
    """Save a new note with a unique title and a Markdown body. Fails if a
    note with the same title already exists, so use search_notes first if
    unsure. Returns a confirmation with the saved title."""
    notes = load_notes()
    if any(n["title"].lower() == title.lower() for n in notes):
    raise ToolError(f'A note titled "{title}" already exists. Choose a different title or use search_notes to find it.')
    notes.append({"title": title, "body": body, "created": now_iso()})
    save_notes(notes)
    return f'Saved note "{title}".'

    Use ToolError, not ValueError or another built-in exception. With any other exception, the model sees only “Error executing tool add_note” and can’t tell what to fix. destructiveHint and openWorldHint default to True, so set them to False when they don’t apply.

  • Verify: A duplicate title returns the “already exists” message in the Inspector, and the server stays up.

Step 6: Resources, prompts, and structured output (optional)

Section titled “Step 6: Resources, prompts, and structured output (optional)”
  • Goal: Expose read-only context, user-invoked templates, and parseable results.

  • Do:

    @mcp.resource("notes://all", mime_type="application/json")
    def all_notes() -> str:
    """Every saved note as JSON."""
    return json.dumps(load_notes(), indent=2)
    @mcp.prompt()
    def weekly_review(focus: str = "") -> str:
    """Summarise this week's notes."""
    return "Search my notes from this week and write a weekly review" + (f" focused on {focus}." if focus else ".")

    Return a Pydantic model or a TypedDict from a tool to get structured output: MCPServer generates the outputSchema and fills structuredContent for you.

  • Verify: They appear on the Inspector’s Resources and Prompts tabs.

  • Goal: No hard-coded paths or keys, non-blocking I/O, and progress on long operations.
  • Do:
    • Read configuration from environment variables with safe defaults, as NOTES_FILE does in Step 4. If a required variable is missing, print a clear message to stderr and exit.
    • Use async def for tools that do I/O (HTTP calls, database queries).
    • Add a ctx: Context parameter (from mcp.server.mcpserver import Context) for progress reporting (await ctx.report_progress(...)) and elicitation.
    • Don’t use ctx.info() or ctx.log(). They’re deprecated, because the logging capability is deprecated in the 2026-07-28 spec. Log to stderr instead.
  • Verify: It runs with the variable unset and set, and long operations report progress.
  • Goal: Automated confidence at the unit and protocol level.

  • Do:

    1. Run it in the Inspector: uv run mcp dev server.py.

    2. Run the protocol smoke test that ships with the template, from the project folder: node scripts/mcp-smoke.mjs uv run server.py (or node scripts/mcp-smoke.mjs python server.py inside an activated virtual environment). It needs Node 20 or later and nothing else. If you built from scratch, copy scripts/mcp-smoke.mjs from the template download.

    3. Unit-test the plain functions (load_notes, search) with pytest. For in-memory protocol tests, pass the MCPServer instance straight to the client:

      import pytest
      from mcp import Client
      from server import mcp
      @pytest.mark.anyio
      async def test_search_notes():
      async with Client(mcp) as client:
      result = await client.call_tool("search_notes", {"query": "x"})
      assert not result.is_error
  • Verify: The smoke test prints PASS, and pytest is green.

  • Goal: It works in real hosts.

  • Do: Follow Connect to clients. With uv, the config is:

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

    In Cursor, add "type": "stdio" to the entry. Shortcuts: uv run mcp install server.py registers it with Claude Desktop, and claude mcp add notes -- uv --directory C:/path/to/notes-server run server.py registers it with Claude Code.

  • Verify: Cursor shows the server as green (Claude Code shows “✔ Connected” in /mcp), and a natural-language request calls the tool.

  • Goal: A shared server that remote clients, including claude.ai, can reach securely.
  • Do: Switch the transport with mcp.run(transport="streamable-http"). It serves /mcp on port 8000, bound to 127.0.0.1 by default. In a container, bind to all interfaces with mcp.run(transport="streamable-http", host="0.0.0.0"). Put it behind HTTPS and authentication, and deploy it. See Security & production.
  • Verify: npx @modelcontextprotocol/inspector connects to https://your-host/mcp with authentication, and is rejected without it.