mirror of
https://github.com/crewAIInc/crewAI.git
synced 2026-09-22 02:46:39 +00:00
* 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.
155 lines
5.5 KiB
Python
155 lines
5.5 KiB
Python
"""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
|
|
|
|
|
|
@pytest.fixture
|
|
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)
|
|
|
|
|
|
@pytest.fixture
|
|
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 == 401
|