🐫 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(mcp): preserve multiple tool result content blocks (#4265)
Shriprasad R Patilbc07a0960d42
diff --git a/camel/utils/mcp_client.py b/camel/utils/mcp_client.pyindex 4db185cd0..b1f9a3332 100644--- a/camel/utils/mcp_client.py+++ b/camel/utils/mcp_client.py@@ -659,6 +659,31 @@ class MCPClient:return run_async(self.list_mcp_tools)()+ def _convert_mcp_content_to_string(self, content: Any) -> str:+ r"""Convert a single MCP content block to its string representation.++ Args:+ content (Any): An MCP content block from CallToolResult.content.++ Returns:+ str: Textual representation of the content block.+ """+ if content.type == "text":+ return content.text+ elif content.type == "image":+ # Return image URL or data URI if available+ if hasattr(content, "url") and content.url:+ return f"Image available at: {content.url}"+ return "Image content received (data URI not shown)"+ elif content.type == "embedded_resource":+ # Return resource information if available+ if hasattr(content, "name") and content.name:+ return f"Embedded resource: {content.name}"+ return "Embedded resource received"+ else:+ msg = f"Received content of type '{content.type}'"+ return f"{msg} which is not fully supported yet."+def generate_function_from_mcp_tool(self, mcp_tool: types.Tool) -> Callable:@@ -730,24 +755,12 @@ class MCPClient:if not result.content or len(result.content) == 0:return "No data available for this request."- # Handle different content types+ # Handle different content types for every MCP content block.try:- content = result.content[0]- if content.type == "text":- return content.text- elif content.type == "image":- # Return image URL or data URI if available- if hasattr(content, "url") and content.url:- return f"Image available at: {content.url}"- return "Image content received (data URI not shown)"- elif content.type == "embedded_resource":- # Return resource information if available- if hasattr(content, "name") and content.name:- return f"Embedded resource: {content.name}"- return "Embedded resource received"- else:- msg = f"Received content of type '{content.type}'"- return f"{msg} which is not fully supported yet."+ return "\n".join(+ self._convert_mcp_content_to_string(content)+ for content in result.content+ )except (IndexError, AttributeError) as e:from camel.logger import get_loggerdiff --git a/test/utils/test_mcp_client.py b/test/utils/test_mcp_client.pyindex 5d27969fd..39a4bd607 100644--- a/test/utils/test_mcp_client.py+++ b/test/utils/test_mcp_client.py@@ -20,7 +20,7 @@ import jsonimport tempfilefrom pathlib import Pathfrom typing import Any, Optional, Union-from unittest.mock import MagicMock+from unittest.mock import AsyncMock, MagicMockimport mcp.types as typesimport pytest@@ -829,5 +829,78 @@ class TestSSEFallback:assert observed_timeouts == [42.0, 42.0]+class TestGenerateFunctionFromMCPToolContent:+ """Tests for MCP tool result content block rendering."""++ @pytest.fixture+ def client(self):+ client = MCPClient({"url": "https://example.com/mcp"})+ client._session = AsyncMock()+ return client++ def _tool(self, name: str = "multi_block_tool") -> types.Tool:+ return types.Tool(+ name=name,+ description="Returns MCP content blocks",+ inputSchema={"type": "object", "properties": {}},+ )++ @pytest.mark.asyncio+ async def test_multiple_text_blocks_preserved_in_order(self, client):+ """All text content blocks should be returned in order."""+ client._session.call_tool.return_value = types.CallToolResult(+ content=[+ types.TextContent(type="text", text="search result"),+ types.TextContent(type="text", text="citation"),+ ]+ )+ generated = client.generate_function_from_mcp_tool(self._tool())++ result = await generated.async_call()++ assert result == "search result\ncitation"++ @pytest.mark.asyncio+ async def test_single_text_block_unchanged(self, client):+ """A single text block should keep the existing output."""+ client._session.call_tool.return_value = types.CallToolResult(+ content=[types.TextContent(type="text", text="search result")]+ )+ generated = client.generate_function_from_mcp_tool(self._tool())++ result = await generated.async_call()++ assert result == "search result"++ @pytest.mark.asyncio+ async def test_empty_content_returns_existing_message(self, client):+ """Empty content should keep the existing empty-response message."""+ client._session.call_tool.return_value = types.CallToolResult(+ content=[]+ )+ generated = client.generate_function_from_mcp_tool(self._tool())++ result = await generated.async_call()++ assert result == "No data available for this request."++ @pytest.mark.asyncio+ async def test_content_block_order_is_deterministic(self, client):+ """Block order must match the MCP result content list order."""+ client._session.call_tool.return_value = types.CallToolResult(+ content=[+ types.TextContent(type="text", text="first"),+ types.TextContent(type="text", text="second"),+ types.TextContent(type="text", text="third"),+ ]+ )+ generated = client.generate_function_from_mcp_tool(self._tool())++ result = await generated.async_call()++ assert result == "first\nsecond\nthird"+ assert result.split("\n") == ["first", "second", "third"]++if __name__ == "__main__":pytest.main([__file__])