@@ -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 :
0 commit comments