Skip to main content
net10.0

Provides durable agent hosting and orchestration support for Microsoft Agent Framework workloads.

Published
Nov 9, 2026
7d ago
Total Downloads
53.6K
53,611

Install

dotnet add package Microsoft.Agents.AI.Hosting.AzureFunctions --version 1.16.0
ProductVersions
.NET
net10.0

README

Microsoft.Agents.AI.Hosting.AzureFunctions

This package adds Azure Functions integration and serverless hosting for Microsoft Agent Framework on Azure Functions. It builds upon the Microsoft.Agents.AI.DurableTask package to provide the following capabilities:

  • Stateful, durable execution of agents in distributed, serverless environments
  • Automatic conversation history management in supported Durable Functions backends
  • Long-running agent workflows as "durable orchestrator" functions
  • Tools and dashboards for managing and monitoring agents and agent workflows

Install the package

From the command-line:

dotnet add package Microsoft.Agents.AI.Hosting.AzureFunctions

Or directly in your project file:

<ItemGroup>
  <PackageReference Include="Microsoft.Agents.AI.Hosting.AzureFunctions" Version="[CURRENTVERSION]" />
</ItemGroup>

Usage Examples

For a comprehensive tour of all the functionality, concepts, and APIs, check out the Azure Functions samples in the Microsoft Agent Framework Durable extension repository.

Hosting single agents

This package provides a ConfigureDurableAgents extension method on the FunctionsApplicationBuilder class to configure the application to host Microsoft Agent Framework agents. These hosted agents are automatically registered as durable entities with the Durable Task runtime and can be invoked via HTTP or Durable Task orchestrator functions.

// Create agents using the standard Microsoft Agent Framework.
// Invocable via HTTP via http://localhost:7071/api/agents/SpamDetectionAgent/run
AIAgent spamDetector = new AzureOpenAIClient(new Uri(endpoint), new AzureCliCredential())
    .GetChatClient(deploymentName)
    .AsAIAgent(
        instructions: "You are a spam detection assistant that identifies spam emails.",
        name: "SpamDetectionAgent");

AIAgent emailAssistant = new AzureOpenAIClient(new Uri(endpoint), new AzureCliCredential())
    .GetChatClient(deploymentName)
    .AsAIAgent(
        instructions: "You are an email assistant that helps users draft responses to emails with professionalism.",
        name: "EmailAssistantAgent");

// Configure the Functions application to host the agents.
using IHost app = FunctionsApplication
    .CreateBuilder(args)
    .ConfigureFunctionsWebApplication()
    .ConfigureDurableAgents(options =>
    {
        options.AddAIAgent(spamDetector);
        options.AddAIAgent(emailAssistant);
    })
    .Build();
app.Run();

By default, each agent can be invoked via a built-in HTTP trigger function at the route http[s]://[host]/api/agents/{agentName}/run.

Host-side work-item filtering and rolling upgrades

New sessions target dafx-v2-{agent} entity triggers by default, while DurableAgentsOptions.ProcessLegacyEntities (or DURABLE_AGENTS_PROCESS_LEGACY_ENTITIES=true) additionally registers dafx-{agent} triggers in Phase 2 after v1 workers are stopped. On Azure Functions, distinct entity trigger names only isolate dispatch across side-by-side hosts when host-side work-item filtering is enabled. Reference Microsoft.Azure.Functions.Worker 2.52.0+, Microsoft.Azure.Functions.Worker.Extensions.DurableTask 1.19.0+, and Microsoft.Azure.Functions.Worker.Extensions.DurableTask.AzureManaged 1.10.0+ (which brings Microsoft.Azure.WebJobs.Extensions.DurableTask.AzureManaged 1.8.0+), and set "workItemFilteringEnabled": true in host.json:

{
  "version": "2.0",
  "extensions": {
    "durableTask": {
      "hubName": "default",
      "storageProvider": {
        "type": "AzureManaged",
        "connectionStringName": "DURABLE_TASK_SCHEDULER_CONNECTION_STRING",
        "workItemFilteringEnabled": true
      }
    }
  }
}

When host-side work-item filtering is not enabled on the participating Functions hosts, use an offline rollout instead of running v1 and v2 Functions hosts concurrently against the same Task Hub.

Agent completion outcomes

HTTP fire-and-forget calls return 202 Accepted; this acknowledges dispatch, not successful execution. Calls that wait return 200 only for an available successful result. With Accept: application/json, successful responses use string status: "success" and numeric status_code: 200; accepted responses use status: "accepted" and status_code: 202. Clients upgrading from the earlier .NET preview must move numeric comparisons from status to status_code. the native response shape remains compatible, and the additive result contains canonical retained terminal-response JSON. Use result for optional value (absent and explicit null remain distinct), opaque content, and unknown metadata that the native response cannot represent. Legacy plain-text negotiation remains supported.

A supported committed terminal failure returns 500 with string status: "failed", numeric status_code: 500, outcome: "failed", and the retained error code/details. A completion whose result is unavailable returns 410 Gone with status: "completedResultUnavailable", status_code: 410, and the retained outcome ("succeeded" or "failed"). The canonical x-ms-durable-outcome header carries the same outcome for JSON and plain-text callers. The legacy completion_outcome body property and x-ms-agent-completion-outcome header are emitted as compatibility aliases for existing .NET clients. It must not be treated as pending, retried with a new identity automatically, or replaced by a transcript-derived result. Ordinary transient failures and cancellation are not durable terminal outcomes.

MCP agent calls continue waiting while pending and return text by default for compatibility. The optional responseFormat argument is a .NET-only opt-in and is not advertised by the Python MCP surface; cross-runtime clients should omit it. In .NET, set it to "json" to receive the full successful response envelope (status, status_code, session_id, response, and canonical result); "text" explicitly selects legacy text. Unsupported format values are rejected before dispatch. Committed failures and unavailable results throw DurableAgentTerminalException and DurableAgentResultUnavailableException respectively, for the MCP host to report as tool failures. They are never returned as successful text or JSON responses. Cancellation is propagated to the durable client.

These endpoints use the same mailbox-aware client as AgentRunHandle and durable proxies. New sessions route to dafx-v2-{agent} entities and write schema 2.0.0 state by default, while explicit legacy session IDs (@dafx-{agent}@{key}) route to dafx-{agent} and are upgraded in-place to schema 2.0.0 when DurableAgentsOptions.ProcessLegacyEntities is enabled in Phase 2. Response-format choices ("text" or "json") do not change the entity-state version.

Orchestrating hosted agents

This package also provides a set of extension methods such as GetAgent on the TaskOrchestrationContext class for interacting with hosted agents within orchestrations.

[Function(nameof(SpamDetectionOrchestration))]
public static async Task<string> SpamDetectionOrchestration(
    [OrchestrationTrigger] TaskOrchestrationContext context)
{
    Email email = context.GetInput<Email>() ?? throw new InvalidOperationException("Email is required");

    // Get the spam detection agent
    DurableAIAgent spamDetectionAgent = context.GetAgent("SpamDetectionAgent");
    AgentSession spamSession = await spamDetectionAgent.CreateSessionAsync();

    // Step 1: Check if the email is spam
    AgentResponse<DetectionResult> spamDetectionResponse = await spamDetectionAgent.RunAsync<DetectionResult>(
        message:
            $"""
            Analyze this email for spam content and return a JSON response with 'is_spam' (boolean) and 'reason' (string) fields:
            Email ID: {email.EmailId}
            Content: {email.EmailContent}
            """,
        session: spamSession);
    DetectionResult result = spamDetectionResponse.Result;

    // Step 2: Conditional logic based on spam detection result
    if (result.IsSpam)
    {
        // Handle spam email
        return await context.CallActivityAsync<string>(nameof(HandleSpamEmail), result.Reason);
    }
    else
    {
        // Generate and send response for legitimate email
        DurableAIAgent emailAssistantAgent = context.GetAgent("EmailAssistantAgent");
        AgentSession emailSession = await emailAssistantAgent.CreateSessionAsync();

        AgentResponse<EmailResponse> emailAssistantResponse = await emailAssistantAgent.RunAsync<EmailResponse>(
            message:
                $"""
                Draft a professional response to this email. Return a JSON response with a 'response' field containing the reply:
                
                Email ID: {email.EmailId}
                Content: {email.EmailContent}
                """,
            session: emailSession);

        EmailResponse emailResponse = emailAssistantResponse.Result;
        return await context.CallActivityAsync<string>(nameof(SendEmail), emailResponse.Response);
    }
}

Scheduling orchestrations from custom code tools

Agents can also schedule and interact with orchestrations from custom code tools. This is useful for long-running tool use cases where orchestrations need to be executed in the context of the agent.

The DurableAgentContext.Current AsyncLocal property provides access to the current agent context, which can be used to schedule and interact with orchestrations.

class Tools
{
    [Description("Starts a content generation workflow and returns the instance ID for tracking.")]
    public string StartContentGenerationWorkflow(
        [Description("The topic for content generation")] string topic)
    {
        // ContentGenerationWorkflow is an orchestrator function defined in the same project.
        string instanceId = DurableAgentContext.Current.ScheduleNewOrchestration(
            name: nameof(ContentGenerationWorkflow),
            input: topic);

        // Return the instance ID so that it gets added to the LLM context.
        return instanceId;
    }

    [Description("Gets the status of a content generation workflow.")]
    public async Task<OrchestrationMetadata> GetContentGenerationStatus(
        [Description("The instance ID of the workflow to check")] string instanceId,
        [Description("Whether to include detailed information")] bool includeDetails = true)
    {
        OrchestrationMetadata? status = await DurableAgentContext.Current.Client.GetOrchestrationStatusAsync(
            instanceId,
            includeDetails);
        return status ?? throw new InvalidOperationException($"Workflow instance '{instanceId}' not found.");
    }
}

These tools are registered with the agent using the tools parameter when creating the agent.

Tools tools = new();
AIAgent agent = new AzureOpenAIClient(new Uri(endpoint), new AzureCliCredential())
    .GetChatClient(deploymentName)
    .AsAIAgent(
        instructions: "You are a content generation assistant that helps users generate content.",
        name: "ContentGenerationAgent",
        tools: [
            AIFunctionFactory.Create(tools.StartContentGenerationWorkflow),
            AIFunctionFactory.Create(tools.GetContentGenerationStatus)
        ]);

using IHost app = FunctionsApplication
    .CreateBuilder(args)
    .ConfigureFunctionsWebApplication()
    .ConfigureDurableAgents(options => options.AddAIAgent(agent))
    .Build();
app.Run();

Feedback & Contributing

We welcome feedback and contributions in our GitHub repo.

Changes from Previous Version

No structural changes between v1.16.0-preview.261029.1 and v1.16.0.

Adoption Assessment

A verified publisher signal is available. Assess fit from the package's supported frameworks, license and dependency graph rather than popularity alone.

Compatibility metadata lists 1 target framework; confirm the exact target used by your application.The published metadata declares 36 direct dependency entries across framework groups. Inspect the resolved dependency graph for your target framework.

Related Guides & Workflows

Learn how to evaluate, integrate, or audit this package in your .NET project.