Build an MCP Server in Python with FastMCP

Step-by-step: build a Model Context Protocol server in Python using the official SDK and FastMCP, expose tools and resources, test it and connect it.

Published December 1, 2026

The fastest way to understand MCP is to build a server. With the official Python SDK and its FastMCP API, a working server that exposes a tool and a resource is about twenty lines. In this tutorial you will build a small "notes" server, test it with the MCP Inspector, and connect it to an AI host.

The concept

FastMCP turns ordinary Python functions into MCP primitives with decorators. Type hints and docstrings become the tool's input schema and description, which the model reads to decide when and how to call it. Return values are converted into MCP content automatically.

During development the server runs over stdio: the host launches it as a subprocess and talks through stdin and stdout. That means you must never print debug output to stdout, because it would corrupt the protocol stream. Log to stderr instead.

The plan

  1. Create a project and install the SDK (uv add "mcp[cli]")
  2. Create a FastMCP instance with a server name
  3. Decorate functions with @mcp.tool() and @mcp.resource()
  4. Run with mcp.run() (stdio by default)
  5. Test in the Inspector, then register it in your host config
From empty folder to connected server.

The complete server

Save as notes_server.py. Notes are kept in a JSON file so they persist between runs.

import json, sys
from pathlib import Path
from mcp.server.fastmcp import FastMCP

mcp = FastMCP("notes")
STORE = Path.home() / ".notes.json"

def _load() -> dict[str, str]:
    return json.loads(STORE.read_text()) if STORE.exists() else {}

@mcp.tool()
def add_note(title: str, body: str) -> str:
    """Save a note under a short title. Overwrites an existing note with the same title."""
    notes = _load(); notes[title] = body
    STORE.write_text(json.dumps(notes, indent=2))
    print(f"saved {title}", file=sys.stderr)      # stderr, never stdout
    return f"Saved note '{title}'"

@mcp.tool()
def search_notes(query: str) -> list[str]:
    """Return titles of notes whose title or body contains the query (case-insensitive)."""
    q = query.lower()
    return [t for t, b in _load().items() if q in t.lower() or q in b.lower()]

@mcp.resource("notes://{title}")
def read_note(title: str) -> str:
    """The full text of one note."""
    return _load().get(title, "Note not found")

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

Test it

uv init notes-mcp && cd notes-mcp && uv add "mcp[cli]"
uv run mcp dev notes_server.py
Starting MCP inspector...
MCP Inspector is up and running at http://127.0.0.1:6274
mcp dev launches the server together with the Inspector.

Practical examples

Register in a host

Use absolute paths; hosts often start servers from a different working directory.

{
  "mcpServers": {
    "notes": { "command": "uv", "args": ["--directory", "/abs/path/notes-mcp", "run", "notes_server.py"] }
  }
}

Return structured data

Typed return values (Pydantic models, TypedDicts) give the model clean structured results.

from pydantic import BaseModel

class Note(BaseModel):
    title: str
    words: int

@mcp.tool()
def list_notes() -> list[Note]:
    """List all notes with word counts."""
    return [Note(title=t, words=len(b.split())) for t, b in _load().items()]

Serve over HTTP instead of stdio

For remote use, run the Streamable HTTP transport.

if __name__ == "__main__":
    mcp.run(transport="streamable-http")   # serves on /mcp

Common mistakes

  • print() to stdout in a stdio server, which breaks the JSON-RPC stream.
  • Vague docstrings; the model chooses tools from their descriptions.
  • Tools that do too much; prefer small, well-named operations.
  • Relative paths in host configs that resolve differently at launch.

Key takeaways

  • FastMCP turns typed, documented Python functions into MCP tools and resources.
  • Log to stderr in stdio servers.
  • Test with mcp dev / the Inspector before connecting a host.
  • Switch to Streamable HTTP when the server must run remotely.

FAQ

Which Python version do I need?

A recent Python 3 (3.10+) works with the current SDK; check the SDK README for the exact minimum.

Can a tool be async?

Yes. Define it with async def and FastMCP awaits it, which is ideal for HTTP calls or database queries.

How do I pass secrets like API keys?

Use environment variables set in the host config (an "env" block) rather than hard-coding them.

More AI articles