← Back to Pull requests

fix(sdk-mcp): release pending request id when unsent send is cancelled #1562

Open
unknown opened this pull request with 359 lines diff across 4 files
View on GitHub
unknown unknown commented on Nov 20, 2026 03:49 UTC
Author

Fixes #1557

Symptom & Repro


Cancelling SdkMcpBridge.handle() while _Session.submit() is blocked in await self._to_server.send(parsed) (for example while a server lifespan is still starting up) removes the waiting send from the AnyIO memory stream, but leaves its _PendingResponse entry permanently registered in _Session._pending. Once startup completes, reusing that JSON-RPC request ID fails with Exception: Request id <id> is already in flight.

Root Cause


_Session.submit() registered _PendingResponse before awaiting _to_server.send(), and only cleared it on ClosedResourceError / BrokenResourceError. As noted in #1557, a blanket except BaseException: cleanup is unsafe because anyio's receive_nowait() moves a waiting sender's message into the stream buffer and sets send_event before returning; a raw asyncio.Task.cancel() in that scheduling gap still raises CancelledError out of send() even though the server now owns the queued message.

Fix


  • Wrapped the server's inbound stream in _InboundReceiveStream (preserving both mcp 1.x MemoryObjectReceiveStream methods/sync-cm and mcp 2.x ContextReceiveStream.last_context via __getattr__) to track actual message consumption (_consume) and filter out aborted handoff items on both receive() and receive_nowait().

  • Serialized outbound client-to-server sends through _send_lock in _send_tracked() across both submit() and _answer_server_request(), using an O(1) FIFO tombstone queue (_InboundState.aborted) only when recv_count changed while a send was in flight:

  • - Cancelled while waiting before admission or when recv_count did not advance: immediately removes tracking and resolves pending (unsent) so the ID can be reused safely.
    - Cancelled during an ambiguous buffer-handoff bump before consumption: marks the item aborted so _InboundReceiveStream drops it instead of executing it, while sweeping stale aborted entries as subsequent tracked messages/ping replies arrive.
    - Cancelled after consumption (attempt.delivered == True): preserves the existing invariant that the ID remains reserved until the server responds.
  • Added deterministic regression tests covering both asyncio and trio in tests/test_sdk_mcp_integration.py (barrier slow-start cancellation, delivered-request ID retention, raw asyncio.Task.cancel() buffer-handoff drop, batch-cancel idle cleanup, ping-interleaved tombstone sweep, and MemoryObjectReceiveStream compatibility).
  • Verification


  • Pre-fix TDD: unsent-cancellation cases failed on origin/main (69846cd) across both asyncio and trio.

  • Post-fix:

  • - uv run pytest: 1769 passed, 6 skipped
    - uv run ruff check src/ tests/: passed
    - uv run ruff format --check src/ tests/: 65 files already formatted
    - uv run mypy src/: no issues found in 27 source files

    Diff: 359 lines (+269 / -90) across 4 files Reviewer: tonydzi Review duration: 15533m
    All Vouch review confidence checks passed
    Residual risk 0.24 = Change Risk (0.43) × (1 − Review Confidence (0.43)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.43 · 359 lines diff across 4 files
    0.43
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.02 · 1 substantive comment(s)
    0.02
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    42%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.352
    Shallow Review Depth shallow_review_depth
    0.344
    Real PR Conversation Timeline
    1 comments
    "Review active on #1562"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 43.0% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 42.6% (MEDIUM) · Higher = larger blast radius
    42.6%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 43.0% · Lower = rushed or shallow review
    43.0%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 24.3% · Safe to merge
    24.3%