Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 12 additions & 8 deletions src/agents/mcp/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,14 +35,6 @@
from ..tracing import FunctionSpanData, get_current_span, mcp_tools_span
from ..util._custom_data import maybe_extract_custom_data
from ..util._types import MaybeAwaitable
from ._compat import (
MCPError,
image_mime_type,
mcp_error_message,
result_is_error,
result_structured_content,
tool_input_schema,
)
from ._logging import get_mcp_server_log_message, get_mcp_server_log_name

if TYPE_CHECKING:
Expand Down Expand Up @@ -535,6 +527,8 @@ def to_function_tool(
policies. If the server uses a callable approval policy, approvals default
to required to avoid bypassing dynamic checks.
"""
from ._compat import tool_input_schema

tool_public_name = tool_name_override or tool.name
static_meta = cls._extract_static_meta(tool)
defaults = _DiscoveredToolMeta(static_meta) if static_meta is not None else None
Expand Down Expand Up @@ -654,6 +648,8 @@ async def _extract_custom_data(
if extractor is None:
return None

from ._compat import result_is_error, result_structured_content

extractor_context = MCPToolCustomDataContext(
run_context=context,
server_name=server.name,
Expand Down Expand Up @@ -707,6 +703,14 @@ async def invoke_mcp_tool(
tool_display_name: str | None = None,
) -> ToolOutput:
"""Invoke an MCP tool and return the result as ToolOutput."""
from ._compat import (
MCPError,
image_mime_type,
mcp_error_message,
result_is_error,
result_structured_content,
)

tool_name_for_display = tool_display_name or tool.name
json_decode_error: Exception | None = None
try:
Expand Down
12 changes: 9 additions & 3 deletions src/agents/run_state.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from collections import deque
from collections.abc import Callable, Collection, Mapping, Sequence
from dataclasses import dataclass, field
from functools import cache
from typing import TYPE_CHECKING, Annotated, Any, Generic, Literal, cast, get_args
from uuid import uuid4

Expand Down Expand Up @@ -340,7 +341,6 @@ class _LocalShellCallOutputPayload(TypedDict):
FunctionCallOutput | ComputerCallOutput | LocalShellCallOutput
] = TypeAdapter(FunctionCallOutput | ComputerCallOutput | LocalShellCallOutput)
_MCP_APPROVAL_RESPONSE_ADAPTER: TypeAdapter[McpApprovalResponse] = TypeAdapter(McpApprovalResponse)
_HANDOFF_OUTPUT_ADAPTER: TypeAdapter[TResponseInputItem] = TypeAdapter(TResponseInputItem)
_LOCAL_SHELL_CALL_ADAPTER: TypeAdapter[LocalShellCall] = TypeAdapter(LocalShellCall)
_TOOL_APPROVAL_MODEL_TYPES: tuple[type[BaseModel], ...] = tuple(
raw_item_type
Expand All @@ -358,6 +358,12 @@ class _LocalShellCallOutputPayload(TypedDict):
_ALLOWED_MISSING_MESSAGE_FIELDS = frozenset({"status"})


@cache
def _response_input_adapter() -> TypeAdapter[TResponseInputItem]:
"""Build the large input union only when restoring a handoff or compaction item."""
return TypeAdapter(TResponseInputItem)


def _deserialize_tool_origin(data: Any) -> ToolOrigin | None:
"""Best-effort deserialization for optional tool origin metadata."""
return ToolOrigin.from_json_dict(data)
Expand Down Expand Up @@ -5376,7 +5382,7 @@ def _resolve_agent_info(
# as a TResponseInputItem (which is a union type)
# If validation fails, use the raw dict as-is (for test compatibility)
try:
raw_item_handoff_output = _HANDOFF_OUTPUT_ADAPTER.validate_python(
raw_item_handoff_output = _response_input_adapter().validate_python(
normalized_raw_item
)
except ValidationError:
Expand All @@ -5395,7 +5401,7 @@ def _resolve_agent_info(

elif item_type == "compaction_item":
try:
raw_item_compaction = _HANDOFF_OUTPUT_ADAPTER.validate_python(
raw_item_compaction = _response_input_adapter().validate_python(
normalized_raw_item
)
except ValidationError:
Expand Down
29 changes: 29 additions & 0 deletions tests/test_run_state.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@
)
from agents.handoffs import Handoff
from agents.items import (
CompactionItem,
HandoffOutputItem,
ItemHelpers,
MCPApprovalResponseItem,
Expand Down Expand Up @@ -4946,6 +4947,34 @@ async def test_serialization_includes_handoff_fields(self):
assert len(restored._generated_items) == 1
assert restored._generated_items[0].type == "handoff_output_item"

async def test_handoff_and_compaction_replay_after_restore(self):
target = Agent(name="target")
source = Agent(name="source", handoffs=[target])
state = make_state(source, context=RunContextWrapper(context=None))
output: TResponseInputItem = {
"type": "function_call_output",
"call_id": "transfer",
"output": [{"type": "input_text", "text": "accepted"}],
}
compaction: TResponseInputItem = {
"type": "compaction",
"id": "cmp_1",
"encrypted_content": "opaque",
}
state._generated_items.extend(
[
HandoffOutputItem(
agent=target, source_agent=source, target_agent=target, raw_item=output
),
CompactionItem(agent=target, raw_item=compaction),
]
)

restored = await RunState.from_string(source, state.to_string())

assert [item.to_input_item() for item in restored._generated_items] == [output, compaction]
assert all(item.agent is target for item in restored._generated_items)

async def test_model_response_serialization_roundtrip(self):
"""Test that model responses serialize and deserialize correctly."""

Expand Down
33 changes: 33 additions & 0 deletions tests/tracing/test_import_side_effects.py
Original file line number Diff line number Diff line change
Expand Up @@ -354,3 +354,36 @@ def fake_register(fn):
assert payload["shutdown_registration_count"] == 1
assert payload["exporter_initialized"] is False
assert payload["processor_initialized"] is False


def test_first_local_tool_run_does_not_load_mcp() -> None:
payload = _run_python(
"""
import json
import sys

from agents import Agent, RunConfig, Runner
from agents.decorators import tool
from agents.testing import ScriptedModel, assistant_message, function_call

@tool
async def increment(value: int) -> int:
return value + 1

model = ScriptedModel([
[function_call("increment", {"value": 1}, call_id="call_1")],
[assistant_message("done")],
])
agent = Agent(name="local", model=model, tools=[increment])
result = Runner.run_sync(agent, "start", run_config=RunConfig(tracing_disabled=True))
model.assert_complete()

print(json.dumps({
"answer": result.final_output,
"tool_output": model.calls[1].input[-1]["output"],
"mcp_loaded": "mcp" in sys.modules,
}))
"""
)

assert payload == {"answer": "done", "tool_output": "2", "mcp_loaded": False}
Loading