AI Coding

How to Build an MCP Server in Python, Step by Step (SDK v2)

Most tutorials that show you how to build an MCP server in Python now fail on the very first import. The official SDK moved to version 2, renamed FastMCP to MCPServer, and changed field names on the client side. We found that out the direct way: we installed the SDK in a fresh virtual environment on a Windows 10 PC, built a small notes server, and ran it. Old-style code threw a ModuleNotFoundError before anything else happened.

Below is the version that actually ran, with the real output, plus the errors we hit and how to fix them.

Quick answer: To build an MCP server in Python, install the official SDK with pip install "mcp[cli]" (or uv add "mcp[cli]"), create an MCPServer, turn plain functions into tools with @mcp.tool(), and start it with mcp.run(transport="stdio"). Then point an MCP client such as Claude Desktop or Claude Code at the script.

  • SDK 2.x uses from mcp.server import MCPServer. The old mcp.server.fastmcp import fails.
  • Type hints become the tool’s input schema automatically. The docstring’s first line becomes its description.
  • Never print() in a stdio server. Log to stderr with the logging module.
  • Our test server (2 tools, 1 resource, 1 prompt) worked over stdio and Streamable HTTP with mcp 2.3.0 on Python 3.12.4.

What you’ll build

An MCP server is a small program that gives an AI app new abilities through the Model Context Protocol: tools it can call, resources it can read, and prompt templates. If that’s new, start with our plain-English explainer on what an MCP server is, then come back.

Our example is a notes server. It lets an AI client search a folder of text notes and add new ones. It’s deliberately boring. The pattern is the same one you’d use to wrap an internal API, a database query or a build script, and it’s small enough to read in one go.

  • Tool search_notes(query): finds lines that contain a word.
  • Tool add_note(title, body): saves a note, and refuses to overwrite.
  • Resource notes://{title}: returns one full note.
  • Prompt weekly_review: a ready-made request to list open TODOs.
Five steps to build an MCP server in Python and connect it to Claude

Prerequisites

You need Python and a terminal. The official Build an MCP server guide asks for Python 3.10 or higher and SDK 2.0.0 or higher, while the python-sdk README on GitHub says 3.11+. When two official pages disagree, take the stricter one. We used Python 3.12.4.

The docs use uv, a fast Python package manager. Plain pip works too, and that’s what we used. Either way, put the server in its own virtual environment so its packages don’t clash with other projects. If you’re shaky on that part, our guide to Python virtual environments covers it.

Step 1: Install the MCP Python SDK

# Windows (PowerShell)
python -m venv .venv
.venv\Scripts\activate
pip install "mcp[cli]"

# macOS / Linux
python3 -m venv .venv
source .venv/bin/activate
pip install "mcp[cli]"

# or, with uv
uv add "mcp[cli]"

On 16 November 2026 this installed mcp 2.3.0. The [cli] extra adds the mcp command, which on our install listed four subcommands: version, dev (runs the server with the MCP Inspector), run and install (adds a server to the Claude desktop app). Check your version with pip show mcp. If it starts with 1, the code below won’t match, and you should either upgrade or follow v1 docs.

Step 2: Build the MCP server in Python

Create notes_server.py. This is the exact file we ran:

import logging
from pathlib import Path

from mcp.server import MCPServer

logger = logging.getLogger(__name__)  # logs go to stderr, never stdout
NOTES_DIR = Path(__file__).parent / "notes"
NOTES_DIR.mkdir(exist_ok=True)

mcp = MCPServer("notes")


def _safe_path(title: str) -> Path:
    name = "".join(c for c in title.lower() if c.isalnum() or c in "-_ ").strip().replace(" ", "-")
    if not name:
        raise ValueError("Title must contain letters or numbers.")
    return NOTES_DIR / f"{name}.txt"


@mcp.tool()
def search_notes(query: str) -> str:
    """Search all notes for a word or phrase (case-insensitive).

    Args:
        query: Text to look for
    """
    hits = []
    for f in sorted(NOTES_DIR.glob("*.txt")):
        for n, line in enumerate(f.read_text(encoding="utf-8").splitlines(), 1):
            if query.lower() in line.lower():
                hits.append(f"{f.stem}:{n}: {line.strip()}")
    logger.info("search %r -> %d hits", query, len(hits))
    return "\n".join(hits) if hits else "No matches."


@mcp.tool()
def add_note(title: str, body: str) -> str:
    """Save a new note. Refuses to overwrite an existing note.

    Args:
        title: Short title, used as the file name
        body: Note text
    """
    path = _safe_path(title)
    if path.exists():
        return f"A note called '{path.stem}' already exists."
    path.write_text(body, encoding="utf-8")
    return f"Saved note '{path.stem}' ({len(body)} characters)."


@mcp.resource("notes://{title}")
def read_note(title: str) -> str:
    """Return the full text of one note."""
    return _safe_path(title).read_text(encoding="utf-8")


@mcp.prompt()
def weekly_review() -> str:
    """Ask the model to review this week's notes."""
    return "Search my notes for 'TODO', group the results by note, and list what is still open."


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

How the decorators work

@mcp.tool() registers a function the model can call. The SDK reads the type hints to build a JSON schema for the inputs, so title: str, body: str becomes two required string fields. @mcp.resource("notes://{title}") registers read-only data, and the {title} part of the URI is passed to your function. @mcp.prompt() registers a reusable prompt that the user (not the model) picks from the client’s menu.

The _safe_path helper matters more than it looks. The model decides what goes into title, so treat it like any untrusted input. Stripping everything except letters, numbers, dashes and spaces keeps a title like ../../secrets from escaping the notes folder.

Minimal code to build an MCP server in Python with MCPServer, a tool, a resource and stdio transport

Step 3: Test it before connecting an AI app

The SDK ships a client too, so you can test without Claude or any other app. This script launches the server as a subprocess over stdio, lists what it exposes and calls each piece:

import asyncio, sys
from mcp import Client, StdioServerParameters

async def main():
    params = StdioServerParameters(command=sys.executable, args=["notes_server.py"])
    async with Client(params) as client:
        tools = await client.list_tools()
        print([t.name for t in tools.tools])
        r = await client.call_tool("add_note", {"title": "Bug list", "body": "TODO fix login timeout"})
        print(r.is_error, r.content[0].text)
        r = await client.call_tool("search_notes", {"query": "todo"})
        print(r.content[0].text)
        r = await client.read_resource("notes://release-plan")
        print(r.contents[0].text)

asyncio.run(main())

Here’s what our full test script printed, trimmed for width (we’d put one sample note, release-plan.txt, in the folder first):

tool: search_notes | input schema: {'properties': {'query': {'title': 'Query', 'type': 'string'}}, 'required': ['query'], ...}
tool: add_note | input schema: {'properties': {'title': {...}, 'body': {...}}, 'required': ['title', 'body'], ...}
prompts: ['weekly_review']
resource templates: ['notes://{title}']
call add_note -> isError=False: "Saved note 'bug-list' (22 characters)."
call add_note (same title) -> isError=False: "A note called 'bug-list' already exists."
call search_notes('todo') -> 'bug-list:1: TODO fix login timeout\nrelease-plan:2: TODO update changelog'
read notes://release-plan -> 'Ship v1.2 on Friday\nTODO update changelog\n'
call add_note without body -> isError=True | 1 validation error ... body Field required

Two details worth noticing. The schema came straight from the type hints, with no extra code. And the missing-argument call didn’t crash anything: the SDK rejected it and sent back an error result the model can read and retry. Connecting took between 3.5 and 6.5 seconds across our runs, mostly Python starting up and importing packages, so don’t panic if the first call feels slow.

If you’d rather click than script, mcp dev notes_server.py opens the MCP Inspector, a browser UI for calling tools by hand. The SDK’s CLI launches it through npx, so it needs Node.js installed. We didn’t run it for this post.

Step 4: Connect it to Claude Desktop or Claude Code

For Claude Desktop, the official guide says to edit claude_desktop_config.json (on Windows it lives at %AppData%\Claude\) and add your server under mcpServers, then restart the app. The official example launches the server through uv. If you used pip like we did, a version pointing straight at the virtual environment’s Python looks like this (absolute paths, double backslashes on Windows):

{
  "mcpServers": {
    "notes": {
      "command": "C:\\path\\to\\project\\.venv\\Scripts\\python.exe",
      "args": ["C:\\path\\to\\project\\notes_server.py"]
    }
  }
}

For Claude Code, the Claude Code MCP docs use claude mcp add, with -- separating Claude’s options from the command that starts your server. Add --scope project to share it with your team through a .mcp.json file, then check it with claude mcp list or /mcp inside a session.

claude mcp add --transport stdio notes -- C:\path\to\project\.venv\Scripts\python.exe C:\path\to\project\notes_server.py

To be clear about what we tested: we ran the server with the SDK’s own client over stdio and over HTTP. We didn’t connect it to Claude Desktop or Claude Code for this post, so the two snippets above are based on the official docs, not our own run. New to Claude Code? Our Claude Code tutorial for beginners walks through the basics first.

Optional: run it over Streamable HTTP

Stdio is right when the AI app runs on the same machine and starts your server itself. If the server should run somewhere else, or several clients need it, use Streamable HTTP. Change the last line:

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

# client side
async with Client("http://127.0.0.1:8765/mcp") as client:
    r = await client.call_tool("search_notes", {"query": "changelog"})

Our run returned 'release-plan:2: TODO update changelog' over HTTP, the same answer as stdio. Before you expose this beyond localhost, add authentication. A notes server that anyone on the network can write to is a bad idea.

Common errors and fixes

ModuleNotFoundError: No module named ‘mcp.server.fastmcp’

You’re running v1 tutorial code on SDK 2.x. On our install the error message itself told us the fix: FastMCP was renamed to MCPServer, see the v2 migration guide, or pin mcp<2 to keep v1 code running. Pinning is fine for an existing project. For a new one, use v2.

‘Tool’ object has no attribute ‘inputSchema’

Same cause, client side. Our first test script used v1-style camelCase names and failed. In 2.3.0 the fields are snake_case: input_schema, is_error, uri_template, resource_templates.

Failed to parse JSONRPC message from server

Something wrote to stdout. In a stdio server, stdout is the channel that carries protocol messages, and the official guide says never to write to it. We tested this by swapping one logger.info line for print(). The SDK client logged “Failed to parse JSONRPC message from server”, showing our print text as invalid JSON, then carried on.

The client can’t start the server

Usually a path problem. Client apps don’t start in your project folder, so use absolute paths for both Python and the script, and point at the virtual environment’s Python so the mcp package is found.

The part most tutorials skip: the print() test didn’t crash. Every tool call still returned the right answer, and the only sign of trouble was an error in the client’s log. That sounds harmless. It isn’t. A quiet fault like that is easy to ship, and the docs are blunt that stdout writes can break a stdio server, so a different client or a bigger print may not be as forgiving. Make it a rule: logging only, and grep for print( before you share a server.

Should you build your own MCP server?

Build one when you have something only you can expose: an internal API, a company database, a script your team runs every day. Skip it when a maintained server already exists for the service. Wrapping GitHub or a popular database yourself means owning the security and updates forever.

Keep tools small and specific. “search_notes” with one argument is easier for a model to use correctly than a do-everything tool with ten optional flags. Return plain, short text. Validate every input, because the model writes the arguments, and refuse destructive actions unless they’re clearly intended, the way add_note refuses to overwrite.

Next: if you’re choosing which AI coding agent to plug your server into, read our Claude Code vs Codex vs GitHub Copilot comparison.

FAQ

What Python version do I need for an MCP server?

The modelcontextprotocol.io guide says 3.10 or higher, and the SDK’s GitHub README says 3.11+. Use 3.11 or newer to satisfy both. We tested on 3.12.4.

Is FastMCP the same as MCPServer?

In the official SDK, yes in spirit: v2 renamed the FastMCP class to MCPServer and changed other APIs. There’s also a separate project called FastMCP with its own docs, so check which package a tutorial uses.

Can I use pip instead of uv?

Yes. The SDK README lists both uv add "mcp[cli]" and pip install "mcp[cli]". We used pip in a fresh virtual environment.

What’s the difference between a tool and a resource?

A tool is an action the model decides to call, like searching or saving. A resource is data the client can read, like one note’s text. Prompts are templates the user picks.

Leave a Comment