An engineering record based on a two-week internal rewrite, published 2026-11-24. This guide restates the changes, their rationale, and the resulting metrics in a revised structure; it does not introduce new benchmark claims.
1. Background and Starting State
The team maintains six internal MCP Servers, connected respectively to the order, inventory, ticket, report, permission, and log systems. After three months in production, the client-side timeout rate had stabilized near 12%. Dozens of tool calls failed each day, and the Agent could only retry the request or abandon it. Repeated retries added load to the same stalled downstream, while abandoned calls left the Agent without the data it needed to complete a task.
The transport layer of all six servers was rewritten over a two-week window. After the work, the timeout rate fell to 0.3%. This record focuses on concrete changes: what was modified, why the modification was made, and how the metrics moved afterward. It does not repeat general introductions to the Model Context Protocol, and it treats the six servers as ordinary internal services rather than as a reference deployment.
The first version followed a tutorial from late 2024. Each server ran a single SSEServerTransport, every tool function was synchronous, logs were written with print, and the timeout was set uniformly to 60 seconds.
The baseline tool looked like this:
# First version: the problems are all in these lines
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("order")
@mcp.tool()
def query_order(order_id: str) -> dict: # synchronous function
print(f"query {order_id}") # pollutes stdout
resp = requests.get(f"http://api/orders/{order_id}") # blocking call
return resp.json()
Twenty lines of this kind carried four defects: synchronous blocking, stdout pollution, missing pagination, and an uncontrolled timeout. Each defect alone was unlikely to be fatal. Stacked together, they produced the 12% timeout rate. The defects also interacted: a blocked loop delayed later requests, truncated responses removed the diagnostic fields a retry needed, and a single 60-second ceiling hid whether the failure originated in the client, the tool, or the downstream service.
2. Change One: Convert Tools to Async and Offload Blocking Work to a Thread Pool
This change delivered the largest single gain. MCP tool functions run inside the event loop. A single three-second synchronous HTTP request blocks the entire loop, and every queued request behind it then times out. The blocking call does not fail fast; it occupies the loop while other requests accumulate, which spreads one slow dependency into a broader service slowdown.
Where the code could be converted directly, it moved to the async HTTP client:
import httpx
from mcp.server.fastmcp import FastMCP
client = httpx.AsyncClient(timeout=4.0, limits=httpx.Limits(max_connections=50))
@mcp.tool()
async def query_order(order_id: str) -> dict:
"""Return order details by order ID."""
resp = await client.get(f"http://api/orders/{order_id}")
resp.raise_for_status()
return resp.json()
The client keeps its own connection pool and applies a four-second per-request limit, so a slow endpoint cannot hold a connection indefinitely. The connection cap of 50 bounds outbound pressure under concurrent Agent calls.
Legacy code that could not be made async — for example, a report SDK that exposes only a synchronous interface — was pushed to a thread pool with anyio.to_thread.run_sync:
import anyio
@mcp.tool()
async def run_monthly_report(month: str) -> str:
"""Run the monthly report from the legacy system."""
return await anyio.to_thread.run_sync(_report_sync, month, limiter=_limiter)
One detail matters here. The thread pool defaults to a concurrency of 40, while the report tool takes eight seconds per run. A single burst fills the pool, and any additional report call queues behind threads that are still working. An explicit CapacityLimiter(8) was therefore added. Requests that exceed the limit return a queued status immediately, instead of waiting on an overloaded pool. The caller can decide whether to retry later or schedule the report in a background step.
Metrics after this change: four of the six servers were implemented synchronously. After the async conversion, P99 latency dropped from 40 seconds to 1.8 seconds, and the timeout rate fell from 12% to 5.1%. The P99 improvement reflects the removal of loop contention more than a change in raw downstream speed.
3. Change Two: Reorder the Three-Layer Timeout So the Inner Layer Is Shorter
The original configuration had three mismatched limits: the client waited 60 seconds, the tool function set no limit, and the downstream API used the requests default, effectively unlimited. When the downstream service stalled, the client waited the full 60 seconds before failing, and the log carried only a -32603 Internal error. No field in that response identified whether the stall came from the tool, the database, or an external dependency.
The revised limits follow an inner-shorter-than-outer rule. Each outer layer must wait long enough for the inner layer to fail and report a structured error:
| Layer | Timeout | Implementation |
|---|---|---|
| Downstream internal API | 4s | httpx client level |
| Tool function | 8s |
asyncio.wait_for wrapper |
| Client HTTP | 15s | Client side |
The tool wrapper reads as follows:
import asyncio
TOOL_TIMEOUT = 8.0
@mcp.tool()
async def safe_query_order(order_id: str) -> dict:
try:
return await asyncio.wait_for(query_order(order_id), TOOL_TIMEOUT)
except asyncio.TimeoutError:
return {"error": "timeout", "order_id": order_id, "layer": "downstream"}
The key rule is to return a structured error after a timeout rather than raise an exception. With an exception, the client can only observe the generic -32603 code. With a structured error, the Agent can read layer: downstream and decide whether to retry or degrade. The response also carries the original order ID, so a retry targets the same request instead of reconstructing parameters from memory.
This change raised the retry success rate from 31% to 68%. The improvement comes from two sides: retries are issued only where the failure is retryable, and the error payload removes ambiguity about which layer failed.
Metrics after this change: the timeout rate moved from 5.1% to 2.4%, and P99 latency held at 1.6 seconds.
4. Change Three: Align the Gateway SSE Heartbeat and Timeout Settings
All services sit behind an Nginx layer with the default proxy_read_timeout of 60 seconds. A Server-Sent Events long connection sends no data while there is no message to push. When the 60-second mark arrives with no traffic, the connection is cut, and the client experiences a drop with no visible cause. The failure looks like a client-side disconnect, even though the actual cause is an idle-connection expiry at the gateway.
The gateway timeout and the SSE heartbeat therefore have to be configured together. If the upstream produces long quiet periods, the read timeout must cover those periods, and heartbeat events must arrive before the gateway closes the idle connection. A mismatch in either direction leaves the client with an unexplained disconnect: either the heartbeat is too slow for the gateway limit, or the gateway limit is too tight for the workload's quiet intervals.
This layer also fits the broader routing role of an API gateway. When several MCP servers and upstream tool endpoints share one control plane, a gateway such as 4sapi can centralize timeout policy, connection limits, and routing rules, so individual servers do not each duplicate Nginx-style tuning. Policy changes then apply at one layer, and server configuration stays focused on tool behavior.
Metrics after this change: the timeout rate moved from 2.4% to 1.1%, and P99 latency settled at 1.5 seconds.
5. Change Four: Paginate Results and Turn Large Fields into References
The next change addresses response size rather than latency alone. Large tool responses were serialized into a single message, and the connection was truncated before the client could read the full payload. Truncation appeared intermittently: small requests completed, while list-heavy or detail-heavy responses were cut mid-stream.
The revised listing tool returns a page of results, a continuation marker, and a reference for detail retrieval:
@mcp.tool()
async def list_orders(page: int = 1, size: int = 50) -> dict:
"""Paginated order query; at most 50 rows per page."""
size = min(size, 50)
rows = await db.fetch_orders(offset=(page - 1) * size, limit=size)
return {
"page": page,
"has_more": len(rows) == size,
"items": [{"id": r.id, "amount": r.amount, "status": r.status} for r in rows],
"hint": "Call get_order_detail(order_id) for row details.",
}
The page size is capped at 50 rows, and has_more tells the caller whether another page exists. Heavy detail fields are not repeated in the list. Instead, the response points to a separate get_order_detail tool that loads the full record on demand. This keeps the listing payload narrow even when the underlying record contains long descriptions, attachments, or history entries.
The working rule adopted in the team is: a single tool response above 50 KB should be paginated. In measurements across the six servers, responses kept within 20 KB no longer showed truncation. The gap between the 50 KB threshold and the 20 KB observed ceiling leaves room for encoding differences and protocol overhead.
Metrics after this change: the timeout rate moved from 1.1% to 0.6%, and P99 latency dropped to 1.2 seconds.
6. Change Five: Replace Globals with ContextVar for Concurrent Requests
This change was not a timeout problem. It was a request cross-wiring problem. One Agent fans out four subtasks concurrently, and occasionally task A received an order that belonged to task B. The symptom looked like a wrong result rather than a failure, which made it harder to trace than a timeout.
The cause was that the first version stored the current user in a module-level variable. Under concurrent execution, that variable was readable and writable across requests. The fix moved the value into a ContextVar:
from contextvars import ContextVar
current_user: ContextVar[str] = ContextVar("current_user")
async def handle_request(req):
token = current_user.set(req.headers.get("X-User", "anonymous"))
try:
return await mcp.handle(req)
finally:
current_user.reset(token)
The reset call in finally cannot be omitted. Otherwise, when the context is reused by a later asynchronous task, the previous request's value remains attached. The token returned by set identifies the exact context to restore, so nested or reused contexts do not interfere with one another. After this fix, a three-day load test produced zero cross-wiring incidents.
7. Change Six: Watch stdin EOF in stdio Servers to Prevent Zombie Processes
Some local tools use the stdio transport. After the client crashes, the child process remains hung. On one test machine, 37 zombie processes accumulated over a week until memory was exhausted. Each orphaned process held its loaded runtime and any partially held state, which reduced headroom for the next run.
The server watches stdin and exits when the parent disappears:
async def watch_stdin():
loop = asyncio.get_running_loop()
while True:
line = await loop.run_in_executor(None, sys.stdin.readline)
if not line: # EOF: the parent is gone
sys.exit(0)
await handle_line(line)
Reading in an executor avoids blocking the event loop on a synchronous standard-input call. The empty-line check treats EOF as a signal to shut down cleanly rather than waiting indefinitely for a parent that will never write again.
A second stdio rule applies to logging. In stdio mode, all logs must go to stderr. Writing to stdout pollutes the protocol stream; the client then reports a JSON parse error: Unexpected token 'I', which is caused by an interleaved log line rather than a malformed JSON message. The diagnostic points at the parser, but the root cause is a shared output channel.
8. Cumulative Metrics After the Rewrite
The table below records timeout rate and P99 latency at each stage, in the order the changes were applied:
| Stage | Timeout rate | P99 latency |
|---|---|---|
| Before rewrite | 12.0% | 40s |
| After async conversion | 5.1% | 1.8s |
| After timeout layering | 2.4% | 1.6s |
| After gateway heartbeat | 1.1% | 1.5s |
| After pagination | 0.6% | 1.2s |
| All changes complete, including the cross-wiring fix | 0.3% | 1.1s |
The remaining 0.3% consists mainly of genuine downstream outages, which falls within the normal failure range for this environment. The cross-wiring fix did not enter the timeout figures directly, but it removed a class of incorrect results that would otherwise be reported as task failures.
9. Prioritization If Only Two Changes Can Be Made
If team resources allow only two changes, the record recommends the async conversion and the timeout layering. These two account for the large majority of the gain from 12% down to 2.4%, and they carry the smallest implementation cost. The async conversion is a mechanical replacement, and timeout layering adds one wait_for wrapper plus the structured error return.
The gateway heartbeat and pagination are environment-dependent. Another deployment may not need them, especially if the gateway already sends keepalive messages or if tool responses are uniformly small. The async conversion and timeout layering, by contrast, apply to any MCP Server that talks to a remote dependency under concurrent load.
A practical rollout order follows the metric sequence: remove loop contention first, because it affects every queued request; then add timeout boundaries so failures surface with a layer label; align gateway idle settings; and finally split oversized responses. The ContextVar isolation and stdio watchdog address correctness and process hygiene rather than raw latency.
10. Version and Compatibility Notes
The code in this record recommends locking FastMCP at version 1.10 or above. Older versions had incomplete support for Streamable HTTP. The team encountered one bug where the session could not downgrade to SSE after the initialize handshake; upgrading the dependency resolved it.
Two maintenance rules follow from the record. First, keep tool functions non-blocking, and push sync-only legacy libraries behind an explicit concurrency limit. Second, every failure boundary should return a machine-readable error that identifies the affected layer, so the Agent can choose retry or degradation instead of seeing a generic internal error.
For deployment, keep the transport configuration visible alongside the tool code. Timeout values, connection limits, heartbeat intervals, and pagination caps should live in one reviewed configuration block, rather than being scattered across tutorial snippets. This makes it possible to audit why a request failed, and to adjust one setting without rewriting the tool.
Top comments (0)