Skip to content

Commit dbec565

Browse files
committed
fix(mcp): add explicit tool_result_content selection policy
Replace hard-coded content-first behavior with structured_first/content_first/content_only/structured_only/both, defaulting to structured_first per microsoft#7866 discussion.
1 parent 6d58210 commit dbec565

2 files changed

Lines changed: 100 additions & 7 deletions

File tree

‎python/packages/core/agent_framework/_mcp.py‎

Lines changed: 70 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,29 @@ class MCPSpecificApproval(TypedDict, total=False):
9797
never_require_approval: Collection[str] | None
9898

9999

100+
101+
MCPToolResultContentMode = Literal[
102+
"structured_first",
103+
"content_first",
104+
"content_only",
105+
"structured_only",
106+
"both",
107+
]
108+
"""How model-visible text is selected when a tool result has both ``content`` and ``structuredContent``.
109+
110+
MCP servers disagree on whether the two fields are duplicates or complementary (#7866).
111+
Callers pick an explicit policy:
112+
113+
- ``structured_first`` (default): use ``structuredContent`` when present, else ``content``
114+
- ``content_first``: use ``content`` when non-empty, else ``structuredContent``
115+
- ``content_only``: ignore ``structuredContent`` for the model-visible result
116+
- ``structured_only``: ignore ``content`` for the model-visible result
117+
- ``both``: append serialized ``structuredContent`` after ``content`` blocks
118+
119+
The full MCP payload is still retained on the Host channel regardless of mode.
120+
Custom ``parse_tool_results`` overrides this policy entirely.
121+
"""
122+
100123
_MCP_REMOTE_NAME_KEY = "_mcp_remote_name"
101124
_MCP_NORMALIZED_NAME_KEY = "_mcp_normalized_name"
102125
_MCP_TOOL_RESULT_HOST_PAYLOAD_KEY = "_mcp_tool_result_host_payload"
@@ -839,6 +862,7 @@ def __init__(
839862
always_load: Collection[str] | None = None,
840863
*,
841864
max_host_payload_size_bytes: int | None = _DEFAULT_MCP_HOST_PAYLOAD_SIZE_BYTES,
865+
tool_result_content: MCPToolResultContentMode = "structured_first",
842866
) -> None:
843867
"""Initialize the MCP Tool base.
844868
@@ -908,6 +932,9 @@ def __init__(
908932
max_host_payload_size_bytes: Maximum encoded size of the complete MCP result retained
909933
for Host transports. Oversized payloads are omitted from the Host channel while
910934
the parsed model result is preserved. Set to ``None`` to disable the limit.
935+
tool_result_content: How to choose model-visible text when both ``content`` and
936+
``structuredContent`` are present. See :data:`MCPToolResultContentMode`.
937+
Ignored when ``parse_tool_results`` is set. Default ``structured_first``.
911938
"""
912939
if use_progressive_disclosure and not load_tools:
913940
raise ValueError("use_progressive_disclosure=True requires load_tools=True.")
@@ -920,6 +947,18 @@ def __init__(
920947
)
921948
if max_host_payload_size_bytes is not None and max_host_payload_size_bytes <= 0:
922949
raise ValueError("max_host_payload_size_bytes must be positive or None.")
950+
allowed_modes = {
951+
"structured_first",
952+
"content_first",
953+
"content_only",
954+
"structured_only",
955+
"both",
956+
}
957+
if tool_result_content not in allowed_modes:
958+
raise ValueError(
959+
f"tool_result_content must be one of {sorted(allowed_modes)}, "
960+
f"got {tool_result_content!r}."
961+
)
923962
self.name = name
924963
self.description = description or ""
925964
self.approval_mode = approval_mode
@@ -928,6 +967,7 @@ def __init__(
928967
self.additional_properties = additional_properties
929968
self.load_tools_flag = load_tools
930969
self.parse_tool_results = parse_tool_results
970+
self.tool_result_content = tool_result_content
931971
self.load_prompts_flag = load_prompts
932972
self.parse_prompt_results = parse_prompt_results
933973
self.max_host_payload_size_bytes = max_host_payload_size_bytes
@@ -1110,11 +1150,30 @@ def _parse_tool_result_from_mcp(
11101150
case _:
11111151
result.append(Content.from_text(str(item), **additional_kwargs))
11121152

1113-
# Prefer content blocks for the model-visible result. structuredContent is
1114-
# still retained on the Host payload; appending it again here duplicates
1115-
# what many servers already serialize into content (#7866).
1116-
if mcp_type.structuredContent is not None and not result:
1117-
result.append(Content.from_text(json.dumps(mcp_type.structuredContent, default=str), **additional_kwargs))
1153+
structured_block: Content | None = None
1154+
if mcp_type.structuredContent is not None:
1155+
structured_block = Content.from_text(
1156+
json.dumps(mcp_type.structuredContent, default=str), **additional_kwargs
1157+
)
1158+
1159+
# Select model-visible content per explicit policy (#7866). Host payload still
1160+
# retains the full MCP result regardless of this choice.
1161+
mode = self.tool_result_content
1162+
if mode == "both":
1163+
if structured_block is not None:
1164+
result.append(structured_block)
1165+
elif mode == "content_only":
1166+
pass
1167+
elif mode == "structured_only":
1168+
result = [structured_block] if structured_block is not None else []
1169+
elif mode == "content_first":
1170+
if not result and structured_block is not None:
1171+
result.append(structured_block)
1172+
elif mode == "structured_first":
1173+
if structured_block is not None:
1174+
result = [structured_block]
1175+
else: # pragma: no cover - validated in __init__
1176+
raise ValueError(f"Unknown tool_result_content mode: {mode!r}")
11181177

11191178
if not result:
11201179
result.append(Content.from_text("null", **additional_kwargs))
@@ -3284,6 +3343,7 @@ def __init__(
32843343
task_options: MCPTaskOptions | None = None,
32853344
additional_tool_argument_names: Sequence[str] | Mapping[str, Sequence[str]] | None = None,
32863345
max_host_payload_size_bytes: int | None = _DEFAULT_MCP_HOST_PAYLOAD_SIZE_BYTES,
3346+
tool_result_content: MCPToolResultContentMode = "structured_first",
32873347
**kwargs: Any,
32883348
) -> None:
32893349
"""Initialize the MCP stdio tool.
@@ -3400,6 +3460,7 @@ def __init__(
34003460
sampling_max_tokens=sampling_max_tokens,
34013461
sampling_max_requests=sampling_max_requests,
34023462
max_host_payload_size_bytes=max_host_payload_size_bytes,
3463+
tool_result_content=tool_result_content,
34033464
)
34043465
self.command = command
34053466
self.args = args or []
@@ -3486,6 +3547,7 @@ def __init__(
34863547
task_options: MCPTaskOptions | None = None,
34873548
additional_tool_argument_names: Sequence[str] | Mapping[str, Sequence[str]] | None = None,
34883549
max_host_payload_size_bytes: int | None = _DEFAULT_MCP_HOST_PAYLOAD_SIZE_BYTES,
3550+
tool_result_content: MCPToolResultContentMode = "structured_first",
34893551
**kwargs: Any,
34903552
) -> None:
34913553
"""Initialize the MCP streamable HTTP tool.
@@ -3646,6 +3708,7 @@ def __init__(
36463708
sampling_max_tokens=sampling_max_tokens,
36473709
sampling_max_requests=sampling_max_requests,
36483710
max_host_payload_size_bytes=max_host_payload_size_bytes,
3711+
tool_result_content=tool_result_content,
36493712
)
36503713
self.url = url
36513714
self.terminate_on_close = terminate_on_close
@@ -3892,6 +3955,7 @@ def __init__(
38923955
task_options: MCPTaskOptions | None = None,
38933956
additional_tool_argument_names: Sequence[str] | Mapping[str, Sequence[str]] | None = None,
38943957
max_host_payload_size_bytes: int | None = _DEFAULT_MCP_HOST_PAYLOAD_SIZE_BYTES,
3958+
tool_result_content: MCPToolResultContentMode = "structured_first",
38953959
**kwargs: Any,
38963960
) -> None:
38973961
"""Initialize the MCP WebSocket tool.
@@ -4006,6 +4070,7 @@ def __init__(
40064070
sampling_max_tokens=sampling_max_tokens,
40074071
sampling_max_requests=sampling_max_requests,
40084072
max_host_payload_size_bytes=max_host_payload_size_bytes,
4073+
tool_result_content=tool_result_content,
40094074
)
40104075
self.url = url
40114076
self._client_kwargs = kwargs

‎python/packages/core/tests/core/test_mcp.py‎

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -546,7 +546,7 @@ def test_parse_tool_result_from_mcp_structured_content_only():
546546

547547

548548
def test_parse_tool_result_from_mcp_structured_content_with_text():
549-
"""When content is present, do not also dump structuredContent into model text (#7866)."""
549+
"""Default structured_first prefers structuredContent when both are present (#7866)."""
550550
mcp_result = types.CallToolResult(
551551
content=[types.TextContent(type="text", text="Summary")],
552552
structuredContent={"data": [1, 2, 3]},
@@ -556,7 +556,35 @@ def test_parse_tool_result_from_mcp_structured_content_with_text():
556556
assert isinstance(result, list)
557557
assert len(result) == 1
558558
assert result[0].type == "text"
559-
assert result[0].text == "Summary"
559+
assert json.loads(result[0].text) == {"data": [1, 2, 3]}
560+
561+
562+
def test_parse_tool_result_content_modes_for_complementary_and_duplicate_payloads():
563+
"""tool_result_content covers structured-only, content-only, either-first, and both."""
564+
mcp_result = types.CallToolResult(
565+
content=[types.TextContent(type="text", text="Summary")],
566+
structuredContent={"data": [1, 2, 3]},
567+
)
568+
569+
content_first = MCPTool(name="helper", tool_result_content="content_first") # type: ignore[abstract]
570+
assert [c.text for c in content_first._parse_tool_result_from_mcp(mcp_result)] == ["Summary"]
571+
572+
content_only = MCPTool(name="helper", tool_result_content="content_only") # type: ignore[abstract]
573+
assert [c.text for c in content_only._parse_tool_result_from_mcp(mcp_result)] == ["Summary"]
574+
575+
structured_only = MCPTool(name="helper", tool_result_content="structured_only") # type: ignore[abstract]
576+
assert json.loads(structured_only._parse_tool_result_from_mcp(mcp_result)[0].text) == {"data": [1, 2, 3]}
577+
578+
both = MCPTool(name="helper", tool_result_content="both") # type: ignore[abstract]
579+
both_result = both._parse_tool_result_from_mcp(mcp_result)
580+
assert both_result[0].text == "Summary"
581+
assert json.loads(both_result[1].text) == {"data": [1, 2, 3]}
582+
583+
structured_only_empty = types.CallToolResult(content=[], structuredContent={"x": 1})
584+
assert json.loads(content_first._parse_tool_result_from_mcp(structured_only_empty)[0].text) == {"x": 1}
585+
586+
empty = types.CallToolResult(content=[], structuredContent=None)
587+
assert content_only._parse_tool_result_from_mcp(empty)[0].text == "null"
560588

561589

562590
async def test_generated_mcp_tool_preserves_complete_host_payload_once() -> None:

0 commit comments

Comments
 (0)