Skip to content

Hosted agent built on MagenticBuilder is not working on foundry. Magentic only support a single task message to start the workflow #379

@karun19

Description

@karun19

I have created a multi agent workflow using MagenticBuilder and tested successfully in local machine. I deployed as hosted agent on foundry but it is giving error Magentic only support a single task message to start the workflow when playground.

Error stack from log stream:

2026-04-15T06:49:10.2770698Z stdout F INFO: 127.0.0.1:34612 - "GET /readiness HTTP/1.1" 200 OK 2026-04-15T06:49:14.3062592Z stdout F 2026-04-15 06:49:14,305 - azure.ai.agentserver - INFO - Start processing CreateResponse request. 2026-04-15T06:49:14.3255070Z stdout F 2026-04-15 06:49:14,325 - azure.ai.agentserver - INFO - Starting WorkflowAgent agent_run with stream=True 2026-04-15T06:49:14.3255421Z stdout F 2026-04-15 06:49:14,325 - azure.ai.agentserver - INFO - Loaded agent session for conversation: conv_ab1527a1457def5d00GqAWOC7uOK1umgDNDxCnhjz3TNDlSE7M 2026-04-15T06:49:14.3256184Z stdout F 2026-04-15 06:49:14,325 - azure.ai.agentserver - INFO - Checking for pending HITL requests. Session messages count: 0 2026-04-15T06:49:14.3257157Z stdout F 2026-04-15 06:49:14,325 - azure.ai.agentserver - INFO - Running agent in streaming mode 2026-04-15T06:49:14.3264956Z stdout F INFO: 10.7.126.251:0 - "POST /responses HTTP/1.1" 200 OK 2026-04-15T06:49:14.4728179Z stdout F INFO: 127.0.0.1:39332 - "GET /readiness HTTP/1.1" 200 OK 2026-04-15T06:49:14.4985205Z stdout F 2026-04-15 06:49:14,498 - azure.ai.agentserver - INFO - Retrieved 1 messages for conversation conv_ab1527a1457def5d00GqAWOC7uOK1umgDNDxCnhjz3TNDlSE7M from Foundry. 2026-04-15T06:49:14.5004663Z stdout F 2026-04-15 06:49:14,499 - azure.ai.agentserver - ERROR - Unhandled exception during streaming updates: Magentic only support a single task message to start the workflow. 2026-04-15T06:49:14.5004935Z stdout F Traceback (most recent call last): 2026-04-15T06:49:14.5005113Z stdout F File "/usr/local/lib/python3.12/site-packages/azure/ai/agentserver/agentframework/_agent_framework.py", line 246, in stream_updates 2026-04-15T06:49:14.5005141Z stdout F async for event in streaming_converter.convert(stream): 2026-04-15T06:49:14.5005162Z stdout F File "/usr/local/lib/python3.12/site-packages/azure/ai/agentserver/agentframework/models/agent_framework_output_streaming_converter.py", line 369, in convert 2026-04-15T06:49:14.5005183Z stdout F async for group in chunk_on_change(updates, is_changed): 2026-04-15T06:49:14.5005204Z stdout F File "/usr/local/lib/python3.12/site-packages/azure/ai/agentserver/agentframework/models/utils/async_iter.py", line 39, in chunk_on_change 2026-04-15T06:49:14.5005226Z stdout F async for group in chunk_by_key(source, lambda x: x, key_equal=key_equal): 2026-04-15T06:49:14.5005248Z stdout F File "/usr/local/lib/python3.12/site-packages/azure/ai/agentserver/agentframework/models/utils/async_iter.py", line 69, in chunk_by_key 2026-04-15T06:49:14.5005269Z stdout F pending = await it.__anext__() 2026-04-15T06:49:14.5006244Z stdout F ^^^^^^^^^^^^^^^^^^^^ 2026-04-15T06:49:14.5006475Z stdout F File "/usr/local/lib/python3.12/site-packages/agent_framework/_types.py", line 2843, in __anext__ 2026-04-15T06:49:14.5006578Z stdout F update = await self._iterator.__anext__() 2026-04-15T06:49:14.5006596Z stdout F ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 2026-04-15T06:49:14.5006613Z stdout F File "/usr/local/lib/python3.12/site-packages/agent_framework/_workflows/_agent.py", line 331, in _run_stream_impl 2026-04-15T06:49:14.5006626Z stdout F async for event in self._run_core( 2026-04-15T06:49:14.5006639Z stdout F File "/usr/local/lib/python3.12/site-packages/agent_framework/_workflows/_agent.py", line 399, in _run_core 2026-04-15T06:49:14.5006650Z stdout F async for event in self.workflow.run( 2026-04-15T06:49:14.5006689Z stdout F File "/usr/local/lib/python3.12/site-packages/agent_framework/_types.py", line 2843, in __anext__ 2026-04-15T06:49:14.5006701Z stdout F update = await self._iterator.__anext__() 2026-04-15T06:49:14.5006712Z stdout F ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 2026-04-15T06:49:14.5006723Z stdout F File "/usr/local/lib/python3.12/site-packages/agent_framework/_workflows/_workflow.py", line 567, in _run_core 2026-04-15T06:49:14.5006735Z stdout F async for event in self._run_workflow_with_tracing( 2026-04-15T06:49:14.5006747Z stdout F File "/usr/local/lib/python3.12/site-packages/agent_framework/_workflows/_workflow.py", line 363, in _run_workflow_with_tracing 2026-04-15T06:49:14.5008025Z stdout F await initial_executor_fn() 2026-04-15T06:49:14.5008219Z stdout F File "/usr/local/lib/python3.12/site-packages/agent_framework/_workflows/_workflow.py", line 446, in _execute_with_message_or_checkpoint 2026-04-15T06:49:14.5008292Z stdout F await executor.execute( 2026-04-15T06:49:14.5008316Z stdout F File "/usr/local/lib/python3.12/site-packages/agent_framework/_workflows/_executor.py", line 279, in execute 2026-04-15T06:49:14.5008337Z stdout F await handler(message, context) 2026-04-15T06:49:14.5008359Z stdout F File "/usr/local/lib/python3.12/site-packages/agent_framework/_workflows/_executor.py", line 664, in wrapper 2026-04-15T06:49:14.5008379Z stdout F return await func(self, message, ctx) 2026-04-15T06:49:14.5008401Z stdout F ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 2026-04-15T06:49:14.5008420Z stdout F File "/usr/local/lib/python3.12/site-packages/agent_framework_orchestrations/_base_group_chat_orchestrator.py", line 233, in handle_messages 2026-04-15T06:49:14.5008440Z stdout F await self._handle_messages(task, ctx) 2026-04-15T06:49:14.5008463Z stdout F File "/usr/local/lib/python3.12/site-packages/agent_framework_orchestrations/_magentic.py", line 913, in _handle_messages 2026-04-15T06:49:14.5008499Z stdout F raise ValueError("Magentic only support a single task message to start the workflow.") 2026-04-15T06:49:14.5008521Z stdout F ValueError: Magentic only support a single task message to start the workflow. 2026-04-15T06:49:14.5019679Z stdout F 2026-04-15 06:49:14,501 - azure.ai.agentserver - INFO - End of processing CreateResponse request. 2026-04-15T06:49:19.4728243Z stdout F INFO: 127.0.0.1:39340 - "GET /liveness HTTP/1.1" 200 OK 2026-04-15T06:49:19.4730059Z stdout F INFO: 127.0.0.1:39352 - "GET /readiness HTTP/1.1" 200 OK 2026-04-15T06:49:24.4731333Z stdout F INFO: 127.0.0.1:34198 - "GET /readiness HTTP/1.1" 200 OK 2026-04-15T06:49:29.4755533Z stdout F INFO: 127.0.0.1:34210 - "GET /liveness HTTP/1.1" 200 OK

Agent code:

`from future import annotations

import os
from pathlib import Path
from typing import Any

from agent_framework import (
Agent,
MCPStreamableHTTPTool,
)
from agent_framework.azure import AzureOpenAIChatClient
from agent_framework.orchestrations import MagenticBuilder
from azure.ai.agentserver.agentframework import from_agent_framework
from azure.identity import AzureCliCredential

FLOW_NAME = "IncidentMitigationFlow"
FLOW_DESCRIPTION = (
"Trigger this team for any active service disruptions, outages, performance degradations, "
"or alerts requiring immediate investigation and resolution."
)

AGENT_DEFINITIONS: list[dict[str, Any]] = [
{
"name": "IncidentSummaryAgent",
"system_message": "Primary agent for initiating flow. Summarize all ServiceNow incidents, clearly mentioning the incident numbers (e.g., INC0012345) along with common patterns in symptoms, timeframes, and services impacted.",
"description": "ABSOLUTELY ESSENTIAL FIRST STEP. Reflects and summarizes ServiceNow incidents before deeper analysis.",
"tools": ["fetch_servicenow_incident_details"],
"group": "ITSM",
},
{
"name": "LogSummaryAgent",
"system_message": "Summarize key findings from system and application logs, noting errors, warnings, and system behavior abnormalities relevant to the HRMS portal.",
"description": "MANDATORY STEP. Summarizes logs into key problem patterns.",
"tools": ["fetch_system_logs", "fetch_hrms_application_logs"],
"group": "General",
},
{
"name": "ConnectivityAssessmentAgent",
"system_message": "Use the check_port_status tool to determine whether the specified port is blocked or not based on configuration policy assignments. If the port is reported as blocked, explicitly recommend firewall and configuration policy review, including change records. If the port is not blocked, suggest investigating network routing, service health, or endpoint connectivity instead.",
"description": "MANDATORY STEP. Assesses connectivity and configuration policy impact on service availability.",
"tools": ["check_port_status"],
"group": "DEM",
},
{
"name": "ChangeImpactAgent",
"system_message": "Analyze change records and identify any potential or actual impacts on HRMS service availability. Carefully compare the planned change described in the change request, the implementation steps in the change task descriptions, and the actual actions documented in the task work notes. Highlight any inconsistencies between what was planned and what was executed, and flag such discrepancies as potential root causes of unintended service impacts.",
"description": "MANDATORY STEP. Reflects on change records to predict service impacts and highlight implementation errors.",
"tools": ["fetch_change_management_records"],
"group": "ITSM",
},
{
"name": "TimelineBuilderAgent",
"system_message": "CRITICAL: You are a mandatory gatekeeper and MUST NOT be skipped. Your sole responsibility is to construct a factual, chronological timeline of events using ONLY the following four inputs: 1) Incident details, 2) Log summaries, 3) Connectivity status, and 4) Change records.\n\nSTRICT RULES:\n- You MUST NOT perform Root Cause Analysis (RCA).\n- You MUST NOT infer, speculate, correlate, or conclude causality.\n- You MUST NOT use interpretive language such as 'likely caused by', 'suggests', 'indicates root cause', 'primary cause', or similar.\n- You MUST NOT include recommendations, insights, or analysis.\n\nOUTPUT REQUIREMENTS:\n- Present events in chronological order with timestamps where available.\n- Each event must be phrased as an observable fact.\n- Separate sections for Incident Details, Log Summaries, Connectivity Status, and Change Records.\n- If any of the four data sources are missing or incomplete, explicitly state 'DATA MISSING' for that section, but continue building the timeline with available data.\n\nGOVERNANCE:\n- Your output is the ONLY authorized input for the RootCauseInvestigatorAgent.\n- Any violation of the above rules invalidates downstream RCA processing.",
"description": "MANDATORY STEP. Produces a neutral, factual timeline of events with no analysis or conclusions. RootCauseInvestigatorAgent is forbidden from starting without this agent’s output.",
"tools": [],
"group": "General",
},
{
"name": "RootCauseInvestigatorAgent",
"system_message": "Using the timeline and reflections, identify the most probable root cause of the HRMS portal issue. Clearly justify why this cause is the most likely.",
"description": "Identifies root cause using timeline and reflection outputs.",
"tools": [],
"group": "General",
},
{
"name": "ResolutionAdvisorAgent",
"system_message": "Based on the determined root cause, recommend specific resolution actions and preventive measures to avoid recurrence. Format your resolution as a suggestion (e.g., 'Apply...'). The root cause should be explained in detail, including technical and contextual information. Use only the verified and correct incident ID (e.g., INC0012345) from the input or previous tools. Do not guess or fabricate the incident number. Update the corresponding ServiceNow incident with the detailed root cause and resolution. AFTER completing your update, explicitly state: 'ActionInitiatorAgent must now begin the remediation approval workflow.'",
"description": "Suggests resolution and preventive actions, updates ServiceNow incidents with detailed root cause and resolution. MUST signal ActionInitiatorAgent to begin remediation approval.",
"tools": ["update_servicenow_incident"],
"group": "General",
},
{
"name": "RemediationInitiatorAgent",
"system_message": "Responsible ONLY for initiating remediation approval. Send an email notification containing response from ResolutionAdvisorAgent to the Site Reliability Engineer (SRE) for approval. After sending email, STOP and explicitly state workflow is paused awaiting explicit human approval. You MUST NOT execute remediation scripts, MUST NOT update remediation ticket fields, and MUST NOT claim approval unless callback content explicitly confirms approval.",
"description": "Sends remediation approval request and strictly pauses for explicit human approval. No remediation execution is allowed in this step.",
"tools": ["send_remediation_approval_email_inc"],
"group": "General",
},
{
"name": "RemediationExecutorAgent",
"system_message": "Run ONLY after explicit human approval is received. Execute approved remediation actions, update ITSM remediation details, include the change request number, and provide concise execution summary.",
"description": "Executes remediation and updates ITSM only after approval gate is satisfied.",
"tools": ["execute_remedy_script", "update_servicenow_incident_remedy"],
"group": "General",
},
{
"name": "ReportGeneratorAgent",
"system_message": "Generate a formal RCA (Root Cause Analysis) document that includes Summary, Timeline, Root Cause, Resolution, and Preventive Measures sections.",
"description": "Generates the final RCA report.",
"tools": [],
"group": "General",
},
]

def _mcp_tool_for(agent_name: str, allowed_tools: list[str]) -> MCPStreamableHTTPTool:
mcp_url = os.getenv(
"MCP_URL",
"http://localhost:8000/mcp",
)
return MCPStreamableHTTPTool(
name=f"{agent_name}MCP",
url=mcp_url,
load_prompts=False,
allowed_tools=allowed_tools,
)

def _load_local_env_hints() -> None:
env_path = Path(file).parent / ".env"
if not env_path.exists():
return

for raw_line in env_path.read_text(encoding="utf-8").splitlines():
    line = raw_line.strip()
    if not line or line.startswith("#"):
        continue

    if line.startswith("$env:") and "=" in line:
        key_value = line[len("$env:") :]
        key, value = key_value.split("=", 1)
        key = key.strip()
        value = value.strip().strip('"').strip("'")
        if key and value and key not in os.environ:
            os.environ[key] = value
        continue

    if "=" in line and not line.startswith("export "):
        key, value = line.split("=", 1)
        key = key.strip()
        value = value.strip().strip('"').strip("'")
        if key and value and key not in os.environ:
            os.environ[key] = value

def _create_chat_client() -> AzureOpenAIChatClient:
deployment_name = os.getenv("AZURE_OPENAI_CHAT_DEPLOYMENT_NAME") or os.getenv("FOUNDRY_MODEL")
endpoint = os.getenv("AZURE_OPENAI_ENDPOINT")
return AzureOpenAIChatClient(
credential=AzureCliCredential(),
deployment_name=deployment_name,
endpoint=endpoint,
)

def _create_agents() -> tuple[dict[str, Agent], list[MCPStreamableHTTPTool]]:
client = _create_chat_client()
agents: dict[str, Agent] = {}
managed_tools: list[MCPStreamableHTTPTool] = []

for definition in AGENT_DEFINITIONS:
    tools = definition["tools"]
    agent_tools = [_mcp_tool_for(definition["name"], tools)] if tools else None
    if agent_tools:
        for tool in agent_tools:
            tool.terminate_on_close = True
            managed_tools.append(tool)

    agents[definition["name"]] = Agent(
        client=client,
        name=definition["name"],
        description=definition["description"],
        instructions=definition["system_message"],
        tools=agent_tools,
    )

return agents, managed_tools

def _create_manager() -> Agent:
manager_instructions = (
"You orchestrate incident mitigation end-to-end. "
"You MUST enforce this high-level phase order: "
"IncidentSummaryAgent -> (LogSummaryAgent, ConnectivityAssessmentAgent, ChangeImpactAgent) -> "
"TimelineBuilderAgent -> RootCauseInvestigatorAgent -> ResolutionAdvisorAgent -> "
"RemediationInitiatorAgent. "
"Use RemediationExecutorAgent ONLY after explicit human approval is present in conversation context, "
"such as a tool callback confirming approval. "
"If explicit approval is not present, you MUST STOP after RemediationInitiatorAgent and wait. "
"Always finish with ReportGeneratorAgent. "
"Never skip TimelineBuilderAgent before RCA."
)
return Agent(
client=_create_chat_client(),
name="IncidentMagenticManager",
description="Magentic manager coordinating incident mitigation phases and gating.",
instructions=manager_instructions,
)

def create_incident_mitigation_flow():
_load_local_env_hints()
agents, managed_tools = _create_agents()
participants = [
agents["IncidentSummaryAgent"],
agents["LogSummaryAgent"],
agents["ConnectivityAssessmentAgent"],
agents["ChangeImpactAgent"],
agents["TimelineBuilderAgent"],
agents["RootCauseInvestigatorAgent"],
agents["ResolutionAdvisorAgent"],
agents["RemediationInitiatorAgent"],
agents["RemediationExecutorAgent"],
agents["ReportGeneratorAgent"],
]

workflow = MagenticBuilder(
    participants=participants,
    manager_agent=_create_manager(),
    enable_plan_review=False,
    intermediate_outputs=True,
    max_round_count=30,
    max_stall_count=2,
    max_reset_count=2,
).build()
setattr(workflow, "_managed_mcp_tools", managed_tools)
return workflow

def main() -> None:
from_agent_framework(create_incident_mitigation_flow).run()

if name == "main":
main()
`

Metadata

Metadata

Assignees

No one assigned

    Labels

    needs more infoNeed user to provide more info

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions