A Python server with the official SDK (stdio)
Skill packs and prompts are provided in English so they work best with the AI tools. Use them as-is.
A Python server with the official SDK (stdio)
Read this before the video (optional, partially obsolete). The embedded freeCodeCamp course (YouTube DosHnyq78xY) installs the standalone fastmcp package without a version pin and tests with an older, unpinned MCP Inspector. Do not copy those commands. This lesson uses the official Python SDK, mcp 2.3.0, pinned with a lock file. If you launch the Inspector, use only the pinned, patched release from L09 (2.16.0): older releases have published remote code execution advisories. The video is still useful for the general idea of decorating a function to make it a tool. Where it and this lesson disagree, follow the lesson.
Where you are
Module 2, lesson 8. You know the server primitives (L04) and the stdio transport (L07). Now you build and verify a complete stdio server with the official Python SDK.
What you will be able to do
- Write an
MCPServerwith two tools, a resource and a prompt, using the official SDK 2.x. - Return structured results that match an
outputSchema, and report bad input as a tool error (isError: true). - Keep stdout clean in a stdio server.
- Verify the server with a scripted client, and register it with a host using absolute paths.
Naming: MCPServer, FastMCP and fastmcp
Three names cause most of the confusion in older tutorials:
| Name | What it is | Label |
|---|---|---|
from mcp.server import MCPServer | The high-level server class of the official SDK mcp 2.x | Current (this course) |
from mcp.server.fastmcp import FastMCP | The same class's name in SDK 1.x. The module mcp.server.fastmcp does not exist in 2.x, so this import fails | Legacy (SDK 1.x) |
from fastmcp import FastMCP | The standalone fastmcp package (PrefectHQ), a separate project | Not the official SDK; not used here |
If a guide says "FastMCP", check which of the three it means before you copy anything.
Worked example: the notes server (lab-l08)
Download Lab files (ZIP) and open lab-l08/. It pins Python 3.12 and exactly one direct dependency, mcp==2.3.0; uv.lock pins every transitive dependency with hashes. All data is synthetic and in memory.
The server object. These lines are from notes_server.py:
from mcp.server import MCPServer
from mcp.server.mcpserver.exceptions import ToolError
from mcp_types import ToolAnnotations
from pydantic import BaseModel, Field
class Note(BaseModel):
id: str
title: str
body: str
tags: list[str]
mcp = MCPServer(
"demo-notes",
instructions="A DEMO notes store with synthetic data. add_note changes state; get_note is read-only.",
version="1.0.0",
)
A tool with structured output. The return type is the Pydantic model Note, so the SDK publishes an outputSchema built from it and returns structuredContent, plus a JSON text copy for clients that ignore structured output. Input limits come from Field; the SDK turns them into the inputSchema.
@mcp.tool(
name="add_note",
title="Add a note",
annotations=ToolAnnotations(read_only_hint=False, destructive_hint=False, idempotent_hint=False,
open_world_hint=False),
)
def add_note(
title: Annotated[str, Field(min_length=1, max_length=80, description="Short title (1-80 characters)")],
body: Annotated[str, Field(max_length=2000, description="Note text (up to 2000 characters)")] = "",
tags: Annotated[list[str], Field(max_length=5, description="Up to 5 lowercase tags")] = [], # noqa: B006
) -> Note:
"""Create a note in the demo store and return it. The returned object is structured content."""
The docstring becomes the tool description, and each Field(description=...) becomes a parameter description. The model reads both. Annotations are hints: the spec says clients MUST treat them as untrusted unless the server is trusted.
A tool error the model can read. get_note validates its argument in code and raises ToolError:
if not re.fullmatch(NOTE_ID_PATTERN, note_id):
raise ToolError(f"Invalid note id {note_id!r}: expected the format N-001.")
note = _NOTES.get(note_id)
if note is None:
raise ToolError(f"No note with id {note_id}.")
return note
ToolError becomes a normal result with isError: true. That is a tool execution error: the client SHOULD pass it to the model so it can correct its call. A JSON-RPC protocol error is for malformed requests and server faults. Arguments that break the schema (an empty title) also come back as isError: true. Validating input is a security control too: the spec says servers MUST validate all tool inputs.
A resource and a prompt.
@mcp.resource(
"notes://index",
name="notes-index",
title="Notes index",
description="JSON list of note ids and titles currently in the demo store",
mime_type="application/json",
)
def notes_index() -> str:
return json.dumps([{"id": n.id, "title": n.title} for n in _NOTES.values()])
@mcp.prompt(name="summarize_notes", title="Summarize notes on a topic")
def summarize_notes(topic: str) -> str:
The stdio rule. The spec says a stdio server MUST NOT write anything to stdout that is not a valid MCP message; it MAY log to stderr. The lab logs like this, and starts the transport explicitly:
def log(message: str) -> None:
"""Diagnostics go to stderr so they never corrupt the stdio JSON-RPC stream."""
print(f"[notes-server] {message}", file=sys.stderr, flush=True)
if __name__ == "__main__":
log("starting on stdio")
mcp.run("stdio")
One stray print() to stdout breaks the JSON-RPC stream. Also, do not start a stdio server and type into it: it waits for JSON-RPC on stdin, so typing is not a test.
Verifying with a client
verify_client.py uses the official SDK client, which launches the server as a subprocess:
SERVER = StdioServerParameters(command=sys.executable, args=[str(HERE / "notes_server.py")], cwd=str(HERE))
...
async with Client(SERVER) as client:
print(f" negotiated protocol version: {client.protocol_version}")
It checks the modern path, which negotiates protocol 2026-07-28 (current, via server/discover), and then Client(SERVER, mode="legacy"), which uses the initialize handshake and negotiates 2025-11-25 (legacy). You wrote no compatibility code: SDK 2.3.0 served both eras from the same server.
Registering with a host (host-specific)
./run.sh path prints a ready command for Claude Code:
claude mcp add demo-notes -- /abs/path/.venv/bin/python /abs/path/notes_server.py
In Claude Code, -- separates its own options from the server command. Use absolute paths to the lab's .venv Python and to the script, because a host may start the server from another directory and without your virtual environment on PATH. Other hosts have their own configuration formats; check their documentation. The lab did not exercise any host: the scripted client is the verified path.
Practice
- In
lab-l08/, run./run.sh(it runsuv sync --locked, thenverify_client.py). - Open
notes_server.py, change theget_noteerror textexpected the format N-001to something else, and run./run.shagain. Watch which check fails, then restore the text.
Check your result
- The header shows
python 3.12.x | mcp 2.3.0 | transport stdio. - Section
[1]showsnegotiated protocol version: 2026-07-28; section[6]showsnegotiated protocol version: 2025-11-25. - Section
[3]showsadd_note -> is_error=False structured={'id': 'N-003', 'title': 'Demo: lab note', 'body': 'Synthetic.', 'tags': ['lab']}. - Section
[4]showsis_error=Truefor../etc/passwd, forN-999and for an empty title. - The run ends with
ALL CHECKS PASSED (15). - In step 2, the run stops with a traceback that contains
AssertionError: FAIL: malformed id returns isError with a correctable message. That proves the test reads the message, not just the flag.
Lines starting with [notes-server] or Tool 'get_note' failed are the server's stderr logs and are expected. Compare with lab-l08/VERIFY-OUTPUT.txt.
Check your understanding
-
A tutorial starts with
from mcp.server.fastmcp import FastMCPand fails withModuleNotFoundErroronmcp2.3.0. What happened? The tutorial targets SDK 1.x, where the class was calledFastMCP. In 2.x the class isMCPServer, imported frommcp.server, and the old module is gone. Port the import; do not downgrade the SDK to make old code run. -
Why raise
ToolErrorfor an unknown note id instead of letting aKeyErrorescape, or returningNone?ToolErrorproduces a result withisError: trueand a clear message the model can act on ("No note with id N-999."). An escaping exception gives a less useful error, andNonewould not match the declaredoutputSchema, which servers MUST conform to. -
Your server works in the verifier but fails when a host launches it with
python notes_server.py. Name two likely causes. The host runs a differentpythonthat lacks the locked dependencies, and/or it starts in another working directory so the relative script path does not resolve. Register absolute paths to the lab's.venv/bin/pythonand tonotes_server.py.
Sources
- Python SDK README (
MCPServer, install): https://github.com/modelcontextprotocol/python-sdk - Tools (outputSchema, structuredContent, isError, input validation, untrusted annotations): https://modelcontextprotocol.io/specification/2026-07-28/server/tools
- stdio transport (stdout and stderr rules, legacy probe): https://modelcontextprotocol.io/specification/2026-07-28/basic/transports/stdio
- Claude Code MCP docs (
claude mcp add ... -- <command>): https://code.claude.com/docs/en/mcp - Course lab:
lab-l08/README.md,notes_server.py,verify_client.py,VERIFY-OUTPUT.txt(run 2026-11-26,mcp2.3.0)
