@@ -418,6 +418,52 @@ def _should_propagate_cancelled_error(ex: BaseException) -> bool:
418418 return task is not None and task .cancelling () > 0
419419
420420
421+ _MAX_ERROR_UNWRAP_HOPS = 10 # pathological chains only; normally 0-2 hops
422+
423+
424+ def _describe_error (ex : BaseException ) -> str :
425+ """Return the most specific message in *ex*'s chain, unmasking cancel scopes.
426+
427+ AnyIO cancel scopes and task groups surface internal failures as a bare
428+ ``CancelledError`` ("Cancelled via cancel scope ...") or a single-member
429+ ``ExceptionGroup``; the real error (e.g. an HTTP 401 from the MCP server)
430+ sits in ``__cause__``/``__context__`` or the group's single leaf. Follow
431+ those links so the reported message names the actual failure. A genuine
432+ bare cancellation keeps its own message.
433+ """
434+ current = ex
435+ for _ in range (_MAX_ERROR_UNWRAP_HOPS ):
436+ # Group membership is gated on the type name (not the attribute) so a
437+ # non-group exception that happens to carry .exceptions is not unwrapped.
438+ inner = (
439+ getattr (current , "exceptions" , None )
440+ if type (current ).__name__ in ("ExceptionGroup" , "BaseExceptionGroup" )
441+ else None
442+ )
443+ if inner is not None and len (inner ) == 1 :
444+ current = inner [0 ]
445+ continue
446+ cause = current .__cause__ or current .__context__
447+ if cause is None or cause is current :
448+ break
449+ if isinstance (current , asyncio .CancelledError ) and isinstance (cause , asyncio .CancelledError ):
450+ break # cancel-of-cancel carries no information
451+ current = cause
452+ return str (current ) or repr (current )
453+
454+
455+ def _describe_with_cleanup (ex : BaseException , cleanup_error : BaseException | None ) -> str :
456+ """Describe *ex*, preferring the cleanup failure when *ex* is a bare cancellation.
457+
458+ A bare CancelledError from the task group carries no detail of its own; the
459+ real failure (e.g. an HTTP 401 from the MCP server) can surface only when
460+ the exit stack is closed, so the close's leaf is the better message then.
461+ """
462+ if isinstance (ex , asyncio .CancelledError ) and cleanup_error is not None :
463+ return _describe_error (cleanup_error )
464+ return _describe_error (ex )
465+
466+
421467# region: MCP Plugin
422468
423469
@@ -1236,8 +1282,13 @@ async def _run_on_lifecycle_owner(
12361282 await queue .put ((action , reset , load_configured , future ))
12371283 await future
12381284
1239- async def _safe_close_exit_stack (self ) -> None :
1240- """Safely close the exit stack, handling unexpected cleanup failures."""
1285+ async def _safe_close_exit_stack (self ) -> BaseException | None :
1286+ """Safely close the exit stack, handling unexpected cleanup failures.
1287+
1288+ Returns the swallowed cleanup failure, if any. A caller that only saw a
1289+ bare cancellation from the task group can still name the real cause the
1290+ close surfaced (e.g. the HTTP status error of a rejected handshake).
1291+ """
12411292 try :
12421293 await self ._exit_stack .aclose ()
12431294 except RuntimeError as e :
@@ -1248,26 +1299,33 @@ async def _safe_close_exit_stack(self) -> None:
12481299 "This indicates MCP lifecycle ownership was lost. Error: %s" ,
12491300 e ,
12501301 )
1251- else :
1252- raise
1253- except asyncio .CancelledError :
1302+ return e
1303+ raise
1304+ except asyncio .CancelledError as e :
12541305 logger .warning ("Could not cleanly close MCP exit stack because the lifecycle owner task was cancelled." )
1306+ return e
12551307 except Exception as e :
12561308 if type (e ).__name__ == "ExceptionGroup" :
12571309 logger .warning ("Could not cleanly close MCP exit stack due to cleanup error group. Error: %s" , e )
1258- else :
1259- raise
1310+ return e
1311+ raise
1312+ return None
12601313
1261- async def _close_and_check_cancelled (self , ex : BaseException ) -> bool :
1262- """Close the exit stack and return True if *ex* is a genuine task cancellation.
1314+ async def _close_and_check_cancelled (self , ex : BaseException ) -> tuple [ bool , BaseException | None ] :
1315+ """Close the exit stack and report whether *ex* is a genuine task cancellation.
12631316
1264- Callers should immediately re-raise when this returns True::
1317+ Returns ``(should_reraise, cleanup_error)``. Callers should immediately
1318+ re-raise when the first element is True::
12651319
1266- if await self._close_and_check_cancelled(ex):
1320+ cancelled, cleanup_error = await self._close_and_check_cancelled(ex)
1321+ if cancelled:
12671322 raise
1323+
1324+ The second element carries the failure swallowed while closing, so an
1325+ error path holding only a bare cancellation can still describe it.
12681326 """
1269- await self ._safe_close_exit_stack ()
1270- return _should_propagate_cancelled_error (ex )
1327+ cleanup_error = await self ._safe_close_exit_stack ()
1328+ return _should_propagate_cancelled_error (ex ), cleanup_error
12711329
12721330 def _reset_session_state (self ) -> None :
12731331 self ._server_capabilities = None
@@ -1332,13 +1390,14 @@ async def _connect_on_owner(self, *, reset: bool = False, load_configured: bool
13321390 # instead of wrapping it in ToolException. On Python < 3.11, task.cancelling()
13331391 # is unavailable so MCP-internal CancelledErrors cannot be distinguished from
13341392 # caller-driven cancellation; they are wrapped as ToolException in that case.
1335- if await self ._close_and_check_cancelled (ex ):
1393+ cancelled , cleanup_error = await self ._close_and_check_cancelled (ex )
1394+ if cancelled :
13361395 raise
13371396 command = getattr (self , "command" , None )
13381397 if command :
1339- error_msg = f"Failed to start MCP server '{ command } ': { ex } "
1398+ error_msg = f"Failed to start MCP server '{ command } ': { _describe_with_cleanup ( ex , cleanup_error ) } "
13401399 else :
1341- error_msg = f"Failed to connect to MCP server: { ex } "
1400+ error_msg = f"Failed to connect to MCP server: { _describe_with_cleanup ( ex , cleanup_error ) } "
13421401 # CancelledError is a BaseException (not Exception) on Python >= 3.8, so
13431402 # inner_exception=None and ToolException.__init__ won't log exc_info.
13441403 if isinstance (ex , asyncio .CancelledError ):
@@ -1374,9 +1433,10 @@ async def _connect_on_owner(self, *, reset: bool = False, load_configured: bool
13741433 )
13751434 )
13761435 except (Exception , asyncio .CancelledError ) as ex :
1377- if await self ._close_and_check_cancelled (ex ):
1436+ cancelled , cleanup_error = await self ._close_and_check_cancelled (ex )
1437+ if cancelled :
13781438 raise
1379- session_error_msg = f"Failed to create MCP session: { ex } "
1439+ session_error_msg = f"Failed to create MCP session: { _describe_with_cleanup ( ex , cleanup_error ) } "
13801440 if isinstance (ex , asyncio .CancelledError ):
13811441 logger .debug (session_error_msg , exc_info = True )
13821442 raise ToolException (
@@ -1389,16 +1449,18 @@ async def _connect_on_owner(self, *, reset: bool = False, load_configured: bool
13891449 init_span .set_attribute (OtelAttr .MCP_PROTOCOL_VERSION , initialize_result .protocolVersion )
13901450 self ._set_server_capabilities (getattr (initialize_result , "capabilities" , None ))
13911451 except (Exception , asyncio .CancelledError ) as ex :
1392- if await self ._close_and_check_cancelled (ex ):
1452+ cancelled , cleanup_error = await self ._close_and_check_cancelled (ex )
1453+ if cancelled :
13931454 raise
13941455 # Provide context about initialization failure
13951456 command = getattr (self , "command" , None )
13961457 if command :
13971458 args_str = " " .join (getattr (self , "args" , []))
13981459 full_command = f"{ command } { args_str } " .strip ()
1399- error_msg = f"MCP server '{ full_command } ' failed to initialize: { ex } "
1460+ described = _describe_with_cleanup (ex , cleanup_error )
1461+ error_msg = f"MCP server '{ full_command } ' failed to initialize: { described } "
14001462 else :
1401- error_msg = f"MCP server failed to initialize: { ex } "
1463+ error_msg = f"MCP server failed to initialize: { _describe_with_cleanup ( ex , cleanup_error ) } "
14021464 if isinstance (ex , asyncio .CancelledError ):
14031465 logger .debug (error_msg , exc_info = True )
14041466 raise ToolException (error_msg , inner_exception = ex if isinstance (ex , Exception ) else None ) from ex
0 commit comments