Sub topic 18
Running it in production
This chapter assumes you have built the agent loop from earlier chapters and can connect to one or more MCP servers. It covers three things that change once real users depend on the application: connection lifecycle, context size, and cost.
Manage the connection lifecycle
A stdio server is a child process. Your application owns it, so it must start the process, initialize the session, and shut it down cleanly. An AsyncExitStack guarantees the subprocess is cleaned up even when an error occurs.
Treat a failed server as degraded, not fatal. Remove its tools from the list you send to the model, and retry with a growing delay.
Bound every call
A tool can hang or return far more text than the model needs. Put a timeout and a size limit around every call.
import asyncio
from contextlib import AsyncExitStack
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
MAX_TOOL_CHARS = 4000
CALL_TIMEOUT = 30
params = StdioServerParameters(command="python", args=["server.py"])
def clip(text: str) -> str:
if len(text) <= MAX_TOOL_CHARS:
return text
return text[:MAX_TOOL_CHARS] + "\n[truncated]"
async def safe_call(session, name, args):
try:
result = await asyncio.wait_for(
session.call_tool(name, args), timeout=CALL_TIMEOUT
)
except asyncio.TimeoutError:
return "Tool timed out", True
text = "\n".join(c.text for c in result.content if c.type == "text")
return clip(text), bool(result.isError)
async def main():
async with AsyncExitStack() as stack:
read, write = await stack.enter_async_context(stdio_client(params))
session = await stack.enter_async_context(ClientSession(read, write))
await session.initialize()
print(await safe_call(session, "add", {"a": 2, "b": 3}))
asyncio.run(main())Returning the timeout as an error result, rather than raising, keeps the conversation alive. The model can then try something else or explain the failure.
Control context size
Every tool definition is sent on every model request, and every tool result stays in the message history. Both consume tokens.
- Expose only the tools a given task needs. Ten servers with fifty tools each can fill the context before the user says anything.
- Keep tool descriptions short and precise.
- Clip or summarize large results, as
clipdoes above. - Drop or compress old tool results once the model has used them.
Control cost
Cost comes from tokens and from loop length. A tool-heavy turn can make many model calls, and each call resends the whole history.
- Keep
MAX_STEPSlow enough to cap the worst case. - Log token usage per turn, per tool, and per server.
- Cache results from tools that are read-only and deterministic.
- Alert on turns that hit the step limit. They usually point to a bad tool description.
Operate it
Log every tool call with its name, duration, and error status. Never log secrets that appear in arguments. Pin server versions, because a changed tool schema changes your prompts and your costs. Run the Inspector checks from the testing chapter in your deployment pipeline.
Exercise
A turn sometimes ends with "Tool loop did not finish within MAX_STEPS", and token costs spike on those turns. Name two production measures from this chapter that reduce the damage and help you find the cause.
Show answer
Cap the loop with a low MAX_STEPS so the worst case is bounded, and log token usage per turn and per tool, with an alert when the step limit is hit. The logs show which tool or description sends the model into repeated calls. Clipping large results also shrinks the history that each repeated call resends.