Skip to content

Commit be61396

Browse files
CopilotCopilot
andcommitted
Refactor MCP tool emit functions and add missing tests (#4213)
- Extract _emit_tool_result_common shared helper to eliminate duplication between _emit_tool_result and _emit_mcp_tool_result - Remove server_name prefix from tool_call_name in _emit_mcp_tool_call; display_name now equals tool_name directly - Add test for tool_name fallback to 'mcp_tool' when tool_name is None - Add test for output=None fallback to empty string in _emit_mcp_tool_result Co-authored-by: Copilot <[email protected]>
1 parent ed735b3 commit be61396

2 files changed

Lines changed: 54 additions & 66 deletions

File tree

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

Lines changed: 30 additions & 64 deletions
Original file line numberDiff line numberDiff line change
@@ -230,27 +230,28 @@ def _emit_tool_call(
230230
return events
231231

232232

233-
def _emit_tool_result(
234-
content: Content,
233+
def _emit_tool_result_common(
234+
call_id: str,
235+
raw_result: Any,
235236
flow: FlowState,
236237
predictive_handler: PredictiveStateHandler | None = None,
237238
) -> list[BaseEvent]:
238-
"""Emit ToolCallResult events for function_result content."""
239-
events: list[BaseEvent] = []
239+
"""Shared helper for emitting ToolCallEnd + ToolCallResult events and performing FlowState cleanup.
240240
241-
if not content.call_id:
242-
return events
241+
Both ``_emit_tool_result`` (standard function results) and ``_emit_mcp_tool_result``
242+
(MCP server tool results) delegate to this function.
243+
"""
244+
events: list[BaseEvent] = []
243245

244-
events.append(ToolCallEndEvent(tool_call_id=content.call_id))
245-
flow.tool_calls_ended.add(content.call_id)
246+
events.append(ToolCallEndEvent(tool_call_id=call_id))
247+
flow.tool_calls_ended.add(call_id)
246248

247-
raw_result = content.result if content.result is not None else ""
248249
result_content = raw_result if isinstance(raw_result, str) else json.dumps(make_json_safe(raw_result))
249250
message_id = generate_event_id()
250251
events.append(
251252
ToolCallResultEvent(
252253
message_id=message_id,
253-
tool_call_id=content.call_id,
254+
tool_call_id=call_id,
254255
content=result_content,
255256
role="tool",
256257
)
@@ -260,7 +261,7 @@ def _emit_tool_result(
260261
{
261262
"id": message_id,
262263
"role": "tool",
263-
"toolCallId": content.call_id,
264+
"toolCallId": call_id,
264265
"content": result_content,
265266
}
266267
)
@@ -274,14 +275,26 @@ def _emit_tool_result(
274275
flow.tool_call_name = None
275276

276277
if flow.message_id:
277-
logger.debug("Closing text message (issue #3568 fix): message_id=%s", flow.message_id)
278+
logger.debug("Closing text message: message_id=%s", flow.message_id)
278279
events.append(TextMessageEndEvent(message_id=flow.message_id))
279280
flow.message_id = None
280281
flow.accumulated_text = ""
281282

282283
return events
283284

284285

286+
def _emit_tool_result(
287+
content: Content,
288+
flow: FlowState,
289+
predictive_handler: PredictiveStateHandler | None = None,
290+
) -> list[BaseEvent]:
291+
"""Emit ToolCallResult events for function_result content."""
292+
if not content.call_id:
293+
return []
294+
raw_result = content.result if content.result is not None else ""
295+
return _emit_tool_result_common(content.call_id, raw_result, flow, predictive_handler)
296+
297+
285298
def _emit_approval_request(
286299
content: Content,
287300
flow: FlowState,
@@ -402,8 +415,7 @@ def _emit_mcp_tool_call(content: Content, flow: FlowState) -> list[BaseEvent]:
402415
tool_call_id = content.call_id or generate_event_id()
403416
tool_name = content.tool_name or "mcp_tool"
404417

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
418+
display_name = tool_name
407419

408420
events.append(
409421
ToolCallStartEvent(
@@ -438,60 +450,14 @@ def _emit_mcp_tool_result(
438450
) -> list[BaseEvent]:
439451
"""Emit ToolCallResult events for MCP server tool result content.
440452
441-
Maps MCP tool results to the same AG-UI ToolCallEnd + ToolCallResult events
442-
used by regular function results. Uses ``content.output`` (the MCP-specific
443-
result field) instead of ``content.result``.
444-
445-
Mirrors the FlowState cleanup performed by ``_emit_tool_result`` (resetting
446-
tool_call_id/tool_call_name, closing any open text message) so MCP results
447-
behave consistently with standard tool results.
453+
Delegates to the shared _emit_tool_result_common helper using content.output
454+
(the MCP-specific result field) instead of content.result.
448455
"""
449-
events: list[BaseEvent] = []
450-
451456
if not content.call_id:
452457
logger.warning("MCP tool result content missing call_id, skipping")
453-
return events
454-
455-
events.append(ToolCallEndEvent(tool_call_id=content.call_id))
456-
flow.tool_calls_ended.add(content.call_id)
457-
458+
return []
458459
raw_output = content.output if content.output is not None else ""
459-
result_content = raw_output if isinstance(raw_output, str) else json.dumps(make_json_safe(raw_output))
460-
message_id = generate_event_id()
461-
events.append(
462-
ToolCallResultEvent(
463-
message_id=message_id,
464-
tool_call_id=content.call_id,
465-
content=result_content,
466-
role="tool",
467-
)
468-
)
469-
470-
flow.tool_results.append(
471-
{
472-
"id": message_id,
473-
"role": "tool",
474-
"toolCallId": content.call_id,
475-
"content": result_content,
476-
}
477-
)
478-
479-
if predictive_handler:
480-
predictive_handler.apply_pending_updates()
481-
if flow.current_state:
482-
events.append(StateSnapshotEvent(snapshot=flow.current_state))
483-
484-
# Mirror _emit_tool_result cleanup so MCP results behave consistently
485-
flow.tool_call_id = None
486-
flow.tool_call_name = None
487-
488-
if flow.message_id:
489-
logger.debug("Closing text message for MCP tool result: message_id=%s", flow.message_id)
490-
events.append(TextMessageEndEvent(message_id=flow.message_id))
491-
flow.message_id = None
492-
flow.accumulated_text = ""
493-
494-
return events
460+
return _emit_tool_result_common(content.call_id, raw_output, flow, predictive_handler)
495461

496462

497463
def _emit_text_reasoning(content: Content) -> list[BaseEvent]:

‎python/packages/ag-ui/tests/ag_ui/test_run.py‎

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1025,7 +1025,7 @@ def test_produces_start_and_args_events(self):
10251025
assert len(events) == 2
10261026
assert events[0].type == "TOOL_CALL_START"
10271027
assert events[0].tool_call_id == "mcp_call_1"
1028-
assert events[0].tool_call_name == "brave/search"
1028+
assert events[0].tool_call_name == "search"
10291029
assert events[1].type == "TOOL_CALL_ARGS"
10301030
assert events[1].tool_call_id == "mcp_call_1"
10311031
assert "weather" in events[1].delta
@@ -1082,6 +1082,17 @@ def test_generates_id_when_missing(self):
10821082
assert len(events) >= 1
10831083
assert events[0].tool_call_id is not None
10841084
assert events[0].tool_call_id != ""
1085+
assert events[0].tool_call_name == "test_tool"
1086+
1087+
def test_missing_tool_name_falls_back_to_mcp_tool(self):
1088+
"""When tool_name is None, the fallback 'mcp_tool' is used."""
1089+
flow = FlowState()
1090+
content = Content(type="mcp_server_tool_call")
1091+
1092+
events = _emit_mcp_tool_call(content, flow)
1093+
1094+
assert len(events) >= 1
1095+
assert events[0].tool_call_name == "mcp_tool"
10851096

10861097

10871098
class TestEmitMcpToolResult:
@@ -1142,6 +1153,17 @@ def test_serializes_non_string_output(self):
11421153
assert isinstance(result_event.content, str)
11431154
assert '"key": "value"' in result_event.content
11441155

1156+
def test_output_none_falls_back_to_empty_string(self):
1157+
"""When output is None (default), the result content is an empty string."""
1158+
flow = FlowState()
1159+
content = Content(type="mcp_server_tool_result", call_id="mcp_call_none")
1160+
1161+
events = _emit_mcp_tool_result(content, flow)
1162+
1163+
assert len(events) == 2
1164+
assert events[1].type == "TOOL_CALL_RESULT"
1165+
assert events[1].content == ""
1166+
11451167
def test_resets_flow_state_like_emit_tool_result(self):
11461168
"""MCP tool result performs same FlowState cleanup as _emit_tool_result."""
11471169
flow = FlowState()
@@ -1299,7 +1321,7 @@ def test_routes_mcp_server_tool_call(self):
12991321

13001322
assert len(events) >= 1
13011323
assert events[0].type == "TOOL_CALL_START"
1302-
assert events[0].tool_call_name == "test_server/test_tool"
1324+
assert events[0].tool_call_name == "test_tool"
13031325

13041326
def test_routes_mcp_server_tool_result(self):
13051327
"""_emit_content dispatches mcp_server_tool_result to _emit_mcp_tool_result."""

0 commit comments

Comments
 (0)