diff --git a/src/agent_env/env/gateway/gateway.py b/src/agent_env/env/gateway/gateway.py index ae2af8ed6..734850f39 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 @@ -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 @@ -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, @@ -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. """ @@ -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)) + 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: 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..5641b5ba6 --- /dev/null +++ b/tst/unit/env/gateway/node_child/server.mjs @@ -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)); 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..882d2f408 --- /dev/null +++ b/tst/unit/env/gateway/node_child_arguments_test.py @@ -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 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..782ae0941 --- /dev/null +++ b/tst/unit/env/gateway/unknown_arguments_test.py @@ -0,0 +1,187 @@ +"""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 +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={ + "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}) +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 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 TOOLS + + @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))] + + 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 TOOLS: + 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]: + 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]: + 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 + + +@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): + 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 + + +@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}