Skip to content

Commit bd91ae6

Browse files
authored
fix(mcp): bind resumed MCP calls to their original recipients (#5119)
1 parent 88b722d commit bd91ae6

12 files changed

Lines changed: 792 additions & 41 deletions

‎integration_tests/packaging/test_run_state_compatibility.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
import pytest
66

77
from agents import Agent, RunState
8-
from agents.run_state import SUPPORTED_SCHEMA_VERSIONS
8+
from agents.run_state import CURRENT_SCHEMA_VERSION, SUPPORTED_SCHEMA_VERSIONS
99
from integration_tests._contract_state import (
1010
_deserialize_common_sandbox_session_state,
1111
_redaction_observables,
@@ -21,7 +21,7 @@
2121

2222

2323
def test_installed_distribution_supports_the_historical_fixture_corpus() -> None:
24-
assert frozenset(SOURCES["versions"]) == SUPPORTED_SCHEMA_VERSIONS
24+
assert frozenset(SOURCES["versions"]) | {CURRENT_SCHEMA_VERSION} == SUPPORTED_SCHEMA_VERSIONS
2525

2626

2727
@pytest.mark.parametrize(

‎src/agents/mcp/util.py‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -300,6 +300,7 @@ async def get_all_function_tools(
300300
agent,
301301
failure_error_function=failure_error_function,
302302
tool_name_overrides=tool_name_overrides,
303+
server_index=server_index,
303304
)
304305
server_tool_names = {tool.name for tool in function_tools}
305306
duplicate_tool_names = sorted(server_tool_names & tool_names)
@@ -313,13 +314,14 @@ async def get_all_function_tools(
313314

314315
return tools
315316

316-
for server in servers:
317+
for server_index, server in enumerate(servers):
317318
server_tools = await cls.get_function_tools(
318319
server,
319320
convert_schemas_to_strict,
320321
run_context,
321322
agent,
322323
failure_error_function=failure_error_function,
324+
server_index=server_index,
323325
)
324326
server_tool_names = {tool.name for tool in server_tools}
325327
duplicate_tool_names = sorted(server_tool_names & tool_names)
@@ -359,8 +361,9 @@ def _convert_mcp_tools_to_function_tools(
359361
agent: AgentBase,
360362
failure_error_function: ToolErrorFunction | None = default_tool_error_function,
361363
tool_name_overrides: list[str] | None = None,
364+
server_index: int = 0,
362365
) -> list[Tool]:
363-
return [
366+
function_tools = [
364367
cls.to_function_tool(
365368
tool,
366369
server,
@@ -373,6 +376,11 @@ def _convert_mcp_tools_to_function_tools(
373376
)
374377
for index, tool in enumerate(tools)
375378
]
379+
for function_tool in function_tools:
380+
assert function_tool._mcp_tool_binding is not None
381+
server_name, raw_tool_name, _ = function_tool._mcp_tool_binding
382+
function_tool._mcp_tool_binding = (server_name, raw_tool_name, server_index)
383+
return list(function_tools)
376384

377385
@classmethod
378386
async def get_function_tools(
@@ -411,6 +419,7 @@ async def get_function_tools(
411419
agent,
412420
failure_error_function=failure_error_function,
413421
tool_name_overrides=tool_name_overrides,
422+
server_index=server_index,
414423
)
415424

416425
@staticmethod
@@ -592,6 +601,7 @@ def to_function_tool(
592601
mcp_server_name=get_mcp_server_log_name(server.name),
593602
),
594603
)
604+
function_tool._mcp_tool_binding = (get_mcp_server_log_name(server.name), tool.name, None)
595605
return function_tool
596606

597607
@staticmethod

‎src/agents/run_internal/run_steps.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,10 @@ class ProcessedResponse:
131131
default_factory=list
132132
)
133133
custom_tool_calls: list[ToolRunCustom] = dataclasses.field(default_factory=list)
134+
mcp_tool_bindings: dict[str, tuple[str, str, int | None]] = dataclasses.field(
135+
default_factory=dict
136+
)
137+
# Original invocation recipients, independent of the currently available callables.
134138

135139
def has_tools_or_approvals_to_run(self) -> bool:
136140
# Handoffs, functions and computer actions need local processing

‎src/agents/run_internal/turn_resolution.py‎

Lines changed: 40 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1224,6 +1224,12 @@ async def _record_function_rejection(
12241224
) -> None:
12251225
if isinstance(call_id, str) and call_id in rejected_function_call_ids:
12261226
return
1227+
approval_record = (
1228+
function_approval_items_by_call_id.get(call_id)
1229+
or approval_items_by_call_id.get(call_id)
1230+
if call_id
1231+
else None
1232+
)
12271233
rejection_message = REJECTION_MESSAGE
12281234
if call_id:
12291235
tool_namespace = get_tool_call_namespace(tool_call)
@@ -1236,10 +1242,7 @@ async def _record_function_rejection(
12361242
call_id=call_id,
12371243
tool_namespace=tool_namespace,
12381244
tool_lookup_key=get_function_tool_lookup_key_for_tool(function_tool),
1239-
existing_pending=(
1240-
function_approval_items_by_call_id.get(call_id)
1241-
or approval_items_by_call_id.get(call_id)
1242-
),
1245+
existing_pending=approval_record,
12431246
)
12441247
rejected_function_outputs.append(
12451248
function_rejection_item(
@@ -1248,7 +1251,11 @@ async def _record_function_rejection(
12481251
rejection_message=rejection_message,
12491252
output_json_schema=function_tool.output_json_schema,
12501253
scope_id=tool_state_scope_id,
1251-
tool_origin=get_function_tool_origin(function_tool),
1254+
tool_origin=(
1255+
approval_record.tool_origin
1256+
if approval_record is not None
1257+
else get_function_tool_origin(function_tool)
1258+
),
12521259
)
12531260
)
12541261
if isinstance(call_id, str):
@@ -2160,8 +2167,26 @@ def _rebind_function_run(
21602167
else True
21612168
)
21622169
stale_function = stale_functions.get(call_id)
2170+
original_binding = processed_response.mcp_tool_bindings.get(call_id)
21632171
current_function = current_functions.get(call_id)
21642172
if current_function is not None:
2173+
current_binding = current_function.function_tool._mcp_tool_binding
2174+
missing_mcp_binding = (
2175+
original_binding is None
2176+
and approval_record is not None
2177+
and approval_record.tool_origin is not None
2178+
and approval_record.tool_origin.type == ToolOriginType.MCP
2179+
)
2180+
# Rejected calls cannot execute. MCP approvals must not authorize a
2181+
# different MCP recipient or a local replacement's approval policy.
2182+
if approval_status is not False and (
2183+
missing_mcp_binding or original_binding != current_binding
2184+
):
2185+
raise UserError(
2186+
"Cannot resume a local MCP tool call with a missing or different recipient "
2187+
"binding. Restore the original MCP server configuration and tool listing, "
2188+
"or start a new run."
2189+
)
21652190
reconciled_functions.append(_rebind_function_run(stale_function, current_function))
21662191
continue
21672192

@@ -2180,6 +2205,11 @@ def _rebind_function_run(
21802205
),
21812206
)
21822207
if current_handoff is not None and approval_status is True:
2208+
if original_binding is not None:
2209+
raise UserError(
2210+
"Cannot resume a local MCP tool call as a handoff. Restore the original "
2211+
"tool configuration, or start a new run."
2212+
)
21832213
if stale_function is not None:
21842214
_reject_nested_replacement(stale_function)
21852215
reconciled_handoffs.append(current_handoff)
@@ -3440,6 +3470,11 @@ def _dump_output_item(raw_item: Any) -> dict[str, Any]:
34403470
mcp_approval_requests=mcp_approval_requests,
34413471
interruptions=[],
34423472
function_tools_not_found=function_tools_not_found,
3473+
mcp_tool_bindings={
3474+
run.tool_call.call_id: binding
3475+
for run in functions
3476+
if (binding := run.function_tool._mcp_tool_binding) is not None
3477+
},
34433478
)
34443479

34453480

‎src/agents/run_state.py‎

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -190,7 +190,7 @@ def _default_run_state_validation_error(
190190
# 3. to_json() always emits CURRENT_SCHEMA_VERSION.
191191
# 4. Forward compatibility is intentionally fail-fast (older SDKs reject newer or unsupported
192192
# versions).
193-
CURRENT_SCHEMA_VERSION = "1.17"
193+
CURRENT_SCHEMA_VERSION = "1.18"
194194
_PROGRAMMATIC_TOOL_CALLING_MIN_SCHEMA_VERSION = "1.13"
195195
_HOSTED_MCP_APPROVALS_MIN_SCHEMA_VERSION = "1.14"
196196
_CURRENT_RESPONSE_OWNERSHIP_MIN_SCHEMA_VERSION = "1.17"
@@ -229,6 +229,7 @@ def _default_run_state_validation_error(
229229
"Persists Docker container labels and current-response generated-item ownership across "
230230
"resume flows, including pending resumed Session writes and terminal-unrecoverable runs."
231231
),
232+
"1.18": "Binds restored local MCP calls to their configured server and original tool name.",
232233
}
233234
SUPPORTED_SCHEMA_VERSIONS = frozenset(SCHEMA_VERSION_SUMMARIES)
234235

@@ -1984,6 +1985,10 @@ def _serialize_processed_response(
19841985
"tools_used": processed_response.tools_used,
19851986
**action_groups,
19861987
"interruptions": interruptions_data,
1988+
"mcp_tool_bindings": {
1989+
call_id: list(binding)
1990+
for call_id, binding in processed_response.mcp_tool_bindings.items()
1991+
},
19871992
}
19881993

19891994
def _serialize_current_step(self) -> dict[str, Any] | None:
@@ -2209,6 +2214,13 @@ async def from_string(
22092214
server and apply authorized approval decisions to that server-owned state instead.
22102215
Neither `context_override` nor `strict_context` verifies snapshot integrity.
22112216
2217+
Executing pending local MCP calls requires recipient bindings written by schema 1.18
2218+
or later.
2219+
Keep the application's MCP server configuration and ordering unchanged when resuming.
2220+
Bindings detect changes in tool-list routing, not transport settings or credentials.
2221+
Start a new run to replace a pending MCP call with a local function or handoff.
2222+
Start a new run to execute an MCP call if an older snapshot lacks these bindings.
2223+
22122224
Args:
22132225
initial_agent: The initial agent (used to build agent map for resolution).
22142226
state_string: The JSON string to deserialize.
@@ -2290,6 +2302,13 @@ async def from_json(
22902302
server and apply authorized approval decisions to that server-owned state instead.
22912303
Neither `context_override` nor `strict_context` verifies snapshot integrity.
22922304
2305+
Executing pending local MCP calls requires recipient bindings written by schema 1.18
2306+
or later.
2307+
Keep the application's MCP server configuration and ordering unchanged when resuming.
2308+
Bindings detect changes in tool-list routing, not transport settings or credentials.
2309+
Start a new run to replace a pending MCP call with a local function or handoff.
2310+
Start a new run to execute an MCP call if an older snapshot lacks these bindings.
2311+
22932312
Args:
22942313
initial_agent: The initial agent (used to build agent map for resolution).
22952314
state_json: The JSON dictionary to deserialize.
@@ -3421,6 +3440,13 @@ def _deserialize_function_actions() -> list[_DeserializedFunctionAction]:
34213440
if approval_item is not None:
34223441
interruptions.append(approval_item)
34233442

3443+
saved_bindings = processed_response_data.get("mcp_tool_bindings", {})
3444+
mcp_tool_bindings = {
3445+
call_id: cast(tuple[str, str, int | None], tuple(binding))
3446+
for call_id, binding in saved_bindings.items()
3447+
if isinstance(binding, list)
3448+
}
3449+
34243450
return ProcessedResponse(
34253451
new_items=new_items,
34263452
handoffs=handoffs,
@@ -3433,6 +3459,7 @@ def _deserialize_function_actions() -> list[_DeserializedFunctionAction]:
34333459
tools_used=processed_response_data.get("tools_used", []),
34343460
mcp_approval_requests=mcp_approval_requests,
34353461
interruptions=interruptions,
3462+
mcp_tool_bindings=mcp_tool_bindings,
34363463
)
34373464

34383465

‎src/agents/tool.py‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -589,6 +589,11 @@ class FunctionTool:
589589
_emit_tool_origin: bool = field(default=True, kw_only=True, repr=False)
590590
"""Whether runtime item generation should emit tool origin metadata for this tool."""
591591

592+
_mcp_tool_binding: tuple[str, str, int | None] | None = field(
593+
default=None, kw_only=True, repr=False
594+
)
595+
"""Original MCP server name, raw tool name, and configured server position for resume."""
596+
592597
@property
593598
def qualified_name(self) -> str:
594599
"""Return the public qualified name used to identify this function tool."""

0 commit comments

Comments
 (0)