Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
86 changes: 81 additions & 5 deletions src/agent_env/env/gateway/gateway.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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
Expand Down Expand Up @@ -1663,7 +1663,12 @@ async def proxy(**kwargs) -> CallToolResult:
})
return result

arg_model = self._create_arg_model_from_schema(tool_name, input_schema)
# 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 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(
fn=proxy,
name=tool_name,
Expand Down Expand Up @@ -1822,8 +1827,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.
"""
Expand All @@ -1839,6 +1844,77 @@ def model_dump_one_level(self) -> dict[str, Any]:
return kwargs


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 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, ...]]] = {}

def model_dump_one_level(self) -> dict[str, Any]:
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}


_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, 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)
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


def _json_container_params(input_schema: dict[str, Any]) -> dict[str, tuple[type, ...]]:
"""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)
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))
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
return params


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:
Expand Down
80 changes: 80 additions & 0 deletions tst/unit/env/gateway/node_child/server.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
// 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 (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 = {
name: "find_messages",
description: "Find messages.",
inputSchema: {
type: "object",
properties: {
q: { type: "string" },
labels: { type: "array", items: { type: "string" } },
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" },
mode: { enum: ["null", "auto", "[]"] },
},
additionalProperties: false,
$defs: { Tags: { type: "array", items: { type: "string" } }, Sort: { type: "object" } },
},
};

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);
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);
}
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));
138 changes: 138 additions & 0 deletions tst/unit/env/gateway/node_child_arguments_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
"""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, 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
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
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", "filters", "ids", "tags", "sort", "meta", "mode"}


@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
@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
({"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
({"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):
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_step(gateway, arguments) == expected
Loading
Loading