diff --git a/src/openenv/core/env_server/mcp_environment.py b/src/openenv/core/env_server/mcp_environment.py index 7d683fab84..9d96706f8a 100644 --- a/src/openenv/core/env_server/mcp_environment.py +++ b/src/openenv/core/env_server/mcp_environment.py @@ -84,6 +84,10 @@ def state(self): VALID_MODES = {"production", "simulation"} +class _ToolRaisedTimeout(Exception): + """Wraps a TimeoutError raised inside a tool so it isn't read as timeout_s expiring.""" + + def get_server_tools(mcp_server: Any) -> Dict[str, Any]: """ Get tools from a FastMCP server. @@ -351,6 +355,12 @@ def tool(self, mode: Optional[str] = None) -> Callable: """ Decorator for registering mode-aware tools. + Tools run under `timeout_s` (default `MCP_TOOL_CALL_TIMEOUT`). Sync tools run + in a worker thread, so they must not rely on thread-affine state (for example + a `sqlite3` connection created on another thread). A sync tool that times out + keeps running in its thread until it returns, because threads cannot be + cancelled. + Args: mode: Optional mode for the tool ("production" or "simulation"). If None, tool is available in all modes. @@ -533,11 +543,22 @@ async def _async_handle_call_tool( func = mode_info[None] elif current_mode in mode_info: func = mode_info[current_mode] - try: + + async def invoke(): if inspect.iscoroutinefunction(func): - result = await func(**action.arguments) + call = func(**action.arguments) else: - result = func(**action.arguments) + call = asyncio.to_thread(func, **action.arguments) + try: + return await call + except (asyncio.TimeoutError, TimeoutError) as e: + # A timeout raised by the tool itself (socket, HTTP client) + # is an execution error, not the MCP timeout_s expiring. + # On Python 3.11+ both are the builtin TimeoutError. + raise _ToolRaisedTimeout() from e + + try: + result = await asyncio.wait_for(invoke(), timeout=timeout) return CallToolObservation( tool_name=tool_name, result=CallToolResult( @@ -548,7 +569,18 @@ async def _async_handle_call_tool( is_error=False, ), ) + except asyncio.TimeoutError: + return CallToolObservation( + tool_name=tool_name, + result=None, + error=ToolError( + error_type=ToolErrorType.TIMEOUT, + message=f"Tool '{tool_name}' timed out after {timeout} seconds", + ), + ) except Exception as e: + if isinstance(e, _ToolRaisedTimeout): + e = e.__cause__ return CallToolObservation( tool_name=tool_name, result=None, diff --git a/tests/core/test_mcp/test_mode_aware_tools.py b/tests/core/test_mcp/test_mode_aware_tools.py index cdeed0f238..77659f4977 100644 --- a/tests/core/test_mcp/test_mode_aware_tools.py +++ b/tests/core/test_mcp/test_mode_aware_tools.py @@ -24,6 +24,7 @@ """ import asyncio +import time import pytest from fastmcp import FastMCP @@ -33,6 +34,7 @@ CallToolObservation, ListToolsAction, ListToolsObservation, + ToolErrorType, ) from openenv.core.env_server.types import Observation @@ -732,3 +734,102 @@ async def async_compute(x: int) -> str: # noqa: F811 "Result should be awaited, not a coroutine" ) assert result_sim == "ASYNC_SIM_99", f"Expected ASYNC_SIM_99, got {result_sim}" + + +class TestModeToolTimeout: + """Mode-specific tools honor timeout_s like FastMCP-registered tools.""" + + @pytest.mark.parametrize("is_async", [False, True]) + def test_slow_mode_tool_times_out(self, is_async): + env = MinimalMCPEnv(FastMCP("test-server")) + + if is_async: + + @env.tool() + async def slow() -> str: + await asyncio.sleep(1) + return "done" + + else: + + @env.tool() + def slow() -> str: + time.sleep(1) + return "done" + + obs = env.step(CallToolAction(tool_name="slow", arguments={}), timeout_s=0.1) + + assert obs.error is not None + assert obs.error.error_type == ToolErrorType.TIMEOUT + + @pytest.mark.parametrize("is_async", [False, True]) + def test_timeout_raised_by_tool_is_execution_error(self, is_async): + env = MinimalMCPEnv(FastMCP("test-server")) + + if is_async: + + @env.tool() + async def fetch() -> str: + raise TimeoutError("upstream read timed out") + + else: + + @env.tool() + def fetch() -> str: + raise TimeoutError("upstream read timed out") + + obs = env.step(CallToolAction(tool_name="fetch", arguments={}), timeout_s=5) + + assert obs.error is not None + assert obs.error.error_type == ToolErrorType.EXECUTION_ERROR + assert obs.error.message == "upstream read timed out" + + def test_timeout_returns_without_waiting_for_slow_async_call(self): + env = MinimalMCPEnv(FastMCP("test-server")) + + @env.tool() + def slow() -> str: + time.sleep(1) + return "done" + + async def run(): + start = time.monotonic() + obs = await env._async_handle_call_tool( + CallToolAction(tool_name="slow", arguments={}), timeout_s=0.1 + ) + return obs, time.monotonic() - start + + obs, elapsed = asyncio.run(run()) + + assert obs.error.error_type == ToolErrorType.TIMEOUT + assert elapsed < 0.9 + + def test_sync_mode_tool_does_not_block_event_loop(self): + env = MinimalMCPEnv(FastMCP("test-server")) + + @env.tool(mode="production") + def slow() -> str: + time.sleep(0.3) + return "done" + + async def run(): + ticks = 0 + + async def ticker(): + nonlocal ticks + while True: + await asyncio.sleep(0.01) + ticks += 1 + + task = asyncio.create_task(ticker()) + env.set_mode("production") + obs = await env._async_handle_call_tool( + CallToolAction(tool_name="slow", arguments={}) + ) + task.cancel() + return obs, ticks + + obs, ticks = asyncio.run(run()) + + assert obs.error is None + assert ticks > 5