Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 15 additions & 2 deletions src/mcp/shared/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,16 +108,29 @@ def __exit__(
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: TracebackType | None,
) -> None:
) -> bool | None:
"""Exit the context manager, performing cleanup and notifying completion."""
suppress = False
try:
if self._completed:
self._on_complete(self)
finally:
self._entered = False
if not self._cancel_scope: # pragma: no cover
raise RuntimeError("No active cancel scope")
self._cancel_scope.__exit__(exc_type, exc_val, exc_tb)
try:
suppress = self._cancel_scope.__exit__(exc_type, exc_val, exc_tb)
except BaseException as exc:
if (
self._completed
and self._cancel_scope.cancel_called
and isinstance(exc, anyio.get_cancelled_exc_class())
):
suppress = True
else:
raise

return suppress

async def respond(self, response: SendResultT | ErrorData) -> None:
"""Send a response for this request.
Expand Down
88 changes: 88 additions & 0 deletions tests/shared/test_session.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from typing import Any, cast

import anyio
import pytest

Expand All @@ -23,6 +25,11 @@
)


class _DummySession:
async def _send_response(self, request_id: int | str, response: ClientResult | ErrorData) -> None:
pass


@pytest.mark.anyio
async def test_in_flight_requests_cleared_after_completion():
"""Verify that _in_flight is empty after all requests complete."""
Expand Down Expand Up @@ -98,6 +105,87 @@ async def make_request(client: Client):
await ev_cancelled.wait()


@pytest.mark.anyio
async def test_request_responder_suppresses_completed_cancellation():
"""A request-local cancellation should not leak out after cancel() responds."""

completed: list[RequestResponder[ServerRequest, ClientResult]] = []
responder = RequestResponder[ServerRequest, ClientResult](
request_id=1,
request_meta=None,
request=types.PingRequest(),
session=cast(Any, _DummySession()),
on_complete=completed.append,
)

with responder:
await responder.cancel()
await anyio.sleep(0)

assert completed == [responder]


@pytest.mark.anyio
async def test_request_responder_ignores_late_completed_cancellation():
"""Some backends can surface cancellation while leaving an already-cancelled scope."""

class _CancelScope:
cancel_called = True

def __exit__(
self,
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: object,
) -> bool:
raise anyio.get_cancelled_exc_class()

completed: list[RequestResponder[ServerRequest, ClientResult]] = []
responder = RequestResponder[ServerRequest, ClientResult](
request_id=1,
request_meta=None,
request=types.PingRequest(),
session=cast(Any, _DummySession()),
on_complete=completed.append,
)
responder._entered = True
responder._completed = True
responder._cancel_scope = cast(Any, _CancelScope())

assert responder.__exit__(None, None, None) is True
assert completed == [responder]


@pytest.mark.anyio
async def test_request_responder_reraises_unexpected_exit_error():
"""Unexpected cancel scope errors should still propagate."""

class _CancelScope:
cancel_called = False

def __exit__(
self,
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: object,
) -> bool:
raise RuntimeError("boom")

responder = RequestResponder[ServerRequest, ClientResult](
request_id=1,
request_meta=None,
request=types.PingRequest(),
session=cast(Any, _DummySession()),
on_complete=lambda _: None,
)
responder._entered = True
responder._completed = True
responder._cancel_scope = cast(Any, _CancelScope())

with pytest.raises(RuntimeError, match="boom"):
responder.__exit__(None, None, None)


@pytest.mark.anyio
async def test_response_id_type_mismatch_string_to_int():
"""Test that responses with string IDs are correctly matched to requests sent with
Expand Down
Loading