Skip to content
AISeeker

Search

Search reports, topics, companies…

CH.05Tutorials
3 min read
Signal strength: 4/5Major
Verified · 6 Sources

Build an MCP server in Python with the official SDK v2 and connect it to your agent

A hands-on guide to the rebuilt MCP Python SDK: write a typed tool and resource with MCPServer, test it in the Inspector, and plug it into Claude Code or Codex.

Key figures

2.3.0
mcp package version used
2026-07-28
MCP spec revision in SDK v2

The Model Context Protocol (MCP) has become the common way to give coding agents and chat apps access to your own data and tools. In 2026 the official Python SDK was rebuilt: version 2 implements the 2026-07-28 spec revision while still serving older clients, and the familiar FastMCP class is now MCPServer. This tutorial builds a small server that lets an agent search a folder of Markdown team notes, then connects it to Claude Code and OpenAI Codex. You need Python 3.11+ and uv. Code targets mcp 2.3.0, released on PyPI on 2 October 2026.

1. Create the project

bash
uv init team-notes && cd team-notes
uv add "mcp[cli]"
mkdir notes && printf '# Release process\nTag from main, then run make release.\n' > notes/release.md

The cli extra adds the mcp command used below for testing. If you only need the library, install plain mcp.

2. Write the server

Create server.py in the project root:

python
# server.py  (mcp 2.3.0 / Python SDK v2)
from pathlib import Path

from pydantic import BaseModel
from mcp.server.mcpserver import MCPServer

NOTES_DIR = (Path(__file__).parent / "notes").resolve()
mcp = MCPServer("team-notes")


class NoteHit(BaseModel):
    slug: str
    title: str
    snippet: str


@mcp.tool()
def search_notes(query: str, limit: int = 5) -> list[NoteHit]:
    """Search the team's Markdown notes for a keyword.

    Use this before answering questions about internal processes.
    Returns note slugs that can be read via the notes://{slug} resource.
    """
    q = query.lower().strip()
    hits: list[NoteHit] = []
    for path in sorted(NOTES_DIR.glob("*.md")):
        text = path.read_text(encoding="utf-8")
        i = text.lower().find(q)
        if q and i != -1:
            first = text.splitlines()[0] if text else path.stem
            hits.append(NoteHit(slug=path.stem, title=first.lstrip("# "),
                                snippet=text[max(0, i - 60): i + 60]))
        if len(hits) >= min(limit, 20):
            break
    return hits


@mcp.resource("notes://{slug}")
def read_note(slug: str) -> str:
    """Full Markdown text of one note."""
    path = (NOTES_DIR / f"{slug}.md").resolve()
    if path.parent != NOTES_DIR or not path.is_file():
        raise ValueError(f"Unknown note: {slug}")
    return path.read_text(encoding="utf-8")


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

Three things are doing real work here. The type hints on search_notes become the tool's input schema, so the model knows limit is an integer with a default. Returning Pydantic models gives clients structured content alongside the text rendering, which is easier for an agent to use than a blob of prose. And the docstring is the tool description the model reads when deciding whether to call it, so it says when to use the tool, not just what it does.

3. Test it in the Inspector

bash
uv run mcp dev server.py

This launches the MCP Inspector against your server. List the tools, call search_notes with {"query": "release"}, check that the result contains structured content, then read notes://release. Try a hostile input such as ../pyproject for the resource; it should be rejected.

4. Connect it to an agent

Clients start a stdio server as a subprocess, so give them absolute paths. uv created a virtual environment in .venv:

bash
# Claude Code (add --scope project to share it via .mcp.json)
claude mcp add --transport stdio team-notes -- \
  /abs/path/team-notes/.venv/bin/python /abs/path/team-notes/server.py

# OpenAI Codex
codex mcp add team-notes -- \
  /abs/path/team-notes/.venv/bin/python /abs/path/team-notes/server.py

In Claude Code, /mcp shows whether the server connected. Then ask something like "How do we cut a release?" and watch the agent call search_notes before reading the note.

To serve several users over the network instead, switch the transport. In v2, host and port are arguments to run() rather than the constructor:

python
mcp.run(transport="streamable-http", host="127.0.0.1", port=8000)

Clients then connect to http://127.0.0.1:8000/mcp, for example with claude mcp add --transport http team-notes http://127.0.0.1:8000/mcp. Do not expose this beyond localhost until you have added authentication.

Tips and pitfalls

  • Old tutorials break. from mcp.server.fastmcp import FastMCP raises ModuleNotFoundError in v2. Use MCPServer, and declare a ctx: Context parameter instead of calling the removed get_context().
  • Configuration moved. v2 no longer reads MCP_* environment variables or .env files. Read settings yourself and pass them in.
  • Never print to stdout over stdio. The stdio transport uses stdout for protocol messages; a stray print() corrupts the stream. Log to stderr.
  • Treat inputs as hostile. The model chooses the arguments, and prompt injection can steer it. Resolve paths and check them, cap result sizes (the min(limit, 20) above), and give the server only the permissions it needs.
  • Avoid deprecated features. The 2026-07-28 revision drops the initialization handshake and deprecates roots, sampling and protocol logging. Build on tools, resources, prompts and elicitation.
  • Large payloads. Streamable HTTP request bodies are capped at 4 MiB by default (max_request_body_size raises it).

Next steps

Add a prompt template for a common workflow, write a small pytest suite that calls your tools through the SDK's Client, and only then think about remote deployment with OAuth. A focused server with three well-described tools usually beats a sprawling one with thirty.

Researched and drafted with AI assistance under editorial review. Report errors to support@aiseeker.dev.

Sources

This report synthesises the sources below. Primary sources are marked.

  1. [1]
    MCP Python SDK

    Model Context Protocol (GitHub)2026.11.28Primary

  2. [2]
    mcp 2.3.0

    PyPI2026.10.02Primary

  3. [3]
    Migration Guide: v1 to v2

    MCP Python SDK docs2026.11.28Primary

  4. [4]
    What's new in v2

    MCP Python SDK docs2026.11.28Primary

  5. [5]
    Specification

    Model Context Protocol2026.07.28Primary

  6. [6]
    Connect Claude Code to tools via MCP

    Anthropic (Claude Code Docs)2026.11.28Primary

Back to Tutorials →