Framework for orchestrating role-playing, autonomous AI agents. By fostering collaborative intelligence, CrewAI empowers agents to work together seamlessly, tackling complex tasks.
[OSS-137] Report MCP HTTP auth failures instead of cancelled connections (#7067)
Vidit Ostwal7c23857aedca
diff --git a/lib/crewai/src/crewai/events/event_listener.py b/lib/crewai/src/crewai/events/event_listener.pyindex 291d067a9..95ec236a9 100644--- a/lib/crewai/src/crewai/events/event_listener.py+++ b/lib/crewai/src/crewai/events/event_listener.py@@ -919,6 +919,7 @@ class EventListener(BaseEventListener):event.transport_type,event.error,event.error_type,+ event.status_code,)self._telemetry.feature_usage_span("mcp:connection_failed")diff --git a/lib/crewai/src/crewai/events/types/mcp_events.py b/lib/crewai/src/crewai/events/types/mcp_events.pyindex c9278dec0..ff8ca86ef 100644--- a/lib/crewai/src/crewai/events/types/mcp_events.py+++ b/lib/crewai/src/crewai/events/types/mcp_events.py@@ -49,6 +49,7 @@ class MCPConnectionFailedEvent(MCPEvent):type: Literal["mcp_connection_failed"] = "mcp_connection_failed"error: strerror_type: str | None = None # "timeout", "authentication", "network", etc.+ status_code: int | None = Nonestarted_at: datetime | None = Nonefailed_at: datetime | None = Nonediff --git a/lib/crewai/src/crewai/events/utils/console_formatter.py b/lib/crewai/src/crewai/events/utils/console_formatter.pyindex 4aefb8e47..ada09a3d8 100644--- a/lib/crewai/src/crewai/events/utils/console_formatter.py+++ b/lib/crewai/src/crewai/events/utils/console_formatter.py@@ -1665,6 +1665,7 @@ To enable tracing, do any one of these:transport_type: str | None = None,error: str = "",error_type: str | None = None,+ status_code: int | None = None,) -> None:"""Handle MCP connection failed event."""if not self.verbose:@@ -1683,6 +1684,10 @@ To enable tracing, do any one of these:content.append("Transport: ", style="white")content.append(f"{transport_type}\n", style="red")+ if status_code is not None:+ content.append("HTTP Status: ", style="white")+ content.append(f"{status_code}\n", style="red")+if error_type:content.append("Error Type: ", style="white")content.append(f"{error_type}\n", style="red")diff --git a/lib/crewai/src/crewai/mcp/client.py b/lib/crewai/src/crewai/mcp/client.pyindex 6c311ccf4..b84165fb5 100644--- a/lib/crewai/src/crewai/mcp/client.py+++ b/lib/crewai/src/crewai/mcp/client.py@@ -27,6 +27,14 @@ from crewai.events.types.mcp_events import (MCPToolExecutionFailedEvent,MCPToolExecutionStartedEvent,)+from crewai.mcp.exceptions import (+ MCPConnectionError,+ error_for_status,+ error_type_for_status,+ find_http_status,+ find_transport_failure,+ tool_execution_error_type,+)from crewai.mcp.transports.base import BaseTransportfrom crewai.mcp.transports.http import HTTPTransportfrom crewai.mcp.transports.sse import SSETransport@@ -148,13 +156,18 @@ class MCPClient:Self for method chaining.Raises:- ConnectionError: If connection fails.+ MCPAuthenticationError: If the server refused the connection with+ an authentication status.+ MCPHTTPError: If the server refused the connection with any other+ HTTP status.+ MCPConnectionError: If the connection failed for any other reason.ImportError: If MCP SDK not available."""if self.connected:return self- server_name, server_url, transport_type = self._get_server_info()+ server_info = self._get_server_info()+ server_name, server_url, transport_type = server_infois_reconnect = self._was_connectedstarted_at = datetime.now()@@ -184,40 +197,13 @@ class MCPClient:await self._exit_stack.enter_async_context(self._session)- # MCP protocol requires session.initialize() before any other request- try:- await asyncio.wait_for(- self._session.initialize(),- timeout=self.connect_timeout,- )- except asyncio.CancelledError:- # If initialization was cancelled (e.g., event loop closing),- # cleanup and re-raise - don't suppress cancellation- await self._cleanup_on_error()- raise- except BaseExceptionGroup as eg:- # Handle exception groups from anyio task groups- # Extract the actual meaningful error (not GeneratorExit)- actual_error = None- for exc in eg.exceptions:- if isinstance(exc, Exception) and not isinstance(- exc, GeneratorExit- ):- # Check if it's an HTTP error (like 401)- error_msg = str(exc).lower()- if "401" in error_msg or "unauthorized" in error_msg:- actual_error = exc- break- if "cancel scope" not in error_msg and "task" not in error_msg:- actual_error = exc- break-- await self._cleanup_on_error()- if actual_error:- raise ConnectionError(- f"Failed to connect to MCP server: {actual_error}"- ) from actual_error- raise ConnectionError(f"Failed to connect to MCP server: {eg}") from eg+ # MCP protocol requires session.initialize() before any other request.+ # Failures propagate to the handlers below, which unwind the transport+ # once and inspect what that unwinding reveals about the cause.+ await asyncio.wait_for(+ self._session.initialize(),+ timeout=self.connect_timeout,+ )self._initialized = Trueself._was_connected = True@@ -253,7 +239,12 @@ class MCPClient:)raise ImportError(error_msg) from eexcept asyncio.TimeoutError as e:- await self._cleanup_on_error()+ cleanup_error = await self._cleanup_on_error()+ status_code = find_http_status(e, cleanup_error)+ if status_code is not None:+ raise self._report_connection_failure(+ server_info, started_at, status_code=status_code+ ) from eerror_msg = f"MCP connection timed out after {self.connect_timeout} seconds. The server may be slow or unreachable."self._emit_connection_failed(server_name,@@ -263,10 +254,21 @@ class MCPClient:"timeout",started_at,)- raise ConnectionError(error_msg) from e- except asyncio.CancelledError:- # Re-raise cancellation - don't suppress it- await self._cleanup_on_error()+ raise MCPConnectionError(error_msg) from e+ except asyncio.CancelledError as e:+ # A failing transport cancels this coroutine, so cancellation alone+ # says nothing. Unwinding the transport is what reveals the cause.+ cleanup_error = await self._cleanup_on_error()+ status_code = find_http_status(e, cleanup_error)+ if status_code is not None:+ raise self._report_connection_failure(+ server_info, started_at, status_code=status_code+ ) from e+ if (failure := find_transport_failure(cleanup_error)) is not None:+ raise self._report_connection_failure(+ server_info, started_at, error=failure+ ) from failure+ # Nothing failed, so this is a real cancellation: never swallow it.self._emit_connection_failed(server_name,server_url,@@ -276,54 +278,59 @@ class MCPClient:started_at,)raise- except BaseExceptionGroup as eg:- # Handle exception groups from anyio task groups at outer level- actual_error = None- for exc in eg.exceptions:- if isinstance(exc, Exception) and not isinstance(exc, GeneratorExit):- error_msg = str(exc).lower()- if "401" in error_msg or "unauthorized" in error_msg:- actual_error = exc- break- if "cancel scope" not in error_msg and "task" not in error_msg:- actual_error = exc- break-- await self._cleanup_on_error()- error_type = (- "authentication"- if actual_error- and (- "401" in str(actual_error).lower()- or "unauthorized" in str(actual_error).lower()- )- else "network"- )- error_msg = str(actual_error) if actual_error else str(eg)- self._emit_connection_failed(- server_name,- server_url,- transport_type,- error_msg,- error_type,- started_at,- )- if actual_error:- raise ConnectionError(- f"Failed to connect to MCP server: {actual_error}"- ) from actual_error- raise ConnectionError(f"Failed to connect to MCP server: {eg}") from eg- except Exception as e:- await self._cleanup_on_error()+ except (BaseExceptionGroup, Exception) as e:+ cleanup_error = await self._cleanup_on_error()+ status_code = find_http_status(e, cleanup_error)+ if status_code is not None:+ raise self._report_connection_failure(+ server_info, started_at, status_code=status_code+ ) from e+ failure = find_transport_failure(e, cleanup_error) or e+ raise self._report_connection_failure(+ server_info, started_at, error=failure+ ) from e++ def _report_connection_failure(+ self,+ server_info: tuple[str, str | None, str | None],+ started_at: datetime,+ *,+ error: BaseException | None = None,+ status_code: int | None = None,+ ) -> MCPConnectionError:+ """Build a connection failure, emit the event, and return it to raise."""+ if status_code is not None:+ failure = error_for_status(status_code)+ error_msg = str(failure)+ error_type = error_type_for_status(status_code) or "network"+ elif error is not None and isinstance(error, MCPConnectionError):+ failure = error+ error_msg = str(error)error_type = (- "authentication"- if "401" in str(e).lower() or "unauthorized" in str(e).lower()+ error_type_for_status(error.status_code) or "network"+ if error.status_code is not Noneelse "network")- self._emit_connection_failed(- server_name, server_url, transport_type, str(e), error_type, started_at- )- raise ConnectionError(f"Failed to connect to MCP server: {e}") from e+ status_code = error.status_code+ elif error is not None:+ error_msg = f"Failed to connect to MCP server: {error}"+ error_type = "network"+ status_code = find_http_status(error)+ failure = MCPConnectionError(error_msg, status_code=status_code)+ else:+ raise ValueError("Either error or status_code must be provided")++ server_name, server_url, transport_type = server_info+ self._emit_connection_failed(+ server_name,+ server_url,+ transport_type,+ error_msg,+ error_type,+ started_at,+ status_code=status_code,+ )+ return failuredef _emit_connection_failed(self,@@ -333,6 +340,7 @@ class MCPClient:error: str,error_type: str,started_at: datetime,+ status_code: int | None = None,) -> None:"""Emit connection failed event."""failed_at = datetime.now()@@ -344,19 +352,31 @@ class MCPClient:transport_type=transport_type,error=error,error_type=error_type,+ status_code=status_code,started_at=started_at,failed_at=failed_at,),)- async def _cleanup_on_error(self) -> None:- """Cleanup resources when an error occurs during connection."""+ async def _cleanup_on_error(self) -> BaseException | None:+ """Cleanup resources when an error occurs during connection.++ Returns:+ The exception raised while unwinding the transport, if any. The+ transport reports the server's refusal here rather than to the+ coroutine that was waiting, so the caller inspects this for an+ HTTP status instead of treating it as a cleanup problem.+ """try:await self._exit_stack.aclose()-- except Exception as e:- # Best effort cleanup - ignore all other errors- raise RuntimeError(f"Error during MCP client cleanup: {e}") from e+ except asyncio.CancelledError as e:+ return e+ except (Exception, BaseExceptionGroup) as e:+ # Groups are caught explicitly because one holding only BaseExceptions+ # is not an Exception, yet can still carry the server's refusal.+ return e+ else:+ return Nonefinally:self._session = Noneself._initialized = False@@ -369,7 +389,11 @@ class MCPClient:try:await self._exit_stack.aclose()- except Exception as e:+ except asyncio.CancelledError:+ raise+ except MCPConnectionError:+ raise+ except (Exception, BaseExceptionGroup) as e:raise RuntimeError(f"Error during MCP client disconnect: {e}") from efinally:self._session = None@@ -520,12 +544,6 @@ class MCPClient:return tool_resultexcept Exception as e:failed_at = datetime.now()- error_type = (- "timeout"- if isinstance(e, (asyncio.TimeoutError, ConnectionError))- and "timeout" in str(e).lower()- else "server_error"- )crewai_event_bus.emit(self,MCPToolExecutionFailedEvent(@@ -535,7 +553,7 @@ class MCPClient:tool_name=tool_name,tool_args=cleaned_arguments,error=str(e),- error_type=error_type,+ error_type=tool_execution_error_type(e),started_at=started_at,failed_at=failed_at,),@@ -717,9 +735,17 @@ class MCPClient:raise ConnectionError(last_error) from eexcept Exception as e:+ if isinstance(e, MCPConnectionError):+ raise++ status_code = find_http_status(e)+ if status_code is not None and (+ error_type_for_status(status_code) == "authentication"+ ):+ raise error_for_status(status_code, detail=str(e)) from e+error_str = str(e).lower()- # Classify errors as retryable or non-retryableif "authentication" in error_str or "unauthorized" in error_str:raise ConnectionError(f"Authentication failed: {e}") from ediff --git a/lib/crewai/src/crewai/mcp/exceptions.py b/lib/crewai/src/crewai/mcp/exceptions.pynew file mode 100644index 000000000..1fd1dff07--- /dev/null+++ b/lib/crewai/src/crewai/mcp/exceptions.py@@ -0,0 +1,271 @@+"""Exceptions and error classification for MCP client connections.++When an MCP server refuses a connection with an HTTP status, the status is+observed by the HTTP client but the exception carrying it is raised inside the+transport's anyio task group. The awaiting coroutine therefore sees only a+bare ``CancelledError``, and the real cause surfaces separately as an+exception group once the transport unwinds. ``find_http_status`` recovers the+status from either shape so callers can report it instead of guessing.+"""++from __future__ import annotations++import asyncio+from collections.abc import Iterator+from http import HTTPStatus+import sys+from typing import NoReturn+++if sys.version_info >= (3, 11):+ from builtins import BaseExceptionGroup+else:+ from exceptiongroup import BaseExceptionGroup+++AUTH_STATUS_CODES = frozenset({401, 403})++# Substrings identifying a RuntimeError that describes the unwinding itself.+# anyio and async generators report these while a task group is torn down, so+# they say nothing about why the connection failed.+_TEARDOWN_MARKERS = (+ "cancel scope",+ "async generator",+ "athrow",+ "asend",+ "different task",+ "event loop is closed",+)+++def _status_phrase(status_code: int) -> str:+ """Render a status code with its reason phrase, e.g. ``401 Unauthorized``."""+ try:+ return f"{status_code} {HTTPStatus(status_code).phrase}"+ except ValueError:+ return str(status_code)+++class MCPConnectionError(ConnectionError):+ """Raised when a connection to an MCP server cannot be established.++ Subclasses ``ConnectionError`` so that existing callers handling+ connection failures continue to work unchanged.+ """++ def __init__(self, message: str, status_code: int | None = None) -> None:+ """Create an MCPConnectionError.++ Args:+ message: Description of the failure.+ status_code: HTTP status the server responded with, when known.+ """+ super().__init__(message)+ self.status_code = status_code+++class MCPAuthenticationError(MCPConnectionError):+ """Raised when an MCP server rejects the request's credentials."""++ def __init__(self, status_code: int, detail: str | None = None) -> None:+ """Create an MCPAuthenticationError.++ Args:+ status_code: HTTP status the server responded with (401 or 403).+ detail: Optional underlying error text to append.+ """+ message = (+ f"MCP server refused the connection with HTTP {_status_phrase(status_code)}. "+ "This is an authentication failure - check the credentials sent in the "+ "server's headers."+ )+ if detail:+ message = f"{message} Server response: {detail}"+ super().__init__(message, status_code=status_code)+++class MCPHTTPError(MCPConnectionError):+ """Raised when an MCP server refuses the connection with a non-auth status."""++ def __init__(self, status_code: int, detail: str | None = None) -> None:+ """Create an MCPHTTPError.++ Args:+ status_code: HTTP status the server responded with.+ detail: Optional underlying error text to append.+ """+ message = f"MCP server refused the connection with HTTP {_status_phrase(status_code)}."+ if detail:+ message = f"{message} Server response: {detail}"+ super().__init__(message, status_code=status_code)+++def error_for_status(status_code: int, detail: str | None = None) -> MCPConnectionError:+ """Build the exception matching an HTTP status.++ Args:+ status_code: HTTP status the server responded with.+ detail: Optional underlying error text to append.++ Returns:+ An ``MCPAuthenticationError`` for 401/403, otherwise an ``MCPHTTPError``.+ """+ if status_code in AUTH_STATUS_CODES:+ return MCPAuthenticationError(status_code, detail)+ return MCPHTTPError(status_code, detail)+++def error_type_for_status(status_code: int | None) -> str | None:+ """Map an HTTP status to the ``error_type`` reported on MCP events.++ Args:+ status_code: HTTP status the server responded with, when known.++ Returns:+ ``"authentication"`` for 401/403, ``"http_error"`` for any other+ status, or ``None`` when no status was observed.+ """+ if status_code is None:+ return None+ return "authentication" if status_code in AUTH_STATUS_CODES else "http_error"+++def tool_execution_error_type(exc: BaseException) -> str:+ """Map an exception to ``MCPToolExecutionFailedEvent.error_type``.++ Args:+ exc: The exception raised while executing an MCP tool.++ Returns:+ One of ``"timeout"``, ``"authentication"``, ``"validation"``,+ ``"http_error"``, or ``"server_error"``.+ """+ if isinstance(exc, asyncio.TimeoutError):+ return "timeout"+ if isinstance(exc, ConnectionError) and (+ "timeout" in str(exc).lower() or "timed out" in str(exc).lower()+ ):+ return "timeout"+ if isinstance(exc, ValueError):+ return "validation"+ if isinstance(exc, MCPConnectionError) and exc.status_code is not None:+ return error_type_for_status(exc.status_code) or "server_error"+ status_code = find_http_status(exc)+ if status_code is not None:+ return error_type_for_status(status_code) or "server_error"+ error_str = str(exc).lower()+ if "authentication" in error_str or "unauthorized" in error_str:+ return "authentication"+ return "server_error"+++def raise_connection_failure(message: str, *errors: BaseException | None) -> NoReturn:+ """Raise a typed MCP connection error when an HTTP status is known.++ Args:+ message: Fallback message when no HTTP status can be recovered.+ *errors: Exceptions observed while connecting or unwinding.++ Raises:+ MCPConnectionError: When an HTTP status was observed.+ ConnectionError: When no HTTP status was observed.+ """+ present = [error for error in errors if error is not None]+ if not present:+ raise ConnectionError(message)++ for error in present:+ if isinstance(error, MCPConnectionError):+ raise error++ primary = present[0]+ status_code = find_http_status(*present)+ if status_code is not None:+ raise error_for_status(status_code, detail=str(primary)) from primary+ if isinstance(primary, asyncio.CancelledError):+ failure = find_transport_failure(*present)+ if failure is not None:+ raise failure from primary+ raise ConnectionError(message) from primary+++def _leaves(exc: BaseException | None, seen: set[int]) -> Iterator[BaseException]:+ """Yield the individual exceptions reachable from *exc*.++ Exception groups are containers rather than causes, so their members are+ yielded in place of the group itself. ``__cause__`` and ``__context__`` are+ followed too, because the transport re-wraps failures while unwinding.++ Args:+ exc: Exception to traverse, or None.+ seen: Ids already visited, guarding against reference cycles.++ Yields:+ Each reachable exception that is not itself a group.+ """+ if exc is None or id(exc) in seen:+ return+ seen.add(id(exc))++ if isinstance(exc, BaseExceptionGroup):+ for nested in exc.exceptions:+ yield from _leaves(nested, seen)+ else:+ yield exc++ for linked in (exc.__cause__, exc.__context__):+ yield from _leaves(linked, seen)+++def _is_teardown_noise(exc: BaseException) -> bool:+ """Report whether *exc* describes unwinding rather than a failure."""+ if isinstance(exc, asyncio.CancelledError | GeneratorExit):+ return True+ if isinstance(exc, RuntimeError):+ message = str(exc).lower()+ return any(marker in message for marker in _TEARDOWN_MARKERS)+ return False+++def find_http_status(*errors: BaseException | None) -> int | None:+ """Search exceptions for an HTTP status reported by an MCP server.++ Args:+ *errors: Exceptions to search, in order of preference.++ Returns:+ The first HTTP status found, or ``None`` if none of the exceptions+ were caused by an HTTP status.+ """+ import httpx++ seen: set[int] = set()+ for error in errors:+ for exc in _leaves(error, seen):+ if isinstance(exc, MCPConnectionError) and exc.status_code is not None:+ return exc.status_code+ if isinstance(exc, httpx.HTTPStatusError):+ return exc.response.status_code+ return None+++def find_transport_failure(*errors: BaseException | None) -> BaseException | None:+ """Search exceptions for the one that explains why a connection failed.++ A failing transport cancels the coroutine that was waiting on it, so the+ cancellation reaching the caller is a symptom. The explanation is whichever+ reachable exception is not itself cancellation or teardown bookkeeping.++ Args:+ *errors: Exceptions to search, in order of preference.++ Returns:+ The first explanatory exception, or ``None`` when the exceptions+ describe only cancellation and teardown.+ """+ seen: set[int] = set()+ for error in errors:+ for exc in _leaves(error, seen):+ if not _is_teardown_noise(exc):+ return exc+ return Nonediff --git a/lib/crewai/src/crewai/mcp/tool_resolver.py b/lib/crewai/src/crewai/mcp/tool_resolver.pyindex cad33f4c1..29c2b031c 100644--- a/lib/crewai/src/crewai/mcp/tool_resolver.py+++ b/lib/crewai/src/crewai/mcp/tool_resolver.py@@ -12,10 +12,17 @@ from __future__ import annotationsimport asyncioimport contextvars+import sysimport timefrom typing import TYPE_CHECKING, Any, Final, castfrom urllib.parse import urlparse++if sys.version_info >= (3, 11):+ from builtins import BaseExceptionGroup+else:+ from exceptiongroup import BaseExceptionGroup+from crewai.mcp.client import MCPClientfrom crewai.mcp.config import (MCPServerConfig,@@ -23,6 +30,12 @@ from crewai.mcp.config import (MCPServerSSE,MCPServerStdio,)+from crewai.mcp.exceptions import (+ MCPConnectionError,+ error_for_status,+ find_http_status,+ raise_connection_failure,+)from crewai.mcp.transports.http import HTTPTransportfrom crewai.mcp.transports.sse import SSETransportfrom crewai.mcp.transports.stdio import StdioTransport@@ -271,6 +284,11 @@ class MCPToolResolver:return cast(list[BaseTool], tools)+ except MCPConnectionError as e:+ self._logger.log(+ "warning", f"Failed to connect to MCP server {server_url}: {e}"+ )+ raiseexcept Exception as e:self._logger.log("warning", f"Failed to connect to MCP server {server_url}: {e}"@@ -350,10 +368,23 @@ class MCPToolResolver:self._logger.log("error", f"Error during disconnect: {e}")return tools_list- except Exception as e:+ except (asyncio.CancelledError, Exception) as e:if discovery_client.connected:- await discovery_client.disconnect()- await asyncio.sleep(0.1)+ try:+ await discovery_client.disconnect()+ await asyncio.sleep(0.1)+ except Exception as disconnect_error:+ if isinstance(disconnect_error, MCPConnectionError):+ raise disconnect_error from e+ self._logger.log(+ "error", f"Error during disconnect: {disconnect_error}"+ )+ if isinstance(e, MCPConnectionError):+ raise+ if isinstance(e, asyncio.CancelledError):+ raise_connection_failure(+ f"Error during setup client and list tools: {e}", e+ )raise RuntimeError(f"Error during setup client and list tools: {e}") from e@@ -361,6 +392,12 @@ class MCPToolResolver:try:try:asyncio.get_running_loop()+ except RuntimeError:+ running_loop = False+ else:+ running_loop = True++ if running_loop:import concurrent.futuresctx = contextvars.copy_context()@@ -368,23 +405,17 @@ class MCPToolResolver:future = executor.submit(ctx.run, asyncio.run, _setup_client_and_list_tools())- tools_list = future.result()- except RuntimeError:+ try:+ tools_list = future.result()+ except (asyncio.CancelledError, Exception) as e:+ raise_connection_failure(+ f"Failed to get native MCP tools: {e}", e+ )+ else:try:tools_list = asyncio.run(_setup_client_and_list_tools())- except RuntimeError as e:- error_msg = str(e).lower()- if "cancel scope" in error_msg or "task" in error_msg:- raise ConnectionError(- "MCP connection failed due to event loop cleanup issues. "- "This may be due to authentication errors or server unavailability."- ) from e- raise- except asyncio.CancelledError as e:- raise ConnectionError(- "MCP connection was cancelled. This may indicate an authentication "- "error or server unavailability."- ) from e+ except (asyncio.CancelledError, Exception) as e:+ raise_connection_failure(f"Failed to get native MCP tools: {e}", e)if mcp_config.tool_filter:filtered_tools = []@@ -463,11 +494,13 @@ class MCPToolResolver:continuereturn cast(list[BaseTool], tools), []+ except (MCPConnectionError, ConnectionError):+ raiseexcept Exception as e:if discovery_client.connected:asyncio.run(discovery_client.disconnect())- raise RuntimeError(f"Failed to get native MCP tools: {e}") from e+ raise_connection_failure(f"Failed to get native MCP tools: {e}", e)@staticmethoddef _build_mcp_config_from_dict(@@ -519,6 +552,8 @@ class MCPToolResolver:schemas = asyncio.run(self._get_mcp_tool_schemas_async(server_params))_mcp_schema_cache[cache_key] = (schemas, current_time)return schemas+ except MCPConnectionError:+ raiseexcept Exception as e:self._logger.log("warning", f"Failed to get MCP tool schemas from {server_url}: {e}"@@ -583,11 +618,15 @@ class MCPToolResolver:True,)- except Exception as e:+ except (Exception, BaseExceptionGroup) as e:+ status_code = find_http_status(e)+ if status_code is not None:+ raise error_for_status(status_code, detail=str(e)) from e+ if isinstance(e, MCPConnectionError):+ raise+error_str = str(e).lower()- if "authentication" in error_str or "unauthorized" in error_str:- return None, f"Authentication failed for MCP server: {e!s}", Falseif "connection" in error_str or "network" in error_str:return None, f"Network connection failed: {e!s}", Trueif "json" in error_str or "parsing" in error_str:diff --git a/lib/crewai/src/crewai/mcp/transports/http.py b/lib/crewai/src/crewai/mcp/transports/http.pyindex 7b05ee78d..4468b5a44 100644--- a/lib/crewai/src/crewai/mcp/transports/http.py+++ b/lib/crewai/src/crewai/mcp/transports/http.py@@ -1,6 +1,8 @@"""HTTP and Streamable HTTP transport for MCP servers."""import asyncio+import contextlib+import loggingimport sysfrom typing import Any@@ -12,9 +14,18 @@ if sys.version_info >= (3, 11):else:from exceptiongroup import BaseExceptionGroup+from crewai.mcp.exceptions import (+ error_for_status,+ find_http_status,+ find_transport_failure,+ raise_connection_failure,+)from crewai.mcp.transports.base import BaseTransport, TransportType+logger = logging.getLogger(__name__)++class HTTPTransport(BaseTransport):"""HTTP/Streamable HTTP transport for connecting to remote MCP servers.@@ -58,6 +69,42 @@ class HTTPTransport(BaseTransport):"""Return the transport type."""return TransportType.STREAMABLE_HTTP if self.streamable else TransportType.HTTP+ async def _close_transport_context(+ self,+ exc: BaseException | None = None,+ ) -> BaseException | None:+ """Exit the streamable-HTTP context if one is pending."""+ context, self._transport_context = self._transport_context, None+ self._clear_streams()++ if context is None:+ return None++ exc_type = type(exc) if exc is not None else None+ exc_tb = exc.__traceback__ if exc is not None else None++ try:+ with contextlib.suppress(asyncio.CancelledError):+ await asyncio.sleep(0.1)+ await context.__aexit__(exc_type, exc, exc_tb)+ except asyncio.CancelledError as cancel_exc:+ return cancel_exc+ except (Exception, BaseExceptionGroup) as teardown_exc:+ return teardown_exc+ return None++ def _raise_teardown_failure(self, error: BaseException) -> None:+ """Raise a typed error when teardown reveals why the connection failed."""+ if (status_code := find_http_status(error)) is not None:+ raise error_for_status(status_code) from error+ failure = find_transport_failure(error)+ if failure is not None and not isinstance(failure, asyncio.CancelledError):+ raise failure from error+ if isinstance(error, asyncio.CancelledError):+ logger.debug("MCP HTTP transport teardown was cancelled")+ raise error+ logger.debug("Ignoring MCP HTTP transport teardown error: %s", error)+async def connect(self) -> Self:"""Establish HTTP connection to MCP server.@@ -65,7 +112,8 @@ class HTTPTransport(BaseTransport):Self for method chaining.Raises:- ConnectionError: If connection fails.+ MCPConnectionError: If the server refused the connection with an HTTP status.+ ConnectionError: If connection fails for other reasons.ImportError: If MCP SDK not available."""if self._connected:@@ -73,90 +121,64 @@ class HTTPTransport(BaseTransport):try:from mcp.client.streamable_http import streamablehttp_client-- self._transport_context = streamablehttp_client(- self.url,- headers=self.headers if self.headers else None,- terminate_on_close=True,- )-- try:- read, write, _ = await asyncio.wait_for(- self._transport_context.__aenter__(), timeout=30.0- )- except asyncio.TimeoutError as e:- self._transport_context = None- raise ConnectionError(- "Transport context entry timed out after 30 seconds. "- "Server may be slow or unreachable."- ) from e- except Exception as e:- self._transport_context = None- raise ConnectionError(f"Failed to enter transport context: {e}") from e- self._set_streams(read=read, write=write)- return self-except ImportError as e:raise ImportError("MCP library not available. Please install with: pip install mcp") from e- except Exception as e:- self._clear_streams()- if self._transport_context is not None:- self._transport_context = None- raise ConnectionError(f"Failed to connect to MCP server: {e}") from e++ self._transport_context = streamablehttp_client(+ self.url,+ headers=self.headers if self.headers else None,+ terminate_on_close=True,+ )++ try:+ read, write, _ = await asyncio.wait_for(+ self._transport_context.__aenter__(), timeout=30.0+ )+ except asyncio.TimeoutError as e:+ teardown_error = await self._close_transport_context(e)+ if find_http_status(e, teardown_error) is not None:+ raise_connection_failure(+ f"Failed to connect to MCP server: {e}", e, teardown_error+ )+ raise ConnectionError(+ "Transport context entry timed out after 30 seconds. "+ "Server may be slow or unreachable."+ ) from e+ except asyncio.CancelledError as e:+ teardown_error = await self._close_transport_context(e)+ if find_http_status(e, teardown_error) is not None:+ raise_connection_failure(+ f"Failed to connect to MCP server: {e}", e, teardown_error+ )+ if (failure := find_transport_failure(teardown_error)) is not None:+ raise failure from e+ raise+ except (Exception, BaseExceptionGroup) as e:+ teardown_error = await self._close_transport_context(e)+ raise_connection_failure(+ f"Failed to connect to MCP server: {e}", e, teardown_error+ )++ self._set_streams(read=read, write=write)+ return selfasync def disconnect(self) -> None:- """Close HTTP connection."""- if not self._connected:+ """Close HTTP connection.++ Raises:+ MCPConnectionError: If the server refused the connection. The+ refusal is reported here rather than to the coroutine that+ was waiting, because the underlying task group only raises it+ while unwinding.+ """+ if self._transport_context is None and not self._connected:return- try:- # Clear streams first- self._clear_streams()- # await self._exit_stack.aclose()-- # Exit transport context - this will clean up background tasks- # Give a small delay to allow background tasks to complete- if self._transport_context is not None:- try:- # Wait a tiny bit for any pending operations- await asyncio.sleep(0.1)- await self._transport_context.__aexit__(None, None, None)- except (RuntimeError, asyncio.CancelledError) as e:- # Ignore "exit cancel scope in different task" errors and cancellation- # These happen when asyncio.run() closes the event loop- # while background tasks are still running- error_msg = str(e).lower()- if "cancel scope" not in error_msg and "task" not in error_msg:- # Only suppress cancel scope/task errors, re-raise others- if isinstance(e, RuntimeError):- raise- # For CancelledError, just suppress it- except BaseExceptionGroup as eg:- # Handle exception groups from anyio task groups- # Suppress if they contain cancel scope errors- should_suppress = False- for exc in eg.exceptions:- error_msg = str(exc).lower()- if "cancel scope" in error_msg or "task" in error_msg:- should_suppress = True- break- if not should_suppress:- raise- except Exception as e:- raise RuntimeError(- f"Error during HTTP transport disconnect: {e}"- ) from e-- self._connected = False-- except Exception as e:- # Log but don't raise - cleanup should be best effort- import logging-- logger = logging.getLogger(__name__)- logger.warning(f"Error during HTTP transport disconnect: {e}")+ teardown_error = await self._close_transport_context()+ if teardown_error is not None:+ self._raise_teardown_failure(teardown_error)async def __aenter__(self) -> Self:"""Async context manager entry."""diff --git a/lib/crewai/tests/mcp/test_client_connect_auth.py b/lib/crewai/tests/mcp/test_client_connect_auth.pynew file mode 100644index 000000000..6922e4ff3--- /dev/null+++ b/lib/crewai/tests/mcp/test_client_connect_auth.py@@ -0,0 +1,214 @@+"""Tests for MCPClient connect authentication error handling."""++import asyncio+from typing import Any+from unittest.mock import AsyncMock, MagicMock, patch++import httpx+import pytest++from crewai.events.event_bus import crewai_event_bus+from crewai.events.types.mcp_events import MCPConnectionFailedEvent+from crewai.mcp.client import MCPClient+from crewai.mcp.exceptions import MCPAuthenticationError+from crewai.mcp.transports.base import BaseTransport, TransportType+from crewai.mcp.transports.http import HTTPTransport+++class MockTransport(BaseTransport):+ """Minimal transport stub for connect() error-path tests."""++ @property+ def transport_type(self) -> TransportType:+ return TransportType.STREAMABLE_HTTP++ async def connect(self) -> "MockTransport":+ self._read_stream = MagicMock()+ self._write_stream = MagicMock()+ self._connected = True+ return self++ async def disconnect(self) -> None:+ self._connected = False++ async def __aenter__(self) -> "MockTransport":+ return await self.connect()++ async def __aexit__(+ self,+ exc_type: type[BaseException] | None,+ exc_val: BaseException | None,+ exc_tb: Any,+ ) -> None:+ await self.disconnect()+++def _http_status_error(status_code: int) -> httpx.HTTPStatusError:+ request = httpx.Request("POST", "https://mcp.example.com/mcp")+ response = httpx.Response(status_code, text="refused", request=request)+ return httpx.HTTPStatusError(+ f"HTTP {status_code}",+ request=request,+ response=response,+ )+++async def test_connect_cancelled_with_auth_status_in_cleanup():+ transport = MockTransport()+ client = MCPClient(transport)+ auth_error = _http_status_error(401)+ failed_events: list[MCPConnectionFailedEvent] = []++ mock_session = MagicMock()+ mock_session.initialize = AsyncMock(side_effect=asyncio.CancelledError())+ mock_session.__aenter__ = AsyncMock(return_value=mock_session)+ mock_session.__aexit__ = AsyncMock(return_value=None)++ with (+ patch("mcp.ClientSession", return_value=mock_session),+ patch.object(+ client,+ "_cleanup_on_error",+ AsyncMock(return_value=auth_error),+ ),+ crewai_event_bus.scoped_handlers(),+ ):+ @crewai_event_bus.on(MCPConnectionFailedEvent)+ def _capture(_: object, event: MCPConnectionFailedEvent) -> None:+ failed_events.append(event)++ with pytest.raises(MCPAuthenticationError) as exc_info:+ await client.connect()++ assert crewai_event_bus.flush(timeout=10)++ assert exc_info.value.status_code == 401+ assert len(failed_events) == 1+ assert failed_events[0].error_type == "authentication"+ assert failed_events[0].status_code == 401+ assert "401 Unauthorized" in failed_events[0].error+++async def test_connect_cancelled_without_underlying_failure_emits_cancelled():+ transport = MockTransport()+ client = MCPClient(transport)+ failed_events: list[MCPConnectionFailedEvent] = []++ mock_session = MagicMock()+ mock_session.initialize = AsyncMock(side_effect=asyncio.CancelledError())+ mock_session.__aenter__ = AsyncMock(return_value=mock_session)+ mock_session.__aexit__ = AsyncMock(return_value=None)++ with (+ patch("mcp.ClientSession", return_value=mock_session),+ patch.object(client, "_cleanup_on_error", AsyncMock(return_value=None)),+ crewai_event_bus.scoped_handlers(),+ ):+ @crewai_event_bus.on(MCPConnectionFailedEvent)+ def _capture(_: object, event: MCPConnectionFailedEvent) -> None:+ failed_events.append(event)++ with pytest.raises(asyncio.CancelledError):+ await client.connect()++ assert crewai_event_bus.flush(timeout=10)++ assert len(failed_events) == 1+ assert failed_events[0].error_type == "cancelled"+ assert failed_events[0].error == "Connection cancelled"+++async def test_connect_raises_authentication_error_for_typed_transport_failure():+ transport = MockTransport()+ client = MCPClient(transport)+ failed_events: list[MCPConnectionFailedEvent] = []++ mock_session = MagicMock()+ mock_session.initialize = AsyncMock(+ side_effect=MCPAuthenticationError(401)+ )+ mock_session.__aenter__ = AsyncMock(return_value=mock_session)+ mock_session.__aexit__ = AsyncMock(return_value=None)++ with (+ patch("mcp.ClientSession", return_value=mock_session),+ patch.object(+ client,+ "_cleanup_on_error",+ AsyncMock(return_value=None),+ ),+ crewai_event_bus.scoped_handlers(),+ ):+ @crewai_event_bus.on(MCPConnectionFailedEvent)+ def _capture(_: object, event: MCPConnectionFailedEvent) -> None:+ failed_events.append(event)++ with pytest.raises(MCPAuthenticationError):+ await client.connect()++ assert crewai_event_bus.flush(timeout=10)++ assert len(failed_events) == 1+ assert failed_events[0].error_type == "authentication"+++async def test_connect_cancelled_during_initialize_recovers_auth_on_transport_unwind():+ transport = HTTPTransport(url="https://mcp.example.com/mcp")+ client = MCPClient(transport)+ auth_error = _http_status_error(401)+ failed_events: list[MCPConnectionFailedEvent] = []++ mock_streams = (MagicMock(), MagicMock(), None)+ mock_context = MagicMock()+ mock_context.__aenter__ = AsyncMock(return_value=mock_streams)+ mock_context.__aexit__ = AsyncMock(side_effect=auth_error)++ mock_session = MagicMock()+ mock_session.initialize = AsyncMock(side_effect=asyncio.CancelledError())+ mock_session.__aenter__ = AsyncMock(return_value=mock_session)+ mock_session.__aexit__ = AsyncMock(return_value=None)++ with (+ patch(+ "mcp.client.streamable_http.streamablehttp_client",+ return_value=mock_context,+ ),+ patch("mcp.ClientSession", return_value=mock_session),+ crewai_event_bus.scoped_handlers(),+ ):+ @crewai_event_bus.on(MCPConnectionFailedEvent)+ def _capture(_: object, event: MCPConnectionFailedEvent) -> None:+ failed_events.append(event)++ with pytest.raises(MCPAuthenticationError) as exc_info:+ await client.connect()++ assert crewai_event_bus.flush(timeout=10)++ mock_context.__aexit__.assert_awaited()+ assert exc_info.value.status_code == 401+ assert len(failed_events) == 1+ assert failed_events[0].error_type == "authentication"+ assert failed_events[0].status_code == 401+++async def test_disconnect_preserves_authentication_error_from_teardown():+ transport = MockTransport()+ client = MCPClient(transport)+ auth_error = MCPAuthenticationError(401)+ transport._connected = True+ client._initialized = True++ with patch.object(+ client._exit_stack, "aclose", AsyncMock(side_effect=auth_error)+ ):+ with pytest.raises(MCPAuthenticationError) as exc_info:+ await client.disconnect()++ assert exc_info.value is auth_error+ assert not client.connecteddiff --git a/lib/crewai/tests/mcp/test_client_tool_execution_auth.py b/lib/crewai/tests/mcp/test_client_tool_execution_auth.pynew file mode 100644index 000000000..65700350f--- /dev/null+++ b/lib/crewai/tests/mcp/test_client_tool_execution_auth.py@@ -0,0 +1,63 @@+"""Tests for MCPClient tool execution authentication error handling."""++from unittest.mock import AsyncMock, MagicMock, patch++import pytest++from crewai.events.event_bus import crewai_event_bus+from crewai.events.types.mcp_events import MCPToolExecutionFailedEvent+from crewai.mcp.client import MCPClient+from crewai.mcp.exceptions import MCPAuthenticationError+from crewai.mcp.transports.base import BaseTransport, TransportType+++class MockTransport(BaseTransport):+ @property+ def transport_type(self) -> TransportType:+ return TransportType.STREAMABLE_HTTP++ async def connect(self) -> "MockTransport":+ self._read_stream = MagicMock()+ self._write_stream = MagicMock()+ self._connected = True+ return self++ async def disconnect(self) -> None:+ self._connected = False++ async def __aenter__(self) -> "MockTransport":+ return await self.connect()++ async def __aexit__(self, *args: object) -> None:+ await self.disconnect()+++async def test_call_tool_result_emits_authentication_error_type():+ transport = MockTransport()+ transport._connected = True+ client = MCPClient(transport)+ client._initialized = True+ failed_events: list[MCPToolExecutionFailedEvent] = []++ with (+ patch.object(+ client,+ "_retry_operation",+ AsyncMock(side_effect=MCPAuthenticationError(401)),+ ),+ crewai_event_bus.scoped_handlers(),+ ):+ @crewai_event_bus.on(MCPToolExecutionFailedEvent)+ def _capture(_: object, event: MCPToolExecutionFailedEvent) -> None:+ failed_events.append(event)++ with pytest.raises(MCPAuthenticationError):+ await client.call_tool_result("search", {"query": "test"})++ assert crewai_event_bus.flush(timeout=10)++ assert len(failed_events) == 1+ assert failed_events[0].error_type == "authentication"+ assert failed_events[0].tool_name == "search"+ assert "401 Unauthorized" in failed_events[0].errordiff --git a/lib/crewai/tests/mcp/test_http_transport_auth.py b/lib/crewai/tests/mcp/test_http_transport_auth.pynew file mode 100644index 000000000..a443ba479--- /dev/null+++ b/lib/crewai/tests/mcp/test_http_transport_auth.py@@ -0,0 +1,181 @@+"""Tests for HTTP transport authentication error handling."""++import asyncio+import sys+from unittest.mock import AsyncMock, MagicMock, patch++import httpx+import pytest++from crewai.mcp.exceptions import MCPAuthenticationError, MCPHTTPError+from crewai.mcp.transports.http import HTTPTransport++if sys.version_info >= (3, 11):+ from builtins import BaseExceptionGroup+else:+ from exceptiongroup import BaseExceptionGroup+++def _http_status_error(status_code: int) -> httpx.HTTPStatusError:+ request = httpx.Request("POST", "https://mcp.example.com/mcp")+ response = httpx.Response(status_code, text="refused", request=request)+ return httpx.HTTPStatusError(+ f"HTTP {status_code}",+ request=request,+ response=response,+ )+++async def test_http_transport_connect_raises_authentication_error_for_401():+ transport = HTTPTransport(+ url="https://mcp.example.com/mcp",+ headers={"Authorization": "Bearer stale-token"},+ )+ mock_context = MagicMock()+ mock_context.__aenter__ = AsyncMock(side_effect=_http_status_error(401))++ with patch(+ "mcp.client.streamable_http.streamablehttp_client",+ return_value=mock_context,+ ):+ with pytest.raises(MCPAuthenticationError) as exc_info:+ await transport.connect()++ assert exc_info.value.status_code == 401+ assert "401 Unauthorized" in str(exc_info.value)+ assert "authentication failure" in str(exc_info.value)+++async def test_http_transport_connect_raises_authentication_error_for_403():+ transport = HTTPTransport(url="https://mcp.example.com/mcp")+ mock_context = MagicMock()+ mock_context.__aenter__ = AsyncMock(side_effect=_http_status_error(403))++ with patch(+ "mcp.client.streamable_http.streamablehttp_client",+ return_value=mock_context,+ ):+ with pytest.raises(MCPAuthenticationError) as exc_info:+ await transport.connect()++ assert exc_info.value.status_code == 403+ assert "403 Forbidden" in str(exc_info.value)+++async def test_http_transport_connect_raises_http_error_for_non_auth_status():+ transport = HTTPTransport(url="https://mcp.example.com/mcp")+ mock_context = MagicMock()+ mock_context.__aenter__ = AsyncMock(side_effect=_http_status_error(500))++ with patch(+ "mcp.client.streamable_http.streamablehttp_client",+ return_value=mock_context,+ ):+ with pytest.raises(MCPHTTPError) as exc_info:+ await transport.connect()++ assert exc_info.value.status_code == 500+ assert "500 Internal Server Error" in str(exc_info.value)+++async def test_http_transport_connect_classifies_mixed_exception_group():+ transport = HTTPTransport(url="https://mcp.example.com/mcp")+ auth_error = _http_status_error(401)+ cancelled = asyncio.CancelledError()+ mixed_group = BaseExceptionGroup("task group failed", [auth_error, cancelled])++ mock_context = MagicMock()+ mock_context.__aenter__ = AsyncMock(side_effect=mixed_group)++ with patch(+ "mcp.client.streamable_http.streamablehttp_client",+ return_value=mock_context,+ ):+ with pytest.raises(MCPAuthenticationError) as exc_info:+ await transport.connect()++ assert exc_info.value.status_code == 401+ assert transport._transport_context is None+ assert exc_info.value.__cause__ is mixed_group+++async def test_http_transport_connect_cancelled_on_enter_recovers_auth_on_exit():+ transport = HTTPTransport(url="https://mcp.example.com/mcp")+ cancelled = asyncio.CancelledError()+ mock_context = MagicMock()+ mock_context.__aenter__ = AsyncMock(side_effect=cancelled)+ mock_context.__aexit__ = AsyncMock(side_effect=_http_status_error(401))++ with patch(+ "mcp.client.streamable_http.streamablehttp_client",+ return_value=mock_context,+ ):+ with pytest.raises(MCPAuthenticationError) as exc_info:+ await transport.connect()++ mock_context.__aexit__.assert_awaited_once()+ assert exc_info.value.status_code == 401+ assert transport._transport_context is None+++async def test_http_transport_disconnect_recovers_auth_from_exit():+ transport = HTTPTransport(url="https://mcp.example.com/mcp")+ mock_context = MagicMock()+ mock_context.__aexit__ = AsyncMock(side_effect=_http_status_error(401))+ transport._transport_context = mock_context+ transport._set_streams(MagicMock(), MagicMock())++ with pytest.raises(MCPAuthenticationError) as exc_info:+ await transport.disconnect()++ mock_context.__aexit__.assert_awaited_once()+ assert exc_info.value.status_code == 401+ assert transport._transport_context is None+ assert not transport.connected+++async def test_http_transport_disconnect_propagates_cancellation_without_http_status():+ transport = HTTPTransport(url="https://mcp.example.com/mcp")+ mock_context = MagicMock()+ mock_context.__aexit__ = AsyncMock(side_effect=asyncio.CancelledError())++ transport._transport_context = mock_context+ transport._set_streams(MagicMock(), MagicMock())++ with pytest.raises(asyncio.CancelledError):+ await transport.disconnect()++ mock_context.__aexit__.assert_awaited_once()+ assert transport._transport_context is None+ assert not transport.connected+++async def test_http_transport_connect_timeout_recovers_auth_on_exit():+ transport = HTTPTransport(url="https://mcp.example.com/mcp")+ mock_context = MagicMock()+ mock_context.__aexit__ = AsyncMock(side_effect=_http_status_error(401))++ with (+ patch(+ "mcp.client.streamable_http.streamablehttp_client",+ return_value=mock_context,+ ),+ patch(+ "crewai.mcp.transports.http.asyncio.wait_for",+ side_effect=asyncio.TimeoutError(),+ ),+ ):+ with pytest.raises(MCPAuthenticationError) as exc_info:+ await transport.connect()++ mock_context.__aexit__.assert_awaited_once()+ assert exc_info.value.status_code == 401+ assert transport._transport_context is Nonediff --git a/lib/crewai/tests/mcp/test_mcp_exceptions.py b/lib/crewai/tests/mcp/test_mcp_exceptions.pynew file mode 100644index 000000000..45b71ed30--- /dev/null+++ b/lib/crewai/tests/mcp/test_mcp_exceptions.py@@ -0,0 +1,159 @@+import asyncio+import sys++import httpx+import pytest++if sys.version_info >= (3, 11):+ from builtins import ExceptionGroup+else:+ from exceptiongroup import ExceptionGroup++from crewai.mcp.exceptions import (+ MCPAuthenticationError,+ MCPConnectionError,+ MCPHTTPError,+ error_for_status,+ error_type_for_status,+ find_http_status,+ find_transport_failure,+ raise_connection_failure,+ tool_execution_error_type,+)+++def _http_status_error(status_code: int, detail: str = "refused") -> httpx.HTTPStatusError:+ request = httpx.Request("POST", "https://mcp.example.com/mcp")+ response = httpx.Response(status_code, text=detail, request=request)+ return httpx.HTTPStatusError(+ f"HTTP {status_code}",+ request=request,+ response=response,+ )+++def test_error_for_status_returns_authentication_error_for_401():+ error = error_for_status(401)++ assert isinstance(error, MCPAuthenticationError)+ assert error.status_code == 401+ assert "401 Unauthorized" in str(error)+ assert "authentication failure" in str(error)+++def test_error_for_status_returns_authentication_error_for_403():+ error = error_for_status(403, detail="forbidden")++ assert isinstance(error, MCPAuthenticationError)+ assert error.status_code == 403+ assert "403 Forbidden" in str(error)+ assert "forbidden" in str(error)+++def test_error_for_status_returns_http_error_for_non_auth_status():+ error = error_for_status(500, detail="internal error")++ assert isinstance(error, MCPHTTPError)+ assert error.status_code == 500+ assert "500 Internal Server Error" in str(error)+++def test_error_type_for_status_maps_auth_and_http_errors():+ assert error_type_for_status(401) == "authentication"+ assert error_type_for_status(403) == "authentication"+ assert error_type_for_status(500) == "http_error"+ assert error_type_for_status(None) is None+++def test_find_http_status_from_httpx_error():+ error = _http_status_error(401)++ assert find_http_status(error) == 401+++def test_find_http_status_from_typed_connection_error():+ error = MCPConnectionError("failed", status_code=403)++ assert find_http_status(error) == 403+++def test_find_http_status_from_cancelled_error_with_context():+ auth_error = _http_status_error(401)+ cancelled = asyncio.CancelledError()+ cancelled.__context__ = auth_error++ assert find_http_status(cancelled) == 401+++def test_find_http_status_from_exception_group():+ auth_error = _http_status_error(401)+ group = ExceptionGroup("task group failed", [auth_error])++ assert find_http_status(group) == 401+++def test_find_transport_failure_ignores_teardown_noise():+ cancelled = asyncio.CancelledError()+ teardown = RuntimeError("Attempted to exit cancel scope in a different task")++ assert find_transport_failure(cancelled, teardown) is None+++def test_find_transport_failure_returns_underlying_http_error():+ auth_error = _http_status_error(401)+ cancelled = asyncio.CancelledError()+ cancelled.__context__ = auth_error++ assert find_transport_failure(cancelled) is auth_error+++def test_raise_connection_failure_reraises_typed_error():+ auth_error = MCPAuthenticationError(401)++ with pytest.raises(MCPAuthenticationError) as exc_info:+ raise_connection_failure("unused", auth_error)++ assert exc_info.value is auth_error+++def test_raise_connection_failure_builds_auth_error_from_http_status():+ with pytest.raises(MCPAuthenticationError) as exc_info:+ raise_connection_failure("unused", _http_status_error(401))++ assert exc_info.value.status_code == 401+++def test_raise_connection_failure_prefers_teardown_http_status():+ cancelled = asyncio.CancelledError()+ auth_error = _http_status_error(401)++ with pytest.raises(MCPAuthenticationError) as exc_info:+ raise_connection_failure("unused", cancelled, auth_error)++ assert exc_info.value.status_code == 401+++def test_raise_connection_failure_falls_back_to_connection_error():+ with pytest.raises(ConnectionError, match="host unreachable"):+ raise_connection_failure("host unreachable", ConnectionError("refused"))+++def test_tool_execution_error_type_maps_authentication_failures():+ assert (+ tool_execution_error_type(MCPAuthenticationError(401)) == "authentication"+ )+ assert tool_execution_error_type(_http_status_error(403)) == "authentication"+++def test_tool_execution_error_type_maps_timeout_and_validation():+ assert tool_execution_error_type(asyncio.TimeoutError()) == "timeout"+ assert (+ tool_execution_error_type(ConnectionError("Operation timed out after 30 seconds"))+ == "timeout"+ )+ assert tool_execution_error_type(ValueError("Resource not found")) == "validation"+++def test_tool_execution_error_type_maps_http_and_server_errors():+ assert tool_execution_error_type(MCPHTTPError(500)) == "http_error"+ assert tool_execution_error_type(ConnectionError("unexpected failure")) == "server_error"diff --git a/lib/crewai/tests/mcp/test_tool_resolver_auth.py b/lib/crewai/tests/mcp/test_tool_resolver_auth.pynew file mode 100644index 000000000..43915f2d3--- /dev/null+++ b/lib/crewai/tests/mcp/test_tool_resolver_auth.py@@ -0,0 +1,154 @@+"""Tests for MCPToolResolver authentication error handling."""++import asyncio+import sys+from unittest.mock import AsyncMock, patch++import httpx+import pytest++from crewai.mcp.config import MCPServerHTTP+from crewai.mcp.exceptions import MCPAuthenticationError+from crewai.mcp.tool_resolver import MCPToolResolver++if sys.version_info >= (3, 11):+ from builtins import BaseExceptionGroup+else:+ from exceptiongroup import BaseExceptionGroup+++def resolver():+ from crewai.agent.core import Agent++ agent = Agent(role="Test Agent", goal="Test goal", backstory="Test backstory")+ return MCPToolResolver(agent=agent, logger=agent._logger)+++def http_config():+ return MCPServerHTTP(url="https://mcp.example.com/api")+++def _http_status_error(status_code: int) -> httpx.HTTPStatusError:+ request = httpx.Request("POST", "https://mcp.example.com/mcp")+ response = httpx.Response(status_code, text="refused", request=request)+ return httpx.HTTPStatusError(+ f"HTTP {status_code}",+ request=request,+ response=response,+ )+++class TestResolveNativeAuthErrors:+ @patch("crewai.mcp.tool_resolver.asyncio.run")+ def test_cancelled_error_with_auth_status_raises_authentication_error(+ self, mock_asyncio_run, resolver, http_config+ ):+ cancelled = asyncio.CancelledError()+ cancelled.__context__ = _http_status_error(401)+ mock_asyncio_run.side_effect = cancelled++ with pytest.raises(MCPAuthenticationError) as exc_info:+ resolver._resolve_native(http_config)++ assert exc_info.value.status_code == 401+ assert "401 Unauthorized" in str(exc_info.value)+ assert "may indicate an authentication error" not in str(exc_info.value).lower()++ @patch("crewai.mcp.tool_resolver.asyncio.run")+ def test_typed_authentication_error_propagates_without_speculative_wording(+ self, mock_asyncio_run, resolver, http_config+ ):+ mock_asyncio_run.side_effect = MCPAuthenticationError(401)++ with pytest.raises(MCPAuthenticationError) as exc_info:+ resolver._resolve_native(http_config)++ assert exc_info.value.status_code == 401+ assert "may indicate" not in str(exc_info.value).lower()++ @patch("crewai.mcp.tool_resolver.asyncio.sleep", new_callable=AsyncMock)+ @patch("crewai.mcp.tool_resolver.MCPClient")+ def test_disconnect_runs_when_cancellation_occurs_after_connect(+ self, mock_client_class, _mock_sleep, resolver, http_config+ ):+ mock_client = AsyncMock()+ mock_client.connected = False++ async def _connect():+ mock_client.connected = True++ cancelled = asyncio.CancelledError()+ cancelled.__context__ = _http_status_error(401)++ mock_client.connect = AsyncMock(side_effect=_connect)+ mock_client.list_tools = AsyncMock(side_effect=cancelled)+ mock_client.disconnect = AsyncMock()+ mock_client_class.return_value = mock_client++ with pytest.raises(MCPAuthenticationError) as exc_info:+ resolver._resolve_native(http_config)++ mock_client.disconnect.assert_awaited_once()+ assert exc_info.value.status_code == 401+ assert exc_info.value.__cause__ is cancelled++ @patch("crewai.mcp.tool_resolver.asyncio.sleep", new_callable=AsyncMock)+ @patch("crewai.mcp.tool_resolver.MCPClient")+ def test_disconnect_auth_error_preserved_after_cancellation_without_http_context(+ self, mock_client_class, _mock_sleep, resolver, http_config+ ):+ mock_client = AsyncMock()+ mock_client.connected = False++ async def _connect():+ mock_client.connected = True++ cancelled = asyncio.CancelledError()+ auth_error = MCPAuthenticationError(401)++ mock_client.connect = AsyncMock(side_effect=_connect)+ mock_client.list_tools = AsyncMock(side_effect=cancelled)+ mock_client.disconnect = AsyncMock(side_effect=auth_error)+ mock_client_class.return_value = mock_client++ with pytest.raises(MCPAuthenticationError) as exc_info:+ resolver._resolve_native(http_config)++ mock_client.disconnect.assert_awaited_once()+ assert exc_info.value is auth_error+ assert exc_info.value.status_code == 401+ assert exc_info.value.__cause__ is cancelled+++class TestAttemptMcpDiscoveryAuthErrors:+ @pytest.mark.asyncio+ async def test_attempt_mcp_discovery_raises_authentication_failure_for_401(self):+ async def _fail(_server_url: str) -> dict[str, dict[str, object]]:+ raise _http_status_error(401)++ with pytest.raises(MCPAuthenticationError) as exc_info:+ await MCPToolResolver._attempt_mcp_discovery(+ _fail, "https://mcp.example.com/api"+ )++ assert exc_info.value.status_code == 401+ assert "401 Unauthorized" in str(exc_info.value)+ assert "authentication failure" in str(exc_info.value)++ @pytest.mark.asyncio+ async def test_attempt_mcp_discovery_raises_auth_for_mixed_exception_group(self):+ auth_error = _http_status_error(401)+ cancelled = asyncio.CancelledError()+ mixed_group = BaseExceptionGroup("task group failed", [auth_error, cancelled])++ async def _fail(_server_url: str) -> dict[str, dict[str, object]]:+ raise mixed_group++ with pytest.raises(MCPAuthenticationError) as exc_info:+ await MCPToolResolver._attempt_mcp_discovery(+ _fail, "https://mcp.example.com/api"+ )++ assert exc_info.value.status_code == 401diff --git a/lib/crewai/tests/mcp/test_tool_resolver_native.py b/lib/crewai/tests/mcp/test_tool_resolver_native.pyindex 7fe2ed5be..32e157f63 100644--- a/lib/crewai/tests/mcp/test_tool_resolver_native.py+++ b/lib/crewai/tests/mcp/test_tool_resolver_native.py@@ -95,5 +95,5 @@ class TestResolveNativeRuntimeError:):mock_asyncio_run.side_effect = RuntimeError("some other failure")- with pytest.raises(RuntimeError, match="Failed to get native MCP tools"):+ with pytest.raises(ConnectionError, match="Failed to get native MCP tools"):resolver._resolve_native(http_config)\ No newline at end of file