
How to Fix MCP Tool Timeouts and Deadlocks in FastMCP on Linux
An MCP tool timeout is a symptom, not a diagnosis. The client may have stopped waiting while the server continued working; the server may be waiting for a child process; or a blocked event loop may be unable to make progress. A generic error code alone cannot distinguish these cases.
An earlier version of this article exposed a model-callable shell command and claimed that an async subprocess pattern eliminated deadlock risk. Both claims are withdrawn. This revision removes the downloadable scripts and reported test results because their contents and execution evidence are not available for review.
1. Locate the stalled boundary
Start with the request ID, timestamp, client and SDK versions, transport, configured deadlines, and sanitized client and server logs. Correlate one invocation across those records before changing a timeout.
| Observation | Next check | Do not conclude yet |
|---|---|---|
| Client times out; server logs continue | Compare client deadline with server work and cancellation records | That the server stopped the work |
| Other tools respond; one invocation does not | Inspect that tool’s dependencies, child process and output handling | That the transport is healthy in every respect |
| Server-wide requests stop progressing | Inspect event-loop blocking and shared locks or resource exhaustion | That a subprocess pipe is the cause |
| Child remains alive while producing output | Check whether both piped streams are being drained | That increasing the deadline will resolve it |
| Server records a result; client receives none | Inspect transport lifecycle, framing and the client deadline | That the result reached the caller |
If a child writes to a pipe while its parent waits for exit without reading, the child can block when the pipe fills. Python explicitly warns that Process.wait() can deadlock in this situation; communicate() reads stdout and stderr to EOF and waits for the child. See Python’s subprocess documentation. Do not treat a particular pipe capacity as universal.
A useful decision path is:
- Did the server finish before the client deadline? If yes, investigate delivery and transport. If no, determine whether the invocation continued after the client stopped waiting.
- Is the event loop responsive? If unrelated async work also stalls, inspect synchronous calls and shared contention before focusing on a single child.
- Is a child running or waiting on output? Inspect the parent’s stream readers, child state and ownership. Only diagnose a pipe deadlock when the evidence supports it.
- Did a timeout or cancellation occur? Check the separate cleanup path and whether the direct child and any owned descendants actually exited.
2. Design the subprocess boundary
Avoid exposing a caller-supplied shell command to an agent. Python documents that applications using create_subprocess_shell() are responsible for quoting special characters to avoid shell injection. Prefer a narrowly defined operation with a fixed executable and constrained arguments, and review what those arguments allow the executable itself to do. Python’s subprocess API also provides create_subprocess_exec() for an explicit program and argument list.
Before deployment, define:
- Authority: the operating-system identity, working directory, accessible files and minimal environment. Do not place unnecessary secrets in the child’s environment.
- Input: an allowlist of operations and validated arguments; treat tool inputs and child output as untrusted data.
- Time: separate limits for the client request, server operation and child cleanup, with enough room for the server to report a controlled outcome.
- Output: concurrent draining of both streams, an explicit byte budget and a policy for exceeding it. A length check after
communicate()returns is not a memory cap: the output has already been collected. The subprocesslimitparameter controls the stream-reader wrappers; do not assume it is a total-output budget. - Ownership: a record of which process or process group belongs to the invocation, and what the application is authorized to terminate. A direct child’s exit does not establish that its descendants have exited.
For potentially large output, use bounded streaming with a defined overflow response, or controlled file-backed logs with storage limits and retention. Ensure the overflow path also drains or terminates the producer according to the selected policy; simply stopping reads can leave it blocked.
3. Treat timeout and cancellation as separate lifecycle paths
A deadline around a child wait is only one part of cleanup. Client disconnects, explicit cancellation, server shutdown and internal errors may arrive at different points in process creation and execution.
The following is a non-executable implementation and review checklist, not a verified cancellation implementation:
- Establish ownership as soon as the process is created, including the case where cancellation races with creation.
- On timeout or task cancellation, initiate the approved termination policy for the owned process scope. Handle the race in which the child exits before a termination signal is delivered.
- Continue cleanup until the direct child has been reaped, while accounting for repeated cancellation and errors during cleanup. Apply a bounded escalation policy appropriate to the service and operating system.
- After cleanup, propagate cancellation to the caller; do not turn it into a successful tool result. Report timeout separately where the application’s contract requires it.
- Record cleanup failures without exposing secrets, and surface any remaining owned process for operator investigation.
These steps need implementation and testing against the pinned Python release and the application’s actual process-tree policy. No code in this article demonstrates or verifies cancellation cleanup. In particular, terminating only a direct child is insufficient evidence that a process tree is gone.
A blocking synchronous call can also keep the event loop from servicing deadlines promptly. Moving work to a thread may preserve responsiveness, but cancellation of the waiting coroutine should not be assumed to stop the underlying operation. For long-running work, consider a job interface with authorization, durable status and idempotent retries rather than an indefinitely open tool call.
4. Check the SDK version and transport
Do not combine snippets from different SDK generations. The v1 maintenance documentation shows the mcp.server.fastmcp import and advises keeping v1 installations below version 2. The migration guide says that importing mcp.server.fastmcp in v2 raises ModuleNotFoundError; its high-level server is named MCPServer.
Pin an exact release in the application’s dependency management, then inspect that release’s documentation, signatures and migration notes. The supplied current documentation identifies v2 as stable and requires Python 3.11 or later, but that current page does not establish what was available on a historical date. See the SDK documentation.
For stdio, investigate startup wrappers and logging as well as tool execution. The SDK’s running guide describes stdout as the protocol wire: its current v2 behavior diverts some output while serving, but output flushed before serving or buffered until exit can still reach the wire. Direct diagnostics to an appropriate logging handler and verify the behavior of the pinned SDK release. Do not infer successful client negotiation from a subprocess-only check.
5. Validate in isolation before rollout
Use an isolated environment and harmless, fixed test programs whose source is reviewed and versioned with the test. Capture the Python, SDK, client and operating-system versions, test inputs, timestamps and observed outcomes.
Exercise small output, concurrent stdout and stderr, output exceeding the chosen budget, nonzero exit, a server deadline, and client cancellation. For cleanup, include cancellation during startup and execution, child exit racing with termination, repeated cancellation, and an owned descendant where applicable. Verify both reaping and the absence of remaining task-owned processes; do not terminate unrelated services to make a test pass.
Then test the real client and server together: initialization, tool discovery, a successful call, invalid input, deadline behavior and a subsequent call after failure. Compare observed behavior with the client’s documented timeout and cancellation semantics. Roll out a scoped change with monitoring and a rollback plan only after those checks meet the application’s acceptance criteria.
Primary sources
- Python asyncio subprocesses — pipe handling and subprocess APIs.
- MCP Python SDK v1 documentation and migration guide — version boundaries and import changes.
- MCP server running guide — current stdio transport and logging behavior.
Validation boundary: This article provides a review and test plan, not an executed test, verified implementation or guaranteed fix. No execution receipts were supplied for the former scripts or integration claims. Source excerpts were reviewed for this correction on November 13, 2026; current documentation alone does not prove historical release behavior.