Files
crewAI/lib/crewai/tests/mcp/test_mcp_exceptions.py
Vidit Ostwal 7c23857aed [OSS-137] Report MCP HTTP auth failures instead of cancelled connections (#7067)
* feat(mcp): add shared error classifier for HTTP auth failures

When an MCP server refuses a streamable-HTTP connection, the HTTP status is
observed by the client but often buried inside anyio teardown. Add typed
connection exceptions and helpers to recover the status from exception groups,
CancelledError context chains, and httpx errors so later call sites can report
authentication failures instead of guessing.

Groundwork only; no call sites wired yet.

* feat(mcp): raise typed errors from HTTPTransport.connect on HTTP status

When streamable-HTTP connect fails with an httpx HTTPStatusError, classify
the status via the shared MCP exception helpers and raise MCPAuthenticationError
for 401/403 or MCPHTTPError for other refused statuses instead of a generic
ConnectionError that hides the credential problem.

* refactor(mcp): centralize raise_connection_failure and simplify connect

Move connection failure classification into exceptions.py so transports and
clients share one helper. Flatten HTTPTransport.connect to a single except
path that cleans up once and raises, avoiding the outer handler re-classifying
errors the inner handler already typed.

* fix(mcp): classify auth failures in MCPClient.connect before reporting cancelled

When a streamable-HTTP server refuses the connection, the awaiting coroutine
often sees only CancelledError while the HTTP status surfaces during transport
unwind. Inspect cleanup for the status before emitting error_type=cancelled,
and fix HTTPTransport.disconnect so it raises typed errors instead of
suppressing exception groups that carry the refusal.

* fix(mcp): replace speculative tool resolver errors with classifier

Use raise_connection_failure for native MCP discovery instead of hedged
cancel-scope wording, preserve typed MCPConnectionError from setup, and
detect event-loop presence explicitly so ConnectionError is not mistaken
for a missing running loop. Update HTTPS discovery to classify HTTP status
codes via find_http_status.

* refactor(mcp): collapse native tool resolver failure handlers

CancelledError is not an Exception subclass, so handle it alongside
Exception in one except clause and delegate to a shared helper.

* refactor(mcp): call raise_connection_failure directly in tool resolver

* fix(mcp): classify tool execution auth failures in events

Add tool_execution_error_type so call_tool_result emits authentication
instead of server_error for MCPAuthenticationError and HTTP 401/403.
Preserve typed MCPConnectionError in _retry_operation instead of flattening
them into a generic ConnectionError first.

* feat(mcp): add status_code to MCPConnectionFailedEvent

Surface the HTTP status observed during connection failures on the event
payload and in verbose console output, so executions and checkpoints record
401/403 alongside error_type=authentication instead of only the message text.

* fix(mcp): handle cancellation and exception groups in auth paths

Ensure discovery cleanup runs on CancelledError, classify mixed
BaseExceptionGroups during HTTP connect, and fix ExceptionGroup imports
on Python 3.10 with regression tests.

* fix(mcp): preserve auth errors from discovery disconnect cleanup

Re-raise MCPConnectionError from disconnect during cancellation cleanup
instead of logging and swallowing it, with a regression test.

* fix(mcp): unwind transport context to recover auth on cancel

Always exit pending streamable-HTTP contexts before classifying failures,
handle CancelledError during client cleanup, propagate typed HTTPS discovery
errors, and add regression tests for the teardown recovery path.

* fix(mcp): classify auth from groups and timeout teardown

Handle BaseExceptionGroup in HTTPS discovery and recover HTTP 401 from
streamable-HTTP context exit after connect timeouts, with regression tests.

* refactor(mcp): consolidate client connection failure reporting

Extract _report_connection_failure and delegate _http_failure and
_connection_failure to it without changing connect error behavior.

* refactor(mcp): drop redundant client failure helper wrappers

Call _report_connection_failure directly from connect() instead of
_http_failure and _connection_failure delegators.

* fix(mcp): propagate CancelledError after HTTP transport teardown

Re-raise cancellation from disconnect when no HTTP auth status is
recovered during context unwind, with a regression test.

* fix(mcp): preserve typed errors from MCPClient.disconnect

Re-raise MCPConnectionError and CancelledError from exit-stack teardown
instead of wrapping auth failures in RuntimeError, with a regression test.
2026-08-25 16:47:31 +00:00

160 lines
4.9 KiB
Python

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"