---
title: Build an MCP server in Python with the official SDK
type: guide
url: https://agentsfordevs.com/guides/build-mcp-server-python
markdown: https://agentsfordevs.com/guides/build-mcp-server-python.md
publisher: Agents for Devs
author: Agents for Devs desk
reviewed_by: Agents for Devs desk
published: 2026-12-06
updated: 2026-12-06
license: https://agentsfordevs.com/reuse
citation: Agents for Devs. "Build an MCP server in Python with the official SDK." Published Dec 6, 2026. https://agentsfordevs.com/guides/build-mcp-server-python
attribution: Credit Agents for Devs and link to https://agentsfordevs.com/guides/build-mcp-server-python
format: Guide
topics:
  - build
description: "Build an MCP server with the official Python SDK v2: install mcp[cli], register tools on MCPServer, test with mcp dev and pytest, serve over HTTP."
---

# Build an MCP server in Python with the official SDK

Install the mcp package, put @mcp.tool() on a type-hinted function, and serve it over stdio or Streamable HTTP with mcp.run().

## Short answer

To build an MCP server in Python, install the official SDK with `uv add "mcp[cli]"`; the `mcp` package is version 2.3.0 on PyPI as of December 6, 2026. Create `MCPServer("Name")` from `mcp.server`, put `@mcp.tool()` on a type-hinted function with a docstring, and call `mcp.run()` for stdio or `mcp.run(transport="streamable-http")` for HTTP. Open it in MCP Inspector with `uv run mcp dev server.py`.

**Checked against:** the [MCP Python SDK README](https://github.com/modelcontextprotocol/python-sdk), its docs pages [Running your server](https://github.com/modelcontextprotocol/python-sdk/blob/main/docs/run/index.md), [Tools](https://github.com/modelcontextprotocol/python-sdk/blob/main/docs/servers/tools.md), [Testing](https://github.com/modelcontextprotocol/python-sdk/blob/main/docs/get-started/testing.md) and [Connect to a real host](https://github.com/modelcontextprotocol/python-sdk/blob/main/docs/get-started/real-host.md), and the [mcp package on PyPI](https://pypi.org/project/mcp/), December 6, 2026.

**Run by us:** no. Commands are copied from the MCP Python SDK's docs.

## Which package and Python version do I need?

As of December 6, 2026, the official Python SDK is the `mcp` package, version 2.3.0 on PyPI, and its README requires Python 3.11 or later.

| Item | Value |
| --- | --- |
| Package | `mcp` 2.3.0, uploaded to PyPI on October 2, 2026 |
| Python | 3.11+, per the README |
| Server class | `MCPServer`, imported from `mcp.server` |
| CLI extra | `mcp[cli]`, which adds `mcp dev`, `mcp run` and `mcp install` |

The [installation page](https://github.com/modelcontextprotocol/python-sdk/blob/main/docs/get-started/installation.md) calls v2 the current stable line and lists its breaking changes in a migration guide. A package that isn't ready to migrate should keep a `<2` bound, such as `mcp>=1.28,<2`. The server and the client have separate import paths: `from mcp.server import MCPServer` and `from mcp import Client`. There is no `from mcp import MCPServer`.

## How do I install it?

Add the SDK to your project with its `cli` extra.

```bash
uv add "mcp[cli]"      # or: pip install "mcp[cli]"
```

The `cli` extra installs the `mcp` command-line tool, which you want during development and may not need in a deployed server. Install plain `mcp` if you don't need the tool. For a one-off command outside a project, the README gives `uv run --with "mcp[cli]" mcp ...`.

## What does a minimal server look like?

A minimal server is one `MCPServer` instance, one decorated function and a `run()` call.

```python
from mcp.server import MCPServer

mcp = MCPServer("Bookshop")


@mcp.tool()
def search_books(query: str) -> str:
    """Search the catalog by title or author."""
    return f"Found 3 books matching {query!r}."


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

This `server.py` is from the SDK's [Running your server](https://github.com/modelcontextprotocol/python-sdk/blob/main/docs/run/index.md) page. `@mcp.tool()` is the whole registration. The SDK takes the tool name from the function name, the description from the docstring and the input schema from the type hints. `mcp.run()` with no argument serves stdio and blocks for the life of the server. It sits under the `__main__` guard because `mcp dev`, `mcp run`, `mcp install` and your tests import the file.

## How do I describe and constrain arguments?

Wrap a parameter's type in `Annotated` with a Pydantic `Field`, give it a default to make it optional, and use `Literal` for a fixed set of values.

```python
from typing import Annotated, Literal

from pydantic import Field

from mcp.server import MCPServer

mcp = MCPServer("Bookshop")


@mcp.tool()
def search_books(
    query: Annotated[str, Field(description="Title or author to search for.")],
    limit: Annotated[int, Field(ge=1, le=50, description="Maximum number of results.")] = 10,
    genre: Literal["fiction", "non-fiction", "poetry"] | None = None,
) -> str:
    """Search the catalog by title or author."""
    where = f" in {genre}" if genre else ""
    return f"Found 3 books matching {query!r}{where} (showing up to {limit})."
```

Per the [Tools page](https://github.com/modelcontextprotocol/python-sdk/blob/main/docs/servers/tools.md), `Field(description=...)` gives the model a per-argument description. `ge=1, le=50` land in the schema as `minimum` and `maximum`, and the `Literal` becomes an enum. The SDK enforces these before the function runs, so a call with `limit=999` returns this tool error to the model:

```text
Input should be less than or equal to 50
```

A declared return type such as `-> str` also adds a `structured_content` field to the result, next to the text `content` the model reads.

## How do I test it without a host?

Open the server in MCP Inspector with `mcp dev`, or connect the SDK's `Client` to the server object in memory.

```console
uv run mcp dev server.py
```

`mcp dev` needs `npx` on your `PATH`, because the Inspector is a Node.js app. It launches `server.py` over stdio, as a host would. For automated tests, the [Testing page](https://github.com/modelcontextprotocol/python-sdk/blob/main/docs/get-started/testing.md) adds `pytest` and `inline-snapshot` as dev dependencies and tests a `Calculator` server whose `add` tool takes `a` and `b`:

```python
import pytest
from inline_snapshot import snapshot
from mcp import Client
from mcp.types import CallToolResult, TextContent

from server import mcp


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


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


@pytest.mark.anyio
async def test_call_add_tool(client: Client):
    result = await client.call_tool("add", {"a": 1, "b": 2})
    # Drop the server identity stamp in `_meta`; it is not what this test is about.
    result.meta = None
    assert result == snapshot(
        CallToolResult(
            content=[TextContent(type="text", text="3")],
            structured_content={"result": 3},
        )
    )
```

`Client(mcp)` uses no subprocess and no port. `raise_exceptions=True` shows the real message when something fails outside a tool body, which the server otherwise reduces to `"Internal server error"`. A failing tool still returns a normal result with `is_error=True`.

## How do I serve it over Streamable HTTP?

Name the transport in `run()`, and the same file listens on a port.

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

Clients then connect to `http://127.0.0.1:3001/mcp`. Every transport option is a keyword argument to `run()`:

| Argument | Default | Effect |
| --- | --- | --- |
| `host`, `port` | `127.0.0.1`, `8000` | Where the server listens |
| `streamable_http_path` | `/mcp` | Path of the MCP endpoint |
| `json_response` | off | One JSON body per POST instead of an SSE stream |
| `stateless_http` | off | No session tracking for 2025-era clients |
| `max_request_body_size` | 4 MiB | Larger requests get HTTP 413 |

Passing `port=` to `MCPServer(...)` instead fails with `TypeError: MCPServer.__init__() got an unexpected keyword argument 'port'`. The docs say SSE was superseded by [Streamable HTTP](/glossary/streamable-http) in the 2025-03-26 protocol revision, and that nothing new should be built on it. A server behind a real hostname also needs a Host allowlist; [Run a remote MCP server](/guides/deploy-remote-mcp-server) covers that.

## How do I connect it to a host?

Give the host one launch command that uses an absolute path to `server.py`.

```bash
claude mcp add bookshop -- uv run --with "mcp[cli]" mcp run /absolute/path/to/server.py
```

```bash
uv run mcp install server.py
```

The first command registers the server in Claude Code; run `/mcp` in a session to confirm it is connected. The second writes an entry into Claude Desktop's config, the only host `mcp install` configures. Per the [real-host page](https://github.com/modelcontextprotocol/python-sdk/blob/main/docs/get-started/real-host.md), a host launches the server from its own working directory with a minimal `PATH`. A relative path therefore fails, and a bare `uv` may need its absolute path from `which uv`. Cursor and VS Code take the same `command` and `args` in `.cursor/mcp.json` and `.vscode/mcp.json`; see [Cursor MCP config](/guides/cursor-mcp).

## What breaks, and how do I fix it?

The SDK's [troubleshooting page](https://github.com/modelcontextprotocol/python-sdk/blob/main/docs/troubleshooting.md) lists each error string verbatim; these are the ones a new server hits first.

| Error or symptom | Cause | Fix |
| --- | --- | --- |
| `TypeError: The @tool decorator was used incorrectly. Did you forget to call it? Use @tool() instead of @tool` | `@mcp.tool` written without parentheses | Write `@mcp.tool()` |
| `Tool already exists: <name>` in the server log | Two tools share a name; the first one wins | Rename one of them |
| `Error executing tool <name>` with no message | The tool raised an exception it didn't anticipate | Read the traceback in the server's log |
| The host lists zero tools | Import-time crash, a second `MCPServer` object, or stray output on stdout | Run `python server.py` and read the traceback; log with the `logging` module |
| `421 Misdirected Request` and `Invalid Host header` | A deployed server still uses the localhost-only default | Pass `transport_security=TransportSecuritySettings(...)` |

On stdio, stdout is the protocol channel. The SDK diverts flushed stray output to stderr while it serves, but output written before serving starts still reaches the host and can make it drop the connection.

## What to read next

- [Build an MCP server in TypeScript with the official SDK](/guides/build-mcp-server-typescript)
- [Debug an MCP server with MCP Inspector](/guides/debug-mcp-server-inspector)
- [Run a remote MCP server: Streamable HTTP, sessions and auth](/guides/deploy-remote-mcp-server)
- [MCP server](/glossary/mcp-server)

## Sources

1. [MCP Python SDK README, Model Context Protocol](https://github.com/modelcontextprotocol/python-sdk)
2. [Installation, Model Context Protocol](https://github.com/modelcontextprotocol/python-sdk/blob/main/docs/get-started/installation.md)
3. [Running your server, Model Context Protocol](https://github.com/modelcontextprotocol/python-sdk/blob/main/docs/run/index.md)
4. [Tools, Model Context Protocol](https://github.com/modelcontextprotocol/python-sdk/blob/main/docs/servers/tools.md)
5. [Testing, Model Context Protocol](https://github.com/modelcontextprotocol/python-sdk/blob/main/docs/get-started/testing.md)
6. [Connect to a real host, Model Context Protocol](https://github.com/modelcontextprotocol/python-sdk/blob/main/docs/get-started/real-host.md)
7. [Troubleshooting, Model Context Protocol](https://github.com/modelcontextprotocol/python-sdk/blob/main/docs/troubleshooting.md)
8. [mcp, Python Package Index](https://pypi.org/project/mcp/)

## Changelog

- 2026-12-06: First published.

## Cite this page

Agents for Devs. "Build an MCP server in Python with the official SDK." Published Dec 6, 2026. https://agentsfordevs.com/guides/build-mcp-server-python

- Page: https://agentsfordevs.com/guides/build-mcp-server-python
- Markdown: https://agentsfordevs.com/guides/build-mcp-server-python.md
- Reuse: quote or summarize with a link to the page. Terms: https://agentsfordevs.com/reuse
