Movatterモバイル変換


[0]ホーム

URL:


Skip to content

MCP Util

ToolFilterCallablemodule-attribute

ToolFilterCallable=Callable[["ToolFilterContext","MCPTool"],MaybeAwaitable[bool]]

A function that determines whether a tool should be available.

Parameters:

NameTypeDescriptionDefault
context

The context information including run context, agent, and server name.

required
tool

The MCP tool to filter.

required

Returns:

TypeDescription

Whether the tool should be available (True) or filtered out (False).

ToolFiltermodule-attribute

ToolFilter=Union[ToolFilterCallable,ToolFilterStatic,None]

A tool filter that can be either a function, static configuration, or None (no filtering).

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:Optional[dict[str,str]]=None,timeout:Optional[httpx.Timeout]=None,auth:Optional[httpx.Auth]=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.

MCPUtil

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

Source code insrc/agents/mcp/util.py
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",)->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)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",)->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)fortoolintools]@classmethoddefto_function_tool(cls,tool:"MCPTool",server:"MCPServer",convert_schemas_to_strict:bool)->FunctionTool:"""Convert an MCP tool to an Agents SDK function tool."""invoke_func=functools.partial(cls.invoke_mcp_tool,server,tool)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}")returnFunctionTool(name=tool.name,description=tool.descriptionor"",params_json_schema=schema,on_invoke_tool=invoke_func,strict_json_schema=is_strict,)@classmethodasyncdefinvoke_mcp_tool(cls,server:"MCPServer",tool:"MCPTool",context:RunContextWrapper[Any],input_json:str)->str:"""Invoke an MCP tool and return the result as a string."""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:result=awaitserver.call_tool(tool.name,json_data)exceptExceptionase:logger.error(f"Error invoking MCP tool{tool.name}:{e}")raiseAgentsException(f"Error invoking MCP tool{tool.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 exclusivelyifserver.use_structured_contentandresult.structuredContent:tool_output=json.dumps(result.structuredContent)else:# Fall back to regular text content processing# The MCP tool result is a list of content items, whereas OpenAI tool# outputs are a single string. We'll try to convert.iflen(result.content)==1:tool_output=result.content[0].model_dump_json()eliflen(result.content)>1:tool_results=[item.model_dump(mode="json")foriteminresult.content]tool_output=json.dumps(tool_results)else:# Empty content is a valid result (e.g., "no results found")tool_output="[]"current_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,)->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",)->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)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,)->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",)->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)fortoolintools]

to_function_toolclassmethod

to_function_tool(tool:Tool,server:MCPServer,convert_schemas_to_strict:bool,)->FunctionTool

Convert an MCP tool to an Agents SDK function tool.

Source code insrc/agents/mcp/util.py
@classmethoddefto_function_tool(cls,tool:"MCPTool",server:"MCPServer",convert_schemas_to_strict:bool)->FunctionTool:"""Convert an MCP tool to an Agents SDK function tool."""invoke_func=functools.partial(cls.invoke_mcp_tool,server,tool)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}")returnFunctionTool(name=tool.name,description=tool.descriptionor"",params_json_schema=schema,on_invoke_tool=invoke_func,strict_json_schema=is_strict,)

invoke_mcp_toolasyncclassmethod

invoke_mcp_tool(server:MCPServer,tool:Tool,context:RunContextWrapper[Any],input_json:str,)->str

Invoke an MCP tool and return the result as a string.

Source code insrc/agents/mcp/util.py
@classmethodasyncdefinvoke_mcp_tool(cls,server:"MCPServer",tool:"MCPTool",context:RunContextWrapper[Any],input_json:str)->str:"""Invoke an MCP tool and return the result as a string."""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:result=awaitserver.call_tool(tool.name,json_data)exceptExceptionase:logger.error(f"Error invoking MCP tool{tool.name}:{e}")raiseAgentsException(f"Error invoking MCP tool{tool.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 exclusivelyifserver.use_structured_contentandresult.structuredContent:tool_output=json.dumps(result.structuredContent)else:# Fall back to regular text content processing# The MCP tool result is a list of content items, whereas OpenAI tool# outputs are a single string. We'll try to convert.iflen(result.content)==1:tool_output=result.content[0].model_dump_json()eliflen(result.content)>1:tool_results=[item.model_dump(mode="json")foriteminresult.content]tool_output=json.dumps(tool_results)else:# Empty content is a valid result (e.g., "no results found")tool_output="[]"current_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:Optional[list[str]]=None,blocked_tool_names:Optional[list[str]]=None,)->Optional[ToolFilterStatic]

Create a static tool filter from allowlist and blocklist parameters.

This is a convenience function for creating a ToolFilterStatic.

Parameters:

NameTypeDescriptionDefault
allowed_tool_namesOptional[list[str]]

Optional list of tool names to allow (whitelist).

None
blocked_tool_namesOptional[list[str]]

Optional list of tool names to exclude (blacklist).

None

Returns:

TypeDescription
Optional[ToolFilterStatic]

A ToolFilterStatic if any filtering is specified, None otherwise.

Source code insrc/agents/mcp/util.py
defcreate_static_tool_filter(allowed_tool_names:Optional[list[str]]=None,blocked_tool_names:Optional[list[str]]=None,)->Optional[ToolFilterStatic]:"""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-2025 Movatter.jp