Skip to content

Commit e22f25a

Browse files
fix(mcp): reject non-object tool input JSON (#3135)
1 parent 6e691ee commit e22f25a

2 files changed

Lines changed: 21 additions & 1 deletion

File tree

src/agents/mcp/util.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -378,7 +378,7 @@ async def invoke_mcp_tool(
378378
"""Invoke an MCP tool and return the result as ToolOutput."""
379379
json_decode_error: Exception | None = None
380380
try:
381-
json_data: dict[str, Any] = json.loads(input_json) if input_json else {}
381+
json_data = json.loads(input_json) if input_json else {}
382382
except Exception as e:
383383
json_decode_error = e
384384

@@ -392,6 +392,11 @@ async def invoke_mcp_tool(
392392
logger.debug(error_message)
393393
raise ModelBehaviorError(error_message) from json_decode_error
394394

395+
if not isinstance(json_data, dict):
396+
raise ModelBehaviorError(
397+
f"Invalid JSON input for tool {tool.name}: expected a JSON object"
398+
)
399+
395400
if _debug.DONT_LOG_TOOL_DATA:
396401
logger.debug(f"Invoking MCP tool {tool.name}")
397402
else:

tests/mcp/test_mcp_util.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -306,6 +306,21 @@ async def test_mcp_invoke_bad_json_includes_payload_when_tool_logging_enabled(
306306
assert "SECRET_TOKEN_123" in caplog.text
307307

308308

309+
@pytest.mark.asyncio
310+
@pytest.mark.parametrize("input_json", ["[]", '"value"', "123", "null"])
311+
async def test_mcp_invoke_rejects_non_object_json_input(input_json: str):
312+
server = FakeMCPServer()
313+
server.add_tool("test_tool_1", {})
314+
315+
ctx = RunContextWrapper(context=None)
316+
tool = MCPTool(name="test_tool_1", inputSchema={})
317+
318+
with pytest.raises(ModelBehaviorError, match="expected a JSON object"):
319+
await MCPUtil.invoke_mcp_tool(server, tool, ctx, input_json)
320+
321+
assert server.tool_calls == []
322+
323+
309324
class CrashingFakeMCPServer(FakeMCPServer):
310325
async def call_tool(
311326
self,

0 commit comments

Comments
 (0)