From bf82b980195decfdb7944b2bc7597aab28533f8f Mon Sep 17 00:00:00 2001 From: Lenin Mookiah <2639584+leninworld@users.noreply.github.com> Date: Sun, 22 Nov 2026 09:00:36 -0800 Subject: [PATCH 1/4] fix(server): run direct MCP tool calls through overridden step (#1507) When an MCPEnvironment overrides step_async, a direct /mcp tools/call now goes through call_mcp_style_step, so the environment's step and time limits, done/reward and calls after the episode end apply to direct MCP calls. The JSON-RPC response shape is unchanged; tools/list and environments without a step_async override keep the direct dispatch. --- docs/source/environments/posttrain.md | 5 +- docs/source/tutorials/mcp-environment.md | 2 +- src/openenv/core/env_server/http_server.py | 39 +- .../core/test_mcp/test_mcp_step_lifecycle.py | 387 ++++++++++++++++++ 4 files changed, 428 insertions(+), 5 deletions(-) create mode 100644 tests/core/test_mcp/test_mcp_step_lifecycle.py diff --git a/docs/source/environments/posttrain.md b/docs/source/environments/posttrain.md index 4630304038..70250382bb 100644 --- a/docs/source/environments/posttrain.md +++ b/docs/source/environments/posttrain.md @@ -121,8 +121,9 @@ Through `step(CallToolAction(...))`, an episode ends when the agent calls `submit`, after `max_steps` tool calls (default 100) or after the task's time limit. The step and time limits give reward 0. -Direct `/mcp` calls, including `env.call_tool`, bypass the step and time limits -and do not return the final step observation with reward and `service_spend`. +Direct `/mcp` calls, including `env.call_tool`, follow the environment's step and +time limits. They still return only the JSON-RPC tool result, not the final step +observation with reward and `service_spend`. If the score job itself fails, times out or is cancelled, the episode ends unscored: `reward` is `None` and `episode_end.reason` is `score_failed`, since diff --git a/docs/source/tutorials/mcp-environment.md b/docs/source/tutorials/mcp-environment.md index 4d54f60496..4e0ab4414f 100644 --- a/docs/source/tutorials/mcp-environment.md +++ b/docs/source/tutorials/mcp-environment.md @@ -267,4 +267,4 @@ You will see the discovery call, two tool invocations, and an error case printed - **MCP in both modes**: [Simulation vs Production](../guides/simulation-vs-production) covers `step()` vs `step_async()`, the `call_tool()` convenience path, and common debugging questions. - **A richer MCP environment** — [`envs/finqa_env/`](https://github.com/openenv/OpenEnv/tree/main/envs/finqa_env) shows tool calls participating in episode progression, rewards, and terminal submission — not just a stateless echo. - **Design rationale** — [RFC 003](https://github.com/openenv/OpenEnv/blob/main/rfcs/003-mcp-support.md) explains why OpenEnv picked MCP as the agent boundary and how tool-calling and CodeAct styles share the same plumbing. -- **Serving tools to an external agent** — the `/mcp` JSON-RPC endpoint is available alongside `/ws` on any MCP environment server. Point an MCP-compatible client at it for production inference without going through the step loop. This direct path bypasses reward computation, step counts, and episode termination, and it exposes only registered MCP tools — not `reset`, `step`, or `state`. +- **Serving tools to an external agent** — the `/mcp` JSON-RPC endpoint is available alongside `/ws` on any MCP environment server. Point an MCP-compatible client at it for production inference. When an environment overrides `step_async()`, direct tool calls use that lifecycle for reward computation, step counts, and episode termination; otherwise they retain the direct MCP dispatch. The endpoint exposes only registered MCP tools — not `reset`, `step`, or `state`. diff --git a/src/openenv/core/env_server/http_server.py b/src/openenv/core/env_server/http_server.py index 640905b386..580102259b 100644 --- a/src/openenv/core/env_server/http_server.py +++ b/src/openenv/core/env_server/http_server.py @@ -47,7 +47,7 @@ from ._utils import overrides_method from .interfaces import Environment -from .mcp_environment import get_server_tools +from .mcp_environment import get_server_tools, MCPEnvironment from .mcp_types import ( CallToolAction, CallToolObservation, @@ -1481,6 +1481,41 @@ async def call_mcp_style_step(action: Action) -> Observation: request_id=request_id, ) + uses_step_lifecycle = isinstance( + _env, MCPEnvironment + ) and overrides_method(_env.step_async, MCPEnvironment.step_async) + if uses_step_lifecycle: + observation = await call_mcp_style_step( + CallToolAction( + tool_name=tool_name, + arguments=arguments, + ) + ) + if not isinstance(observation, CallToolObservation): + return JsonRpcResponse.success( + result=None, + request_id=request_id, + ) + if observation.error: + err_code = ( + JsonRpcErrorCode.INVALID_PARAMS + if observation.error.error_type + in ( + ToolErrorType.INVALID_ARGS, + ToolErrorType.TOOL_NOT_FOUND, + ) + else JsonRpcErrorCode.INTERNAL_ERROR + ) + return JsonRpcResponse.error_response( + err_code, + observation.error.message, + request_id=request_id, + ) + return JsonRpcResponse.success( + result=_make_json_serializable(observation.result), + request_id=request_id, + ) + if hasattr(_env, "_mode_tools") and any( m is not None for m in _env._mode_tools.get(tool_name, {}) ): @@ -2002,7 +2037,7 @@ async def get_schemas() -> SchemaResponse: async def mcp_endpoint(request_raw: Request) -> Dict[str, Any]: """MCP JSON-RPC endpoint for production mode. - Bypasses step() overhead and provides direct access to MCP tools. + Uses an environment's overridden step lifecycle when present. Supports tools/list and tools/call methods. """ # Parse JSON manually to handle parse errors gracefully diff --git a/tests/core/test_mcp/test_mcp_step_lifecycle.py b/tests/core/test_mcp/test_mcp_step_lifecycle.py new file mode 100644 index 0000000000..f6a5e9ff49 --- /dev/null +++ b/tests/core/test_mcp/test_mcp_step_lifecycle.py @@ -0,0 +1,387 @@ +# SPDX-License-Identifier: BSD-3-Clause + +"""Lifecycle coverage for MCP tool calls exposed by the environment server.""" + +from typing import Any, Callable + +from fastapi.testclient import TestClient +from fastmcp import FastMCP +from openenv.core.env_server.http_server import create_app +from openenv.core.env_server.mcp_environment import MCPEnvironment +from openenv.core.env_server.mcp_types import CallToolAction, CallToolObservation +from openenv.core.env_server.types import Action, Observation, State + + +class FakeClock: + def __init__(self) -> None: + self.now = 0.0 + + def __call__(self) -> float: + return self.now + + def advance(self, seconds: float) -> None: + self.now += seconds + + +class LifecycleMCPEnvironment(MCPEnvironment): + """Small MCP environment with injectable episode limits.""" + + def __init__( + self, + clock: Callable[[], float], + max_steps: int = 2, + time_limit_s: float = 10.0, + ) -> None: + self.clock = clock + self.max_steps = max_steps + self.time_limit_s = time_limit_s + self.started_at = clock() + self.done = False + self.tool_calls = 0 + self._state = State(episode_id="lifecycle", step_count=0) + + server = FastMCP("lifecycle-test") + + @server.tool + def record(value: int = 1) -> int: + self.tool_calls += 1 + return value + + @server.tool + def fail() -> None: + raise RuntimeError("tool failed") + + super().__init__(server) + + def reset(self, **_: Any) -> Observation: + self.started_at = self.clock() + self.done = False + self.tool_calls = 0 + self._state = State(episode_id="lifecycle", step_count=0) + return Observation(done=False, reward=0.0) + + def _step_impl(self, action: Action, **_: Any) -> Observation: + return Observation(metadata={"action": str(action)}) + + def _finish(self, observation: Observation) -> Observation: + if ( + self._state.step_count >= self.max_steps + or self.clock() - self.started_at >= self.time_limit_s + ): + self.done = True + observation.done = True + return observation + + def step(self, action: Action, **kwargs: Any) -> Observation: + if self.done: + return Observation(done=True) + self._state.step_count += 1 + return self._finish(super().step(action, **kwargs)) + + async def step_async(self, action: Action, **kwargs: Any) -> Observation: + if self.done: + return Observation(done=True) + self._state.step_count += 1 + return self._finish(await super().step_async(action, **kwargs)) + + @property + def state(self) -> State: + return self._state + + +class DirectMCPEnvironment(MCPEnvironment): + """MCP environment that retains the base class direct dispatch.""" + + def __init__(self) -> None: + self.tool_calls = 0 + self._state = State(episode_id="direct", step_count=0) + server = FastMCP("direct-test") + + @server.tool + def record() -> str: + self.tool_calls += 1 + return "direct" + + super().__init__(server) + + def reset(self, **_: Any) -> Observation: + return Observation() + + def _step_impl(self, action: Action, **_: Any) -> Observation: + return Observation(metadata={"action": str(action)}) + + @property + def state(self) -> State: + return self._state + + +class SyncOnlyMCPEnvironment(DirectMCPEnvironment): + """MCP environment that overrides only the synchronous step method.""" + + def __init__(self) -> None: + self.step_calls = 0 + super().__init__() + + def step(self, action: Action, **kwargs: Any) -> Observation: + self.step_calls += 1 + return super().step(action, **kwargs) + + +def make_app(factory: Callable[[], MCPEnvironment]): + return create_app( + env=factory, + action_cls=CallToolAction, + observation_cls=CallToolObservation, + mode="production", + ) + + +def create_session(client: TestClient) -> str: + response = client.post( + "/mcp", + json={ + "jsonrpc": "2.0", + "method": "openenv/session/create", + "params": {}, + "id": 1, + }, + ) + return response.json()["result"]["session_id"] + + +def call_tool(client: TestClient, session_id: str, request_id: int = 2) -> dict: + response = client.post( + "/mcp", + json={ + "jsonrpc": "2.0", + "method": "tools/call", + "params": { + "name": "record", + "arguments": {"value": request_id}, + "session_id": session_id, + }, + "id": request_id, + }, + ) + return response.json() + + +def test_http_mcp_calls_use_step_and_stop_at_limit() -> None: + clock = FakeClock() + instances: list[LifecycleMCPEnvironment] = [] + + def factory() -> LifecycleMCPEnvironment: + env = LifecycleMCPEnvironment(clock) + instances.append(env) + return env + + with TestClient(make_app(factory)) as client: + session_id = create_session(client) + env = instances[-1] + + assert "result" in call_tool(client, session_id, 2) + second = call_tool(client, session_id, 3) + after_end = call_tool(client, session_id, 4) + + assert "result" in second + assert after_end["result"] is None + assert env.state.step_count == 2 + assert env.tool_calls == 2 + assert env.done is True + + +def test_mcp_websocket_calls_use_step_once() -> None: + clock = FakeClock() + instances: list[LifecycleMCPEnvironment] = [] + + def factory() -> LifecycleMCPEnvironment: + env = LifecycleMCPEnvironment(clock) + instances.append(env) + return env + + with TestClient(make_app(factory)) as client: + with client.websocket_connect("/mcp") as websocket: + for request_id in (1, 2, 3): + websocket.send_json( + { + "jsonrpc": "2.0", + "method": "tools/call", + "params": { + "name": "record", + "arguments": {"value": request_id}, + }, + "id": request_id, + } + ) + response = websocket.receive_json() + + env = instances[-1] + assert response["result"] is None + assert env.state.step_count == 2 + assert env.tool_calls == 2 + + +def test_http_mcp_and_websocket_step_share_one_episode_without_double_counting() -> ( + None +): + clock = FakeClock() + instances: list[LifecycleMCPEnvironment] = [] + + def factory() -> LifecycleMCPEnvironment: + env = LifecycleMCPEnvironment(clock) + instances.append(env) + return env + + with TestClient(make_app(factory)) as client: + session_id = create_session(client) + env = instances[-1] + call_tool(client, session_id) + + with client.websocket_connect(f"/ws?session_id={session_id}") as websocket: + websocket.send_json( + { + "type": "step", + "data": { + "type": "call_tool", + "tool_name": "record", + "arguments": {"value": 3}, + }, + } + ) + response = websocket.receive_json() + + assert response["type"] == "observation" + assert response["data"]["done"] is True + assert env.state.step_count == 2 + assert env.tool_calls == 2 + + +def test_time_limit_and_calls_after_episode_end() -> None: + clock = FakeClock() + instances: list[LifecycleMCPEnvironment] = [] + + def factory() -> LifecycleMCPEnvironment: + env = LifecycleMCPEnvironment(clock) + instances.append(env) + return env + + with TestClient(make_app(factory)) as client: + session_id = create_session(client) + env = instances[-1] + clock.advance(11) + + first = call_tool(client, session_id) + after_end = call_tool(client, session_id, 3) + + assert "result" in first + assert after_end["result"] is None + assert env.state.step_count == 1 + assert env.tool_calls == 1 + assert env.done is True + + +def test_tools_list_does_not_count_as_a_step() -> None: + clock = FakeClock() + instances: list[LifecycleMCPEnvironment] = [] + + def factory() -> LifecycleMCPEnvironment: + env = LifecycleMCPEnvironment(clock) + instances.append(env) + return env + + with TestClient(make_app(factory)) as client: + session_id = create_session(client) + response = client.post( + "/mcp", + json={ + "jsonrpc": "2.0", + "method": "tools/list", + "params": {"session_id": session_id}, + "id": 2, + }, + ) + + assert "tools" in response.json()["result"] + assert instances[-1].state.step_count == 0 + + +def test_tool_errors_keep_existing_json_rpc_mapping() -> None: + clock = FakeClock() + + with TestClient(make_app(lambda: LifecycleMCPEnvironment(clock))) as client: + session_id = create_session(client) + missing = client.post( + "/mcp", + json={ + "jsonrpc": "2.0", + "method": "tools/call", + "params": { + "name": "missing", + "session_id": session_id, + }, + "id": 2, + }, + ).json() + failed = client.post( + "/mcp", + json={ + "jsonrpc": "2.0", + "method": "tools/call", + "params": {"name": "fail", "session_id": session_id}, + "id": 3, + }, + ).json() + + assert missing["error"]["code"] == -32602 + assert failed["error"]["code"] == -32603 + + +def test_environment_without_step_override_keeps_direct_dispatch() -> None: + instances: list[DirectMCPEnvironment] = [] + + def factory() -> DirectMCPEnvironment: + env = DirectMCPEnvironment() + instances.append(env) + return env + + with TestClient(make_app(factory)) as client: + session_id = create_session(client) + response = client.post( + "/mcp", + json={ + "jsonrpc": "2.0", + "method": "tools/call", + "params": {"name": "record", "session_id": session_id}, + "id": 2, + }, + ).json() + + assert "result" in response + assert instances[-1].tool_calls == 1 + assert instances[-1].state.step_count == 0 + + +def test_environment_with_only_sync_step_override_keeps_direct_dispatch() -> None: + instances: list[SyncOnlyMCPEnvironment] = [] + + def factory() -> SyncOnlyMCPEnvironment: + env = SyncOnlyMCPEnvironment() + instances.append(env) + return env + + with TestClient(make_app(factory)) as client: + session_id = create_session(client) + response = client.post( + "/mcp", + json={ + "jsonrpc": "2.0", + "method": "tools/call", + "params": {"name": "record", "session_id": session_id}, + "id": 2, + }, + ).json() + + # This matches the current WebSocket step dispatch for a sync-only override. + assert "result" in response + assert instances[-1].tool_calls == 1 + assert instances[-1].step_calls == 0 From 12564b6ff6386b2b3ffb7e7b69b6546b19a8ecd7 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Wed, 2 Dec 2026 11:51:48 +0000 Subject: [PATCH 2/4] refactor(server): share MCP tools/call observation handling; test stateless /mcp call (#1507) Fold the step-lifecycle branch into the existing mode-tool branch instead of duplicating the error mapping, rename the error test to say what it checks, and cover a /mcp call without a session. Co-authored-by: burtenshaw --- src/openenv/core/env_server/http_server.py | 48 +++++-------------- .../core/test_mcp/test_mcp_step_lifecycle.py | 30 +++++++++++- 2 files changed, 42 insertions(+), 36 deletions(-) diff --git a/src/openenv/core/env_server/http_server.py b/src/openenv/core/env_server/http_server.py index 580102259b..e102c80b60 100644 --- a/src/openenv/core/env_server/http_server.py +++ b/src/openenv/core/env_server/http_server.py @@ -1481,47 +1481,25 @@ async def call_mcp_style_step(action: Action) -> Observation: request_id=request_id, ) - uses_step_lifecycle = isinstance( - _env, MCPEnvironment - ) and overrides_method(_env.step_async, MCPEnvironment.step_async) - if uses_step_lifecycle: - observation = await call_mcp_style_step( - CallToolAction( - tool_name=tool_name, - arguments=arguments, - ) - ) - if not isinstance(observation, CallToolObservation): - return JsonRpcResponse.success( - result=None, - request_id=request_id, - ) - if observation.error: - err_code = ( - JsonRpcErrorCode.INVALID_PARAMS - if observation.error.error_type - in ( - ToolErrorType.INVALID_ARGS, - ToolErrorType.TOOL_NOT_FOUND, - ) - else JsonRpcErrorCode.INTERNAL_ERROR - ) - return JsonRpcResponse.error_response( - err_code, - observation.error.message, - request_id=request_id, - ) - return JsonRpcResponse.success( - result=_make_json_serializable(observation.result), - request_id=request_id, + obs: Observation | None = None + if isinstance(_env, MCPEnvironment) and overrides_method( + _env.step_async, MCPEnvironment.step_async + ): + obs = await call_mcp_style_step( + CallToolAction(tool_name=tool_name, arguments=arguments) ) - - if hasattr(_env, "_mode_tools") and any( + elif hasattr(_env, "_mode_tools") and any( m is not None for m in _env._mode_tools.get(tool_name, {}) ): obs = await _env._async_handle_call_tool( CallToolAction(tool_name=tool_name, arguments=arguments) ) + if obs is not None: + if not isinstance(obs, CallToolObservation): + return JsonRpcResponse.success( + result=None, + request_id=request_id, + ) if obs.error: err_code = ( JsonRpcErrorCode.INVALID_PARAMS diff --git a/tests/core/test_mcp/test_mcp_step_lifecycle.py b/tests/core/test_mcp/test_mcp_step_lifecycle.py index f6a5e9ff49..8f69b9c2af 100644 --- a/tests/core/test_mcp/test_mcp_step_lifecycle.py +++ b/tests/core/test_mcp/test_mcp_step_lifecycle.py @@ -305,7 +305,7 @@ def factory() -> LifecycleMCPEnvironment: assert instances[-1].state.step_count == 0 -def test_tool_errors_keep_existing_json_rpc_mapping() -> None: +def test_tool_errors_map_to_json_rpc_codes() -> None: clock = FakeClock() with TestClient(make_app(lambda: LifecycleMCPEnvironment(clock))) as client: @@ -385,3 +385,31 @@ def factory() -> SyncOnlyMCPEnvironment: assert "result" in response assert instances[-1].tool_calls == 1 assert instances[-1].step_calls == 0 + + +def test_http_mcp_call_without_session_runs_one_step_on_a_fresh_environment() -> None: + clock = FakeClock() + instances: list[LifecycleMCPEnvironment] = [] + + def factory() -> LifecycleMCPEnvironment: + env = LifecycleMCPEnvironment(clock, max_steps=1) + instances.append(env) + return env + + with TestClient(make_app(factory)) as client: + responses = [ + client.post( + "/mcp", + json={ + "jsonrpc": "2.0", + "method": "tools/call", + "params": {"name": "record"}, + "id": request_id, + }, + ).json() + for request_id in (1, 2) + ] + + assert all("result" in response for response in responses) + assert all(response["result"] is not None for response in responses) + assert [env.state.step_count for env in instances[-2:]] == [1, 1] From bd2fe45710a13091974325a27a9638baf581867e Mon Sep 17 00:00:00 2001 From: Lenin Mookiah <2639584+leninworld@users.noreply.github.com> Date: Wed, 2 Dec 2026 04:44:54 -0800 Subject: [PATCH 3/4] fix(server): return the tool value from step-lifecycle /mcp tools/call (#1507) For environments that override step_async, direct /mcp tools/call routes through call_mcp_style_step, whose CallToolObservation.result is a FastMCP CallToolResult. Return its hydrated data (or the structured content when hydration fails) so the JSON-RPC result matches the direct dispatch path. Results without structured content keep the CallToolResult shape. --- src/openenv/core/env_server/http_server.py | 29 ++++- .../core/test_mcp/test_mcp_step_lifecycle.py | 119 +++++++++++++++++- 2 files changed, 143 insertions(+), 5 deletions(-) diff --git a/src/openenv/core/env_server/http_server.py b/src/openenv/core/env_server/http_server.py index e102c80b60..05155cce26 100644 --- a/src/openenv/core/env_server/http_server.py +++ b/src/openenv/core/env_server/http_server.py @@ -43,6 +43,7 @@ WebSocket, WebSocketDisconnect, ) +from fastmcp.client.client import CallToolResult from pydantic import ValidationError from ._utils import overrides_method @@ -1482,9 +1483,10 @@ async def call_mcp_style_step(action: Action) -> Observation: ) obs: Observation | None = None - if isinstance(_env, MCPEnvironment) and overrides_method( - _env.step_async, MCPEnvironment.step_async - ): + uses_step_lifecycle = isinstance( + _env, MCPEnvironment + ) and overrides_method(_env.step_async, MCPEnvironment.step_async) + if uses_step_lifecycle: obs = await call_mcp_style_step( CallToolAction(tool_name=tool_name, arguments=arguments) ) @@ -1515,8 +1517,27 @@ async def call_mcp_style_step(action: Action) -> Observation: obs.error.message, request_id=request_id, ) + result = obs.result + if ( + uses_step_lifecycle + and isinstance(result, CallToolResult) + and not result.is_error + ): + if result.data is not None: + result = result.data + elif result.structured_content is not None: + structured_content = result.structured_content + fastmcp_meta = (result.meta or {}).get("fastmcp") + if ( + isinstance(fastmcp_meta, dict) + and fastmcp_meta.get("wrap_result") is True + ): + structured_content = structured_content.get( + "result" + ) + result = structured_content return JsonRpcResponse.success( - result=_make_json_serializable(obs.result), + result=_make_json_serializable(result), request_id=request_id, ) diff --git a/tests/core/test_mcp/test_mcp_step_lifecycle.py b/tests/core/test_mcp/test_mcp_step_lifecycle.py index 8f69b9c2af..e6ad39e56f 100644 --- a/tests/core/test_mcp/test_mcp_step_lifecycle.py +++ b/tests/core/test_mcp/test_mcp_step_lifecycle.py @@ -6,7 +6,10 @@ from fastapi.testclient import TestClient from fastmcp import FastMCP +from fastmcp.client.client import CallToolResult +from mcp.types import TextContent from openenv.core.env_server.http_server import create_app +from openenv.core.env_server.interfaces import Environment from openenv.core.env_server.mcp_environment import MCPEnvironment from openenv.core.env_server.mcp_types import CallToolAction, CallToolObservation from openenv.core.env_server.types import Action, Observation, State @@ -51,6 +54,18 @@ def record(value: int = 1) -> int: def fail() -> None: raise RuntimeError("tool failed") + @server.tool + def return_string() -> str: + return "tool result" + + @server.tool + def return_dict() -> dict[str, object]: + return {"value": 7, "nested": {"ok": True}} + + @server.tool + def return_none() -> None: + return None + super().__init__(server) def reset(self, **_: Any) -> Observation: @@ -127,7 +142,40 @@ def step(self, action: Action, **kwargs: Any) -> Observation: return super().step(action, **kwargs) -def make_app(factory: Callable[[], MCPEnvironment]): +class DirectToolEnvironment(Environment): + """Environment exposing a FastMCP server without an async step override.""" + + def __init__(self) -> None: + super().__init__() + self._state = State(episode_id="direct-tool", step_count=0) + server = FastMCP("direct-tool-test") + + @server.tool + def return_string() -> str: + return "tool result" + + @server.tool + def return_dict() -> dict[str, object]: + return {"value": 7, "nested": {"ok": True}} + + @server.tool + def return_none() -> None: + return None + + self.mcp_server = server + + def reset(self, **_: Any) -> Observation: + return Observation() + + def step(self, action: Action, **_: Any) -> Observation: + return Observation(metadata={"action": str(action)}) + + @property + def state(self) -> State: + return self._state + + +def make_app(factory: Callable[[], Environment]): return create_app( env=factory, action_cls=CallToolAction, @@ -361,6 +409,75 @@ def factory() -> DirectMCPEnvironment: assert instances[-1].state.step_count == 0 +def test_step_lifecycle_keeps_direct_tool_result_shape() -> None: + clock = FakeClock() + + def call_results(factory: Callable[[], Environment]) -> list[object]: + with TestClient(make_app(factory)) as client: + session_id = create_session(client) + return [ + client.post( + "/mcp", + json={ + "jsonrpc": "2.0", + "method": "tools/call", + "params": {"name": tool_name, "session_id": session_id}, + "id": request_id, + }, + ).json()["result"] + for request_id, tool_name in enumerate( + ("return_string", "return_dict", "return_none"), start=2 + ) + ] + + direct_results = call_results(DirectToolEnvironment) + lifecycle_results = call_results(lambda: LifecycleMCPEnvironment(clock)) + + assert ( + lifecycle_results + == direct_results + == [ + "tool result", + {"value": 7, "nested": {"ok": True}}, + None, + ] + ) + + +def test_step_lifecycle_falls_back_to_wrapped_structured_content() -> None: + clock = FakeClock() + + async def return_hydration_failure( + _tool_name: str, _arguments: dict + ) -> CallToolResult: + return CallToolResult( + content=[TextContent(type="text", text="tool result")], + structured_content={"result": "tool result"}, + meta={"fastmcp": {"wrap_result": True}}, + data=None, + is_error=False, + ) + + def factory() -> LifecycleMCPEnvironment: + env = LifecycleMCPEnvironment(clock) + env._async_call_tool = return_hydration_failure + return env + + with TestClient(make_app(factory)) as client: + session_id = create_session(client) + response = client.post( + "/mcp", + json={ + "jsonrpc": "2.0", + "method": "tools/call", + "params": {"name": "return_string", "session_id": session_id}, + "id": 2, + }, + ).json() + + assert response["result"] == "tool result" + + def test_environment_with_only_sync_step_override_keeps_direct_dispatch() -> None: instances: list[SyncOnlyMCPEnvironment] = [] From 0e6f981636edbfc21c910556f2804da6da3263a3 Mon Sep 17 00:00:00 2001 From: Lenin Mookiah <2639584+leninworld@users.noreply.github.com> Date: Wed, 2 Dec 2026 05:08:24 -0800 Subject: [PATCH 4/4] fix(server): keep mode-tool results and None returns on the step /mcp path Mode-specific tools keep the CallToolResult shape that the _mode_tools branch returns, and tools registered with mode=None return their raw value (including None) instead of the {"result": ...} structured content. --- src/openenv/core/env_server/http_server.py | 12 ++- .../core/test_mcp/test_mcp_step_lifecycle.py | 86 +++++++++++++++++++ 2 files changed, 94 insertions(+), 4 deletions(-) diff --git a/src/openenv/core/env_server/http_server.py b/src/openenv/core/env_server/http_server.py index 05155cce26..bd263e08ec 100644 --- a/src/openenv/core/env_server/http_server.py +++ b/src/openenv/core/env_server/http_server.py @@ -1486,13 +1486,14 @@ async def call_mcp_style_step(action: Action) -> Observation: uses_step_lifecycle = isinstance( _env, MCPEnvironment ) and overrides_method(_env.step_async, MCPEnvironment.step_async) + is_mode_tool = hasattr(_env, "_mode_tools") and any( + m is not None for m in _env._mode_tools.get(tool_name, {}) + ) if uses_step_lifecycle: obs = await call_mcp_style_step( CallToolAction(tool_name=tool_name, arguments=arguments) ) - elif hasattr(_env, "_mode_tools") and any( - m is not None for m in _env._mode_tools.get(tool_name, {}) - ): + elif is_mode_tool: obs = await _env._async_handle_call_tool( CallToolAction(tool_name=tool_name, arguments=arguments) ) @@ -1520,10 +1521,13 @@ async def call_mcp_style_step(action: Action) -> Observation: result = obs.result if ( uses_step_lifecycle + and not is_mode_tool and isinstance(result, CallToolResult) and not result.is_error ): - if result.data is not None: + if None in _env._mode_tools.get(tool_name, {}): + result = result.data + elif result.data is not None: result = result.data elif result.structured_content is not None: structured_content = result.structured_content diff --git a/tests/core/test_mcp/test_mcp_step_lifecycle.py b/tests/core/test_mcp/test_mcp_step_lifecycle.py index e6ad39e56f..e469dcc4dd 100644 --- a/tests/core/test_mcp/test_mcp_step_lifecycle.py +++ b/tests/core/test_mcp/test_mcp_step_lifecycle.py @@ -68,6 +68,22 @@ def return_none() -> None: super().__init__(server) + @self.tool() + def decorated_string() -> str: + return "decorated tool result" + + @self.tool() + def decorated_none() -> None: + return None + + @self.tool(mode="production") + def mode_string() -> str: + return "mode tool result" + + @self.tool(mode="production") + def mode_none() -> None: + return None + def reset(self, **_: Any) -> Observation: self.started_at = self.clock() self.done = False @@ -119,6 +135,14 @@ def record() -> str: super().__init__(server) + @self.tool(mode="production") + def mode_string() -> str: + return "mode tool result" + + @self.tool(mode="production") + def mode_none() -> None: + return None + def reset(self, **_: Any) -> Observation: return Observation() @@ -162,6 +186,14 @@ def return_dict() -> dict[str, object]: def return_none() -> None: return None + @server.tool + def decorated_string() -> str: + return "decorated tool result" + + @server.tool + def decorated_none() -> None: + return None + self.mcp_server = server def reset(self, **_: Any) -> Observation: @@ -444,6 +476,60 @@ def call_results(factory: Callable[[], Environment]) -> list[object]: ) +def test_step_lifecycle_keeps_mode_tool_result_shape() -> None: + clock = FakeClock() + + def call_results(factory: Callable[[], Environment]) -> list[object]: + with TestClient(make_app(factory)) as client: + session_id = create_session(client) + return [ + client.post( + "/mcp", + json={ + "jsonrpc": "2.0", + "method": "tools/call", + "params": {"name": tool_name, "session_id": session_id}, + "id": request_id, + }, + ).json()["result"] + for request_id, tool_name in enumerate( + ("mode_string", "mode_none"), start=2 + ) + ] + + direct_results = call_results(DirectMCPEnvironment) + lifecycle_results = call_results(lambda: LifecycleMCPEnvironment(clock)) + + assert lifecycle_results == direct_results + + +def test_step_lifecycle_keeps_decorated_tool_result_shape() -> None: + clock = FakeClock() + + def call_results(factory: Callable[[], Environment]) -> list[object]: + with TestClient(make_app(factory)) as client: + session_id = create_session(client) + return [ + client.post( + "/mcp", + json={ + "jsonrpc": "2.0", + "method": "tools/call", + "params": {"name": tool_name, "session_id": session_id}, + "id": request_id, + }, + ).json()["result"] + for request_id, tool_name in enumerate( + ("decorated_string", "decorated_none"), start=2 + ) + ] + + direct_results = call_results(DirectToolEnvironment) + lifecycle_results = call_results(lambda: LifecycleMCPEnvironment(clock)) + + assert lifecycle_results == direct_results == ["decorated tool result", None] + + def test_step_lifecycle_falls_back_to_wrapped_structured_content() -> None: clock = FakeClock()