Skip to content

Pipelined requests fail with -32602 (or overtake on_initialized) because notifications/initialized is spawned concurrently #3952

Backlog

Description

@Svliverse-1

Initial Checks

Release line

2.x (current stable)

Description

Description

In v2 runner.py, initialize is handled inline in JSONRPCDispatcher specifically so pipelined requests do not hit the init-gate before initialization commits (src/mcp/server/runner.py:493-496, 733):

inline_methods=frozenset({"initialize"}),

notifications/initialized does not have this guarantee:

  1. JSONRPCDispatcher._dispatch_notification (src/mcp/shared/jsonrpc_dispatcher.py:552, 567-570, 676) is synchronous, ignores inline_methods, and unconditionally spawns a background task via self._spawn(...).
  2. In ServerRunner._on_notify (src/mcp/server/runner.py:263-285), self.connection.initialized.set() runs inside _inner, which is wrapped by Server.middleware.

If any middleware performs async I/O (e.g. audit logging, auth, metrics), the read loop immediately dispatches the next frame concurrently before notifications/initialized reaches runner.py:267 (self.connection.initialized.set()) and its registered handler.

Impact

  • Bare notifications/initialized path (explicitly supported by _replay_from_opening_request in runner.py:649-652 and Connection.initialize_accepted in connection.py:335-337):
    • A pipelined tools/list fails the init-gate with -32602 Invalid request parameters.
    • A pipelined notifications/roots/list_changed is silently dropped at runner.py:268-270 (received before initialization).
  • Full handshake path (initialize -> response -> notifications/initialized -> tools/list):
    • initialize already sets client_params so the init-gate is open, but tools/list still overtakes notifications/initialized: connection.initialized.is_set() is False and the notifications/initialized handler has not run yet when tools/list executes.

Minimal Reproduction

import asyncio
import json
import tempfile
import uuid
from pathlib import Path

from mcp_types import JSONRPCError, JSONRPCNotification, JSONRPCRequest, ListToolsResult, NotificationParams
from pydantic import BaseModel

from mcp.client._memory import InMemoryTransport
from mcp.server import Server
from mcp.shared.message import SessionMessage


class Empty(BaseModel):
    pass


def write_audit(d, method):
    f = d / f"{uuid.uuid4().hex}.jsonl"
    f.write_text(json.dumps({"method": method}) + "\n", encoding="utf-8")


def make_server(d):
    state = {
        "inited": False,
        "roots": False,
        "saw_init": None,
        "ev_init": asyncio.Event(),
        "ev_roots": asyncio.Event(),
    }
    srv = Server("demo")

    async def audit_mw(ctx, call_next):
        try:
            await asyncio.to_thread(write_audit, d, ctx.method)
            return await call_next(ctx)
        finally:
            if ctx.method == "notifications/initialized":
                state["ev_init"].set()
            elif ctx.method == "notifications/roots/list_changed":
                state["ev_roots"].set()

    async def on_init(ctx, params):
        state["inited"] = True

    async def on_roots(ctx, params):
        state["roots"] = True

    async def on_tools(ctx, params):
        state["saw_init"] = state["inited"]
        return ListToolsResult(tools=[])

    srv.middleware.append(audit_mw)
    srv.add_notification_handler("notifications/initialized", NotificationParams, on_init)
    srv.add_notification_handler("notifications/roots/list_changed", NotificationParams, on_roots)
    srv.add_request_handler("tools/list", Empty, on_tools)
    return srv, state


async def main():
    init_params = {
        "protocolVersion": "2025-11-25",
        "capabilities": {},
        "clientInfo": {"name": "client", "version": "1.0"},
    }

    with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp:
        d = Path(tmp)

        # Case 1: bare notifications/initialized + tools/list
        for i in range(1, 101):
            srv, st = make_server(d)
            async with InMemoryTransport(srv) as (r, w):
                await w.send(SessionMessage(JSONRPCNotification(jsonrpc="2.0", method="notifications/initialized")))
                await w.send(SessionMessage(JSONRPCRequest(jsonrpc="2.0", id=1, method="tools/list", params={})))
                res = await asyncio.wait_for(r.receive(), 5)
                await asyncio.wait_for(st["ev_init"].wait(), 5)
            if isinstance(res, SessionMessage) and isinstance(res.message, JSONRPCError):
                print(f"case 1 (iter {i}): tools/list rejected -> {res.message.error.code} {res.message.error.message}")
                break

        # Case 2: bare notifications/initialized + notifications/roots/list_changed
        for i in range(1, 101):
            srv, st = make_server(d)
            async with InMemoryTransport(srv) as (r, w):
                await w.send(SessionMessage(JSONRPCNotification(jsonrpc="2.0", method="notifications/initialized")))
                await w.send(SessionMessage(JSONRPCNotification(jsonrpc="2.0", method="notifications/roots/list_changed")))
                await w.send(SessionMessage(JSONRPCRequest(jsonrpc="2.0", id=1, method="tools/list", params={})))
                await asyncio.wait_for(r.receive(), 5)
                await asyncio.wait_for(asyncio.gather(st["ev_init"].wait(), st["ev_roots"].wait()), 5)
            if not st["roots"]:
                print(f"case 2 (iter {i}): notifications/roots/list_changed dropped")
                break

        # Case 3: full handshake + pipelined tools/list
        for i in range(1, 101):
            srv, st = make_server(d)
            async with InMemoryTransport(srv) as (r, w):
                await w.send(SessionMessage(JSONRPCRequest(jsonrpc="2.0", id=1, method="initialize", params=init_params)))
                await asyncio.wait_for(r.receive(), 5)
                await w.send(SessionMessage(JSONRPCNotification(jsonrpc="2.0", method="notifications/initialized")))
                await w.send(SessionMessage(JSONRPCRequest(jsonrpc="2.0", id=2, method="tools/list", params={})))
                await asyncio.wait_for(r.receive(), 5)
                await asyncio.wait_for(st["ev_init"].wait(), 5)
            if st["saw_init"] is False:
                print(f"case 3 (iter {i}): tools/list ran before on_init")
                break


asyncio.run(main())

Observed output (reproduces within ~1-10 iterations in plain asyncio):

case 1 (iter 2): tools/list rejected -> -32602 Invalid request parameters
case 2 (iter 1): notifications/roots/list_changed dropped
case 3 (iter 3): tools/list ran before on_init

Expected Behavior

notifications/initialized should commit initialization state (and ideally run inline in the read loop, matching initialize) before subsequent frames on the same stream are dispatched.

Production Impact

Any MCP server using async Server.middleware (e.g. audit logging, auth checks, telemetry, DB/cache lookups) is exposed to intermittent startup failures when clients send notifications/initialized followed immediately by their first request or notification:

  • Spurious -32602 rejections on startup: on the bare notifications/initialized path (supported in runner.py:649-652 and connection.py:335-337), the first tools/list can overtake notifications/initialized and fail the init-gate with -32602 Invalid request parameters.
  • Silent drop of initial client notifications: notifications such as notifications/roots/list_changed arriving immediately after bare notifications/initialized are silently discarded (received before initialization) without returning an error to the client.
  • Uninitialized per-session state on full handshake: servers that initialize session state (permissions, client config, dynamic tools) inside the notifications/initialized handler can serve the first tools/list before on_initialized finishes and while connection.initialized.is_set() is still False.
  • Non-deterministic under load: the race rarely surfaces in local testing without I/O latency, but triggers intermittently in production whenever middleware yields on real I/O.

Suggested Fix

Support inline_methods in JSONRPCDispatcher._dispatch_notification (make it async and await matching notification methods inline instead of calling self._spawn), and include "notifications/initialized" in inline_methods in serve_handshake_loop (runner.py:496) and serve_dual_era_loop (runner.py:733).

Python & MCP Python SDK

Python 3.12.10
mcp: main @ 77001c96 (2.3.1.dev20+77001c96)

Activity

  1. apoorv-shrivastav commented on Dec 2, 2026

    @apoorv-shrivastav

    I can reproduce this on main (77001c9). A deterministic version: one middleware that awaits on notifications/initialized (stand-in for audit/auth I/O), then pipeline notifications/initialized, notifications/roots/list_changed and tools/list over InMemoryTransport. It fails every time: tools/list gets -32602 and the roots handler never runs.

    One concern with the suggested fix: making notifications/initialized inline also parks the read loop while the user's handler runs. A handler that awaits the client then deadlocks, which the inline_methods docstring already warns about. I tried it by emulating the inline path with an on_initialized that calls ctx.session.list_roots(): today it gets the roots back, inline it hangs until my 3s timeout. Calling the client from on_initialized (roots, sampling, elicitation) seems common enough that I'd avoid that.

    A narrower option: the dispatcher already has on_notify_intercept, which runs synchronously in receive order. ServerRunner could pass one that validates notifications/initialized the same way _on_notify does and sets connection.initialized there, without consuming the notification, so middleware and the handler still run spawned as today. That needs ~15 lines plus the two dispatcher.run(...) call sites (serve_connection and _serve_legacy_stream). With it, the reporter's first two cases and my deterministic repro pass, and the existing runner tests and coverage stay green.

    It doesn't cover the third case (a request running before a slow on_initialized handler has finished). I'm not sure that ordering should be guaranteed, since it can't be without the inline deadlock risk. Is "initialized is committed in wire order, handlers run concurrently" the intended contract?

    If you'd take an outside PR for this, I have the change and a regression test ready.

    AI assistance was used to investigate this and draft the comment.

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