Skip to main content

Build an MCP Server in Python from Scratch

The shortest path to a working MCP server: Python 3.11, the official SDK, Pydantic validation, tools, prompts, resources, and a real test in under twenty minutes.

Mustafa Tawab

Mustafa Tawab

•16 min read
#MCP#Python#AI#Tutorial#Beginner
Build an MCP Server in Python from Scratch

Python is the shortest path from an idea to a working MCP server.

There is no build step, no bundler, no HTTP framework to wire up. You write a function, add one decorator, and a client can call it. The official SDK reads your function name, docstring, and type hints and turns them into the tool description and schema automatically.

This article builds a complete, read-only notes server. It assumes you know basic Python: functions, type hints, and dictionaries. It assumes nothing about MCP.

Which version is this? This uses the v2 Python SDK, where the server class is MCPServer and the import is from mcp.server import MCPServer. Older tutorials use FastMCP from mcp.server.fastmcp. If you copy code from an older article and the import fails, that is why.


What We're Building#

Type Name What it does
Tool notes_list List notes with pagination
Tool notes_search Search notes by keyword
Tool notes_get Read one note by id
Prompt weekly_digest Summarize recent notes into a digest
Resource note://{note_id} Read one note as plain text

Everything is read-only. The server needs no database, no API key, and no network access. It runs from a single file.

code
Claude / Cursor / Inspector
        │  JSON-RPC
        ▼
     MCPServer
        ├── notes_list
        ├── notes_search
        ├── notes_get
        ├── weekly_digest
        └── note://{note_id}

Prerequisites#

  • Python 3.11 or newer
  • uv installed (recommended), or plain pip
  • npx available, only if you want the Inspector

Check your Python version:

bash
python3 --version

If it prints 3.11 or higher, you are ready.


Step 1 — Create the Project#

bash
uv init notes-mcp
cd notes-mcp
uv add "mcp[cli]"

That is the entire install. The [cli] extra adds the mcp command, which gives you mcp dev, mcp run, and mcp install.

If you prefer pip:

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

Create one file called server.py. Everything below goes in it.


Step 2 — Add Some Data#

Start with the data the server will expose. In a real project this would come from a database or a filesystem. The MCP layer does not care where it lives, only what shape you return.

python
from pydantic import BaseModel


class Note(BaseModel):
    id: str
    title: str
    body: str
    tags: list[str]
    updated: str


NOTES: dict[str, Note] = {
    "docker-compose": Note(
        id="docker-compose",
        title="Docker Compose basics",
        body="Compose defines services, networks, and volumes in one YAML file. Use it when you have more than one container.",
        tags=["docker", "devops"],
        updated="2026-11-02",
    ),
    "linux-permissions": Note(
        id="linux-permissions",
        title="Linux file permissions",
        body="chmod changes permissions, chown changes ownership. 755 means the owner can write, everyone else can read and execute.",
        tags=["linux", "devops"],
        updated="2026-10-18",
    ),
    "mcp-intro": Note(
        id="mcp-intro",
        title="MCP in one sentence",
        body="MCP is a standard menu that lets an AI order from your software without entering the kitchen.",
        tags=["mcp", "ai"],
        updated="2026-11-20",
    ),
}

Why a Pydantic model instead of a plain dict?

  • It validates the data once, at construction.
  • It gives you editor autocomplete (note.title, not note["title"]).
  • Returning one from a tool produces structured output automatically, which clients can render as JSON.

A dictionary keyed by id makes notes_get a one-line lookup.


Step 3 — Create the Server and Your First Tool#

Append this to server.py:

python
from typing import Annotated

from pydantic import Field

from mcp.server import MCPServer

mcp = MCPServer("Notes")


@mcp.tool()
def notes_search(
    query: Annotated[
        str,
        Field(
            min_length=1,
            max_length=200,
            description="Keywords to match, e.g. 'docker compose'.",
        ),
    ],
) -> str:
    """Search notes by keyword. Use this when the user asks what they wrote about a topic."""
    tokens = [token for token in query.lower().split() if len(token) > 1]

    matches = [
        note
        for note in NOTES.values()
        if any(
            token
            in f"{note.title} {note.body} {' '.join(note.tags)}".lower()
            for token in tokens
        )
    ]

    if not matches:
        return "No notes matched that query. Try fewer or different keywords."

    blocks = [f"# Notes\n\nFound {len(matches)}."]
    for note in matches:
        blocks.append(
            f"## {note.title}\n\n{note.body}\n\nID: `{note.id}`"
        )

    return "\n\n".join(blocks)

That is a working MCP tool. Read it again and notice what is not there:

  • No JSON Schema. The type hint query: str becomes the schema.
  • No request parsing. The SDK speaks the protocol.
  • No validation code. min_length=1 is enforced before your function runs.
  • No server loop. The transport handles connections.

Three things are derived from the function:

What Where it comes from
Tool name The function name: notes_search
Tool description The docstring
Input schema The type hints and Field(...)

The docstring is the most important line in the whole file. It is the only thing the model reads when deciding whether to call your tool. Write it for the model, not for you.


Step 4 — Type Hints Are the Contract#

This is the part that surprises people coming from other languages: in Python, the type hints are not documentation. They are the protocol.

python
@mcp.tool()
def notes_list(
    limit: Annotated[
        int,
        Field(ge=1, le=50, description="Maximum number of notes to return."),
    ] = 10,
    offset: Annotated[
        int,
        Field(ge=0, description="Number of notes to skip, for pagination."),
    ] = 0,
) -> "NotePage":
    """Browse notes, newest first. Use this when the user asks what they have written recently."""
    ...

Three separate mechanisms are at work:

Code Effect
limit: int The argument must be an integer
= 10 The argument is optional, with a default
Field(ge=1, le=50) The schema gets minimum: 1, maximum: 50
Field(description=...) The model gets a description for that field

If the model sends {"limit": 999}, the SDK rejects it before your function runs and returns a tool error the model can read:

code
Input should be less than or equal to 50

You wrote le=50 once and got a self-correcting agent for free.

You can also use Literal for a fixed set of choices:

python
from typing import Literal

@mcp.tool()
def notes_by_tag(
    tag: Literal["docker", "linux", "mcp", "ai"],
) -> str:
    """List notes that carry one specific tag."""
    ...

The model can only pick one of those four strings. Anything else is rejected.

Define the page model#

Add this above notes_list:

python
class NotePage(BaseModel):
    total: int
    count: int
    offset: int
    has_more: bool
    next_offset: int | None = None
    notes: list[Note]

Then the full tool:

python
@mcp.tool(
    title="List notes",
    annotations=ToolAnnotations(read_only_hint=True, open_world_hint=False),
)
def notes_list(
    limit: Annotated[
        int,
        Field(ge=1, le=50, description="Maximum number of notes to return."),
    ] = 10,
    offset: Annotated[
        int,
        Field(ge=0, description="Number of notes to skip, for pagination."),
    ] = 0,
) -> NotePage:
    """Browse notes, newest first. Use this when the user asks what they have written recently."""
    ordered = sorted(NOTES.values(), key=lambda note: note.updated, reverse=True)
    page = ordered[offset : offset + limit]
    next_offset = offset + len(page)
    has_more = next_offset < len(ordered)

    return NotePage(
        total=len(ordered),
        count=len(page),
        offset=offset,
        has_more=has_more,
        next_offset=next_offset if has_more else None,
        notes=page,
    )

Import ToolAnnotations at the top:

python
from mcp.types import ToolAnnotations

read_only_hint=True tells the client this tool cannot change anything. open_world_hint=False says it works on a closed set of data, not the open web. Clients use these hints to decide when to ask the user for confirmation.

They are hints, not security. Never rely on a client honoring them.


Step 5 — Return Text or Structured Data#

A tool can return two kinds of things, and the SDK picks the right wire format from your return annotation.

Return a str for text the model reads#

python
@mcp.tool()
def notes_search(query: str) -> str:
    """Search notes by keyword."""
    ...
    return "## Docker Compose basics\n\nCompose defines services..."

result.content contains that exact string. This is what the model reads and quotes.

Return a Pydantic model for structured data#

python
@mcp.tool()
def notes_list(limit: int = 10, offset: int = 0) -> NotePage:
    """Browse notes, newest first."""
    ...

Now:

python
result.content             # [TextContent(text='{"total": 3, ...}')]
result.structured_content  # {"total": 3, "count": 3, ...}

The model reads JSON, and the client application gets a typed object it can render as a table or a card.

Use a str when the answer is prose or Markdown. Use a model when the answer is data. When in doubt, return the model and let the client format it.

Finish the get tool#

python
@mcp.tool(
    title="Get note",
    annotations=ToolAnnotations(read_only_hint=True, open_world_hint=False),
)
def notes_get(
    note_id: Annotated[
        str,
        Field(description="Note id from notes_search, e.g. 'docker-compose'."),
    ],
) -> Note:
    """Read one note by id. Call notes_search first if you do not know the id."""
    note = NOTES.get(note_id)

    if note is None:
        raise ToolError(
            f"No note found for {note_id!r}. Call notes_search to see valid ids."
        )

    return note

That raise is the subject of the next section, and it matters more than it looks.


Step 6 — Errors That Teach the Model#

A tool can fail in three ways. The SDK treats each one differently.

You raise The model sees Use it when
ToolError is_error=True plus your message The model can fix it
MCPError A JSON-RPC error, no result The request itself is invalid
Anything else Error executing tool notes_get A real bug or crash

ToolError — the model can recover#

python
from mcp.server.mcpserver.exceptions import ToolError

raise ToolError(f"No note found for {note_id!r}. Call notes_search to see valid ids.")

The request still succeeds. The result has is_error=True and your message in content. The model reads it, realizes it guessed the id wrong, and tries again.

That is why the message names the next step. Compare:

code
❌ "Not found"
✅ "No note found for 'abc'. Call notes_search to see valid ids."

The first makes the model guess. The second lets it recover in one turn.

MCPError — the model cannot recover#

python
from mcp import MCPError
from mcp.types import INVALID_PARAMS

raise MCPError(code=INVALID_PARAMS, message="This server is read-only.")

The whole tools/call request fails with a JSON-RPC error. There is no result and nothing for the model to read. The host application handles it.

Use this when retrying with different arguments would not help: a missing capability, a server that is not ready, a required setup step the caller skipped.

One question decides between the two: could a smarter model have avoided this? If yes, ToolError. If no, MCPError.

Never return an error string#

python
# ❌ Wrong: looks like a successful answer
return f"No note found for {note_id!r}"

A returned string has is_error=False. To the model and to every client UI, it looks like the tool worked and that sentence was the data. Raise. The flag is the signal.


Step 7 — Add a Prompt#

Tools are buttons the model presses. Prompts are recipes the user picks from a menu, fills in, and sends.

python
@mcp.prompt(title="Weekly digest")
def weekly_digest(
    focus: Annotated[
        str,
        Field(description="Optional focus, e.g. 'devops'."),
    ] = "",
) -> str:
    """Summarize recent notes into a short digest with next actions."""
    focus_line = f" Focus on {focus}." if focus else ""

    return (
        "Write a short weekly digest of my notes."
        f"{focus_line} "
        "Call notes_list first. "
        "Then call notes_get for the three most relevant notes. "
        "Use only facts from the notes. Do not invent anything. "
        "Return five bullet points and one suggested next action."
    )

A prompt returns instructions, not facts. It tells the model which tools to call and how to format the answer. The data stays in the tools, so there is still only one source of truth.

When the user picks weekly_digest, the string you return becomes a normal user message. The model then calls the tools you named.

If you want to seed a longer conversation, return a list of messages instead:

python
from mcp.server.mcpserver.prompts.base import AssistantMessage, Message, UserMessage

@mcp.prompt()
def debug_notes() -> list[Message]:
    """Start a conversation about a problem with the notes server."""
    return [
        UserMessage("My notes server is returning empty results."),
        AssistantMessage("Let's debug it. What does notes_list return right now?"),
    ]

Pre-filling an assistant turn is a neat trick: it steers the model's next reply without making the user type the steering.


Step 8 — Add a Resource (Optional)#

Resources are the third primitive. A tool is something the model decides to call. A resource is something the application decides to load and put in front of the model.

If you only want tools and prompts, skip this section. The server works without it.

python
from mcp.server.mcpserver.exceptions import ResourceNotFoundError


@mcp.resource("note://{note_id}")
def note_resource(note_id: str) -> str:
    """Read one note as plain text."""
    note = NOTES.get(note_id)

    if note is None:
        raise ResourceNotFoundError(f"No note with id {note_id!r}.")

    return f"# {note.title}\n\n{note.body}\n\nTags: {', '.join(note.tags)}"

Three things to notice:

  1. The URI is the address. Clients ask for note://docker-compose, never for note_resource.
  2. The {note_id} placeholder must match the function parameter name exactly. Rename one and the server refuses to start, which is a good trade.
  3. Because the URI has a placeholder, this is a resource template. It appears under "Resource Templates" in the Inspector, not in the plain resource list.

Resource reads either return content or fail. There is no is_error half-result, so ResourceNotFoundError becomes a protocol error with the requested URI attached.


Step 9 — Run It#

Add the entry point at the bottom of server.py:

python
if __name__ == "__main__":
    mcp.run()

With no argument, mcp.run() serves stdio: the client launches your file as a child process and talks over standard input and output. That is what desktop clients want.

Keep it under if __name__ == "__main__":. Everything that loads your server imports the file first, and the guard stops an import from turning into a running server.

Open the Inspector#

bash
uv run mcp dev server.py

Open the URL it prints. You get a tab for each primitive:

  • Tools: call notes_search with {"query": "docker"} and watch the form the Inspector built from your type hints.
  • Prompts: pick weekly_digest, fill in focus, and read the rendered message.
  • Resources: open note://docker-compose.

The Inspector runs over stdio, so there is no port and nothing to configure.

Serve over HTTP#

To put the same server on a port, name the transport in run():

python
if __name__ == "__main__":
    mcp.run(transport="streamable-http", port=3001)

Then the endpoint is:

code
http://127.0.0.1:3001/mcp

Two rules that trip people up:

  • Transport options go on run(), never on MCPServer(...). MCPServer("Notes", port=3001) raises TypeError.
  • run() forwards only --transport when you use mcp run. If you need a custom port, run the file directly: uv run server.py.

Other options on run():

Option Default Meaning
host 127.0.0.1 Interface to bind
port 8000 Port to listen on
streamable_http_path /mcp Endpoint path
stateless_http False Fresh transport per request, no sessions
json_response False Return one JSON body instead of an SSE stream

For a deployed, horizontally scaled server, stateless_http=True is usually what you want.

Test the handshake with curl#

bash
curl -sN -X POST http://127.0.0.1:3001/mcp \
  -H 'content-type: application/json' \
  -H 'accept: application/json, text/event-stream' \
  -d '{
    "jsonrpc": "2.0",
    "id": 1,
    "method": "initialize",
    "params": {
      "protocolVersion": "2025-11-25",
      "capabilities": {},
      "clientInfo": { "name": "curl", "version": "0" }
    }
  }'

Then list the tools, this time with the negotiated version header:

bash
curl -s -X POST http://127.0.0.1:3001/mcp \
  -H 'content-type: application/json' \
  -H 'accept: application/json, text/event-stream' \
  -H 'mcp-protocol-version: 2025-11-25' \
  -d '{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}'

initialize must not send MCP-Protocol-Version. Every request after it must. Mix that up and you get a 400 saying the headers and body disagree.


Step 10 — Connect a Real Client#

Claude Desktop, in one command#

bash
uv run mcp install server.py --name "Notes"

That writes an entry into Claude Desktop's config. Restart Claude Desktop and the tools appear.

If your server needs environment variables, pass them explicitly, because Claude Desktop starts your server in its own process without your shell environment:

bash
uv run mcp install server.py --name "Notes" -v API_KEY=abc123
uv run mcp install server.py --name "Notes" -f .env

Cursor, VS Code, Claude Code#

Each host has its own config file, but they all take the same launch command:

json
{
    "mcpServers": {
        "notes": {
            "command": "uv",
            "args": [
                "run",
                "--directory",
                "/absolute/path/to/notes-mcp",
                "server.py"
            ]
        }
    }
}

Use an absolute path. Relative paths resolve from wherever the host happens to start the process, which is rarely where you think.

A remote HTTP client#

Point it at http://127.0.0.1:3001/mcp with the Streamable HTTP transport. If you deploy it, use HTTPS and a real hostname; never expose plain HTTP to the internet.


Step 11 — Write a Test#

You do not need a running server or a port to test an MCP server. The SDK ships an in-memory client that connects straight to the server object.

bash
uv add --dev pytest

Create test_server.py:

python
import pytest

from mcp import Client

from server import mcp


@pytest.fixture
def anyio_backend():
    return "asyncio"


@pytest.fixture
async def client():
    async with Client(mcp, raise_exceptions=True) as connection:
        yield connection


@pytest.mark.anyio
async def test_tools_are_listed(client: Client):
    result = await client.list_tools()
    names = {tool.name for tool in result.tools}
    assert {"notes_list", "notes_search", "notes_get"} <= names


@pytest.mark.anyio
async def test_search_finds_docker(client: Client):
    result = await client.call_tool("notes_search", {"query": "docker"})
    assert result.is_error is False
    assert "Docker Compose" in result.content[0].text


@pytest.mark.anyio
async def test_missing_note_is_a_tool_error(client: Client):
    result = await client.call_tool("notes_get", {"note_id": "does-not-exist"})
    assert result.is_error is True
    assert "notes_search" in result.content[0].text

Run it:

bash
uv run pytest

raise_exceptions=True is for tests only. It makes a genuine crash show you the real exception instead of the sanitized Internal server error a remote caller would see. It does not change ToolError behavior: that still comes back as a normal is_error=True result, because that is what a tool error is.


Step 12 — Production Notes#

Keep the server stateless#

Do not store conversation state in module variables. If you need state, put it in a database keyed by a user id. Stateless servers restart, scale, and deploy without surprises.

Bind correctly behind a proxy#

127.0.0.1 is right for local development. In a container you usually need 0.0.0.0:

python
mcp.run(transport="streamable-http", host="0.0.0.0", port=3001, stateless_http=True)

Put HTTPS in front with Caddy, Nginx, or your platform's load balancer.

Add authentication for private data#

This server is read-only and public, so it needs no auth. If your tools touch private data, add OAuth 2.1 or bearer-token verification in front of the HTTP endpoint. A public endpoint with no auth is only acceptable for data that is already public.

Log to stderr#

Under stdio, stdout is the wire. The SDK redirects most stray output to stderr, but a print that flushes before serving begins can still corrupt the stream. Use the logging module and stop using print for diagnostics.

Dockerfile#

dockerfile
FROM python:3.12-slim

WORKDIR /app

COPY --from=ghcr.io/astral-sh/uv:latest /uv /uvx /bin/

COPY pyproject.toml uv.lock ./
RUN uv sync --frozen --no-dev

COPY server.py ./

ENV PORT=3001
EXPOSE 3001

CMD ["uv", "run", "--no-sync", "server.py"]

Build and run:

bash
docker build -t notes-mcp .
docker run --rm -p 3001:3001 notes-mcp

Common Mistakes#

Symptom Cause Fix
ImportError: cannot import name 'FastMCP' Old tutorial, new SDK Use from mcp.server import MCPServer
TypeError: unexpected keyword argument 'port' Passed options to the constructor Move them to mcp.run(...)
Tool missing from the list Decorator applied after run() Define every tool before mcp.run()
ValueError: Mismatch between URI parameters Resource placeholder and parameter names differ Make them identical
Client gets Internal server error Unhandled exception in a tool Catch it and raise ToolError(...)
Model ignores the tool Vague docstring Say when to use it and what to do next
Server hangs in Docker Bound to 127.0.0.1 Bind to 0.0.0.0
mcp dev fails npx missing Install Node.js, or use mcp run

Recap#

You built a complete MCP server in one Python file:

  • three tools with validated inputs and a mix of text and structured output
  • a prompt that encodes a workflow
  • a resource template for direct reads
  • recoverable errors that teach the model
  • a test suite that needs no port
  • stdio and Streamable HTTP from the same code

The Python version is shorter than the Next.js and Node.js versions for one reason: the SDK derives almost everything from the function itself. No schema file, no router, no adapter.

If you want the concepts behind all of this first, read What Is MCP?.

Tags:#MCP#Python#AI#Tutorial#Beginner
Mustafa Tawab

Author

Mustafa Tawab

Software Engineer & Product Builder focused on scalable SaaS architectures, AI agents, and resilient cloud systems.

Chat on WhatsApp