Pipelined requests fail with -32602 (or overtake on_initialized) because notifications/initialized is spawned concurrently
Maintainer thường phản hồi trong vòng 1 ngày
Chưa có ai nhận issue này.
Đánh giá
- Độ khó
- 4/5
- Thời gian dự kiến
- 3-5 ngày
- Mức phù hợp với người mới
- 48/100
- Loại issue
- Lỗi
- Độ rõ ràng
- Đặc tả rõ ràng
- Mức độ hoạt động
- Sôi nổi
- Công nghệ
- python
- Lĩnh vực
- backend-api-design
Hướng nghiên cứu
Start by reading src/mcp/shared/jsonrpc_dispatcher.py around _dispatch_notification and src/mcp/server/runner.py at the cited inline_methods setup and _on_notify handler. Trace how notification dispatch interacts with middleware and initialization state, then inspect the related tests for pipelined messages. Done means subsequent frames on the same stream are handled only after notifications/initialized has committed its state and run its handler.
Do mô hình lập chỉ mục viết ra từ nội dung của issue.
Mô tả
Initial Checks
- I confirm that I'm using the newest release of my line (the latest 2.x, or the latest 1.x if I'm still on v1)
- I confirm that I searched for my issue in https://github.com/modelcontextprotocol/python-sdk/issues before opening this issue
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:
JSONRPCDispatcher._dispatch_notification(src/mcp/shared/jsonrpc_dispatcher.py:552, 567-570, 676) is synchronous, ignoresinline_methods, and unconditionally spawns a background task viaself._spawn(...).- In
ServerRunner._on_notify(src/mcp/server/runner.py:263-285),self.connection.initialized.set()runs inside_inner, which is wrapped byServer.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/initializedpath (explicitly supported by_replay_from_opening_requestinrunner.py:649-652andConnection.initialize_acceptedinconnection.py:335-337):- A pipelined
tools/listfails the init-gate with-32602 Invalid request parameters. - A pipelined
notifications/roots/list_changedis silently dropped atrunner.py:268-270(received before initialization).
- A pipelined
- Full handshake path (
initialize-> response ->notifications/initialized->tools/list):initializealready setsclient_paramsso the init-gate is open, buttools/liststill overtakesnotifications/initialized:connection.initialized.is_set()isFalseand thenotifications/initializedhandler has not run yet whentools/listexecutes.
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
-32602rejections on startup: on the barenotifications/initializedpath (supported inrunner.py:649-652andconnection.py:335-337), the firsttools/listcan overtakenotifications/initializedand fail the init-gate with-32602 Invalid request parameters. - Silent drop of initial client notifications: notifications such as
notifications/roots/list_changedarriving immediately after barenotifications/initializedare 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/initializedhandler can serve the firsttools/listbeforeon_initializedfinishes and whileconnection.initialized.is_set()is stillFalse. - 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)
- Ngôn ngữ chính
- Python
- Star
- 25k
- Fork
- 4.2k
- Merge trung bình
- 10 phút
- Pull request đã merge (30 ngày)
- 1
Chuẩn bị môi trường
- Không có Dockerfile hay tệp Docker Compose
- Có mẫu pull request
- Đọc hướng dẫn đóng góp
Bắt đầu từ đâu
- Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
- Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
- Fork repository và làm thay đổi trên một nhánh.
- Mở pull request có tham chiếu số hiệu của issue.
Issue khác của modelcontextprotocol/python-sdk
-
v2
Độ khó 1/5 Dưới một giờ Mức phù hợp với người mới 86/100
modelcontextprotocol/python-sdk#3978 · 2 bình luận ·
Maintainer thường phản hồi trong vòng 1 ngày
-
Client serves cached tools after its context exits with an exceptionCó thể đã có người làm @jonxsong đã nhận 1 ngày trước. Đang mở
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 65/100
modelcontextprotocol/python-sdk#3968 · 1 bình luận ·
Maintainer thường phản hồi trong vòng 1 ngày
-
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 85/100
modelcontextprotocol/python-sdk#3957 ·
Maintainer thường phản hồi trong vòng 1 ngày
-
v2
Độ khó 1/5 Dưới một giờ Mức phù hợp với người mới 91/100
modelcontextprotocol/python-sdk#3934 · 2 bình luận ·
Maintainer thường phản hồi trong vòng 1 ngày
-
bug v1
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 79/100
modelcontextprotocol/python-sdk#3929 · 2 bình luận ·
Maintainer thường phản hồi trong vòng 1 ngày
Tất cả issue của modelcontextprotocol/python-sdk
Issue tương tự
-
soup prune-prompt exits 1 after writing its output on a file over 100,000 rows, and reports a capped row count otherwiseCó thể đã có người làm @abdulwaarith0 đã nhận hôm nay. Đang mởneeds-triage
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 84/100
MakazhanAlpamys/Soup#3690 · 1 bình luận ·
Maintainer thường phản hồi trong vòng 1 ngày
-
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 78/100
Maintainer thường phản hồi trong vòng 1 ngày
-
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 78/100
-
bug data-types native-format
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 65/100
ClickHouse/clickhouse-connect#1320 ·
Maintainer thường phản hồi trong vòng 1 ngày
-
Public benchmark import end-to-end test fails when the test stack's worker runs the parity jobĐang mởaccepted
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 68/100
future-agi/future-agi#6392 ·
Maintainer thường phản hồi trong vòng 1 ngày