Skip to content

Commit 57a5335

Browse files
committed
Add test for mcp result text extraction
1 parent 95572d6 commit 57a5335

2 files changed

Lines changed: 21 additions & 4 deletions

File tree

integrations/mcp/src/haystack_integrations/tools/mcp/mcp_tool.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ def _resolve_headers(headers: dict[str, str | Secret] | None) -> dict[str, str]
6363
return resolved_headers
6464

6565

66-
def extract_first_text(result: str) -> str:
66+
def extract_first_text_element(result: str) -> str:
6767
# Per MCP spec, content[] may contain TextContent, ImageContent, AudioContent, etc.
6868
# Parse only first TextContent block (ToolInvoker requires dict, not list).
6969
parsed: dict = json.loads(result)
@@ -1103,7 +1103,7 @@ async def invoke() -> Any:
11031103
# Parse JSON to dict only when outputs_to_state is configured.
11041104
# ToolInvoker requires dict for _merge_tool_outputs(); ToolCallResult.result expects str otherwise.
11051105
if self.outputs_to_state:
1106-
return self.extract_first_text(result)
1106+
return extract_first_text_element(result)
11071107

11081108
return result
11091109
except (MCPError, TimeoutError) as e:
@@ -1134,7 +1134,7 @@ async def ainvoke(self, **kwargs: Any) -> str | dict[str, Any]:
11341134
# Parse JSON to dict only when outputs_to_state is configured.
11351135
# ToolInvoker requires dict for _merge_tool_outputs(); ToolCallResult.result expects str otherwise.
11361136
if self.outputs_to_state:
1137-
return extract_first_text(result)
1137+
return extract_first_text_element(result)
11381138

11391139
return result
11401140
except asyncio.TimeoutError as e:

integrations/mcp/tests/test_mcp_tool.py

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
MCPTool,
1616
StdioServerInfo,
1717
)
18-
from haystack_integrations.tools.mcp.mcp_tool import StdioClient
18+
from haystack_integrations.tools.mcp.mcp_tool import StdioClient, extract_first_text_element
1919

2020
from .mcp_memory_transport import InMemoryServerInfo
2121
from .mcp_servers_fixtures import calculator_mcp, echo_mcp
@@ -27,6 +27,23 @@ def simple_haystack_tool(name: str) -> str:
2727
return f"Hello, {name}!"
2828

2929

30+
def test_extract_first_text_element():
31+
"""Test that extract_first_text skips non-text blocks and parses the first text block."""
32+
result = json.dumps(
33+
{
34+
"content": [
35+
{"type": "image", "data": "ignored"},
36+
{"type": "text", "text": '{"answer": 42}'},
37+
{"type": "text", "text": '{"answer": 7}'},
38+
]
39+
}
40+
)
41+
42+
extracted = extract_first_text_element(result)
43+
44+
assert extracted == {"answer": 42}
45+
46+
3047
class TestMCPTool:
3148
"""Tests for the MCPTool class using in-memory servers."""
3249

0 commit comments

Comments
 (0)