Skip to content
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
2 changes: 2 additions & 0 deletions src/agents/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,7 @@
RunConfig,
Runner,
ToolCallHookContext,
ToolDeclaration,
ToolErrorFormatter,
ToolErrorFormatterArgs,
ToolExecutionConfig,
Expand Down Expand Up @@ -499,6 +500,7 @@ def enable_verbose_stdout_logging() -> None:
"ReasoningItemIdPolicy",
"ToolExecutionConfig",
"ToolCallHookContext",
"ToolDeclaration",
"ToolErrorFormatter",
"ToolErrorFormatterArgs",
"ToolNotFoundBehavior",
Expand Down
9 changes: 2 additions & 7 deletions src/agents/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@
ToolOriginType,
_build_handled_function_tool_error_handler,
_build_wrapped_function_tool,
_function_tool_enabled,
_log_function_tool_invocation,
_parse_function_tool_json_input,
default_tool_error_function,
Expand Down Expand Up @@ -303,13 +304,7 @@ async def _check_tool_enabled(tool: Tool) -> bool:
if not isinstance(tool, FunctionTool):
return True

attr = tool.is_enabled
if isinstance(attr, bool):
return attr
res = attr(run_context, get_public_agent(self))
if inspect.isawaitable(res):
return bool(await res)
return bool(res)
return await _function_tool_enabled(tool, run_context, self)

results = await gather_with_cancel(*(_check_tool_enabled(t) for t in tools))
enabled: list[Tool] = [t for t, ok in zip(tools, results, strict=False) if ok]
Expand Down
174 changes: 88 additions & 86 deletions src/agents/mcp/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -841,6 +841,94 @@ def _is_tool_list_schema(value: object) -> bool:

return _to_bool(require_approval, location="require_approval")

tool_filter: ToolFilter = None

async def _apply_tool_filter(
self,
tools: list[MCPTool],
run_context: RunContextWrapper[Any] | None = None,
agent: AgentBase | None = None,
) -> list[MCPTool]:
"""Apply the tool filter to the list of tools."""
if self.tool_filter is None:
return tools

# Handle static tool filter
if isinstance(self.tool_filter, dict):
return self._apply_static_tool_filter(tools, self.tool_filter)

# Handle callable tool filter (dynamic filter)
else:
if run_context is None or agent is None:
raise UserError("run_context and agent are required for dynamic tool filtering")
return await self._apply_dynamic_tool_filter(tools, run_context, agent)

def _apply_static_tool_filter(
self, tools: list[MCPTool], static_filter: ToolFilterStatic
) -> list[MCPTool]:
"""Apply static tool filtering based on allowlist and blocklist."""
filtered_tools = tools

# Apply allowed_tool_names filter (whitelist)
if "allowed_tool_names" in static_filter:
allowed_names = static_filter["allowed_tool_names"]
filtered_tools = [t for t in filtered_tools if t.name in allowed_names]

# Apply blocked_tool_names filter (blacklist)
if "blocked_tool_names" in static_filter:
blocked_names = static_filter["blocked_tool_names"]
filtered_tools = [t for t in filtered_tools if t.name not in blocked_names]

return filtered_tools

async def _apply_dynamic_tool_filter(
self,
tools: list[MCPTool],
run_context: RunContextWrapper[Any],
agent: AgentBase,
) -> list[MCPTool]:
"""Apply dynamic tool filtering using a callable filter function."""

# Ensure we have a callable filter
if not callable(self.tool_filter):
raise ValueError("Tool filter must be callable for dynamic filtering")
tool_filter_func = self.tool_filter

# Create filter context
filter_context = ToolFilterContext(
run_context=run_context,
agent=agent,
server_name=self.name,
)

filtered_tools = []
for tool, detached in zip(tools, _snapshot_tools(tools), strict=True):
try:
# Inspect a detached copy so a mutating filter cannot corrupt the cache.
result = tool_filter_func(filter_context, detached)

if inspect.isawaitable(result):
should_include = await result
else:
should_include = result

if should_include:
filtered_tools.append(tool)
except Exception as e:
if _debug.DONT_LOG_TOOL_DATA:
message = "Error applying MCP tool filter"
else:
server_name = get_mcp_server_log_name(self.name)
message = (
f"Error applying MCP tool filter to tool '{tool.name}' "
f"on server '{server_name}'"
)
log_tool_action_error(logger, message, e)
# On error, exclude the tool for safety
continue

return filtered_tools

def _get_needs_approval_for_tool(
self,
tool: MCPTool,
Expand Down Expand Up @@ -1038,92 +1126,6 @@ async def _list_prompts_page(
),
)

async def _apply_tool_filter(
self,
tools: list[MCPTool],
run_context: RunContextWrapper[Any] | None = None,
agent: AgentBase | None = None,
) -> list[MCPTool]:
"""Apply the tool filter to the list of tools."""
if self.tool_filter is None:
return tools

# Handle static tool filter
if isinstance(self.tool_filter, dict):
return self._apply_static_tool_filter(tools, self.tool_filter)

# Handle callable tool filter (dynamic filter)
else:
if run_context is None or agent is None:
raise UserError("run_context and agent are required for dynamic tool filtering")
return await self._apply_dynamic_tool_filter(tools, run_context, agent)

def _apply_static_tool_filter(
self, tools: list[MCPTool], static_filter: ToolFilterStatic
) -> list[MCPTool]:
"""Apply static tool filtering based on allowlist and blocklist."""
filtered_tools = tools

# Apply allowed_tool_names filter (whitelist)
if "allowed_tool_names" in static_filter:
allowed_names = static_filter["allowed_tool_names"]
filtered_tools = [t for t in filtered_tools if t.name in allowed_names]

# Apply blocked_tool_names filter (blacklist)
if "blocked_tool_names" in static_filter:
blocked_names = static_filter["blocked_tool_names"]
filtered_tools = [t for t in filtered_tools if t.name not in blocked_names]

return filtered_tools

async def _apply_dynamic_tool_filter(
self,
tools: list[MCPTool],
run_context: RunContextWrapper[Any],
agent: AgentBase,
) -> list[MCPTool]:
"""Apply dynamic tool filtering using a callable filter function."""

# Ensure we have a callable filter
if not callable(self.tool_filter):
raise ValueError("Tool filter must be callable for dynamic filtering")
tool_filter_func = self.tool_filter

# Create filter context
filter_context = ToolFilterContext(
run_context=run_context,
agent=agent,
server_name=self.name,
)

filtered_tools = []
for tool, detached in zip(tools, _snapshot_tools(tools), strict=True):
try:
# Inspect a detached copy so a mutating filter cannot corrupt the cache.
result = tool_filter_func(filter_context, detached)

if inspect.isawaitable(result):
should_include = await result
else:
should_include = result

if should_include:
filtered_tools.append(tool)
except Exception as e:
if _debug.DONT_LOG_TOOL_DATA:
message = "Error applying MCP tool filter"
else:
server_name = get_mcp_server_log_name(self.name)
message = (
f"Error applying MCP tool filter to tool '{tool.name}' "
f"on server '{server_name}'"
)
log_tool_action_error(logger, message, e)
# On error, exclude the tool for safety
continue

return filtered_tools

@abc.abstractmethod
def create_streams(
self,
Expand Down
39 changes: 33 additions & 6 deletions src/agents/mcp/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
ToolOutputTextDict,
_build_handled_function_tool_error_handler,
_build_wrapped_function_tool,
_ToolEligibilityError,
default_tool_error_function,
)
from ..tool_context import ToolContext
Expand All @@ -54,7 +55,7 @@
ToolOutput = Union[str, ToolOutputItem, list[ToolOutputItem]] # noqa: UP007

if TYPE_CHECKING:
from mcp.types import Tool as MCPTool
from mcp.types import CallToolResult, Tool as MCPTool

from ..agent import AgentBase
from .server import MCPServer
Expand Down Expand Up @@ -716,19 +717,45 @@ async def invoke_mcp_tool(
f"Invalid JSON input for tool {tool_name_for_display}: expected a JSON object"
)

async def call_peer() -> CallToolResult:
if merged_meta is None:
return await server.call_tool(tool.name, json_data)
return await server.call_tool(tool.name, json_data, meta=merged_meta)

invoke = call_peer
if _debug.DONT_LOG_TOOL_DATA:
logger.debug("Invoking MCP tool")
else:
logger.debug("Invoking MCP tool %s with input %s", tool_name_for_display, input_json)

try:
if (
isinstance(context, ToolContext)
and (record := context._tool_invocations.get(context.tool_call_id)) is not None
and record.declaration is not None
):
binding = record.declaration

async def check_and_call() -> CallToolResult:
# Check inside the scheduled task, after metadata resolution.
try:
if context.run_config is None or binding.server is not server:
raise UserError("MCP recipient or policy changed.")
if not await server._apply_tool_filter([tool], context, binding.agent):
raise UserError("MCP tool filter refused the call.")
await binding.check(context, context.run_config)
if tool.name != binding.view.mcp_tool_name:
raise UserError("MCP tool name changed.")
except Exception as error:
raise _ToolEligibilityError(
"Prepared MCP tool is no longer eligible."
) from error
return await call_peer()

invoke = check_and_call
resolved_meta = await cls._resolve_meta(server, context, tool.name, json_data)
merged_meta = cls._merge_mcp_meta(resolved_meta, meta)
call_task = asyncio.create_task(
server.call_tool(tool.name, json_data)
if merged_meta is None
else server.call_tool(tool.name, json_data, meta=merged_meta)
)
call_task = asyncio.create_task(invoke())
try:
done, _ = await asyncio.wait({call_task}, return_when=asyncio.FIRST_COMPLETED)
finished_task = done.pop()
Expand Down
11 changes: 5 additions & 6 deletions src/agents/models/openai_responses.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@
Tool,
ToolSearchTool,
WebSearchTool,
_builtin_tool_choice_name,
has_required_tool_search_surface,
validate_responses_programmatic_tool_calling_configuration,
validate_responses_tool_search_configuration,
Expand Down Expand Up @@ -1962,11 +1963,9 @@ def convert_tool_choice(
return "auto"
elif tool_choice == "none":
return "none"
elif tool_choice in {
"computer",
"computer_use",
"computer_use_preview",
} and cls._has_computer_tool(tools):
elif _builtin_tool_choice_name(
tool_choice
) == "computer_use_preview" and cls._has_computer_tool(tools):
return cls._convert_builtin_computer_tool_choice(
tool_choice=tool_choice,
model=model,
Expand All @@ -1990,7 +1989,7 @@ def convert_tool_choice(
"web_search_preview",
}:
# WebSearchTool advertises web_search for both search selectors.
hosted_type = "web_search" if tool_choice == "web_search_preview" else tool_choice
hosted_type = _builtin_tool_choice_name(tool_choice)
if not any(tool["type"] == hosted_type for tool in tool_params) and any(
tool["type"] == "function"
and tool["name"] == tool_choice
Expand Down
5 changes: 5 additions & 0 deletions src/agents/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@
RunConfig,
RunOptions,
ToolCallHookContext,
ToolDeclaration,
ToolErrorFormatter,
ToolErrorFormatterArgs,
ToolExecutionConfig,
Expand Down Expand Up @@ -166,6 +167,7 @@
take_held_session_write,
update_run_state_after_resume,
)
from .run_internal.tool_declarations import validate_resume_policy
from .run_internal.tool_use_tracker import (
AgentToolUseTracker,
hydrate_tool_use_tracker,
Expand Down Expand Up @@ -210,6 +212,7 @@
"ReasoningItemIdPolicy",
"ToolExecutionConfig",
"ToolCallHookContext",
"ToolDeclaration",
"ToolErrorFormatter",
"ToolErrorFormatterArgs",
"ToolNotFoundBehavior",
Expand Down Expand Up @@ -699,6 +702,7 @@ async def _run_impl(
context=context,
)
context_wrapper._resolve_function_approval_owners(starting_agent)
validate_resume_policy(run_state, context_wrapper, run_config)
context = context_wrapper.context

reject_unrecoverable_terminal_state(run_state)
Expand Down Expand Up @@ -2725,6 +2729,7 @@ def run_streamed(
context=context,
)
context_wrapper._resolve_function_approval_owners(starting_agent)
validate_resume_policy(run_state, context_wrapper, run_config)

# Override max_turns with the state's max_turns to preserve it across resumption
max_turns = run_state._max_turns
Expand Down
Loading
Loading