From 1b1fc1c24c7709b0b85a87a3760807f8c294620e Mon Sep 17 00:00:00 2001 From: Tu Trinh Date: Sat, 21 Nov 2026 02:14:48 +0000 Subject: [PATCH 1/8] fix(gateway): forward undeclared tool arguments to the child on the MCP path The MCP proxy's argument model ignored keys the tool's schema didn't declare, so a call such as {"query": ...} to a tool taking `q` reached the child as {} and returned unfiltered results with isError false, while /step forwarded the same call unchanged and the child refused it. The proxy now forwards the arguments as sent, so the child's own input validation decides on both paths. Co-Authored-By: Claude Opus 5.5 --- src/agent_env/env/gateway/gateway.py | 13 +-- .../env/gateway/unknown_arguments_test.py | 105 ++++++++++++++++++ 2 files changed, 111 insertions(+), 7 deletions(-) create mode 100644 tst/unit/env/gateway/unknown_arguments_test.py diff --git a/src/agent_env/env/gateway/gateway.py b/src/agent_env/env/gateway/gateway.py index ae2af8ed6..68c9795c9 100644 --- a/src/agent_env/env/gateway/gateway.py +++ b/src/agent_env/env/gateway/gateway.py @@ -29,7 +29,7 @@ from mcp.server.fastmcp.tools import Tool as FastMCPTool from mcp.server.fastmcp.utilities.func_metadata import FuncMetadata, ArgModelBase from mcp.types import CallToolResult, TextContent, Tool as MCPTool -from pydantic import create_model +from pydantic import ConfigDict, create_model from starlette.requests import HTTPConnection, Request from starlette.responses import Response, StreamingResponse from starlette.routing import WebSocketRoute @@ -1820,13 +1820,11 @@ async def _refuse_disabled_calls(self, body: bytes, role: str) -> Response | Non class _ProxyArgModelBase(ArgModelBase): - """ArgModelBase subclass that excludes unset fields from model_dump_one_level(). + """Forwards exactly the arguments the caller sent, as /step does: unset optional fields stay unset (an explicit + null is still sent) and keys the schema doesn't declare reach the child, whose own validation rejects or accepts + them, instead of being dropped here.""" - This prevents the gateway proxy from forwarding null values for optional - parameters that the caller didn't provide. Pydantic's model_fields_set - tracks which fields were actually present in the input, so explicitly - provided null values are still forwarded correctly. - """ + model_config = ConfigDict(extra="allow") def model_dump_one_level(self) -> dict[str, Any]: kwargs: dict[str, Any] = {} @@ -1836,6 +1834,7 @@ def model_dump_one_level(self) -> dict[str, Any]: value = getattr(self, field_name) output_name = field_info.alias if field_info.alias else field_name kwargs[output_name] = value + kwargs.update(self.model_extra or {}) return kwargs diff --git a/tst/unit/env/gateway/unknown_arguments_test.py b/tst/unit/env/gateway/unknown_arguments_test.py new file mode 100644 index 000000000..afe065048 --- /dev/null +++ b/tst/unit/env/gateway/unknown_arguments_test.py @@ -0,0 +1,105 @@ +"""Arguments a tool's schema doesn't declare reach the child on the MCP proxy path exactly as on /step, so the +child's own validation decides: a tool closed with additionalProperties false answers an error naming the key, +and one that allows extras receives them.""" +from __future__ import annotations + +import json + +import pytest +import pytest_asyncio +from mcp.server.lowlevel import Server +from mcp.shared.memory import create_connected_server_and_client_session +from mcp.types import TextContent, Tool as MCPTool + +from agent_env.env.gateway import InternalMCPServer +from agent_env.env.gateway.gateway import Gateway + +URL = "http://backing/mcp" +CLOSED = MCPTool(name="search", description="", inputSchema={ + "type": "object", "properties": {"q": {"type": "string"}, "limit": {"type": "integer"}}, + "additionalProperties": False}) +OPEN = MCPTool(name="tag", description="", inputSchema={ + "type": "object", "properties": {"name": {"type": "string"}}, "required": ["name"], + "additionalProperties": True}) + + +def _child(received: list[tuple[str, dict]]) -> Server: + """A child built on mcp's low-level server, which validates every call against the tool's inputSchema.""" + server = Server("child") + + @server.list_tools() + async def list_tools(): + return [CLOSED, OPEN] + + @server.call_tool() + async def call_tool(name, arguments): + received.append((name, dict(arguments))) + return [TextContent(type="text", text=json.dumps(arguments, sort_keys=True))] + + return server + + +@pytest_asyncio.fixture +async def gateway(): + received: list[tuple[str, dict]] = [] + gw = Gateway(host="127.0.0.1", port=0, server_name="t", internal_mcp_servers=[InternalMCPServer("svc", URL)]) + + async def _open(server, stack, report): + return await stack.enter_async_context(create_connected_server_and_client_session(_child(received))) + + gw._sessions.open_session = _open # type: ignore[method-assign] + for tool in (CLOSED, OPEN): + gw._create_and_register_proxy_tool(URL, tool) + gw._tool_server_urls[tool.name] = URL + try: + yield gw, received + finally: + await gw._close_child_sessions() + + +async def _via_mcp(gw: Gateway, name: str, arguments: dict) -> tuple[bool, str]: + async with create_connected_server_and_client_session(gw._mcp._mcp_server) as client: + result = await client.call_tool(name, arguments) + return result.isError, result.content[0].text + + +async def _via_step(gw: Gateway, name: str, arguments: dict) -> tuple[bool, str]: + resp = await gw._step_call_tool({"tool_name": name, "arguments": arguments}, "default") + assert resp.status_code == 200 + body = json.loads(resp.body) + result = body.get("result", body) + return result["isError"], result["content"][0]["text"] + + +CALLS = [_via_mcp, _via_step] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("call", CALLS) +async def test_an_undeclared_key_on_a_closed_schema_is_an_error_naming_it(gateway, call): + gw, received = gateway + is_error, text = await call(gw, CLOSED.name, {"query": "invoices"}) + assert is_error is True + assert "query" in text + assert received == [] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("call", CALLS) +async def test_extras_reach_a_tool_whose_schema_allows_them(gateway, call): + gw, received = gateway + is_error, text = await call(gw, OPEN.name, {"name": "urgent", "color": "red"}) + assert is_error is False + assert received == [(OPEN.name, {"name": "urgent", "color": "red"})] + assert json.loads(text) == {"name": "urgent", "color": "red"} + + +@pytest.mark.asyncio +@pytest.mark.parametrize("call", CALLS) +async def test_declared_arguments_are_forwarded_as_sent(gateway, call): + gw, received = gateway + is_error, _ = await call(gw, CLOSED.name, {"q": "invoices", "limit": None}) + assert is_error is True # an explicit null is forwarded, and the child's schema refuses it + is_error, _ = await call(gw, CLOSED.name, {"q": "invoices"}) + assert is_error is False + assert received == [(CLOSED.name, {"q": "invoices"})] # an unset optional stays unset From 519d9026ad29bab3b6db3994b64d9e8b7ce24fb2 Mon Sep 17 00:00:00 2001 From: Tu Trinh Date: Sat, 21 Nov 2026 03:06:22 +0000 Subject: [PATCH 2/8] fix(gateway): forward undeclared arguments only through child proxies The previous commit gave every argument model the gateway builds the forwarding base, including the ones for its own tools (get_time, the scheduled-check tools, message_user, stay_quiet). Those are plain functions, so a stray key such as get_time's {"timezone": ...} raised TypeError and /step answered 500, which test_gateway_clock_extension pins as "an answer, not a 500". Only a child proxy now forwards undeclared keys; the gateway's own tools drop them as before. Co-Authored-By: Claude Opus 5.5 --- src/agent_env/env/gateway/gateway.py | 31 ++++++++++----- .../env/gateway/unknown_arguments_test.py | 39 ++++++++++++++++--- 2 files changed, 56 insertions(+), 14 deletions(-) diff --git a/src/agent_env/env/gateway/gateway.py b/src/agent_env/env/gateway/gateway.py index 68c9795c9..8bef169e2 100644 --- a/src/agent_env/env/gateway/gateway.py +++ b/src/agent_env/env/gateway/gateway.py @@ -1663,7 +1663,7 @@ async def proxy(**kwargs) -> CallToolResult: }) return result - arg_model = self._create_arg_model_from_schema(tool_name, input_schema) + arg_model = self._create_arg_model_from_schema(tool_name, input_schema, forward_extras=True) return FastMCPTool( fn=proxy, name=tool_name, @@ -1674,7 +1674,10 @@ async def proxy(**kwargs) -> CallToolResult: ) @staticmethod - def _create_arg_model_from_schema(tool_name: str, schema: dict[str, Any]): + def _create_arg_model_from_schema(tool_name: str, schema: dict[str, Any], forward_extras: bool = False): + """A child proxy forwards keys its schema doesn't declare, for the child's own validation to judge; a tool the + gateway serves itself drops them, so a stray argument still gets an answer.""" + base = _ForwardingArgModelBase if forward_extras else _ProxyArgModelBase fields = {} properties = schema.get("properties", {}) required = set(schema.get("required", [])) @@ -1684,8 +1687,8 @@ def _create_arg_model_from_schema(tool_name: str, schema: dict[str, Any]): else: fields[name] = (Any, None) if not fields: - return create_model(f"{tool_name}Args", __base__=_ProxyArgModelBase) - return create_model(f"{tool_name}Args", __base__=_ProxyArgModelBase, **fields) + return create_model(f"{tool_name}Args", __base__=base) + return create_model(f"{tool_name}Args", __base__=base, **fields) def _close_trajectory_file(self) -> None: if self._trajectory_file and not self._trajectory_file.closed: @@ -1820,11 +1823,13 @@ async def _refuse_disabled_calls(self, body: bytes, role: str) -> Response | Non class _ProxyArgModelBase(ArgModelBase): - """Forwards exactly the arguments the caller sent, as /step does: unset optional fields stay unset (an explicit - null is still sent) and keys the schema doesn't declare reach the child, whose own validation rejects or accepts - them, instead of being dropped here.""" + """ArgModelBase subclass that excludes unset fields from model_dump_one_level(). - model_config = ConfigDict(extra="allow") + This prevents the gateway proxy from forwarding null values for optional + parameters that the caller didn't provide. Pydantic's model_fields_set + tracks which fields were actually present in the input, so explicitly + provided null values are still forwarded correctly. + """ def model_dump_one_level(self) -> dict[str, Any]: kwargs: dict[str, Any] = {} @@ -1834,10 +1839,18 @@ def model_dump_one_level(self) -> dict[str, Any]: value = getattr(self, field_name) output_name = field_info.alias if field_info.alias else field_name kwargs[output_name] = value - kwargs.update(self.model_extra or {}) return kwargs +class _ForwardingArgModelBase(_ProxyArgModelBase): + """Keeps undeclared keys too, so a child proxy forwards exactly what the caller sent, as /step does.""" + + model_config = ConfigDict(extra="allow") + + def model_dump_one_level(self) -> dict[str, Any]: + return {**super().model_dump_one_level(), **(self.model_extra or {})} + + def _step_source(body: dict) -> dict | None: """The trajectory tag of a /step call: step_api, or the post-turn hook its body names; None for any other source.""" if "source" not in body: diff --git a/tst/unit/env/gateway/unknown_arguments_test.py b/tst/unit/env/gateway/unknown_arguments_test.py index afe065048..ebd2acfcb 100644 --- a/tst/unit/env/gateway/unknown_arguments_test.py +++ b/tst/unit/env/gateway/unknown_arguments_test.py @@ -1,18 +1,22 @@ """Arguments a tool's schema doesn't declare reach the child on the MCP proxy path exactly as on /step, so the child's own validation decides: a tool closed with additionalProperties false answers an error naming the key, -and one that allows extras receives them.""" +and one that allows extras receives them. A tool the gateway serves itself still drops them and answers.""" from __future__ import annotations import json import pytest import pytest_asyncio +from mcp.server.fastmcp.exceptions import ToolError from mcp.server.lowlevel import Server from mcp.shared.memory import create_connected_server_and_client_session -from mcp.types import TextContent, Tool as MCPTool +from mcp.types import CallToolResult, TextContent, Tool as MCPTool from agent_env.env.gateway import InternalMCPServer from agent_env.env.gateway.gateway import Gateway +from agent_env.env.gateway.get_time import GET_TIME_TOOL_NAME, build_get_time_tool +from agent_env.env.gateway.notifications import build_check_tools +from agent_env.env.gateway.user_chat import build_stay_quiet_tool, build_user_chat_tool URL = "http://backing/mcp" CLOSED = MCPTool(name="search", description="", inputSchema={ @@ -58,9 +62,13 @@ async def _open(server, stack, report): async def _via_mcp(gw: Gateway, name: str, arguments: dict) -> tuple[bool, str]: - async with create_connected_server_and_client_session(gw._mcp._mcp_server) as client: - result = await client.call_tool(name, arguments) - return result.isError, result.content[0].text + try: + result = await gw._mcp._tool_manager.call_tool(name, arguments) + except ToolError as e: # FastMCP's server answers a raised ToolError as isError true + return True, str(e) + if isinstance(result, CallToolResult): + return result.isError, result.content[0].text + return False, json.dumps(result) async def _via_step(gw: Gateway, name: str, arguments: dict) -> tuple[bool, str]: @@ -103,3 +111,24 @@ async def test_declared_arguments_are_forwarded_as_sent(gateway, call): is_error, _ = await call(gw, CLOSED.name, {"q": "invoices"}) assert is_error is False assert received == [(CLOSED.name, {"q": "invoices"})] # an unset optional stays unset + + +@pytest.mark.asyncio +@pytest.mark.parametrize("call", CALLS) +async def test_a_gateway_tool_drops_an_undeclared_key_and_answers(gateway, call): + gw, _ = gateway + gw._clock.set_time("2019-06-15T12:00:00Z", 0) + gw._register_get_time_tool() + is_error, text = await call(gw, GET_TIME_TOOL_NAME, {"timezone": "Asia/Tokyo"}) + assert is_error is False and "2019-06-15T12:00:00Z" in text + + +@pytest.mark.asyncio +async def test_every_gateway_tool_drops_an_undeclared_key(): + gw = Gateway(host="127.0.0.1", port=0, server_name="t", internal_mcp_servers=[]) + make = gw._create_arg_model_from_schema + tools = [build_get_time_tool(gw._clock, make), *build_check_tools(gw._notifications, make), + build_user_chat_tool(gw._user_chat, make), build_stay_quiet_tool(gw._user_chat, make)] + for tool in tools: + args = tool.fn_metadata.arg_model.model_validate({"bogus": 1, "note": "n", "check_id": "c", "text": "t"}) + assert "bogus" not in args.model_dump_one_level(), tool.name From 369c207bb9e50fea93ea9a8695099b25b162b034 Mon Sep 17 00:00:00 2001 From: Tu Trinh Date: Mon, 23 Nov 2026 09:58:27 +0000 Subject: [PATCH 3/8] fix(gateway): leave a child tool's arguments for the child to validate The proxy's argument model still declared the child's required fields, so over MCP a missing or misnamed required argument got the gateway's pydantic "Field required" error instead of the child's, and FastMCP's JSON pre-parsing turned a string that parses as JSON into an object. A child proxy's model now declares no fields and forwards every key exactly as sent, as /step does; the published inputSchema is unchanged and the gateway's own tools keep their model. Co-Authored-By: Claude Opus 5.5 --- src/agent_env/env/gateway/gateway.py | 24 +++---- .../env/gateway/unknown_arguments_test.py | 67 +++++++++++++++++-- 2 files changed, 72 insertions(+), 19 deletions(-) diff --git a/src/agent_env/env/gateway/gateway.py b/src/agent_env/env/gateway/gateway.py index 8bef169e2..214ad96c4 100644 --- a/src/agent_env/env/gateway/gateway.py +++ b/src/agent_env/env/gateway/gateway.py @@ -1663,7 +1663,9 @@ async def proxy(**kwargs) -> CallToolResult: }) return result - arg_model = self._create_arg_model_from_schema(tool_name, input_schema, forward_extras=True) + # The child validates its own arguments: the model declares none and forwards what the caller sent, as /step + # does, so a missing, misnamed, undeclared or wrong-typed argument gets the child's own answer. + arg_model = create_model(f"{tool_name}Args", __base__=_ForwardingArgModelBase) return FastMCPTool( fn=proxy, name=tool_name, @@ -1674,10 +1676,7 @@ async def proxy(**kwargs) -> CallToolResult: ) @staticmethod - def _create_arg_model_from_schema(tool_name: str, schema: dict[str, Any], forward_extras: bool = False): - """A child proxy forwards keys its schema doesn't declare, for the child's own validation to judge; a tool the - gateway serves itself drops them, so a stray argument still gets an answer.""" - base = _ForwardingArgModelBase if forward_extras else _ProxyArgModelBase + def _create_arg_model_from_schema(tool_name: str, schema: dict[str, Any]): fields = {} properties = schema.get("properties", {}) required = set(schema.get("required", [])) @@ -1687,8 +1686,8 @@ def _create_arg_model_from_schema(tool_name: str, schema: dict[str, Any], forwar else: fields[name] = (Any, None) if not fields: - return create_model(f"{tool_name}Args", __base__=base) - return create_model(f"{tool_name}Args", __base__=base, **fields) + return create_model(f"{tool_name}Args", __base__=_ProxyArgModelBase) + return create_model(f"{tool_name}Args", __base__=_ProxyArgModelBase, **fields) def _close_trajectory_file(self) -> None: if self._trajectory_file and not self._trajectory_file.closed: @@ -1825,8 +1824,8 @@ async def _refuse_disabled_calls(self, body: bytes, role: str) -> Response | Non class _ProxyArgModelBase(ArgModelBase): """ArgModelBase subclass that excludes unset fields from model_dump_one_level(). - This prevents the gateway proxy from forwarding null values for optional - parameters that the caller didn't provide. Pydantic's model_fields_set + This keeps a tool the gateway serves itself from receiving null values for + optional parameters that the caller didn't provide. Pydantic's model_fields_set tracks which fields were actually present in the input, so explicitly provided null values are still forwarded correctly. """ @@ -1842,13 +1841,14 @@ def model_dump_one_level(self) -> dict[str, Any]: return kwargs -class _ForwardingArgModelBase(_ProxyArgModelBase): - """Keeps undeclared keys too, so a child proxy forwards exactly what the caller sent, as /step does.""" +class _ForwardingArgModelBase(ArgModelBase): + """A child proxy's arguments: no declared fields, so nothing is required, typed or JSON-pre-parsed, and every key + the caller sent (an explicit null included) is forwarded unchanged, exactly as /step forwards them.""" model_config = ConfigDict(extra="allow") def model_dump_one_level(self) -> dict[str, Any]: - return {**super().model_dump_one_level(), **(self.model_extra or {})} + return dict(self.model_extra or {}) def _step_source(body: dict) -> dict | None: diff --git a/tst/unit/env/gateway/unknown_arguments_test.py b/tst/unit/env/gateway/unknown_arguments_test.py index ebd2acfcb..782ae0941 100644 --- a/tst/unit/env/gateway/unknown_arguments_test.py +++ b/tst/unit/env/gateway/unknown_arguments_test.py @@ -1,12 +1,14 @@ -"""Arguments a tool's schema doesn't declare reach the child on the MCP proxy path exactly as on /step, so the -child's own validation decides: a tool closed with additionalProperties false answers an error naming the key, -and one that allows extras receives them. A tool the gateway serves itself still drops them and answers.""" +"""A child tool's arguments reach the child on the MCP proxy path exactly as on /step, unvalidated by the gateway, +so the child's own validation decides: an undeclared key on a tool closed with additionalProperties false, a missing +or misnamed required argument and a wrong-typed one each get the child's error naming the key, and a tool that allows +extras receives them. A tool the gateway serves itself still drops an undeclared key and answers.""" from __future__ import annotations import json import pytest import pytest_asyncio +from jsonschema import Draft202012Validator from mcp.server.fastmcp.exceptions import ToolError from mcp.server.lowlevel import Server from mcp.shared.memory import create_connected_server_and_client_session @@ -25,18 +27,32 @@ OPEN = MCPTool(name="tag", description="", inputSchema={ "type": "object", "properties": {"name": {"type": "string"}}, "required": ["name"], "additionalProperties": True}) +EVENTS = MCPTool(name="list_events", description="", inputSchema={ + "type": "object", "properties": {"calendarId": {"type": "string"}, "maxResults": {"type": "integer"}}, + "required": ["calendarId"], "additionalProperties": False}) +TOOLS = [CLOSED, OPEN, EVENTS] def _child(received: list[tuple[str, dict]]) -> Server: - """A child built on mcp's low-level server, which validates every call against the tool's inputSchema.""" + """A child on mcp's low-level server that validates every call against the tool's inputSchema and, like the hub's + servers, refuses an invalid one with invalid_arguments naming every key at fault.""" server = Server("child") @server.list_tools() async def list_tools(): - return [CLOSED, OPEN] + return TOOLS - @server.call_tool() + @server.call_tool(validate_input=False) async def call_tool(name, arguments): + schema = next(tool.inputSchema for tool in TOOLS if tool.name == name) + if errors := list(Draft202012Validator(schema).iter_errors(arguments)): + properties = schema["properties"] + fields = {key for key in arguments if key not in properties and not schema["additionalProperties"]} + fields |= {key for key in schema.get("required", []) if key not in arguments} + fields |= {error.path[0] for error in errors if error.path} + text = json.dumps({"error": "invalid_arguments", "invalid_fields": sorted(fields), + "messages": sorted(error.message for error in errors)}) + return CallToolResult(isError=True, content=[TextContent(type="text", text=text)]) received.append((name, dict(arguments))) return [TextContent(type="text", text=json.dumps(arguments, sort_keys=True))] @@ -52,7 +68,7 @@ async def _open(server, stack, report): return await stack.enter_async_context(create_connected_server_and_client_session(_child(received))) gw._sessions.open_session = _open # type: ignore[method-assign] - for tool in (CLOSED, OPEN): + for tool in TOOLS: gw._create_and_register_proxy_tool(URL, tool) gw._tool_server_urls[tool.name] = URL try: @@ -113,6 +129,36 @@ async def test_declared_arguments_are_forwarded_as_sent(gateway, call): assert received == [(CLOSED.name, {"q": "invoices"})] # an unset optional stays unset +@pytest.mark.asyncio +@pytest.mark.parametrize(("arguments", "invalid_fields", "message"), [ + ({"calendar_id": "primary"}, ["calendarId", "calendar_id"], "'calendar_id' was unexpected"), + ({"maxResults": 5}, ["calendarId"], "'calendarId' is a required property"), + ({"calendarId": "primary", "maxResults": "[10]"}, ["maxResults"], "'[10]' is not of type 'integer'"), +], ids=["misnamed_required", "missing_required", "wrong_type"]) +async def test_an_invalid_call_gets_the_childs_own_error_on_both_paths(gateway, arguments, invalid_fields, message): + gw, received = gateway + via_mcp = await _via_mcp(gw, EVENTS.name, arguments) + via_step = await _via_step(gw, EVENTS.name, arguments) + assert via_mcp == via_step + is_error, text = via_mcp + assert is_error is True + error = json.loads(text) + assert error["error"] == "invalid_arguments" and error["invalid_fields"] == invalid_fields + assert any(message in m for m in error["messages"]) + assert received == [] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("call", CALLS) +async def test_a_valid_call_reaches_the_child_unchanged(gateway, call): + gw, received = gateway + arguments = {"calendarId": '{"id": "primary"}', "maxResults": 5} # a string that parses as JSON stays a string + is_error, text = await call(gw, EVENTS.name, arguments) + assert is_error is False + assert received == [(EVENTS.name, arguments)] + assert json.loads(text) == arguments + + @pytest.mark.asyncio @pytest.mark.parametrize("call", CALLS) async def test_a_gateway_tool_drops_an_undeclared_key_and_answers(gateway, call): @@ -132,3 +178,10 @@ async def test_every_gateway_tool_drops_an_undeclared_key(): for tool in tools: args = tool.fn_metadata.arg_model.model_validate({"bogus": 1, "note": "n", "check_id": "c", "text": "t"}) assert "bogus" not in args.model_dump_one_level(), tool.name + + +@pytest.mark.asyncio +async def test_the_agent_sees_the_childs_schema_verbatim(gateway): + gw, _ = gateway + listed = {tool.name: tool.inputSchema for tool in await gw._mcp.list_tools()} + assert {name: listed[name] for name in (t.name for t in TOOLS)} == {t.name: t.inputSchema for t in TOOLS} From c88c0563ab06da939e99894eb188d25aaa8581b2 Mon Sep 17 00:00:00 2001 From: Tu Trinh Date: Mon, 23 Nov 2026 14:09:10 +0000 Subject: [PATCH 4/8] test(gateway): a non-FastMCP (Node) child gets undeclared keys and JSON-looking strings as sent node_child/server.mjs is a dependency-free Node MCP server over streamable HTTP that validates strictly and never re-parses JSON strings. Behind a real Gateway, over MCP and /step: declared arguments arrive unchanged, an undeclared key reaches the child (refused by name), and '["a"]' arrives as the string. On the merge base the undeclared key was dropped and the string arrived as a list. Co-Authored-By: Claude Opus 5.5 --- tst/unit/env/gateway/node_child/server.mjs | 64 ++++++++++++ .../env/gateway/node_child_arguments_test.py | 97 +++++++++++++++++++ 2 files changed, 161 insertions(+) create mode 100644 tst/unit/env/gateway/node_child/server.mjs create mode 100644 tst/unit/env/gateway/node_child_arguments_test.py diff --git a/tst/unit/env/gateway/node_child/server.mjs b/tst/unit/env/gateway/node_child/server.mjs new file mode 100644 index 000000000..d98188ec2 --- /dev/null +++ b/tst/unit/env/gateway/node_child/server.mjs @@ -0,0 +1,64 @@ +// A child MCP server that is not FastMCP and not Python: plain Node, no dependencies, MCP's streamable HTTP transport +// answered with JSON bodies (stateless). Its one tool validates strictly, as a hand-written or TypeScript server does: +// an undeclared key or a wrong type is refused with invalid_arguments naming the keys, and it never re-parses a JSON +// string. A valid call answers with the arguments exactly as they arrived. Prints its port on stdout once listening. +import http from "node:http"; + +const TOOL = { + name: "find_messages", + description: "Find messages.", + inputSchema: { + type: "object", + properties: { q: { type: "string" }, labels: { type: "array", items: { type: "string" } } }, + additionalProperties: false, + }, +}; + +function invalidFields(args) { + const bad = []; + for (const [key, value] of Object.entries(args)) { + if (!(key in TOOL.inputSchema.properties)) bad.push(key); + else if (key === "q" && typeof value !== "string") bad.push(key); + else if (key === "labels" && !(Array.isArray(value) && value.every((v) => typeof v === "string"))) bad.push(key); + } + return bad.sort(); +} + +function answer(msg) { + const ok = (result) => ({ jsonrpc: "2.0", id: msg.id, result }); + switch (msg.method) { + case "initialize": + return ok({ protocolVersion: msg.params.protocolVersion, capabilities: { tools: {} }, + serverInfo: { name: "node-child", version: "1.0.0" } }); + case "ping": + return ok({}); + case "tools/list": + return ok({ tools: [TOOL] }); + case "tools/call": { + const args = msg.params.arguments ?? {}; + const bad = msg.params.name === TOOL.name ? invalidFields(args) : ["name"]; + const text = bad.length ? JSON.stringify({ error: "invalid_arguments", invalid_fields: bad }) : JSON.stringify(args); + return ok({ isError: bad.length > 0, content: [{ type: "text", text }] }); + } + default: + return { jsonrpc: "2.0", id: msg.id, error: { code: -32601, message: `method not found: ${msg.method}` } }; + } +} + +const server = http.createServer((req, res) => { + if (req.method !== "POST") { + res.writeHead(405).end(); + return; + } + let body = ""; + req.on("data", (chunk) => (body += chunk)); + req.on("end", () => { + const msg = JSON.parse(body); + if (msg.id === undefined) { // a notification + res.writeHead(202).end(); + return; + } + res.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify(answer(msg))); + }); +}); +server.listen(0, "127.0.0.1", () => console.log(server.address().port)); diff --git a/tst/unit/env/gateway/node_child_arguments_test.py b/tst/unit/env/gateway/node_child_arguments_test.py new file mode 100644 index 000000000..070781f03 --- /dev/null +++ b/tst/unit/env/gateway/node_child_arguments_test.py @@ -0,0 +1,97 @@ +"""A child that is not FastMCP (node_child/server.mjs: plain Node over MCP's streamable HTTP, validating strictly and +never re-parsing a JSON string) gets a tool's arguments from the gateway's MCP path exactly as the caller sent them: +an undeclared key reaches it (and it refuses it by name), declared ones arrive unchanged, and a string that parses as +JSON stays a string. Before the gateway stopped validating child arguments, the undeclared key was dropped and +'["a"]' arrived as the list ["a"], which this child would have accepted.""" +from __future__ import annotations + +import asyncio +import json +import shutil +from pathlib import Path + +import pytest +import pytest_asyncio +from mcp.server.fastmcp.exceptions import ToolError +from mcp.types import CallToolResult +from pytest_socket import enable_socket + +from agent_env.env.gateway import InternalMCPServer +from agent_env.env.gateway.gateway import Gateway + +NODE = shutil.which("node") +SERVER = Path(__file__).parent / "node_child" / "server.mjs" +TOOL = "find_messages" + +pytestmark = pytest.mark.skipif(NODE is None, reason="needs the node binary to run the Node child server") + + +@pytest.fixture(autouse=True) +def _disable_network(): + """Override the suite-wide socket block (tst/unit/conftest.py) for this module: the child listens on loopback.""" + enable_socket() + yield + + +@pytest_asyncio.fixture +async def gateway(): + proc = await asyncio.create_subprocess_exec(NODE, str(SERVER), stdout=asyncio.subprocess.PIPE) + try: + port = int((await asyncio.wait_for(proc.stdout.readline(), timeout=30)).decode().strip()) + gw = Gateway(host="127.0.0.1", port=0, server_name="t", + internal_mcp_servers=[InternalMCPServer("node", f"http://127.0.0.1:{port}/mcp")]) + try: + await gw._ensure_tools_discovered() + yield gw + finally: + await gw._close_child_sessions() + finally: + proc.kill() + await proc.wait() + + +async def _via_mcp(gw: Gateway, arguments: dict) -> tuple[bool, dict]: + try: + result = await gw._mcp._tool_manager.call_tool(TOOL, arguments) + except ToolError as e: + return True, {"gateway_error": str(e)} + assert isinstance(result, CallToolResult), result + return result.isError, json.loads(result.content[0].text) + + +async def _via_step(gw: Gateway, arguments: dict) -> tuple[bool, dict]: + resp = await gw._step_call_tool({"tool_name": TOOL, "arguments": arguments}, "default") + body = json.loads(resp.body) + result = body.get("result", body) + return result["isError"], json.loads(result["content"][0]["text"]) + + +@pytest.mark.asyncio +async def test_the_gateway_lists_the_node_childs_schema_verbatim(gateway): + listed = {tool.name: tool for tool in await gateway._mcp.list_tools()} + assert listed[TOOL].inputSchema["additionalProperties"] is False + assert set(listed[TOOL].inputSchema["properties"]) == {"q", "labels"} + + +@pytest.mark.asyncio +async def test_declared_arguments_reach_the_node_child_unchanged(gateway): + arguments = {"q": "invoice", "labels": ["INBOX", "a b"]} + assert await _via_mcp(gateway, arguments) == (False, arguments) + assert await _via_step(gateway, arguments) == (False, arguments) + + +@pytest.mark.asyncio +async def test_an_undeclared_argument_reaches_the_node_child_which_refuses_it_by_name(gateway): + arguments = {"q": "invoice", "query": "invoice"} + expected = (True, {"error": "invalid_arguments", "invalid_fields": ["query"]}) + assert await _via_mcp(gateway, arguments) == expected + assert await _via_step(gateway, arguments) == expected + + +@pytest.mark.asyncio +async def test_a_stringified_array_reaches_the_node_child_as_the_string(gateway): + # the child never re-parses JSON strings, so it sees (and refuses) the string the caller sent + arguments = {"labels": '["a"]'} + expected = (True, {"error": "invalid_arguments", "invalid_fields": ["labels"]}) + assert await _via_mcp(gateway, arguments) == expected + assert await _via_step(gateway, arguments) == expected From ff7ed9045950eb9e9e1224528c7d8c2341aca565 Mon Sep 17 00:00:00 2001 From: Tu Trinh Date: Mon, 23 Nov 2026 16:57:04 +0000 Subject: [PATCH 5/8] fix(gateway): still decode a JSON string sent for an array or object parameter The forwarding model dropped FastMCP's pre-parsing, so strict non-FastMCP children such as @playwright/mcp refused a model's stringified array (browser_select_option.values, browser_fill_form.fields). Keep that one repair, only for parameters the child types array/object (not string) and only when the string decodes to that type; undeclared keys and every other value are still forwarded as sent. Co-Authored-By: Claude Opus 5.5 --- src/agent_env/env/gateway/gateway.py | 53 +++++++++++++++++-- tst/unit/env/gateway/node_child/server.mjs | 12 ++++- .../env/gateway/node_child_arguments_test.py | 46 +++++++++++++--- 3 files changed, 96 insertions(+), 15 deletions(-) diff --git a/src/agent_env/env/gateway/gateway.py b/src/agent_env/env/gateway/gateway.py index 214ad96c4..61759afc3 100644 --- a/src/agent_env/env/gateway/gateway.py +++ b/src/agent_env/env/gateway/gateway.py @@ -15,7 +15,7 @@ from contextlib import asynccontextmanager from datetime import datetime, timezone from pathlib import Path -from typing import TYPE_CHECKING, Any, NamedTuple +from typing import TYPE_CHECKING, Any, ClassVar, NamedTuple from urllib.parse import parse_qsl, urljoin, urlsplit from uuid import uuid4 @@ -1664,8 +1664,10 @@ async def proxy(**kwargs) -> CallToolResult: return result # The child validates its own arguments: the model declares none and forwards what the caller sent, as /step - # does, so a missing, misnamed, undeclared or wrong-typed argument gets the child's own answer. + # does, so a missing, misnamed, undeclared or wrong-typed argument gets the child's own answer. The one repair + # kept from the typed model: a JSON string for a parameter the child types array or object is decoded. arg_model = create_model(f"{tool_name}Args", __base__=_ForwardingArgModelBase) + arg_model.json_container_params = _json_container_params(input_schema) return FastMCPTool( fn=proxy, name=tool_name, @@ -1842,13 +1844,54 @@ def model_dump_one_level(self) -> dict[str, Any]: class _ForwardingArgModelBase(ArgModelBase): - """A child proxy's arguments: no declared fields, so nothing is required, typed or JSON-pre-parsed, and every key - the caller sent (an explicit null included) is forwarded unchanged, exactly as /step forwards them.""" + """A child proxy's arguments: no declared fields, so nothing is required or typed, and every key the caller sent + (an explicit null included) is forwarded as sent. The exception is the JSON-string repair the gateway's typed model + used to give through FastMCP's pre-parsing: a string sent for a parameter the child types array or object (and + not string) is decoded when it decodes to that type, so a model's '["a"]' still reaches a strict child as a list.""" model_config = ConfigDict(extra="allow") + json_container_params: ClassVar[dict[str, tuple[type, ...]]] = {} def model_dump_one_level(self) -> dict[str, Any]: - return dict(self.model_extra or {}) + kwargs = dict(self.model_extra or {}) + for name, kinds in self.json_container_params.items(): + value = kwargs.get(name) + if not isinstance(value, str): + continue + try: + decoded = json.loads(value) + except ValueError: + continue + if isinstance(decoded, kinds): + kwargs[name] = decoded + return kwargs + + +_JSON_CONTAINER_TYPES: dict[str, type] = {"array": list, "object": dict} + + +def _schema_types(schema: Any) -> set[str]: + """The JSON types a property schema allows: its `type` (a name or a list) plus those of its anyOf/oneOf branches.""" + if not isinstance(schema, dict): + return set() + declared = schema.get("type") + types = {declared} if isinstance(declared, str) else {t for t in declared or () if isinstance(t, str)} + for key in ("anyOf", "oneOf"): + for branch in schema.get(key) or (): + types |= _schema_types(branch) + return types + + +def _json_container_params(input_schema: dict[str, Any]) -> dict[str, tuple[type, ...]]: + """Each property the child types array and/or object but not string, with the Python types a JSON string sent for + it may decode to. A property that also accepts a string keeps the string the caller sent.""" + params: dict[str, tuple[type, ...]] = {} + for name, schema in (input_schema.get("properties") or {}).items(): + types = _schema_types(schema) + kinds = tuple(_JSON_CONTAINER_TYPES[t] for t in sorted(types) if t in _JSON_CONTAINER_TYPES) + if kinds and "string" not in types: + params[name] = kinds + return params def _step_source(body: dict) -> dict | None: diff --git a/tst/unit/env/gateway/node_child/server.mjs b/tst/unit/env/gateway/node_child/server.mjs index d98188ec2..1ef0143af 100644 --- a/tst/unit/env/gateway/node_child/server.mjs +++ b/tst/unit/env/gateway/node_child/server.mjs @@ -1,7 +1,7 @@ // A child MCP server that is not FastMCP and not Python: plain Node, no dependencies, MCP's streamable HTTP transport // answered with JSON bodies (stateless). Its one tool validates strictly, as a hand-written or TypeScript server does: // an undeclared key or a wrong type is refused with invalid_arguments naming the keys, and it never re-parses a JSON -// string. A valid call answers with the arguments exactly as they arrived. Prints its port on stdout once listening. +// string (as zod-based servers such as @playwright/mcp do not). A valid call answers with the arguments exactly as they arrived. Prints its port on stdout once listening. import http from "node:http"; const TOOL = { @@ -9,7 +9,12 @@ const TOOL = { description: "Find messages.", inputSchema: { type: "object", - properties: { q: { type: "string" }, labels: { type: "array", items: { type: "string" } } }, + properties: { + q: { type: "string" }, + labels: { type: "array", items: { type: "string" } }, + filters: { type: "object" }, + ids: { anyOf: [{ type: "array", items: { type: "string" } }, { type: "null" }] }, + }, additionalProperties: false, }, }; @@ -20,6 +25,9 @@ function invalidFields(args) { if (!(key in TOOL.inputSchema.properties)) bad.push(key); else if (key === "q" && typeof value !== "string") bad.push(key); else if (key === "labels" && !(Array.isArray(value) && value.every((v) => typeof v === "string"))) bad.push(key); + else if (key === "filters" && !(value !== null && typeof value === "object" && !Array.isArray(value))) bad.push(key); + else if (key === "ids" && !(value === null || (Array.isArray(value) && value.every((v) => typeof v === "string")))) + bad.push(key); } return bad.sort(); } diff --git a/tst/unit/env/gateway/node_child_arguments_test.py b/tst/unit/env/gateway/node_child_arguments_test.py index 070781f03..e831f3d3a 100644 --- a/tst/unit/env/gateway/node_child_arguments_test.py +++ b/tst/unit/env/gateway/node_child_arguments_test.py @@ -1,8 +1,9 @@ """A child that is not FastMCP (node_child/server.mjs: plain Node over MCP's streamable HTTP, validating strictly and -never re-parsing a JSON string) gets a tool's arguments from the gateway's MCP path exactly as the caller sent them: -an undeclared key reaches it (and it refuses it by name), declared ones arrive unchanged, and a string that parses as -JSON stays a string. Before the gateway stopped validating child arguments, the undeclared key was dropped and -'["a"]' arrived as the list ["a"], which this child would have accepted.""" +never re-parsing a JSON string, as @playwright/mcp does) gets a tool's arguments from the gateway's MCP path as the +caller sent them: an undeclared key reaches it (and it refuses it by name) and declared ones arrive unchanged. The one +repair the gateway keeps on the MCP path, as before it stopped validating child arguments: a JSON string sent for a +parameter the child types array or object is decoded to that list or dict, and any other string (one for a string +parameter, or one that decodes to another type) stays the string. /step forwards every value as sent.""" from __future__ import annotations import asyncio @@ -70,7 +71,7 @@ async def _via_step(gw: Gateway, arguments: dict) -> tuple[bool, dict]: async def test_the_gateway_lists_the_node_childs_schema_verbatim(gateway): listed = {tool.name: tool for tool in await gateway._mcp.list_tools()} assert listed[TOOL].inputSchema["additionalProperties"] is False - assert set(listed[TOOL].inputSchema["properties"]) == {"q", "labels"} + assert set(listed[TOOL].inputSchema["properties"]) == {"q", "labels", "filters", "ids"} @pytest.mark.asyncio @@ -89,9 +90,38 @@ async def test_an_undeclared_argument_reaches_the_node_child_which_refuses_it_by @pytest.mark.asyncio -async def test_a_stringified_array_reaches_the_node_child_as_the_string(gateway): - # the child never re-parses JSON strings, so it sees (and refuses) the string the caller sent +@pytest.mark.parametrize("arguments, decoded", [ + ({"labels": '["a", "b c"]'}, {"labels": ["a", "b c"]}), + ({"filters": '{"from": "x", "n": 2}'}, {"filters": {"from": "x", "n": 2}}), + ({"ids": '["m1"]'}, {"ids": ["m1"]}), # anyOf array | null + ({"q": '["a"]', "labels": "[]"}, {"q": '["a"]', "labels": []}), # q is typed string: it stays the string +]) +async def test_a_json_string_for_an_array_or_object_parameter_reaches_the_node_child_decoded(gateway, arguments, + decoded): + assert await _via_mcp(gateway, arguments) == (False, decoded) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("arguments, invalid", [ + ({"labels": '{"a": 1}'}, ["labels"]), # decodes to an object, the parameter is an array + ({"filters": '["a"]'}, ["filters"]), # decodes to an array, the parameter is an object + ({"labels": "INBOX"}, ["labels"]), # not JSON + ({"labels": "true"}, ["labels"]), # JSON, but not an array +]) +async def test_any_other_string_for_an_array_or_object_parameter_reaches_the_node_child_as_sent(gateway, arguments, + invalid): + assert await _via_mcp(gateway, arguments) == (True, {"error": "invalid_arguments", "invalid_fields": invalid}) + + +@pytest.mark.asyncio +async def test_an_undeclared_key_that_looks_like_json_is_forwarded_as_sent(gateway): + expected = (True, {"error": "invalid_arguments", "invalid_fields": ["fields"]}) + assert await _via_mcp(gateway, {"fields": '["a"]'}) == expected + + +@pytest.mark.asyncio +async def test_step_forwards_a_stringified_array_as_the_string(gateway): + # /step never pre-parsed: the child sees (and refuses) the string the caller sent arguments = {"labels": '["a"]'} expected = (True, {"error": "invalid_arguments", "invalid_fields": ["labels"]}) - assert await _via_mcp(gateway, arguments) == expected assert await _via_step(gateway, arguments) == expected From 6f42144563357f1cbe0b6d8b9004e9ef284f1fac Mon Sep 17 00:00:00 2001 From: Tu Trinh Date: Mon, 23 Nov 2026 18:33:04 +0000 Subject: [PATCH 6/8] fix(gateway): the JSON-string repair also follows a local $ref to an array or object definition Co-Authored-By: Claude Opus 5.5 --- src/agent_env/env/gateway/gateway.py | 21 ++++++++++++++----- tst/unit/env/gateway/node_child/server.mjs | 3 +++ .../env/gateway/node_child_arguments_test.py | 3 ++- 3 files changed, 21 insertions(+), 6 deletions(-) diff --git a/src/agent_env/env/gateway/gateway.py b/src/agent_env/env/gateway/gateway.py index 61759afc3..8d683fee4 100644 --- a/src/agent_env/env/gateway/gateway.py +++ b/src/agent_env/env/gateway/gateway.py @@ -1870,15 +1870,26 @@ def model_dump_one_level(self) -> dict[str, Any]: _JSON_CONTAINER_TYPES: dict[str, type] = {"array": list, "object": dict} -def _schema_types(schema: Any) -> set[str]: - """The JSON types a property schema allows: its `type` (a name or a list) plus those of its anyOf/oneOf branches.""" - if not isinstance(schema, dict): +_SCHEMA_REF_DEPTH = 8 # local $ref hops followed when typing a property; deeper (or cyclic) refs add no type + + +def _schema_types(schema: Any, root: Any = None, depth: int = 0) -> set[str]: + """The JSON types a property schema allows: its `type` (a name or a list), those of its anyOf/oneOf branches, and + those of a local `$ref` (``#/$defs/...``, ``#/definitions/...``) into ``root``, the tool's input schema.""" + if not isinstance(schema, dict) or depth > _SCHEMA_REF_DEPTH: return set() declared = schema.get("type") types = {declared} if isinstance(declared, str) else {t for t in declared or () if isinstance(t, str)} for key in ("anyOf", "oneOf"): for branch in schema.get(key) or (): - types |= _schema_types(branch) + types |= _schema_types(branch, root, depth + 1) + ref = schema.get("$ref") + if isinstance(ref, str) and ref.startswith("#/"): + target: Any = root + for part in ref[2:].split("/"): + part = part.replace("~1", "/").replace("~0", "~") + target = target.get(part) if isinstance(target, dict) else None + types |= _schema_types(target, root, depth + 1) return types @@ -1887,7 +1898,7 @@ def _json_container_params(input_schema: dict[str, Any]) -> dict[str, tuple[type it may decode to. A property that also accepts a string keeps the string the caller sent.""" params: dict[str, tuple[type, ...]] = {} for name, schema in (input_schema.get("properties") or {}).items(): - types = _schema_types(schema) + types = _schema_types(schema, input_schema) kinds = tuple(_JSON_CONTAINER_TYPES[t] for t in sorted(types) if t in _JSON_CONTAINER_TYPES) if kinds and "string" not in types: params[name] = kinds diff --git a/tst/unit/env/gateway/node_child/server.mjs b/tst/unit/env/gateway/node_child/server.mjs index 1ef0143af..16909e868 100644 --- a/tst/unit/env/gateway/node_child/server.mjs +++ b/tst/unit/env/gateway/node_child/server.mjs @@ -14,8 +14,10 @@ const TOOL = { labels: { type: "array", items: { type: "string" } }, filters: { type: "object" }, ids: { anyOf: [{ type: "array", items: { type: "string" } }, { type: "null" }] }, + tags: { $ref: "#/$defs/Tags" }, }, additionalProperties: false, + $defs: { Tags: { type: "array", items: { type: "string" } } }, }, }; @@ -26,6 +28,7 @@ function invalidFields(args) { else if (key === "q" && typeof value !== "string") bad.push(key); else if (key === "labels" && !(Array.isArray(value) && value.every((v) => typeof v === "string"))) bad.push(key); else if (key === "filters" && !(value !== null && typeof value === "object" && !Array.isArray(value))) bad.push(key); + else if (key === "tags" && !(Array.isArray(value) && value.every((v) => typeof v === "string"))) bad.push(key); else if (key === "ids" && !(value === null || (Array.isArray(value) && value.every((v) => typeof v === "string")))) bad.push(key); } diff --git a/tst/unit/env/gateway/node_child_arguments_test.py b/tst/unit/env/gateway/node_child_arguments_test.py index e831f3d3a..cf9a8af6b 100644 --- a/tst/unit/env/gateway/node_child_arguments_test.py +++ b/tst/unit/env/gateway/node_child_arguments_test.py @@ -71,7 +71,7 @@ async def _via_step(gw: Gateway, arguments: dict) -> tuple[bool, dict]: async def test_the_gateway_lists_the_node_childs_schema_verbatim(gateway): listed = {tool.name: tool for tool in await gateway._mcp.list_tools()} assert listed[TOOL].inputSchema["additionalProperties"] is False - assert set(listed[TOOL].inputSchema["properties"]) == {"q", "labels", "filters", "ids"} + assert set(listed[TOOL].inputSchema["properties"]) == {"q", "labels", "filters", "ids", "tags"} @pytest.mark.asyncio @@ -94,6 +94,7 @@ async def test_an_undeclared_argument_reaches_the_node_child_which_refuses_it_by ({"labels": '["a", "b c"]'}, {"labels": ["a", "b c"]}), ({"filters": '{"from": "x", "n": 2}'}, {"filters": {"from": "x", "n": 2}}), ({"ids": '["m1"]'}, {"ids": ["m1"]}), # anyOf array | null + ({"tags": '["t1"]'}, {"tags": ["t1"]}), # a local $ref to an array definition ({"q": '["a"]', "labels": "[]"}, {"q": '["a"]', "labels": []}), # q is typed string: it stays the string ]) async def test_a_json_string_for_an_array_or_object_parameter_reaches_the_node_child_decoded(gateway, arguments, From e697099752dc8840dc978382a70bb845216d78c1 Mon Sep 17 00:00:00 2001 From: Tu Trinh Date: Tue, 24 Nov 2026 00:57:40 +0000 Subject: [PATCH 7/8] gateway: JSON-string repair also covers allOf refs, untyped properties and "null" As the typed model's FastMCP pre-parsing did for declared properties: a JSON string for a declared property that takes no strings decodes to the list/dict/null it holds when the property takes that, including allOf: [{$ref}] (older pydantic, zod) and untyped ({}) properties; "null" becomes None. Undeclared keys are still forwarded unchanged. Co-Authored-By: Claude Opus 5.5 --- src/agent_env/env/gateway/gateway.py | 28 +++++++++++-------- tst/unit/env/gateway/node_child/server.mjs | 7 +++-- .../env/gateway/node_child_arguments_test.py | 14 ++++++++-- 3 files changed, 33 insertions(+), 16 deletions(-) diff --git a/src/agent_env/env/gateway/gateway.py b/src/agent_env/env/gateway/gateway.py index 8d683fee4..1383ef4c2 100644 --- a/src/agent_env/env/gateway/gateway.py +++ b/src/agent_env/env/gateway/gateway.py @@ -1665,7 +1665,8 @@ async def proxy(**kwargs) -> CallToolResult: # The child validates its own arguments: the model declares none and forwards what the caller sent, as /step # does, so a missing, misnamed, undeclared or wrong-typed argument gets the child's own answer. The one repair - # kept from the typed model: a JSON string for a parameter the child types array or object is decoded. + # kept from the typed model: a JSON string for a declared parameter that takes no strings is decoded to the + # list, dict or null it holds when the parameter takes that. arg_model = create_model(f"{tool_name}Args", __base__=_ForwardingArgModelBase) arg_model.json_container_params = _json_container_params(input_schema) return FastMCPTool( @@ -1846,8 +1847,9 @@ def model_dump_one_level(self) -> dict[str, Any]: class _ForwardingArgModelBase(ArgModelBase): """A child proxy's arguments: no declared fields, so nothing is required or typed, and every key the caller sent (an explicit null included) is forwarded as sent. The exception is the JSON-string repair the gateway's typed model - used to give through FastMCP's pre-parsing: a string sent for a parameter the child types array or object (and - not string) is decoded when it decodes to that type, so a model's '["a"]' still reaches a strict child as a list.""" + used to give through FastMCP's pre-parsing: a string sent for a declared parameter that takes no strings is decoded + when it decodes to a list, dict or null the parameter takes (``_json_container_params``), so a model's '["a"]' + still reaches a strict child as a list and "null" as null.""" model_config = ConfigDict(extra="allow") json_container_params: ClassVar[dict[str, tuple[type, ...]]] = {} @@ -1874,13 +1876,14 @@ def model_dump_one_level(self) -> dict[str, Any]: def _schema_types(schema: Any, root: Any = None, depth: int = 0) -> set[str]: - """The JSON types a property schema allows: its `type` (a name or a list), those of its anyOf/oneOf branches, and - those of a local `$ref` (``#/$defs/...``, ``#/definitions/...``) into ``root``, the tool's input schema.""" + """The JSON types a property schema allows: its `type` (a name or a list), those of its anyOf/oneOf/allOf branches + (allOf: [{$ref}] is how older pydantic and zod wrap a reference), and those of a local `$ref` (``#/$defs/...``, + ``#/definitions/...``) into ``root``, the tool's input schema. Empty when the schema names no type.""" if not isinstance(schema, dict) or depth > _SCHEMA_REF_DEPTH: return set() declared = schema.get("type") types = {declared} if isinstance(declared, str) else {t for t in declared or () if isinstance(t, str)} - for key in ("anyOf", "oneOf"): + for key in ("anyOf", "oneOf", "allOf"): for branch in schema.get(key) or (): types |= _schema_types(branch, root, depth + 1) ref = schema.get("$ref") @@ -1894,14 +1897,17 @@ def _schema_types(schema: Any, root: Any = None, depth: int = 0) -> set[str]: def _json_container_params(input_schema: dict[str, Any]) -> dict[str, tuple[type, ...]]: - """Each property the child types array and/or object but not string, with the Python types a JSON string sent for - it may decode to. A property that also accepts a string keeps the string the caller sent.""" + """Each declared property that takes no string, with the Python types a JSON string sent for it may decode to, as + the typed model's FastMCP pre-parsing did: a list or dict when the child types it array or object, or names no + type at all (``{}``), and None (the string "null") always. A property that accepts a string keeps the string the + caller sent, and a string decoding to a number or boolean stays a string.""" params: dict[str, tuple[type, ...]] = {} for name, schema in (input_schema.get("properties") or {}).items(): types = _schema_types(schema, input_schema) - kinds = tuple(_JSON_CONTAINER_TYPES[t] for t in sorted(types) if t in _JSON_CONTAINER_TYPES) - if kinds and "string" not in types: - params[name] = kinds + if "string" in types: + continue + containers = types & _JSON_CONTAINER_TYPES.keys() if types else _JSON_CONTAINER_TYPES.keys() + params[name] = (*(_JSON_CONTAINER_TYPES[t] for t in sorted(containers)), type(None)) return params diff --git a/tst/unit/env/gateway/node_child/server.mjs b/tst/unit/env/gateway/node_child/server.mjs index 16909e868..5b84cdfcf 100644 --- a/tst/unit/env/gateway/node_child/server.mjs +++ b/tst/unit/env/gateway/node_child/server.mjs @@ -15,9 +15,11 @@ const TOOL = { filters: { type: "object" }, ids: { anyOf: [{ type: "array", items: { type: "string" } }, { type: "null" }] }, tags: { $ref: "#/$defs/Tags" }, + sort: { allOf: [{ $ref: "#/$defs/Sort" }], description: "older pydantic / zod wrap a $ref in allOf" }, + meta: { description: "untyped: any JSON value" }, }, additionalProperties: false, - $defs: { Tags: { type: "array", items: { type: "string" } } }, + $defs: { Tags: { type: "array", items: { type: "string" } }, Sort: { type: "object" } }, }, }; @@ -27,7 +29,8 @@ function invalidFields(args) { if (!(key in TOOL.inputSchema.properties)) bad.push(key); else if (key === "q" && typeof value !== "string") bad.push(key); else if (key === "labels" && !(Array.isArray(value) && value.every((v) => typeof v === "string"))) bad.push(key); - else if (key === "filters" && !(value !== null && typeof value === "object" && !Array.isArray(value))) bad.push(key); + else if ((key === "filters" || key === "sort") && !(value !== null && typeof value === "object" && !Array.isArray(value))) + bad.push(key); else if (key === "tags" && !(Array.isArray(value) && value.every((v) => typeof v === "string"))) bad.push(key); else if (key === "ids" && !(value === null || (Array.isArray(value) && value.every((v) => typeof v === "string")))) bad.push(key); diff --git a/tst/unit/env/gateway/node_child_arguments_test.py b/tst/unit/env/gateway/node_child_arguments_test.py index cf9a8af6b..9c86ac7fc 100644 --- a/tst/unit/env/gateway/node_child_arguments_test.py +++ b/tst/unit/env/gateway/node_child_arguments_test.py @@ -2,8 +2,9 @@ never re-parsing a JSON string, as @playwright/mcp does) gets a tool's arguments from the gateway's MCP path as the caller sent them: an undeclared key reaches it (and it refuses it by name) and declared ones arrive unchanged. The one repair the gateway keeps on the MCP path, as before it stopped validating child arguments: a JSON string sent for a -parameter the child types array or object is decoded to that list or dict, and any other string (one for a string -parameter, or one that decodes to another type) stays the string. /step forwards every value as sent.""" +declared parameter that takes no strings is decoded to the list or dict it holds when the child types it array or +object (directly, through anyOf/allOf or a $ref) or leaves it untyped, and "null" to null; any other string (one for a +string parameter, or one that decodes to another type) stays the string. /step forwards every value as sent.""" from __future__ import annotations import asyncio @@ -71,7 +72,7 @@ async def _via_step(gw: Gateway, arguments: dict) -> tuple[bool, dict]: async def test_the_gateway_lists_the_node_childs_schema_verbatim(gateway): listed = {tool.name: tool for tool in await gateway._mcp.list_tools()} assert listed[TOOL].inputSchema["additionalProperties"] is False - assert set(listed[TOOL].inputSchema["properties"]) == {"q", "labels", "filters", "ids", "tags"} + assert set(listed[TOOL].inputSchema["properties"]) == {"q", "labels", "filters", "ids", "tags", "sort", "meta"} @pytest.mark.asyncio @@ -96,6 +97,13 @@ async def test_an_undeclared_argument_reaches_the_node_child_which_refuses_it_by ({"ids": '["m1"]'}, {"ids": ["m1"]}), # anyOf array | null ({"tags": '["t1"]'}, {"tags": ["t1"]}), # a local $ref to an array definition ({"q": '["a"]', "labels": "[]"}, {"q": '["a"]', "labels": []}), # q is typed string: it stays the string + ({"sort": '{"a": 1}'}, {"sort": {"a": 1}}), # allOf: [{$ref}] to an object definition + ({"meta": '["a"]'}, {"meta": ["a"]}), # an untyped property + ({"meta": '{"a": 1}'}, {"meta": {"a": 1}}), + ({"ids": "null"}, {"ids": None}), # the string "null" for a property that doesn't take strings + ({"meta": "null"}, {"meta": None}), + ({"q": "null"}, {"q": "null"}), # q is typed string: it stays the string + ({"meta": "7"}, {"meta": "7"}), # JSON, but a number: stays the string, as before ]) async def test_a_json_string_for_an_array_or_object_parameter_reaches_the_node_child_decoded(gateway, arguments, decoded): From 22f567dbb54e025cad2aeed0a145dcee6b6d78cb Mon Sep 17 00:00:00 2001 From: Tu Trinh Date: Tue, 24 Nov 2026 01:18:06 +0000 Subject: [PATCH 8/8] gateway: an enum or const of strings counts as taking strings in the JSON-string repair A property with no type but enum ["null", "auto"] got its valid "null" decoded to null; enum/const values now give the property their JSON types, so such strings stay strings. Co-Authored-By: Claude Opus 5.5 --- src/agent_env/env/gateway/gateway.py | 6 +++++- tst/unit/env/gateway/node_child/server.mjs | 2 ++ tst/unit/env/gateway/node_child_arguments_test.py | 4 +++- 3 files changed, 10 insertions(+), 2 deletions(-) diff --git a/src/agent_env/env/gateway/gateway.py b/src/agent_env/env/gateway/gateway.py index 1383ef4c2..734850f39 100644 --- a/src/agent_env/env/gateway/gateway.py +++ b/src/agent_env/env/gateway/gateway.py @@ -1872,17 +1872,21 @@ def model_dump_one_level(self) -> dict[str, Any]: _JSON_CONTAINER_TYPES: dict[str, type] = {"array": list, "object": dict} +_JSON_VALUE_TYPES: dict[type, str] = {str: "string", type(None): "null", list: "array", dict: "object", bool: "boolean"} _SCHEMA_REF_DEPTH = 8 # local $ref hops followed when typing a property; deeper (or cyclic) refs add no type def _schema_types(schema: Any, root: Any = None, depth: int = 0) -> set[str]: """The JSON types a property schema allows: its `type` (a name or a list), those of its anyOf/oneOf/allOf branches (allOf: [{$ref}] is how older pydantic and zod wrap a reference), and those of a local `$ref` (``#/$defs/...``, - ``#/definitions/...``) into ``root``, the tool's input schema. Empty when the schema names no type.""" + ``#/definitions/...``) into ``root``, the tool's input schema, plus the types of its `enum` / `const` values. + Empty when the schema says nothing about type.""" if not isinstance(schema, dict) or depth > _SCHEMA_REF_DEPTH: return set() declared = schema.get("type") types = {declared} if isinstance(declared, str) else {t for t in declared or () if isinstance(t, str)} + values = list(schema.get("enum") or ()) + ([schema["const"]] if "const" in schema else []) + types |= {_JSON_VALUE_TYPES.get(type(v), "number") for v in values} for key in ("anyOf", "oneOf", "allOf"): for branch in schema.get(key) or (): types |= _schema_types(branch, root, depth + 1) diff --git a/tst/unit/env/gateway/node_child/server.mjs b/tst/unit/env/gateway/node_child/server.mjs index 5b84cdfcf..5641b5ba6 100644 --- a/tst/unit/env/gateway/node_child/server.mjs +++ b/tst/unit/env/gateway/node_child/server.mjs @@ -17,6 +17,7 @@ const TOOL = { tags: { $ref: "#/$defs/Tags" }, sort: { allOf: [{ $ref: "#/$defs/Sort" }], description: "older pydantic / zod wrap a $ref in allOf" }, meta: { description: "untyped: any JSON value" }, + mode: { enum: ["null", "auto", "[]"] }, }, additionalProperties: false, $defs: { Tags: { type: "array", items: { type: "string" } }, Sort: { type: "object" } }, @@ -31,6 +32,7 @@ function invalidFields(args) { else if (key === "labels" && !(Array.isArray(value) && value.every((v) => typeof v === "string"))) bad.push(key); else if ((key === "filters" || key === "sort") && !(value !== null && typeof value === "object" && !Array.isArray(value))) bad.push(key); + else if (key === "mode" && !TOOL.inputSchema.properties.mode.enum.includes(value)) bad.push(key); else if (key === "tags" && !(Array.isArray(value) && value.every((v) => typeof v === "string"))) bad.push(key); else if (key === "ids" && !(value === null || (Array.isArray(value) && value.every((v) => typeof v === "string")))) bad.push(key); diff --git a/tst/unit/env/gateway/node_child_arguments_test.py b/tst/unit/env/gateway/node_child_arguments_test.py index 9c86ac7fc..882d2f408 100644 --- a/tst/unit/env/gateway/node_child_arguments_test.py +++ b/tst/unit/env/gateway/node_child_arguments_test.py @@ -72,7 +72,7 @@ async def _via_step(gw: Gateway, arguments: dict) -> tuple[bool, dict]: async def test_the_gateway_lists_the_node_childs_schema_verbatim(gateway): listed = {tool.name: tool for tool in await gateway._mcp.list_tools()} assert listed[TOOL].inputSchema["additionalProperties"] is False - assert set(listed[TOOL].inputSchema["properties"]) == {"q", "labels", "filters", "ids", "tags", "sort", "meta"} + assert set(listed[TOOL].inputSchema["properties"]) == {"q", "labels", "filters", "ids", "tags", "sort", "meta", "mode"} @pytest.mark.asyncio @@ -104,6 +104,8 @@ async def test_an_undeclared_argument_reaches_the_node_child_which_refuses_it_by ({"meta": "null"}, {"meta": None}), ({"q": "null"}, {"q": "null"}), # q is typed string: it stays the string ({"meta": "7"}, {"meta": "7"}), # JSON, but a number: stays the string, as before + ({"mode": "null"}, {"mode": "null"}), # an untyped enum of strings takes strings: they stay strings + ({"mode": "[]"}, {"mode": "[]"}), ]) async def test_a_json_string_for_an_array_or_object_parameter_reaches_the_node_child_decoded(gateway, arguments, decoded):