modelcontextprotocol / modelcontextprotocol/python-sdk

RequestResponder.__exit__ leaks CancelledError on cancelled request, killing the stdio receive loop

Đang mở
#2,610 3 bình luận 0 reaction 0 người được giao Xem trên GitHub

Chưa có ai nhận issue này.

bug needs confirmation P2 potentially close
Ngôn ngữ chính
Python
Star
24.3k
Fork
4k
Merge trung bình
1 ngày 1 giờ
Pull request đã merge (30 ngày)
31

Mô tả

Summary

When a client sends notifications/cancelled for an in-flight request handled over stdio, the server's receive loop task group dies. The process stays alive but stops reading stdin, so every subsequent request hangs and the client eventually reports MCP error -32000: Connection closed. The bug is racy — it reproduces in roughly 40–80% of attempts depending on platform timing.

Affects: mcp 1.26.0 and 1.27.1 (latest at time of writing). Confirmed with FastMCP 3.1.x and the in-tree stdio server.

Reproduction

A standalone subprocess test is in mlorentedev/hive tests/test_transport_recovery.py. The relevant flow:

  1. initialize → ack
  2. notifications/initialized
  3. tools/call id=2
  4. notifications/cancelled for requestId=2 (within a few ms of step 3)
  5. Receive: {"id": 2, "error": {"code": 0, "message": "Request cancelled"}} ← OK
  6. tools/call id=3
  7. No response. Server is alive but proc.stdout.readline() hangs.

Root cause

mcp.shared.session.RequestResponder.__exit__:

def __exit__(self, exc_type, exc_val, exc_tb):
    try:
        if self._completed:
            self._on_complete(self)
    finally:
        self._entered = False
        ...
        self._cancel_scope.__exit__(exc_type, exc_val, exc_tb)  # ← (A)

When notifications/cancelled arrives, RequestResponder.cancel() calls self._cancel_scope.cancel() and sends the error response. The handler task catches the CancelledError in mcp/server/lowlevel/server.py (around line 766) and returns. The with responder: block then exits with exc_type=None while the cancel scope is still in cancelled state — at line (A), anyio's CancelScope.__exit__ re-raises CancelledError.

That exception bubbles up to:

async with anyio.create_task_group() as tg:
    async for message in session.incoming_messages:
        tg.start_soon(self._handle_message, ...)

…in Server._run. anyio task groups cancel all sibling tasks and propagate the cancellation. The receive loop is one of those sibling tasks, so it dies.

Suggested fix

Swallow the spurious cancellation when the responder has already sent its response:

def __exit__(self, exc_type, exc_val, exc_tb):
    try:
        if self._completed:
            self._on_complete(self)
    finally:
        self._entered = False
        if not self._cancel_scope:
            raise RuntimeError("No active cancel scope")
        try:
            self._cancel_scope.__exit__(exc_type, exc_val, exc_tb)
        except BaseException as exc:
            if self._completed and isinstance(exc, anyio.get_cancelled_exc_class()):
                # cancel() already sent the error response — the scope's
                # re-raised cancellation is spurious.
                return
            raise

Mirrors what we ship in hive src/hive/_compat.py.

Workaround used downstream

We monkey-patch RequestResponder.__exit__ at import time. The patch is self-gated (only fires when _completed=True AND the leaking exception is anyio.get_cancelled_exc_class()), so it stays inert once a fix lands upstream.

Environment

  • Reproduced on Windows 11 (mcp 1.26.0, 1.27.1) and via Claude Code as the host.
  • Tracked downstream in mlorentedev/hive#75.
  • Regression test passes 5/5 with the patch applied on Python 3.12; fails 2/5 — 4/5 without it.
  • Python 3.13 appears to have additional uncancel semantics that the patch does not yet fully cover — verification in progress.

Hướng dẫn đóng góp

Mở hướng dẫn đóng góp

Bắt đầu từ đâu

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. 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.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. Mở pull request có tham chiếu số hiệu của issue.

Hướng nghiên cứu

Bắt đầu tại mcp.shared.session.RequestResponder.exit và kiểm tra phần xử lý việc hủy xung quanh mcp/server/lowlevel/server.py, gần dòng 766. Tái hiện bằng tests/test_transport_recovery.py, sau đó xác minh rằng việc hủy một yêu cầu stdio vẫn tạo ra phản hồi lỗi của nó và một yêu cầu tiếp theo nhận được phản hồi mà không làm vòng lặp nhận dừng lại.

Do mô hình lập chỉ mục viết ra từ nội dung của issue.

Đánh giá

Công nghệ
python
Lĩnh vực
api, backend
Loại issue
Lỗi
Độ khó
3/5
Thời gian dự kiến
1-2 ngày
Mức độ hoạt động
Ít trao đổi
Độ rõ ràng
Đặc tả rõ ràng
Mức phù hợp với người mới
68/100

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.