Movatterモバイル変換


[0]ホーム

URL:


Skip to content

MCP Util

HttpClientFactory

Bases:Protocol

Protocol for HTTP client factory functions.

This interface matches the MCP SDK's McpHttpClientFactory but is defined locallyto avoid accessing internal MCP SDK modules.

Source code insrc/agents/mcp/util.py
classHttpClientFactory(Protocol):"""Protocol for HTTP client factory functions.    This interface matches the MCP SDK's McpHttpClientFactory but is defined locally    to avoid accessing internal MCP SDK modules.    """def__call__(self,headers:dict[str,str]|None=None,timeout:httpx.Timeout|None=None,auth:httpx.Auth|None=None,)->httpx.AsyncClient:...

ToolFilterContextdataclass

Context information available to tool filter functions.

Source code insrc/agents/mcp/util.py
@dataclassclassToolFilterContext:"""Context information available to tool filter functions."""run_context:RunContextWrapper[Any]"""The current run context."""agent:AgentBase"""The agent that is requesting the tool list."""server_name:str"""The name of the MCP server."""

run_contextinstance-attribute

run_context:RunContextWrapper[Any]

The current run context.

agentinstance-attribute

agent:AgentBase

The agent that is requesting the tool list.

server_nameinstance-attribute

server_name:str

The name of the MCP server.

ToolFilterStatic

Bases:TypedDict

Static tool filter configuration using allowlists and blocklists.

Source code insrc/agents/mcp/util.py
classToolFilterStatic(TypedDict):"""Static tool filter configuration using allowlists and blocklists."""allowed_tool_names:NotRequired[list[str]]"""Optional list of tool names to allow (whitelist).    If set, only these tools will be available."""blocked_tool_names:NotRequired[list[str]]"""Optional list of tool names to exclude (blacklist).    If set, these tools will be filtered out."""

allowed_tool_namesinstance-attribute

allowed_tool_names:NotRequired[list[str]]

Optional list of tool names to allow (whitelist).If set, only these tools will be available.

blocked_tool_namesinstance-attribute

blocked_tool_names:NotRequired[list[str]]

Optional list of tool names to exclude (blacklist).If set, these tools will be filtered out.

MCPToolMetaContextdataclass

Context information available to MCP tool meta resolver functions.

Source code insrc/agents/mcp/util.py
@dataclassclassMCPToolMetaContext:"""Context information available to MCP tool meta resolver functions."""run_context:RunContextWrapper[Any]"""The current run context."""server_name:str"""The name of the MCP server."""tool_name:str"""The name of the tool being invoked."""arguments:dict[str,Any]|None"""The parsed tool arguments."""

run_contextinstance-attribute

run_context:RunContextWrapper[Any]

The current run context.

server_nameinstance-attribute

server_name:str

The name of the MCP server.

tool_nameinstance-attribute

tool_name:str

The name of the tool being invoked.

argumentsinstance-attribute

arguments:dict[str,Any]|None

The parsed tool arguments.

MCPUtil

Set of utilities for interop between MCP and Agents SDK tools.

Source code insrc/agents/mcp/util.py
170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
classMCPUtil:"""Set of utilities for interop between MCP and Agents SDK tools."""@classmethodasyncdefget_all_function_tools(cls,servers:list[MCPServer],convert_schemas_to_strict:bool,run_context:RunContextWrapper[Any],agent:AgentBase,failure_error_function:ToolErrorFunction|None=default_tool_error_function,)->list[Tool]:"""Get all function tools from a list of MCP servers."""tools=[]tool_names:set[str]=set()forserverinservers:server_tools=awaitcls.get_function_tools(server,convert_schemas_to_strict,run_context,agent,failure_error_function=failure_error_function,)server_tool_names={tool.namefortoolinserver_tools}iflen(server_tool_names&tool_names)>0:raiseUserError(f"Duplicate tool names found across MCP servers: "f"{server_tool_names&tool_names}")tool_names.update(server_tool_names)tools.extend(server_tools)returntools@classmethodasyncdefget_function_tools(cls,server:MCPServer,convert_schemas_to_strict:bool,run_context:RunContextWrapper[Any],agent:AgentBase,failure_error_function:ToolErrorFunction|None=default_tool_error_function,)->list[Tool]:"""Get all function tools from a single MCP server."""withmcp_tools_span(server=server.name)asspan:tools=awaitserver.list_tools(run_context,agent)span.span_data.result=[tool.namefortoolintools]return[cls.to_function_tool(tool,server,convert_schemas_to_strict,agent,failure_error_function=failure_error_function,)fortoolintools]@classmethoddefto_function_tool(cls,tool:MCPTool,server:MCPServer,convert_schemas_to_strict:bool,agent:AgentBase|None=None,failure_error_function:ToolErrorFunction|None=default_tool_error_function,)->FunctionTool:"""Convert an MCP tool to an Agents SDK function tool.        The ``agent`` parameter is optional for backward compatibility with older        call sites that used ``MCPUtil.to_function_tool(tool, server, strict)``.        When omitted, this helper preserves the historical behavior and leaves        ``needs_approval`` disabled.        """invoke_func_impl=functools.partial(cls.invoke_mcp_tool,server,tool)effective_failure_error_function=server._get_failure_error_function(failure_error_function)schema,is_strict=tool.inputSchema,False# MCP spec doesn't require the inputSchema to have `properties`, but OpenAI spec does.if"properties"notinschema:schema["properties"]={}ifconvert_schemas_to_strict:try:schema=ensure_strict_json_schema(schema)is_strict=TrueexceptExceptionase:logger.info(f"Error converting MCP schema to strict mode:{e}")# Wrap the invoke function with error handling, similar to regular function tools.# This ensures that MCP tool errors (like timeouts) are handled gracefully instead# of halting the entire agent flow.asyncdefinvoke_func(ctx:ToolContext[Any],input_json:str)->ToolOutput:try:returnawaitinvoke_func_impl(ctx,input_json)exceptExceptionase:ifeffective_failure_error_functionisNone:raise# Use configured error handling function to convert exception to error message.result=effective_failure_error_function(ctx,e)ifinspect.isawaitable(result):result=awaitresult# Attach error to tracing span._error_tracing.attach_error_to_current_span(SpanError(message="Error running tool (non-fatal)",data={"tool_name":tool.name,"error":str(e),},))# Log the error.if_debug.DONT_LOG_TOOL_DATA:logger.debug(f"MCP tool{tool.name} failed")else:logger.error(f"MCP tool{tool.name} failed:{input_json}{e}",exc_info=e,)returnresultneeds_approval:(bool|Callable[[RunContextWrapper[Any],dict[str,Any],str],Awaitable[bool]])=server._get_needs_approval_for_tool(tool,agent)returnFunctionTool(name=tool.name,description=tool.descriptionor"",params_json_schema=schema,on_invoke_tool=invoke_func,strict_json_schema=is_strict,needs_approval=needs_approval,)@staticmethoddef_merge_mcp_meta(resolved_meta:dict[str,Any]|None,explicit_meta:dict[str,Any]|None,)->dict[str,Any]|None:ifresolved_metaisNoneandexplicit_metaisNone:returnNonemerged:dict[str,Any]={}ifresolved_metaisnotNone:merged.update(resolved_meta)ifexplicit_metaisnotNone:merged.update(explicit_meta)returnmerged@classmethodasyncdef_resolve_meta(cls,server:MCPServer,context:RunContextWrapper[Any],tool_name:str,arguments:dict[str,Any]|None,)->dict[str,Any]|None:meta_resolver=getattr(server,"tool_meta_resolver",None)ifmeta_resolverisNone:returnNonearguments_copy=copy.deepcopy(arguments)ifargumentsisnotNoneelseNoneresolver_context=MCPToolMetaContext(run_context=context,server_name=server.name,tool_name=tool_name,arguments=arguments_copy,)result=meta_resolver(resolver_context)ifinspect.isawaitable(result):result=awaitresultifresultisNone:returnNoneifnotisinstance(result,dict):raiseTypeError("MCP meta resolver must return a dict or None.")returnresult@classmethodasyncdefinvoke_mcp_tool(cls,server:MCPServer,tool:MCPTool,context:RunContextWrapper[Any],input_json:str,*,meta:dict[str,Any]|None=None,)->ToolOutput:"""Invoke an MCP tool and return the result as ToolOutput."""try:json_data:dict[str,Any]=json.loads(input_json)ifinput_jsonelse{}exceptExceptionase:if_debug.DONT_LOG_TOOL_DATA:logger.debug(f"Invalid JSON input for tool{tool.name}")else:logger.debug(f"Invalid JSON input for tool{tool.name}:{input_json}")raiseModelBehaviorError(f"Invalid JSON input for tool{tool.name}:{input_json}")fromeif_debug.DONT_LOG_TOOL_DATA:logger.debug(f"Invoking MCP tool{tool.name}")else:logger.debug(f"Invoking MCP tool{tool.name} with input{input_json}")try:resolved_meta=awaitcls._resolve_meta(server,context,tool.name,json_data)merged_meta=cls._merge_mcp_meta(resolved_meta,meta)ifmerged_metaisNone:result=awaitserver.call_tool(tool.name,json_data)else:result=awaitserver.call_tool(tool.name,json_data,meta=merged_meta)exceptUserError:# Re-raise UserError as-is (it already has a good message)raiseexceptExceptionase:logger.error(f"Error invoking MCP tool{tool.name} on server '{server.name}':{e}")raiseAgentsException(f"Error invoking MCP tool{tool.name} on server '{server.name}':{e}")fromeif_debug.DONT_LOG_TOOL_DATA:logger.debug(f"MCP tool{tool.name} completed.")else:logger.debug(f"MCP tool{tool.name} returned{result}")# If structured content is requested and available, use it exclusivelytool_output:ToolOutputifserver.use_structured_contentandresult.structuredContent:tool_output=json.dumps(result.structuredContent)else:tool_output_list:list[ToolOutputItem]=[]foriteminresult.content:ifitem.type=="text":tool_output_list.append(ToolOutputTextDict(type="text",text=item.text))elifitem.type=="image":tool_output_list.append(ToolOutputImageDict(type="image",image_url=f"data:{item.mimeType};base64,{item.data}"))else:# Fall back to regular text contenttool_output_list.append(ToolOutputTextDict(type="text",text=str(item.model_dump(mode="json"))))iflen(tool_output_list)==1:tool_output=tool_output_list[0]else:tool_output=tool_output_listcurrent_span=get_current_span()ifcurrent_span:ifisinstance(current_span.span_data,FunctionSpanData):current_span.span_data.output=tool_outputcurrent_span.span_data.mcp_data={"server":server.name,}else:logger.warning(f"Current span is not a FunctionSpanData, skipping tool output:{current_span}")returntool_output

get_all_function_toolsasyncclassmethod

get_all_function_tools(servers:list[MCPServer],convert_schemas_to_strict:bool,run_context:RunContextWrapper[Any],agent:AgentBase,failure_error_function:ToolErrorFunction|None=default_tool_error_function,)->list[Tool]

Get all function tools from a list of MCP servers.

Source code insrc/agents/mcp/util.py
@classmethodasyncdefget_all_function_tools(cls,servers:list[MCPServer],convert_schemas_to_strict:bool,run_context:RunContextWrapper[Any],agent:AgentBase,failure_error_function:ToolErrorFunction|None=default_tool_error_function,)->list[Tool]:"""Get all function tools from a list of MCP servers."""tools=[]tool_names:set[str]=set()forserverinservers:server_tools=awaitcls.get_function_tools(server,convert_schemas_to_strict,run_context,agent,failure_error_function=failure_error_function,)server_tool_names={tool.namefortoolinserver_tools}iflen(server_tool_names&tool_names)>0:raiseUserError(f"Duplicate tool names found across MCP servers: "f"{server_tool_names&tool_names}")tool_names.update(server_tool_names)tools.extend(server_tools)returntools

get_function_toolsasyncclassmethod

get_function_tools(server:MCPServer,convert_schemas_to_strict:bool,run_context:RunContextWrapper[Any],agent:AgentBase,failure_error_function:ToolErrorFunction|None=default_tool_error_function,)->list[Tool]

Get all function tools from a single MCP server.

Source code insrc/agents/mcp/util.py
@classmethodasyncdefget_function_tools(cls,server:MCPServer,convert_schemas_to_strict:bool,run_context:RunContextWrapper[Any],agent:AgentBase,failure_error_function:ToolErrorFunction|None=default_tool_error_function,)->list[Tool]:"""Get all function tools from a single MCP server."""withmcp_tools_span(server=server.name)asspan:tools=awaitserver.list_tools(run_context,agent)span.span_data.result=[tool.namefortoolintools]return[cls.to_function_tool(tool,server,convert_schemas_to_strict,agent,failure_error_function=failure_error_function,)fortoolintools]

to_function_toolclassmethod

to_function_tool(tool:Tool,server:MCPServer,convert_schemas_to_strict:bool,agent:AgentBase|None=None,failure_error_function:ToolErrorFunction|None=default_tool_error_function,)->FunctionTool

Convert an MCP tool to an Agents SDK function tool.

Theagent parameter is optional for backward compatibility with oldercall sites that usedMCPUtil.to_function_tool(tool, server, strict).When omitted, this helper preserves the historical behavior and leavesneeds_approval disabled.

Source code insrc/agents/mcp/util.py
@classmethoddefto_function_tool(cls,tool:MCPTool,server:MCPServer,convert_schemas_to_strict:bool,agent:AgentBase|None=None,failure_error_function:ToolErrorFunction|None=default_tool_error_function,)->FunctionTool:"""Convert an MCP tool to an Agents SDK function tool.    The ``agent`` parameter is optional for backward compatibility with older    call sites that used ``MCPUtil.to_function_tool(tool, server, strict)``.    When omitted, this helper preserves the historical behavior and leaves    ``needs_approval`` disabled.    """invoke_func_impl=functools.partial(cls.invoke_mcp_tool,server,tool)effective_failure_error_function=server._get_failure_error_function(failure_error_function)schema,is_strict=tool.inputSchema,False# MCP spec doesn't require the inputSchema to have `properties`, but OpenAI spec does.if"properties"notinschema:schema["properties"]={}ifconvert_schemas_to_strict:try:schema=ensure_strict_json_schema(schema)is_strict=TrueexceptExceptionase:logger.info(f"Error converting MCP schema to strict mode:{e}")# Wrap the invoke function with error handling, similar to regular function tools.# This ensures that MCP tool errors (like timeouts) are handled gracefully instead# of halting the entire agent flow.asyncdefinvoke_func(ctx:ToolContext[Any],input_json:str)->ToolOutput:try:returnawaitinvoke_func_impl(ctx,input_json)exceptExceptionase:ifeffective_failure_error_functionisNone:raise# Use configured error handling function to convert exception to error message.result=effective_failure_error_function(ctx,e)ifinspect.isawaitable(result):result=awaitresult# Attach error to tracing span._error_tracing.attach_error_to_current_span(SpanError(message="Error running tool (non-fatal)",data={"tool_name":tool.name,"error":str(e),},))# Log the error.if_debug.DONT_LOG_TOOL_DATA:logger.debug(f"MCP tool{tool.name} failed")else:logger.error(f"MCP tool{tool.name} failed:{input_json}{e}",exc_info=e,)returnresultneeds_approval:(bool|Callable[[RunContextWrapper[Any],dict[str,Any],str],Awaitable[bool]])=server._get_needs_approval_for_tool(tool,agent)returnFunctionTool(name=tool.name,description=tool.descriptionor"",params_json_schema=schema,on_invoke_tool=invoke_func,strict_json_schema=is_strict,needs_approval=needs_approval,)

invoke_mcp_toolasyncclassmethod

invoke_mcp_tool(server:MCPServer,tool:Tool,context:RunContextWrapper[Any],input_json:str,*,meta:dict[str,Any]|None=None,)->ToolOutput

Invoke an MCP tool and return the result as ToolOutput.

Source code insrc/agents/mcp/util.py
@classmethodasyncdefinvoke_mcp_tool(cls,server:MCPServer,tool:MCPTool,context:RunContextWrapper[Any],input_json:str,*,meta:dict[str,Any]|None=None,)->ToolOutput:"""Invoke an MCP tool and return the result as ToolOutput."""try:json_data:dict[str,Any]=json.loads(input_json)ifinput_jsonelse{}exceptExceptionase:if_debug.DONT_LOG_TOOL_DATA:logger.debug(f"Invalid JSON input for tool{tool.name}")else:logger.debug(f"Invalid JSON input for tool{tool.name}:{input_json}")raiseModelBehaviorError(f"Invalid JSON input for tool{tool.name}:{input_json}")fromeif_debug.DONT_LOG_TOOL_DATA:logger.debug(f"Invoking MCP tool{tool.name}")else:logger.debug(f"Invoking MCP tool{tool.name} with input{input_json}")try:resolved_meta=awaitcls._resolve_meta(server,context,tool.name,json_data)merged_meta=cls._merge_mcp_meta(resolved_meta,meta)ifmerged_metaisNone:result=awaitserver.call_tool(tool.name,json_data)else:result=awaitserver.call_tool(tool.name,json_data,meta=merged_meta)exceptUserError:# Re-raise UserError as-is (it already has a good message)raiseexceptExceptionase:logger.error(f"Error invoking MCP tool{tool.name} on server '{server.name}':{e}")raiseAgentsException(f"Error invoking MCP tool{tool.name} on server '{server.name}':{e}")fromeif_debug.DONT_LOG_TOOL_DATA:logger.debug(f"MCP tool{tool.name} completed.")else:logger.debug(f"MCP tool{tool.name} returned{result}")# If structured content is requested and available, use it exclusivelytool_output:ToolOutputifserver.use_structured_contentandresult.structuredContent:tool_output=json.dumps(result.structuredContent)else:tool_output_list:list[ToolOutputItem]=[]foriteminresult.content:ifitem.type=="text":tool_output_list.append(ToolOutputTextDict(type="text",text=item.text))elifitem.type=="image":tool_output_list.append(ToolOutputImageDict(type="image",image_url=f"data:{item.mimeType};base64,{item.data}"))else:# Fall back to regular text contenttool_output_list.append(ToolOutputTextDict(type="text",text=str(item.model_dump(mode="json"))))iflen(tool_output_list)==1:tool_output=tool_output_list[0]else:tool_output=tool_output_listcurrent_span=get_current_span()ifcurrent_span:ifisinstance(current_span.span_data,FunctionSpanData):current_span.span_data.output=tool_outputcurrent_span.span_data.mcp_data={"server":server.name,}else:logger.warning(f"Current span is not a FunctionSpanData, skipping tool output:{current_span}")returntool_output

create_static_tool_filter

create_static_tool_filter(allowed_tool_names:list[str]|None=None,blocked_tool_names:list[str]|None=None,)->ToolFilterStatic|None

Create a static tool filter from allowlist and blocklist parameters.

This is a convenience function for creating a ToolFilterStatic.

Parameters:

NameTypeDescriptionDefault
allowed_tool_nameslist[str] | None

Optional list of tool names to allow (whitelist).

None
blocked_tool_nameslist[str] | None

Optional list of tool names to exclude (blacklist).

None

Returns:

TypeDescription
ToolFilterStatic | None

A ToolFilterStatic if any filtering is specified, None otherwise.

Source code insrc/agents/mcp/util.py
defcreate_static_tool_filter(allowed_tool_names:list[str]|None=None,blocked_tool_names:list[str]|None=None,)->ToolFilterStatic|None:"""Create a static tool filter from allowlist and blocklist parameters.    This is a convenience function for creating a ToolFilterStatic.    Args:        allowed_tool_names: Optional list of tool names to allow (whitelist).        blocked_tool_names: Optional list of tool names to exclude (blacklist).    Returns:        A ToolFilterStatic if any filtering is specified, None otherwise.    """ifallowed_tool_namesisNoneandblocked_tool_namesisNone:returnNonefilter_dict:ToolFilterStatic={}ifallowed_tool_namesisnotNone:filter_dict["allowed_tool_names"]=allowed_tool_namesifblocked_tool_namesisnotNone:filter_dict["blocked_tool_names"]=blocked_tool_namesreturnfilter_dict

[8]ページ先頭

©2009-2026 Movatter.jp