diff --git a/src/agents/__init__.py b/src/agents/__init__.py index ae226a9f56..2b5941d41e 100644 --- a/src/agents/__init__.py +++ b/src/agents/__init__.py @@ -129,6 +129,7 @@ ToolNotFoundBehavior, ) from .run_budget import RunBudget, RunBudgetError +from .run_config import MCPTextTransform from .run_context import AgentHookContext, RunContextWrapper, TContext from .run_error_handlers import ( RunErrorData, @@ -503,6 +504,7 @@ def enable_verbose_stdout_logging() -> None: "OutputGuardrailBlockedMessageFormatter", "ToolNameCollisionPolicy", "ReasoningItemIdPolicy", + "MCPTextTransform", "ToolExecutionConfig", "ToolCallHookContext", "ToolDeclaration", diff --git a/src/agents/mcp/server.py b/src/agents/mcp/server.py index f645a87018..c2fb879978 100644 --- a/src/agents/mcp/server.py +++ b/src/agents/mcp/server.py @@ -74,6 +74,7 @@ ToolFilter, ToolFilterContext, ToolFilterStatic, + _FilteredTools, ) @@ -1561,14 +1562,12 @@ async def fetch_pages() -> Literal["complete", "repeated_cursor", "page_limit"]: self._cache_dirty = False self._tools_last_published_refresh_sequence = refresh_sequence - # Filter tools based on tool_filter - filtered_tools = tools + # Snapshot even filtered schemas to isolate callers from the cache. if self.tool_filter is not None: - filtered_tools = await self._apply_tool_filter(filtered_tools, run_context, agent) - # Always deep-copy tools. Even when filters build a new list, the Tool - # objects (and nested input schemas) would otherwise remain shared with - # the cache and let callers corrupt required-parameter validation. - return _snapshot_tools(filtered_tools) + names = frozenset(tool.name for tool in tools) + filtered_tools = await self._apply_tool_filter(tools, run_context, agent) + return _FilteredTools(_snapshot_tools(filtered_tools), names) + return _snapshot_tools(tools) except mcp_compat.HTTP_STATUS_ERROR_TYPES as e: status_code = http_status_code(e) transport_error = UserError( diff --git a/src/agents/mcp/util.py b/src/agents/mcp/util.py index e7811cc4e1..8d043b79a1 100644 --- a/src/agents/mcp/util.py +++ b/src/agents/mcp/util.py @@ -6,6 +6,7 @@ import hashlib import inspect import json +import weakref from collections import Counter from collections.abc import Awaitable, Callable, Mapping from dataclasses import dataclass @@ -62,6 +63,14 @@ from .server import MCPServer +class _FilteredTools(list["MCPTool"]): + """Visible tools with raw-name evidence from the same complete discovery.""" + + def __init__(self, tools: list[MCPTool], names: frozenset[str]) -> None: + super().__init__(tools) + self._raw_names = names + + _MCP_FUNCTION_TOOL_NAME_MAX_LENGTH = 64 _MCP_FUNCTION_TOOL_HASH_LENGTH = 8 @@ -386,7 +395,14 @@ def _convert_mcp_tools_to_function_tools( ) for index, tool in enumerate(tools) ] + # Share one snapshot from this discovery, before agent-level omissions. + names: frozenset[str] | None + if isinstance(tools, _FilteredTools): + names = tools._raw_names + else: + names = frozenset(t.name for t in tools) if server.tool_filter is None else None for function_tool in function_tools: + function_tool._mcp_raw_names = names assert function_tool._mcp_tool_binding is not None server_name, raw_tool_name, _ = function_tool._mcp_tool_binding function_tool._mcp_tool_binding = (server_name, raw_tool_name, server_index) @@ -611,6 +627,7 @@ def to_function_tool( mcp_server_name=get_mcp_server_log_name(server.name), ), ) + function_tool._mcp_server_ref = weakref.ref(server) function_tool._mcp_annotations = copy.deepcopy(tool.annotations) function_tool._mcp_tool_binding = (get_mcp_server_log_name(server.name), tool.name, None) require_clean_function(function_tool) @@ -764,6 +781,10 @@ async def check_and_call() -> CallToolResult: invoke = check_and_call resolved_meta = await cls._resolve_meta(server, context, tool.name, json_data) + if isinstance(context, ToolContext) and context._edit_text is not None: + from ..tool import _protect_selected_task + + invoke = functools.partial(_protect_selected_task, invoke) merged_meta = cls._merge_mcp_meta(resolved_meta, meta) call_task = asyncio.create_task(invoke()) try: @@ -789,6 +810,8 @@ async def check_and_call() -> CallToolResult: # will format them into model-visible tool errors when appropriate. raise except Exception as e: + if isinstance(context, ToolContext) and context._edit_text is not None: + raise if isinstance(e, MCPError): # An MCP-level error (e.g. upstream HTTP 4xx/5xx, tool not found, etc.) # is not a programming error – re-raise so the FunctionTool failure @@ -819,6 +842,13 @@ async def check_and_call() -> CallToolResult: f"'{get_mcp_server_log_name(server.name)}': {e}" ) from e + if isinstance(context, ToolContext) and context._edit_text is not None: + from ..run_internal.tool_text import edit_mcp_result + + result = await edit_mcp_result( + context._edit_text, result, server.use_structured_content + ) + if _debug.DONT_LOG_TOOL_DATA: logger.debug("MCP tool completed.") else: diff --git a/src/agents/memory/resumable_session.py b/src/agents/memory/resumable_session.py index 1f24e5421e..72992a24a9 100644 --- a/src/agents/memory/resumable_session.py +++ b/src/agents/memory/resumable_session.py @@ -336,6 +336,7 @@ async def _begin_run( _check_approved_functions, _check_workspace_approvals, ) + from ..run_internal.tool_text import validate_pending_text_transforms processed = input._last_processed_response if processed is not None and processed.native_approvals: @@ -346,6 +347,7 @@ async def _begin_run( _check_workspace_approvals(pending, tool_hooks.agent, processed) if tool_not_found_behavior == "raise_error": _check_approved_functions(pending, tool_hooks.agent, tool_hooks.context) + await validate_pending_text_transforms(input, tool_hooks.settings, tool_hooks.context) active = self._checkpoint.model_copy( update={ "version": 2 if current_redactor() is not None else self._checkpoint.version, diff --git a/src/agents/run.py b/src/agents/run.py index 5c35a7a50a..e5fcd69406 100644 --- a/src/agents/run.py +++ b/src/agents/run.py @@ -54,11 +54,12 @@ from .memory.resumable_session import ResumableSession from .models._run_context import ModelToolHooks from .result import RunResult, RunResultStreaming -from .run_budget import _check_resume, _prepare_budget +from .run_budget import _prepare_budget from .run_config import ( DEFAULT_MAX_TURNS, CallModelData, CallModelInputFilter, + MCPTextTransform, ModelInputData, OutputGuardrailBlockedMessageArgs, OutputGuardrailBlockedMessageFormatter, @@ -97,6 +98,7 @@ update_run_state_for_interruption, usage_delta, validate_output_guardrails_with_server_managed_conversation, + validate_resumed_agent_tools, validate_session_conversation_settings, ) from .run_internal.agent_tool_configuration import agent_tool_configuration_run @@ -223,6 +225,7 @@ "OutputGuardrailBlockedMessageFormatter", "ToolNameCollisionPolicy", "ReasoningItemIdPolicy", + "MCPTextTransform", "ToolExecutionConfig", "ToolCallHookContext", "ToolDeclaration", @@ -768,7 +771,13 @@ async def _run_impl( ) context_wrapper._resolve_function_approval_owners(starting_agent) validate_resume_policy(run_state, context_wrapper, run_config) - await _check_resume(run_state, run_config.budget, context_wrapper) + await validate_resumed_agent_tools( + run_state, + run_config.budget, + context_wrapper, + run_config.tool_execution, + manual_root=not isinstance(session, ResumableRun), + ) context = context_wrapper.context reject_unrecoverable_terminal_state(run_state) @@ -3042,7 +3051,13 @@ async def run_loop() -> None: ): try: if is_resumed_state and run_state is not None: - await _check_resume(run_state, run_config.budget, context_wrapper) + await validate_resumed_agent_tools( + run_state, + run_config.budget, + context_wrapper, + run_config.tool_execution, + manual_root=not isinstance(session, ResumableRun), + ) if isinstance(session, ResumableRun): await session.begin( input, diff --git a/src/agents/run_budget.py b/src/agents/run_budget.py index 73c41783a7..6e66ef2489 100644 --- a/src/agents/run_budget.py +++ b/src/agents/run_budget.py @@ -2,7 +2,6 @@ from __future__ import annotations -import copy from dataclasses import dataclass from typing import TYPE_CHECKING, Any, Literal @@ -22,7 +21,6 @@ from .models.interface import Model from .result import RunResultStreaming from .run_config import RunConfig - from .run_context import RunContextWrapper from .run_state import RunState from .tool import Tool @@ -181,11 +179,10 @@ def _check_model(model: object) -> None: raise UserError("RunBudget cannot enforce native sampling limits with CodexProvider.") -def _tool_budget(tool: Tool) -> RunBudget | None: +def _tool_config(tool: Tool) -> RunConfig | None: invoker = getattr(tool, "on_invoke_tool", None) impl = getattr(invoker, "_invoke_tool_impl", None) - config = getattr(impl, "__agents_run_config__", None) - return config.budget if config is not None else None + return getattr(impl, "__agents_run_config__", None) async def _admit( @@ -230,58 +227,11 @@ async def _admit( raise -async def _check_resume( - state: RunState[Any], limits: RunBudget | None, context: RunContextWrapper[Any] -) -> bool: - """Validate pending policies and report whether this subtree owns a budget.""" - from ._tool_identity import get_function_tool_lookup_key_for_call, get_function_tool_lookup_keys - from .agent_tool_state import get_agent_tool_resume_state, peek_agent_tool_run_result - from .tool import FunctionTool, _function_tool_enabled - +def _check_resumed_budget(state: RunState[Any], limits: RunBudget | None) -> bool: saved = state._context._budget if state._context is not None else None if (saved.limits if saved is not None else None) != limits: raise UserError("Resume requires the same RunBudget limits and missing_usage policy.") - budgeted = saved is not None - for action in getattr(state._last_processed_response, "functions", ()): - if not action.function_tool._is_agent_tool: - continue - result = peek_agent_tool_run_result( - action.tool_call, scope_id=state._agent_tool_state_scope_id - ) - child = get_agent_tool_resume_state(result) - if child is None and result is not None and result.interruptions: - child = result.to_state() - if child is None: - continue - # Turn resolution can rebind a queued call after load_state(). Check - # the current qualified binding and grant only for required branches. - key = get_function_tool_lookup_key_for_call(action.tool_call) - tools = state._current_agent.tools if state._current_agent is not None else [] - bindings = [ - tool - for tool in tools - if isinstance(tool, FunctionTool) and key in get_function_tool_lookup_keys(tool) - ] - policies = (_tool_budget(tool) for tool in bindings) - policy = next((value for value in policies if value is not None), None) - if await _check_resume(child, policy, context): - owner = state._context - if owner is not None and owner is not context: - # Agent.as_tool keeps the nested wrapper but forwards application - # context and usage. Leave the saved state untouched on refusal. - owner = copy.copy(owner) - owner.context = context.context - owner.usage = context.usage - if ( - len(bindings) != 1 - or bindings[0]._agent_instance is not action.function_tool._agent_instance - or owner is None - or state._current_agent is None - or not await _function_tool_enabled(bindings[0], owner, state._current_agent) - ): - raise UserError("A pending RunBudget requires the same unique enabled agent tool.") - budgeted = True - return budgeted + return saved is not None def _prepare_budget( diff --git a/src/agents/run_config.py b/src/agents/run_config.py index b95367ce8b..a264e3e9e5 100644 --- a/src/agents/run_config.py +++ b/src/agents/run_config.py @@ -2,7 +2,7 @@ import inspect import os -from collections.abc import Awaitable, Callable +from collections.abc import Awaitable, Callable, Sequence from dataclasses import dataclass, field from pathlib import PurePath from typing import TYPE_CHECKING, Any, Generic, Literal @@ -37,13 +37,17 @@ if TYPE_CHECKING: from .agent import Agent + from .mcp import MCPServer from .run_context import RunContextWrapper from .sandbox.manifest import Manifest from .sandbox.session.base_sandbox_session import BaseSandboxSession from .sandbox.session.sandbox_client import BaseSandboxClient from .sandbox.session.sandbox_session_state import SandboxSessionState from .sandbox.snapshot import SnapshotBase, SnapshotSpec - from .tool import NativeTool, Tool + from .tool import FunctionTool, NativeTool, Tool +else: + # Runtime config adapters must retain the registered instances. Validate them below. + FunctionTool = MCPServer = Any DEFAULT_MAX_TURNS = 10 @@ -159,6 +163,9 @@ class ToolCallHookContext(Generic[TContext]): The original text is available in the function's `ToolContext.tool_arguments`. """ + mcp_target: tuple[MCPServer, str] | None = field(default=None, kw_only=True, repr=False) + """Server and original tool name for a selected Runner MCP text transform.""" + @dataclass(frozen=True) class ToolDeclaration: @@ -171,6 +178,30 @@ class ToolDeclaration: mcp_tool_name: str | None = None +_TextEditor = Callable[ + [ToolCallHookContext[Any], tuple[str, ...]], Awaitable[list[str] | tuple[str, ...]] +] + + +@dataclass(frozen=True, kw_only=True) +class MCPTextTransform: + """Edit only text from a Runner MCP tool on the exact connected server object.""" + + server: MCPServer + tool_name: str + edit: _TextEditor + + def __post_init__(self) -> None: + from .mcp import MCPServer + + if not isinstance(self.server, MCPServer): + raise ValueError("MCPTextTransform requires an MCP server object, not a server name.") + if not isinstance(self.tool_name, str) or not self.tool_name.strip(): + raise ValueError("MCPTextTransform requires a nonblank raw tool name.") + if not callable(self.edit): + raise ValueError("MCPTextTransform requires an async editor.") + + @dataclass class ToolExecutionConfig: """Configure tool execution and run-wide preparation callbacks. @@ -180,6 +211,11 @@ class ToolExecutionConfig: return the original result or replacement text for the model. API-hosted tools execute outside the client hook lifecycle. + For Runner tools, use `tool_text_transforms` with `(report, edit_text)` for a + `FunctionTool` or `MCPTextTransform(server=peer, tool_name="lookup", edit=edit_text)` + for MCP. Use the server object and raw tool name. The async editor replaces + text parts and keeps the original media. + Supply the same callbacks when resuming a run in another process. """ @@ -255,9 +291,77 @@ async def prepare(ctx, declaration): Raw provider stream events and provider-managed history may contain the original proposal. """ + tool_text_transforms: Sequence[tuple[FunctionTool, _TextEditor] | MCPTextTransform] = field( + default=(), kw_only=True + ) + """Experimental. Edit selected Runner tool results before output hooks, traces and history. + + Register the exact function in the agent's tools or the MCP server and raw tool name. + For a namespace, use the tool returned by `tool_namespace`. Reuse that object. + If another local function has the same dispatch key (including namespace), or + another MCP server has the same name and raw tool name, the Runner raises + `UserError` before invoking it unless it has its own exact registration. + This applies across agents. The SDK compares URL-based server names without + credentials, query strings or fragments. Register the replacement server after + reconnecting. For MCP, a selector matching the exposed name + or an SDK-normalized or server-prefixed name requires an exact raw-name registration. For + example, register `read.report` even if the model sees `mcp_Reports__read_report`. + If a different raw tool is named `read_report`, register both to call both. + When configured, `RunConfig.redact_text` scrubs the edited text before validation. + If a registered raw name is absent from this server object's unfiltered + discovery, the Runner blocks calls on that server without an exact editor. + An exact editor takes precedence and may return its input unchanged. + A temporarily missing name can block other calls. Built-in clients check names before filtering. + Custom peers with filtered or missing catalogs may miss unrelated typos. If you add an + editor for a previously unselected MCP call on restore and no catalog is + available yet, an unknown raw name may fail only after the session claim. + + Here, `report` is the agent's `FunctionTool`, `server` is the object in + `agent.mcp_servers`, and `lookup` is the raw MCP tool name. + + ```python + from agents import MCPTextTransform, ToolExecutionConfig + + async def edit_text(call, texts): + return [text.replace("internal draft", "[hidden]") for text in texts] + + config = ToolExecutionConfig(tool_text_transforms=[ + (report, edit_text), + MCPTextTransform(server=server, tool_name="lookup", edit=edit_text), + ]) + ``` + + The editor receives a tuple of strings. Return a list or tuple of strings of the same + length, with one replacement per text slot in the original order. + Images and function file parts stay in place. A typed function result uses one JSON + slot. The caller receives the accepted JSON object as a dictionary. Unchanged text + keeps the serialized values. Changed JSON must validate against the declared type + and serialize back to the same values. Ignored extra top-level fields are dropped. + Bare output schemas and arbitrary Python objects are unsupported. + MCP supports text and image blocks. If the server prefers structured content and + returns a JSON object, even an empty one, its JSON replaces the + first text slot. Remaining text slots start empty. If needed, the SDK appends a + text slot. Extractors see the edited result without MCP metadata or fallback data. + + A tool failure, unsupported result, invalid edit or editor exception stops the run + without a successful output. Cancellation still cancels the call. Completed side + effects cannot be undone. Neither error formatters nor `prepare_tool_output` replace + a selected result. Other calls keep their usual behavior. + + The editor and retained media are trusted. A pending selected call requires + an exact registration on resume. After restoring state, register the current + tool or server object. Only the requirement is saved in the checkpoint. + This option does not intercept hosted or native tools, inputs or application logging. + """ + prepare_tool_output: Callable[[ToolCallHookContext[Any], Any], Awaitable[Any]] | None = None """Experimental. Return the tool result to use after the tool has executed. + A selected result editor replaces this callback even when it returns its input unchanged. + For Runner MCP tools, custom data extraction happens before this callback. Runner text + editors do not cover native MCP tools, even when the names match. Enforce mandatory + rules in every matching editor or at the source. + The runner awaits this callback before function-tool output guardrails and before building the tool-output item used for history and later model turns. `on_tool_end` observes the accepted result after that item is built. For native tools it observes the prepared value before Codex @@ -284,6 +388,39 @@ def __post_init__(self) -> None: raise ValueError("tool_execution.pre_approval_tool_input_guardrails must be a bool") if not isinstance(self.sdk_only_tool_hooks, bool): raise ValueError("tool_execution.sdk_only_tool_hooks must be a bool") + invalid = ( + "For tool_text_transforms, use (function_tool, edit_text) or " + "MCPTextTransform(server=peer, tool_name=raw_name, edit=edit_text) " + "with the MCP server object." + ) + try: + self.tool_text_transforms = tuple(self.tool_text_transforms) + except TypeError: + raise ValueError(invalid) from None + if self.tool_text_transforms: + from .tool import FunctionTool + + seen: set[tuple[int, str | None]] = set() + for entry in self.tool_text_transforms: + key: tuple[int, str | None] + if isinstance(entry, MCPTextTransform): + key = (id(entry.server), entry.tool_name) + elif isinstance(entry, tuple) and len(entry) == 2: + target, edit = entry + if ( + not isinstance(target, FunctionTool) + or target._is_agent_tool + or target._is_codex_tool + or target._mcp_tool_binding + or not callable(edit) + ): + raise ValueError(invalid) + key = (id(target), None) + else: + raise ValueError(invalid) + if key in seen: + raise ValueError("Each tool_text_transforms target requires one editor.") + seen.add(key) @dataclass @@ -812,6 +949,7 @@ def _coerce_run_config(value: RunConfig | dict[str, Any]) -> RunConfig: "SandboxArchiveLimits", "SandboxConcurrencyLimits", "SandboxRunConfig", + "MCPTextTransform", "ToolExecutionConfig", "ToolCallHookContext", "ToolDeclaration", diff --git a/src/agents/run_context.py b/src/agents/run_context.py index c2064604d5..6e5592aca6 100644 --- a/src/agents/run_context.py +++ b/src/agents/run_context.py @@ -157,6 +157,7 @@ class _ToolInvocationRecord: fingerprint: str executed: bool = False completed: bool = False + requires_text_transform: bool = field(default=False, kw_only=True) # The input admitted under this ID, paired with the digest of the original proposal. input_rewrite: tuple[str, dict[str, Any]] | None = None requires_declaration: bool = False @@ -1651,6 +1652,11 @@ def _rebuild_tool_invocations( ) if not isinstance(serialized_invocation, Mapping): raise validation_error_factory("RunState tool invocation must be a mapping.") + requires_edit = serialized_invocation.get("requires_text_transform", False) + if not isinstance(requires_edit, bool): + raise validation_error_factory( + "RunState tool text transform requirement is invalid." + ) invocation_type = serialized_invocation.get("type") approval_scope = serialized_invocation.get("approval_scope") fingerprint = serialized_invocation.get("fingerprint") @@ -1692,6 +1698,7 @@ def _rebuild_tool_invocations( invocation_type=invocation_type, approval_scope=approval_scope, fingerprint=fingerprint, + requires_text_transform=requires_edit, executed=executed, completed=completed, input_rewrite=input_rewrite, diff --git a/src/agents/run_internal/agent_runner_helpers.py b/src/agents/run_internal/agent_runner_helpers.py index 0da768da3a..425cee48ec 100644 --- a/src/agents/run_internal/agent_runner_helpers.py +++ b/src/agents/run_internal/agent_runner_helpers.py @@ -9,8 +9,13 @@ from openai.types.responses.response_usage import OutputTokensDetails from .._redaction import current_redactor +from .._tool_identity import get_function_tool_lookup_key_for_call, get_function_tool_lookup_keys from ..agent import Agent -from ..agent_tool_state import set_agent_tool_state_scope +from ..agent_tool_state import ( + get_agent_tool_resume_state, + peek_agent_tool_run_result, + set_agent_tool_state_scope, +) from ..exceptions import UserError from ..guardrail import InputGuardrailResult from ..items import ModelResponse, RunItem, ToolApprovalItem, TResponseInputItem @@ -18,9 +23,11 @@ from ..models.openai_agent_registration import add_openai_harness_id_to_metadata from ..models.openai_chatcompletions import OpenAIChatCompletionsModel from ..result import RunResult -from ..run_config import ReasoningItemIdPolicy, RunConfig +from ..run_budget import RunBudget, _check_resumed_budget, _tool_config +from ..run_config import ReasoningItemIdPolicy, RunConfig, ToolExecutionConfig from ..run_context import RunContextWrapper, TContext from ..run_state import RunState +from ..tool import FunctionTool, _unique_enabled_function from ..tool_guardrails import ToolInputGuardrailResult, ToolOutputGuardrailResult from ..tracing import Span from ..tracing.config import TracingConfig @@ -51,6 +58,7 @@ save_resumed_turn_items, take_held_session_write, ) +from .tool_text import validate_pending_text_transforms from .tool_use_tracker import AgentToolUseTracker, serialize_tool_use_tracker from .turn_preparation import get_model @@ -68,6 +76,7 @@ "get_unsent_tool_call_ids_for_interrupted_state", "input_guardrails_triggered", "validate_output_guardrails_with_server_managed_conversation", + "validate_resumed_agent_tools", "validate_session_conversation_settings", "resolve_trace_settings", "resolve_processed_response", @@ -368,6 +377,101 @@ def resolve_resumed_context( return run_state._context +async def validate_resumed_agent_tools( + state: RunState[Any], + limits: RunBudget | None, + context: RunContextWrapper[Any], + settings: ToolExecutionConfig | None, + *, + manual_root: bool = False, + delegate_replaced: bool = False, +) -> tuple[bool, bool]: + """Check required delegate bindings once for both budgets and text editors.""" + budgeted = _check_resumed_budget(state, limits) + edited = False + for action in getattr(state._last_processed_response, "functions", ()): + if not action.function_tool._is_agent_tool: + continue + result = peek_agent_tool_run_result( + action.tool_call, scope_id=state._agent_tool_state_scope_id + ) + child = get_agent_tool_resume_state(result) + if child is None and result is not None and result.interruptions: + child = result.to_state() + if child is None: + continue + # Turn resolution can rebind a queued call after load_state(). Check + # the current qualified binding and grant only for required branches. + key = get_function_tool_lookup_key_for_call(action.tool_call) + tools = state._current_agent.tools if state._current_agent is not None else [] + bindings = [ + tool + for tool in tools + if isinstance(tool, FunctionTool) and key in get_function_tool_lookup_keys(tool) + ] + # A replacement can introduce a policy even on an unmarked branch. + # Resolve that key before inspecting its child, and reuse the grant. + retained = action.function_tool + active = None + for candidate in bindings: + if candidate is retained or candidate.is_enabled is False: + continue + override = _tool_config(candidate) + execution = override.tool_execution if override is not None else settings + if (override and override.budget is not None) or ( + execution and execution.tool_text_transforms + ): + if state._current_agent is not None: + active = await _unique_enabled_function(bindings, context, state._current_agent) + if active is None or active._agent_instance is not retained._agent_instance: + requirement = "RunBudget" if override and override.budget else "text editor" + raise UserError( + f"A pending {requirement} requires the same unique enabled agent tool." + ) + break + recipient = active or (bindings[0] if len(bindings) == 1 else retained) + override = _tool_config(recipient) + policy = override.budget if override is not None else None + child_settings = override.tool_execution if override is not None else settings + replaced = delegate_replaced or recipient is not retained + # Agent.as_tool keeps the child's wrapper but forwards current context and usage. + # Use the same view for leaf and delegate grants without mutating saved state. + owner = context + if child._context is not None and child._context is not context: + owner = copy.copy(child._context) + owner.context = context.context + owner.usage = context.usage + budget, editor = await validate_resumed_agent_tools( + child, policy, owner, child_settings, delegate_replaced=replaced + ) + # Check delegated editors now, before any approved sibling can run. + editor |= await validate_pending_text_transforms( + child, child_settings, owner, delegate_replaced=replaced + ) + if budget or editor: + active = active or ( + await _unique_enabled_function(bindings, context, state._current_agent) + if state._current_agent is not None and state._context is not None + else None + ) + if ( + active is None + or active is not recipient + or active._agent_instance is not action.function_tool._agent_instance + ): + requirement = "RunBudget" if budget else "text editor" + raise UserError( + f"A pending {requirement} requires the same unique enabled agent tool." + ) + budgeted |= budget + edited |= editor + # Managed roots check after the session's missing-tool diagnostics. Ordinary + # roots can check local approvals now and reconcile MCP against live discovery. + if manual_root: + await validate_pending_text_transforms(state, settings, context, local_only=True) + return budgeted, edited + + def ensure_context_wrapper( context: RunContextWrapper[TContext] | TContext | None, ) -> RunContextWrapper[TContext]: diff --git a/src/agents/run_internal/run_loop.py b/src/agents/run_internal/run_loop.py index 273dab3c8f..abecdc4ab5 100644 --- a/src/agents/run_internal/run_loop.py +++ b/src/agents/run_internal/run_loop.py @@ -2838,6 +2838,7 @@ async def after_invocation_validation( tool_execution.prepare_tool_declaration is not None or tool_execution.prepare_tool_input is not None or tool_execution.prepare_tool_output is not None + or tool_execution.tool_text_transforms ): # A stream consumer must not change the invocation seen by preparation hooks. model_items = [ diff --git a/src/agents/run_internal/tool_execution.py b/src/agents/run_internal/tool_execution.py index 10d87b3176..1857524441 100644 --- a/src/agents/run_internal/tool_execution.py +++ b/src/agents/run_internal/tool_execution.py @@ -123,6 +123,7 @@ ) from .run_steps import ToolRunFunction from .tool_hooks import transform_tool_output +from .tool_text import invoke_selected_tool, select_text_editor from .tool_use_tracker import AgentToolUseTracker if TYPE_CHECKING: @@ -2144,7 +2145,19 @@ async def _invoke_tool_and_run_post_invoke( with hook_payload_diagnostics( "Function tool execution failed.", redact_by_default=False ): - invocation_result = await _invoke_function_tool_with_metadata( + tool_context._edit_text = select_text_editor( + self.config.tool_execution, + self.public_agent, + func_tool, + tool_context, + tool_call.arguments, + ) + invoke = ( + invoke_selected_tool + if tool_context._edit_text is not None + else _invoke_function_tool_with_metadata + ) + invocation_result = await invoke( function_tool=func_tool, context=tool_context, arguments=tool_call.arguments, @@ -2152,7 +2165,7 @@ async def _invoke_tool_and_run_post_invoke( real_result = invocation_result.output bypass_output_schema = invocation_result.is_sdk_generated_error except asyncio.CancelledError as e: - if outer_task in self.teardown_cancelled_tasks: + if tool_context._edit_text is not None or outer_task in self.teardown_cancelled_tasks: raise result = await maybe_invoke_function_tool_failure_error_function( @@ -2194,14 +2207,15 @@ async def _invoke_tool_and_run_post_invoke( task_state.in_post_invoke_phase = True unfiltered_result = real_result - real_result = await transform_tool_output( - self.config, - tool_context, - self.public_agent, - func_tool, - task_state.tool_run.tool_call, - real_result, - ) + if tool_context._edit_text is None: + real_result = await transform_tool_output( + self.config, + tool_context, + self.public_agent, + func_tool, + task_state.tool_run.tool_call, + real_result, + ) # Only the SDK's original failure may bypass a success schema. bypass_output_schema = bypass_output_schema and real_result is unfiltered_result output_guardrail_result = await _execute_tool_output_guardrails( @@ -2241,7 +2255,7 @@ async def _invoke_tool_and_run_post_invoke( provider_result, output_json_schema=None if bypass_output_schema else func_tool.output_json_schema, output_type_adapter=None - if bypass_output_schema + if bypass_output_schema or tool_context._edit_text is not None else func_tool._output_type_adapter, ) require_clean(raw_output_item) diff --git a/src/agents/run_internal/tool_text.py b/src/agents/run_internal/tool_text.py new file mode 100644 index 0000000000..e116a634a9 --- /dev/null +++ b/src/agents/run_internal/tool_text.py @@ -0,0 +1,404 @@ +"""Text-only edits before a selected Runner tool publishes any result data.""" + +from __future__ import annotations + +import json +from collections.abc import Awaitable, Callable +from functools import partial +from typing import TYPE_CHECKING, Any + +from pydantic import BaseModel + +from .._redaction import redact_payload, require_clean +from .._tool_identity import get_function_tool_lookup_key_for_tool, get_function_tool_lookup_keys +from ..exceptions import ( + UserError, + _mark_error_data_redacted, + _prepare_data_redacted_error, + _raise_data_redacted_error, +) +from ..run_config import MCPTextTransform, ToolCallHookContext +from ..tool import ( + FunctionTool, + ToolOriginType, + ToolOutputText, + ValidToolOutputPydanticModelsTypeAdapter, + _FunctionToolInvocationResult, + _invoke_function_tool_with_metadata, + _parse_function_tool_json_input, + _protect_selected_task, + _SelectedTaskExit, + _unique_enabled_function, +) +from .agent_tool_configuration import snapshot_agent_tools +from .tool_hooks import _await_hook + +if TYPE_CHECKING: + from mcp.types import CallToolResult + + from ..agent import Agent + from ..mcp import MCPServer + from ..run_config import ToolExecutionConfig, _TextEditor + from ..run_context import RunContextWrapper, _ToolInvocationRecord + from ..run_state import RunState + from ..tool_context import ToolContext + +_PEER_ERROR = "Selected MCP tool reported an error." +_Edit = Callable[[tuple[str, ...]], Awaitable[tuple[str, ...]]] + + +def bind_text_transform( + settings: ToolExecutionConfig | None, + tool: FunctionTool | None, + record: _ToolInvocationRecord | None, + *, + deferred_mcp: tuple[MCPServer, str, str] | None = None, +) -> int | None: + """Require an exact selector at admission, on resume and before invocation.""" + ambiguous = False + if settings is not None and settings.tool_text_transforms: + binding = tool._mcp_tool_binding if tool else None + server = tool._mcp_server_ref() if tool and tool._mcp_server_ref else None + exposed = tool.name if tool else "" + if deferred_mcp is not None: + from ..mcp._logging import get_mcp_server_log_name + + server, raw_name, exposed = deferred_mcp + binding = (get_mcp_server_log_name(server.name), raw_name, None) + for index, entry in enumerate(settings.tool_text_transforms): + if isinstance(entry, MCPTextTransform): + if binding is None: + continue + if server is not entry.server: + from ..mcp._logging import get_mcp_server_log_name + + # Use the same credential-free identity as discovery and restore. + if binding[0] != get_mcp_server_log_name(entry.server.name): + continue + if entry.tool_name != binding[1]: + from ..mcp.util import MCPUtil + + if server is entry.server and tool is not None: + names = tool._mcp_raw_names + ambiguous |= names is not None and entry.tool_name not in names + # A partial catalog cannot prove absence. A visible alias can + # signal a mistake, but only the exact raw name can select. + ambiguous |= entry.tool_name in ( + exposed, + MCPUtil._safe_tool_name_part(binding[1], "tool"), + MCPUtil._build_prefixed_tool_base_name(binding[0], binding[1]), + ) + continue + if server is not entry.server: + ambiguous = True + continue + elif entry[0] is not tool: + if ( + tool is not None + and binding is None + and not tool._is_agent_tool + and not tool._is_codex_tool + ): + ambiguous |= ( + tool._namespace_source is not None and tool._namespace_source() is entry[0] + ) + ambiguous |= get_function_tool_lookup_key_for_tool( + entry[0] + ) == get_function_tool_lookup_key_for_tool(tool) + continue + if record is not None: + record.requires_text_transform = True + return index + if ambiguous or (record is not None and record.requires_text_transform): + raise UserError( + "Missing exact tool_text_transforms target. Register the agent's FunctionTool " + "(the copy returned by tool_namespace) or the connected MCP server " + "and original tool name, including on resume." + ) + return None + + +async def validate_pending_text_transforms( + state: RunState[Any, Any], + settings: ToolExecutionConfig | None, + owner: RunContextWrapper[Any], + *, + local_only: bool = False, + delegate_replaced: bool = False, +) -> bool: + """Check required editors before claiming a checkpoint or dispatching siblings.""" + from .run_steps import NextStepInterruption + + processed = state._last_processed_response + context, agent = state._context, state._current_agent + if ( + processed is None + or context is None + or agent is None + or not isinstance(state._current_step, NextStepInterruption) + ): + return False + required = False + for item in state._current_step.interruptions: + call_id = item.call_id + record = context._tool_invocations.get(call_id) if call_id else None + if not call_id or record is None or record.completed: + continue + if not record.requires_text_transform and not (settings and settings.tool_text_transforms): + continue + if ( + context.get_approval_status( + item.tool_name or "", + call_id, + tool_namespace=item.tool_namespace, + existing_pending=item, + current_invocation=item, + ) + is False + ): + continue + if delegate_replaced and record.requires_text_transform: + raise UserError("A pending text editor requires the same unique enabled agent tool.") + tool = next( + (run.function_tool for run in processed.functions if run.tool_call.call_id == call_id), + None, + ) + # Protected loads defer MCP discovery. Check the saved recipient before the + # session claim. Reconciliation still checks the live binding before execution. + binding = processed.mcp_tool_bindings.get(call_id) + if local_only and (binding is not None or (tool and tool._mcp_tool_binding)): + continue + if tool is None and state._requires_redaction and binding is not None: + from ..mcp._logging import get_mcp_server_log_name + + name, raw_name, index = binding + if index is not None and 0 <= index < len(agent.mcp_servers): + peer = agent.mcp_servers[index] + if get_mcp_server_log_name(peer.name) == name: + selected = bind_text_transform( + settings, + None, + record if record.requires_text_transform else None, + deferred_mcp=(peer, raw_name, item.tool_name or ""), + ) + required |= selected is not None + continue + if tool is not None and tool._mcp_tool_binding is not None: + server = tool._mcp_server_ref() if tool._mcp_server_ref else None + if record.requires_text_transform and not any( + peer is server for peer in agent.mcp_servers + ): + raise UserError( + "Reload the paused state after replacing a selected tool or server." + ) + elif tool is not None or ( + item.tool_origin is not None and item.tool_origin.type == ToolOriginType.FUNCTION + ): + # Load may omit a disabled function. Use the saved key to find the current + # local candidate, then require the exact selected object below. + if ( + not record.requires_text_transform + and tool is not None + and (tool._is_agent_tool or tool._is_codex_tool) + ): + continue + key = item.tool_lookup_key + if key is None and tool is not None: + key = get_function_tool_lookup_key_for_tool(tool) + original = tool._namespace_source() if tool and tool._namespace_source else None + if not record.requires_text_transform and not ( + settings + and any( + not isinstance(entry, MCPTextTransform) + and (original is entry[0] or key in get_function_tool_lookup_keys(entry[0])) + for entry in settings.tool_text_transforms + ) + ): + continue + matches = [ + candidate + for candidate in snapshot_agent_tools(agent) + if isinstance(candidate, FunctionTool) + and candidate.is_enabled is not False + and key in get_function_tool_lookup_keys(candidate) + ] + current = await _unique_enabled_function(matches, owner, agent) + if current is None: + raise UserError("A pending text editor requires a unique enabled function tool.") + if record.requires_text_transform and tool is not None and current is not tool: + raise UserError( + "Reload the paused state after replacing a selected tool or server." + ) + tool = current + # Validate new selectors without changing the saved requirement. + selected = bind_text_transform( + settings, tool, record if record.requires_text_transform else None + ) + required |= selected is not None + return required + + +def select_text_editor( + settings: ToolExecutionConfig | None, + agent: Agent[Any], + tool: FunctionTool, + context: ToolContext[Any], + arguments: str, +) -> _Edit | None: + index = bind_text_transform(settings, tool, context._tool_invocations.get(context.tool_call_id)) + if index is None or settings is None: + return None + entry = settings.tool_text_transforms[index] + editor = entry.edit if isinstance(entry, MCPTextTransform) else entry[1] + call = ToolCallHookContext( + context, + agent, + tool, + context.tool_call_id, + context.tool_namespace, + _parse_function_tool_json_input(tool_name=tool.name, input_json=arguments), + mcp_target=(entry.server, entry.tool_name) if isinstance(entry, MCPTextTransform) else None, + ) + + return partial(_validated_edit, editor, call, tool.name) + + +class _InvalidTextEdit(ValueError): + """The editor returned a value with the wrong shape.""" + + +async def _validated_edit( + edit: _TextEditor, call: ToolCallHookContext[Any], name: str, texts: tuple[str, ...] +) -> tuple[str, ...]: + async def invoke() -> tuple[str, ...] | None: + result = await _protect_selected_task(partial(edit, call, texts)) + # Refuse arbitrary objects before the hook takes ownership with deepcopy. + if type(result) not in (list, tuple): + return None + frozen = tuple(result) + if len(frozen) != len(texts) or any(type(text) is not str for text in frozen): + return None + return frozen + + result = await _await_hook(invoke, "tool_text_transforms", name) + if result is None: + raise _InvalidTextEdit() + for text in result: + text.encode("utf-8") + return redact_payload(result) + + +async def invoke_selected_tool( + function_tool: FunctionTool, context: ToolContext[Any], arguments: str +) -> _FunctionToolInvocationResult: + edit = context._edit_text + assert edit is not None + try: + result = await _invoke_function_tool_with_metadata( + function_tool=function_tool, context=context, arguments=arguments + ) + if result.is_sdk_generated_error: + raise UserError("Selected tool failed.") + if function_tool._mcp_tool_binding is not None: + # The MCP adapter edits before its extractor and live span see the result. + return result + output = await _edit_function_result(edit, function_tool, result.output) + require_clean(output) + return _FunctionToolInvocationResult(output) + except BaseException as error: + result = None + if type(error) is _SelectedTaskExit: + error = error.args[0] + safe_error = _prepare_data_redacted_error(error, trusted_error_message=_PEER_ERROR) + if isinstance(safe_error, Exception) and not isinstance(safe_error, UserError): + safe_error = UserError( + "Text editors must return a same-length list or tuple of strings." + if type(error) is _InvalidTextEdit + else "Selected tool execution failed." + ) + _mark_error_data_redacted(safe_error) + # Neither a tool nor its editor may publish a rejected payload via exception details. + _raise_data_redacted_error(safe_error) + + +async def _edit_function_result(edit: _Edit, tool: FunctionTool, output: Any) -> Any: + adapter = tool._output_type_adapter + if adapter is not None: + # The declared converter already validated the function's result. Publish + # only its JSON representation, without private fields or another conversion. + source = adapter.dump_json(output, by_alias=True, warnings="error").decode() + original = json.loads(source) + if not isinstance(original, dict): + raise ValueError + (edited,) = await edit((source,)) + if edited == source: + return original + candidate = json.loads(edited) + validated = adapter.validate_json(edited, strict=True) + accepted = json.loads(adapter.dump_json(validated, by_alias=True, warnings="error")) + if not isinstance(candidate, dict) or not isinstance(accepted, dict): + raise ValueError + # Ignore extra input keys discarded by the declared type. Refuse changes + # made by validators or serializers, including changes to untouched fields. + expected = {k: v for k, v in candidate.items() if k in original or k in accepted} + if json.dumps(expected, sort_keys=True, allow_nan=False) != json.dumps( + accepted, sort_keys=True, allow_nan=False + ): + raise ValueError + return accepted + if tool.output_json_schema is not None: + # A bare JSON schema has no corresponding runtime validator. + raise ValueError + if type(output) is str: + (edited,) = await edit((output,)) + return edited + + multiple = isinstance(output, (list, tuple)) + parts = [] + for part in output if multiple else [output]: + if isinstance(part, BaseModel): + part = part.model_dump(warnings="error") + if not isinstance(part, dict) or "type" not in part: + raise ValueError + parts.append(ValidToolOutputPydanticModelsTypeAdapter.validate_python(part, strict=True)) + slots = [part for part in parts if isinstance(part, ToolOutputText)] + for slot, text in zip(slots, await edit(tuple(slot.text for slot in slots)), strict=True): + slot.text = text + return parts if multiple else parts[0] + + +async def edit_mcp_result( + edit: _Edit, result: CallToolResult, use_structured_content: bool +) -> CallToolResult: + from mcp.types import CallToolResult + + from ..mcp._compat import image_mime_type, result_is_error, result_structured_content + + is_error = result_is_error(result) + if type(is_error) is not bool: + raise ValueError + if is_error: + raise UserError(_PEER_ERROR) + structured = result_structured_content(result) if use_structured_content else None + if structured is not None and not isinstance(structured, dict): + raise ValueError + content: list[dict[str, str]] = [] + for item in result.content: + if item.type == "text": + content.append({"type": "text", "text": "" if structured is not None else item.text}) + elif item.type == "image": + content.append({"type": "image", "mimeType": image_mime_type(item), "data": item.data}) + else: + raise ValueError + # Rebuild only supported fields. Never expose metadata or the original fallback. + if structured is not None and not any(part["type"] == "text" for part in content): + content.append({"type": "text", "text": ""}) + clean = CallToolResult.model_validate({"content": content}, strict=True) + slots = [part for part in clean.content if part.type == "text"] + if structured is not None: + slots[0].text = json.dumps(structured, allow_nan=False) + edited = await edit(tuple(slot.text for slot in slots)) + for slot, text in zip(slots, edited, strict=True): + slot.text = text + require_clean(clean) + return clean diff --git a/src/agents/run_internal/turn_resolution.py b/src/agents/run_internal/turn_resolution.py index e75fefac7c..295a32ed4d 100644 --- a/src/agents/run_internal/turn_resolution.py +++ b/src/agents/run_internal/turn_resolution.py @@ -227,6 +227,7 @@ _select_function_tool_runs_for_resume, _validate_unresolved_function_calls, ) +from .tool_text import bind_text_transform from .turn_preparation import get_handoffs, get_output_schema _DEFAULT_NEST_HANDOFF_HISTORY = nest_handoff_history @@ -2650,6 +2651,13 @@ def _rebind_function_run( if approval_record is not None else True ) + if approval_status is not False: + queued = current_functions.get(call_id) + bind_text_transform( + run_config.tool_execution, + queued.function_tool if queued else None, + context_wrapper._tool_invocations.get(call_id), + ) stale_function = stale_functions.get(call_id) original_binding = processed_response.mcp_tool_bindings.get(call_id) current_function = current_functions.get(call_id) @@ -4384,6 +4392,14 @@ def classify() -> ProcessedResponse: for call_id, rewrite in new_bindings.items(): context_wrapper._tool_invocations[call_id].input_rewrite = rewrite + if settings is not None and settings.tool_text_transforms: + for action in processed_response.functions: + bind_text_transform( + settings, + action.function_tool, + context_wrapper._tool_invocations.get(action.tool_call.call_id), + ) + if after_invocation_validation is not None: await after_invocation_validation(processed_response) diff --git a/src/agents/run_state.py b/src/agents/run_state.py index 61ef87ebbf..a93830a250 100644 --- a/src/agents/run_state.py +++ b/src/agents/run_state.py @@ -260,7 +260,7 @@ def _default_run_state_validation_error( # 3. to_json() always emits CURRENT_SCHEMA_VERSION. # 4. Forward compatibility is intentionally fail-fast (older SDKs reject newer or unsupported # versions). -CURRENT_SCHEMA_VERSION = "1.25" +CURRENT_SCHEMA_VERSION = "1.26" _PROGRAMMATIC_TOOL_CALLING_MIN_SCHEMA_VERSION = "1.13" _HOSTED_MCP_APPROVALS_MIN_SCHEMA_VERSION = "1.14" _CURRENT_RESPONSE_OWNERSHIP_MIN_SCHEMA_VERSION = "1.17" @@ -329,6 +329,7 @@ def _default_run_state_validation_error( ), "1.24": "Requires caller-supplied text redaction when resuming protected RunState snapshots.", "1.25": "Preserves required Runner budgets and consumption across approval resumes.", + "1.26": "Requires an exact text editor when resuming selected tool calls.", } SUPPORTED_SCHEMA_VERSIONS = frozenset(SCHEMA_VERSION_SUMMARIES) @@ -1551,6 +1552,9 @@ def _serialize_tool_invocations(self) -> dict[str, dict[str, Any]]: "executed": invocation.executed, "completed": invocation.completed, } + # Schema 1.26 retains the requirement, never the editor or selector objects. + if invocation.requires_text_transform and not invocation.completed: + record["requires_text_transform"] = True if invocation.input_rewrite is not None: fingerprint, arguments = invocation.input_rewrite record["input_rewrite"] = { @@ -2696,10 +2700,15 @@ def _validate_pending_approvals( required_children: set[int], *, nested: bool = False, -) -> bool: - """Validate before best-effort child restoration and report whether a budget is required.""" +) -> tuple[bool, bool]: + """Check pending approvals and propagate budget and editor requirements to ancestors.""" context = state.get("context") requires_budget = isinstance(context, dict) and "budget" in context + invocations = context.get("tool_invocations") if isinstance(context, dict) else None + requires_editor = isinstance(invocations, dict) and any( + isinstance(record, dict) and "requires_text_transform" in record + for record in invocations.values() + ) response = state.get("last_processed_response") if not isinstance(response, dict): response = {} @@ -2716,19 +2725,28 @@ def _validate_pending_approvals( if isinstance(functions, list): for entry in functions: child = entry.get("agent_run_state") if isinstance(entry, dict) else None - if isinstance(child, dict) and _validate_pending_approvals( + if not isinstance(child, dict): + continue + budget, editor = _validate_pending_approvals( child, validation_error_factory, required_children, nested=True - ): + ) + if budget or editor: # Track the exact child snapshot until its pending run is registered. required_children.add(id(child)) - requires_budget = True - if requires_budget: + requires_budget |= budget + requires_editor |= editor + if requires_budget or requires_editor: version = _validate_run_state_schema_version( state, validation_error_factory=validation_error_factory ) - if tuple(map(int, version.split("."))) < (1, 25): + schema = tuple(map(int, version.split("."))) + if requires_editor and schema < (1, 26): + raise validation_error_factory( + "Tool text transforms require RunState schema 1.26.", UserError + ) + if requires_budget and schema < (1, 25): raise _BudgetCheckpointError("Run budgets require schema 1.25 or later.") - return requires_budget + return requires_budget, requires_editor def _validate_run_state_json_value(value: object) -> None: @@ -5923,6 +5941,8 @@ def _clone_original_input(original_input: str | list[Any]) -> str | list[Any]: _REQUIRED_CHILD_MISSING, "RunState tool_invocations must be a mapping.", "RunState tool_invocations contains an invalid call ID.", + "Tool text transforms require RunState schema 1.26.", + "RunState tool text transform requirement is invalid.", "RunState tool invocation must be a mapping.", "RunState tool invocation contains invalid lifecycle data.", "Tool input rewrites require RunState schema 1.23.", diff --git a/src/agents/tool.py b/src/agents/tool.py index 81c5e52c1e..61e1374b0f 100644 --- a/src/agents/tool.py +++ b/src/agents/tool.py @@ -92,6 +92,7 @@ from .agent import Agent, AgentBase from .items import RunItem, ToolApprovalItem + from .mcp.server import MCPServer ToolParams = ParamSpec("ToolParams") @@ -582,6 +583,10 @@ class FunctionTool: _tool_namespace_description: str | None = field(default=None, kw_only=True, repr=False) """Internal namespace description used when serializing grouped function tools.""" + _namespace_source: Callable[[], FunctionTool | None] | None = field( + default=None, init=False, repr=False, compare=False + ) + _mcp_title: str | None = field(default=None, kw_only=True, repr=False) """Internal MCP display title used for ToolCallItem metadata.""" @@ -598,6 +603,16 @@ class FunctionTool: _mcp_annotations: ToolAnnotations | None = field(default=None, kw_only=True, repr=False) + # The invocation partial owns the peer. Keep its identity across roster changes + # without copying the live connection when a tool is copied. + _mcp_server_ref: Callable[[], MCPServer | None] | None = field( + default=None, init=False, repr=False, compare=False + ) + + _mcp_raw_names: frozenset[str] | None = field( + default=None, init=False, repr=False, compare=False + ) + @property def mcp_annotations(self) -> ToolAnnotations | None: """Return a copy of the MCP annotations captured when this tool was converted. @@ -699,6 +714,8 @@ async def __call__(self, ctx: ToolContext[Any], input: str) -> Any: try: return await self._invoke_tool_impl(ctx, input) except Exception as e: + if isinstance(ctx, ToolContext) and ctx._edit_text is not None: + raise assert self._function_tool is not None result = await maybe_invoke_function_tool_failure_error_function( function_tool=self._function_tool, @@ -822,6 +839,14 @@ async def _function_tool_enabled( return bool(await result if inspect.isawaitable(result) else result) +async def _unique_enabled_function( + bindings: list[FunctionTool], context: RunContextWrapper[Any], agent: AgentBase[Any] +) -> FunctionTool | None: + """Resolve a protected approval key without probing unrelated tools.""" + enabled = [tool for tool in bindings if await _function_tool_enabled(tool, context, agent)] + return enabled[0] if len(enabled) == 1 else None + + def get_function_tool_origin(function_tool: FunctionTool) -> ToolOrigin | None: """Return scalar origin metadata for a function tool.""" if not function_tool._emit_tool_origin: @@ -1730,6 +1755,8 @@ def tool_namespace( for tool in tools: validate_function_tool_namespace_shape(tool.name, namespace_name) namespaced_tool = copy.copy(tool) + if tool._tool_namespace is None: + namespaced_tool._namespace_source = weakref.ref(tool) namespaced_tool._tool_namespace = namespace_name namespaced_tool._tool_namespace_description = normalized_description namespaced_tools.append(namespaced_tool) @@ -2310,6 +2337,24 @@ class _FunctionToolInvocationResult: is_sdk_generated_error: bool = False +_SelectedT = TypeVar("_SelectedT") + + +class _SelectedTaskExit(BaseException): + """Carry a sanitized process-control signal to the selected invocation boundary.""" + + +async def _protect_selected_task(invoke: Callable[[], Awaitable[_SelectedT]]) -> _SelectedT: + # asyncio propagates these directly to the loop before the awaiting task can redact them. + try: + return await invoke() + except (SystemExit, KeyboardInterrupt) as error: + from .exceptions import _prepare_data_redacted_error + + safe_error = _prepare_data_redacted_error(error) + raise _SelectedTaskExit(safe_error) + + async def _invoke_function_tool_with_metadata( *, function_tool: FunctionTool, @@ -2327,8 +2372,9 @@ async def _invoke_function_tool_with_metadata( is_sdk_generated_error=_consume_function_tool_default_failure(context), ) + invoke = functools.partial(function_tool.on_invoke_tool, cast(Any, invoke_context), arguments) tool_task: asyncio.Future[Any] = asyncio.ensure_future( - function_tool.on_invoke_tool(cast(Any, invoke_context), arguments) + _protect_selected_task(invoke) if context._edit_text is not None else invoke() ) try: output = await asyncio.wait_for(tool_task, timeout=timeout_seconds) @@ -2350,7 +2396,7 @@ async def _invoke_function_tool_with_metadata( tool_name=function_tool.name, timeout_seconds=timeout_seconds, ) - if function_tool.timeout_behavior == "raise_exception": + if function_tool.timeout_behavior == "raise_exception" or context._edit_text is not None: raise timeout_error from exc timeout_error_function = function_tool.timeout_error_function @@ -2878,7 +2924,11 @@ async def _on_invoke_tool_impl(ctx: ToolContext[Any], input: str) -> Any: result = None raise - if _debug.DONT_LOG_TOOL_DATA or current_redactor() is not None: + if ( + _debug.DONT_LOG_TOOL_DATA + or current_redactor() is not None + or (isinstance(ctx, ToolContext) and ctx._edit_text is not None) + ): logger.debug("Tool %s completed.", tool_name) else: logger.debug("Tool %s returned %s", tool_name, result) diff --git a/src/agents/tool_context.py b/src/agents/tool_context.py index 926f89130f..4a9d9a0694 100644 --- a/src/agents/tool_context.py +++ b/src/agents/tool_context.py @@ -18,6 +18,8 @@ from .usage import Usage if TYPE_CHECKING: + from collections.abc import Awaitable, Callable + from ._function_tool_arguments import PreparedFunctionArguments from .agent import AgentBase from .items import ToolApprovalItem, TResponseInputItem @@ -117,6 +119,7 @@ def __init__( else: self.run_config = None # Internal adapter hook used to attach SDK-only custom data to the emitted output item. + self._edit_text: Callable[[tuple[str, ...]], Awaitable[tuple[str, ...]]] | None = None self._custom_data: dict[str, Any] | None = None self._function_tool_arguments: PreparedFunctionArguments | None = None diff --git a/tests/fixtures/run_state/features/v1_25_run_budget.json b/tests/fixtures/run_state/features/v1_25_run_budget.json new file mode 100644 index 0000000000..c8f41b00ef --- /dev/null +++ b/tests/fixtures/run_state/features/v1_25_run_budget.json @@ -0,0 +1,69 @@ +{ + "$schemaVersion": "1.25", + "auto_previous_response_id": false, + "context": { + "approvals": {}, + "budget": { + "max_requests": 3, + "max_tokens": null, + "missing_usage": "stop", + "requests": 1, + "tokens": 0, + "unavailable": false + }, + "context": {}, + "context_meta": { + "omitted": false, + "original_type": "mapping", + "requires_deserializer": false, + "serialized_via": "mapping" + }, + "tool_invocations": {}, + "usage": { + "input_tokens": 0, + "input_tokens_details": [ + { + "cache_write_tokens": 0, + "cache_write_tokens_details": null, + "cached_tokens": 0 + } + ], + "output_tokens": 0, + "output_tokens_details": [ + { + "reasoning_tokens": 0 + } + ], + "request_usage_entries": [], + "requests": 0, + "total_tokens": 0 + } + }, + "conversation_id": null, + "current_agent": { + "name": "compat-agent" + }, + "current_step": null, + "current_turn": 0, + "current_turn_persisted_item_count": 0, + "generated_items": [], + "generated_prompt_cache_key": null, + "generated_session_item_indexes": [], + "input_guardrail_results": [], + "last_model_response": null, + "last_processed_response": null, + "max_turns": 10, + "model_responses": [], + "nested_history_owned_session_item_refs": [], + "no_active_agent_run": true, + "original_input": "historical input", + "output_guardrail_results": [], + "pending_input": [], + "previous_response_id": null, + "reasoning_item_id_policy": null, + "session_items": [], + "tool_input_guardrail_results": [], + "tool_output_guardrail_results": [], + "tool_use_tracker": {}, + "trace": null +} diff --git a/tests/fixtures/run_state/generate_corpus.py b/tests/fixtures/run_state/generate_corpus.py index a6c77f911b..443c30b03d 100644 --- a/tests/fixtures/run_state/generate_corpus.py +++ b/tests/fixtures/run_state/generate_corpus.py @@ -48,6 +48,7 @@ CODEX_1_22_WRITER = "448ae7a3d9c5ddbfa0656a04a021ffb3f3c16530" RESUMABLE_1_23_WRITER = "d48e3c89ecdb71ad78d9eb90ed97bf632598d51c" RELEASED_1_24_WRITER = "6463d16ca5b680107df2e37386ed94c1bbb8ff81" +BUDGET_1_25_WRITER = "827149084e196f724035733e9146291bab7755ea" GUARDRAIL_1_20_WRITER = "125efa029b4bfd84238bd2c4fd69c3406f802663" LEGACY_CANONICAL_COMPATIBILITY_NOTE = ( @@ -611,6 +612,17 @@ def approval(call_id): fingerprint="b" * 64, requires_declaration=True, ) +""", + ), + Scenario( + "1.25", + BUDGET_1_25_WRITER, + "run_budget", + """ +from agents import RunBudget +from agents.run_budget import _BudgetState + +state._context._budget = _BudgetState(RunBudget(max_requests=3), requests=1) """, ), ) @@ -662,6 +674,7 @@ def approval(call_id): Scenario("1.22", RELEASED_1_22_WRITER, "minimal", ""), Scenario("1.23", RESUMABLE_1_23_WRITER, "minimal", ""), Scenario("1.24", RELEASED_1_24_WRITER, "minimal", ""), + Scenario("1.25", BUDGET_1_25_WRITER, "minimal", ""), ) diff --git a/tests/fixtures/run_state/minimal/v1_25.json b/tests/fixtures/run_state/minimal/v1_25.json new file mode 100644 index 0000000000..97453c77f9 --- /dev/null +++ b/tests/fixtures/run_state/minimal/v1_25.json @@ -0,0 +1,61 @@ +{ + "$schemaVersion": "1.25", + "auto_previous_response_id": false, + "context": { + "approvals": {}, + "context": {}, + "context_meta": { + "omitted": false, + "original_type": "mapping", + "requires_deserializer": false, + "serialized_via": "mapping" + }, + "tool_invocations": {}, + "usage": { + "input_tokens": 0, + "input_tokens_details": [ + { + "cache_write_tokens": 0, + "cache_write_tokens_details": null, + "cached_tokens": 0 + } + ], + "output_tokens": 0, + "output_tokens_details": [ + { + "reasoning_tokens": 0 + } + ], + "request_usage_entries": [], + "requests": 0, + "total_tokens": 0 + } + }, + "conversation_id": null, + "current_agent": { + "name": "compat-agent" + }, + "current_step": null, + "current_turn": 0, + "current_turn_persisted_item_count": 0, + "generated_items": [], + "generated_prompt_cache_key": null, + "generated_session_item_indexes": [], + "input_guardrail_results": [], + "last_model_response": null, + "last_processed_response": null, + "max_turns": 10, + "model_responses": [], + "nested_history_owned_session_item_refs": [], + "no_active_agent_run": true, + "original_input": "historical input", + "output_guardrail_results": [], + "pending_input": [], + "previous_response_id": null, + "reasoning_item_id_policy": null, + "session_items": [], + "tool_input_guardrail_results": [], + "tool_output_guardrail_results": [], + "tool_use_tracker": {}, + "trace": null +} diff --git a/tests/fixtures/run_state/sources.json b/tests/fixtures/run_state/sources.json index 48789451a0..90a99dae67 100644 --- a/tests/fixtures/run_state/sources.json +++ b/tests/fixtures/run_state/sources.json @@ -178,6 +178,13 @@ "fixture": "features/v1_24_requires_declaration.json", "provenance": "historical_writer", "version": "1.24" + }, + { + "commit": "827149084e196f724035733e9146291bab7755ea", + "feature": "run_budget", + "fixture": "features/v1_25_run_budget.json", + "provenance": "historical_writer", + "version": "1.25" } ], "resume": { @@ -281,6 +288,10 @@ "commit": "6463d16ca5b680107df2e37386ed94c1bbb8ff81", "fixture": "minimal/v1_24.json" }, + "1.25": { + "commit": "827149084e196f724035733e9146291bab7755ea", + "fixture": "minimal/v1_25.json" + }, "1.3": { "commit": "6814a54711f591712c893f0a8be1cf56c512ae63", "fixture": "minimal/v1_3.json" diff --git a/tests/test_run_budget.py b/tests/test_run_budget.py index 583efe2bf5..85b8f300e9 100644 --- a/tests/test_run_budget.py +++ b/tests/test_run_budget.py @@ -24,6 +24,7 @@ RunConfig, Runner, RunState, + ToolExecutionConfig, Usage, UserError, input_guardrail, @@ -415,7 +416,8 @@ def record() -> str: @pytest.mark.asyncio @pytest.mark.parametrize("approved", [False, True]) -async def test_unavailable_budgeted_grandchild_refuses_restore_before_sibling(approved): +@pytest.mark.parametrize("policy", ["budget", "editor", "both"]) +async def test_required_grandchild_checks_grant_before_restore_and_resume(approved, policy): effects = [] @tool(needs_approval=True) @@ -428,11 +430,25 @@ def model(*calls): leaf_model = model(get_function_tool_call("record", call_id="leaf")) leaf = Agent(name="leaf", tools=[record], model=leaf_model) - config = RunConfig(budget=RunBudget(max_model_calls=2), tracing_disabled=True) + + async def edit(call, texts): + effects.append("edit") + return ("edited",) + + config = RunConfig( + budget=RunBudget(max_model_calls=2) if policy != "editor" else None, + tool_execution=ToolExecutionConfig(tool_text_transforms=[(record, edit)]) + if policy != "budget" + else None, + tracing_disabled=True, + ) allowed = True + grants = [] async def grant(ctx, agent): assert agent.name == "middle" + if store.checkpoint(session.session_id)["status"] == "paused": + grants.append(ctx.context["allowed"]) return allowed and ctx.context["allowed"] inner = leaf.as_tool("inner", "Delegate", run_config=config, is_enabled=grant) @@ -482,13 +498,20 @@ def disabled(ctx, agent): pending.approve(item) for enabled, context in [(True, None), (False, {"allowed": True}), (True, {"allowed": False})]: allowed = enabled - with pytest.raises(UserError, match="RunBudget"): + grants.clear() + saved_checkpoint = store.records[session.session_id] + with pytest.raises(UserError, match="text editor" if policy == "editor" else "RunBudget"): await run(root, None, approved, pending, context=context) - assert store.checkpoint(session.session_id)["status"] == "paused" + assert grants == [bool(context and context["allowed"])] + assert store.records[session.session_id] == saved_checkpoint assert not effects assert len(root_model.calls) == len(middle_model.calls) == len(leaf_model.calls) == 1 + grants.clear() result = await run(root, None, approved, pending, context={"allowed": True}) - assert result.final_output == "done" and effects == ["record", "record"] + assert grants == [True] + assert result.final_output == "done" + expected = ["record", "record"] if policy == "budget" else ["edit", "record", "record"] + assert sorted(effects) == expected assert len(root_model.calls) == len(middle_model.calls) == len(leaf_model.calls) == 2 diff --git a/tests/test_run_state.py b/tests/test_run_state.py index b5f8d617f3..a6a196c907 100644 --- a/tests/test_run_state.py +++ b/tests/test_run_state.py @@ -9044,6 +9044,7 @@ def test_supported_schema_versions_match_released_boundary(self): "1.22", "1.23", "1.24", + "1.25", CURRENT_SCHEMA_VERSION, } ) diff --git a/tests/test_tool_text_transforms.py b/tests/test_tool_text_transforms.py new file mode 100644 index 0000000000..680d7c67af --- /dev/null +++ b/tests/test_tool_text_transforms.py @@ -0,0 +1,1687 @@ +import asyncio +import json +import logging +from dataclasses import replace + +import pytest +from mcp.types import CallToolResult +from opentelemetry.sdk.trace import TracerProvider +from opentelemetry.sdk.trace.export import SimpleSpanProcessor +from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter +from pydantic import BaseModel, Field, TypeAdapter, field_validator + +from agents import ( + Agent, + MCPTextTransform, + RunConfig, + RunHooks, + Runner, + RunState, + SQLiteSession, + ToolExecutionConfig, + ToolGuardrailFunctionOutput, + UserError, + _debug, + function_tool, + tool_namespace, + tool_output_guardrail, +) +from agents.extensions.tracing import OpenTelemetryTracingProcessor +from agents.testing import ScriptedModel, assistant_message, function_call +from agents.tracing import get_current_span, set_trace_processors + +from .mcp.helpers import FakeMCPServer +from .testing_processor import SPAN_PROCESSOR_TESTING, fetch_ordered_spans + +RAW = "synthetic-private-draft" +SAFE = "approved-preview" +IMAGE = {"type": "image", "mimeType": "image/png", "data": "AQID"} + + +@pytest.fixture +def exporter(): + provider = TracerProvider() + recorder = InMemorySpanExporter() + provider.add_span_processor(SimpleSpanProcessor(recorder)) + processor = OpenTelemetryTracingProcessor(tracer_provider=provider) + set_trace_processors([SPAN_PROCESSOR_TESTING, processor]) + try: + yield recorder + finally: + set_trace_processors([SPAN_PROCESSOR_TESTING]) + processor.shutdown() + provider.shutdown() + + +class Source(FakeMCPServer): + def __init__(self, server_name="Reports", **kwargs): + super().__init__(server_name=server_name, **kwargs) + self.add_tool("read.report", {}) + self.use_structured_content = True + self.result = { + "content": [ + {"type": "text", "text": RAW + " fallback"}, + IMAGE, + {"type": "text", "text": RAW + " suffix"}, + ], + "structuredContent": {"draft": RAW}, + "_meta": {"private": RAW}, + } + + async def call_tool(self, tool_name, arguments, meta=None): + self.tool_calls.append(tool_name) + return CallToolResult.model_validate(self.result) + + +def model_for(name): + return ScriptedModel([[function_call(name, {}, call_id="one")], [assistant_message("done")]]) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("detail", [None, "content"]) +@pytest.mark.parametrize("route", ["function", "mcp"]) +@pytest.mark.parametrize( + "outcome", ["edit", "list", "throw", "cancel", "invalid", "short", "string"] +) +async def test_selected_output_before_publication( + detail, route, outcome, exporter, caplog, monkeypatch +): + monkeypatch.setattr(_debug, "DONT_LOG_TOOL_DATA", False) + caplog.set_level(logging.DEBUG, logger="openai.agents") + observed = [] + edits = [] + effects = [] + + @tool_output_guardrail + def guard(data): + observed.append(str(data.output)) + return ToolGuardrailFunctionOutput.allow() + + class Hooks(RunHooks): + async def on_tool_end(self, context, agent, tool, result): + observed.append(str(result)) + + @function_tool(tool_output_guardrails=[guard]) + async def report(): + effects.append("local") + return [ + {"type": "text", "text": RAW}, + {"type": "image", "image_url": "data:image/png;base64,AQID"}, + {"type": "file", "file_id": "example-file"}, + ] + + def extract(ctx): + observed.append(str((ctx.tool_output, ctx.result_meta, ctx.structured_content))) + return {"copy": observed[-1]} + + source = Source(custom_data_extractor=extract, tool_output_guardrails=[guard]) + local = route == "function" + model = model_for("report" if local else "mcp_Reports__read_report") + agent = Agent( + name="reports", + tools=[report], + mcp_servers=[source], + mcp_config={"include_server_in_tool_names": True}, + model=model, + ) + + async def edit(call, texts): + span = get_current_span() + assert span is not None + edits.append((call.call_id, call.mcp_target, texts, str(span.export()))) + if outcome == "throw": + raise ValueError(RAW) + if outcome == "cancel": + raise asyncio.CancelledError(RAW) + if outcome == "short": + return () + if outcome == "string": + return RAW + if outcome == "invalid": + return [IMAGE] * len(texts) + replacements = [SAFE if t else "" for t in texts] + if outcome == "list": + asyncio.get_running_loop().call_soon(replacements.clear) + return replacements + return tuple(replacements) + + async def legacy(*args): + pytest.fail("selected call reached the generic editor") + + config = RunConfig( + tool_execution=ToolExecutionConfig( + tool_text_transforms=[ + (report, edit) + if local + else MCPTextTransform(server=source, tool_name="read.report", edit=edit) + ], + prepare_tool_output=legacy, + ), + tracing={"operation_detail": detail} if detail else {}, + trace_include_sensitive_data=True, + redact_text=(lambda text: text) if outcome == "short" else None, + ) + session = SQLiteSession("local") + try: + run = Runner.run_streamed(agent, "go", run_config=config, hooks=Hooks(), session=session) + events = [] + + async def collect(): + async for event in run.stream_events(): + if ( + event.type == "run_item_stream_event" + and event.item.type == "tool_call_output_item" + ): + events.append(event.item) + + if outcome in {"edit", "list"}: + await collect() + (item,) = events + assert item.raw_item["call_id"] == "one" + blocks = item.raw_item["output"] + assert blocks[0] == {"type": "input_text", "text": SAFE} + assert blocks[1] == {"type": "input_image", "image_url": "data:image/png;base64,AQID"} + assert blocks[2] == ( + {"type": "input_file", "file_id": "example-file"} + if local + else {"type": "input_text", "text": ""} + ) + assert len(observed) == (2 if local else 3) + views = [ + *observed, + str(item.output), + str(model.calls[1].input), + str(await session.get_items()), + str(run.to_input_list()), + run.to_state().to_string(), + ] + if not local: + views.append(str(item.custom_data)) + assert all(SAFE in view and RAW not in view for view in views) + else: + with pytest.raises(asyncio.CancelledError if outcome == "cancel" else UserError) as exc: + await collect() + assert ("same-length list or tuple of strings" in str(exc.value)) == ( + outcome in {"invalid", "short", "string"} + ) + error: BaseException | None = exc.value + seen = set() + while error is not None: + assert id(error) not in seen + seen.add(id(error)) + assert error.__cause__ is None + assert RAW not in str((error, vars(error))) + if outcome == "cancel": + # Python 3.10 chains empty cancellations across task boundaries. + assert type(error) is asyncio.CancelledError and not error.args + else: + assert error.__context__ is None + error = error.__context__ + assert RAW not in str(run.to_input_list()) + assert RAW not in run.to_state().to_string() + assert not observed and not events and len(model.calls) == 1 + assert RAW not in str(await session.get_items()) + assert effects + source.tool_calls == (["local"] if local else ["read.report"]) + [(call_id, mcp_target, slots, live)] = edits + assert call_id == "one" and mcp_target == (None if local else (source, "read.report")) + assert slots == ((RAW,) if local else (json.dumps({"draft": RAW}), "")) + spans = [span.export() for span in fetch_ordered_spans()] + otel = [span.to_json() for span in exporter.get_finished_spans()] + assert spans and otel + assert RAW not in str((spans, otel, live, caplog.text)) + if outcome in {"edit", "list"}: + assert SAFE in str(spans) + if detail: + assert SAFE in str(otel) + finally: + session.close() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("detail", [None, "content"]) +@pytest.mark.parametrize("failure", ["peer", "transport", "function", "unsupported"]) +async def test_selected_failures_never_become_success( + failure, detail, exporter, monkeypatch, caplog +): + monkeypatch.setattr(_debug, "DONT_LOG_TOOL_DATA", False) + caplog.set_level(logging.DEBUG, logger="openai.agents") + + unexpected = [] + + def forbidden(*args): + unexpected.append(args) + + @function_tool(failure_error_function=forbidden) + async def report(): + raise ValueError(RAW) + + class Peer(Source): + async def call_tool(self, tool_name, arguments, meta=None): + if failure == "transport": + raise RuntimeError(RAW) + return await super().call_tool(tool_name, arguments, meta) + + source = Peer(custom_data_extractor=forbidden, failure_error_function=forbidden) + if failure == "peer": + source.result["isError"] = True + if failure == "unsupported": + source.result["content"].append({"type": "audio", "mimeType": "audio/wav", "data": "AQID"}) + local = failure == "function" + model = model_for("report" if local else "read.report") + agent = Agent(name="reports", tools=[report], mcp_servers=[source], model=model) + config = RunConfig( + tracing={"operation_detail": detail} if detail else {}, + tool_execution=ToolExecutionConfig( + tool_text_transforms=[ + (report, forbidden) + if local + else MCPTextTransform(server=source, tool_name="read.report", edit=forbidden) + ], + prepare_tool_output=forbidden, + ), + ) + with pytest.raises(UserError) as exc: + await Runner.run(agent, "go", run_config=config) + assert not unexpected + assert "editor" not in str(exc.value) and "transform" not in str(exc.value) + if failure == "peer": + assert "MCP tool reported an error" in str(exc.value) + assert len(model.calls) == 1 and exc.value.__context__ is None and exc.value.__cause__ is None + spans = [s.export() for s in fetch_ordered_spans()] + otel = [s.to_json() for s in exporter.get_finished_spans()] + assert spans and otel and RAW not in str((spans, otel, exc.value, caplog.text)) + + +class Preview(BaseModel): + text: str + + +@pytest.mark.asyncio +@pytest.mark.parametrize("valid", [True, False]) +async def test_typed_result_has_one_validated_value_for_caller_and_model(valid): + @function_tool(output_type=Preview) + def report(): + return Preview(text=RAW) + + async def edit(call, slots): + assert json.loads(slots[0]) == {"text": RAW} + return (json.dumps({"text": SAFE if valid else 7, "ignored": RAW}),) + + model = model_for("report") + agent = Agent(name="reports", tools=[report], model=model) + config = RunConfig(tool_execution=ToolExecutionConfig(tool_text_transforms=[(report, edit)])) + if not valid: + with pytest.raises(UserError): + await Runner.run(agent, "go", run_config=config) + assert len(model.calls) == 1 + return + result = await Runner.run(agent, "go", run_config=config) + item = next(item for item in result.new_items if item.type == "tool_call_output_item") + assert item.output == {"text": SAFE} + assert SAFE in str(model.calls[1].input) + assert RAW not in result.to_state().to_string() + + +@pytest.mark.asyncio +async def test_exact_selection_across_parallel_calls_and_approval_resume(): + completed = asyncio.Event() + seen = [] + + @function_tool(needs_approval=True) + async def report(index: int): + return RAW + str(index) + + async def prepare(call): + return {"index": call.arguments["index"] + 1} + + async def edit(call, texts): + index = call.arguments.pop("index") + assert call.tool is report and texts == (RAW + str(index),) + if index == 1: + await asyncio.wait_for(completed.wait(), timeout=5) + else: + completed.set() + seen.append((call.call_id, index)) + return (SAFE + str(index),) + + model = ScriptedModel( + [ + [function_call("report", {"index": i}, call_id=str(i)) for i in range(2)], + [assistant_message("done")], + ] + ) + agent = Agent(name="reports", tools=[report], model=model) + config = RunConfig( + tool_execution=ToolExecutionConfig( + prepare_tool_input=prepare, tool_text_transforms=[(report, edit)] + ) + ) + paused = await Runner.run(agent, "go", run_config=config) + state = await RunState.from_string(agent, paused.to_state().to_string()) + for approval in state.get_interruptions(): + state.approve(approval) + result = await Runner.run(agent, state, run_config=config) + assert seen == [("1", 2), ("0", 1)] + outputs = { + i.raw_item["call_id"]: i.output + for i in result.new_items + if i.type == "tool_call_output_item" + } + assert outputs == {"0": SAFE + "1", "1": SAFE + "2"} + assert RAW not in result.to_state().to_string() + + +@pytest.mark.asyncio +async def test_unselected_peer_with_same_tool_name_keeps_legacy_behavior(): + selected, other = Source("Reports.A"), Source("Reports_A") + seen = [] + + async def legacy(call, output): + seen.append(output) + return "legacy" + + async def edit(*args): + pytest.fail("matched a different server") + + model = model_for("read.report") + agent = Agent(name="reports", mcp_servers=[other], model=model) + config = RunConfig( + tool_execution=ToolExecutionConfig( + tool_text_transforms=[ + MCPTextTransform(server=selected, tool_name="read.report", edit=edit) + ], + prepare_tool_output=legacy, + ) + ) + await Runner.run(agent, "go", run_config=config) + assert seen == [json.dumps({"draft": RAW})] + assert "legacy" in str(model.calls[1].input) + assert not selected.tool_calls + + +@pytest.mark.asyncio +@pytest.mark.parametrize("structured", [False, True]) +async def test_selected_image_only_result_keeps_media_position(structured): + peer = Source() + peer.use_structured_content = structured + peer.result["content"] = [IMAGE] + slots = [] + + async def edit(call, texts): + slots.append(texts) + return (SAFE,) if texts else () + + model = model_for("read.report") + agent = Agent(name="reports", mcp_servers=[peer], model=model) + config = RunConfig( + tool_execution=ToolExecutionConfig( + tool_text_transforms=[MCPTextTransform(server=peer, tool_name="read.report", edit=edit)] + ) + ) + result = await Runner.run(agent, "go", run_config=config) + item = next(item for item in result.new_items if item.type == "tool_call_output_item") + assert slots == ([(json.dumps({"draft": RAW}),)] if structured else [()]) + assert item.raw_item["output"][0]["image_url"] == "data:image/png;base64,AQID" + assert RAW not in result.to_state().to_string() + + +def test_invalid_or_duplicate_registration(): + peer = Source() + + async def edit(call, texts): + return texts + + @function_tool + def report() -> str: + return RAW + + entry = MCPTextTransform(server=peer, tool_name="read.report", edit=edit) + settings = TypeAdapter(ToolExecutionConfig).validate_python( + {"tool_text_transforms": [entry, (report, edit)]} + ) + assert settings.tool_text_transforms[0] is entry + assert settings.tool_text_transforms[1][0] is report + with pytest.raises(AttributeError): + entry.tool_name = "other" + with pytest.raises(TypeError): + MCPTextTransform(peer, "read.report", edit) # pyright: ignore[reportCallIssue] + with pytest.raises(ValueError, match="MCP server object") as error: + MCPTextTransform(server="example-server", tool_name="read.report", edit=edit) + assert "example-server" not in str(error.value) and "read.report" not in str(error.value) + for name in ("", " \t "): + with pytest.raises(ValueError, match="nonblank raw tool name"): + MCPTextTransform(server=peer, tool_name=name, edit=edit) + assert MCPTextTransform(server=peer, tool_name=" lookup ", edit=edit).tool_name == " lookup " + for malformed in [ + None, + [None], + [(peer, RAW, edit)], + [(peer, RAW), edit], + [((peer, RAW), edit)], + ]: + with pytest.raises(ValueError) as error: + ToolExecutionConfig(tool_text_transforms=malformed) + assert "(function_tool, edit_text)" in str(error.value) + assert "MCPTextTransform(" in str(error.value) + assert RAW not in str(error.value) + for entries in [ + [("read.report", edit)], + [MCPTextTransform(server=peer, tool_name="read.report", edit=edit)] * 2, + ]: + with pytest.raises(ValueError, match="tool_text_transforms"): + ToolExecutionConfig(tool_text_transforms=entries) + + +@pytest.mark.asyncio +async def test_cancelled_run_discards_a_late_edit(exporter): + started, finished = asyncio.Event(), asyncio.Event() + + async def edit(call, slots): + started.set() + try: + await asyncio.Event().wait() + except asyncio.CancelledError: + finished.set() + return slots + + source = Source() + model = model_for("read.report") + agent = Agent(name="reports", model=model, mcp_servers=[source]) + config = RunConfig( + tracing={"operation_detail": "content"}, + tool_execution=ToolExecutionConfig( + tool_text_transforms=[ + MCPTextTransform(server=source, tool_name="read.report", edit=edit) + ] + ), + ) + attempt = asyncio.create_task(Runner.run(agent, "go", run_config=config)) + await asyncio.wait_for(started.wait(), timeout=5) + attempt.cancel() + with pytest.raises(asyncio.CancelledError): + await attempt + await asyncio.wait_for(finished.wait(), timeout=5) + assert source.tool_calls == ["read.report"] and len(model.calls) == 1 + assert RAW not in str([s.export() for s in fetch_ordered_spans()]) + assert RAW not in str([s.to_json() for s in exporter.get_finished_spans()]) + + +@pytest.mark.asyncio +async def test_timeout_does_not_recover_a_selected_tool(): + unexpected = [] + + def forbidden(*args): + unexpected.append(args) + + @function_tool(timeout=0.01, timeout_error_function=forbidden) + async def report(): + await asyncio.Event().wait() + + model = model_for("report") + agent = Agent(name="reports", tools=[report], model=model) + config = RunConfig( + tool_execution=ToolExecutionConfig(tool_text_transforms=[(report, forbidden)]) + ) + with pytest.raises(UserError): + await Runner.run(agent, "go", run_config=config) + assert len(model.calls) == 1 + assert not unexpected + + +@pytest.mark.asyncio +async def test_namespace_copies_select_the_registered_function(): + @function_tool + async def report(): + return "status" + + (selected,) = tool_namespace(name="internal", description="Reports", tools=[report]) + (other,) = tool_namespace(name="public", description="Reports", tools=[report]) + + async def edit(call, texts): + assert call.tool is selected and call.tool_namespace == "internal" + return (SAFE,) + + model = ScriptedModel( + [ + [function_call("report", {}, namespace=n, call_id=n) for n in ("internal", "public")], + [assistant_message("done")], + ] + ) + agent = Agent(name="reports", tools=[selected, other], model=model) + config = RunConfig(tool_execution=ToolExecutionConfig(tool_text_transforms=[(selected, edit)])) + result = await Runner.run(agent, "go", run_config=config) + outputs = { + i.raw_item["call_id"]: i.output + for i in result.new_items + if i.type == "tool_call_output_item" + } + assert outputs == {"internal": SAFE, "public": "status"} + + +@pytest.mark.asyncio +@pytest.mark.parametrize("change, key", [(False, "amount"), (False, "cents"), (True, "amount")]) +async def test_typed_edit_preserves_converted_values_or_stops(change, key): + conversions = [] + + class Price(BaseModel): + amount: int = Field(serialization_alias=key) + label: str + internal: str = Field(default=RAW, exclude=True) + + @field_validator("amount") + @classmethod + def cents(cls, amount: int) -> int: + conversions.append(amount) + return amount * 100 + + @function_tool(output_type=Price) + def quote(): + return Price(amount=2, label="old") + + async def edit(call, texts): + assert json.loads(texts[0]) == {key: 200, "label": "old"} + return (texts[0].replace("old", "new"),) if change else texts + + model = model_for("quote") + config = RunConfig(tool_execution=ToolExecutionConfig(tool_text_transforms=[(quote, edit)])) + agent = Agent(name="reports", model=model, tools=[quote]) + if change: + with pytest.raises(UserError): + await Runner.run(agent, "go", run_config=config) + assert len(model.calls) == 1 + return + result = await Runner.run(agent, "go", run_config=config) + output = next(i for i in result.new_items if i.type == "tool_call_output_item") + assert conversions == [2] + assert output.output == json.loads(output.raw_item["output"]) == {key: 200, "label": "old"} + assert RAW not in result.to_state().to_string() + + +@pytest.mark.asyncio +async def test_empty_mcp_object_withholds_fallback_text(): + server = Source() + server.result["structuredContent"] = {} + + async def edit(call, texts): + assert texts == ("{}", "") + return texts + + model = model_for("read.report") + config = RunConfig( + tool_execution=ToolExecutionConfig( + tool_text_transforms=[ + MCPTextTransform(server=server, tool_name="read.report", edit=edit) + ] + ) + ) + result = await Runner.run( + Agent(name="reports", model=model, mcp_servers=[server]), "go", run_config=config + ) + assert RAW not in result.to_state().to_string() + assert IMAGE["data"] in str(model.calls[1].input) + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("point", "fallback"), + [ + ("response.output_item.done", True), + ("response.completed", False), + ("response.completed", True), + ], +) +async def test_stream_views_cannot_change_selected_arguments(point, fallback): + displayed = asyncio.Event() + classified = asyncio.Event() + + class Paused(ScriptedModel): + async def stream_response(self, *args, **kwargs): + async for event in super().stream_response(*args, **kwargs): + if event.type == "response.completed" and fallback: + event.response.output = [] + yield event + if event.type == point: + await asyncio.wait_for(displayed.wait(), 5) + + @function_tool + async def report(color: str): + return color + + async def edit(call, texts): + await asyncio.wait_for(classified.wait(), 5) + assert call.arguments == {"color": "Blue"} + return texts + + model = Paused([[function_call("report", {"color": "Blue"}, call_id="color")]]) + config = RunConfig(tool_execution=ToolExecutionConfig(tool_text_transforms=[(report, edit)])) + result = Runner.run_streamed( + Agent(name="reports", model=model, tools=[report], tool_use_behavior="stop_on_first_tool"), + "go", + run_config=config, + ) + async for event in result.stream_events(): + if event.type == "raw_response_event" and event.data.type == point: + item = ( + event.data.item + if point == "response.output_item.done" + else event.data.response.output[0] + ) + item.arguments = '{"color":"blue"}' + displayed.set() + if event.type == "run_item_stream_event" and event.name == "tool_called": + event.item.raw_item.arguments = '{"color":"green"}' + classified.set() + assert result.final_output == "Blue" + + +def _check_selected_exit(route): + import traceback + + class Peer(Source): + async def call_tool(self, tool_name, arguments, meta=None): + if route == "peer": + raise SystemExit(RAW) + return await super().call_tool(tool_name, arguments, meta) + + @function_tool(timeout=5 if route == "timed" else None) + async def report(): + if route == "timed": + raise SystemExit(7) + return RAW + + async def edit(call, texts): + if route == "interrupt": + raise KeyboardInterrupt(texts[0]) + raise SystemExit(texts[0]) + + peer = Peer() + remote = route.startswith("peer") + model = model_for("read.report" if remote else "report") + agent = Agent(name="reports", model=model, tools=[report], mcp_servers=[peer]) + config = RunConfig( + tracing_disabled=True, + tool_execution=ToolExecutionConfig( + tool_text_transforms=[ + MCPTextTransform(server=peer, tool_name="read.report", edit=edit) + if remote + else (report, edit) + ] + ), + ) + loop = asyncio.new_event_loop() + task = loop.create_task(Runner.run(agent, "go", run_config=config)) + expected = KeyboardInterrupt if route == "interrupt" else SystemExit + try: + # Each awaiting task can propagate the exit to the loop before Runner finishes. + while not task.done(): + with pytest.raises(expected) as exc: + loop.run_until_complete(task) + error = exc.value + if isinstance(error, SystemExit): + assert error.code == (7 if route == "timed" else 1) + assert error.__cause__ is None and error.__context__ is None + assert RAW not in str((error, vars(error))) + for frame, _ in traceback.walk_tb(error.__traceback__): + if frame.f_globals.get("__name__", "").startswith("agents."): + assert RAW not in str(frame.f_locals) + assert isinstance(task.exception(), expected) + assert len(model.calls) == 1 + finally: + loop.close() + + +def test_selected_exit_is_redacted_before_reaching_the_event_loop(): + import subprocess + import sys + + program = """ +from tests.test_tool_text_transforms import _check_selected_exit +for route in ("edit", "timed", "peer", "peer_edit", "interrupt"): + _check_selected_exit(route) +""" + result = subprocess.run( + [sys.executable, "-c", program], capture_output=True, text=True, timeout=30 + ) + assert result.returncode == 0, result.stderr + assert RAW not in result.stdout + result.stderr + + +@pytest.mark.asyncio +@pytest.mark.parametrize("invalid", ["status", "structured"]) +async def test_invalid_peer_result_stops_before_editing(invalid): + from agents.mcp._compat import MCP_V2 + + class Invalid(Source): + async def call_tool(self, *args, **kwargs): + result = await super().call_tool(*args, **kwargs) + status = "is_error" if MCP_V2 else "isError" + structured = "structured_content" if MCP_V2 else "structuredContent" + return result.model_copy( + update={status: 0} if invalid == "status" else {structured: []} + ) + + async def edit(call, texts): + pytest.fail("invalid peer result reached the editor") + + server = Invalid() + model = model_for("read.report") + config = RunConfig( + tool_execution=ToolExecutionConfig( + tool_text_transforms=[ + MCPTextTransform(server=server, tool_name="read.report", edit=edit) + ] + ) + ) + with pytest.raises(UserError): + await Runner.run( + Agent(name="reports", model=model, mcp_servers=[server]), "go", run_config=config + ) + assert len(model.calls) == len(server.tool_calls) == 1 + + +@pytest.mark.asyncio +async def test_model_adapter_retaining_a_call_cannot_change_accepted_arguments(): + class Model(ScriptedModel): + async def get_response(self, *args, **kwargs): + response = await super().get_response(*args, **kwargs) + self.saved = response.output[0] + return response + + class Hooks(RunHooks): + async def on_llm_end(self, context, agent, response): + model.saved.arguments = '{"color":"blue"}' + + @function_tool + async def report(color: str): + return color + + async def edit(call, texts): + assert call.arguments == {"color": "Blue"} + return texts + + model = Model([[function_call("report", {"color": "Blue"}, call_id="color")]]) + config = RunConfig(tool_execution=ToolExecutionConfig(tool_text_transforms=[(report, edit)])) + result = await Runner.run( + Agent(name="reports", model=model, tools=[report], tool_use_behavior="stop_on_first_tool"), + "go", + run_config=config, + hooks=Hooks(), + ) + assert result.final_output == "Blue" + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) +@pytest.mark.parametrize("resume", [False, True]) +async def test_second_wrapper_requires_exact_editor_before_effect(streamed, resume): + effects = [] + + def report(): + effects.append(True) + return RAW + + async def edit(call, texts): + return (SAFE,) + + selected = function_tool(report, needs_approval=resume) + replacement = function_tool(report, needs_approval=resume) + model = model_for("report") + agent = Agent(name="reports", tools=[selected if resume else replacement], model=model) + config = RunConfig(tool_execution=ToolExecutionConfig(tool_text_transforms=[(selected, edit)])) + request: str | RunState = "go" + if resume: + paused = await Runner.run(agent, request, run_config=config) + snapshot = paused.to_state().to_string() + agent.tools = [replacement] + request = await RunState.from_string(agent, snapshot) + request.approve(request.get_interruptions()[0]) + + with pytest.raises(UserError, match="exact tool_text_transforms target"): + if streamed: + stream = Runner.run_streamed(agent, request, run_config=config) + async for _ in stream.stream_events(): + pass + else: + await Runner.run(agent, request, run_config=config) + assert effects == [] and len(model.calls) == 1 + + +@pytest.mark.asyncio +async def test_same_name_on_distinct_agents_uses_only_exact_editors(): + effects = [] + + def make_report(name="report"): + @function_tool(name_override=name) + def report(): + effects.append(name) + return "original" + + return report + + first, second = make_report(), make_report() + other = make_report("other") + + async def edit(call, texts): + return (SAFE,) + + config = RunConfig(tool_execution=ToolExecutionConfig(tool_text_transforms=[(first, edit)])) + with pytest.raises(UserError, match="exact tool_text_transforms target"): + await Runner.run( + Agent(name="second", tools=[second], model=model_for("report")), "go", run_config=config + ) + assert not effects + config.tool_execution = ToolExecutionConfig( + tool_text_transforms=[(first, edit), (second, edit)] + ) + for tool, expected in [(first, SAFE), (second, SAFE), (other, "original")]: + agent = Agent(name="reports", tools=[tool], model=model_for(tool.name)) + result = await Runner.run(agent, "go", run_config=config) + assert ( + next(i.output for i in result.new_items if i.type == "tool_call_output_item") + == expected + ) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("restored", [False, True]) +@pytest.mark.parametrize("selection", ["stale", "missing", "current"]) +async def test_pending_mcp_edit_requires_current_exact_selector(restored, selection): + previous = Source(require_approval="always") + current = Source(require_approval="always") + + async def edit(call, texts): + assert call.mcp_target == (current, "read.report") + return tuple(SAFE for _ in texts) + + def config(server): + return RunConfig( + tool_execution=ToolExecutionConfig( + tool_text_transforms=[ + MCPTextTransform(server=server, tool_name="read.report", edit=edit) + ] + ) + ) + + model = model_for("read.report") + agent = Agent(name="reports", mcp_servers=[previous], model=model) + paused = await Runner.run(agent, "go", run_config=config(previous)) + state = paused.to_state() + snapshot = state.to_string() + agent.mcp_servers = [current] + if restored: + state = await RunState.from_string(agent, snapshot) + state.approve(state.get_interruptions()[0]) + if selection == "current": + result = await Runner.run(agent, state, run_config=config(current)) + assert current.tool_calls == ["read.report"] + assert SAFE in str(model.calls[-1].input) and RAW not in result.to_state().to_string() + else: + settings = config(previous) if selection == "stale" else RunConfig() + with pytest.raises(UserError, match="exact tool_text_transforms target"): + await Runner.run(agent, state, run_config=settings) + assert not current.tool_calls and len(model.calls) == 1 + assert not previous.tool_calls + + +@pytest.mark.asyncio +@pytest.mark.parametrize("historical", ["1.23", "1.24", "1.25"]) +async def test_pending_text_requirement_uses_current_checkpoint_schema(historical): + effects = [] + + @function_tool(needs_approval=True) + def report(): + effects.append(True) + return RAW + + async def edit(call, texts): + return (SAFE,) + + agent = Agent(name="reports", tools=[report], model=model_for("report")) + config = RunConfig(tool_execution=ToolExecutionConfig(tool_text_transforms=[(report, edit)])) + paused = await Runner.run(agent, "go", run_config=config) + snapshot = paused.to_state().to_json() + assert snapshot["$schemaVersion"] == "1.26" + snapshot["$schemaVersion"] = historical + with pytest.raises(UserError, match="require RunState schema 1.26"): + await RunState.from_json(agent, snapshot) + del snapshot["context"]["tool_invocations"]["one"]["requires_text_transform"] + state = await RunState.from_json(agent, snapshot) + assert not effects and state.to_json()["$schemaVersion"] == "1.26" + state.approve(state.get_interruptions()[0]) + result = await Runner.run(agent, state, run_config=config) + assert effects == [True] and RAW not in result.to_state().to_string() + + +@pytest.mark.asyncio +async def test_admitted_call_cannot_lose_editor_before_invocation(): + @function_tool + def report(): + pytest.fail("executed after the editor was removed") + + async def edit(call, texts): + return (SAFE,) + + settings = ToolExecutionConfig(tool_text_transforms=[(report, edit)]) + + class Hooks(RunHooks): + async def on_tool_start(self, context, agent, tool): + settings.tool_text_transforms = () + + agent = Agent(name="reports", tools=[report], model=model_for("report")) + with pytest.raises(UserError, match="exact tool_text_transforms target"): + await Runner.run(agent, "go", run_config=RunConfig(tool_execution=settings), hooks=Hooks()) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("rotate", [False, True]) +async def test_reconnected_server_with_same_name_needs_its_own_editor(rotate): + stale, current = Source(), Source() + + async def edit(call, texts): + assert call.mcp_target == (current, "read.report") + return tuple(SAFE for _ in texts) + + selected = MCPTextTransform(server=stale, tool_name="read.report", edit=edit) + agent = Agent(name="reports", mcp_servers=[current], model=model_for("read.report")) + config = RunConfig(tool_execution=ToolExecutionConfig(tool_text_transforms=[selected])) + + class Hooks(RunHooks): + async def on_llm_start(self, *args): + if rotate: + agent.mcp_servers = [stale] + + with pytest.raises(UserError, match="exact tool_text_transforms target"): + await Runner.run(agent, "go", run_config=config, hooks=Hooks()) + assert not current.tool_calls + agent.mcp_servers = [current] + agent.model = model_for("read.report") + config.tool_execution = ToolExecutionConfig( + tool_text_transforms=[ + selected, + MCPTextTransform(server=current, tool_name="read.report", edit=edit), + ] + ) + result = await Runner.run(agent, "go", run_config=config) + assert RAW not in result.to_state().to_string() + assert current.tool_calls == ["read.report"] and not stale.tool_calls + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) +@pytest.mark.parametrize( + "route", ["function", "mcp", "child", "namespaced", "copied", "reject_child"] +) +async def test_missing_editor_leaves_session_paused_for_corrected_retry(streamed, route): + from agents import ModelBehaviorError, ResumableSession + + from .memory.test_resumable_session import MemoryStore + + effects = [] + + @function_tool(needs_approval=True) + def report(): + effects.append(True) + return RAW + + async def edit(call, texts): + return tuple(SAFE for _ in texts) + + store = MemoryStore() + session = await ResumableSession.create(store) + peer = Source(require_approval="always") + mcp = route == "mcp" + model = model_for("read.report" if mcp else "report") + worker = Agent(name="reports", tools=[report], mcp_servers=[peer], model=model) + + def config(target): + entry = ( + MCPTextTransform(server=target, tool_name="read.report", edit=edit) + if mcp + else (target, edit) + ) + return RunConfig(tool_execution=ToolExecutionConfig(tool_text_transforms=[entry])) + + correct = config(peer if mcp else report) + namespace = "team" if route == "namespaced" else None + parent = Agent( + name="parent", + model=ScriptedModel( + [ + [function_call("delegate", {"input": "go"}, namespace=namespace, call_id="parent")], + [assistant_message("done")], + ] + ), + ) + + def configure(settings): + if route in ("child", "reject_child", "namespaced", "copied"): + delegate = worker.as_tool( + "delegate", "Delegate", run_config=settings, failure_error_function=None + ) + if namespace: + (delegate,) = tool_namespace(name=namespace, description="Team", tools=[delegate]) + if route == "copied": + delegate = replace(delegate) + parent.tools = [delegate] + return parent, correct if route == "copied" else RunConfig() + return worker, settings + + agent, settings = configure(correct) + paused = await Runner.run(agent, "go", session=session, run_config=settings) + if route == "child": + snapshot = paused.to_state().to_json() + child = snapshot["last_processed_response"]["functions"][0]["agent_run_state"] + assert child["$schemaVersion"] == snapshot["$schemaVersion"] == "1.26" + for node in (child, snapshot): + node["$schemaVersion"] = "1.25" + with pytest.raises(UserError, match="require RunState schema 1.26"): + await RunState.from_json(agent, snapshot) + node["$schemaVersion"] = "1.26" + assert not effects + saved = store.records[session.session_id] + + async def resume(settings, reject=False): + agent, settings = configure(settings) + restored = await ResumableSession.resume(store, session.session_id) + state = await restored.load_state(agent) + pending = state.get_interruptions()[0] + if reject: + state.reject(pending) + else: + state.approve(pending) + if streamed: + stream = Runner.run_streamed(agent, state, run_config=settings) + async for _ in stream.stream_events(): + pass + return stream + return await Runner.run(agent, state, run_config=settings) + + if route == "function": + worker.tools = [] + with pytest.raises(ModelBehaviorError, match="Tool report not found"): + await resume(correct) + assert store.records[session.session_id] == saved + assert not effects and len(model.calls) == 1 + worker.tools = [report] + + stale = config(Source()) if mcp else RunConfig() + with pytest.raises(UserError, match="exact tool_text_transforms target"): + await resume(stale) + assert store.records[session.session_id] == saved + assert not effects and not peer.tool_calls and len(model.calls) == 1 + if route == "reject_child": + result = await resume(stale, reject=True) + assert result.final_output == "done" and not effects + return + result = await resume(correct) + assert result.final_output == "done" and RAW not in result.to_state().to_string() + assert peer.tool_calls == (["read.report"] if mcp else []) + assert effects == ([] if mcp else [True]) + assert store.checkpoint(session.session_id)["status"] == "ready" + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) +@pytest.mark.parametrize("selector", ["read_report", "mcp_Reports__read_report", "read.reprot"]) +async def test_mcp_wrong_name_cannot_silently_skip_an_editor(streamed, selector): + peer = Source() + prefixed = selector.startswith("mcp_") + model = model_for(selector if prefixed else "read.report") + agent = Agent( + name="reports", + model=model, + mcp_servers=[peer], + mcp_config={"include_server_in_tool_names": prefixed}, + ) + + async def forbidden(call, texts): + pytest.fail("An alias must never bind an editor") + + config = RunConfig( + tool_execution=ToolExecutionConfig( + tool_text_transforms=[MCPTextTransform(server=peer, tool_name=selector, edit=forbidden)] + ) + ) + with pytest.raises(UserError, match="original tool name"): + if streamed: + result = Runner.run_streamed(agent, "go", run_config=config) + async for event in result.stream_events(): + assert RAW not in repr(event) + else: + await Runner.run(agent, "go", run_config=config) + assert not peer.tool_calls and len(model.calls) == 1 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("selector", ["read_report", "read.reprot"]) +async def test_mcp_wrong_name_added_on_resume_leaves_approval_retryable(selector): + from agents import ResumableSession + + from .memory.test_resumable_session import MemoryStore + + peer = Source(require_approval="always") + model = model_for("read.report") + agent = Agent(name="reports", model=model, mcp_servers=[peer]) + store = MemoryStore() + session = await ResumableSession.create(store) + await Runner.run(agent, "go", session=session) + saved = store.records[session.session_id] + resumed = await ResumableSession.resume(store, session.session_id) + state = await resumed.load_state(agent) + state.approve(state.get_interruptions()[0]) + + async def edit(call, texts): + return tuple(SAFE for _ in texts) + + def config(name): + return RunConfig( + tool_execution=ToolExecutionConfig( + tool_text_transforms=[MCPTextTransform(server=peer, tool_name=name, edit=edit)] + ) + ) + + with pytest.raises(UserError, match="original tool name"): + await Runner.run(agent, state, run_config=config(selector)) + assert store.records[session.session_id] == saved and not peer.tool_calls + result = await Runner.run(agent, state, run_config=config("read.report")) + assert peer.tool_calls == ["read.report"] and result.final_output == "done" + assert RAW not in store.records[session.session_id] + repr(model.calls[-1].input) + + +@pytest.mark.asyncio +async def test_mcp_raw_names_win_over_alias_collisions(): + peer = Source() + peer.add_tool("read_report", {}) + + async def edit(call, texts): + return tuple("edited " + call.mcp_target[1] for _ in texts) + + names = ("read_report", "read.report") + config = RunConfig( + tool_execution=ToolExecutionConfig( + tool_text_transforms=[ + MCPTextTransform(server=peer, tool_name=name, edit=edit) for name in names + ] + ) + ) + for name in names: + model = model_for(name) + agent = Agent(name="reports", model=model, mcp_servers=[peer]) + result = await Runner.run(agent, "go", run_config=config) + assert RAW not in repr(model.calls[-1].input) + assert "edited " + name in repr(result.to_input_list()) + assert peer.tool_calls == list(names) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) +@pytest.mark.parametrize("transport", ["http", "sse"]) +@pytest.mark.parametrize("selector", ["read.report", "read_report"]) +async def test_rotated_mcp_url_requires_current_server(streamed, transport, selector, monkeypatch): + from agents.mcp import MCPServerSse, MCPServerStreamableHttp + + server_cls = MCPServerSse if transport == "sse" else MCPServerStreamableHttp + previous, current = ( + server_cls(params={"url": f"https://user:{rev}@example.invalid/tools?q={rev}#{rev}"}) + for rev in ("old", "new") + ) + source = Source() + monkeypatch.setattr(current, "list_tools", source.list_tools) + monkeypatch.setattr(current, "call_tool", source.call_tool) + + async def edit(call, texts): + assert call.mcp_target == (current, "read.report") + return tuple(SAFE for _ in texts) + + stale = MCPTextTransform(server=previous, tool_name=selector, edit=edit) + model = model_for("read.report") + agent = Agent(name="reports", model=model, mcp_servers=[current]) + + async def run(entries): + settings = RunConfig(tool_execution=ToolExecutionConfig(tool_text_transforms=entries)) + if streamed: + stream = Runner.run_streamed(agent, "go", run_config=settings) + async for event in stream.stream_events(): + assert RAW not in repr(event) + return stream + return await Runner.run(agent, "go", run_config=settings) + + with pytest.raises(UserError, match="exact tool_text_transforms target"): + await run([stale]) + assert not source.tool_calls and len(model.calls) == 1 + agent.model = model = model_for("read.report") + result = await run( + [stale, MCPTextTransform(server=current, tool_name="read.report", edit=edit)] + ) + assert source.tool_calls == ["read.report"] + assert SAFE in repr(model.calls[-1].input) + assert RAW not in repr(model.calls[-1].input) + result.to_state().to_string() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) +@pytest.mark.parametrize("remote", [False, True]) +async def test_redact_text_after_selected_edit_on_approval_resume(streamed, remote, exporter): + from agents import ResumableSession + + from .memory.test_resumable_session import MemoryStore + + secret = "synthetic-editor-secret" + observed = [] + + @function_tool(output_type=Preview, needs_approval=True) + def report(): + return Preview(text=RAW) + + async def edit(call, slots): + assert RAW in slots[0] + return tuple(text.replace(RAW, secret) for text in slots) + + class Hooks(RunHooks): + async def on_tool_end(self, context, agent, tool, result): + observed.append(result) + + peer = Source(require_approval="always") + model = model_for("read.report" if remote else "report") + agent = Agent(name="reports", model=model, tools=[report], mcp_servers=[peer]) + settings = RunConfig( + redact_text=lambda text: text.replace(secret, SAFE), + tracing={"operation_detail": "content"}, + tool_execution=ToolExecutionConfig( + tool_text_transforms=[ + MCPTextTransform(server=peer, tool_name="read.report", edit=edit) + if remote + else (report, edit) + ] + ), + ) + store = MemoryStore() + session = await ResumableSession.create(store) + + async def run(value): + if not streamed: + return await Runner.run( + agent, value, session=session, run_config=settings, hooks=Hooks() + ) + result = Runner.run_streamed( + agent, value, session=session, run_config=settings, hooks=Hooks() + ) + async for event in result.stream_events(): + assert event.type != "raw_response_event" + if event.type == "run_item_stream_event" and event.name == "tool_output": + observed.append(event.item.output) + return result + + await run("go") + session = await ResumableSession.resume(store, session.session_id) + state = await session.load_state(agent) + state.approve(state.get_interruptions()[0]) + saved = store.records[session.session_id] + execution = settings.tool_execution + settings.tool_execution = None + with pytest.raises(RuntimeError, match="redacted"): + await run(state) + assert saved == store.records[session.session_id] and not peer.tool_calls and not observed + settings.tool_execution = execution + result = await run(state) + assert observed and all(SAFE in str(value) for value in observed) + assert SAFE in str(model.calls[-1].input) + if not remote: + assert next(i.output for i in result.new_items if i.type == "tool_call_output_item") == { + "text": SAFE + } + spans = [s.export() for s in fetch_ordered_spans()] + otel = [s.to_json() for s in exporter.get_finished_spans()] + assert spans and otel and SAFE not in str((spans, otel)) + published = str( + (observed, spans, otel, model.calls[-1].input, store.records, result.to_input_list()) + ) + assert secret not in published and RAW not in published + + +@pytest.mark.asyncio +async def test_mcp_missing_name_check_uses_this_servers_unfiltered_discovery(): + peer = Source() + peer.add_tool("sibling", {}) + + async def edit(call, texts): + return tuple(SAFE for _ in texts) + + entries = [MCPTextTransform(server=peer, tool_name="sibling", edit=edit)] + + async def dispatch(server): + model = model_for("read.report") + agent = Agent(name="reports", model=model, mcp_servers=[server]) + config = RunConfig(tool_execution=ToolExecutionConfig(tool_text_transforms=entries)) + await Runner.run(agent, "go", run_config=config) + return repr(model.calls[-1].input) + + assert RAW in await dispatch(peer) + peer.tool_filter = {"allowed_tool_names": ["read.report"]} + assert RAW in await dispatch(peer) + peer.tool_filter = None + peer.tools.pop() + assert RAW in await dispatch(Source()) + with pytest.raises(UserError, match="original tool name"): + await dispatch(peer) + assert peer.tool_calls == ["read.report"] * 2 + entries.append(MCPTextTransform(server=peer, tool_name="read.report", edit=edit)) + accepted = await dispatch(peer) + assert SAFE in accepted and RAW not in accepted + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) +@pytest.mark.parametrize("restored", [False, True]) +@pytest.mark.parametrize("deny_child", [False, True]) +async def test_missing_child_editor_blocks_approved_sibling_before_effects( + streamed, restored, deny_child +): + effects = [] + + @function_tool(needs_approval=True) + def sibling(): + effects.append("sibling") + return "ok" + + @function_tool(needs_approval=True) + def report(): + effects.append("report") + return RAW + + async def edit(call, texts): + return (SAFE,) + + child_model = model_for("report") + child = Agent(name="reports", tools=[report], model=child_model) + model = ScriptedModel( + [ + [ + function_call("sibling", {}, call_id="first"), + function_call("delegate", {"input": "go"}, call_id="parent"), + ], + [assistant_message("done")], + ] + ) + agent = Agent( + name="root", + model=model, + tools=[sibling, child.as_tool("delegate", "Delegate", failure_error_function=None)], + ) + config = RunConfig(tool_execution=ToolExecutionConfig(tool_text_transforms=[(report, edit)])) + paused = await Runner.run(agent, "go", run_config=config) + state = paused.to_state() + if restored: + state = await RunState.from_string(agent, state.to_string()) + assert len(state.get_interruptions()) == 2 + for item in state.get_interruptions(): + if deny_child and item.tool_name == "report": + state.reject(item) + else: + state.approve(item) + + async def resume(settings): + if streamed: + result = Runner.run_streamed(agent, state, run_config=settings) + async for _ in result.stream_events(): + pass + return result + return await Runner.run(agent, state, run_config=settings) + + if deny_child: + result = await resume(RunConfig()) + assert effects == ["sibling"] and result.final_output == "done" + return + + with pytest.raises(UserError, match="exact tool_text_transforms target"): + await resume(RunConfig()) + assert not effects and len(model.calls) == len(child_model.calls) == 1 + result = await resume(config) + assert sorted(effects) == ["report", "sibling"] + assert result.final_output == "done" and RAW not in repr(child_model.calls[-1].input) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) +@pytest.mark.parametrize("managed", [False, True]) +@pytest.mark.parametrize( + ("nested", "change"), + [ + (nested, change) + for nested in (False, True) + for change in ( + "grant", + "new_editor", + "replacement", + "disabled_at_load", + "absent_at_load", + "ambiguous", + "marked_switch", + ) + ] + + [ + (True, change) + for change in ("delegate", "new_child_editor", "new_child_budget", "marked_child") + ], +) +async def test_local_editor_preflight_keeps_approved_calls_retryable( + streamed, managed, nested, change +): + from agents import ResumableSession, RunBudget + + from .memory.test_resumable_session import MemoryStore + + effects = [] + available = True + + @function_tool(needs_approval=True) + def sibling(): + effects.append("sibling") + return "ok" + + @function_tool( + needs_approval=True, is_enabled=lambda ctx, agent: available and ctx.context["allowed"] + ) + def report(): + effects.append("report") + return RAW + + async def edit(call, texts): + effects.append("edit") + return (SAFE,) + + def config(target): + return RunConfig(tool_execution=ToolExecutionConfig(tool_text_transforms=[(target, edit)])) + + model = model_for("report") + child = Agent(name="reports", model=model, tools=[report]) + agent = child + settings = ( + config(report) + if change in ("grant", "marked_switch", "ambiguous", "marked_child") + else RunConfig() + ) + outer = RunConfig() if nested else settings + if nested: + parent_model = ScriptedModel( + [ + [ + function_call("sibling", {}, call_id="first"), + function_call("delegate", {"input": "go"}, call_id="parent"), + ], + [assistant_message("done")], + ] + ) + agent = Agent( + name="parent", + model=parent_model, + tools=[ + sibling, + Agent(name="other").as_tool( + "delegate", + "Other", + is_enabled=False if change == "new_editor" else lambda *_: False, + ), + child.as_tool( + "delegate", + "Ask", + failure_error_function=None, + run_config=settings, + is_enabled=lambda ctx, agent: ctx.context.get("delegate", True), + ), + ], + ) + + switch = change in ("new_child_editor", "new_child_budget", "marked_child") + if switch: + alternate = RunConfig() + agent.tools[1] = child.as_tool( + "delegate", + "Other", + failure_error_function=None, + run_config=alternate, + is_enabled=lambda ctx, agent: not ctx.context.get("delegate", True), + ) + + store = MemoryStore() + session = await ResumableSession.create(store) if managed else None + paused = await Runner.run( + agent, + "go", + context={"allowed": True}, + session=session, + run_config=outer, + ) + if session: + saved = store.records[session.session_id] + session = await ResumableSession.resume(store, session.session_id) + available = change != "disabled_at_load" + if change == "absent_at_load": + child.tools = [] + state = ( + await session.load_state(agent) + if session + else await RunState.from_string(agent, paused.to_state().to_string()) + ) + available = True + child.tools = [report] + for item in state.get_interruptions(): + state.approve(item) + + async def resume(target, *, allowed=True, delegate=True): + context = {"allowed": allowed, "delegate": delegate} + recipient = alternate if switch and not delegate else settings + if change == "new_child_budget" and not delegate: + recipient.budget = RunBudget(max_model_calls=2) + else: + recipient.tool_execution = config(target).tool_execution + if streamed: + result = Runner.run_streamed(agent, state, context=context, run_config=outer) + async for _ in result.stream_events(): + pass + return result + return await Runner.run(agent, state, context=context, run_config=outer) + + if change == "replacement": + child.tools = [replace(report), replace(report, is_enabled=False)] + if change == "ambiguous": + child.tools.append(replace(report)) + stale = ( + replace(report) + if change in ("new_editor", "disabled_at_load", "absent_at_load", "new_child_editor") + else report + ) + if change == "marked_switch": + stale = replace(report) + child.tools = [stale] + with pytest.raises( + UserError, + match="enabled .*tool|exact tool_text_transforms|Reload the paused state|same RunBudget", + ): + await resume(stale, allowed=change != "grant", delegate=not switch and change != "delegate") + if session: + assert store.records[session.session_id] == saved + assert not effects and len(model.calls) == 1 + if nested: + assert len(parent_model.calls) == 1 + if change == "ambiguous": + child.tools[-1].is_enabled = lambda ctx, agent: not ctx.context["allowed"] + if change == "marked_switch": + child.tools = [report] + result = await resume(child.tools[0], delegate=change != "new_child_editor") + assert sorted(effects) == (["edit", "report", "sibling"] if nested else ["edit", "report"]) + assert result.final_output == "done" + assert SAFE in repr(model.calls[-1].input) + assert RAW not in result.to_state().to_string() + repr(model.calls[-1].input) + if session: + assert RAW not in store.records[session.session_id] + + +@pytest.mark.asyncio +async def test_namespace_copy_requires_exact_registration_for_its_source(): + effects = [] + + @function_tool + def report() -> str: + effects.append("called") + return RAW + + async def edit(call, texts): + return (SAFE,) + + (named,) = tool_namespace(name="desk", description="Reports", tools=[report]) + + async def dispatch(entries): + model = ScriptedModel([[function_call("report", {}, namespace="desk", call_id="c")]]) + agent = Agent( + name="reports", tools=[named], model=model, tool_use_behavior="stop_on_first_tool" + ) + config = RunConfig(tool_execution=ToolExecutionConfig(tool_text_transforms=entries)) + return (await Runner.run(agent, "go", run_config=config)).final_output + + with pytest.raises(UserError, match="tool_namespace"): + await dispatch([(report, edit)]) + assert not effects + assert await dispatch([(report, edit), (named, edit)]) == SAFE + assert await dispatch([(replace(report), edit)]) == RAW + + +@pytest.mark.asyncio +async def test_filtered_stdio_catalog_distinguishes_hidden_name_from_typo(): + import sys + from pathlib import Path + + from agents.mcp import MCPServerStdio + + calls = [] + + async def edit(call, texts): + return (SAFE,) + + async with MCPServerStdio( + params={ + "command": sys.executable, + "args": [str(Path(__file__).parent / "mcp/servers/paginated.py")], + }, + tool_filter={"allowed_tool_names": ["first_page_tool"]}, + tool_meta_resolver=lambda call: calls.append(call.tool_name), + ) as peer: + + async def dispatch(name): + model = model_for("first_page_tool") + agent = Agent(name="reports", mcp_servers=[peer], model=model) + config = RunConfig( + tool_execution=ToolExecutionConfig( + tool_text_transforms=[MCPTextTransform(server=peer, tool_name=name, edit=edit)] + ) + ) + run = Runner.run_streamed(agent, "go", run_config=config) + async for _ in run.stream_events(): + pass + return repr(model.calls[-1].input) + + with pytest.raises(UserError, match="original tool name"): + await dispatch("first_page_typo") + assert not calls + assert "called:first_page_tool" in await dispatch("second_page_tool") + assert calls == ["first_page_tool"]