Testing FastMCP Servers with Pytest
Write quick, reliable tests with an in-memory client, pytest fixtures, parametrised cases and snapshots.
Read articleRun your server over HTTP, add health checks, scale with stateless mode and put it behind systemd and nginx.

/health custom route for probes.proxy_buffering off.A server that works on your laptop is only halfway there. This guide covers the decisions and settings that turn it into a dependable service other people can rely on, from the first HTTP run to TLS, scaling and monitoring.
You have two broad options.
my_server.py:mcp). The server then becomes available at a URL such as https://your-project.fastmcp.app/mcp.Managed hosting removes most operational work. Self-managed hosting gives you full control over the network, data location and costs. The rest of this guide focuses on self-managed hosting, because it involves more decisions.
uv.lock or a requirements.txt with exact versions.from fastmcp import FastMCP
mcp = FastMCP("My Server")
@mcp.tool
def process_data(input: str) -> str:
"""Process data on the server."""
return f"Processed: {input}"
if __name__ == "__main__":
mcp.run(transport="http", host="0.0.0.0", port=8000)Binding to 0.0.0.0 makes the server reachable from outside the machine or container. The equivalent CLI command is fastmcp run server.py --transport http --host 0.0.0.0 --port 8000. This is the simplest route and suits small services.
For more control over workers and middleware, create an ASGI application and run it with Uvicorn:
# app.py
from my_server import mcp
app = mcp.http_app()uvicorn app:app --host 0.0.0.0 --port 8000The default endpoint path is /mcp. Change it with mcp.http_app(path="/api/mcp") if it conflicts with an existing route.
Load balancers and orchestrators need a cheap endpoint to probe. A custom route provides one:
from starlette.requests import Request
from starlette.responses import JSONResponse
@mcp.custom_route("/health", methods=["GET"])
async def health_check(request: Request) -> JSONResponse:
return JSONResponse({"status": "healthy", "service": "mcp-server"})Custom routes skip the server’s authentication middleware, which is exactly what a health probe needs. For the same reason, never return sensitive information from them.
By default, sessions live in the memory of a single process. If a load balancer spreads requests across several workers or instances, a client may reach a worker that does not know its session. Stateless mode removes that dependency:
app = mcp.http_app(stateless_http=True)FASTMCP_STATELESS_HTTP=true uvicorn app:app --host 0.0.0.0 --port 8000 --workers 4Start with a single worker and add more only when monitoring shows that you need them.
Most MCP clients are not browsers and need no CORS configuration. If a browser-based client such as the MCP Inspector must connect, allow exact origins only and expose the session header:
from starlette.middleware import Middleware
from starlette.middleware.cors import CORSMiddleware
middleware = [
Middleware(
CORSMiddleware,
allow_origins=["https://app.example.com"],
allow_methods=["GET", "POST", "DELETE", "OPTIONS"],
allow_headers=["mcp-protocol-version", "mcp-session-id", "Authorization", "Content-Type"],
expose_headers=["mcp-session-id"],
)
]
app = mcp.http_app(middleware=middleware)Avoid allow_origins=["*"] in production. FastMCP also offers an opt-in guard that checks Host and Origin headers, enabled with host_origin_protection=True and lists of allowed hosts and origins.
On a Linux server, systemd restarts the process if it stops and starts it again after a reboot. Create /etc/systemd/system/fastmcp.service:
[Unit]
Description=FastMCP Server
After=network.target
[Service]
User=www-data
Group=www-data
WorkingDirectory=/opt/fastmcp
ExecStart=/opt/fastmcp/.venv/bin/uvicorn app:app --host 127.0.0.1 --port 8000
Restart=always
RestartSec=5
Environment="PATH=/opt/fastmcp/.venv/bin"
[Install]
WantedBy=multi-user.targetsudo systemctl daemon-reload
sudo systemctl enable --now fastmcp
sudo systemctl status fastmcpBinding to 127.0.0.1 here is deliberate: only nginx, on the same machine, should reach Uvicorn directly.
Place nginx in front of Uvicorn to handle HTTPS. Streaming responses require buffering to be switched off:
location / {
proxy_pass http://127.0.0.1:8000;
proxy_http_version 1.1;
proxy_set_header Connection '';
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_buffering off;
proxy_cache off;
proxy_read_timeout 300s;
proxy_send_timeout 300s;
}sudo nginx -t && sudo systemctl reload nginxIf clients connect but never receive streamed results, check proxy_buffering off first.
Most container platforms expect your server packaged with a Dockerfile or a requirements file. The principle is the same as above: install your pinned dependencies, then run the Uvicorn command as the container’s entry point, bound to 0.0.0.0 so the platform can route traffic to it. Pass secrets through the platform’s environment-variable settings rather than baking them into the image.
/health endpoint from your uptime monitor.journalctl -u fastmcp shows them on a systemd host.For public servers, yes. A reverse proxy such as nginx handles HTTPS certificates and keeps Uvicorn bound to localhost. Some platforms provide this layer for you automatically.
Sessions live in one process's memory by default. Behind a load balancer, a request may reach a different worker. Enable stateless mode with stateless_http=True or the matching environment variable.
Yes. Prefect offers managed hosting through FastMCP Gateway: connect a GitHub repository, set the entry point and receive an HTTPS URL. Container platforms are another option.
In environment variables or the platform's secrets manager. Keeping tokens and connection strings out of source code prevents leaks and lets the same build run in every environment.
Write quick, reliable tests with an in-memory client, pytest fixtures, parametrised cases and snapshots.
Read articleLet tools return forms, tables and charts that render in the conversation, and preview them locally.
Read articleCheck your Python version, install the package with uv or pip, confirm it works and fix the problems people meet most often.
Read article