diff --git a/python/packages/core/agent_framework/_compaction.py b/python/packages/core/agent_framework/_compaction.py index 70e6e82ea81..16a5dcfcf1e 100644 --- a/python/packages/core/agent_framework/_compaction.py +++ b/python/packages/core/agent_framework/_compaction.py @@ -1016,6 +1016,11 @@ def annotate_message_groups( _OPAQUE_REASONING_KEYS: Final[frozenset[str]] = frozenset({"encrypted_content"}) +# Host-only content that is retained for the framework but never replayed to +# the model. Keep this key in sync with _mcp._MCP_TOOL_RESULT_HOST_PAYLOAD_KEY; +# importing _mcp here would pull the full MCP stack into compaction. +_HOST_ONLY_ADDITIONAL_PROPERTY_KEYS: Final[frozenset[str]] = frozenset({"_mcp_tool_result_host_payload"}) + def _strip_opaque_reasoning_payload(value: Any) -> Any: """Recursively drop opaque reasoning members, keeping clear-text payloads.""" @@ -1073,7 +1078,12 @@ def _serialize_content(content: Content) -> dict[str, Any]: additional_properties = payload.get("additional_properties") if isinstance(additional_properties, dict) and additional_properties: filtered_properties = _strip_opaque_reasoning_payload(additional_properties) - payload["additional_properties"] = filtered_properties or {} + if isinstance(filtered_properties, dict): + for key in _HOST_ONLY_ADDITIONAL_PROPERTY_KEYS: + filtered_properties.pop(key, None) + payload["additional_properties"] = filtered_properties or {} + else: + payload["additional_properties"] = {} return payload diff --git a/python/packages/core/tests/core/test_compaction.py b/python/packages/core/tests/core/test_compaction.py index 665a473991b..45760576095 100644 --- a/python/packages/core/tests/core/test_compaction.py +++ b/python/packages/core/tests/core/test_compaction.py @@ -625,6 +625,26 @@ def test_annotate_message_groups_token_counts_ignore_encrypted_content_in_additi assert _token_count(with_message) == _token_count(without_message) +def test_annotate_message_groups_token_counts_ignore_mcp_host_payload() -> None: + from agent_framework._mcp import _MCP_TOOL_RESULT_HOST_PAYLOAD_KEY + + host_payload = "X" * 4096 + with_payload = Content.from_function_result( + "call_1", + result="tool result", + additional_properties={_MCP_TOOL_RESULT_HOST_PAYLOAD_KEY: host_payload}, + ) + without_payload = Content.from_function_result("call_1", result="tool result") + + with_message = Message(role="assistant", contents=[with_payload]) + without_message = Message(role="assistant", contents=[without_payload]) + + annotate_message_groups([with_message], tokenizer=CharacterEstimatorTokenizer()) + annotate_message_groups([without_message], tokenizer=CharacterEstimatorTokenizer()) + + assert _token_count(with_message) == _token_count(without_message) + + def test_annotate_message_groups_token_counts_keep_clear_text_reasoning_details() -> None: import json