Skip to content

Commit 1a51fdd

Browse files
authored
Python: fix(mcp): name the real error when a cancel scope masks MCP init failures (#7704)
* Python: fix(mcp): name the real error when a cancel scope masks MCP init failures When the MCP client stack cancels (e.g. an HTTP 401 from the server during session creation), anyio surfaces a bare CancelledError and the wrap sites reported 'Cancelled via cancel scope ...' as the failure. Unwrap single-member exception groups and __cause__/__context__ chains when composing the ToolException message so the real error is named. Genuine caller-driven cancellations still propagate unchanged and bare cancellations keep their own message. Fixes #7699 * Python: fix: name the close-time failure when MCP initialize cancels bare * Python: test: resolve ExceptionGroup compatibly
1 parent c79718f commit 1a51fdd

2 files changed

Lines changed: 181 additions & 21 deletions

File tree

‎python/packages/core/agent_framework/_mcp.py‎

Lines changed: 83 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -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

‎python/packages/core/tests/core/test_mcp.py‎

Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@
3333
from agent_framework._mcp import (
3434
MCPTool,
3535
_build_prefixed_mcp_name,
36+
_describe_error,
3637
_get_input_model_from_mcp_prompt,
3738
_normalize_additional_tool_argument_names,
3839
_normalize_mcp_name,
@@ -3737,6 +3738,103 @@ async def test_connect_cancelled_error_during_session_creation_includes_exceptio
37373738
assert "cancel scope detail" in str(exc_info.value)
37383739

37393740

3741+
# Tests for _describe_error helper (cancel-scope / exception-group unmasking)
3742+
3743+
3744+
def test_describe_error_keeps_plain_exception_message():
3745+
assert _describe_error(RuntimeError("boom")) == "boom"
3746+
3747+
3748+
@pytest.mark.skipif(sys.version_info < (3, 11), reason="ExceptionGroup is Python >= 3.11")
3749+
def test_describe_error_unwraps_single_member_exception_group():
3750+
import builtins
3751+
3752+
exception_group_type = getattr(builtins, "ExceptionGroup", None)
3753+
if exception_group_type is None:
3754+
pytest.skip("ExceptionGroup is not available on this Python version")
3755+
3756+
real = RuntimeError("401 Client Error: Unauthorized")
3757+
group = exception_group_type("unhandled errors in a TaskGroup", [real])
3758+
assert _describe_error(group) == "401 Client Error: Unauthorized"
3759+
3760+
3761+
def test_describe_error_unmasks_cancel_scope_via_context():
3762+
real = RuntimeError("401 Client Error: Unauthorized")
3763+
masked = asyncio.CancelledError("Cancelled via cancel scope")
3764+
masked.__context__ = real
3765+
assert _describe_error(masked) == "401 Client Error: Unauthorized"
3766+
3767+
3768+
def test_describe_error_keeps_bare_cancellation():
3769+
assert _describe_error(asyncio.CancelledError("Cancelled via cancel scope")) == "Cancelled via cancel scope"
3770+
3771+
3772+
async def test_connect_cancelled_error_unmasks_inner_auth_failure():
3773+
"""A 401 swallowed by the MCP client's cancel scope must be named in the ToolException."""
3774+
tool = MCPStreamableHTTPTool(name="test", url="http://example.com")
3775+
3776+
mock_transport = (Mock(), Mock())
3777+
mock_context_manager = Mock()
3778+
mock_context_manager.__aenter__ = AsyncMock(return_value=mock_transport)
3779+
mock_context_manager.__aexit__ = AsyncMock(return_value=None)
3780+
tool.get_mcp_client = Mock(return_value=mock_context_manager) # type: ignore[method-assign]
3781+
3782+
real = RuntimeError("401 Client Error: Unauthorized")
3783+
masked = asyncio.CancelledError("Cancelled via cancel scope")
3784+
masked.__context__ = real
3785+
3786+
with patch("mcp.client.session.ClientSession") as mock_session_class:
3787+
mock_session_class.return_value.__aenter__ = AsyncMock(side_effect=masked)
3788+
mock_session_class.return_value.__aexit__ = AsyncMock(return_value=None)
3789+
3790+
with pytest.raises(ToolException) as exc_info:
3791+
await tool.connect()
3792+
3793+
message = str(exc_info.value)
3794+
assert "Failed to create MCP session" in message
3795+
assert "401 Client Error: Unauthorized" in message
3796+
assert "Cancelled via cancel scope" not in message
3797+
3798+
3799+
@pytest.mark.skipif(sys.version_info < (3, 11), reason="ExceptionGroup is Python >= 3.11")
3800+
async def test_connect_bare_cancel_names_cleanup_error_from_exit_stack():
3801+
"""The reported 401 path: initialize() raises a bare CancelledError and the
3802+
real HTTP failure only surfaces from the exit-stack close. The ToolException
3803+
must name that close-time error, not the cancellation."""
3804+
import builtins
3805+
3806+
exception_group_type = getattr(builtins, "ExceptionGroup", None)
3807+
if exception_group_type is None:
3808+
pytest.skip("ExceptionGroup is not available on this Python version")
3809+
3810+
tool = MCPStreamableHTTPTool(name="test", url="http://example.com")
3811+
3812+
mock_transport = (Mock(), Mock())
3813+
mock_context_manager = Mock()
3814+
mock_context_manager.__aenter__ = AsyncMock(return_value=mock_transport)
3815+
mock_context_manager.__aexit__ = AsyncMock(return_value=None)
3816+
tool.get_mcp_client = Mock(return_value=mock_context_manager) # type: ignore[method-assign]
3817+
3818+
cleanup_group = exception_group_type(
3819+
"unhandled errors in a TaskGroup", [RuntimeError("401 Client Error: Unauthorized")]
3820+
)
3821+
3822+
mock_session = Mock()
3823+
mock_session.initialize = AsyncMock(side_effect=asyncio.CancelledError("Cancelled via cancel scope"))
3824+
3825+
with patch("mcp.client.session.ClientSession") as mock_session_class:
3826+
mock_session_class.return_value.__aenter__ = AsyncMock(return_value=mock_session)
3827+
mock_session_class.return_value.__aexit__ = AsyncMock(side_effect=cleanup_group)
3828+
3829+
with pytest.raises(ToolException) as exc_info:
3830+
await tool.connect()
3831+
3832+
message = str(exc_info.value)
3833+
assert "MCP server failed to initialize" in message
3834+
assert "401 Client Error: Unauthorized" in message
3835+
assert "Cancelled via cancel scope" not in message
3836+
3837+
37403838
async def test_connect_cancelled_error_during_session_creation_logs_with_exc_info():
37413839
"""Test that CancelledError from session creation is logged with exc_info=True."""
37423840
tool = MCPStreamableHTTPTool(name="test", url="http://example.com")

0 commit comments

Comments
 (0)