Skip to content

armgit / camel

Public Imported from GitHub
0

🐫 CAMEL: The first and the best multi-agent framework. Finding the Scaling Law of Agents. https://www.camel-ai.org

fix: SSE fallback + robust connect for Harbor-spec HTTP MCP sidecars (#3934)

Puzhen Zhang9566e763378b
diff --git a/camel/models/anthropic_model.py b/camel/models/anthropic_model.py
index 533add9de..fda12a935 100644
--- a/camel/models/anthropic_model.py
+++ b/camel/models/anthropic_model.py
@@ -319,7 +319,7 @@ class AnthropicModel(BaseModelBackend):
)
elif role == "tool":
# Convert tool response message
- tool_call_id = msg.get("tool_call_id", "")
+ tool_call_id = str(msg.get("tool_call_id", ""))
tool_content = (
content if isinstance(content, str) else str(content)
)
diff --git a/camel/toolkits/mcp_toolkit.py b/camel/toolkits/mcp_toolkit.py
index 62f64cd7e..4aa096f5d 100644
--- a/camel/toolkits/mcp_toolkit.py
+++ b/camel/toolkits/mcp_toolkit.py
@@ -12,10 +12,10 @@
# limitations under the License.
# ========= Copyright 2023-2026 @ CAMEL-AI.org. All Rights Reserved. =========
+import asyncio
import json
import os
import warnings
-from contextlib import AsyncExitStack
from typing import Any, Dict, List, Optional
from typing_extensions import TypeGuard
@@ -273,7 +273,7 @@ class MCPToolkit(BaseToolkit):
Note:
Both MCPClient and MCPToolkit now use the same async context manager
pattern for consistent connection management. MCPToolkit automatically
- manages multiple MCPClient instances using AsyncExitStack.
+ manages multiple MCPClient instances.
Args:
clients (Optional[List[MCPClient]], optional): List of :obj:`MCPClient`
@@ -336,6 +336,10 @@ class MCPToolkit(BaseToolkit):
config_path: Optional[str] = None,
config_dict: Optional[Dict[str, Any]] = None,
timeout: Optional[float] = None,
+ skip_failed: bool = True,
+ per_client_timeout: Optional[float] = None,
+ max_retries: int = 2,
+ retry_delay: float = 3.0,
):
# Call parent constructor first
super().__init__(timeout=timeout)
@@ -353,7 +357,18 @@ class MCPToolkit(BaseToolkit):
self.clients: List[MCPClient] = clients or []
self._is_connected = False
- self._exit_stack: Optional[AsyncExitStack] = None
+ self._connected_clients: List[MCPClient] = []
+
+ # Robustness options
+ # skip_failed: if True, log a warning for failed MCP connections
+ # instead of aborting the whole toolkit
+ # per_client_timeout: independent timeout for each MCP client;
+ # defaults to the overall toolkit timeout
+ # max_retries / retry_delay: retry each failed client before giving up
+ self._skip_failed = skip_failed
+ self._per_client_timeout = per_client_timeout or timeout or 60.0
+ self._max_retries = max_retries
+ self._retry_delay = retry_delay
# Load clients from config sources
if config_path:
@@ -366,10 +381,9 @@ class MCPToolkit(BaseToolkit):
raise ValueError("No valid MCP clients could be created")
async def connect(self) -> "MCPToolkit":
- r"""Connect to all MCP servers using AsyncExitStack.
+ r"""Connect to all MCP servers.
- Establishes connections to all configured MCP servers sequentially.
- Uses :obj:`AsyncExitStack` to manage the lifecycle of all connections,
+ Establishes connections to all configured MCP servers concurrently,
ensuring proper cleanup on exit or error.
Returns:
@@ -401,74 +415,134 @@ class MCPToolkit(BaseToolkit):
logger.warning("MCPToolkit is already connected")
return self
- self._exit_stack = AsyncExitStack()
+ self._connected_clients = []
try:
- # Apply timeout to the entire connection process
- import asyncio
+ connected, failed = await self._connect_all_clients()
+
+ if failed and not self._skip_failed:
+ self._is_connected = False
+ await self._disconnect_all_clients()
+ error_msg = (
+ f"Failed to connect to {len(failed)} MCP server(s): "
+ + ", ".join(f"client {i+1}" for i in failed)
+ )
+ raise MCPConnectionError(error_msg)
- timeout_seconds = self.timeout or 30.0
- await asyncio.wait_for(
- self._connect_all_clients(), timeout=timeout_seconds
- )
+ if connected == 0:
+ self._is_connected = False
+ raise MCPConnectionError("All MCP servers failed to connect.")
self._is_connected = True
- msg = f"Successfully connected to {len(self.clients)} MCP servers"
+ msg = f"Connected to {connected}/{len(self.clients)} MCP servers"
+ if failed:
+ msg += f" ({len(failed)} skipped due to errors)"
logger.info(msg)
return self
- except (asyncio.TimeoutError, asyncio.CancelledError):
- self._is_connected = False
- if self._exit_stack:
- await self._exit_stack.aclose()
- self._exit_stack = None
-
- timeout_seconds = self.timeout or 30.0
- error_msg = (
- f"Connection timeout after {timeout_seconds}s. "
- f"One or more MCP servers are not responding. "
- f"Please check if the servers are running and accessible."
- )
- logger.error(error_msg)
- raise MCPConnectionError(error_msg)
-
+ except MCPConnectionError:
+ raise
except Exception:
self._is_connected = False
- if self._exit_stack:
- await self._exit_stack.aclose()
- self._exit_stack = None
+ await self._disconnect_all_clients()
raise
+ async def _connect_single_client(self, i: int, client):
+ r"""Connect one client with per-client timeout and retry.
+
+ Returns True on success, raises on final failure.
+ """
+ last_exc: Optional[BaseException] = None
+ for attempt in range(1, self._max_retries + 1):
+ try:
+ await asyncio.wait_for(
+ client.__aenter__(), timeout=self._per_client_timeout
+ )
+ self._connected_clients.append(client)
+ logger.debug(
+ f"Connected to client {i+1}/{len(self.clients)}"
+ + (f" (attempt {attempt})" if attempt > 1 else "")
+ )
+ return True
+ except asyncio.TimeoutError as e:
+ last_exc = e
+ # Clean up partially-established resources before retry
+ await client._cleanup_connection()
+ logger.warning(
+ f"Client {i+1} timed out after "
+ f"{self._per_client_timeout}s "
+ f"(attempt {attempt}/{self._max_retries})"
+ )
+ except asyncio.CancelledError:
+ await client._cleanup_connection()
+ raise
+ except Exception as e:
+ last_exc = e
+ # Clean up partially-established resources before retry
+ await client._cleanup_connection()
+ logger.warning(
+ f"Client {i+1} connection failed "
+ f"(attempt {attempt}/{self._max_retries}): {e}"
+ )
+ if attempt < self._max_retries:
+ await asyncio.sleep(self._retry_delay)
+ raise ConnectionError(
+ f"Client {i+1} failed after {self._max_retries} attempts"
+ ) from last_exc
+
async def _connect_all_clients(self):
- r"""Connect to all clients sequentially."""
- # Connect to all clients using AsyncExitStack
- for i, client in enumerate(self.clients):
+ r"""Connect all clients with per-client timeout and retry.
+
+ Uses a semaphore to avoid overwhelming the system when many stdio
+ MCP servers each trigger a ``uv run`` / package-build step on first
+ launch. Concurrency defaults to 4 but can be overridden by the
+ ``MCP_CONNECT_CONCURRENCY`` environment variable.
+
+ Returns (connected_count, failed_indices).
+ Clients that fail are skipped when skip_failed=True.
+ """
+ max_concurrent = int(os.environ.get("MCP_CONNECT_CONCURRENCY", "4"))
+ semaphore = asyncio.Semaphore(max_concurrent)
+
+ async def _guarded(i, client):
+ async with semaphore:
+ return await self._connect_single_client(i, client)
+
+ tasks = [
+ asyncio.create_task(_guarded(i, client))
+ for i, client in enumerate(self.clients)
+ ]
+
+ connected = 0
+ failed: list = []
+ results = await asyncio.gather(*tasks, return_exceptions=True)
+ for i, result in enumerate(results):
+ if isinstance(result, asyncio.CancelledError):
+ raise result
+ if isinstance(result, Exception):
+ logger.error(f"Failed to connect to client {i+1}: {result}")
+ failed.append(i)
+ else:
+ connected += 1
+ return connected, failed
+
+ async def _disconnect_all_clients(self):
+ r"""Disconnect all successfully connected clients."""
+ for client in list(getattr(self, "_connected_clients", [])):
try:
- # Use MCPClient directly as async context manager
- await self._exit_stack.enter_async_context(client)
- msg = f"Connected to client {i+1}/{len(self.clients)}"
- logger.debug(msg)
+ await client.__aexit__(None, None, None)
except Exception as e:
- logger.error(f"Failed to connect to client {i+1}: {e}")
- # AsyncExitStack will cleanup already connected clients
- await self._exit_stack.aclose()
- self._exit_stack = None
- error_msg = f"Failed to connect to client {i+1}: {e}"
- raise MCPConnectionError(error_msg) from e
+ logger.warning(f"Error during client disconnect: {e}")
+ self._connected_clients = []
async def disconnect(self):
r"""Disconnect from all MCP servers."""
- if not self._is_connected:
+ if not self._is_connected and not getattr(
+ self, "_connected_clients", []
+ ):
return
- if self._exit_stack:
- try:
- await self._exit_stack.aclose()
- except Exception as e:
- logger.warning(f"Error during disconnect: {e}")
- finally:
- self._exit_stack = None
-
+ await self._disconnect_all_clients()
self._is_connected = False
logger.debug("Disconnected from all MCP servers")
@@ -477,14 +551,17 @@ class MCPToolkit(BaseToolkit):
r"""Check if toolkit is connected.
Returns:
- bool: True if the toolkit is connected to all MCP servers,
- False otherwise.
+ bool: True if the toolkit has at least one active client
+ connection, False otherwise.
"""
if not self._is_connected:
return False
- # Check if all clients are connected
- return all(client.is_connected() for client in self.clients)
+ # With skip_failed=True, only successfully connected clients matter
+ connected_clients = getattr(self, "_connected_clients", None)
+ if connected_clients is None:
+ connected_clients = self.clients
+ return any(client.is_connected() for client in connected_clients)
def connect_sync(self):
r"""Synchronously connect to all MCP servers."""
@@ -524,6 +601,10 @@ class MCPToolkit(BaseToolkit):
config_path: Optional[str] = None,
config_dict: Optional[Dict[str, Any]] = None,
timeout: Optional[float] = None,
+ skip_failed: bool = True,
+ per_client_timeout: Optional[float] = None,
+ max_retries: int = 2,
+ retry_delay: float = 3.0,
) -> "MCPToolkit":
r"""Factory method that creates and connects to all MCP servers.
@@ -569,6 +650,10 @@ class MCPToolkit(BaseToolkit):
config_path=config_path,
config_dict=config_dict,
timeout=timeout,
+ skip_failed=skip_failed,
+ per_client_timeout=per_client_timeout,
+ max_retries=max_retries,
+ retry_delay=retry_delay,
)
try:
await toolkit.connect()
@@ -588,10 +673,21 @@ class MCPToolkit(BaseToolkit):
config_path: Optional[str] = None,
config_dict: Optional[Dict[str, Any]] = None,
timeout: Optional[float] = None,
+ skip_failed: bool = True,
+ per_client_timeout: Optional[float] = None,
+ max_retries: int = 2,
+ retry_delay: float = 3.0,
) -> "MCPToolkit":
r"""Synchronously create and connect to all MCP servers."""
return run_async(cls.create)(
- clients, config_path, config_dict, timeout
+ clients,
+ config_path,
+ config_dict,
+ timeout,
+ skip_failed,
+ per_client_timeout,
+ max_retries,
+ retry_delay,
)
def _load_clients_from_config(self, config_path: str) -> List[MCPClient]:
diff --git a/camel/utils/mcp_client.py b/camel/utils/mcp_client.py
index f1e321f08..4db185cd0 100644
--- a/camel/utils/mcp_client.py
+++ b/camel/utils/mcp_client.py
@@ -19,8 +19,9 @@ using different transport protocols (stdio, sse, streamable-http, websocket).
The client can automatically detect the transport type based on configuration.
"""
+import asyncio
import inspect
-from contextlib import asynccontextmanager
+from contextlib import asynccontextmanager, suppress
from datetime import timedelta
from enum import Enum
from pathlib import Path
@@ -254,7 +255,7 @@ class MCPClient:
self,
config: Union[ServerConfig, Dict[str, Any]],
client_info: Optional[types.Implementation] = None,
- timeout: Optional[float] = 10.0,
+ timeout: Optional[float] = None,
):
# Convert dict config to ServerConfig if needed
if isinstance(config, dict):
@@ -267,10 +268,13 @@ class MCPClient:
self.client_info = client_info
self.read_timeout_seconds = timedelta(seconds=timeout or 10.0)
+ self._handshake_timeout_seconds = (
+ timeout if timeout is not None else self.config.timeout
+ )
self._session: Optional[ClientSession] = None
self._tools: List[types.Tool] = []
- self._connection_context = None
+ self._connection_context: Optional[Any] = None
@property
def transport_type(self) -> TransportType:
@@ -296,12 +300,73 @@ class MCPClient:
await self._cleanup_connection()
async def _establish_connection(self):
- r"""Establish connection to the MCP server."""
+ r"""Establish connection to the MCP server.
+
+ For auto-detected HTTP/HTTPS URLs, first tries StreamableHTTP
+ transport (MCP 2025 spec). If that fails or times out, automatically
+ falls back to SSE transport (MCP 2024 / supergateway-compatible).
+ Explicitly configured transport types are honored without fallback.
+ """
+ transport_type = self.config.transport_type
+ transports_to_try = [transport_type]
+
+ # Only auto-detected HTTP transports fall back to SSE. If the user
+ # explicitly selected a transport type, keep connection behavior
+ # deterministic and honor that choice.
+ if (
+ transport_type == TransportType.STREAMABLE_HTTP
+ and self.config.type is None
+ ):
+ transports_to_try.append(TransportType.SSE)
+
+ last_error: Optional[Exception] = None
+ for attempt_transport in transports_to_try:
+ connect_task = asyncio.create_task(
+ self._try_connect(attempt_transport)
+ )
+ try:
+ await asyncio.shield(connect_task)
+ return # success
+ except asyncio.CancelledError:
+ if not connect_task.done():
+ connect_task.cancel()
+ with suppress(BaseException):
+ await connect_task
+ await self._cleanup_connection()
+ raise
+ last_error = ConnectionError(
+ f"{attempt_transport} connection attempt was cancelled"
+ )
+ except Exception as e:
+ last_error = e
+ if attempt_transport != transports_to_try[-1]:
+ from camel.logger import get_logger
+
+ logger = get_logger(__name__)
+ logger.warning(
+ f"StreamableHTTP connection failed "
+ f"({type(e).__name__}: {str(e)[:80]}). "
+ f"Retrying with SSE transport..."
+ )
+
+ # All transports exhausted — raise simplified error
+ await self._cleanup_connection()
+ from camel.logger import get_logger
+
+ logger = get_logger(__name__)
+ error_msg = self._simplify_connection_error(last_error)
+ logger.error(f"MCP connection failed: {error_msg}")
+ raise ConnectionError(error_msg) from last_error
+
+ async def _try_connect(self, transport_type: "TransportType"):
+ r"""Attempt connection with a specific transport type."""
try:
- self._connection_context = self._create_transport()
+ self._connection_context = self._create_transport(
+ override_transport=transport_type
+ )
streams = await self._connection_context.__aenter__()
- # Handle extra returns safely
+ # Handle extra returns safely (streamable_http yields 3 values)
read_stream, write_stream = streams[:2]
self._session = ClientSession(
@@ -314,25 +379,20 @@ class MCPClient:
# Start the session's message processing loop
await self._session.__aenter__()
- # Initialize the session and load tools
- await self._session.initialize()
- tools_response = await self._session.list_tools()
+ # Initialize the session and load tools — apply a hard timeout so
+ # a hung server (e.g., streamable_http vs supergateway mismatch)
+ # fails fast instead of blocking forever.
+ init_timeout = self._handshake_timeout_seconds
+ await self._run_operation_with_timeout(
+ self._session.initialize(), timeout=init_timeout
+ )
+ tools_response = await self._run_operation_with_timeout(
+ self._session.list_tools(), timeout=init_timeout
+ )
self._tools = tools_response.tools if tools_response else []
-
- except Exception as e:
- # Clean up on error
+ except BaseException:
await self._cleanup_connection()
-
- # Convert complex exceptions to simpler, more understandable ones
- from camel.logger import get_logger
-
- logger = get_logger(__name__)
-
- error_msg = self._simplify_connection_error(e)
- logger.error(f"MCP connection failed: {error_msg}")
-
- # Raise a simpler exception
- raise ConnectionError(error_msg) from e
+ raise
async def _cleanup_connection(self):
r"""Clean up connection resources."""
@@ -365,7 +425,25 @@ class MCPClient:
# Ensure state is reset
self._tools = []
- def _simplify_connection_error(self, error: Exception) -> str:
+ async def _run_operation_with_timeout(
+ self, operation: Any, timeout: float
+ ) -> Any:
+ r"""Run a session operation with deterministic timeout cleanup."""
+ task = asyncio.create_task(operation)
+ try:
+ return await asyncio.wait_for(task, timeout=timeout)
+ except asyncio.TimeoutError:
+ task.cancel()
+ with suppress(BaseException):
+ await task
+ raise
+ except asyncio.CancelledError:
+ task.cancel()
+ with suppress(BaseException):
+ await task
+ raise
+
+ def _simplify_connection_error(self, error: BaseException) -> str:
r"""Convert complex MCP connection errors to simple, understandable
messages.
"""
@@ -436,9 +514,16 @@ class MCPClient:
)
@asynccontextmanager
- async def _create_transport(self):
- """Create the appropriate transport based on detected type."""
- transport_type = self.config.transport_type
+ async def _create_transport(
+ self, override_transport: Optional["TransportType"] = None
+ ):
+ """Create the appropriate transport based on detected type.
+
+ Args:
+ override_transport: If provided, use this transport type instead
+ of the auto-detected one. Used for fallback logic.
+ """
+ transport_type = override_transport or self.config.transport_type
if transport_type == TransportType.STDIO:
from mcp import StdioServerParameters
diff --git a/test/toolkits/test_mcp_toolkit.py b/test/toolkits/test_mcp_toolkit.py
index e36d5b1ec..bf6a15ac3 100644
--- a/test/toolkits/test_mcp_toolkit.py
+++ b/test/toolkits/test_mcp_toolkit.py
@@ -15,6 +15,7 @@
Tests for the refactored MCPToolkit.
"""
+import asyncio
import json
import tempfile
from contextlib import asynccontextmanager
@@ -193,10 +194,16 @@ class TestMCPToolkitConnectionManagement:
# Set up the second client to raise an exception during __aenter__
mock_client2.__aenter__.side_effect = Exception("Connection failed")
+ mock_client2._cleanup_connection = AsyncMock()
- toolkit = MCPToolkit(clients=[mock_client1, mock_client2])
+ toolkit = MCPToolkit(
+ clients=[mock_client1, mock_client2],
+ skip_failed=False,
+ max_retries=1,
+ retry_delay=0,
+ )
- expected_msg = "Failed to connect to client 2"
+ expected_msg = "Failed to connect to 1 MCP server"
with pytest.raises(MCPConnectionError, match=expected_msg):
await toolkit.connect()
@@ -283,12 +290,93 @@ class TestMCPToolkitConnectionManagement:
# Mark as connected
toolkit._is_connected = True
+ toolkit._connected_clients = [mock_client1, mock_client2]
assert toolkit.is_connected
# One client disconnected
mock_client2.is_connected.return_value = False
+ assert toolkit.is_connected
+
+ # No connected clients remain
+ mock_client1.is_connected.return_value = False
assert not toolkit.is_connected
+ @pytest.mark.asyncio
+ async def test_connect_skip_failed_keeps_toolkit_usable(self):
+ """A partial connect should still leave the toolkit usable."""
+ mock_client1 = MagicMock()
+ mock_client2 = MagicMock()
+
+ mock_tool = MagicMock()
+ mock_tool.func.__name__ = "tool1"
+
+ mock_client1.__aenter__.return_value = mock_client1
+ mock_client1.__aexit__.return_value = None
+ mock_client1.is_connected.return_value = True
+ mock_client1.get_tools.return_value = [mock_tool]
+ mock_client1.call_tool = AsyncMock(return_value="tool result")
+
+ mock_client2.__aenter__.side_effect = Exception("Connection failed")
+ mock_client2._cleanup_connection = AsyncMock()
+ mock_client2.is_connected.return_value = False
+ mock_client2.get_tools.side_effect = RuntimeError("not connected")
+
+ toolkit = MCPToolkit(
+ clients=[mock_client1, mock_client2],
+ max_retries=1,
+ retry_delay=0,
+ )
+
+ await toolkit.connect()
+
+ assert toolkit.is_connected
+ assert (
+ await toolkit.call_tool("tool1", {"arg": "value"}) == "tool result"
+ )
+
+ @pytest.mark.asyncio
+ async def test_connect_propagates_cancellation(self):
+ """Cancellation should not be converted into a retry loop."""
+ mock_client = MagicMock()
+ started = asyncio.Event()
+
+ async def slow_enter():
+ started.set()
+ await asyncio.sleep(10)
+
+ mock_client.__aenter__.side_effect = slow_enter
+ mock_client._cleanup_connection = AsyncMock()
+
+ toolkit = MCPToolkit(
+ clients=[mock_client],
+ max_retries=2,
+ retry_delay=0,
+ per_client_timeout=30,
+ )
+
+ task = asyncio.create_task(toolkit.connect())
+ await started.wait()
+ task.cancel()
+
+ with pytest.raises(asyncio.CancelledError):
+ await task
+
+ mock_client._cleanup_connection.assert_awaited_once()
+
+ @pytest.mark.asyncio
+ async def test_connect_all_clients_propagates_cancelled_subtask(self):
+ """A cancelled child task should not be counted as success."""
+ toolkit = MCPToolkit(clients=[MagicMock()])
+
+ async def cancelled_client(*args, **kwargs):
+ raise asyncio.CancelledError()
+
+ with patch.object(
+ toolkit, "_connect_single_client", side_effect=cancelled_client
+ ):
+ with pytest.raises(asyncio.CancelledError):
+ await toolkit._connect_all_clients()
+
@pytest.mark.asyncio
async def test_context_manager(self):
"""Test async context manager."""
@@ -338,6 +426,41 @@ class TestMCPToolkitFactoryMethods:
assert result is toolkit
assert toolkit._is_connected
+ @pytest.mark.asyncio
+ async def test_create_forwards_robust_connect_options(self):
+ """Factory method should forward the new connection controls."""
+ with patch.object(
+ MCPToolkit, '__init__', return_value=None
+ ) as init_mock:
+ toolkit = MCPToolkit.__new__(MCPToolkit)
+ toolkit.disconnect = AsyncMock()
+
+ async def mock_connect():
+ return toolkit
+
+ toolkit.connect = mock_connect
+
+ patch_path = 'camel.toolkits.mcp_toolkit.MCPToolkit.__new__'
+ with patch(patch_path, return_value=toolkit):
+ await MCPToolkit.create(
+ clients=[],
+ skip_failed=False,
+ per_client_timeout=12,
+ max_retries=4,
+ retry_delay=0.5,
+ )
+
+ init_mock.assert_called_once_with(
+ clients=[],
+ config_path=None,
+ config_dict=None,
+ timeout=None,
+ skip_failed=False,
+ per_client_timeout=12,
+ max_retries=4,
+ retry_delay=0.5,
+ )
+
@pytest.mark.asyncio
async def test_create_failure_cleanup(self):
"""Test cleanup on creation failure."""
diff --git a/test/utils/test_mcp_client.py b/test/utils/test_mcp_client.py
index 386cf2374..5d27969fd 100644
--- a/test/utils/test_mcp_client.py
+++ b/test/utils/test_mcp_client.py
@@ -15,6 +15,7 @@
Tests for the unified MCP client.
"""
+import asyncio
import json
import tempfile
from pathlib import Path
@@ -572,5 +573,261 @@ class TestEdgeCases:
assert client3.client_info.version == "2.0"
+class TestSSEFallback:
+ """Test StreamableHTTP -> SSE automatic fallback."""
+
+ @pytest.mark.asyncio
+ async def test_sse_fallback_on_streamablehttp_failure(self):
+ """StreamableHTTP failure should trigger SSE retry."""
+ from contextlib import asynccontextmanager
+ from unittest.mock import AsyncMock, MagicMock, patch
+
+ client = MCPClient(
+ {"url": "http://localhost:8000/mcp", "timeout": 5.0}
+ )
+ assert client.config.transport_type == TransportType.STREAMABLE_HTTP
+
+ call_log = []
+
+ @asynccontextmanager
+ async def fake_transport(override_transport=None):
+ call_log.append(override_transport)
+ if override_transport == TransportType.STREAMABLE_HTTP:
+ raise ConnectionError("streamablehttp timed out")
+ # SSE succeeds: yield fake streams
+ reader = MagicMock()
+ writer = MagicMock()
+ yield reader, writer
+
+ mock_session = AsyncMock()
+ mock_session.initialize = AsyncMock(return_value=None)
+ mock_session.list_tools = AsyncMock(return_value=MagicMock(tools=[]))
+ mock_session.__aenter__ = AsyncMock(return_value=mock_session)
+ mock_session.__aexit__ = AsyncMock(return_value=None)
+
+ with (
+ patch.object(
+ client, "_create_transport", side_effect=fake_transport
+ ),
+ patch(
+ "camel.utils.mcp_client.ClientSession",
+ return_value=mock_session,
+ ),
+ ):
+ await client._establish_connection()
+
+ # Both transports were attempted in order
+ assert call_log[0] == TransportType.STREAMABLE_HTTP
+ assert call_log[1] == TransportType.SSE
+
+ @pytest.mark.asyncio
+ async def test_no_sse_fallback_for_stdio(self):
+ """stdio transport should NOT attempt SSE fallback on failure."""
+ from contextlib import asynccontextmanager
+ from unittest.mock import patch
+
+ client = MCPClient({"command": "fake-command", "timeout": 5.0})
+ assert client.config.transport_type == TransportType.STDIO
+
+ call_log = []
+
+ @asynccontextmanager
+ async def fake_transport(override_transport=None):
+ call_log.append(override_transport)
+ raise ConnectionError("stdio failed")
+ yield # make it a generator
+
+ with patch.object(
+ client, "_create_transport", side_effect=fake_transport
+ ):
+ with pytest.raises(ConnectionError):
+ await client._establish_connection()
+
+ # Only stdio was tried, no SSE fallback
+ assert len(call_log) == 1
+ assert call_log[0] == TransportType.STDIO
+
+ @pytest.mark.asyncio
+ async def test_error_raised_when_both_transports_fail(self):
+ """If both StreamableHTTP and SSE fail, ConnectionError is raised."""
+ from contextlib import asynccontextmanager
+ from unittest.mock import patch
+
+ client = MCPClient(
+ {"url": "http://localhost:8000/mcp", "timeout": 5.0}
+ )
+
+ @asynccontextmanager
+ async def fake_transport(override_transport=None):
+ raise ConnectionError(f"{override_transport} failed")
+ yield
+
+ with patch.object(
+ client, "_create_transport", side_effect=fake_transport
+ ):
+ with pytest.raises(ConnectionError):
+ await client._establish_connection()
+
+ @pytest.mark.asyncio
+ async def test_streamablehttp_succeeds_no_fallback(self):
+ """If StreamableHTTP succeeds, SSE fallback should NOT be attempted."""
+ from contextlib import asynccontextmanager
+ from unittest.mock import AsyncMock, MagicMock, patch
+
+ client = MCPClient(
+ {"url": "http://localhost:8000/mcp", "timeout": 5.0}
+ )
+
+ call_log = []
+
+ @asynccontextmanager
+ async def fake_transport(override_transport=None):
+ call_log.append(override_transport)
+ reader = MagicMock()
+ writer = MagicMock()
+ yield reader, writer
+
+ mock_session = AsyncMock()
+ mock_session.initialize = AsyncMock(return_value=None)
+ mock_session.list_tools = AsyncMock(return_value=MagicMock(tools=[]))
+ mock_session.__aenter__ = AsyncMock(return_value=mock_session)
+ mock_session.__aexit__ = AsyncMock(return_value=None)
+
+ with (
+ patch.object(
+ client, "_create_transport", side_effect=fake_transport
+ ),
+ patch(
+ "camel.utils.mcp_client.ClientSession",
+ return_value=mock_session,
+ ),
+ ):
+ await client._establish_connection()
+
+ # Only StreamableHTTP was used
+ assert call_log == [TransportType.STREAMABLE_HTTP]
+
+ @pytest.mark.asyncio
+ async def test_explicit_streamablehttp_disables_sse_fallback(self):
+ """Explicit StreamableHTTP config should not fall back to SSE."""
+ from unittest.mock import patch
+
+ client = MCPClient(
+ {
+ "url": "http://localhost:8000/mcp",
+ "type": "streamable_http",
+ "timeout": 5.0,
+ }
+ )
+
+ call_log = []
+
+ async def fake_try_connect(transport_type):
+ call_log.append(transport_type)
+ raise ConnectionError("streamablehttp timed out")
+
+ with patch.object(
+ client, "_try_connect", side_effect=fake_try_connect
+ ):
+ with pytest.raises(ConnectionError):
+ await client._establish_connection()
+
+ assert call_log == [TransportType.STREAMABLE_HTTP]
+
+ @pytest.mark.asyncio
+ async def test_cancelled_streamablehttp_falls_back_to_sse(self):
+ """Child-task cancellation should still allow SSE fallback."""
+ from unittest.mock import MagicMock, patch
+
+ client = MCPClient(
+ {"url": "http://localhost:8000/sse", "timeout": 5.0}
+ )
+
+ call_log = []
+
+ async def fake_try_connect(transport_type):
+ call_log.append(transport_type)
+ if transport_type == TransportType.STREAMABLE_HTTP:
+ raise asyncio.CancelledError()
+ client._session = MagicMock()
+ client._tools = []
+
+ with patch.object(
+ client, "_try_connect", side_effect=fake_try_connect
+ ):
+ await client._establish_connection()
+
+ assert call_log == [
+ TransportType.STREAMABLE_HTTP,
+ TransportType.SSE,
+ ]
+
+ @pytest.mark.asyncio
+ async def test_external_cancellation_is_not_swallowed(self):
+ """Real task cancellation should still propagate to the caller."""
+ from unittest.mock import patch
+
+ client = MCPClient(
+ {"url": "http://localhost:8000/sse", "timeout": 5.0}
+ )
+ started = asyncio.Event()
+
+ async def slow_try_connect(transport_type):
+ started.set()
+ await asyncio.sleep(10)
+
+ with patch.object(
+ client, "_try_connect", side_effect=slow_try_connect
+ ):
+ task = asyncio.create_task(client._establish_connection())
+ await started.wait()
+ task.cancel()
+
+ with pytest.raises(asyncio.CancelledError):
+ await task
+
+ @pytest.mark.asyncio
+ async def test_initialize_timeout_uses_config_timeout(self):
+ """Handshake timeout should respect the server config timeout."""
+ from contextlib import asynccontextmanager
+ from unittest.mock import AsyncMock, MagicMock, patch
+
+ client = MCPClient(
+ {"url": "http://localhost:8000/mcp", "timeout": 42.0}
+ )
+
+ observed_timeouts = []
+
+ @asynccontextmanager
+ async def fake_transport(override_transport=None):
+ reader = MagicMock()
+ writer = MagicMock()
+ yield reader, writer
+
+ mock_session = AsyncMock()
+ mock_session.initialize = AsyncMock(return_value=None)
+ mock_session.list_tools = AsyncMock(return_value=MagicMock(tools=[]))
+ mock_session.__aenter__ = AsyncMock(return_value=mock_session)
+ mock_session.__aexit__ = AsyncMock(return_value=None)
+
+ async def fake_wait_for(awaitable, timeout):
+ observed_timeouts.append(timeout)
+ return await awaitable
+
+ with (
+ patch.object(
+ client, "_create_transport", side_effect=fake_transport
+ ),
+ patch(
+ "camel.utils.mcp_client.ClientSession",
+ return_value=mock_session,
+ ),
+ patch("asyncio.wait_for", side_effect=fake_wait_for),
+ ):
+ await client._try_connect(TransportType.STREAMABLE_HTTP)
+
+ assert observed_timeouts == [42.0, 42.0]
+
+
if __name__ == "__main__":
pytest.main([__file__])