AI Hints
Home›MCP Tutorial›Running Servers Well
MCP · Lesson 70 of 120

Stateless Servers

Scaling out.

⏱ 2 min read▶ Video at 1:02:17🎓 Free
Watch this lesson in the MCP courseWatch on YouTube ↗Full MCP course

By default, an HTTP server keeps a session for each client, in memory. That breaks when you run several copies behind a load balancer. A stateless server keeps nothing between requests, so any copy can answer any request.

Stateless Servers
From the video: Stateless Servers
  • Sessions in memory
  • Many copies break it
  • Stateless fixes it

A stateless server

We ask for a stateless app, with plain JSON replies. Then three separate clients each make one call. Run it. Every call is answered on its own, with no session to remember.

stateless.pypython
import asyncio
from mcp import Client
from northwind import mcp
from serve import start

start(mcp.streamable_http_app(stateless_http=True, json_response=True))

async def ask(order_id):
    async with Client("http://127.0.0.1:8765/mcp") as client:
        r = await client.call_tool("order_status", {"order_id": order_id})
        print(order_id, "->", r.content[0].text)

async def main():
    for order_id in [1042, 1043, 1044]:
        await ask(order_id)

asyncio.run(main())
Output
1042 -> shipped
1043 -> packing
1044 -> delivered
Also uses northwind.py
from mcp.server.mcpserver import MCPServer
from mcp.server.mcpserver.exceptions import ToolError

mcp = MCPServer("northwind")
ORDERS = {1042: "shipped", 1043: "packing", 1044: "delivered"}

@mcp.tool()
def order_status(order_id: int) -> str:
    """Look up the status of a Northwind order by its number."""
    if order_id not in ORDERS:
        raise ToolError(f"Order {order_id} not found")
    return ORDERS[order_id]

@mcp.tool()
def delivery_cost(order_total: float) -> str:
    """UK delivery cost for an order total in pounds."""
    return "free" if order_total >= 50 else "£4.99"

@mcp.resource("policy://returns")
def returns_policy() -> str:
    """Northwind's returns policy."""
    return "You can return any unused item within 30 days of delivery."

@mcp.prompt()
def support_reply(question: str) -> str:
    """Draft a polite reply to a customer."""
    return f"Write a short, polite reply to this Northwind customer: {question}"

if __name__ == "__main__":
    mcp.run()
Also uses serve.py
import threading, time, uvicorn

def start(app, port=8765):
    """Run a web app in the background, just for demos."""
    threading.Thread(target=uvicorn.run, args=(app,), daemon=True,
                     kwargs={"port": port, "log_level": "critical"}).start()
    time.sleep(1)

Stateful or stateless

Stateful servers can push updates, and keep long streams open, but need sticky sessions. Stateless servers scale easily, and survive restarts. Most tool servers can be stateless.

Stateful

  • Server can pushLong streamsSticky sessions

Stateless

  • Scales outSurvives restartsAny copy answers

Summary

Stateless HTTP servers keep nothing between requests, so they scale out easily. Next, the lifespan.

Key takeaways
  • stateless_http
  • json_response
  • Scale out
Next up: Lifespan — open once, share everywhere