From 079bb0279a7b41781f86561acf76d66889508134 Mon Sep 17 00:00:00 2001 From: Mark Stuart Date: Fri, 20 Nov 2026 22:02:37 -0800 Subject: [PATCH 1/7] feat: add per-run request, token and estimated cost limits --- src/agents/__init__.py | 3 + src/agents/agent.py | 5 + src/agents/extensions/models/any_llm_model.py | 2 + src/agents/extensions/models/litellm_model.py | 1 + .../openai_responses_compaction_session.py | 10 +- src/agents/models/chatcmpl_stream_handler.py | 6 +- src/agents/models/openai_chatcompletions.py | 1 + src/agents/run.py | 9 +- src/agents/run_budget.py | 328 ++++++++++ src/agents/run_config.py | 9 + src/agents/run_context.py | 16 +- src/agents/run_internal/model_retry.py | 4 + src/agents/run_internal/resumable_session.py | 5 + src/agents/run_internal/run_loop.py | 22 +- src/agents/run_state.py | 21 +- src/agents/usage.py | 35 +- tests/test_run_budget.py | 604 ++++++++++++++++++ 17 files changed, 1063 insertions(+), 18 deletions(-) create mode 100644 src/agents/run_budget.py create mode 100644 tests/test_run_budget.py diff --git a/src/agents/__init__.py b/src/agents/__init__.py index 7e6885c971..fec95ed502 100644 --- a/src/agents/__init__.py +++ b/src/agents/__init__.py @@ -126,6 +126,7 @@ ToolNameCollisionPolicy, ToolNotFoundBehavior, ) +from .run_budget import RunBudget, RunBudgetError from .run_context import AgentHookContext, RunContextWrapper, TContext from .run_error_handlers import ( RunErrorData, @@ -492,6 +493,8 @@ def enable_verbose_stdout_logging() -> None: "RunResult", "RunResultStreaming", "ResponsesWebSocketSession", + "RunBudget", + "RunBudgetError", "RunConfig", "OutputGuardrailBlockedMessageArgs", "OutputGuardrailBlockedMessageFormatter", diff --git a/src/agents/agent.py b/src/agents/agent.py index 48fea87c0d..fdc9971e81 100644 --- a/src/agents/agent.py +++ b/src/agents/agent.py @@ -797,6 +797,9 @@ async def _run_agent_impl(context: ToolContext, input_json: str) -> Any: resolved_run_config = run_config if resolved_run_config is None and isinstance(context, ToolContext): resolved_run_config = context.run_config + if resolved_run_config is not None and resolved_run_config.budget is not None: + resolved_run_config = copy.copy(resolved_run_config) + resolved_run_config.budget = None tool_state_scope_id = get_agent_tool_state_scope(context) if isinstance(context, ToolContext): # Use a fresh ToolContext to avoid sharing approval state with parent runs. @@ -1140,6 +1143,8 @@ async def enqueue_stream_events() -> None: return run_result.final_output + # Keep the live policy with the implementation, which survives tool rebinding. + cast(Any, _run_agent_impl).__agents_run_config__ = run_config run_agent_tool = _build_wrapped_function_tool( name=tool_name_resolved, description=tool_description_resolved, diff --git a/src/agents/extensions/models/any_llm_model.py b/src/agents/extensions/models/any_llm_model.py index b6f07520af..19c5b70b0e 100644 --- a/src/agents/extensions/models/any_llm_model.py +++ b/src/agents/extensions/models/any_llm_model.py @@ -465,6 +465,7 @@ async def _get_response_via_responses( # The request completed, so it counts even when the provider omits usage. else Usage(requests=1) ) + usage._total_missing = response.usage is None or response.usage.total_tokens is None span_response.span_data.usage = model_usage_to_span_usage(usage) @@ -672,6 +673,7 @@ async def _get_response_via_chat( # The request completed, so it counts even when the provider omits usage. else Usage(requests=1) ) + usage._total_missing = response.usage is None or response.usage.total_tokens is None # Some providers signal a filtered non-streaming completion only through # finish_reason="content_filter" and an otherwise empty message. Preserve diff --git a/src/agents/extensions/models/litellm_model.py b/src/agents/extensions/models/litellm_model.py index 4732874f5f..507b2494ca 100644 --- a/src/agents/extensions/models/litellm_model.py +++ b/src/agents/extensions/models/litellm_model.py @@ -325,6 +325,7 @@ async def get_response( # The request completed, so it counts even when the provider omits usage. else Usage(requests=1) ) + usage._total_missing = response_usage is None or response_usage.total_tokens is None else: usage = Usage(requests=1) logger.warning("No usage information returned from Litellm") diff --git a/src/agents/memory/openai_responses_compaction_session.py b/src/agents/memory/openai_responses_compaction_session.py index cc863e5736..ebc40ba2d0 100644 --- a/src/agents/memory/openai_responses_compaction_session.py +++ b/src/agents/memory/openai_responses_compaction_session.py @@ -479,8 +479,14 @@ async def _run_compaction_locked( compacted = await self.client.responses.compact(**compact_kwargs) compacted_usage = getattr(compacted, "usage", None) - if wrapper is not None and compacted_usage is not None: - wrapper.usage.add(_response_usage_to_usage(compacted_usage)) + if wrapper is not None: + usage = ( + _response_usage_to_usage(compacted_usage) if compacted_usage is not None else None + ) + if wrapper._budget is not None: + wrapper._budget.observe(usage) + if usage is not None: + wrapper.usage.add(usage) output_items = _strip_orphaned_assistant_ids( _normalize_compaction_output_items(compacted.output or []) diff --git a/src/agents/models/chatcmpl_stream_handler.py b/src/agents/models/chatcmpl_stream_handler.py index b0c041f9cb..60b138734e 100644 --- a/src/agents/models/chatcmpl_stream_handler.py +++ b/src/agents/models/chatcmpl_stream_handler.py @@ -1369,7 +1369,7 @@ def _build_response_usage(usage: CompletionUsage | None) -> ResponseUsage | None """Convert the streamed provider usage into a Responses usage payload.""" if usage is None: return None - return ResponseUsage( + result = ResponseUsage( input_tokens=usage.prompt_tokens or 0, output_tokens=usage.completion_tokens or 0, total_tokens=usage.total_tokens or 0, @@ -1386,3 +1386,7 @@ def _build_response_usage(usage: CompletionUsage | None) -> ResponseUsage | None cache_write_tokens=_cache_write_tokens(usage.prompt_tokens_details), ), ) + if usage.total_tokens is None: + # Keep the public numeric default without reporting a measured zero. + object.__setattr__(result, "_agents_sdk_total_missing", True) + return result diff --git a/src/agents/models/openai_chatcompletions.py b/src/agents/models/openai_chatcompletions.py index 8528d0ac37..af457c38b5 100644 --- a/src/agents/models/openai_chatcompletions.py +++ b/src/agents/models/openai_chatcompletions.py @@ -320,6 +320,7 @@ async def get_response( # The request completed, so it counts even when the provider omits usage. else Usage(requests=1) ) + usage._total_missing = response.usage is None or response.usage.total_tokens is None # Record the request and token usage on the span before the terminal # branches below, so a ModelBehaviorError raised for a truncated empty diff --git a/src/agents/run.py b/src/agents/run.py index 57ca88bbe2..ed224bc2ba 100644 --- a/src/agents/run.py +++ b/src/agents/run.py @@ -44,6 +44,7 @@ from .memory import Session from .memory.resumable_session import ResumableSession from .result import RunResult, RunResultStreaming +from .run_budget import _prepare_budget from .run_config import ( DEFAULT_MAX_TURNS, CallModelData, @@ -657,6 +658,7 @@ async def _run_impl( run_state: RunState[TContext] | None = ( cast(RunState[TContext], input) if is_resumed_state else None ) + budget = _prepare_budget(run_config, starting_agent, run_state, session) resolved_reasoning_item_id_policy: ReasoningItemIdPolicy | None = ( run_config.reasoning_item_id_policy if run_config.reasoning_item_id_policy is not None @@ -716,7 +718,7 @@ async def _run_impl( previous_response_id=previous_response_id, auto_previous_response_id=auto_previous_response_id, ) - context_wrapper = ensure_context_wrapper(context) + context_wrapper = ensure_context_wrapper(context)._for_new_root(budget) if isinstance(session, ResumableRun): await session.begin(input) context_wrapper._resolve_function_approval_owners(starting_agent) @@ -2671,6 +2673,9 @@ def run_streamed( if run_config.tracing_disabled else contextlib.nullcontext(), ): + budget = _prepare_budget( + run_config, starting_agent, input if isinstance(input, RunState) else None, session + ) # Handle RunState input is_resumed_state = isinstance(input, RunState) run_state: RunState[TContext] | None = None @@ -2739,7 +2744,7 @@ def run_streamed( previous_response_id=previous_response_id, auto_previous_response_id=auto_previous_response_id, ) - context_wrapper = ensure_context_wrapper(context) + context_wrapper = ensure_context_wrapper(context)._for_new_root(budget) context_wrapper._resolve_function_approval_owners(starting_agent) set_agent_tool_state_scope(context_wrapper, uuid4().hex) # input_for_state is the same as input_for_result here diff --git a/src/agents/run_budget.py b/src/agents/run_budget.py new file mode 100644 index 0000000000..e98e16ee2d --- /dev/null +++ b/src/agents/run_budget.py @@ -0,0 +1,328 @@ +"""Limits on model admissions and observed response usage in a Runner run.""" + +from __future__ import annotations + +import copy +import inspect +from collections.abc import Callable, Iterable +from dataclasses import dataclass, field, replace +from typing import TYPE_CHECKING, Any, Literal + +from .exceptions import AgentsException, UserError +from .usage import Usage + +if TYPE_CHECKING: + from .agent import Agent + from .memory import Session + from .models.interface import Model + from .run_config import RunConfig + from .run_state import RunState + from .tool import Tool + + +def _valid_limit(value: object) -> bool: + return type(value) is int and 0 <= value <= 2**53 - 1 + + +@dataclass(frozen=True) +class RunBudget: + """Limits for one Python Runner root, including handoffs and approval resumes. + + Set at least one integer limit from zero through 2**53 - 1. Zero blocks the first + admission. A response may finish above a limit. The next admission then fails. + + Each new regular model invocation counts once, including follow-ups and corrections. + Runner and transport retries, compaction, approval replies and replay add no admissions. + Agent tools and other nested runs have independent budgets. Native sampling through + CodexProvider and hosted multi-agent orchestration are unsupported. Independent + Runner calls, guardrails, sandbox memory, and tool-owned clients are outside the + root. These limits cannot bound physical sends or billing. + + Tokens and estimated cost use completed root responses and reported session compactions. + Failed attempts, child responses and cumulative snapshots are excluded. Only usage + visible to the SDK counts. Adapters that replace missing totals with explicit zeros + make those totals indistinguishable from measured zero. Before the next + admission, the synchronous estimator receives each completion's Usage and returns + millionths of a US dollar in the same integer range, or None for an unknown estimate. + Missing or negative totals, a missing estimator or unknown cost block the next admission + when needed by a limit. Set missing_usage="continue" to use only known values. + + Pass the budget to RunConfig(budget=...) on each call, including resume. RunBudgetError + identifies a blocked admission. Estimated-cost budgets support in-memory + continuation only. ResumableSession rejects cost limits anywhere in the agent graph. + A paused child budget requires a unique, enabled binding in its parent's tools. + Keep the tool graph and policies stable during each invocation. + Child budget errors follow the agent tool's error policy. An unhandled tool failure + leaves a durable session active for reconciliation. A new run starts with fresh counters. + """ + + max_requests: int | None = None + max_tokens: int | None = None + max_estimated_cost_micros: int | None = None + estimate_cost_micros: Callable[[Usage], int | None] | None = None + missing_usage: Literal["stop", "continue"] = "stop" + + def __post_init__(self) -> None: + limits = (self.max_requests, self.max_tokens, self.max_estimated_cost_micros) + if all(limit is None for limit in limits): + raise ValueError("RunBudget requires at least one limit.") + if any(limit is not None and not _valid_limit(limit) for limit in limits): + raise ValueError("RunBudget limits must be integers from zero through 2**53 - 1.") + if self.missing_usage not in ("stop", "continue"): + raise ValueError("RunBudget.missing_usage must be 'stop' or 'continue'.") + if self.estimate_cost_micros is not None and ( + not callable(self.estimate_cost_micros) + or inspect.iscoroutinefunction(self.estimate_cost_micros) + ): + raise TypeError("RunBudget.estimate_cost_micros must be a synchronous callable.") + + +class _BudgetCheckpointError(UserError): + """A budget failure that must also abort an enclosing agent-tool checkpoint.""" + + +class RunBudgetError(AgentsException): + """A blocked admission. The code identifies the reason.""" + + def __init__( + self, + code: Literal[ + "run_budget_exceeded", "run_budget_usage_unavailable", "run_budget_invalid_estimate" + ], + ): + self.code = code + super().__init__(code) + + +def _estimate(estimator: Callable[[Usage], int | None], usage: Usage) -> int | None: + try: + value = estimator(usage) + if value is None or _valid_limit(value): + return value + if inspect.iscoroutine(value): + value.close() + except Exception: + pass + raise RunBudgetError("run_budget_invalid_estimate") + + +@dataclass +class _BudgetState: + limits: RunBudget + requests: int = 0 + tokens: int = 0 + unavailable: bool = False + cost: int = 0 + pending: list[Usage] = field(default_factory=list) + + def observe(self, usage: Usage | None) -> None: + limits = self.limits + if limits.max_tokens is None and limits.max_estimated_cost_micros is None: + return + if ( + usage is None + or (usage._total_missing and usage.total_tokens == 0) + or usage.total_tokens < 0 + ): + self.unavailable = True + return + self.tokens += usage.total_tokens + if limits.max_estimated_cost_micros is not None: + if limits.estimate_cost_micros is None: + self.unavailable = True + else: + self.pending.append(copy.deepcopy(usage)) + + def check(self) -> None: + limits = self.limits + for count, ceiling in ( + (self.requests, limits.max_requests), + (self.tokens, limits.max_tokens), + (self.cost, limits.max_estimated_cost_micros), + ): + if ceiling is not None and count >= ceiling: + raise RunBudgetError("run_budget_exceeded") + if self.unavailable and limits.missing_usage == "stop": + raise RunBudgetError("run_budget_usage_unavailable") + while self.pending: + assert limits.estimate_cost_micros is not None + assert limits.max_estimated_cost_micros is not None + estimate = _estimate(limits.estimate_cost_micros, self.pending[0]) + self.pending.pop(0) + if estimate is None: + self.unavailable = True + if limits.missing_usage == "stop": + raise RunBudgetError("run_budget_usage_unavailable") + else: + self.cost += estimate + if self.cost >= limits.max_estimated_cost_micros: + raise RunBudgetError("run_budget_exceeded") + + def checkpoint(self) -> dict[str, Any]: + if self.limits.max_estimated_cost_micros is not None: + raise _BudgetCheckpointError("Cannot serialize an estimated-cost budget.") + return { + "max_requests": self.limits.max_requests, + "max_tokens": self.limits.max_tokens, + "missing_usage": self.limits.missing_usage, + "requests": self.requests, + "tokens": self.tokens, + "unavailable": self.unavailable, + } + + @classmethod + def restore(cls, data: Any) -> _BudgetState: + if not isinstance(data, dict) or data.keys() != { + "max_requests", + "max_tokens", + "missing_usage", + "requests", + "tokens", + "unavailable", + }: + raise _BudgetCheckpointError("Invalid run budget checkpoint.") + if ( + any(type(data[k]) is not int or data[k] < 0 for k in ("requests", "tokens")) + or type(data["unavailable"]) is not bool + ): + raise _BudgetCheckpointError("Invalid run budget consumption.") + try: + limits = RunBudget( + max_requests=data["max_requests"], + max_tokens=data["max_tokens"], + missing_usage=data["missing_usage"], + ) + except ValueError: + raise _BudgetCheckpointError("Invalid run budget limits.") from None + return cls(limits, data["requests"], data["tokens"], data["unavailable"]) + + +def _check_model(model: object) -> None: + from .extensions.experimental.hosted_multi_agent import OpenAIHostedMultiAgentModel + from .models.codex import CodexProvider, _CodexModel + + if isinstance(model, OpenAIHostedMultiAgentModel): + raise UserError("RunBudget cannot isolate root usage in hosted multi-agent runs.") + if isinstance(model, (CodexProvider, _CodexModel)): + raise UserError("RunBudget cannot enforce native sampling limits with CodexProvider.") + + +def _tool_config(tool: Tool) -> RunConfig | None: + invoker = getattr(tool, "on_invoke_tool", None) + impl = getattr(invoker, "_invoke_tool_impl", None) + return getattr(impl, "__agents_run_config__", None) + + +def _check_portable(limits: RunBudget | None) -> None: + if limits is not None and limits.max_estimated_cost_micros is not None: + raise UserError("ResumableSession cannot checkpoint an estimated-cost budget.") + + +def _check_tools(tools: Iterable[Tool]) -> None: + for tool in tools: + config = _tool_config(tool) + if config is not None: + _check_portable(config.budget) + + +async def _admit( + budget: _BudgetState | None, model: Model, session: Session | None, tools: Iterable[Tool] +) -> None: + from .run_internal.resumable_session import ResumableRun + + try: + if isinstance(session, ResumableRun): + # Include tools resolved dynamically after the initial graph check. + _check_tools(tools) + if budget is not None: + _check_model(model) + budget.check() + budget.requests += 1 + except (RunBudgetError, UserError): + if isinstance(session, ResumableRun): + await session.finish_budget_stop() + raise + + +def _effective_limits(config: RunConfig | None) -> RunBudget | None: + limits = config.budget if config is not None else None + if ( + limits is not None + and limits.max_estimated_cost_micros is None + and limits.estimate_cost_micros is not None + ): + return replace(limits, estimate_cost_micros=None) + return limits + + +def _check_resume(state: RunState[Any], limits: RunBudget | None) -> 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 + + 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 without running enablement callbacks. + 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 = (_effective_limits(_tool_config(tool)) for tool in bindings) + policy = next((value for value in policies if value is not None), None) + if _check_resume(child, policy): + if ( + len(bindings) != 1 + or bindings[0].is_enabled is False + or bindings[0]._agent_instance is not action.function_tool._agent_instance + ): + raise UserError("A pending RunBudget requires the same unique agent tool.") + budgeted = True + return budgeted + + +def _prepare_budget( + config: RunConfig, agent: Agent[Any], state: RunState[Any] | None, session: Session | None +) -> _BudgetState | None: + from .models.interface import Model + from .run_internal.resumable_session import ResumableRun + + limits = _effective_limits(config) + if state is not None: + _check_resume(state, limits) + current = ( + state._current_agent if state is not None and state._current_agent is not None else agent + ) + if isinstance(session, ResumableRun): + from ._run_state_agent_identity import _iter_agent_graph + + _check_portable(limits) + for reachable in _iter_agent_graph(current): + _check_tools(reachable.tools) + if limits is None: + return None + model = config.model if config.model is not None else current.model + _check_model(model if isinstance(model, Model) else config.model_provider) + if state is not None: + assert state._context is not None + return state._context._budget + budget = _BudgetState(limits) + budget.check() + return budget diff --git a/src/agents/run_config.py b/src/agents/run_config.py index c65d9cbd75..ffac97aa3a 100644 --- a/src/agents/run_config.py +++ b/src/agents/run_config.py @@ -28,6 +28,7 @@ from .model_settings import ModelSettings, _coerce_model_settings, _declared_model_settings_type from .models.interface import Model, ModelProvider from .models.multi_provider import MultiProvider +from .run_budget import RunBudget from .run_context import TContext from .run_error_handlers import RunErrorHandlers from .tracing import TracingConfig @@ -589,6 +590,9 @@ class RunConfig: output and guardrail ``output_info`` are never passed to the formatter. """ + budget: RunBudget | None = None + """Optional limits on root model admissions and observed response usage.""" + if TYPE_CHECKING: def __init__( @@ -620,9 +624,14 @@ def __init__( output_guardrail_blocked_message: ( str | OutputGuardrailBlockedMessageFormatter | None ) = None, + budget: RunBudget | dict[str, Any] | None = None, ) -> None: ... def __post_init__(self) -> None: + if self.budget is not None: + self.budget = coerce_dataclass_config( + self.budget, RunBudget, parameter_name="run_config.budget" + ) if self.tool_name_collision_policy not in ("warn", "error"): raise ValueError("tool_name_collision_policy must be either 'warn' or 'error'") blocked_message = self.output_guardrail_blocked_message diff --git a/src/agents/run_context.py b/src/agents/run_context.py index 77ae747a8e..480971f8db 100644 --- a/src/agents/run_context.py +++ b/src/agents/run_context.py @@ -5,7 +5,7 @@ import weakref from collections.abc import Callable, Mapping from dataclasses import dataclass, field -from typing import TYPE_CHECKING, Annotated, Any, Generic +from typing import TYPE_CHECKING, Annotated, Any, Generic, cast from uuid import uuid4 from pydantic import ( @@ -39,6 +39,7 @@ tool_output_identity, ) from .exceptions import ModelBehaviorError, UserError +from .run_budget import _BudgetState from .usage import Usage if TYPE_CHECKING: @@ -211,6 +212,16 @@ class RunContextWrapper(Generic[TContext]): repr=False, ) + # Runtime-only state. RunState owns its portable representation. + _budget = cast("_BudgetState | None", None) + + def _for_new_root(self, budget: _BudgetState | None) -> RunContextWrapper[TContext]: + if budget is None and self._budget is None: + return self + root = copy.copy(self) + root._budget = budget + return root + @model_validator(mode="wrap") @classmethod def _restore_converted_tool_state( @@ -286,6 +297,9 @@ def _copy_for_run_state(self) -> RunContextWrapper[TContext]: # checkpoint's tokens land on every other checkpoint and on the result # the checkpoints came from. copied.usage = copy.deepcopy(self.usage) + if self._budget is not None: + copied._budget = copy.copy(self._budget) + copied._budget.pending = copy.deepcopy(self._budget.pending) copied._approvals = copy.deepcopy(self._approvals) copied._tool_invocations = copy.deepcopy(self._tool_invocations) copied._restored_unbound_approval_call_ids = set(self._restored_unbound_approval_call_ids) diff --git a/src/agents/run_internal/model_retry.py b/src/agents/run_internal/model_retry.py index 4f23b729a8..b19f2864a0 100644 --- a/src/agents/run_internal/model_retry.py +++ b/src/agents/run_internal/model_retry.py @@ -35,6 +35,7 @@ _coerce_backoff_settings, retry_policy_retries_safe_transport_errors, ) +from ..run_budget import _BudgetState from ..tracing._model import ModelRetrySpans, model_retry_scope from ..usage import RequestUsage, Usage from ..util._error_tracing import mark_model_timeout_task @@ -606,6 +607,7 @@ async def get_response_with_retry( timeout: float | None = None, replay_unsafe_request: bool = False, reported_usage: dict[int, Usage] | None = None, + budget: _BudgetState | None = None, ) -> ModelResponse: request_attempt = 1 policy_attempt = 1 @@ -639,6 +641,8 @@ async def get_response_with_retry( model_retry_scope(model_spans, request_attempt), ): response = await _await_model_attempt(get_response(), timeout) + if budget is not None: + budget.observe(response.usage) response.usage = apply_retry_attempt_usage( response.usage, request_attempt - 1, reported_usage ) diff --git a/src/agents/run_internal/resumable_session.py b/src/agents/run_internal/resumable_session.py index a55fba5c31..a529aadd2f 100644 --- a/src/agents/run_internal/resumable_session.py +++ b/src/agents/run_internal/resumable_session.py @@ -44,6 +44,11 @@ async def finish(self, result: RunResult | RunResultStreaming) -> None: state._resumable_binding = "detached" result._resumable_binding = await self._source._save_checkpoint(self._items, state) + async def finish_budget_stop(self) -> None: + """Keep completed work when the next request was refused before dispatch.""" + assert self._source is not None + await self._source._save_checkpoint(self._items, None) + def configure_stream(self, result: RunResultStreaming) -> None: queue = _CheckpointEventQueue() result._event_queue = queue diff --git a/src/agents/run_internal/run_loop.py b/src/agents/run_internal/run_loop.py index 659642845a..404a5a14a2 100644 --- a/src/agents/run_internal/run_loop.py +++ b/src/agents/run_internal/run_loop.py @@ -75,6 +75,7 @@ ) from ..models._run_context import ModelToolHooks, model_run_context, model_run_context_stream from ..result import RunResultStreaming +from ..run_budget import _admit from ..run_config import ReasoningItemIdPolicy, RunConfig from ..run_context import AgentHookContext, RunContextWrapper, TContext from ..run_error_handlers import RunErrorHandlers @@ -2667,6 +2668,7 @@ def get_model_stream() -> AsyncIterator[TResponseStreamEvent]: prompt=prompt_config, ) + await _admit(context_wrapper._budget, model, session, all_tools) retry_stream = stream_response_with_retry( get_stream=get_model_stream, rewind=rewind_model_request, @@ -2732,16 +2734,16 @@ def get_model_stream() -> AsyncIterator[TResponseStreamEvent]: # provider usage (common for some Chat Completions / LiteLLM streams). Skipping # apply_retry_attempt_usage here would drop failed-attempt accounting and diverge # from the non-streaming get_response_with_retry path. - usage = apply_retry_attempt_usage( - ( - _response_usage_to_usage(terminal_response.usage) - if terminal_response.usage - # Defaults to zero requests, so adapters that fold several provider - # responses into one and report counts separately are not double-counted. - else Usage(requests=_requests_for_response_without_usage(terminal_response)) - ), - stream_failed_retry_attempts[0], + usage = ( + _response_usage_to_usage(terminal_response.usage) + if terminal_response.usage + # Defaults to zero requests, so adapters that fold several provider + # responses into one and report counts separately are not double-counted. + else Usage(requests=_requests_for_response_without_usage(terminal_response)) ) + if context_wrapper._budget is not None: + context_wrapper._budget.observe(usage) + usage = apply_retry_attempt_usage(usage, stream_failed_retry_attempts[0]) final_response = ModelResponse( output=terminal_response.output, usage=usage, @@ -3121,7 +3123,9 @@ async def rewind_model_request() -> None: ), record_failed_attempt_usage_on_error(context_wrapper.usage) as reported_usage, ): + await _admit(context_wrapper._budget, model, session, all_tools) new_response = await get_response_with_retry( + budget=context_wrapper._budget, get_response=lambda: model.get_response( system_instructions=filtered.instructions, input=filtered.input, diff --git a/src/agents/run_state.py b/src/agents/run_state.py index 20c8ce2755..5bd9412646 100644 --- a/src/agents/run_state.py +++ b/src/agents/run_state.py @@ -110,6 +110,7 @@ log_model_and_tool_data_warning, logger, ) +from .run_budget import _BudgetCheckpointError, _BudgetState from .run_context import RunContextWrapper, _ApprovalRecord, _FunctionToolApprovalKey from .run_internal.items import ( NestedHistoryOwnedItemRef, @@ -312,7 +313,7 @@ def _default_run_state_validation_error( ), "1.23": ( "Binds prepared tool inputs to their original proposals across retries and resume, " - "and records required ResumableSession ownership for paused runs." + "and records ResumableSession ownership and optional root budgets for paused runs." ), } SUPPORTED_SCHEMA_VERSIONS = frozenset(SCHEMA_VERSION_SUMMARIES) @@ -1982,6 +1983,7 @@ def to_json( "Use unique agent names before starting a persistable run." ) + budget = self._context._budget.checkpoint() if self._context._budget is not None else None approvals_dict = self._serialize_approvals() tool_invocations = self._serialize_tool_invocations() hosted_mcp_approvals = self._serialize_hosted_mcp_approvals() @@ -2000,6 +2002,8 @@ def to_json( # Preserve metadata so deserialization can warn when context types were erased. "context_meta": context_meta, } + if budget is not None: + context_entry["budget"] = budget tool_input = self._serialize_tool_input(self._context.tool_input) if tool_input is not None: context_entry["tool_input"] = tool_input @@ -2567,6 +2571,10 @@ def validation_error_factory( validation_error_factory=validation_error_factory, ) except BaseException as error: + if isinstance(error, _BudgetCheckpointError): + error = validation_error_factory( + "Invalid RunBudget checkpoint or schema version.", UserError + ) trusted_error_message = _trusted_run_state_validation_message( error, trusted_validation_errors, @@ -3049,6 +3057,8 @@ def _serialize_pending_nested_agent_tool_runs( strict_context=strict_context, include_tracing_api_key=include_tracing_api_key, ) + except _BudgetCheckpointError: + raise except Exception: if strict_context: raise @@ -3247,6 +3257,8 @@ async def _restore_pending_nested_agent_tool_runs( strict_context=strict_context, validation_error_factory=validation_error_factory, ) + except _BudgetCheckpointError: + raise except Exception: if strict_context: raise @@ -4280,6 +4292,11 @@ async def _build_run_state_from_json( raise validation_error_factory("Run state agent not found in agent map", UserError) context_data = state_json["context"] + budget = None + if "budget" in context_data: + if (schema_major, schema_minor) < (1, 23): + raise _BudgetCheckpointError("Run budgets require schema 1.23 or later.") + budget = _BudgetState.restore(context_data["budget"]) usage = deserialize_usage(context_data.get("usage", {})) serialized_context: Any = context_data.get("context", _MISSING_CONTEXT_SENTINEL) @@ -4342,6 +4359,7 @@ async def _build_run_state_from_json( "Serialized run state context must be a mapping. Please provide one.", UserError, ) + context = context._for_new_root(budget) context.usage = usage context._restored_unbound_approval_call_ids = set() context._allow_legacy_approval_binding_reconstruction = (schema_major, schema_minor) < (1, 15) @@ -5700,6 +5718,7 @@ def _clone_original_input(original_input: str | list[Any]) -> str | list[Any]: "Run state nested history ownership references a missing input item", "Run state nested history ownership session digest does not match", "Run state nested history ownership input digest does not match", + "Invalid RunBudget checkpoint or schema version.", "RunState tool_invocations must be a mapping.", "RunState tool_invocations contains an invalid call ID.", "RunState tool invocation must be a mapping.", diff --git a/src/agents/usage.py b/src/agents/usage.py index 90157fab16..a55f5f8e50 100644 --- a/src/agents/usage.py +++ b/src/agents/usage.py @@ -8,8 +8,16 @@ from openai.types.completion_usage import CompletionTokensDetails, PromptTokensDetails from openai.types.responses.response_usage import InputTokensDetails, OutputTokensDetails -from pydantic import BeforeValidator, JsonValue, TypeAdapter, ValidationError +from pydantic import ( + BeforeValidator, + JsonValue, + ModelWrapValidatorHandler, + TypeAdapter, + ValidationError, + model_validator, +) from pydantic.dataclasses import dataclass +from pydantic_core import ArgsKwargs _RAW_USAGE_ATTRIBUTE = "_agents_sdk_raw_usage" _NORMALIZED_USAGE_ATTRIBUTE = "_agents_sdk_normalized_usage" @@ -228,6 +236,23 @@ class Usage: cost calculation or context window management. """ + _total_missing = False + + @model_validator(mode="wrap") + @classmethod + def _remember_total_presence( + cls, value: Any, handler: ModelWrapValidatorHandler[Usage] + ) -> Usage: + usage = handler(value) + if isinstance(value, ArgsKwargs): + # total_tokens is the sixth positional field in the released constructor. + usage._total_missing = len(value.args) < 6 and "total_tokens" not in ( + value.kwargs or {} + ) + elif isinstance(value, Mapping): + usage._total_missing = "total_tokens" not in value + return usage + def __post_init__(self) -> None: # Some providers don't populate optional token detail fields # (cached_tokens, cache_write_tokens, reasoning_tokens), and the OpenAI SDK's generated @@ -262,6 +287,7 @@ def add(self, other: Usage) -> None: Args: other: The Usage object to add to this one. """ + self._total_missing = self._total_missing and other._total_missing self.requests += other.requests if other.requests else 0 self.input_tokens += other.input_tokens if other.input_tokens else 0 self.output_tokens += other.output_tokens if other.output_tokens else 0 @@ -370,7 +396,7 @@ def _response_usage_to_usage(response_usage: Any) -> Usage: usage.requests = max(usage.requests, request_count) return usage - return Usage( + usage = Usage( requests=request_count, input_tokens=response_usage.input_tokens or 0, output_tokens=response_usage.output_tokens or 0, @@ -378,6 +404,11 @@ def _response_usage_to_usage(response_usage: Any) -> Usage: input_tokens_details=response_usage.input_tokens_details, output_tokens_details=response_usage.output_tokens_details, ) + usage._total_missing = ( + response_usage.total_tokens is None + or getattr(response_usage, "_agents_sdk_total_missing", False) is True + ) + return usage def _attach_normalized_usage(target: Any, usage: Usage) -> None: diff --git a/tests/test_run_budget.py b/tests/test_run_budget.py new file mode 100644 index 0000000000..d35727b70c --- /dev/null +++ b/tests/test_run_budget.py @@ -0,0 +1,604 @@ +"""Root budget contracts through the public Runner and approval boundaries.""" + +from __future__ import annotations + +from dataclasses import replace +from types import SimpleNamespace +from unittest.mock import AsyncMock, MagicMock + +import httpx +import httpx2 +import pytest +from openai import APIConnectionError, AsyncOpenAI + +from agents import ( + Agent, + MaxTurnsExceeded, + ModelRetrySettings, + ModelSettings, + RunBudget, + RunBudgetError, + RunConfig, + Runner, + RunState, + Usage, + UserError, + retry_policies, + tool_namespace, +) +from agents.decorators import tool +from agents.memory.openai_responses_compaction_session import OpenAIResponsesCompactionSession +from agents.memory.resumable_session import ResumableSession +from agents.models.codex import CodexProvider +from agents.models.openai_responses import OpenAIResponsesModel +from agents.testing import ModelStep, ScriptedModel +from tests.memory.test_openai_responses_compaction_session import SimpleListSession +from tests.memory.test_resumable_session import MemoryStore +from tests.model_test_helpers import get_response_obj +from tests.test_responses import get_function_tool_call, get_handoff_tool_call, get_text_message + + +async def run(agent, budget, streamed=False, input="begin", **kwargs): + config = RunConfig( + budget=budget, tracing_disabled=True, tool_not_found_behavior="return_error_to_model" + ) + if not streamed: + return await Runner.run(agent, input, run_config=config, **kwargs) + result = Runner.run_streamed(agent, input, run_config=config, **kwargs) + async for _ in result.stream_events(): + pass + return result + + +def step(item, total=None): + usage = Usage(requests=1) if total is None else Usage(requests=1, total_tokens=total) + return ModelStep(output=[item], usage=usage) + + +@pytest.mark.parametrize("value", [None, -1, True, 1.5, 2**53]) +def test_invalid_limits(value): + with pytest.raises(ValueError, match="RunBudget"): + RunConfig(budget={"max_tokens": value}) + + +@pytest.mark.parametrize("limit", ["max_requests", "max_tokens", "max_estimated_cost_micros"]) +def test_zero_blocks_sync_dispatch(limit): + model = ScriptedModel() + with pytest.raises(RunBudgetError, match="run_budget_exceeded"): + Runner.run_sync(Agent(name="root", model=model), "begin", run_config={"budget": {limit: 0}}) + assert not model.calls + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) +async def test_retry_counted_once_and_overshoot_can_finish(streamed): + model = ScriptedModel( + [ + APIConnectionError(request=httpx.Request("POST", "https://example.invalid")), + step(get_function_tool_call("unknown"), 2), + step(get_text_message("done"), 20), + ] + ) + retry = ModelRetrySettings( + max_retries=1, policy=retry_policies.network_error(), backoff={"initial_delay": 0} + ) + agent = Agent(name="root", model=model, model_settings=ModelSettings(retry=retry)) + result = await run(agent, RunBudget(max_requests=2, max_tokens=3), streamed, max_turns=2) + assert result.final_output == "done" + assert result.context_wrapper.usage.requests == len(model.calls) == 3 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) +@pytest.mark.parametrize( + "total,policy,code", + [ + (0, "stop", None), + (None, "stop", "run_budget_usage_unavailable"), + (-1, "stop", "run_budget_usage_unavailable"), + (None, "continue", None), + (10, "stop", "run_budget_exceeded"), + ], +) +async def test_correction_uses_observed_totals(streamed, total, policy, code): + model = ScriptedModel( + [step(get_function_tool_call("unknown"), total), [get_text_message("done")]] + ) + agent = Agent(name="root", model=model) + budget = RunBudget(max_tokens=5, missing_usage=policy) + if code: + with pytest.raises(RunBudgetError, match=code): + await run(agent, budget, streamed) + assert len(model.calls) == 1 + else: + assert (await run(agent, budget, streamed)).final_output == "done" + + +def failing_estimate(usage): + raise RuntimeError("private estimator detail") + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "estimator,code", + [ + (None, "run_budget_usage_unavailable"), + (lambda u: None, "run_budget_usage_unavailable"), + (lambda u: u.total_tokens * 2, "run_budget_exceeded"), + (lambda u: True, "run_budget_invalid_estimate"), + (lambda u: 2**53, "run_budget_invalid_estimate"), + (failing_estimate, "run_budget_invalid_estimate"), + ], +) +async def test_estimates_fail_distinctly_without_callback_details(estimator, code): + model = ScriptedModel([step(get_function_tool_call("unknown"), 3)]) + budget = RunBudget(max_estimated_cost_micros=6, estimate_cost_micros=estimator) + with pytest.raises(RunBudgetError) as error: + await run(Agent(name="root", model=model), budget) + assert error.value.code == code + assert error.value.__context__ is None + assert len(model.calls) == 1 + + +@pytest.mark.asyncio +async def test_max_turns_still_limits_corrections(): + model = ScriptedModel([[get_function_tool_call("unknown")]]) + with pytest.raises(MaxTurnsExceeded): + await run(Agent(name="root", model=model), RunBudget(max_requests=2), max_turns=1) + assert len(model.calls) == 1 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) +@pytest.mark.parametrize("portable", [False, True]) +async def test_resume_after_handoff_checks_policy_before_approval(streamed, portable): + effects = [] + + @tool(needs_approval=True) + def record() -> str: + effects.append(1) + return "saved" + + target_model = ScriptedModel([step(get_function_tool_call("record"), 7)]) + target = Agent(name="target", model=target_model, tools=[record]) + model = ScriptedModel([step(get_handoff_tool_call(target), 2)]) + root = Agent(name="root", model=model, handoffs=[target]) + budget = RunBudget(max_requests=4, max_tokens=5) + result = await run(root, budget, streamed) + state = result.to_state() + if portable: + state = await RunState.from_string(root, state.to_string()) + assert state.to_json()["context"]["budget"]["tokens"] == 9 + state.approve(state.get_interruptions()[0]) + for changed in ( + None, + replace(budget, max_tokens=10), + replace(budget, missing_usage="continue"), + ): + with pytest.raises(UserError, match="same RunBudget"): + await run(root, changed, not streamed, state) + assert not effects + with pytest.raises(RunBudgetError, match="exceeded"): + await run(root, budget, not streamed, state) + assert effects == [1] + assert len(model.calls) == len(target_model.calls) == 1 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) +async def test_durable_approval_stop_preserves_effect_and_idle_budget(streamed): + effects = [] + + @tool(needs_approval=True) + def record() -> str: + effects.append(1) + return "saved" + + store = MemoryStore() + session = await ResumableSession.create(store) + model = ScriptedModel([[get_function_tool_call("record")], [get_text_message("fresh")]]) + root = Agent(name="root", model=model, tools=[record]) + budget = RunBudget(max_requests=1) + for invalid, error in [ + (RunBudget(max_requests=0), RunBudgetError), + (RunBudget(max_estimated_cost_micros=1), UserError), + ]: + with pytest.raises(error): + await run(root, invalid, streamed, session=session) + await run(root, budget, streamed, session=session) + restored = await ResumableSession.resume(store, session.session_id) + state = await restored.load_state(root) + state.approve(state.get_interruptions()[0]) + with pytest.raises(UserError, match="same RunBudget"): + await run(root, replace(budget, missing_usage="continue"), streamed, state) + assert restored.is_paused and not effects + with pytest.raises(RunBudgetError, match="exceeded"): + await run(root, budget, streamed, state) + assert effects == [1] and len(model.calls) == 1 + assert store.checkpoint(session.session_id)["status"] == "ready" + assert (await run(root, budget, streamed, session=restored)).final_output == "fresh" + assert "saved" in str(model.calls[-1].input) + assert effects == [1] + + +@pytest.mark.asyncio +async def test_live_cost_approval_rejects_portable_capture(): + @tool(needs_approval=True) + def record() -> str: + return "saved" + + budget = RunBudget(max_estimated_cost_micros=1, missing_usage="continue") + model = ScriptedModel([step(get_function_tool_call("record"), 1), [get_text_message("done")]]) + root = Agent(name="root", model=model, tools=[record]) + state = (await run(root, budget)).to_state() + with pytest.raises(UserError, match="estimated-cost"): + state.to_string() + state.approve(state.get_interruptions()[0]) + assert (await run(root, budget, input=state)).final_output == "done" + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) +async def test_nested_tool_has_independent_budget_and_usage(streamed): + child_model = ScriptedModel( + [step(get_function_tool_call("unknown"), 50), step(get_text_message("child"), 50)] + ) + child = Agent(name="child", model=child_model) + nested = child.as_tool( + "ask", + "Ask child", + on_stream=(lambda event: None) if streamed else None, + failure_error_function=None, + ) + model = ScriptedModel( + [ + step(get_function_tool_call("ask", '{"input":"ask"}'), 1), + step(get_text_message("done"), 1), + ] + ) + result = await run( + Agent(name="root", model=model, tools=[nested]), + RunBudget(max_requests=2, max_tokens=2), + streamed, + ) + assert result.final_output == "done" + assert len(model.calls) == len(child_model.calls) == 2 + assert result.context_wrapper.usage.total_tokens == 102 + + +@pytest.mark.asyncio +async def test_compaction_charges_tokens_without_an_admission(): + # ScriptedModel does not own the separate session compaction endpoint. + client = MagicMock() + client.responses.compact = AsyncMock( + return_value=SimpleNamespace( + output=[{"type": "compaction", "encrypted_content": "synthetic"}], + usage=Usage(total_tokens=7), + ) + ) + session = OpenAIResponsesCompactionSession( + session_id="example", + underlying_session=SimpleListSession(), + client=client, + should_trigger_compaction=lambda ctx: True, + ) + model = ScriptedModel([step(get_text_message("done"), 2)]) + result = await run( + Agent(name="root", model=model), RunBudget(max_requests=1, max_tokens=3), session=session + ) + checkpoint = result.to_state().to_json()["context"]["budget"] + assert checkpoint["tokens"] == 9 and checkpoint["requests"] == 1 + + +@pytest.mark.asyncio +async def test_native_sampling_rejected_without_dispatch(): + with pytest.raises(UserError, match="native sampling"): + await Runner.run( + Agent(name="root"), + "begin", + run_config=RunConfig(model_provider=CodexProvider(), budget=RunBudget(max_requests=1)), + ) + + +@pytest.mark.asyncio +@pytest.mark.allow_call_model_methods +@pytest.mark.parametrize("total", [None, 0]) +async def test_responses_missing_total_before_normalization(total): + # The Responses adapter normalizes null totals before returning to Runner. + calls = [] + + async def respond(request): + calls.append(request) + item = get_function_tool_call("unknown") if len(calls) == 1 else get_text_message("done") + payload = get_response_obj([item]).model_dump() + payload["usage"] = { + "total_tokens": total, + "input_tokens": 0, + "output_tokens": 0, + "input_tokens_details": {"cached_tokens": 0}, + "output_tokens_details": {"reasoning_tokens": 0}, + } + return httpx2.Response(200, json=payload) + + async with AsyncOpenAI( + api_key="test-key", + base_url="https://example.invalid/v1", + http_client=httpx2.AsyncClient(transport=httpx2.MockTransport(respond)), + ) as client: + root = Agent( + name="root", model=OpenAIResponsesModel(model="synthetic", openai_client=client) + ) + budget = RunBudget(max_tokens=1) + if total is None: + with pytest.raises(RunBudgetError, match="unavailable"): + await run(root, budget) + assert len(calls) == 1 + else: + assert (await run(root, budget)).final_output == "done" + assert len(calls) == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("cost", [False, True]) +async def test_explicit_child_budget_survives_nested_approval(cost): + effects = [] + + @tool(needs_approval=True) + def record() -> str: + effects.append(1) + return "saved" + + child_model = ScriptedModel( + [ + step(get_function_tool_call("record", call_id="inner"), 8), + step(get_text_message("child"), 8), + ] + ) + child = Agent(name="child", model=child_model, tools=[record]) + child_budget = ( + RunBudget(max_estimated_cost_micros=9, estimate_cost_micros=lambda u: u.total_tokens) + if cost + else RunBudget(max_requests=2) + ) + nested = child.as_tool( + "ask", + "Ask child", + run_config=RunConfig(budget=child_budget, tracing_disabled=True), + failure_error_function=None, + ) + model = ScriptedModel( + [ + step(get_function_tool_call("ask", '{"input":"ask"}'), 1), + step(get_text_message("done"), 2), + ] + ) + root = Agent(name="root", model=model, tools=[nested]) + budget = RunBudget(max_requests=2, max_tokens=2) + state = (await run(root, budget)).to_state() + if cost: + with pytest.raises(UserError, match="estimated-cost"): + state.to_string() + else: + state = await RunState.from_string(root, state.to_string()) + state.approve(state.get_interruptions()[0]) + assert (await run(root, budget, True, state)).final_output == "done" + assert len(model.calls) == len(child_model.calls) == 2 + assert effects == [1] + + +@pytest.mark.asyncio +async def test_missing_observation_survives_checkpoint(): + @tool(needs_approval=True) + def record() -> str: + return "saved" + + model = ScriptedModel([[get_function_tool_call("record")]]) + root = Agent(name="root", model=model, tools=[record]) + budget = RunBudget(max_tokens=5) + paused = await run(root, budget) + data = paused.to_state().to_json() + with pytest.raises(UserError): + await RunState.from_json(root, {**data, "$schemaVersion": "1.22"}) + state = await RunState.from_json(root, data) + state.approve(state.get_interruptions()[0]) + with pytest.raises(RunBudgetError, match="unavailable"): + await run(root, budget, input=state) + assert len(model.calls) == 1 + + +@pytest.mark.asyncio +async def test_hosted_child_usage_cannot_be_isolated(): + from agents.extensions.experimental.hosted_multi_agent import OpenAIHostedMultiAgentModel + + root = Agent(name="root", model=OpenAIHostedMultiAgentModel(model="synthetic")) + with pytest.raises(UserError, match="hosted multi-agent"): + await run(root, RunBudget(max_tokens=2)) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) +async def test_durable_child_policy_checked_before_claim(streamed): + effects = [] + + @tool(needs_approval=True) + def record() -> str: + effects.append(1) + return "saved" + + store = MemoryStore() + session = await ResumableSession.create(store) + inner = ScriptedModel( + [ + step(get_function_tool_call("record", call_id="inner"), 4), + step(get_text_message("child"), 4), + ] + ) + child = Agent(name="child", model=inner, tools=[record]) + config = RunConfig(budget=RunBudget(max_estimated_cost_micros=8), tracing_disabled=True) + nested = child.as_tool("ask", "Ask", run_config=config, failure_error_function=None) + outer = ScriptedModel( + [ + step(get_function_tool_call("ask", '{"input":"check"}'), 1), + step(get_text_message("done"), 1), + ] + ) + root = Agent(name="root", model=outer, tools=[nested]) + with pytest.raises(UserError, match="estimated-cost"): + await run(root, None, streamed, session=session) + assert not outer.calls and not inner.calls + assert store.checkpoint(session.session_id)["status"] == "ready" + budget = RunBudget(max_requests=2, max_tokens=5) + config.budget = budget + await run(root, budget, streamed, session=session) + restored = await ResumableSession.resume(store, session.session_id) + state = await restored.load_state(root) + state.approve(state.get_interruptions()[0]) + for changed in (None, replace(budget, missing_usage="continue"), RunBudget(max_requests=3)): + config.budget = changed + with pytest.raises(UserError, match="same RunBudget"): + await run(root, budget, streamed, state) + assert store.checkpoint(session.session_id)["status"] == "paused" + assert not effects + config.budget = budget + changed_tool = child.as_tool( + "ask", + "Ask", + run_config=RunConfig(budget=RunBudget(max_requests=3), tracing_disabled=True), + failure_error_function=None, + ) + disabled = child.as_tool("ask", "Ask", run_config=config, is_enabled=False) + for replacement in ([changed_tool], [disabled], [nested, changed_tool], []): + root.tools = replacement + with pytest.raises(UserError, match="RunBudget"): + await run(root, budget, streamed, state) + assert store.checkpoint(session.session_id)["status"] == "paused" + assert len(outer.calls) == len(inner.calls) == 1 + assert not effects + other = tool_namespace(name="other", description="Other tools", tools=[changed_tool]) + root.tools = [nested, *other] + assert (await run(root, budget, streamed, state)).final_output == "done" + assert len(outer.calls) == len(inner.calls) == 2 + assert effects == [1] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) +async def test_failed_resume_keeps_debit_and_tool_receipt(streamed): + effects = [] + + @tool(needs_approval=True) + def save() -> str: + effects.append(1) + return "saved" + + model = ScriptedModel([[get_function_tool_call("save")], RuntimeError("offline")]) + root = Agent(name="root", model=model, tools=[save]) + budget = RunBudget(max_requests=2) + state = (await run(root, budget, streamed)).to_state() + state.approve(state.get_interruptions()[0]) + with pytest.raises(RuntimeError, match="offline"): + await run(root, budget, streamed, state) + restored = await RunState.from_string(root, state.to_string()) + with pytest.raises(RunBudgetError, match="exceeded"): + await run(root, budget, not streamed, restored) + assert len(model.calls) == 2 + assert effects == [1] + + +@pytest.mark.asyncio +@pytest.mark.allow_call_model_methods +@pytest.mark.parametrize("streamed", [False, True]) +@pytest.mark.parametrize( + ("total", "policy"), [("absent", "stop"), (None, "stop"), (0, "stop"), (None, "continue")] +) +async def test_chat_total_presence_survives_normalization(streamed, total, policy): + # Exercise Chat JSON and SSE conversion before the Runner sees normalized usage. + import json + + from agents.models.openai_chatcompletions import OpenAIChatCompletionsModel + + calls = [] + + async def respond(request): + calls.append(request) + usage = {"prompt_tokens": 0, "completion_tokens": 0} + if total != "absent": + usage["total_tokens"] = total + call = { + "id": "c1", + "type": "function", + "function": {"name": "unknown", "arguments": "{}"}, + } + if streamed: + call["index"] = 0 + first = len(calls) == 1 + message = {"tool_calls": [call]} if first else {"content": "done"} + payload = { + "id": "message", + "created": 1, + "model": "synthetic", + "object": "chat.completion.chunk" if streamed else "chat.completion", + "usage": usage, + "choices": [ + { + "index": 0, + "finish_reason": "tool_calls" if first else "stop", + "delta" if streamed else "message": {"role": "assistant", **message}, + } + ], + } + if streamed: + return httpx2.Response( + 200, + content=f"data: {json.dumps(payload)}\n\ndata: [DONE]\n\n", + headers={"content-type": "text/event-stream"}, + ) + return httpx2.Response(200, json=payload) + + async with AsyncOpenAI( + api_key="test-key", + base_url="https://example.invalid/v1", + http_client=httpx2.AsyncClient(transport=httpx2.MockTransport(respond)), + ) as client: + root = Agent( + name="root", model=OpenAIChatCompletionsModel(model="synthetic", openai_client=client) + ) + budget = RunBudget(max_tokens=1, missing_usage=policy) + if total != 0 and policy == "stop": + with pytest.raises(RunBudgetError, match="unavailable"): + await run(root, budget, streamed) + assert len(calls) == 1 + else: + assert (await run(root, budget, streamed)).final_output == "done" + assert len(calls) == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) +async def test_child_budget_stop_uses_existing_tool_error_policy(streamed): + @tool(needs_approval=True) + def record() -> str: + return "saved" + + store = MemoryStore() + session = await ResumableSession.create(store) + inner = ScriptedModel([[get_function_tool_call("record", call_id="inner")]]) + child = Agent(name="child", model=inner, tools=[record]) + nested = child.as_tool( + "ask", "Ask", run_config=RunConfig(budget=RunBudget(max_requests=1), tracing_disabled=True) + ) + outer = ScriptedModel( + [ + [get_function_tool_call("ask", '{"input":"check"}')], + [get_text_message("done")], + ] + ) + root = Agent(name="root", model=outer, tools=[nested]) + budget = RunBudget(max_requests=2) + await run(root, budget, streamed, session=session) + state = await session.load_state(root) + state.approve(state.get_interruptions()[0]) + assert (await run(root, budget, streamed, state)).final_output == "done" + assert len(inner.calls) == 1 + assert "An error occurred while running the tool" in str(outer.calls[-1].input) + assert store.checkpoint(session.session_id)["status"] == "ready" From e05a2ee67a5447052d48e1e58d95764fd1e31391 Mon Sep 17 00:00:00 2001 From: Mark Stuart Date: Sat, 21 Nov 2026 06:48:07 -0800 Subject: [PATCH 2/7] feat(tools): edit selected tool results before tracing and publication --- src/agents/mcp/util.py | 28 +- src/agents/run_config.py | 79 ++- src/agents/run_internal/run_loop.py | 30 +- src/agents/run_internal/tool_execution.py | 36 +- src/agents/run_internal/tool_text.py | 198 ++++++ src/agents/run_internal/turn_resolution.py | 12 + src/agents/tool.py | 32 +- src/agents/tool_context.py | 3 + tests/test_tool_text_transforms.py | 732 +++++++++++++++++++++ 9 files changed, 1120 insertions(+), 30 deletions(-) create mode 100644 src/agents/run_internal/tool_text.py create mode 100644 tests/test_tool_text_transforms.py diff --git a/src/agents/mcp/util.py b/src/agents/mcp/util.py index d51a773342..e18e31cdc2 100644 --- a/src/agents/mcp/util.py +++ b/src/agents/mcp/util.py @@ -54,7 +54,7 @@ ToolOutput = Union[str, ToolOutputItem, list[ToolOutputItem]] # noqa: UP007 if TYPE_CHECKING: - from mcp.types import Tool as MCPTool + from mcp.types import CallToolResult, Tool as MCPTool from ..agent import AgentBase from .server import MCPServer @@ -601,6 +601,7 @@ def to_function_tool( mcp_server_name=get_mcp_server_log_name(server.name), ), ) + function_tool._mcp_server_id = id(server) function_tool._mcp_annotations = copy.deepcopy(tool.annotations) function_tool._mcp_tool_binding = (get_mcp_server_log_name(server.name), tool.name, None) return function_tool @@ -716,6 +717,12 @@ async def invoke_mcp_tool( f"Invalid JSON input for tool {tool_name_for_display}: expected a JSON object" ) + async def call_peer() -> CallToolResult: + if merged_meta is None: + return await server.call_tool(tool.name, json_data) + return await server.call_tool(tool.name, json_data, meta=merged_meta) + + invoke = call_peer if _debug.DONT_LOG_TOOL_DATA: logger.debug("Invoking MCP tool") else: @@ -723,12 +730,12 @@ async def invoke_mcp_tool( try: 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( - server.call_tool(tool.name, json_data) - if merged_meta is None - else server.call_tool(tool.name, json_data, meta=merged_meta) - ) + call_task = asyncio.create_task(invoke()) try: done, _ = await asyncio.wait({call_task}, return_when=asyncio.FIRST_COMPLETED) finished_task = done.pop() @@ -752,6 +759,8 @@ async def invoke_mcp_tool( # 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 @@ -782,6 +791,13 @@ async def invoke_mcp_tool( 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/run_config.py b/src/agents/run_config.py index c65d9cbd75..7786dc6c1d 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 @@ -35,13 +35,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 @@ -157,6 +161,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 class ToolExecutionConfig: @@ -202,6 +209,47 @@ class ToolExecutionConfig: Raw provider stream events and provider-managed history may contain the original proposal. """ + tool_text_transforms: Sequence[ + tuple[ + FunctionTool | tuple[MCPServer, str], + Callable[[ToolCallHookContext[Any], tuple[str, ...]], Awaitable[tuple[str, ...]]], + ] + ] = 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`. For example, + + ```python + async def hide(call, texts): + return tuple(text.replace("internal draft", "[hidden]") for text in texts) + + config = ToolExecutionConfig(tool_text_transforms=[ + (report, hide), + ((server, "read.report"), hide), + ]) + ``` + + The editor receives ordered text slots and must return one string per slot. + 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. Configure the same targets again on resume. + 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. @@ -231,6 +279,33 @@ 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") + self.tool_text_transforms = tuple(self.tool_text_transforms) + if self.tool_text_transforms: + from .mcp import MCPServer + from .tool import FunctionTool + + seen: set[tuple[int, str | None]] = set() + for target, edit in self.tool_text_transforms: + key: tuple[int, str | None] + if isinstance(target, FunctionTool): + if target._is_agent_tool or target._is_codex_tool or target._mcp_tool_binding: + raise ValueError( + "Select a local function or an MCP server and raw tool name." + ) + key = (id(target), None) + elif ( + isinstance(target, tuple) + and len(target) == 2 + and isinstance(target[0], MCPServer) + and isinstance(target[1], str) + and target[1] + ): + key = (id(target[0]), target[1]) + else: + raise ValueError("Invalid tool_text_transforms target.") + if key in seen or not callable(edit): + raise ValueError("Each tool_text_transforms target requires one editor.") + seen.add(key) @dataclass diff --git a/src/agents/run_internal/run_loop.py b/src/agents/run_internal/run_loop.py index 659642845a..e09e7a210b 100644 --- a/src/agents/run_internal/run_loop.py +++ b/src/agents/run_internal/run_loop.py @@ -17,6 +17,7 @@ from openai.types.responses import ( Response, ResponseCompletedEvent, + ResponseFunctionToolCall, ResponseOutputItemDoneEvent, ) from openai.types.responses.response_output_item import ResponseOutputItem @@ -236,6 +237,7 @@ validate_run_hooks, ) from .turn_resolution import ( + _snapshot_function_calls, check_for_final_output_from_tools, execute_final_output, execute_handoffs, @@ -2702,12 +2704,28 @@ def get_model_stream() -> AsyncIterator[TResponseStreamEvent]: if isinstance(event_response, Response): stream_response_id = event_response.id stream_request_id = getattr(event_response, "_request_id", None) - streamed_result._event_queue.put_nowait(RawResponsesStreamEvent(data=event)) + if ( + isinstance(event, ResponseCompletedEvent) + and not event.response.output + and streamed_response_output + ): + # Some backends leave completed output empty after item.done events. + event.response.output = list(streamed_response_output) + + raw_event = event + if run_config.tool_execution is not None: + item = getattr(event, "item", None) + if isinstance(item, ResponseFunctionToolCall): + raw_event = event.model_copy(update={"item": deepcopy(item)}) + elif isinstance(event_response, Response) and event_response.output: + output = _snapshot_function_calls(event_response.output) + if output is not event_response.output: + response_view = event_response.model_copy(update={"output": output}) + raw_event = event.model_copy(update={"response": response_view}) + streamed_result._event_queue.put_nowait(RawResponsesStreamEvent(data=raw_event)) terminal_response: Response | None = None - is_completed_event = False if isinstance(event, ResponseCompletedEvent): - is_completed_event = True terminal_response = event.response elif getattr(event, "type", None) in {"response.incomplete", "response.failed"}: event_type = cast(str, event.type) @@ -2723,11 +2741,6 @@ def get_model_stream() -> AsyncIterator[TResponseStreamEvent]: raise response_error_event_failure_error(cast(str, event.type), event) if terminal_response is not None: - if is_completed_event and not terminal_response.output and streamed_response_output: - # Some streaming backends emit output items during item.done events while - # leaving the terminal response output empty. Preserve those items so the - # runner can resolve the completed step correctly. - terminal_response.output = list(streamed_response_output) # Always fold retry attempts into usage, even when the terminal response omits # provider usage (common for some Chat Completions / LiteLLM streams). Skipping # apply_retry_attempt_usage here would drop failed-attempt accounting and diverge @@ -2803,6 +2816,7 @@ async def after_invocation_validation( if tool_execution is not None and ( 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 84d0855cd2..2056222fc5 100644 --- a/src/agents/run_internal/tool_execution.py +++ b/src/agents/run_internal/tool_execution.py @@ -117,6 +117,7 @@ ) from .run_steps import ToolRunFunction from .tool_hooks import hook_payload_diagnostics, transform_tool_output +from .tool_text import invoke_selected_tool, select_text_editor from .tool_use_tracker import AgentToolUseTracker if TYPE_CHECKING: @@ -2121,7 +2122,19 @@ async def _invoke_tool_and_run_post_invoke( ) -> Any: bypass_output_schema = False try: - 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, @@ -2129,7 +2142,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( @@ -2171,14 +2184,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( @@ -2214,7 +2228,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, ) output_item: ToolCallOutputItem | None = None diff --git a/src/agents/run_internal/tool_text.py b/src/agents/run_internal/tool_text.py new file mode 100644 index 0000000000..9b53924624 --- /dev/null +++ b/src/agents/run_internal/tool_text.py @@ -0,0 +1,198 @@ +"""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 ..exceptions import ( + UserError, + _mark_error_data_redacted, + _prepare_data_redacted_error, + _raise_data_redacted_error, +) +from ..run_config import ToolCallHookContext +from ..tool import ( + FunctionTool, + ToolOutputText, + ValidToolOutputPydanticModelsTypeAdapter, + _FunctionToolInvocationResult, + _invoke_function_tool_with_metadata, + _parse_function_tool_json_input, + _protect_selected_task, + _SelectedTaskExit, +) +from .tool_hooks import _await_hook + +if TYPE_CHECKING: + from mcp.types import CallToolResult + + from ..agent import Agent + from ..run_config import ToolExecutionConfig + from ..tool_context import ToolContext + +_PEER_ERROR = "Selected MCP tool reported an error." +_Edit = Callable[[tuple[str, ...]], Awaitable[tuple[str, ...]]] + + +def select_text_editor( + settings: ToolExecutionConfig | None, + agent: Agent[Any], + tool: FunctionTool, + context: ToolContext[Any], + arguments: str, +) -> _Edit | None: + if settings is None: + return None + for target, editor in settings.tool_text_transforms: + if isinstance(target, tuple): + binding = tool._mcp_tool_binding + if binding is None or tool._mcp_server_id != id(target[0]) or binding[1] != target[1]: + continue + elif target is not tool: + continue + 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=target if isinstance(target, tuple) else None, + ) + + return partial(_validated_edit, partial(editor, call), tool.name) + return None + + +async def _validated_edit(edit: _Edit, name: str, texts: tuple[str, ...]) -> tuple[str, ...]: + async def invoke() -> tuple[str, ...]: + result = await _protect_selected_task(partial(edit, texts)) + # Refuse arbitrary objects before the hook takes ownership with deepcopy. + if type(result) is not tuple or any(type(text) is not str for text in result): + raise ValueError + return result + + result = await _await_hook(invoke, "tool_text_transforms", name) + if len(result) != len(texts): + raise ValueError + for text in result: + text.encode("utf-8") + return 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 + return _FunctionToolInvocationResult( + await _edit_function_result(edit, function_tool, result.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( + "Selected tool failed or its text transform did not produce a valid result." + ) + _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 + return clean diff --git a/src/agents/run_internal/turn_resolution.py b/src/agents/run_internal/turn_resolution.py index 04fad384e2..ded0f7ad0a 100644 --- a/src/agents/run_internal/turn_resolution.py +++ b/src/agents/run_internal/turn_resolution.py @@ -96,6 +96,7 @@ ToolSearchCallItem, ToolSearchOutputItem, TResponseInputItem, + TResponseOutputItem, coerce_tool_search_call_raw_item, coerce_tool_search_output_raw_item, ) @@ -4093,6 +4094,14 @@ def _preflight_response_invocations( } +def _snapshot_function_calls(items: list[TResponseOutputItem]) -> list[TResponseOutputItem]: + if not any(isinstance(item, ResponseFunctionToolCall) for item in items): + return items + return [ + deepcopy(item) if isinstance(item, ResponseFunctionToolCall) else item for item in items + ] + + async def get_single_step_result_from_response( *, bindings: AgentBindings[TContext], @@ -4140,6 +4149,9 @@ def classify() -> ProcessedResponse: ): # Keep the tool and its callbacks on the same arguments if a consumer edits a raw event. new_response.output = deepcopy(new_response.output) + elif settings is not None: + # A model adapter can retain the items it returned. + new_response.output = _snapshot_function_calls(new_response.output) new_bindings: dict[str, tuple[str, dict[str, Any]]] = {} try: processed_response = classify() diff --git a/src/agents/tool.py b/src/agents/tool.py index 66d70c20c9..32619ee068 100644 --- a/src/agents/tool.py +++ b/src/agents/tool.py @@ -597,6 +597,9 @@ class FunctionTool: _mcp_annotations: ToolAnnotations | None = field(default=None, kw_only=True, repr=False) + # The invocation partial retains the server. Its identity survives roster reordering. + _mcp_server_id: int | 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. @@ -698,6 +701,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, @@ -2282,6 +2287,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, @@ -2299,8 +2322,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) @@ -2322,7 +2346,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 @@ -2850,7 +2874,9 @@ async def _on_invoke_tool_impl(ctx: ToolContext[Any], input: str) -> Any: result = None raise - if _debug.DONT_LOG_TOOL_DATA: + if _debug.DONT_LOG_TOOL_DATA 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/test_tool_text_transforms.py b/tests/test_tool_text_transforms.py new file mode 100644 index 0000000000..8f4ccfd5aa --- /dev/null +++ b/tests/test_tool_text_transforms.py @@ -0,0 +1,732 @@ +import asyncio +import json +import logging + +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, + 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, **kwargs): + super().__init__(server_name="Reports", **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", "throw", "cancel", "invalid"]) +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" + target = report if local else (source, "read.report") + 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 == "invalid": + return (RAW, 42) + return tuple(SAFE if t else "" for t in texts) + + async def legacy(*args): + pytest.fail("selected call reached the generic editor") + + config = RunConfig( + tool_execution=ToolExecutionConfig( + tool_text_transforms=[(target, edit)], prepare_tool_output=legacy + ), + tracing={"operation_detail": detail} if detail else {}, + trace_include_sensitive_data=True, + ) + 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 == "edit": + 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() + 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 target) + 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 == "edit": + 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 if local else (source, "read.report"), forbidden)], + prepare_tool_output=forbidden, + ), + ) + with pytest.raises(UserError) as exc: + await Runner.run(agent, "go", run_config=config) + assert not unexpected + 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_name_keeps_legacy_behavior(): + selected, other = Source(), Source() + 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=[((selected, "read.report"), 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=[((peer, "read.report"), 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 + + settings = TypeAdapter(ToolExecutionConfig).validate_python( + {"tool_text_transforms": [((peer, "read.report"), edit)]} + ) + assert settings.tool_text_transforms[0][0][0] is peer + for entries in [[("read.report", edit)], [((peer, "read.report"), 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=[((source, "read.report"), 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=[((server, "read.report"), 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=[((peer, "read.report") 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=[((server, "read.report"), 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" From e2a1bc4b50e0eae822b9cb8c981e6370e68d995a Mon Sep 17 00:00:00 2001 From: Mark Stuart Date: Sun, 22 Nov 2026 00:56:14 -0800 Subject: [PATCH 3/7] Publish committed stream events before raising a run budget error --- src/agents/run_budget.py | 20 +++++++++---- src/agents/run_internal/run_loop.py | 4 ++- tests/test_run_budget.py | 46 ++++++++++++++++++++++++++++- 3 files changed, 63 insertions(+), 7 deletions(-) diff --git a/src/agents/run_budget.py b/src/agents/run_budget.py index e98e16ee2d..a249e419db 100644 --- a/src/agents/run_budget.py +++ b/src/agents/run_budget.py @@ -8,13 +8,14 @@ from dataclasses import dataclass, field, replace from typing import TYPE_CHECKING, Any, Literal -from .exceptions import AgentsException, UserError +from .exceptions import AgentsException, UserError, _mark_error_to_drain_stream_events from .usage import Usage if TYPE_CHECKING: from .agent import Agent from .memory import Session from .models.interface import Model + from .result import RunResultStreaming from .run_config import RunConfig from .run_state import RunState from .tool import Tool @@ -226,9 +227,14 @@ def _check_tools(tools: Iterable[Tool]) -> None: async def _admit( - budget: _BudgetState | None, model: Model, session: Session | None, tools: Iterable[Tool] + budget: _BudgetState | None, + model: Model, + session: Session | None, + tools: Iterable[Tool], + *, + streamed_result: RunResultStreaming | None = None, ) -> None: - from .run_internal.resumable_session import ResumableRun + from .run_internal.resumable_session import ResumableRun, checkpoint_streamed_result try: if isinstance(session, ResumableRun): @@ -238,9 +244,13 @@ async def _admit( _check_model(model) budget.check() budget.requests += 1 - except (RunBudgetError, UserError): + except (RunBudgetError, UserError) as error: if isinstance(session, ResumableRun): - await session.finish_budget_stop() + if streamed_result is None: + await session.finish_budget_stop() + else: + await checkpoint_streamed_result(streamed_result, interruptions=[]) + _mark_error_to_drain_stream_events(error) raise diff --git a/src/agents/run_internal/run_loop.py b/src/agents/run_internal/run_loop.py index 9f3bf2b784..6c315a689d 100644 --- a/src/agents/run_internal/run_loop.py +++ b/src/agents/run_internal/run_loop.py @@ -2668,7 +2668,9 @@ def get_model_stream() -> AsyncIterator[TResponseStreamEvent]: prompt=prompt_config, ) - await _admit(context_wrapper._budget, model, session, all_tools) + await _admit( + context_wrapper._budget, model, session, all_tools, streamed_result=streamed_result + ) retry_stream = stream_response_with_retry( get_stream=get_model_stream, rewind=rewind_model_request, diff --git a/tests/test_run_budget.py b/tests/test_run_budget.py index d35727b70c..abaf9df653 100644 --- a/tests/test_run_budget.py +++ b/tests/test_run_budget.py @@ -2,6 +2,7 @@ from __future__ import annotations +import asyncio from dataclasses import replace from types import SimpleNamespace from unittest.mock import AsyncMock, MagicMock @@ -28,7 +29,7 @@ ) from agents.decorators import tool from agents.memory.openai_responses_compaction_session import OpenAIResponsesCompactionSession -from agents.memory.resumable_session import ResumableSession +from agents.memory.resumable_session import ResumableSession, ResumableSessionError from agents.models.codex import CodexProvider from agents.models.openai_responses import OpenAIResponsesModel from agents.testing import ModelStep, ScriptedModel @@ -602,3 +603,46 @@ def record() -> str: assert len(inner.calls) == 1 assert "An error occurred while running the tool" in str(outer.calls[-1].input) assert store.checkpoint(session.session_id)["status"] == "ready" + + +@pytest.mark.asyncio +@pytest.mark.parametrize("fail", [False, True]) +async def test_stream_budget_stop_publishes_only_committed_work(fail): + effects = [] + + @tool + def record() -> str: + effects.append(1) + return "saved" + + store = MemoryStore() + session = await ResumableSession.create(store) + store.block_checkpoint = True + store.fail_checkpoint = fail + model = ScriptedModel([[get_text_message("working"), get_function_tool_call("record")]]) + agent = Agent(name="root", model=model, tools=[record]) + result = Runner.run_streamed( + agent, + "begin", + session=session, + run_config=RunConfig(budget=RunBudget(max_requests=1), tracing_disabled=True), + ) + events = [] + + async def consume(): + async for event in result.stream_events(): + if event.type == "run_item_stream_event": + events.append(event.name) + + consumer = asyncio.create_task(consume()) + try: + await asyncio.wait_for(store.saving.wait(), timeout=5) + assert not events + finally: + store.release.set() + with pytest.raises(ResumableSessionError if fail else RunBudgetError): + await asyncio.wait_for(consumer, timeout=5) + assert len(model.calls) == 1 and effects == [1] + assert store.checkpoint(session.session_id)["status"] == ("active" if fail else "ready") + assert result.final_output is None + assert events == ([] if fail else ["message_output_created", "tool_called", "tool_output"]) From edfb871c1b3edf3f44d92641872e85c043e0bd36 Mon Sep 17 00:00:00 2001 From: Mark Stuart Date: Sun, 22 Nov 2026 19:31:41 -0800 Subject: [PATCH 4/7] Check canonical MCP tool identities before skipping a text editor --- src/agents/run_config.py | 4 ++- src/agents/run_internal/tool_text.py | 8 ++++-- tests/test_tool_text_transforms.py | 43 ++++++++++++++++++++++++++++ 3 files changed, 52 insertions(+), 3 deletions(-) diff --git a/src/agents/run_config.py b/src/agents/run_config.py index 9a5f0cb4b5..524dd0576e 100644 --- a/src/agents/run_config.py +++ b/src/agents/run_config.py @@ -222,7 +222,9 @@ class ToolExecutionConfig: 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. For MCP, a selector matching the exposed name + 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. diff --git a/src/agents/run_internal/tool_text.py b/src/agents/run_internal/tool_text.py index 6cf255e128..fa96ab3b42 100644 --- a/src/agents/run_internal/tool_text.py +++ b/src/agents/run_internal/tool_text.py @@ -56,8 +56,12 @@ def bind_text_transform( if binding is None: continue server = tool._mcp_server_ref() if tool._mcp_server_ref else None - if server is not None and server is not target[0] and server.name != target[0].name: - continue + if server is not target[0]: + 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(target[0].name): + continue if target[1] != binding[1]: from ..mcp.util import MCPUtil diff --git a/tests/test_tool_text_transforms.py b/tests/test_tool_text_transforms.py index ef24db9c54..b40b90ee78 100644 --- a/tests/test_tool_text_transforms.py +++ b/tests/test_tool_text_transforms.py @@ -1091,3 +1091,46 @@ async def edit(call, texts): 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 = ((previous, selector), 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, ((current, "read.report"), 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() From 81d7537d42e897e70773d8bd78c42253b6a2eaad Mon Sep 17 00:00:00 2001 From: Mark Stuart Date: Sun, 22 Nov 2026 21:32:11 -0800 Subject: [PATCH 5/7] Drain committed events before reporting a streamed run budget stop --- src/agents/run_budget.py | 34 +++++++++++----- tests/test_run_budget.py | 84 +++++++++++++++++++++++++++++++++++----- 2 files changed, 98 insertions(+), 20 deletions(-) diff --git a/src/agents/run_budget.py b/src/agents/run_budget.py index 14f69b943b..b73d40cdea 100644 --- a/src/agents/run_budget.py +++ b/src/agents/run_budget.py @@ -13,6 +13,7 @@ from ._redaction import current_redactor, protected_error from .exceptions import ( AgentsException, + InputGuardrailTripwireTriggered, UserError, _mark_error_to_drain_stream_events, _raise_data_redacted_error, @@ -340,16 +341,29 @@ async def _admit( budget.check() budget.requests += 1 except (RunBudgetError, UserError) as error: - if isinstance(session, ResumableRun): - if streamed_result is None: - await session.finish_budget_stop() - else: - await checkpoint_streamed_result(streamed_result, interruptions=[]) - if current_redactor() is not None: - safe = protected_error(error) - _mark_error_to_drain_stream_events(safe) - _raise_data_redacted_error(safe) - _mark_error_to_drain_stream_events(error) + if streamed_result is not None: + from .run_internal.guardrails import input_guardrail_tripwire_triggered_for_stream + + # A parallel check can reject the completed turn while its tools run. + await input_guardrail_tripwire_triggered_for_stream( + streamed_result, ignore_cancelled=True + ) + tripwire = streamed_result._triggered_input_guardrail_result + if tripwire is not None: + raise InputGuardrailTripwireTriggered(tripwire) from None + checks = streamed_result._input_guardrails_task + if checks is not None: + if checks.cancelled(): + raise # No verdict to authorize publishing the queued events. + checks.result() + await checkpoint_streamed_result(streamed_result, interruptions=[]) + if current_redactor() is not None: + safe = protected_error(error) + _mark_error_to_drain_stream_events(safe) + _raise_data_redacted_error(safe) + _mark_error_to_drain_stream_events(error) + elif isinstance(session, ResumableRun): + await session.finish_budget_stop() raise diff --git a/tests/test_run_budget.py b/tests/test_run_budget.py index a7ec33106b..1af534b6cf 100644 --- a/tests/test_run_budget.py +++ b/tests/test_run_budget.py @@ -14,6 +14,8 @@ from agents import ( Agent, + GuardrailFunctionOutput, + InputGuardrailTripwireTriggered, MaxTurnsExceeded, ModelProvider, ModelRetrySettings, @@ -25,6 +27,7 @@ RunState, Usage, UserError, + input_guardrail, retry_policies, tool_namespace, ) @@ -655,9 +658,9 @@ def record() -> str: @pytest.mark.asyncio -@pytest.mark.parametrize("fail", [False, True]) +@pytest.mark.parametrize("session_mode", ["none", "ordinary", "durable", "failed_save"]) @pytest.mark.parametrize("protected", [False, True]) -async def test_stream_budget_stop_publishes_only_committed_work(fail, protected): +async def test_stream_budget_stop_publishes_only_committed_work(session_mode, protected): effects = [] @tool @@ -666,9 +669,13 @@ def record() -> str: return "saved" store = MemoryStore() - session = await ResumableSession.create(store) - store.block_checkpoint = True - store.fail_checkpoint = fail + fail = session_mode == "failed_save" + if session_mode in ("durable", "failed_save"): + session = await ResumableSession.create(store) + store.block_checkpoint = True + store.fail_checkpoint = fail + else: + session = SimpleListSession() if session_mode == "ordinary" else None model = ScriptedModel([[get_text_message("working"), get_function_tool_call("record")]]) agent = Agent(name="root", model=model, tools=[record]) result = Runner.run_streamed( @@ -691,25 +698,82 @@ async def consume(): if event.type == "run_item_stream_event": events.append(event.name) + if not isinstance(session, ResumableSession): + # Let the producer finish before the reader checks for errors. + assert result.run_loop_task is not None + _, pending = await asyncio.wait([result.run_loop_task], timeout=5) + assert not pending consumer = asyncio.create_task(consume()) try: - await asyncio.wait_for(store.saving.wait(), timeout=5) - assert not events + if isinstance(session, ResumableSession): + await asyncio.wait_for(store.saving.wait(), timeout=5) + assert not events finally: store.release.set() - with pytest.raises( + expected = ( ResumableSessionError if fail else (RuntimeError if protected else RunBudgetError) - ) as error: + ) + with pytest.raises(expected) as error: await asyncio.wait_for(consumer, timeout=5) if protected and not fail: assert str(error.value) == "Error details are redacted." assert error.value.__context__ is None assert len(model.calls) == 1 and effects == [1] - assert store.checkpoint(session.session_id)["status"] == ("active" if fail else "ready") + if isinstance(session, ResumableSession): + assert store.checkpoint(session.session_id)["status"] == ("active" if fail else "ready") assert result.final_output is None assert events == ([] if fail else ["message_output_created", "tool_called", "tool_output"]) +@pytest.mark.asyncio +@pytest.mark.parametrize("durable", [False, True]) +@pytest.mark.parametrize("verdict", ["accept", "reject", "cancel"]) +async def test_budget_stop_waits_for_parallel_input_verdict(durable, verdict): + ran = asyncio.Event() + + @tool + async def record() -> str: + ran.set() + return "saved" + + @input_guardrail + async def check(ctx, agent, input): + await ran.wait() + if verdict == "cancel": + raise asyncio.CancelledError + return GuardrailFunctionOutput(output_info=None, tripwire_triggered=verdict == "reject") + + store = MemoryStore() + session = await ResumableSession.create(store) if durable else None + model = ScriptedModel([[get_text_message("working"), get_function_tool_call("record")]]) + result = Runner.run_streamed( + Agent(name="root", model=model, tools=[record], input_guardrails=[check]), + "begin", + session=session, + run_config=RunConfig(budget=RunBudget(max_requests=1), tracing_disabled=True), + ) + assert result.run_loop_task is not None + _, pending = await asyncio.wait([result.run_loop_task], timeout=5) + assert not pending + events = [] + with pytest.raises(InputGuardrailTripwireTriggered if verdict == "reject" else RunBudgetError): + async for event in result.stream_events(): + events.append(event) + assert ran.is_set() and len(model.calls) == 1 and result.final_output is None + if verdict != "accept": + assert not events + else: + assert [e.name for e in events if e.type == "run_item_stream_event"] == [ + "message_output_created", + "tool_called", + "tool_output", + ] + if session is not None: + assert store.checkpoint(session.session_id)["status"] == ( + "ready" if verdict == "accept" else "active" + ) + + @pytest.mark.parametrize("value", [True, -0.01, float("nan"), float("inf"), "0.01"]) def test_invalid_dollar_limit(value): with pytest.raises(ValueError, match="max_estimated_cost_usd"): From 7b067230ed1d95a58e92f4f36658b3e7ac036271 Mon Sep 17 00:00:00 2001 From: Mark Stuart Date: Mon, 23 Nov 2026 17:52:15 -0800 Subject: [PATCH 6/7] Clarify text editing for Runner functions and MCP tools --- src/agents/run_config.py | 23 +++++++++++++++++------ tests/test_tool_text_transforms.py | 3 +++ 2 files changed, 20 insertions(+), 6 deletions(-) diff --git a/src/agents/run_config.py b/src/agents/run_config.py index 8abefc9b44..eafcd7ad04 100644 --- a/src/agents/run_config.py +++ b/src/agents/run_config.py @@ -187,6 +187,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 `((server, "lookup"), edit_text)` for MCP. Select the server + object and use the 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. """ @@ -290,19 +295,21 @@ async def prepare(ctx, declaration): 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. - For example, + Here, `report` is the agent's `FunctionTool`, `server` is the object in + `agent.mcp_servers`, and `lookup` is the raw MCP tool name. ```python - async def hide(call, texts): + async def edit_text(call, texts: tuple[str, ...]) -> tuple[str, ...]: return tuple(text.replace("internal draft", "[hidden]") for text in texts) config = ToolExecutionConfig(tool_text_transforms=[ - (report, hide), - ((server, "read.report"), hide), + (report, edit_text), + ((server, "lookup"), edit_text), ]) ``` - The editor receives ordered text slots and must return one string per slot. + The editor receives a tuple of strings. Return a 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 @@ -376,7 +383,11 @@ def __post_init__(self) -> None: ): key = (id(target[0]), target[1]) else: - raise ValueError("Invalid tool_text_transforms target.") + raise ValueError( + "For tool_text_transforms, use a local FunctionTool object or " + "(server, raw_tool_name) with the MCP server object and a nonempty " + "raw tool name. A server name string is invalid here." + ) if key in seen or not callable(edit): raise ValueError("Each tool_text_transforms target requires one editor.") seen.add(key) diff --git a/tests/test_tool_text_transforms.py b/tests/test_tool_text_transforms.py index b2e304bec5..9ef14573ca 100644 --- a/tests/test_tool_text_transforms.py +++ b/tests/test_tool_text_transforms.py @@ -406,6 +406,9 @@ async def edit(call, texts): {"tool_text_transforms": [((peer, "read.report"), edit)]} ) assert settings.tool_text_transforms[0][0][0] is peer + with pytest.raises(ValueError, match="MCP server object") as error: + ToolExecutionConfig(tool_text_transforms=[(("example-server", "read.report"), edit)]) + assert "example-server" not in str(error.value) and "read.report" not in str(error.value) for entries in [[("read.report", edit)], [((peer, "read.report"), edit)] * 2]: with pytest.raises(ValueError, match="tool_text_transforms"): ToolExecutionConfig(tool_text_transforms=entries) From f5079d2ce6affaf1a354b28fb7601d9ebf00c1d3 Mon Sep 17 00:00:00 2001 From: Mark Stuart Date: Mon, 23 Nov 2026 23:24:37 -0800 Subject: [PATCH 7/7] Clarify editor precedence and reject blank MCP tool names --- src/agents/run_config.py | 11 +++++++++-- tests/test_tool_text_transforms.py | 4 ++++ 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/src/agents/run_config.py b/src/agents/run_config.py index 94c9b6c50e..a264e3e9e5 100644 --- a/src/agents/run_config.py +++ b/src/agents/run_config.py @@ -196,8 +196,10 @@ def __post_init__(self) -> None: 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 or not callable(self.edit): - raise ValueError("MCPTextTransform requires a raw tool name and an async editor.") + 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 @@ -355,6 +357,11 @@ async def edit_text(call, texts): 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 diff --git a/tests/test_tool_text_transforms.py b/tests/test_tool_text_transforms.py index e84c4bdff8..680d7c67af 100644 --- a/tests/test_tool_text_transforms.py +++ b/tests/test_tool_text_transforms.py @@ -448,6 +448,10 @@ def report() -> str: 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],