MCP Deployment and Production Readiness
The new stateless core makes scaling easier, as long as you handle the few things that still have to be shared.
A modern MCP server over HTTP scales like an ordinary web service: any instance can answer any request. To make that true, keep application state in a shared store, share the key that protects request state, make changing operations safe to repeat, configure proxies for streaming, and set limits, monitoring and a rollback path before anyone depends on it.
What you will learn: choosing a hosting model, what must be shared between instances, a runnable two-instance test, containers and network settings, capacity, observability, upgrades and readiness checks.
Prerequisites: MCP Messages, Transports and Advanced Features and MCP Authentication and Security.
Checked against the 2026-07-28 specification in November 2026 and run with Python package mcp 2.3.0. The Dockerfile and settings are examples that were not built or deployed.
Three hosting models
| Model | How users get it | You operate | Fits |
|---|---|---|---|
| Local package over stdio | Install and run on their machine | Releases only | Developer tools, local files |
| Container they run | Pull an image into their environment | Releases and images | Data that must stay inside a network |
| Hosted service over HTTP | Connect to an address | Everything | Shared company or product services |
A local package avoids servers but spreads versions and credentials across many machines. A hosted service is one place to secure, update and observe, and one place that can fail for everybody.
A production shape
What must be shared
| State | Where it belongs |
|---|---|
| Business records, baskets, reports | A database, addressed by explicit handles |
| Key protecting request state | A secret store read by every instance |
| Operation keys already applied | A database with a unique constraint |
| Background tasks | A durable task store and queue |
| Change notifications to subscribers | A shared message bus |
| Rate limit counters | A shared counter or the gateway |
The key that is easy to forget
When a tool asks for confirmation, the first request may reach one instance and the retry another. The server protects the returned requestState with a key. In mcp 2.3.0 each process invents its own key unless you configure one. This script tries both arrangements.
"""Send the first round to one instance and the retry to another."""
import logging
from typing import Annotated
from mcp.server import MCPServer
from mcp.server.mcpserver import Elicit, RequestStateSecurity, Resolve
from pydantic import BaseModel
from starlette.testclient import TestClient
from wire import post
logging.disable(logging.CRITICAL)
SHARED_KEY = "demo-key-load-this-from-a-secret-store-0001"
STATUS = {"A-100": "open"} # stands in for the shared database
class Confirm(BaseModel):
confirm: bool
def ask(order_id: str) -> Elicit[Confirm]:
return Elicit(f"Cancel order {order_id}?", Confirm)
def build(security=None):
mcp = MCPServer("orders", log_level="CRITICAL",
request_state_security=security)
@mcp.tool()
def cancel_order(order_id: str,
answer: Annotated[Confirm, Resolve(ask)]) -> str:
"""Cancel an order after confirmation."""
STATUS[order_id] = "canceled" if answer.confirm else "open"
return f"{order_id} is {STATUS[order_id]}"
return mcp.streamable_http_app(json_response=True)
def exchange(first_app, second_app, tamper=False):
options = {"base_url": "http://127.0.0.1:8000"}
call = {"name": "cancel_order", "arguments": {"order_id": "A-100"}}
with TestClient(first_app, **options) as a:
first = post(a, "tools/call", call).json()["result"]
key = next(iter(first["inputRequests"]))
state = first["requestState"]
if tamper:
state = state[:-4] + ("AAAA" if state[-4:] != "AAAA" else "BBBB")
retry = dict(call, requestState=state, inputResponses={
key: {"action": "accept", "content": {"confirm": True}}})
with TestClient(second_app, **options) as b:
reply = post(b, "tools/call", retry).json()
if "error" in reply:
return f"error {reply['error']['code']}: {reply['error']['message']}"
return reply["result"]["content"][0]["text"]
print("each instance has its own key:")
print(" ", exchange(build(), build()))
shared = RequestStateSecurity(keys=[SHARED_KEY])
print("instances share a key:")
print(" ", exchange(build(shared), build(shared)))
STATUS["A-100"] = "open"
print("shared key, altered state:")
print(" ", exchange(build(shared), build(shared), tamper=True))
print("order status:", STATUS["A-100"])
Output:
each instance has its own key:
error -32602: Invalid or expired requestState
instances share a key:
A-100 is canceled
shared key, altered state:
error -32602: Invalid or expired requestState
order status: open
With separate keys the confirmation fails, which in production would appear as random failures that grow worse as you add instances, and as failures after every restart. With a shared key it works, and an altered value is still refused without changing the order. The helper post comes from the probe script in MCP Messages, Transports and Advanced Features.
Load the key from a secret manager, never from source code as the demo does. The SDK accepts a list of keys so you can rotate: first every instance learns the new key, then it becomes the one used to seal, and the old one is removed after the state lifetime has passed. Instances must also agree on the server name, which the SDK uses as the default audience.
Safe repeats
If a response stream breaks, the client is expected to send the work again as a new request. A restart, a proxy timeout or a deployment can all cause it.
| Tool type | Protection |
|---|---|
| Reads | Usually none needed |
| Set a value | Naturally repeatable; check the expected version |
| Create, send, charge | An operation key stored with the result, returned on repeats |
| Long jobs | Start once, return a handle or task, poll for status |
See Reliable Tool Execution and Error Recovery for a working idempotency pattern.
A container example
FROM python:3.13-slim
WORKDIR /app
RUN pip install --no-cache-dir mcp==2.3.0
COPY server.py .
RUN useradd --create-home app
USER app
EXPOSE 8000
CMD ["python", "server.py"]
Inside a container the server must listen on an interface the load balancer can reach, not only the loopback address. That removes the protection a localhost binding gives, so set the allowed host names and origins in the SDK's transport security settings, require authorization, and expose the port only to the gateway. Pin dependencies with hashes, scan the image and run without root. Docker and Kubernetes for Agents covers the platform side.
Proxies and streaming
| Setting | Why |
|---|---|
Disable response buffering (servers should send X-Accel-Buffering: no) | Otherwise progress arrives all at once |
| Idle timeout longer than keep-alive interval | Subscription streams are quiet for long periods |
| Forward MCP headers unchanged | Servers reject mismatched or missing headers |
| Preserve the public host in settings | Origin, host and resource checks depend on it |
| Request size limit | Protects memory |
| Graceful shutdown | Let in-flight calls finish during rollouts |
Because the protocol keeps no session, sticky routing is not needed for ordinary requests. If you also serve clients of older revisions that rely on sessions, test that path separately: it may still need affinity.
Identity and downstream access
A hosted server acts for many people at once, so decide early how each downstream call is made.
| Approach | How it works | Watch for |
|---|---|---|
| On behalf of the user | The server obtains a separate token for the downstream service that represents the same person | Token storage, expiry and consent |
| Service identity with checks | The server uses its own credential and enforces the user's rights itself | Every missed check becomes broad access |
| Per-tenant credentials | Each customer organization has its own credential | Never choose the tenant from model input |
Whatever you choose, cache entries, handles, task identifiers and log queries must all be scoped to the same identity. A cache keyed only by arguments will one day serve one customer's result to another. Test this with two users who send identical requests, and confirm each sees only their own data.
Configuration per environment
| Setting | Development | Production |
|---|---|---|
| Address | Loopback | Public name behind TLS |
| Allowed origins and hosts | Local only | Explicit list |
| Authorization server | Test tenant | Production tenant |
| Downstream systems | Fakes or sandboxes | Real, with narrow rights |
| Log detail | Verbose, synthetic data | Minimized and redacted |
| Debug mode | As needed | Off |
Read settings from the environment and refuse to start when a required security value is missing. A server that silently falls back to no authorization is worse than one that fails to start. Add a test that launches it with the production configuration shape and checks that an anonymous request is refused.
Limits and capacity
- Set a time limit for every downstream call, shorter than the client's patience.
- Rate-limit by user and by tool; an agent in a loop can send many requests quickly.
- Cap result sizes and page lists.
- Limit concurrent work per instance and return a clear "retry later" when full.
- Load test with realistic mixes, including slow downstreams.
The Mcp-Method and Mcp-Name headers let a gateway apply different limits to expensive tools without reading bodies.
Caching
Set ttlMs and cacheScope deliberately. A tool list that changes only on release can have a longer lifetime; anything filtered by user must be private. The SDK takes per-method cache hints when you construct the server. After a release, remember that clients may hold the old list until it expires, so keep removed tools working for at least that long.
Observability
| Signal | Break down by |
|---|---|
| Request rate and latency | Method and tool |
| Protocol errors | Error code and client version |
Tool results with isError | Tool and cause |
| Authorization refusals | Reason, without token values |
| Input-required rounds and abandonments | Tool |
| Downstream health | Dependency |
Pass trace context through the _meta keys and on to downstream calls so one trace covers the whole path. Liveness checks should confirm the process works; readiness checks should confirm it can reach what it needs. See Agent Tracing and OpenTelemetry.
Load testing an MCP server
Agent traffic differs from human web traffic. One user request can produce a burst of list and call requests, several in parallel, followed by silence while a model thinks. Test with that shape.
- Record the mix of methods and tools from a pilot, including the share that ends in an error.
- Replay it with several identities, so per-user limits and caches behave as they will in service.
- Include input-required exchanges, with the retry reaching a different instance.
- Slow one downstream dependency and confirm that timeouts free capacity.
- Restart instances during the run and count lost or repeated actions.
- Note the load at which latency rises sharply, then set limits below it.
Report latency by tool rather than as one average. A fast read can hide a slow write that causes every timeout.
Releasing changes
- Compare the new tool definitions with the released ones and flag any difference for review.
- Run protocol tests for each revision you support, plus the tool selection evaluation.
- Roll out to a small share, compare errors and latency, then continue.
- Keep the previous version ready. Make data changes work with both.
- Announce removed or renamed tools in advance and watch who still calls them.
A team scales from one instance to three. Confirmations begin failing for about two calls in three, while lists and reads look healthy. Traces show the first and second rounds on different instances. The cause is a per-process key; the fix is a shared secret and a test that runs the exchange across two instances.
Distributing local packages
If users run your server themselves, the release is your production system. Publish from an automated pipeline rather than a laptop, pin and scan dependencies, document the exact permissions and environment variables the server needs, state which protocol revisions it supports, and keep a changelog that calls out tool changes. Never let a start command fetch and run an unpinned latest version.
Targets to agree
Write down what good looks like before an incident forces the question. The values depend on your users and dependencies.
| Target | Measured as | When it is missed |
|---|---|---|
| Availability | Share of valid requests answered without a server error | Check health, capacity and dependencies |
| Latency per tool | A high percentile, tool by tool | Find the slow dependency; consider the tasks extension |
| Tool error rate | Results marked as errors, by tool and client | Review descriptions, validation and upstream faults |
| Authorization failures | 401 and 403 counts by client | Look for misconfiguration or probing |
| Recovery time | Time to restore after a bad release | Rehearse rollback |
Report each tool separately. An average across tools hides the one that fails every time but is called rarely.
A short runbook
| Symptom | First checks |
|---|---|
| All calls fail | Certificates, authorization server, gateway rules |
| Only confirmations fail | Shared key, server name, state lifetime |
| One tool slow | Its downstream, limits, result size |
| Header mismatch errors | A proxy rewriting headers or an old client |
| Progress arrives late | Proxy buffering |
Common mistakes
| Mistake | Better practice |
|---|---|
| State kept in process memory | Shared store and explicit handles |
| Testing with one instance only | Test across at least two |
| Assuming calls arrive once | Operation keys |
| Opening the container port to everyone | Gateway only, with authorization |
| Releasing tool changes silently | Review, announce and monitor |
Production readiness checklist
- Authorization, audience checks and Origin validation are on
- Two-instance and restart tests pass
- Changing tools are safe to repeat
- Timeouts, rate limits and size limits are set
- Dashboards and alerts cover errors, latency and refusals
- Secrets come from a manager and can be rotated
- Rollback has been performed at least once
- An owner and an on-call path are named
Frequently asked questions
Can I run an MCP server on a serverless platform?
The stateless core suits it. Check streaming support, execution time limits and cold starts, keep state outside the function and share the request-state key.
Do I need sticky sessions?
Not for the 2026-07-28 revision. You may for older clients that use protocol sessions, so check what your clients speak.
Should one server host many domains?
Smaller servers with one owner and a narrow set of permissions are easier to secure, release and switch off.
How do I handle jobs that take minutes?
Return a handle your own tools can check, or implement the Tasks extension where your clients support it. Do not hold one request open and hope.
References and further reading
- Streamable HTTP transport
- Key changes in the 2026-07-28 specification
- Official Python SDK
- Docker build best practices
Next steps
MCP Gateways, Catalogs and Governance
Manage many servers together.
Deployment and Infrastructure
Deployment across the agent stack.
MCP Troubleshooting, Versions and Message Reference
Diagnose failures.