|
| 1 | +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +"""Unit tests for ToolTimeoutMiddleware.""" |
| 16 | + |
| 17 | +import anyio |
| 18 | +import httpx |
| 19 | +import mcp.types as mt |
| 20 | +import pytest |
| 21 | +from fastmcp.server.middleware import MiddlewareContext |
| 22 | +from fastmcp.tools.tool import ToolResult |
| 23 | +from mcp import McpError |
| 24 | +from mcp.types import ErrorData |
| 25 | +from mcp_proxy_for_aws.middleware.tool_timeout_middleware import ( |
| 26 | + ToolTimeoutMiddleware, |
| 27 | + _FailedToolResult, |
| 28 | +) |
| 29 | +from typing import Optional |
| 30 | +from unittest.mock import AsyncMock, Mock |
| 31 | + |
| 32 | + |
| 33 | +def _make_context(tool_name: str = 'test_tool') -> MiddlewareContext[mt.CallToolRequestParams]: |
| 34 | + """Create a minimal MiddlewareContext for tool calls.""" |
| 35 | + params = Mock(spec=mt.CallToolRequestParams) |
| 36 | + params.name = tool_name |
| 37 | + return MiddlewareContext[mt.CallToolRequestParams]( |
| 38 | + message=params, |
| 39 | + type='request', |
| 40 | + method='tools/call', |
| 41 | + ) |
| 42 | + |
| 43 | + |
| 44 | +def _make_middleware(tool_call_timeout: Optional[float] = 5.0) -> ToolTimeoutMiddleware: |
| 45 | + """Create a ToolTimeoutMiddleware with mocked dependencies.""" |
| 46 | + middleware = ToolTimeoutMiddleware( |
| 47 | + tool_call_timeout=tool_call_timeout, |
| 48 | + ) |
| 49 | + return middleware |
| 50 | + |
| 51 | + |
| 52 | +def _get_text(result: ToolResult, index: int = 0) -> str: |
| 53 | + """Extract text from a ToolResult content item.""" |
| 54 | + content = result.content[index] |
| 55 | + assert isinstance(content, mt.TextContent) |
| 56 | + return content.text |
| 57 | + |
| 58 | + |
| 59 | +class TestToolTimeoutMiddleware: |
| 60 | + """Test cases for ToolTimeoutMiddleware.""" |
| 61 | + |
| 62 | + @pytest.mark.asyncio |
| 63 | + async def test_passes_through_on_success(self): |
| 64 | + """Successful tool calls pass through unchanged.""" |
| 65 | + middleware = _make_middleware() |
| 66 | + expected = ToolResult(content=[mt.TextContent(type='text', text='ok')]) |
| 67 | + call_next = AsyncMock(return_value=expected) |
| 68 | + context = _make_context() |
| 69 | + |
| 70 | + result = await middleware.on_call_tool(context, call_next) |
| 71 | + |
| 72 | + assert result is expected |
| 73 | + assert not isinstance(result, _FailedToolResult) |
| 74 | + call_next.assert_awaited_once_with(context) |
| 75 | + |
| 76 | + @pytest.mark.asyncio |
| 77 | + async def test_catches_exception_returns_error_result(self): |
| 78 | + """Exceptions are caught and returned as error ToolResults.""" |
| 79 | + middleware = _make_middleware() |
| 80 | + call_next = AsyncMock( |
| 81 | + side_effect=McpError(ErrorData(code=-1, message='Connection closed')) |
| 82 | + ) |
| 83 | + context = _make_context() |
| 84 | + |
| 85 | + result = await middleware.on_call_tool(context, call_next) |
| 86 | + |
| 87 | + assert isinstance(result, _FailedToolResult) |
| 88 | + assert len(result.content) == 1 |
| 89 | + text = _get_text(result) |
| 90 | + assert 'Connection closed' in text |
| 91 | + |
| 92 | + @pytest.mark.asyncio |
| 93 | + async def test_timeout_returns_error_result(self): |
| 94 | + """Tool calls that exceed the timeout return an error ToolResult.""" |
| 95 | + middleware = _make_middleware(tool_call_timeout=0.1) |
| 96 | + |
| 97 | + async def hang_forever(context: MiddlewareContext[mt.CallToolRequestParams]) -> ToolResult: |
| 98 | + await anyio.sleep(999) |
| 99 | + return ToolResult(content=[]) # unreachable |
| 100 | + |
| 101 | + context = _make_context(tool_name='slow_tool') |
| 102 | + |
| 103 | + result = await middleware.on_call_tool(context, hang_forever) |
| 104 | + |
| 105 | + assert isinstance(result, _FailedToolResult) |
| 106 | + assert len(result.content) == 1 |
| 107 | + text = _get_text(result) |
| 108 | + assert 'slow_tool' in text |
| 109 | + |
| 110 | + @pytest.mark.asyncio |
| 111 | + async def test_credential_error_suggests_profile(self): |
| 112 | + """Credential errors suggest using long-lived credentials.""" |
| 113 | + middleware = _make_middleware() |
| 114 | + response = Mock(spec=httpx.Response) |
| 115 | + response.status_code = 401 |
| 116 | + call_next = AsyncMock( |
| 117 | + side_effect=httpx.HTTPStatusError('Unauthorized', request=Mock(), response=response) |
| 118 | + ) |
| 119 | + context = _make_context() |
| 120 | + |
| 121 | + result = await middleware.on_call_tool(context, call_next) |
| 122 | + |
| 123 | + assert isinstance(result, _FailedToolResult) |
| 124 | + text = _get_text(result) |
| 125 | + assert 'expired or invalid AWS credentials' in text |
| 126 | + assert '--profile' in text |
| 127 | + |
| 128 | + @pytest.mark.asyncio |
| 129 | + async def test_non_credential_error_no_suggestion(self): |
| 130 | + """Non-credential errors do not suggest credential remediation.""" |
| 131 | + middleware = _make_middleware() |
| 132 | + call_next = AsyncMock(side_effect=RuntimeError('transport died')) |
| 133 | + context = _make_context() |
| 134 | + |
| 135 | + result = await middleware.on_call_tool(context, call_next) |
| 136 | + |
| 137 | + assert isinstance(result, _FailedToolResult) |
| 138 | + text = _get_text(result) |
| 139 | + assert '--profile' not in text |
| 140 | + |
| 141 | + @pytest.mark.asyncio |
| 142 | + async def test_no_timeout_when_none(self): |
| 143 | + """When tool_call_timeout is None, no timeout is applied.""" |
| 144 | + middleware = _make_middleware(tool_call_timeout=None) |
| 145 | + expected = ToolResult(content=[mt.TextContent(type='text', text='ok')]) |
| 146 | + call_next = AsyncMock(return_value=expected) |
| 147 | + context = _make_context() |
| 148 | + |
| 149 | + result = await middleware.on_call_tool(context, call_next) |
| 150 | + |
| 151 | + assert result is expected |
0 commit comments