Skip to content

stdio server stops answering queued requests under CPU contention until more input arrives (lost wakeup?) #3964

Backlog

Description

@qspencer

Versions: mcp 1.30.0, anyio 4.16.0, CPython 3.14.7, Linux x86_64.

What happens. A FastMCP stdio server, given several requests in one write, sometimes answers the first few and
then stops: the remaining requests (and a final ping) get no response, with stdin still open, for as long as we
waited (90 s). It happens only under CPU contention. Alone it answered every time (0 of 10 runs stalled). With eight
copies running at once on four cores, 6 of 48 runs stalled. The point where it stops varies between runs: the
missing ids were {6, 7, 999}, {7, 999} or {999}.

Minimal server (no application code):

from mcp.server.fastmcp import FastMCP
m = FastMCP("bare")
@m.tool()
def recall(query: str) -> str:
    return "ok"
m.run()

Driver. One write to stdin of these lines, then wait (stdin left open) for responses to ids 3, 4, 6, 7 and 999:
initialize (id 1); notifications/initialized; a malformed line ({not json ...); a request with an unknown
method (id 2); tools/call of an unknown tool (id 3); tools/call of recall with an unknown argument (id 4); a
tools/call whose params is a string (id 5); a batch array; prompts/get of an unknown prompt (id 6);
resources/read of an unknown URI (id 7); ping (id 999).

Stack dump of a stalled server (faulthandler, SIGABRT after 30 s without a response): the main thread is idle in
the asyncio loop's select (epoll_wait), and the AnyIO worker threads are idle in queue.get. No request handler
is running, and nothing is blocked. That looks like a result handed back to the loop without the loop being woken:
a further message sent after the stall gets the outstanding responses answered: a driver that sends an extra
ping after 5 s of silence saw 3 of 40 runs stall under the same load, and all 3 completed after the ping.

Expected: every request read from stdin is eventually answered while stdin is open, whatever the CPU load.

Happy to provide the full driver script and dumps.

Activity

  1. achisman-sarangi commented on Dec 3, 2026

    @achisman-sarangi

    Hi, I'd be interested in investigating this issue. I'd like to reproduce the behavior under CPU contention, identify the underlying cause in the request processing or asynchronous scheduling path, and work on a fix with regression tests.

    Would it be okay for me to take this issue? It would also be helpful if you could share the full reproduction script.

    Thank you!

  2. qspencer commented on Dec 4, 2026

    @qspencer
    Author

    Thanks for picking this up. Assignment is the maintainers' call, but from our side please go ahead.

    Here is a self-contained reproduction (needs only mcp). It is the same request batch as in the issue. drive.py writes it in one go, keeps stdin open, waits 30 s for ids 3, 4, 6, 7 and 999, and on a stall SIGABRTs the server with PYTHONFAULTHANDLER=1 to dump every thread's stack. load.sh runs eight drivers at once pinned to four CPUs, for five rounds.

    Re-run just now on mcp 1.30.0, anyio 4.15.1, CPython 3.14.7, Linux x86_64 (16-core host, drivers pinned to 4): 4 of 40 runs stalled. The missing ids were {6, 7, 999}, {7, 999} twice, and {999}. Run alone, the driver has never stalled (0 of 10 in the original measurement, and 1 of 1 complete just now).

    bash load.sh python3 ./load-out 0-3

    bare_server.py
    from mcp.server.fastmcp import FastMCP
    m = FastMCP("bare")
    @m.tool()
    def recall(query: str) -> str:
        return "ok"
    m.run()
    drive.py
    """Drive bare_server.py over stdio: one write of the request batch, stdin left open, then wait for responses to ids
    3, 4, 6, 7 and 999. On a 30 s stall, SIGABRT the server (PYTHONFAULTHANDLER=1) so it prints every thread's stack.
    
    Usage: python drive.py [server.py] [dump.txt]   exit 0: every response arrived; exit 1: stalled (dump written)
    """
    import json, os, selectors, signal, subprocess, sys, time
    
    server = sys.argv[1] if len(sys.argv) > 1 else os.path.join(os.path.dirname(os.path.abspath(__file__)), "bare_server.py")
    dump = sys.argv[2] if len(sys.argv) > 2 else "stall-dump.txt"
    X = "some-caller-text"
    
    
    def rpc(i, method, params=None):
        d = {"jsonrpc": "2.0", "id": i, "method": method}
        if params is not None:
            d["params"] = params
        return json.dumps(d)
    
    
    msgs = [
        rpc(1, "initialize", {"protocolVersion": "2025-06-18", "capabilities": {}, "clientInfo": {"name": "d", "version": "0"}}),
        json.dumps({"jsonrpc": "2.0", "method": "notifications/initialized"}),
        "{not json " + X,                                                     # a malformed line
        rpc(2, X),                                                            # an unknown method
        rpc(3, "tools/call", {"name": X, "arguments": {}}),                   # an unknown tool
        rpc(4, "tools/call", {"name": "recall", "arguments": {X: X}}),        # an unknown argument
        json.dumps({"jsonrpc": "2.0", "id": 5, "method": "tools/call", "params": X}),  # params is a string
        json.dumps([X]),                                                      # a batch array
        rpc(6, "prompts/get", {"name": X}),                                   # an unknown prompt
        rpc(7, "resources/read", {"uri": "file:///" + X}),                    # an unknown resource
        rpc(999, "ping"),
    ]
    env = dict(os.environ, PYTHONFAULTHANDLER="1")
    p = subprocess.Popen([sys.executable, server], env=env, text=True,
                         stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    p.stdin.write("\n".join(msgs) + "\n")
    p.stdin.flush()                                                           # stdin stays open
    want, got = {3, 4, 6, 7, 999}, []
    sel = selectors.DefaultSelector()
    sel.register(p.stdout, selectors.EVENT_READ)
    deadline = time.monotonic() + 30
    while want and time.monotonic() < deadline:
        if sel.select(timeout=1):
            line = p.stdout.readline()
            if not line:
                break
            try:
                i = json.loads(line).get("id")
            except (ValueError, AttributeError):
                i = "?"
            got.append(i)
            want.discard(i)
    if want:
        p.send_signal(signal.SIGABRT)
        _, err = p.communicate(timeout=30)
        with open(dump, "w") as fh:
            fh.write(err)
        print("STALL: no response for", sorted(want), "| got", got, "| stacks in", dump)
        sys.exit(1)
    p.stdin.close()
    p.communicate(timeout=60)
    print("OK: got", got)
    load.sh
    #!/bin/bash
    # Eight drivers at once pinned to four CPUs, five rounds (40 runs). Each stall leaves its stack dump in OUT.
    # Usage: bash load.sh [python] [out dir] [cpu list]
    PY=${1:-python3}; OUT=${2:-./load-out}; CPUS=${3:-0-3}; HERE=$(cd "$(dirname "$0")" && pwd)
    mkdir -p "$OUT"
    for round in 1 2 3 4 5; do
      for k in 1 2 3 4 5 6 7 8; do
        taskset -c "$CPUS" "$PY" "$HERE/drive.py" "$HERE/bare_server.py" "$OUT/dump-$round-$k.txt" > "$OUT/run-$round-$k.out" 2>&1 &
      done
      wait
    done
    grep -h . "$OUT"/run-*.out | cut -d: -f1 | sort | uniq -c

    What the four stall dumps show:

    • In every dump, the main thread is in selectors.select under the asyncio loop's _run_once, and no Python request-handler frame is on any thread's stack.
    • The two AnyIO worker threads:
      • In two dumps, both workers are idle in queue.get.
      • In one dump, one worker is idle in queue.get. The other is at anyio/_backends/_asyncio.py:1100 (result = context.run(func, *args)) with no Python frame above it, so it is inside a C call. stdio_server reads stdin through anyio.wrap_file, which runs readline in a worker thread, so this is consistent with a pending stdin read. That last part is my inference; the dump doesn't show it.
      • In one dump, one worker's frame was unreadable (threading.py ... in RLock, then <invalid frame>), and the other is in queue.get.

    I can share the raw dumps if they help.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions