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
mcp1.x this class was calledFastMCP(from mcp.server.fastmcp import FastMCP). The decorators (@mcp.tool(),@mcp.resource(),@mcp.prompt()) andmcp.run()keep the same syntax, but some behaviour changed: for example, a raisedValueErrorno longer shows its message to the model (see Step 5). The separate third-partyfastmcppackage is a different project. If you must keep v1 code running, pinmcp<2. Migration guide: https://py.sdk.modelcontextprotocol.io/v2/migration/.
Step 1: Define the capabilities
Section titled “Step 1: Define the capabilities”- 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.
Step 2: Scaffold with uv
Section titled “Step 2: Scaffold with uv”-
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-servercd notes-serveruv add "mcp[cli]"If you use pip instead:
python -m venv .venv, activate it, thenpip install "mcp[cli]". -
Verify:
uv run python -c "import mcp; print('ok')"printsok.
Step 3: Create the server
Section titled “Step 3: Create the server”-
Goal: A server that connects over stdio.
-
Do: In
server.py:import sysfrom mcp.server.mcpserver import MCPServermcp = MCPServer("notes", version="0.1.0")# tools, resources, prompts go hereif __name__ == "__main__":print("notes MCP server starting on stdio", file=sys.stderr) # stderr, never stdoutmcp.run() # stdio by default -
Verify:
uv run mcp dev server.pyopens the Inspector and connects.
Step 4: Add tools
Section titled “Step 4: Add tools”-
Goal: Type-safe tools with good descriptions.
-
Do:
-
Add the storage helpers near the top of
server.py. They read and write a JSON file, andsearchsorts matches newest first:import jsonimport osfrom datetime import datetime, timezonefrom pathlib import PathNOTES_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 -
Add the tool. The docstring becomes the description and the type hints become the schema:
from typing import Annotatedfrom mcp.types import ToolAnnotationsfrom 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) andlimit(default 5), and running it works.
Step 5: Handle errors well
Section titled “Step 5: Handle errors well”-
Goal: The model can recover from failures.
-
Do: For expected failures, raise
ToolErrorwith an actionable message.MCPServerreturns 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 anote with the same title already exists, so use search_notes first ifunsure. 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, notValueErroror another built-in exception. With any other exception, the model sees only “Error executing tool add_note” and can’t tell what to fix.destructiveHintandopenWorldHintdefault toTrue, so set them toFalsewhen 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
TypedDictfrom a tool to get structured output:MCPServergenerates theoutputSchemaand fillsstructuredContentfor you. -
Verify: They appear on the Inspector’s Resources and Prompts tabs.
Step 7: Configuration, async, and context
Section titled “Step 7: Configuration, async, and context”- 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_FILEdoes in Step 4. If a required variable is missing, print a clear message to stderr and exit. - Use
async deffor tools that do I/O (HTTP calls, database queries). - Add a
ctx: Contextparameter (from mcp.server.mcpserver import Context) for progress reporting (await ctx.report_progress(...)) and elicitation. - Don’t use
ctx.info()orctx.log(). They’re deprecated, because the logging capability is deprecated in the 2026-07-28 spec. Log to stderr instead.
- Read configuration from environment variables with safe defaults, as
- Verify: It runs with the variable unset and set, and long operations report progress.
Step 8: Test
Section titled “Step 8: Test”-
Goal: Automated confidence at the unit and protocol level.
-
Do:
-
Run it in the Inspector:
uv run mcp dev server.py. -
Run the protocol smoke test that ships with the template, from the project folder:
node scripts/mcp-smoke.mjs uv run server.py(ornode scripts/mcp-smoke.mjs python server.pyinside an activated virtual environment). It needs Node 20 or later and nothing else. If you built from scratch, copyscripts/mcp-smoke.mjsfrom the template download. -
Unit-test the plain functions (
load_notes,search) with pytest. For in-memory protocol tests, pass theMCPServerinstance straight to the client:import pytestfrom mcp import Clientfrom server import mcp@pytest.mark.anyioasync 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.
Step 9: Connect to your clients
Section titled “Step 9: Connect to your clients”-
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.pyregisters it with Claude Desktop, andclaude mcp add notes -- uv --directory C:/path/to/notes-server run server.pyregisters 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.
Step 10: Remote deployment (optional)
Section titled “Step 10: Remote deployment (optional)”- 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/mcpon port 8000, bound to127.0.0.1by default. In a container, bind to all interfaces withmcp.run(transport="streamable-http", host="0.0.0.0"). Put it behind HTTPS and authentication, and deploy it. See Security & production. - Verify:
npx @modelcontextprotocol/inspectorconnects tohttps://your-host/mcpwith authentication, and is rejected without it.