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.

BeginnerIntermediateExpert · 11 min read · Last updated:

In short

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.

Versions used

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.

Beginner Where a server can run

Three hosting models

ModelHow users get itYou operateFits
Local package over stdioInstall and run on their machineReleases onlyDeveloper tools, local files
Container they runPull an image into their environmentReleases and imagesData that must stay inside a network
Hosted service over HTTPConnect to an addressEverythingShared 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

Clientshosts and agents
GatewayTLS, limits, routing
Instancesidentical, replaceable
Shared servicesdata, keys, queue, logs
Nothing important lives only inside one instance.
Intermediate Making instances interchangeable

What must be shared

StateWhere it belongs
Business records, baskets, reportsA database, addressed by explicit handles
Key protecting request stateA secret store read by every instance
Operation keys already appliedA database with a unique constraint
Background tasksA durable task store and queue
Change notifications to subscribersA shared message bus
Rate limit countersA 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.

Handle keys properly

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 typeProtection
ReadsUsually none needed
Set a valueNaturally repeatable; check the expected version
Create, send, chargeAn operation key stored with the result, returned on repeats
Long jobsStart 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

SettingWhy
Disable response buffering (servers should send X-Accel-Buffering: no)Otherwise progress arrives all at once
Idle timeout longer than keep-alive intervalSubscription streams are quiet for long periods
Forward MCP headers unchangedServers reject mismatched or missing headers
Preserve the public host in settingsOrigin, host and resource checks depend on it
Request size limitProtects memory
Graceful shutdownLet 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.

Expert Operating the service

Identity and downstream access

A hosted server acts for many people at once, so decide early how each downstream call is made.

ApproachHow it worksWatch for
On behalf of the userThe server obtains a separate token for the downstream service that represents the same personToken storage, expiry and consent
Service identity with checksThe server uses its own credential and enforces the user's rights itselfEvery missed check becomes broad access
Per-tenant credentialsEach customer organization has its own credentialNever 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

SettingDevelopmentProduction
AddressLoopbackPublic name behind TLS
Allowed origins and hostsLocal onlyExplicit list
Authorization serverTest tenantProduction tenant
Downstream systemsFakes or sandboxesReal, with narrow rights
Log detailVerbose, synthetic dataMinimized and redacted
Debug modeAs neededOff

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

SignalBreak down by
Request rate and latencyMethod and tool
Protocol errorsError code and client version
Tool results with isErrorTool and cause
Authorization refusalsReason, without token values
Input-required rounds and abandonmentsTool
Downstream healthDependency

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.

  1. Record the mix of methods and tools from a pilot, including the share that ends in an error.
  2. Replay it with several identities, so per-user limits and caches behave as they will in service.
  3. Include input-required exchanges, with the retry reaching a different instance.
  4. Slow one downstream dependency and confirm that timeouts free capacity.
  5. Restart instances during the run and count lost or repeated actions.
  6. 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

  1. Compare the new tool definitions with the released ones and flag any difference for review.
  2. Run protocol tests for each revision you support, plus the tool selection evaluation.
  3. Roll out to a small share, compare errors and latency, then continue.
  4. Keep the previous version ready. Make data changes work with both.
  5. Announce removed or renamed tools in advance and watch who still calls them.
Illustrative incident, not a real one

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.

TargetMeasured asWhen it is missed
AvailabilityShare of valid requests answered without a server errorCheck health, capacity and dependencies
Latency per toolA high percentile, tool by toolFind the slow dependency; consider the tasks extension
Tool error rateResults marked as errors, by tool and clientReview descriptions, validation and upstream faults
Authorization failures401 and 403 counts by clientLook for misconfiguration or probing
Recovery timeTime to restore after a bad releaseRehearse rollback

Report each tool separately. An average across tools hides the one that fails every time but is called rarely.

A short runbook

SymptomFirst checks
All calls failCertificates, authorization server, gateway rules
Only confirmations failShared key, server name, state lifetime
One tool slowIts downstream, limits, result size
Header mismatch errorsA proxy rewriting headers or an old client
Progress arrives lateProxy buffering

Common mistakes

MistakeBetter practice
State kept in process memoryShared store and explicit handles
Testing with one instance onlyTest across at least two
Assuming calls arrive onceOperation keys
Opening the container port to everyoneGateway only, with authorization
Releasing tool changes silentlyReview, 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

Next steps