Repository navigation
fix(gateway): forward undeclared tool arguments to the child on the MCP path #857
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
tu-trinh-scale
wants to merge
8
commits into
main
Choose a base branch
from
tutrinh/gateway-reject-unknown-args
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
1b1fc1c
fix(gateway): forward undeclared tool arguments to the child on the M…
tu-trinh-scale 519d902
fix(gateway): forward undeclared arguments only through child proxies
tu-trinh-scale 369c207
fix(gateway): leave a child tool's arguments for the child to validate
tu-trinh-scale c88c056
test(gateway): a non-FastMCP (Node) child gets undeclared keys and JS…
tu-trinh-scale ff7ed90
fix(gateway): still decode a JSON string sent for an array or object …
tu-trinh-scale 6f42144
fix(gateway): the JSON-string repair also follows a local $ref to an …
tu-trinh-scale e697099
gateway: JSON-string repair also covers allOf refs, untyped propertie…
tu-trinh-scale 22f567d
gateway: an enum or const of strings counts as taking strings in the …
tu-trinh-scale File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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)); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.