Sub topic 18
Running it in production
This chapter covers what changes when your MCP-based application leaves your laptop. It assumes you have built the agent loop from earlier chapters, can read async Python, and know how MCP sessions, tool schemas and tool results fit together. The three concerns here are connection lifecycle, context size and cost. Each can fail quietly in a demo and loudly under real traffic.
What changes in production
In a demo you start one server, run one conversation and exit. In production you have many concurrent users, servers that crash or hang, and a bill that grows with every token you send. Three questions drive the design:
- Who owns each server process or connection, and when is it started and stopped?
- How many tokens do the tool definitions and tool results add to every model call?
- What stops one slow tool or one runaway conversation from hurting everyone else?
Managing connection lifecycle
An MCP session is stateful. It starts with the initialization handshake and lasts until you close it. With stdio, the server is a subprocess, so closing the session also ends a process. Starting a subprocess and completing the handshake costs time, so the simplest mistake is to create a new session for every user message.
Choose a session scope
You have three common choices.
| Scope | How it works | Good for | Risk |
|---|---|---|---|
| Per application | One session per server, opened at startup and shared | Stateless, read-only servers | One crash or hang affects every user |
| Per conversation | A session is opened when a conversation starts and closed when it ends | Servers that keep per-user state | Many processes if you have many users |
| Per request | A new session for each model turn | Rare, one-off jobs | Startup cost on every call |
For stdio servers that hold no per-user state, a shared session per application is usually the cheapest option. For servers that hold state or user credentials, use one session per conversation, and do not share it across users.
Keep sessions open with an async context stack
The SDK's stdio_client and ClientSession are async context managers. To keep them open for the life of your application, put them on an AsyncExitStack and close the stack at shutdown.
import asyncio
from contextlib import AsyncExitStack
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
class ServerPool:
def __init__(self):
self._stack = AsyncExitStack()
self.sessions = {}
async def start(self, name, params):
read, write = await self._stack.enter_async_context(stdio_client(params))
session = await self._stack.enter_async_context(ClientSession(read, write))
await session.initialize()
self.sessions[name] = session
async def close(self):
await self._stack.aclose()
async def main():
pool = ServerPool()
try:
await pool.start("calc", StdioServerParameters(command="python", args=["server.py"]))
tools = await pool.sessions["calc"].list_tools()
print([t.name for t in tools.tools])
finally:
await pool.close()
asyncio.run(main())The finally block matters. Without it, an exception can leave server subprocesses running after your application has stopped.
Handle crashes and hangs
Servers fail in two ways. A crashed server closes its streams, and your next call raises an exception. A hung server never answers, and your call waits forever. Plan for both.
- Put a timeout on every tool call. The SDK's
call_toolaccepts aread_timeout_secondsargument that takes atimedelta. You can also wrap the call inasyncio.wait_for. - Treat a timeout or a closed-stream error as a signal to restart that server, not the whole application.
- Return a short error message to the model as a tool result, so the conversation can continue.
- Restart with backoff. A server that fails on startup will fail again immediately, and a tight restart loop wastes CPU.
import asyncio
async def call_with_timeout(session, name, args, seconds=30):
try:
return await asyncio.wait_for(session.call_tool(name, args), timeout=seconds)
except asyncio.TimeoutError:
return NoneA None return tells the caller to build an error result for the model. How you restart the server depends on which session scope you chose, so the pool should expose a restart method for one named server.
Remote servers
For Streamable HTTP servers you do not own the process, so lifecycle is about connections, not subprocesses. Reconnect when a connection drops, and run the initialization handshake again on the new connection. Do not assume that state from the old session survived. Authorization tokens also expire, so refresh them before they do rather than after a failed call.
Controlling context size
Every tool you pass to the model costs input tokens on every request. That includes its name, description and full input schema. A server with 40 tools can add thousands of tokens to each call, even when the user only wants one of them.
Tool results are the second source of growth. The agent loop appends each result to messages, and the next step resends everything. A tool that returns a 50,000-character file, called three times in one turn, can fill the model's context window.
Reduce tool definition cost
- Connect only the servers a given task needs, not every server you have.
- Filter the tool list with an allowlist before calling
to_llm_tools. - Write short, specific tool descriptions in servers you control.
- For large catalogs, select a relevant subset of tools per request, for example with keyword matching or a cheap first model call.
ALLOWED = {"add", "search_docs"}
def filter_tools(mcp_tools):
return [t for t in mcp_tools if t.name in ALLOWED]An allowlist also helps security, because the model cannot call a tool it never sees.
Reduce tool result cost
- Cap the size of each result before it goes into the conversation, and say that you truncated it.
- Ask servers you control to support paging or filters instead of returning everything.
- Drop or summarize old tool results when a conversation gets long.
MAX_RESULT_CHARS = 8000
def clip(text):
if len(text) <= MAX_RESULT_CHARS:
return text
return text[:MAX_RESULT_CHARS] + "\n[truncated: result exceeded limit]"Tell the model when you truncated. Otherwise it may treat partial data as complete and give a confident wrong answer.
Controlling cost and load
Cost has several parts: input tokens, output tokens, tool-side costs such as paid APIs or compute, and the time your workers spend waiting.
Set limits at several levels
| Limit | What it prevents |
|---|---|
| `MAX_STEPS` per turn | A model calling tools in an endless loop |
| Per-call timeout | One hung tool blocking a worker |
| Result size cap | Context overflow and large token bills |
| Max tokens per response | Long, expensive outputs |
| Per-user rate limit | One user consuming shared capacity |
| Concurrency limit per server | A single server being overwhelmed |
A semaphore is a simple way to limit concurrent calls into one server.
import asyncio
server_slots = asyncio.Semaphore(5)
async def limited_call(session, name, args):
async with server_slots:
return await session.call_tool(name, args)Measure before optimizing
Log these values for every turn: input tokens, output tokens, number of steps, tool names called, tool latency and error counts. Most model APIs return token usage on the response object. Without these numbers you cannot tell whether cost comes from big tool lists, big results or many steps.
Observability
MCP servers that use stdio must not write to standard output except for protocol messages. Stdout carries the JSON-RPC stream, and stray print calls corrupt it. Log to standard error or to a file instead.
On your host side, log each tool call with a correlation ID that ties it to the user request. Record the server name, tool name, duration and whether isError was set. Do not log full arguments or results by default, because they may contain personal or secret data. Redact first, or log sizes instead of content.
Versioning and change
Servers change. A tool can be renamed, gain a required argument, or change what it returns. Your application should expect that.
- Pin server versions in your deployment, not "latest".
- Re-run
list_toolsafter a reconnect, and compare it against what you expect. - Test the integration in CI against the pinned server, using the approach from the testing chapter.
- Treat a changed tool description as a change to your prompt, and review it as such.
Deployment checklist
- Session scope chosen per server, with clean shutdown.
- Timeout on every call, and a restart path for crashed servers.
- Tool allowlist in place.
- Result size cap with a truncation notice.
- Step limit, rate limits and concurrency limits set.
- Token usage and tool latency logged, with sensitive data redacted.
- Server versions pinned.
Exercise
Your agent answers a long research question. Token cost per turn rises sharply after the third tool call, and then the API rejects a request after you trim old messages. Name two likely causes and a fix for each.
Show answer
First, tool results are appended to the history and resent on every step, so a large result inflates every later call. Fix this by capping result size with a truncation notice and by summarizing or dropping old results. Second, trimming removed a tool_use message but kept its tool_result (or the reverse), which breaks the pairing the API requires. Fix this by trimming whole tool exchanges together, never one half.
Exercise
A stdio server hangs on one tool call. Describe what your host should do so that other users are not affected and the conversation can continue.
Show answer
Wrap the call in a timeout (for example asyncio.wait_for). On timeout, return an error tool result to the model so it can answer or try another approach. Restart that server's session with backoff. If the server is shared, keep a concurrency limit so waiting calls do not use up every worker.