Skip to content

[MCP][Utils] Add support for FastMCP processing #631

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
wants to merge 1 commit into
base: main
Choose a base branch
from
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
15 changes: 9 additions & 6 deletions src/agents/mcp/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,13 +113,16 @@ async def invoke_mcp_tool(

# The MCP tool result is a list of content items, whereas OpenAI tool outputs are a single
# string. We'll try to convert.
if len(result.content) == 1:
tool_output = result.content[0].model_dump_json()
elif len(result.content) > 1:
tool_output = json.dumps([item.model_dump() for item in result.content])
if type(result) == list:
tool_output = json.dumps([item.model_dump() for item in result])
else:
logger.error(f"Errored MCP tool result: {result}")
tool_output = "Error running tool."
if len(result.content) == 1:
tool_output = result.content[0].model_dump_json()
elif len(result.content) > 1:
tool_output = json.dumps([item.model_dump() for item in result.content])
else:
logger.error(f"Errored MCP tool result: {result}")
tool_output = "Error running tool."

current_span = get_current_span()
if current_span:
Expand Down
45 changes: 44 additions & 1 deletion tests/mcp/test_mcp_util.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import logging
from typing import Any
import json

import pytest
from inline_snapshot import snapshot
from mcp.types import Tool as MCPTool
from mcp.types import Tool as MCPTool, CallToolResult, TextContent
from pydantic import BaseModel, TypeAdapter

from agents import Agent, FunctionTool, RunContextWrapper
Expand Down Expand Up @@ -75,6 +76,19 @@ async def test_get_all_function_tools():
assert all(tool.name in names for tool in tools)


@pytest.mark.asyncio
async def test_invoke_mcp_tool():
"""Test that the invoke_mcp_tool function invokes an MCP tool and returns the result."""
server = FakeMCPServer()
server.add_tool("test_tool_1", {})

ctx = RunContextWrapper(context=None)
tool = MCPTool(name="test_tool_1", inputSchema={})

await MCPUtil.invoke_mcp_tool(server, tool, ctx, "")
# Just making sure it doesn't crash


@pytest.mark.asyncio
async def test_invoke_mcp_tool():
"""Test that the invoke_mcp_tool function invokes an MCP tool and returns the result."""
Expand Down Expand Up @@ -125,6 +139,35 @@ async def test_mcp_invocation_crash_causes_error(caplog: pytest.LogCaptureFixtur
await MCPUtil.invoke_mcp_tool(server, tool, ctx, "")

assert "Error invoking MCP tool test_tool_1" in caplog.text

class ResultTestingServer(FakeMCPServer):
def __init__(self):
super().__init__()
self.return_empty = False
self.return_multiple = False

async def call_tool(self, tool_name: str, arguments: dict[str, Any] | None) -> CallToolResult:
if self.return_empty:
return CallToolResult(content=[])
elif self.return_multiple:
return CallToolResult(content=[
TextContent(text="result1", type="text"),
TextContent(text="result2", type="text")
])
return CallToolResult(content=[TextContent(text=f"result_{tool_name}", type="text")])


@pytest.mark.asyncio
async def test_mcp_tool_result_conversion():
"""Test that MCP tool results with empty content return error message."""
server = ResultTestingServer()
server.return_empty = True
server.add_tool("test_tool", {})
ctx = RunContextWrapper(context=None)
tool = MCPTool(name="test_tool", inputSchema={})

result = await MCPUtil.invoke_mcp_tool(server, tool, ctx, "{}")
assert result == "Error running tool."


@pytest.mark.asyncio
Expand Down