From 05789b777e17e42beee89173ca7cb9deabb6f4bf Mon Sep 17 00:00:00 2001 From: Aafimalek <91587101+Aafimalek@users.noreply.github.com> Date: Wed, 25 Nov 2026 17:02:17 +0530 Subject: [PATCH 1/3] fix(mcp): apply timeout_s to tools registered with @self.tool() Mode-aware tools were called directly, ignoring the step timeout, and sync tools blocked the event loop. Run them under asyncio.wait_for (sync ones via asyncio.to_thread) and return the same TIMEOUT error as the FastMCP path. --- .../core/env_server/mcp_environment.py | 14 +++++++-- tests/core/test_mcp/test_mode_aware_tools.py | 29 +++++++++++++++++++ 2 files changed, 41 insertions(+), 2 deletions(-) diff --git a/src/openenv/core/env_server/mcp_environment.py b/src/openenv/core/env_server/mcp_environment.py index 7d683fab84..11e67c1efa 100644 --- a/src/openenv/core/env_server/mcp_environment.py +++ b/src/openenv/core/env_server/mcp_environment.py @@ -535,9 +535,10 @@ async def _async_handle_call_tool( func = mode_info[current_mode] try: 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) + result = await asyncio.wait_for(call, timeout=timeout) return CallToolObservation( tool_name=tool_name, result=CallToolResult( @@ -548,6 +549,15 @@ 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: return CallToolObservation( tool_name=tool_name, diff --git a/tests/core/test_mcp/test_mode_aware_tools.py b/tests/core/test_mcp/test_mode_aware_tools.py index cdeed0f238..dc94591ef8 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,30 @@ 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 From 1e6063b7ad0c730dba4ebb13375778de05d306d7 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Wed, 2 Dec 2026 11:47:36 +0000 Subject: [PATCH 2/3] docs(mcp): note worker-thread semantics of @self.tool(); add timeout and event-loop tests Co-authored-by: burtenshaw --- .../core/env_server/mcp_environment.py | 6 +++ tests/core/test_mcp/test_mode_aware_tools.py | 50 +++++++++++++++++++ 2 files changed, 56 insertions(+) diff --git a/src/openenv/core/env_server/mcp_environment.py b/src/openenv/core/env_server/mcp_environment.py index 11e67c1efa..037d32d9e7 100644 --- a/src/openenv/core/env_server/mcp_environment.py +++ b/src/openenv/core/env_server/mcp_environment.py @@ -351,6 +351,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. diff --git a/tests/core/test_mcp/test_mode_aware_tools.py b/tests/core/test_mcp/test_mode_aware_tools.py index dc94591ef8..550b0f26f0 100644 --- a/tests/core/test_mcp/test_mode_aware_tools.py +++ b/tests/core/test_mcp/test_mode_aware_tools.py @@ -761,3 +761,53 @@ def slow() -> str: assert obs.error is not None assert obs.error.error_type == ToolErrorType.TIMEOUT + + 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 From 7c31dcdfc7f1c713ccf143d13e7494a57191dcd1 Mon Sep 17 00:00:00 2001 From: Aafimalek <91587101+Aafimalek@users.noreply.github.com> Date: Fri, 4 Dec 2026 14:41:59 +0530 Subject: [PATCH 3/3] fix(mcp): report a tool's own TimeoutError as an execution error The timeout handler for @self.tool() tools also caught TimeoutError raised inside the tool (socket, urllib, aiohttp). On Python 3.11+ asyncio.TimeoutError is the builtin TimeoutError, so those were reported as ToolErrorType.TIMEOUT with a message naming timeout_s. Wrap the tool's own timeout before it reaches wait_for, so only timeout_s expiring maps to TIMEOUT. The tool's error is returned as EXECUTION_ERROR with its own message. Co-Authored-By: Claude Opus 5.5 --- .../core/env_server/mcp_environment.py | 20 +++++++++++++++-- tests/core/test_mcp/test_mode_aware_tools.py | 22 +++++++++++++++++++ 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/src/openenv/core/env_server/mcp_environment.py b/src/openenv/core/env_server/mcp_environment.py index 037d32d9e7..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. @@ -539,12 +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): call = func(**action.arguments) else: call = asyncio.to_thread(func, **action.arguments) - result = await asyncio.wait_for(call, timeout=timeout) + 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( @@ -565,6 +579,8 @@ async def _async_handle_call_tool( ), ) 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 550b0f26f0..77659f4977 100644 --- a/tests/core/test_mcp/test_mode_aware_tools.py +++ b/tests/core/test_mcp/test_mode_aware_tools.py @@ -762,6 +762,28 @@ def slow() -> str: 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"))