|
| 1 | +"""Tests for ConnectionSafeMcpTool — connection errors are returned as |
| 2 | +error text to the LLM instead of raised, preventing tight retry loops. |
| 3 | +
|
| 4 | +See: https://github.com/kagent-dev/kagent/issues/1530 |
| 5 | +""" |
| 6 | + |
| 7 | +import asyncio |
| 8 | +from unittest.mock import AsyncMock, MagicMock, patch |
| 9 | + |
| 10 | +import httpx |
| 11 | +import pytest |
| 12 | +from google.adk.tools.mcp_tool.mcp_tool import McpTool |
| 13 | +from google.adk.tools.mcp_tool.mcp_toolset import McpToolset |
| 14 | +from mcp.shared.exceptions import McpError |
| 15 | + |
| 16 | +from kagent.adk._mcp_toolset import ConnectionSafeMcpTool, KAgentMcpToolset |
| 17 | + |
| 18 | + |
| 19 | +def _make_connection_safe_tool(side_effect): |
| 20 | + """Create a ConnectionSafeMcpTool with a mocked super().run_async.""" |
| 21 | + tool = ConnectionSafeMcpTool.__new__(ConnectionSafeMcpTool) |
| 22 | + tool.name = "test-tool" |
| 23 | + tool._mcp_tool = MagicMock() |
| 24 | + tool._mcp_tool.name = "test-tool" |
| 25 | + tool._mcp_session_manager = AsyncMock() |
| 26 | + tool._header_provider = None |
| 27 | + tool._auth_config = None |
| 28 | + tool._confirmation_config = None |
| 29 | + tool._progress_callback = None |
| 30 | + tool._parent_run_async = AsyncMock(side_effect=side_effect) |
| 31 | + return tool |
| 32 | + |
| 33 | + |
| 34 | +@pytest.mark.asyncio |
| 35 | +async def test_connection_reset_error_returns_error_dict(): |
| 36 | + """ConnectionResetError should be caught and returned as error text.""" |
| 37 | + tool = _make_connection_safe_tool(ConnectionResetError("Connection reset by peer")) |
| 38 | + |
| 39 | + with patch.object(McpTool, "run_async", tool._parent_run_async): |
| 40 | + result = await tool.run_async(args={"key": "value"}, tool_context=MagicMock()) |
| 41 | + |
| 42 | + assert "error" in result |
| 43 | + assert "ConnectionResetError" in result["error"] |
| 44 | + assert "Connection reset by peer" in result["error"] |
| 45 | + assert "Do not retry" in result["error"] |
| 46 | + |
| 47 | + |
| 48 | +@pytest.mark.asyncio |
| 49 | +async def test_connection_refused_error_returns_error_dict(): |
| 50 | + """ConnectionRefusedError should be caught and returned as error text.""" |
| 51 | + tool = _make_connection_safe_tool(ConnectionRefusedError("Connection refused")) |
| 52 | + |
| 53 | + with patch.object(McpTool, "run_async", tool._parent_run_async): |
| 54 | + result = await tool.run_async(args={}, tool_context=MagicMock()) |
| 55 | + |
| 56 | + assert "error" in result |
| 57 | + assert "ConnectionRefusedError" in result["error"] |
| 58 | + |
| 59 | + |
| 60 | +@pytest.mark.asyncio |
| 61 | +async def test_timeout_error_returns_error_dict(): |
| 62 | + """TimeoutError should be caught and returned as error text.""" |
| 63 | + tool = _make_connection_safe_tool(TimeoutError("timed out")) |
| 64 | + |
| 65 | + with patch.object(McpTool, "run_async", tool._parent_run_async): |
| 66 | + result = await tool.run_async(args={}, tool_context=MagicMock()) |
| 67 | + |
| 68 | + assert "error" in result |
| 69 | + assert "TimeoutError" in result["error"] |
| 70 | + |
| 71 | + |
| 72 | +@pytest.mark.asyncio |
| 73 | +async def test_httpx_connect_error_returns_error_dict(): |
| 74 | + """httpx.ConnectError should be caught via httpx.TransportError.""" |
| 75 | + tool = _make_connection_safe_tool(httpx.ConnectError("connection refused")) |
| 76 | + |
| 77 | + with patch.object(McpTool, "run_async", tool._parent_run_async): |
| 78 | + result = await tool.run_async(args={}, tool_context=MagicMock()) |
| 79 | + |
| 80 | + assert "error" in result |
| 81 | + assert "ConnectError" in result["error"] |
| 82 | + |
| 83 | + |
| 84 | +@pytest.mark.asyncio |
| 85 | +async def test_httpx_read_error_returns_error_dict(): |
| 86 | + """httpx.ReadError (connection reset by peer) should be caught.""" |
| 87 | + tool = _make_connection_safe_tool(httpx.ReadError("peer closed connection")) |
| 88 | + |
| 89 | + with patch.object(McpTool, "run_async", tool._parent_run_async): |
| 90 | + result = await tool.run_async(args={}, tool_context=MagicMock()) |
| 91 | + |
| 92 | + assert "error" in result |
| 93 | + assert "ReadError" in result["error"] |
| 94 | + |
| 95 | + |
| 96 | +@pytest.mark.asyncio |
| 97 | +async def test_httpx_connect_timeout_returns_error_dict(): |
| 98 | + """httpx.ConnectTimeout should be caught via httpx.TransportError.""" |
| 99 | + tool = _make_connection_safe_tool(httpx.ConnectTimeout("timed out")) |
| 100 | + |
| 101 | + with patch.object(McpTool, "run_async", tool._parent_run_async): |
| 102 | + result = await tool.run_async(args={}, tool_context=MagicMock()) |
| 103 | + |
| 104 | + assert "error" in result |
| 105 | + assert "ConnectTimeout" in result["error"] |
| 106 | + |
| 107 | + |
| 108 | +@pytest.mark.asyncio |
| 109 | +async def test_mcp_error_returns_error_dict(): |
| 110 | + """McpError (raised by MCP session on stream drop / read timeout) should be caught.""" |
| 111 | + from mcp.types import ErrorData |
| 112 | + |
| 113 | + tool = _make_connection_safe_tool(McpError(ErrorData(code=-1, message="session read timeout"))) |
| 114 | + |
| 115 | + with patch.object(McpTool, "run_async", tool._parent_run_async): |
| 116 | + result = await tool.run_async(args={}, tool_context=MagicMock()) |
| 117 | + |
| 118 | + assert "error" in result |
| 119 | + assert "McpError" in result["error"] |
| 120 | + assert "session read timeout" in result["error"] |
| 121 | + |
| 122 | + |
| 123 | +@pytest.mark.asyncio |
| 124 | +async def test_non_connection_error_still_raises(): |
| 125 | + """Non-connection errors (e.g. ValueError) should still propagate.""" |
| 126 | + tool = _make_connection_safe_tool(ValueError("bad argument")) |
| 127 | + |
| 128 | + with patch.object(McpTool, "run_async", tool._parent_run_async): |
| 129 | + with pytest.raises(ValueError, match="bad argument"): |
| 130 | + await tool.run_async(args={}, tool_context=MagicMock()) |
| 131 | + |
| 132 | + |
| 133 | +@pytest.mark.asyncio |
| 134 | +async def test_cancelled_error_still_raises(): |
| 135 | + """CancelledError must propagate — it's not a connection error.""" |
| 136 | + tool = _make_connection_safe_tool(asyncio.CancelledError("cancelled")) |
| 137 | + |
| 138 | + with patch.object(McpTool, "run_async", tool._parent_run_async): |
| 139 | + with pytest.raises(asyncio.CancelledError): |
| 140 | + await tool.run_async(args={}, tool_context=MagicMock()) |
| 141 | + |
| 142 | + |
| 143 | +@pytest.mark.asyncio |
| 144 | +async def test_get_tools_wraps_mcp_tools(): |
| 145 | + """KAgentMcpToolset.get_tools should wrap McpTool instances with ConnectionSafeMcpTool.""" |
| 146 | + # Create a real McpTool instance (bypassing __init__) so isinstance checks work |
| 147 | + fake_mcp_tool = McpTool.__new__(McpTool) |
| 148 | + fake_mcp_tool.name = "wrapped-tool" |
| 149 | + fake_mcp_tool._some_attr = "value" |
| 150 | + |
| 151 | + # A non-McpTool object that should pass through unchanged |
| 152 | + fake_other_tool = MagicMock() |
| 153 | + fake_other_tool.name = "other-tool" |
| 154 | + |
| 155 | + toolset = KAgentMcpToolset.__new__(KAgentMcpToolset) |
| 156 | + |
| 157 | + async def mock_super_get_tools(self_arg, readonly_context=None): |
| 158 | + return [fake_mcp_tool, fake_other_tool] |
| 159 | + |
| 160 | + with patch.object(McpToolset, "get_tools", mock_super_get_tools): |
| 161 | + tools = await toolset.get_tools() |
| 162 | + |
| 163 | + assert len(tools) == 2 |
| 164 | + assert isinstance(tools[0], ConnectionSafeMcpTool) |
| 165 | + assert tools[0].name == "wrapped-tool" |
| 166 | + assert tools[0]._some_attr == "value" |
| 167 | + # Non-McpTool should pass through unchanged |
| 168 | + assert tools[1] is fake_other_tool |
0 commit comments