|
| 1 | +import functools |
| 2 | +import json |
| 3 | +from typing import Any |
| 4 | + |
| 5 | +from mcp.types import Tool as MCPTool |
| 6 | + |
| 7 | +from .. import _debug |
| 8 | +from ..exceptions import AgentsException, ModelBehaviorError, UserError |
| 9 | +from ..logger import logger |
| 10 | +from ..run_context import RunContextWrapper |
| 11 | +from ..tool import FunctionTool, Tool |
| 12 | +from .server import MCPServer |
| 13 | + |
| 14 | + |
| 15 | +class MCPUtil: |
| 16 | + """Set of utilities for interop between MCP and Agents SDK tools.""" |
| 17 | + |
| 18 | + @classmethod |
| 19 | + async def get_all_function_tools(cls, servers: list[MCPServer]) -> list[Tool]: |
| 20 | + """Get all function tools from a list of MCP servers.""" |
| 21 | + tools = [] |
| 22 | + tool_names: set[str] = set() |
| 23 | + for server in servers: |
| 24 | + server_tools = await cls.get_function_tools(server) |
| 25 | + server_tool_names = {tool.name for tool in server_tools} |
| 26 | + if len(server_tool_names & tool_names) > 0: |
| 27 | + raise UserError( |
| 28 | + f"Duplicate tool names found across MCP servers: " |
| 29 | + f"{server_tool_names & tool_names}" |
| 30 | + ) |
| 31 | + tool_names.update(server_tool_names) |
| 32 | + tools.extend(server_tools) |
| 33 | + |
| 34 | + return tools |
| 35 | + |
| 36 | + @classmethod |
| 37 | + async def get_function_tools(cls, server: MCPServer) -> list[Tool]: |
| 38 | + """Get all function tools from a single MCP server.""" |
| 39 | + tools = await server.list_tools() |
| 40 | + return [cls.to_function_tool(tool, server) for tool in tools] |
| 41 | + |
| 42 | + @classmethod |
| 43 | + def to_function_tool(cls, tool: MCPTool, server: MCPServer) -> FunctionTool: |
| 44 | + """Convert an MCP tool to an Agents SDK function tool.""" |
| 45 | + invoke_func = functools.partial(cls.invoke_mcp_tool, server, tool) |
| 46 | + return FunctionTool( |
| 47 | + name=tool.name, |
| 48 | + description=tool.description or "", |
| 49 | + params_json_schema=tool.inputSchema, |
| 50 | + on_invoke_tool=invoke_func, |
| 51 | + strict_json_schema=False, |
| 52 | + ) |
| 53 | + |
| 54 | + @classmethod |
| 55 | + async def invoke_mcp_tool( |
| 56 | + cls, server: MCPServer, tool: MCPTool, context: RunContextWrapper[Any], input_json: str |
| 57 | + ) -> str: |
| 58 | + """Invoke an MCP tool and return the result as a string.""" |
| 59 | + try: |
| 60 | + json_data: dict[str, Any] = json.loads(input_json) if input_json else {} |
| 61 | + except Exception as e: |
| 62 | + if _debug.DONT_LOG_TOOL_DATA: |
| 63 | + logger.debug(f"Invalid JSON input for tool {tool.name}") |
| 64 | + else: |
| 65 | + logger.debug(f"Invalid JSON input for tool {tool.name}: {input_json}") |
| 66 | + raise ModelBehaviorError( |
| 67 | + f"Invalid JSON input for tool {tool.name}: {input_json}" |
| 68 | + ) from e |
| 69 | + |
| 70 | + if _debug.DONT_LOG_TOOL_DATA: |
| 71 | + logger.debug(f"Invoking MCP tool {tool.name}") |
| 72 | + else: |
| 73 | + logger.debug(f"Invoking MCP tool {tool.name} with input {input_json}") |
| 74 | + |
| 75 | + try: |
| 76 | + result = await server.call_tool(tool.name, json_data) |
| 77 | + except Exception as e: |
| 78 | + logger.error(f"Error invoking MCP tool {tool.name}: {e}") |
| 79 | + raise AgentsException(f"Error invoking MCP tool {tool.name}: {e}") from e |
| 80 | + |
| 81 | + if _debug.DONT_LOG_TOOL_DATA: |
| 82 | + logger.debug(f"MCP tool {tool.name} completed.") |
| 83 | + else: |
| 84 | + logger.debug(f"MCP tool {tool.name} returned {result}") |
| 85 | + |
| 86 | + # The MCP tool result is a list of content items, whereas OpenAI tool outputs are a single |
| 87 | + # string. We'll try to convert. |
| 88 | + if len(result.content) == 1: |
| 89 | + return result.content[0].model_dump_json() |
| 90 | + elif len(result.content) > 1: |
| 91 | + return json.dumps([item.model_dump() for item in result.content]) |
| 92 | + else: |
| 93 | + logger.error(f"Errored MCP tool result: {result}") |
| 94 | + return "Error running tool." |
0 commit comments