FastMCP tutorial: how to build an MCP server in Python and ship it
On this page
FastMCP is a Python framework for building MCP servers and clients: you write ordinary functions, decorate them, and FastMCP generates the tool schemas, validates arguments and speaks the protocol over stdio or Streamable HTTP. It’s maintained by Prefect at PrefectHQ/fastmcp and installs with uv add fastmcp. The official MCP Python SDK has its own, smaller high-level API called MCPServer; FastMCP is built on top of that same SDK and adds auth providers, a test client, a CLI and deployment helpers.
Checked as of November 2026 against the FastMCP docs for release 4.1.6 and the MCP Python SDK README and migration guide for release 2.3.0.
FastMCP vs the official MCP Python SDK
The two share a history, which is why search results mix them up. FastMCP 1.0 was merged into the official SDK in 2024 and shipped there as mcp.server.fastmcp.FastMCP. The standalone project kept going and is now on version 4. In SDK v2, the in-SDK class was renamed: the migration guide says FastMCP became MCPServer, and mcp.server.fastmcp imports now fail with ModuleNotFoundError.
MCP Python SDK (mcp) | FastMCP (fastmcp) | |
|---|---|---|
| Maintainer | MCP project | Prefect |
| High-level server class | MCPServer (formerly FastMCP) | FastMCP |
| Import | from mcp.server import MCPServer | from fastmcp import FastMCP |
| Built on | Itself | MCP Python SDK v2 |
| Extras | Low-level Server, client, mcp dev CLI | Auth providers, middleware, composition and proxying, test client, fastmcp CLI |
If an old tutorial imports from mcp.server.fastmcp import FastMCP, that’s SDK v1. On SDK v2 the equivalent is MCPServer; on standalone FastMCP it’s from fastmcp import FastMCP. The decorators are close enough that moving between them is mostly renaming. Pick the SDK when you want the fewest dependencies and the reference implementation. Pick FastMCP when you want OAuth providers and testing helpers without writing them yourself, which is most remote servers.
Install FastMCP
uv add fastmcp
fastmcp version
pip install fastmcp works too. FastMCP 4.1.6 requires Python 3.10 or newer. fastmcp version prints the FastMCP, MCP SDK and Python versions, which is the first thing to check when an example from the docs doesn’t match your install.
A minimal MCP server in Python
An MCP server exposes three kinds of things: tools the model can call, resources the client can read, and prompts the user can pick. What is an MCP server explains the difference. This server has one of each:
# server.py
from fastmcp import FastMCP
mcp = FastMCP("Release Notes")
RELEASES = {
"2.4.0": "Adds CSV export. Fixes the timezone bug in scheduled reports.",
"2.3.1": "Security fix for session cookies.",
}
@mcp.tool
def get_release_notes(version: str) -> str:
"""Return the release notes for one version, such as 2.4.0."""
if version not in RELEASES:
raise ValueError(f"Unknown version {version}. Known: {', '.join(RELEASES)}")
return RELEASES[version]
@mcp.resource("releases://latest")
def latest_release() -> str:
"""The newest release and its notes."""
version = max(RELEASES)
return f"{version}: {RELEASES[version]}"
@mcp.resource("releases://{version}/notes")
def release_notes(version: str) -> str:
"""Notes for a given version."""
return RELEASES.get(version, "Unknown version")
@mcp.prompt
def changelog_post(version: str) -> str:
"""Draft a short customer-facing changelog post."""
return f"Write a three-sentence changelog post for version {version}, using the release notes resource."
if __name__ == "__main__":
mcp.run()
The type hints become the tool’s JSON Schema, and the docstring becomes its description. Write descriptions for the model, not for a code reviewer: they’re the only thing the model reads when deciding whether to call the tool. A URI with {version} in it becomes a resource template. Raising an exception in a tool returns an error result to the client instead of crashing the server. By default the exception’s message goes back to the model, which helps it correct a bad argument. If your exceptions can carry internal details such as SQL or file paths, construct the server with FastMCP("Release Notes", mask_error_details=True) and raise fastmcp.exceptions.ToolError for the messages you do want the model to see.
Run it over stdio
mcp.run() with no arguments uses stdio, the transport local clients such as Claude Code, Cursor and Claude Desktop use when they launch a server as a subprocess:
python server.py
The FastMCP CLI runs the same server without the __main__ block, and it finds a variable named mcp, server or app on its own:
fastmcp run server.py
fastmcp install writes the client config for you, with dependencies declared so the client’s isolated environment can run it:
fastmcp install claude-code server.py
fastmcp install cursor server.py --with-editable .
With stdio, never print to stdout. The stdio transport spec reserves it for MCP messages, and a stray print() corrupts the stream. Log to stderr instead.
Run it over Streamable HTTP
For a server other people or machines connect to, use HTTP. FastMCP calls Streamable HTTP http:
fastmcp run server.py --transport http --port 8000
or in code, mcp.run(transport="http", host="127.0.0.1", port=8000). The endpoint is http://127.0.0.1:8000/mcp. Point a client at it:
claude mcp add --transport http release-notes http://127.0.0.1:8000/mcp
The legacy SSE transport is still available as transport="sse", but FastMCP’s docs recommend HTTP for all new projects. Remote MCP servers covers how clients reach HTTP servers and what changes once one is public.
Test it with the MCP Inspector
FastMCP wraps the official Inspector with auto-reload:
fastmcp dev inspector server.py
It runs your server through uv run in a subprocess, so declare extra packages with --with. It connects over stdio only. To test the HTTP endpoint, start the server with fastmcp run server.py --transport http and connect the Inspector to the URL:
npx @modelcontextprotocol/inspector --server-url http://127.0.0.1:8000/mcp --transport http
In the Tools tab, call get_release_notes with 2.4.0, then with 9.9.9 to confirm the error comes back as a tool error rather than a crash. MCP Inspector walks through the tabs and a checklist for servers that connect but show no tools.
For automated tests, FastMCP’s client can connect to the server object in memory, with no subprocess or port:
# test_server.py
import pytest
from fastmcp import Client
from server import mcp
@pytest.fixture
async def client():
async with Client(mcp) as c:
yield c
async def test_release_notes(client):
result = await client.call_tool("get_release_notes", {"version": "2.3.1"})
assert "Security fix" in result.content[0].text
FastMCP’s testing docs use pytest-asyncio with asyncio_mode = "auto" under [tool.pytest.ini_options]. fastmcp inspect server.py --format mcp prints exactly what a client would see from tools/list, which is handy in CI.
Add authentication
Auth applies to the HTTP transports; a stdio server runs with the permissions of whoever launched it. FastMCP’s default is auth=None, so an HTTP server you start is open to anyone who can reach it. The authentication docs describe three levels:
- Token verification: your server validates tokens another system issues.
JWTVerifierchecks signature, issuer and audience against a JWKS endpoint. - An external identity provider.
RemoteAuthProviderworks with providers that support Dynamic Client Registration (WorkOS AuthKit is the docs’ example).OAuthProxyand subclasses such asGitHubProviderbridge providers that need a pre-registered app. - A full OAuth server inside your MCP server with
OAuthProvider, which the docs recommend only when nothing else fits.
from fastmcp import FastMCP
from fastmcp.server.auth.providers.jwt import JWTVerifier
auth = JWTVerifier(
jwks_uri="https://auth.example.com/.well-known/jwks.json",
issuer="https://auth.example.com",
audience="release-notes-mcp",
)
mcp = FastMCP("Release Notes", auth=auth)
For local development, StaticTokenVerifier maps fixed tokens to client IDs and scopes. Keep it out of production. Checking the audience matters: the MCP authorization spec forbids servers from accepting tokens that weren’t issued for them, and MCP authentication explains the discovery and audience rules a client expects.
Deploy a FastMCP server
For production, build an ASGI app and serve it with any ASGI server:
# app.py
from server import mcp
app = mcp.http_app(
stateless_http=True,
host_origin_protection=True,
allowed_hosts=["mcp.example.com"],
)
uvicorn app:app --host 0.0.0.0 --port 8000 --workers 4
Three settings deserve attention:
stateless_http=Trueis required for multiple workers or replicas behind a load balancer. By default the HTTP transport keeps sessions in memory per instance, and FastMCP’s docs warn that sticky sessions don’t work reliably because clients such as Cursor and Claude Code don’t forward cookies.host_origin_protectionvalidatesHostandOriginheaders to block DNS rebinding. It defaults to off for compatibility, so turn it on or enforce the same checks at your proxy.- A health check route:
@mcp.custom_route("/health", methods=["GET"])adds one next to/mcpfor your load balancer.
Put TLS in front, at your platform or reverse proxy, and the server runs anywhere a Python web app runs: a container, a VM or a platform service. FastMCP’s own docs also point to Prefect Horizon as a managed host.
Once the server is live on a public HTTPS URL, any remote-capable client can connect, and so can an MCP gateway. Toolstile can add it as a connection with your OAuth or bearer token stored in the gateway, then set Allow, Require approval or Block per tool for each agent. It only reaches public HTTPS servers on port 443, so a server bound to localhost or a private network stays a direct client entry.