Skip to content

Commit a86d0f5

Browse files
committed
Python: Emit AG-UI events for MCP tool calls, results, and text reasoning
Fixes microsoft#4213 — `_emit_content()` in the AG-UI layer only handled `text`, `function_call`, `function_result`, `function_approval_request`, `usage`, and `oauth_consent_request` content types. Foundry MCP content types (`mcp_server_tool_call`, `mcp_server_tool_result`) and `text_reasoning` fell through unhandled, producing no SSE events for AG-UI consumers. Added three new handler functions wired into `_emit_content()`: - `_emit_mcp_tool_call`: emits TOOL_CALL_START + TOOL_CALL_ARGS and tracks in FlowState for MESSAGES_SNAPSHOT inclusion - `_emit_mcp_tool_result`: emits TOOL_CALL_END + TOOL_CALL_RESULT with full FlowState cleanup mirroring `_emit_tool_result` - `_emit_text_reasoning`: emits the protocol-defined reasoning event sequence (ReasoningStart → MessageStart → MessageContent → MessageEnd → ReasoningEnd) with ReasoningEncryptedValueEvent for protected_data
1 parent c2fec6b commit a86d0f5

2 files changed

Lines changed: 464 additions & 0 deletions

File tree

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

Lines changed: 153 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,12 @@
1212
from ag_ui.core import (
1313
BaseEvent,
1414
CustomEvent,
15+
ReasoningEncryptedValueEvent,
16+
ReasoningEndEvent,
17+
ReasoningMessageContentEvent,
18+
ReasoningMessageEndEvent,
19+
ReasoningMessageStartEvent,
20+
ReasoningStartEvent,
1521
RunFinishedEvent,
1622
StateSnapshotEvent,
1723
TextMessageContentEvent,
@@ -381,6 +387,147 @@ def _emit_oauth_consent(content: Content) -> list[BaseEvent]:
381387
)
382388

383389

390+
def _emit_mcp_tool_call(content: Content, flow: FlowState) -> list[BaseEvent]:
391+
"""Emit ToolCall start/args events for MCP server tool call content.
392+
393+
MCP tool calls arrive as complete items (not streamed deltas), so we emit a
394+
``ToolCallStartEvent`` (and, when arguments are present, a ``ToolCallArgsEvent``)
395+
immediately. This maps MCP-specific fields (tool_name, server_name) to the
396+
same AG-UI ToolCall* events used by regular function calls, making MCP tool
397+
execution visible to AG-UI consumers. Completion/end events are handled
398+
separately by ``_emit_mcp_tool_result``.
399+
"""
400+
events: list[BaseEvent] = []
401+
402+
tool_call_id = content.call_id or generate_event_id()
403+
tool_name = content.tool_name or "mcp_tool"
404+
405+
# Prefix with server name for disambiguation when available
406+
display_name = f"{content.server_name}/{tool_name}" if content.server_name else tool_name
407+
408+
events.append(
409+
ToolCallStartEvent(
410+
tool_call_id=tool_call_id,
411+
tool_call_name=display_name,
412+
parent_message_id=flow.message_id,
413+
)
414+
)
415+
416+
# Serialize arguments
417+
args_str = ""
418+
if content.arguments:
419+
args_str = (
420+
content.arguments if isinstance(content.arguments, str) else json.dumps(make_json_safe(content.arguments))
421+
)
422+
events.append(ToolCallArgsEvent(tool_call_id=tool_call_id, delta=args_str))
423+
424+
# Track in flow state for MESSAGES_SNAPSHOT
425+
tool_entry = {
426+
"id": tool_call_id,
427+
"type": "function",
428+
"function": {"name": display_name, "arguments": args_str},
429+
}
430+
flow.pending_tool_calls.append(tool_entry)
431+
flow.tool_calls_by_id[tool_call_id] = tool_entry
432+
433+
return events
434+
435+
436+
def _emit_mcp_tool_result(content: Content, flow: FlowState) -> list[BaseEvent]:
437+
"""Emit ToolCallResult events for MCP server tool result content.
438+
439+
Maps MCP tool results to the same AG-UI ToolCallEnd + ToolCallResult events
440+
used by regular function results. Uses ``content.output`` (the MCP-specific
441+
result field) instead of ``content.result``.
442+
443+
Mirrors the FlowState cleanup performed by ``_emit_tool_result`` (resetting
444+
tool_call_id/tool_call_name, closing any open text message) so MCP results
445+
behave consistently with standard tool results.
446+
"""
447+
events: list[BaseEvent] = []
448+
449+
if not content.call_id:
450+
logger.warning("MCP tool result content missing call_id, skipping")
451+
return events
452+
453+
events.append(ToolCallEndEvent(tool_call_id=content.call_id))
454+
flow.tool_calls_ended.add(content.call_id)
455+
456+
raw_output = content.output if content.output is not None else ""
457+
result_content = raw_output if isinstance(raw_output, str) else json.dumps(make_json_safe(raw_output))
458+
message_id = generate_event_id()
459+
events.append(
460+
ToolCallResultEvent(
461+
message_id=message_id,
462+
tool_call_id=content.call_id,
463+
content=result_content,
464+
role="tool",
465+
)
466+
)
467+
468+
flow.tool_results.append(
469+
{
470+
"id": message_id,
471+
"role": "tool",
472+
"toolCallId": content.call_id,
473+
"content": result_content,
474+
}
475+
)
476+
477+
# Mirror _emit_tool_result cleanup so MCP results behave consistently
478+
flow.tool_call_id = None
479+
flow.tool_call_name = None
480+
481+
if flow.message_id:
482+
logger.debug("Closing text message for MCP tool result: message_id=%s", flow.message_id)
483+
events.append(TextMessageEndEvent(message_id=flow.message_id))
484+
flow.message_id = None
485+
flow.accumulated_text = ""
486+
487+
return events
488+
489+
490+
def _emit_text_reasoning(content: Content) -> list[BaseEvent]:
491+
"""Emit AG-UI reasoning events for text_reasoning content.
492+
493+
Uses the protocol-defined reasoning event types so that AG-UI consumers
494+
such as CopilotKit can render reasoning natively.
495+
496+
Only ``content.text`` is used for the visible reasoning message. If
497+
``content.protected_data`` is present it is emitted as a
498+
``ReasoningEncryptedValueEvent`` so that consumers can persist encrypted
499+
reasoning for state continuity without conflating it with display text.
500+
"""
501+
text = content.text or ""
502+
if not text and content.protected_data is None:
503+
return []
504+
505+
message_id = content.id or generate_event_id()
506+
507+
events: list[BaseEvent] = [
508+
ReasoningStartEvent(message_id=message_id),
509+
ReasoningMessageStartEvent(message_id=message_id, role="assistant"),
510+
]
511+
512+
if text:
513+
events.append(ReasoningMessageContentEvent(message_id=message_id, delta=text))
514+
515+
events.append(ReasoningMessageEndEvent(message_id=message_id))
516+
517+
if content.protected_data is not None:
518+
events.append(
519+
ReasoningEncryptedValueEvent(
520+
subtype="message",
521+
entity_id=message_id,
522+
encrypted_value=content.protected_data,
523+
)
524+
)
525+
526+
events.append(ReasoningEndEvent(message_id=message_id))
527+
528+
return events
529+
530+
384531
def _emit_content(
385532
content: Any,
386533
flow: FlowState,
@@ -402,5 +549,11 @@ def _emit_content(
402549
return _emit_usage(content)
403550
if content_type == "oauth_consent_request":
404551
return _emit_oauth_consent(content)
552+
if content_type == "mcp_server_tool_call":
553+
return _emit_mcp_tool_call(content, flow)
554+
if content_type == "mcp_server_tool_result":
555+
return _emit_mcp_tool_result(content, flow)
556+
if content_type == "text_reasoning":
557+
return _emit_text_reasoning(content)
405558
logger.debug("Skipping unsupported content type in AG-UI emitter: %s", content_type)
406559
return []

0 commit comments

Comments
 (0)