NewAI Content Creation is now live in Early Access
Turning Point Training Instituteby Training Center
Skip to content
0%
Module 2 — Build your first serverLesson 1 of 4
Video lesson

A Python server with the official SDK (stdio)

IntermediateVideo lesson
7 min readIntermediate
Downloads & resources
Download this lesson's materials, ready to use.

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)

Example prompt

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 MCPServer with 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:

NameWhat it isLabel
from mcp.server import MCPServerThe high-level server class of the official SDK mcp 2.xCurrent (this course)
from mcp.server.fastmcp import FastMCPThe same class's name in SDK 1.x. The module mcp.server.fastmcp does not exist in 2.x, so this import failsLegacy (SDK 1.x)
from fastmcp import FastMCPThe standalone fastmcp package (PrefectHQ), a separate projectNot 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:

python
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.

python
@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:

python
    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.

python
@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:

python
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:

python
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:

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

  1. In lab-l08/, run ./run.sh (it runs uv sync --locked, then verify_client.py).
  2. Open notes_server.py, change the get_note error text expected the format N-001 to something else, and run ./run.sh again. 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] shows negotiated protocol version: 2026-07-28; section [6] shows negotiated protocol version: 2025-11-25.
  • Section [3] shows add_note -> is_error=False structured={'id': 'N-003', 'title': 'Demo: lab note', 'body': 'Synthetic.', 'tags': ['lab']}.
  • Section [4] shows is_error=True for ../etc/passwd, for N-999 and 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

  1. A tutorial starts with from mcp.server.fastmcp import FastMCP and fails with ModuleNotFoundError on mcp 2.3.0. What happened? The tutorial targets SDK 1.x, where the class was called FastMCP. In 2.x the class is MCPServer, imported from mcp.server, and the old module is gone. Port the import; do not downgrade the SDK to make old code run.

  2. Why raise ToolError for an unknown note id instead of letting a KeyError escape, or returning None? ToolError produces a result with isError: true and a clear message the model can act on ("No note with id N-999."). An escaping exception gives a less useful error, and None would not match the declared outputSchema, which servers MUST conform to.

  3. 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 different python that 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/python and to notes_server.py.

Sources