Guide build/
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, its docs pages Running your server, Tools, Testing and Connect to a real host, and the mcp package on PyPI, 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 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.
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.
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 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.
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, 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:
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.
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 adds pytest and inline-snapshot as dev dependencies and tests a Calculator server whose add tool takes a and b:
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.
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 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 covers that.
How do I connect it to a host?
Give the host one launch command that uses an absolute path to server.py.
claude mcp add bookshop -- uv run --with "mcp[cli]" mcp run /absolute/path/to/server.py
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, 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.
What breaks, and how do I fix it?
The SDK’s troubleshooting page 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
Sources
Changelog
- 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 version: https://agentsfordevs.com/guides/build-mcp-server-python.md
- Reuse: quote or summarize with a link to this page. Reuse terms