Skip to content
Merged
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
15 changes: 10 additions & 5 deletions src/agents/mcp/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -376,16 +376,21 @@ async def invoke_mcp_tool(
meta: dict[str, Any] | None = None,
) -> ToolOutput:
"""Invoke an MCP tool and return the result as ToolOutput."""
json_decode_error: Exception | None = None
try:
json_data: dict[str, Any] = json.loads(input_json) if input_json else {}
except Exception as e:
json_decode_error = e

if json_decode_error is not None:
error_message = f"Invalid JSON input for tool {tool.name}"
if _debug.DONT_LOG_TOOL_DATA:
logger.debug(f"Invalid JSON input for tool {tool.name}")
logger.debug(error_message)
raise ModelBehaviorError(error_message)
else:
logger.debug(f"Invalid JSON input for tool {tool.name}: {input_json}")
raise ModelBehaviorError(
f"Invalid JSON input for tool {tool.name}: {input_json}"
) from e
error_message = f"{error_message}: {input_json}"
logger.debug(error_message)
raise ModelBehaviorError(error_message) from json_decode_error

if _debug.DONT_LOG_TOOL_DATA:
logger.debug(f"Invoking MCP tool {tool.name}")
Expand Down
49 changes: 49 additions & 0 deletions tests/mcp/test_mcp_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from mcp.types import CallToolResult, ImageContent, TextContent, Tool as MCPTool
from pydantic import BaseModel, TypeAdapter

import agents._debug as _debug
from agents import Agent, FunctionTool, RunContextWrapper, default_tool_error_function
from agents.exceptions import AgentsException, MCPToolCancellationError, ModelBehaviorError
from agents.mcp import MCPServer, MCPUtil
Expand Down Expand Up @@ -222,6 +223,54 @@ async def test_mcp_invoke_bad_json_errors(caplog: pytest.LogCaptureFixture):
assert "Invalid JSON input for tool test_tool_1" in caplog.text


@pytest.mark.asyncio
async def test_mcp_invoke_bad_json_redacts_payload_when_dont_log_tool_data(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
):
caplog.set_level(logging.DEBUG)
monkeypatch.setattr(_debug, "DONT_LOG_TOOL_DATA", True)

server = FakeMCPServer()
server.add_tool("test_tool_1", {})

ctx = RunContextWrapper(context=None)
tool = MCPTool(name="test_tool_1", inputSchema={})
bad_json = '{"secret":"SECRET_TOKEN_123"'

with pytest.raises(ModelBehaviorError) as exc_info:
await MCPUtil.invoke_mcp_tool(server, tool, ctx, bad_json)

assert str(exc_info.value) == "Invalid JSON input for tool test_tool_1"
assert exc_info.value.__cause__ is None
assert exc_info.value.__context__ is None
assert "SECRET_TOKEN_123" not in str(exc_info.value)
assert "SECRET_TOKEN_123" not in caplog.text


@pytest.mark.asyncio
async def test_mcp_invoke_bad_json_includes_payload_when_tool_logging_enabled(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
):
caplog.set_level(logging.DEBUG)
monkeypatch.setattr(_debug, "DONT_LOG_TOOL_DATA", False)

server = FakeMCPServer()
server.add_tool("test_tool_1", {})

ctx = RunContextWrapper(context=None)
tool = MCPTool(name="test_tool_1", inputSchema={})
bad_json = '{"secret":"SECRET_TOKEN_123"'

with pytest.raises(ModelBehaviorError) as exc_info:
await MCPUtil.invoke_mcp_tool(server, tool, ctx, bad_json)

assert str(exc_info.value) == f"Invalid JSON input for tool test_tool_1: {bad_json}"
assert isinstance(exc_info.value.__cause__, json.JSONDecodeError)
assert exc_info.value.__cause__.doc == bad_json
assert "SECRET_TOKEN_123" in str(exc_info.value)
assert "SECRET_TOKEN_123" in caplog.text


class CrashingFakeMCPServer(FakeMCPServer):
async def call_tool(
self,
Expand Down