🐫 CAMEL: The first and the best multi-agent framework. Finding the Scaling Law of Agents. https://www.camel-ai.org
Python agentai-societiesartificial-intelligencecommunicative-aicooperative-aideep-learninglarge-language-modelsmulti-agent-systemsnatural-language-processing
fix: improve error handling and resource cleanup in MCP toolkit (#2091)
CaelumF68247907d5b5
diff --git a/.env b/.envindex 70043a348..2eb338bf3 100644--- a/.env+++ b/.env@@ -92,7 +92,7 @@# CHUNKR_API_KEY="Fill your API key here"# Meshy API (https://www.meshy.ai/api)-# MESHY_API_KEY="Fill your API key h ere"+# MESHY_API_KEY="Fill your API key here"# Dappier API (https://api.dappier.com/)# DAPPIER_API_KEY="Fill your API key here"diff --git a/camel/toolkits/mcp_toolkit.py b/camel/toolkits/mcp_toolkit.pyindex 3c68c631a..fc8cd1d26 100644--- a/camel/toolkits/mcp_toolkit.py+++ b/camel/toolkits/mcp_toolkit.py@@ -145,6 +145,7 @@ class MCPClient(BaseToolkit):# Ensure resources are cleaned up on connection failureawait self.disconnect()logger.error(f"Failed to connect to MCP server: {e}")+ raise easync def disconnect(self):r"""Explicitly disconnect from the MCP server."""@@ -180,7 +181,8 @@ class MCPClient(BaseToolkit):try:return await self._session.list_tools()except Exception as e:- return f"Failed to list MCP tools: {e!s}"+ logger.exception("Failed to list MCP tools")+ raise edef generate_function_from_mcp_tool(self, mcp_tool: "Tool") -> Callable:r"""Dynamically generates a Python callable function corresponding to@@ -245,7 +247,7 @@ class MCPClient(BaseToolkit):logger.error("MCP Client is not connected. Call `connection()` first.")- return (+ raise RuntimeError("MCP Client is not connected. Call `connection()` first.")@@ -255,7 +257,7 @@ class MCPClient(BaseToolkit):)except Exception as e:logger.error(f"Failed to call MCP tool '{func_name}': {e!s}")- return f"Failed to call MCP tool '{func_name}': {e!s}"+ raise eif not result.content or len(result.content) == 0:return "No data available for this request."@@ -282,7 +284,7 @@ class MCPClient(BaseToolkit):logger.error(f"Error processing content from MCP tool response: {e!s}")- return "Error processing content from MCP tool response"+ raise edynamic_function.__name__ = func_namedynamic_function.__doc__ = func_desc@@ -427,10 +429,10 @@ class MCPToolkit(BaseToolkit):logger.warning(f"Invalid JSON in config file '{config_path}': {e!s}")- return []- except FileNotFoundError:+ raise e+ except FileNotFoundError as e:logger.warning(f"Config file not found: '{config_path}'")- return []+ raise eall_servers = []@@ -484,6 +486,7 @@ class MCPToolkit(BaseToolkit):# Ensure resources are cleaned up on connection failureawait self.disconnect()logger.error(f"Failed to connect to one or more MCP servers: {e}")+ raise easync def disconnect(self):r"""Explicitly disconnect from all MCP servers."""diff --git a/test/toolkits/test_video_download_function.py b/test/toolkits/test_video_download_function.pyindex 0138213b6..d629eaa65 100644--- a/test/toolkits/test_video_download_function.py+++ b/test/toolkits/test_video_download_function.py@@ -11,15 +11,22 @@# See the License for the specific language governing permissions and# limitations under the License.# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========+# Mock the dotenv functionality to prevent the TypeError+import sysfrom unittest.mock import MagicMock, mock_open, patchimport pytestfrom camel.toolkits.video_download_toolkit import VideoDownloaderToolkit+sys.modules['dotenv'] = MagicMock()+sys.modules['dotenv.main'] = MagicMock()+sys.modules['dotenv.parser'] = MagicMock()+@pytest.fixturedef mock_downloader():+ # Mock the FastMCP class to avoid dotenv loading issueswith (patch("builtins.open", mock_open(read_data=b"test")),patch("yt_dlp.YoutubeDL") as mock_youtube_dl,@@ -28,6 +35,11 @@ def mock_downloader():patch('ffmpeg.input') as mock_ffmpeg_input,patch('ffmpeg.probe') as mock_ffmpeg_probe,patch('PIL.Image.open'),+ patch('mcp.server.fastmcp.server.FastMCP') as mock_fastmcp,+ patch(+ 'pydantic_settings.sources.DotEnvSettingsSource._read_env_files',+ return_value={},+ ),):mock_ydl_instance = MagicMock()mock_ydl_instance.prepare_filename.return_value = "test.mp4"@@ -43,6 +55,11 @@ def mock_downloader():mock_ffmpeg_probe.return_value = {'format': {'duration': 10}}+ # Configure the FastMCP mock+ mock_fastmcp_instance = MagicMock()+ mock_fastmcp.return_value = mock_fastmcp_instance+ mock_fastmcp_instance.tool.return_value = lambda x: x+yield VideoDownloaderToolkit()