Skip to content

Commit dfb3686

Browse files
committed
fix sending cancel
1 parent f9598ad commit dfb3686

File tree

2 files changed

+19
-19
lines changed

2 files changed

+19
-19
lines changed

src/mcp/shared/session.py

Lines changed: 18 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -256,11 +256,25 @@ async def send_request(
256256
elif self._session_read_timeout_seconds is not None:
257257
timeout = self._session_read_timeout_seconds.total_seconds()
258258

259-
response_or_error = None
260-
261259
try:
262-
with anyio.fail_after(timeout):
260+
with anyio.fail_after(timeout) as scope:
263261
response_or_error = await response_stream_reader.receive()
262+
263+
if scope.cancel_called:
264+
with anyio.CancelScope(shield=True):
265+
notification = CancelledNotification(
266+
method="notifications/cancelled",
267+
params=CancelledNotificationParams(
268+
requestId=request_id,
269+
reason="cancelled"
270+
)
271+
)
272+
await self._send_notification_internal(notification, request_id)
273+
274+
raise McpError(
275+
ErrorData(code=32601, message="request cancelled")
276+
)
277+
264278
except TimeoutError:
265279
raise McpError(
266280
ErrorData(
@@ -272,21 +286,7 @@ async def send_request(
272286
),
273287
)
274288
)
275-
except anyio.get_cancelled_exc_class():
276-
with anyio.CancelScope(shield=True):
277-
notification = CancelledNotification(
278-
method="notifications/cancelled",
279-
params=CancelledNotificationParams(
280-
requestId=request_id,
281-
reason="cancelled"
282-
)
283-
)
284-
await self._send_notification_internal(notification, request_id, )
285-
286-
if response_or_error is None:
287-
raise McpError(
288-
ErrorData(code=32601, message="request cancelled")
289-
)
289+
290290
if isinstance(response_or_error, JSONRPCError):
291291
raise McpError(response_or_error.error)
292292
else:

tests/shared/test_streamable_http.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -989,7 +989,7 @@ async def test_streamablehttp_client_session_termination(
989989
# Attempt to make a request after termination
990990
with pytest.raises(
991991
McpError,
992-
match="request cancelled",
992+
match="Session terminated",
993993
):
994994
await session.list_tools()
995995

0 commit comments

Comments
 (0)