Skip to content

Commit e584a9f

Browse files
authored
Python: fix(mcp): do not duplicate structuredContent when content present (microsoft#8274)
* fix(mcp): do not duplicate structuredContent when content present Fixes microsoft#7866. Prefer content blocks for model-visible tool results; structuredContent remains on the Host payload. Serialize structuredContent only when content is empty. * test(mcp): align expectations with single content+structured item Address Copilot review on microsoft#8274: update suites that still expected the old duplicated model-visible content shape. * 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. * fix(mcp): document tool_result_content and tighten test typing Add undocumented-param docstring entries on MCP transport constructors and assert tool result text before json.loads.
1 parent d341515 commit e584a9f

2 files changed

Lines changed: 115 additions & 11 deletions

File tree

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

Lines changed: 75 additions & 1 deletion
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"
@@ -869,6 +892,7 @@ def __init__(
869892
always_load: Collection[str] | None = None,
870893
*,
871894
max_host_payload_size_bytes: int | None = _DEFAULT_MCP_HOST_PAYLOAD_SIZE_BYTES,
895+
tool_result_content: MCPToolResultContentMode = "structured_first",
872896
) -> None:
873897
"""Initialize the MCP Tool base.
874898
@@ -938,6 +962,9 @@ def __init__(
938962
max_host_payload_size_bytes: Maximum encoded size of the complete MCP result retained
939963
for Host transports. Oversized payloads are omitted from the Host channel while
940964
the parsed model result is preserved. Set to ``None`` to disable the limit.
965+
tool_result_content: How to choose model-visible text when both ``content`` and
966+
``structuredContent`` are present. See :data:`MCPToolResultContentMode`.
967+
Ignored when ``parse_tool_results`` is set. Default ``structured_first``.
941968
"""
942969
if use_progressive_disclosure and not load_tools:
943970
raise ValueError("use_progressive_disclosure=True requires load_tools=True.")
@@ -950,6 +977,18 @@ def __init__(
950977
)
951978
if max_host_payload_size_bytes is not None and max_host_payload_size_bytes <= 0:
952979
raise ValueError("max_host_payload_size_bytes must be positive or None.")
980+
allowed_modes = {
981+
"structured_first",
982+
"content_first",
983+
"content_only",
984+
"structured_only",
985+
"both",
986+
}
987+
if tool_result_content not in allowed_modes:
988+
raise ValueError(
989+
f"tool_result_content must be one of {sorted(allowed_modes)}, "
990+
f"got {tool_result_content!r}."
991+
)
953992
self.name = name
954993
self.description = description or ""
955994
self.approval_mode = approval_mode
@@ -958,6 +997,7 @@ def __init__(
958997
self.additional_properties = additional_properties
959998
self.load_tools_flag = load_tools
960999
self.parse_tool_results = parse_tool_results
1000+
self.tool_result_content = tool_result_content
9611001
self.load_prompts_flag = load_prompts
9621002
self.parse_prompt_results = parse_prompt_results
9631003
self.max_host_payload_size_bytes = max_host_payload_size_bytes
@@ -1140,8 +1180,30 @@ def _parse_tool_result_from_mcp(
11401180
case _:
11411181
result.append(Content.from_text(str(item), **additional_kwargs))
11421182

1183+
structured_block: Content | None = None
11431184
if mcp_type.structuredContent is not None:
1144-
result.append(Content.from_text(json.dumps(mcp_type.structuredContent, default=str), **additional_kwargs))
1185+
structured_block = Content.from_text(
1186+
json.dumps(mcp_type.structuredContent, default=str), **additional_kwargs
1187+
)
1188+
1189+
# Select model-visible content per explicit policy (#7866). Host payload still
1190+
# retains the full MCP result regardless of this choice.
1191+
mode = self.tool_result_content
1192+
if mode == "both":
1193+
if structured_block is not None:
1194+
result.append(structured_block)
1195+
elif mode == "content_only":
1196+
pass
1197+
elif mode == "structured_only":
1198+
result = [structured_block] if structured_block is not None else []
1199+
elif mode == "content_first":
1200+
if not result and structured_block is not None:
1201+
result.append(structured_block)
1202+
elif mode == "structured_first":
1203+
if structured_block is not None:
1204+
result = [structured_block]
1205+
else: # pragma: no cover - validated in __init__
1206+
raise ValueError(f"Unknown tool_result_content mode: {mode!r}")
11451207

11461208
if not result:
11471209
result.append(Content.from_text("null", **additional_kwargs))
@@ -3372,6 +3434,7 @@ def __init__(
33723434
task_options: MCPTaskOptions | None = None,
33733435
additional_tool_argument_names: Sequence[str] | Mapping[str, Sequence[str]] | None = None,
33743436
max_host_payload_size_bytes: int | None = _DEFAULT_MCP_HOST_PAYLOAD_SIZE_BYTES,
3437+
tool_result_content: MCPToolResultContentMode = "structured_first",
33753438
**kwargs: Any,
33763439
) -> None:
33773440
"""Initialize the MCP stdio tool.
@@ -3464,6 +3527,8 @@ def __init__(
34643527
process you do not control.
34653528
max_host_payload_size_bytes: Maximum encoded MCP result size retained for Host
34663529
transports. ``None`` disables the limit.
3530+
tool_result_content: How to choose model-visible text when both ``content`` and
3531+
``structuredContent`` are present. See :data:`MCPToolResultContentMode`.
34673532
kwargs: Any extra arguments to pass to the stdio client.
34683533
"""
34693534
super().__init__(
@@ -3488,6 +3553,7 @@ def __init__(
34883553
sampling_max_tokens=sampling_max_tokens,
34893554
sampling_max_requests=sampling_max_requests,
34903555
max_host_payload_size_bytes=max_host_payload_size_bytes,
3556+
tool_result_content=tool_result_content,
34913557
)
34923558
self.command = command
34933559
self.args = args or []
@@ -3575,6 +3641,7 @@ def __init__(
35753641
task_options: MCPTaskOptions | None = None,
35763642
additional_tool_argument_names: Sequence[str] | Mapping[str, Sequence[str]] | None = None,
35773643
max_host_payload_size_bytes: int | None = _DEFAULT_MCP_HOST_PAYLOAD_SIZE_BYTES,
3644+
tool_result_content: MCPToolResultContentMode = "structured_first",
35783645
**kwargs: Any,
35793646
) -> None:
35803647
"""Initialize the MCP streamable HTTP tool.
@@ -3733,6 +3800,8 @@ def __init__(
37333800
``http_client``.
37343801
max_host_payload_size_bytes: Maximum encoded MCP result size retained for Host
37353802
transports. ``None`` disables the limit.
3803+
tool_result_content: How to choose model-visible text when both ``content`` and
3804+
``structuredContent`` are present. See :data:`MCPToolResultContentMode`.
37363805
kwargs: Additional keyword arguments (accepted for backward compatibility but not used).
37373806
"""
37383807
super().__init__(
@@ -3757,6 +3826,7 @@ def __init__(
37573826
sampling_max_tokens=sampling_max_tokens,
37583827
sampling_max_requests=sampling_max_requests,
37593828
max_host_payload_size_bytes=max_host_payload_size_bytes,
3829+
tool_result_content=tool_result_content,
37603830
)
37613831
self.url = url
37623832
self.terminate_on_close = terminate_on_close
@@ -4165,6 +4235,7 @@ def __init__(
41654235
task_options: MCPTaskOptions | None = None,
41664236
additional_tool_argument_names: Sequence[str] | Mapping[str, Sequence[str]] | None = None,
41674237
max_host_payload_size_bytes: int | None = _DEFAULT_MCP_HOST_PAYLOAD_SIZE_BYTES,
4238+
tool_result_content: MCPToolResultContentMode = "structured_first",
41684239
**kwargs: Any,
41694240
) -> None:
41704241
"""Initialize the MCP WebSocket tool.
@@ -4255,6 +4326,8 @@ def __init__(
42554326
``function_invocation_kwargs`` for servers you do not control.
42564327
max_host_payload_size_bytes: Maximum encoded MCP result size retained for Host
42574328
transports. ``None`` disables the limit.
4329+
tool_result_content: How to choose model-visible text when both ``content`` and
4330+
``structuredContent`` are present. See :data:`MCPToolResultContentMode`.
42584331
kwargs: Any extra arguments to pass to the WebSocket client.
42594332
"""
42604333
super().__init__(
@@ -4279,6 +4352,7 @@ def __init__(
42794352
sampling_max_tokens=sampling_max_tokens,
42804353
sampling_max_requests=sampling_max_requests,
42814354
max_host_payload_size_bytes=max_host_payload_size_bytes,
4355+
tool_result_content=tool_result_content,
42824356
)
42834357
self.url = url
42844358
self._client_kwargs = kwargs

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

Lines changed: 40 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -546,21 +546,51 @@ 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-
"""Test that structuredContent is appended alongside regular content items."""
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]},
553553
)
554554
result = _HELPER_MCP_TOOL._parse_tool_result_from_mcp(mcp_result)
555555

556556
assert isinstance(result, list)
557-
assert len(result) == 2
557+
assert len(result) == 1
558558
assert result[0].type == "text"
559-
assert result[0].text == "Summary"
560-
assert result[1].type == "text"
561-
assert result[1].text is not None
562-
parsed = json.loads(result[1].text)
563-
assert parsed == {"data": [1, 2, 3]}
559+
assert result[0].text is not None
560+
assert json.loads(result[0].text) == {"data": [1, 2, 3]}
561+
562+
563+
def test_parse_tool_result_content_modes_for_complementary_and_duplicate_payloads():
564+
"""tool_result_content covers structured-only, content-only, either-first, and both."""
565+
mcp_result = types.CallToolResult(
566+
content=[types.TextContent(type="text", text="Summary")],
567+
structuredContent={"data": [1, 2, 3]},
568+
)
569+
570+
content_first = MCPTool(name="helper", tool_result_content="content_first") # type: ignore[abstract]
571+
assert [c.text for c in content_first._parse_tool_result_from_mcp(mcp_result)] == ["Summary"]
572+
573+
content_only = MCPTool(name="helper", tool_result_content="content_only") # type: ignore[abstract]
574+
assert [c.text for c in content_only._parse_tool_result_from_mcp(mcp_result)] == ["Summary"]
575+
576+
structured_only = MCPTool(name="helper", tool_result_content="structured_only") # type: ignore[abstract]
577+
structured_only_text = structured_only._parse_tool_result_from_mcp(mcp_result)[0].text
578+
assert structured_only_text is not None
579+
assert json.loads(structured_only_text) == {"data": [1, 2, 3]}
580+
581+
both = MCPTool(name="helper", tool_result_content="both") # type: ignore[abstract]
582+
both_result = both._parse_tool_result_from_mcp(mcp_result)
583+
assert both_result[0].text == "Summary"
584+
assert both_result[1].text is not None
585+
assert json.loads(both_result[1].text) == {"data": [1, 2, 3]}
586+
587+
structured_only_empty = types.CallToolResult(content=[], structuredContent={"x": 1})
588+
empty_structured_text = content_first._parse_tool_result_from_mcp(structured_only_empty)[0].text
589+
assert empty_structured_text is not None
590+
assert json.loads(empty_structured_text) == {"x": 1}
591+
592+
empty = types.CallToolResult(content=[], structuredContent=None)
593+
assert content_only._parse_tool_result_from_mcp(empty)[0].text == "null"
564594

565595

566596
async def test_generated_mcp_tool_preserves_complete_host_payload_once() -> None:
@@ -584,7 +614,7 @@ async def test_generated_mcp_tool_preserves_complete_host_payload_once() -> None
584614
"isError": False,
585615
}
586616

587-
assert [item.additional_properties["_meta"] for item in function_result.items] == [{"widget": "image"}] * 2
617+
assert [item.additional_properties["_meta"] for item in function_result.items] == [{"widget": "image"}]
588618
assert function_result.additional_properties[_MCP_TOOL_RESULT_HOST_PAYLOAD_KEY] == expected_host_payload
589619
assert all(_MCP_TOOL_RESULT_HOST_PAYLOAD_KEY not in item.additional_properties for item in function_result.items)
590620
restored = Content.from_dict(function_result.to_dict())
@@ -1198,7 +1228,7 @@ async def test_secure_mcp_builtin_parser_restricts_all_result_shapes(result_shap
11981228
)
11991229

12001230
assert function_result.items is not None
1201-
assert len(function_result.items) == (2 if result_shape == "both" else 1)
1231+
assert len(function_result.items) == 1
12021232
for hidden_item in function_result.items:
12031233
assert hidden_item.additional_properties["_variable_reference"] is True
12041234
assert hidden_item.additional_properties["security_label"]["integrity"] == "untrusted"
@@ -8292,7 +8322,7 @@ async def test_secure_mcp_task_results_cannot_relax_local_label(result_path: str
82928322
)
82938323

82948324
assert function_result.items is not None
8295-
assert len(function_result.items) == 2
8325+
assert len(function_result.items) == 1
82968326
for item in function_result.items:
82978327
assert item.additional_properties["_variable_reference"] is True
82988328
assert item.additional_properties["security_label"]["integrity"] == "untrusted"

0 commit comments

Comments
 (0)