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..bd263e08ec 100644 --- a/src/openenv/core/env_server/http_server.py +++ b/src/openenv/core/env_server/http_server.py @@ -43,11 +43,12 @@ WebSocket, WebSocketDisconnect, ) +from fastmcp.client.client import CallToolResult from pydantic import ValidationError 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,12 +1482,27 @@ async def call_mcp_style_step(action: Action) -> Observation: request_id=request_id, ) - if hasattr(_env, "_mode_tools") and any( + obs: Observation | None = None + 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 is_mode_tool: 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 @@ -1502,8 +1518,30 @@ async def call_mcp_style_step(action: Action) -> Observation: obs.error.message, request_id=request_id, ) + result = obs.result + if ( + uses_step_lifecycle + and not is_mode_tool + and isinstance(result, CallToolResult) + and not result.is_error + ): + 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 + 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, ) @@ -2002,7 +2040,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..e469dcc4dd --- /dev/null +++ b/tests/core/test_mcp/test_mcp_step_lifecycle.py @@ -0,0 +1,618 @@ +# 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 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 + + +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") + + @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) + + @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 + 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) + + @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() + + 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) + + +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 + + @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: + 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, + 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_map_to_json_rpc_codes() -> 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_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_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() + + 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] = [] + + 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 + + +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]