Skip to content

Commit 12cbc42

Browse files
committed
Fix MCP tool result serialization for list[TextContent]
When MCP tools return results containing list[TextContent], they were incorrectly serialized to object repr strings like: '[<agent_framework._types.TextContent object at 0x...>]' This fix properly extracts text content from list items by: 1. Checking if items have a 'text' attribute (TextContent) 2. Using model_dump() for items that support it 3. Falling back to str() for other types 4. Joining single items as plain text, multiple items as JSON array Fixes microsoft#2509
1 parent 67de7bc commit 12cbc42

2 files changed

Lines changed: 24 additions & 0 deletions

File tree

‎python/packages/ag-ui/agent_framework_ag_ui/_events.py‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -386,6 +386,17 @@ def _handle_function_result_content(self, content: FunctionResultContent) -> lis
386386
result_message_id = generate_event_id()
387387
if isinstance(content.result, dict):
388388
result_content = json.dumps(content.result) # type: ignore[arg-type]
389+
elif isinstance(content.result, list):
390+
# Handle Contents list (e.g., from MCP tool results)
391+
texts = []
392+
for item in content.result:
393+
if hasattr(item, "text"): # TextContent
394+
texts.append(item.text)
395+
elif hasattr(item, "model_dump"):
396+
texts.append(json.dumps(item.model_dump(mode="json")))
397+
else:
398+
texts.append(str(item))
399+
result_content = "\n".join(texts) if len(texts) == 1 else json.dumps(texts)
389400
elif content.result is not None:
390401
result_content = str(content.result)
391402
else:

‎python/packages/ag-ui/agent_framework_ag_ui/_message_adapters.py‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -242,6 +242,19 @@ def agent_framework_messages_to_agui(messages: list[ChatMessage] | list[dict[str
242242
import json
243243

244244
content_text = json.dumps(content.result) # type: ignore
245+
elif isinstance(content.result, list):
246+
# Handle Contents list (e.g., from MCP tool results)
247+
import json
248+
249+
texts = []
250+
for item in content.result:
251+
if hasattr(item, "text"): # TextContent
252+
texts.append(item.text)
253+
elif hasattr(item, "model_dump"):
254+
texts.append(json.dumps(item.model_dump(mode="json")))
255+
else:
256+
texts.append(str(item))
257+
content_text = "\n".join(texts) if len(texts) == 1 else json.dumps(texts)
245258
elif content.result is not None:
246259
content_text = str(content.result)
247260

0 commit comments

Comments
 (0)