Most real MCP tools call a network service. A synchronous call inside an async server blocks the event loop, which can delay every other request and make the client believe the server is unresponsive. Async handlers with explicit timeouts are a baseline requirement, not an optimization.
Async all the way down
from __future__ import annotations
import asyncio
import os
import httpx
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("status-tools")
_client: httpx.AsyncClient | None = None
_semaphore = asyncio.Semaphore(5)
REQUEST_TIMEOUT = httpx.Timeout(connect=5.0, read=20.0, write=10.0, pool=5.0)
def client() -> httpx.AsyncClient:
global _client
if _client is None:
_client = httpx.AsyncClient(timeout=REQUEST_TIMEOUT)
return _client
@mcp.tool()
async def get_service_status(service: str) -> str:
"""Check a service's public status endpoint.
Args:
service: Service identifier from the approved allow-list.
"""
allowed = {"api", "web", "worker"}
if service not in allowed:
raise ValueError(f"unknown service {service!r}")
url = f"https://status.example.com/api/{service}"
async with _semaphore:
try:
response = await client().get(url)
except httpx.TimeoutException:
return f"Status lookup for {service} timed out after 20s."
except httpx.HTTPError as error:
return f"Status lookup failed: {type(error).__name__}"
if response.status_code == 401:
return "Status service rejected the request. Check the server's credentials."
response.raise_for_status()
return response.text[:4000]
async def shutdown() -> None:
if _client is not None:
await _client.aclose()
The semaphore bounds concurrent calls. HTTPX applies connect, read, write, and pool timeouts. Timeout and transport failures become readable tool results rather than unhandled stack traces. The final output is truncated so a status page cannot flood the context.
Do not block the loop
Blocking libraries and CPU-heavy work need an escape hatch:
import asyncio
def parse_large_file(path: str) -> str:
with open(path, "r", encoding="utf-8") as handle:
return handle.read(1000)
@mcp.tool()
async def sample_file(path: str) -> str:
"""Read a bounded sample from an approved file."""
return await asyncio.to_thread(parse_large_file, path)
asyncio.to_thread keeps the event loop responsive, but it does not make unsafe file access safe. Validate the path against an allow-list before reading. For CPU-bound work, use a process pool or a queue, not a thread.
Timeouts versus retries
A timeout is not a retry policy. Retry only idempotent operations, with a small bounded number of attempts and backoff. Never retry a write that might have succeeded. If an upstream API is slow because of an incident, retries multiply load and make the incident worse.
Set two budgets:
- Per-upstream-call timeout inside the tool.
- Overall tool deadline enforced by the server or client.
If the upstream call has a 30-second timeout but the client gives up at 15 seconds, the user sees a timeout while the server keeps working. Align the budgets and return a controlled error before the client disconnects.
Cancellation and cleanup
When a client disconnects or cancels, stop work that no longer matters. Do not leave database transactions open or background tasks running. Use try/finally for resources and close the shared HTTP client during shutdown. If you spawn subprocesses, terminate them explicitly.
FastMCP may expose request context for logging and progress reporting. Use it to emit progress for long operations, but do not log secret arguments. Progress support differs by client; a tool must still work without it.
Concurrency is a permission decision
Five concurrent database queries against a small replica are fine. Five concurrent crawls of a customer site are not. Bound concurrency per tool and per tenant, and apply rate limits at the server or gateway level. The semaphore in the example is a local guard, not a complete abuse control.
Tests to write
- A normal response.
- A timeout from the upstream service (mock it).
- A 401 or 403 response.
- A malformed response body.
- Cancellation during a slow call.
- Concurrent calls that exceed the semaphore.
Use httpx.MockTransport for deterministic tests rather than hitting a live service. Add one integration test against a staging endpoint if the provider offers one; do not label it production verification.
For the transport and deployment side, continue with Python Streamable HTTP and the Python production checklist. For the protocol-level timeout behavior, see MCP request timeouts.
Sources
Sources were checked on Oct 23, 2026. Versions and client behavior can change; confirm the current documentation before relying on a configuration.