Skip to content

Sending cancellation notification to server based on client anyio.CancelScope status #628

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 34 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 23 commits
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
f9598ad
attempt to support cancelation
davemssavage May 4, 2025
dfb3686
fix sending cancel
davemssavage May 4, 2025
abda067
add decorator for handling cancelation
davemssavage May 4, 2025
24553c6
fix capitalisation on error message
davemssavage May 4, 2025
fe49931
try to check notification event received
davemssavage May 4, 2025
efd0ffd
fix test
davemssavage May 4, 2025
1364b7a
fix debug message
davemssavage May 4, 2025
17ae44c
prevent cancel on intialisation as per https://modelcontextprotocol.i…
davemssavage May 4, 2025
06f4b3c
remove unused imports
davemssavage May 4, 2025
07e1a52
fixed long line
davemssavage May 4, 2025
92f806b
fixed long line
davemssavage May 4, 2025
e46c693
updates from ruff format
davemssavage May 4, 2025
2a24e0c
removed dev print statements committed by mistake
davemssavage May 4, 2025
87722f8
add constant for request cancelled and use it in case of cancelled task
davemssavage May 4, 2025
f0782d2
fix long line
davemssavage May 4, 2025
a0164f9
fix import order
davemssavage May 4, 2025
bf220d5
add assert that cancel scope triggered on server, add comments for re…
davemssavage May 5, 2025
45ac52a
trivial update to comment capitalisation
davemssavage May 5, 2025
8b7f1cd
simplify test code
davemssavage May 5, 2025
ac4b822
add tests to assert cancellable=False behaves as expected
davemssavage May 5, 2025
d86b4a5
tidy up ruff check
davemssavage May 5, 2025
6f4ae44
ruff format update
davemssavage May 5, 2025
11d2e52
fixed test description
davemssavage May 5, 2025
235df35
use defined types in decorator
davemssavage May 5, 2025
f96aaa5
Add docstring info for cancellable and add TODO note for initialised …
davemssavage May 5, 2025
bd73448
set read_timeout_seconds to avoid test blocking for ever in case some…
davemssavage May 5, 2025
3817fe2
remove unnecessary shielded cancel scope
davemssavage May 5, 2025
2fd27a2
whitespace
davemssavage May 5, 2025
2e86d32
clarified doc string comment
davemssavage May 6, 2025
1039b99
fixed doc string and added comment on internal notification method
davemssavage May 6, 2025
b926970
Merge branch 'main' into cancellation
davemssavage May 9, 2025
cf1bb2b
merge from upstream main
davemssavage May 17, 2025
39f7739
ignore type warning for internal use of send_notification
davemssavage May 17, 2025
598756d
Merge branch 'main' into cancellation
davemssavage May 24, 2025
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
3 changes: 3 additions & 0 deletions src/mcp/client/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,7 @@ async def initialize(self) -> types.InitializeResult:
)
),
types.InitializeResult,
cancellable=False,
)

if result.protocolVersion not in SUPPORTED_PROTOCOL_VERSIONS:
Expand Down Expand Up @@ -259,6 +260,7 @@ async def call_tool(
name: str,
arguments: dict[str, Any] | None = None,
read_timeout_seconds: timedelta | None = None,
cancellable: bool = True,
) -> types.CallToolResult:
"""Send a tools/call request."""

Expand All @@ -271,6 +273,7 @@ async def call_tool(
),
types.CallToolResult,
request_read_timeout_seconds=read_timeout_seconds,
cancellable=cancellable,
)

async def list_prompts(self) -> types.ListPromptsResult:
Expand Down
14 changes: 14 additions & 0 deletions src/mcp/server/lowlevel/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -441,6 +441,20 @@ async def handler(req: types.ProgressNotification):

return decorator

def cancel_notification(self):
def decorator(
func: Callable[[str | int, str | None], Awaitable[None]],
):
logger.debug("Registering handler for CancelledNotification")

async def handler(req: types.CancelledNotification):
await func(req.params.requestId, req.params.reason)

self.notification_handlers[types.CancelledNotification] = handler
return func

return decorator

def completion(self):
"""Provides completions for prompts and resource templates"""

Expand Down
62 changes: 49 additions & 13 deletions src/mcp/shared/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@
from mcp.shared.exceptions import McpError
from mcp.shared.message import MessageMetadata, ServerMessageMetadata, SessionMessage
from mcp.types import (
REQUEST_CANCELLED,
CancelledNotification,
CancelledNotificationParams,
ClientNotification,
ClientRequest,
ClientResult,
Expand All @@ -33,6 +35,12 @@
SendRequestT = TypeVar("SendRequestT", ClientRequest, ServerRequest)
SendResultT = TypeVar("SendResultT", ClientResult, ServerResult)
SendNotificationT = TypeVar("SendNotificationT", ClientNotification, ServerNotification)
SendNotificationInternalT = TypeVar(
"SendNotificationInternalT",
CancelledNotification,
ClientNotification,
ServerNotification,
)
ReceiveRequestT = TypeVar("ReceiveRequestT", ClientRequest, ServerRequest)
ReceiveResultT = TypeVar("ReceiveResultT", bound=BaseModel)
ReceiveNotificationT = TypeVar(
Expand Down Expand Up @@ -214,6 +222,7 @@ async def send_request(
result_type: type[ReceiveResultT],
request_read_timeout_seconds: timedelta | None = None,
metadata: MessageMetadata = None,
cancellable: bool = True,
) -> ReceiveResultT:
"""
Sends a request and wait for a response. Raises an McpError if the
Expand Down Expand Up @@ -254,20 +263,40 @@ async def send_request(
elif self._session_read_timeout_seconds is not None:
timeout = self._session_read_timeout_seconds.total_seconds()

try:
with anyio.fail_after(timeout):
response_or_error = await response_stream_reader.receive()
except TimeoutError:
raise McpError(
ErrorData(
code=httpx.codes.REQUEST_TIMEOUT,
message=(
f"Timed out while waiting for response to "
f"{request.__class__.__name__}. Waited "
f"{timeout} seconds."
),
with anyio.CancelScope(shield=not cancellable):
Copy link
Author

@davemssavage davemssavage May 5, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Alternative to this might be to separate client cancelation and server cancelation, e.g. client can be cancelled and server cancellation event is only set if a flag such as 'propagate_client_cancelation_to_server' (shorter names available) is set on the request.

try:
with anyio.fail_after(timeout) as scope:
response_or_error = await response_stream_reader.receive()

if scope.cancel_called:
with anyio.CancelScope(shield=True):
notification = CancelledNotification(
method="notifications/cancelled",
params=CancelledNotificationParams(
requestId=request_id, reason="cancelled"
),
)
await self._send_notification_internal(
notification, request_id
)

raise McpError(
ErrorData(
code=REQUEST_CANCELLED, message="Request cancelled"
)
)

except TimeoutError:
raise McpError(
ErrorData(
code=httpx.codes.REQUEST_TIMEOUT,
message=(
f"Timed out while waiting for response to "
f"{request.__class__.__name__}. Waited "
f"{timeout} seconds."
),
)
)
)

if isinstance(response_or_error, JSONRPCError):
raise McpError(response_or_error.error)
Expand All @@ -283,6 +312,13 @@ async def send_notification(
self,
notification: SendNotificationT,
related_request_id: RequestId | None = None,
) -> None:
await self._send_notification_internal(notification, related_request_id)

async def _send_notification_internal(
self,
notification: SendNotificationInternalT,
related_request_id: RequestId | None = None,
) -> None:
"""
Emits a notification, which is a one-way message that does not expect
Expand Down
1 change: 1 addition & 0 deletions src/mcp/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,7 @@ class JSONRPCResponse(BaseModel):
METHOD_NOT_FOUND = -32601
INVALID_PARAMS = -32602
INTERNAL_ERROR = -32603
REQUEST_CANCELLED = -32604


class ErrorData(BaseModel):
Expand Down
126 changes: 94 additions & 32 deletions tests/shared/test_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,6 @@
from mcp.shared.exceptions import McpError
from mcp.shared.memory import create_connected_server_and_client_session
from mcp.types import (
CancelledNotification,
CancelledNotificationParams,
ClientNotification,
ClientRequest,
EmptyResult,
)

Expand Down Expand Up @@ -46,11 +42,11 @@ async def test_in_flight_requests_cleared_after_completion(
@pytest.mark.anyio
async def test_request_cancellation():
"""Test that requests can be cancelled while in-flight."""
# The tool is already registered in the fixture

ev_tool_called = anyio.Event()
ev_tool_cancelled = anyio.Event()
ev_cancelled = anyio.Event()
request_id = None
ev_cancel_notified = anyio.Event()

# Start the request in a separate task so we can cancel it
def make_server() -> Server:
Expand All @@ -59,14 +55,24 @@ def make_server() -> Server:
# Register the tool handler
@server.call_tool()
async def handle_call_tool(name: str, arguments: dict | None) -> list:
nonlocal request_id, ev_tool_called
nonlocal ev_tool_called, ev_tool_cancelled
if name == "slow_tool":
request_id = server.request_context.request_id
ev_tool_called.set()
await anyio.sleep(10) # Long enough to ensure we can cancel
return []
with anyio.CancelScope():
try:
await anyio.sleep(10) # Long enough to ensure we can cancel
return []
except anyio.get_cancelled_exc_class() as err:
ev_tool_cancelled.set()
raise err

raise ValueError(f"Unknown tool: {name}")

@server.cancel_notification()
async def handle_cancel(requestId: str | int, reason: str | None):
nonlocal ev_cancel_notified
ev_cancel_notified.set()

# Register the tool so it shows up in list_tools
@server.list_tools()
async def handle_list_tools() -> list[types.Tool]:
Expand All @@ -80,20 +86,10 @@ async def handle_list_tools() -> list[types.Tool]:

return server

async def make_request(client_session):
async def make_request(client_session: ClientSession):
nonlocal ev_cancelled
try:
await client_session.send_request(
ClientRequest(
types.CallToolRequest(
method="tools/call",
params=types.CallToolRequestParams(
name="slow_tool", arguments={}
),
)
),
types.CallToolResult,
)
await client_session.call_tool("slow_tool")
pytest.fail("Request should have been cancelled")
except McpError as e:
# Expected - request was cancelled
Expand All @@ -110,17 +106,83 @@ async def make_request(client_session):
with anyio.fail_after(1): # Timeout after 1 second
await ev_tool_called.wait()

# Send cancellation notification
assert request_id is not None
await client_session.send_notification(
ClientNotification(
CancelledNotification(
method="notifications/cancelled",
params=CancelledNotificationParams(requestId=request_id),
)
)
)
# Cancel the task via task group
tg.cancel_scope.cancel()

# Give cancellation time to process
with anyio.fail_after(1):
await ev_cancelled.wait()

# Check server cancel notification received
with anyio.fail_after(1):
await ev_cancel_notified.wait()

# Give cancellation time to process on server
with anyio.fail_after(1):
await ev_tool_cancelled.wait()


@pytest.mark.anyio
async def test_request_cancellation_uncancellable():
"""Test that asserts a call with cancellable=False is not cancelled on
server when cancel scope on client is set."""

ev_tool_called = anyio.Event()
ev_tool_commplete = anyio.Event()
ev_cancelled = anyio.Event()

# Start the request in a separate task so we can cancel it
def make_server() -> Server:
server = Server(name="TestSessionServer")

# Register the tool handler
@server.call_tool()
async def handle_call_tool(name: str, arguments: dict | None) -> list:
nonlocal ev_tool_called, ev_tool_commplete
if name == "slow_tool":
ev_tool_called.set()
with anyio.CancelScope():
with anyio.fail_after(10): # Long enough to ensure we can cancel
await ev_cancelled.wait()
ev_tool_commplete.set()
return []

raise ValueError(f"Unknown tool: {name}")

# Register the tool so it shows up in list_tools
@server.list_tools()
async def handle_list_tools() -> list[types.Tool]:
return [
types.Tool(
name="slow_tool",
description="A slow tool that takes 10 seconds to complete",
inputSchema={},
)
]

return server

async def make_request(client_session: ClientSession):
nonlocal ev_cancelled
try:
await client_session.call_tool("slow_tool", cancellable=False)
except McpError:
pytest.fail("Request should not have been cancelled")

async with create_connected_server_and_client_session(
make_server()
) as client_session:
async with anyio.create_task_group() as tg:
tg.start_soon(make_request, client_session)

# Wait for the request to be in-flight
with anyio.fail_after(1): # Timeout after 1 second
await ev_tool_called.wait()

# Cancel the task via task group
tg.cancel_scope.cancel()
ev_cancelled.set()

# Check server completed regardless
with anyio.fail_after(1):
await ev_tool_commplete.wait()
Loading