Skip to content
MfC#

Microsoft Agent Framework (.NET) — Feature Tour

A short tour of the .NET framework's main features beyond the single agent, with links to the pages that cover each: A2A, graph workflows, checkpointing, human-in-the-loop, orchestrations, hosting, OpenTelemetry and evaluation, plus declarative YAML agents, content-safety middleware and dependency-injection patterns with compiled examples.

First written: November 2025, for the October 2025 public preview Verified against: Microsoft.Agents.AI 1.28.0 (checked 2026-11-19). Every C# block on this page was compiled against that release, and the declarative agent was run against a local stand-in for the OpenAI API. Target audience: .NET/C# developers .NET version: 8.0+

This page started as a tour of the preview’s headline features. Most of them now have their own pages; the sections below summarise each and link to the full treatment, and keep the code only for the features that are not covered elsewhere (declarative agents, content-safety middleware and dependency-injection patterns).

The preview-era version of this page described Microsoft.Agents.AI.Graphs, .Config, .Telemetry and .Safety namespaces (AgentGraph, HITLConfig, A2AProtocolAdapter, AgentTelemetry, ContentSafetyConfig). They never shipped. The shipped equivalents are:

FeaturePackage / namespaceKey typesCovered on
A2A clientMicrosoft.Agents.AI.A2A (preview)A2ACardResolver.GetAIAgentAsync(), A2AAgentHosting: A2A
A2A serverMicrosoft.Agents.AI.Hosting.A2A.AspNetCore (preview)AddA2AServer, MapA2AJsonRpc, MapA2AHttpJsonHosting: A2A
Graph workflowsMicrosoft.Agents.AI.WorkflowsWorkflowBuilder, Executor<TIn,TOut>, InProcessExecutionWorkflows
CheckpointingMicrosoft.Agents.AI.WorkflowsCheckpointManager, CheckpointInfoWorkflows: checkpointing
Human-in-the-loopMicrosoft.Agents.AI.WorkflowsRequestPort, RequestInfoEventWorkflows: request ports
OrchestrationsMicrosoft.Agents.AI.WorkflowsAgentWorkflowBuilderOrchestrations
Declarative agentsMicrosoft.Agents.AI.Declarative (rc)ChatClientPromptAgentFactory, CreateFromYamlAsyncBelow
Declarative workflowsMicrosoft.Agents.AI.Workflows.DeclarativeDeclarativeWorkflowBuilderWorkflows: declarative
OpenTelemetryMicrosoft.Agents.AI, Microsoft.Agents.AI.Workflows.AsBuilder().UseOpenTelemetry(), WithOpenTelemetry()Observability
EvaluationMicrosoft.Agents.AILocalEvaluator, EvalChecks, EvaluateAsyncTesting and evaluation
Content safetyyour middleware over Azure.AI.ContentSafety.AsBuilder().Use(...), DelegatingAIAgentBelow
Hosting / DIMicrosoft.Agents.AI.Hosting (preview)AddAIAgent, AddWorkflowHosting, and below

The examples on this page share one helper for creating a chat client:

Models.cs
using Azure.AI.OpenAI;
using Azure.Identity;
using Microsoft.Extensions.AI;
public static class Models
{
public static IChatClient ChatClient() =>
new AzureOpenAIClient(
new Uri(Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT")!),
new DefaultAzureCredential())
.GetChatClient(Environment.GetEnvironmentVariable("AZURE_OPENAI_DEPLOYMENT") ?? "gpt-6-luna")
.AsIChatClient();
}
  1. Agent2Agent (A2A) Protocol - .NET
  2. Graph-Based Workflows - .NET
  3. Declarative Agents with .NET
  4. OpenTelemetry Integration - .NET
  5. Content Safety - .NET
  6. Dependency Injection Patterns
  7. Best Practices

A2A lets agents on different frameworks call each other over HTTP. In the framework a remote A2A agent is just another AIAgent (await new A2ACardResolver(url, http).GetAIAgentAsync(http)), so it can sit in a workflow, be wrapped with middleware, or become a tool with AsAIFunction(). Any AIAgent can be published with AddA2AServer and MapA2AJsonRpc / MapA2AHttpJson; publish its agent card as well with MapWellKnownAgentCard, because the server does not do it for you and clients discover agents from the card. A complete server and client, both run, are on the hosting page. Earlier versions of this page showed a server without a card, which a card-resolving client cannot find.

For a typed contract over A2A, which carries messages rather than typed calls, serialise the request into the message and ask the remote side for JSON; against a local agent, RunAsync<T> gives you the same safety directly.


Workflows are typed graphs of executors joined by edges, run in supersteps. The workflows page covers them in full, with run examples for each feature:

A RequestPort is a node whose input leaves the workflow as a RequestInfoEvent; the caller answers with request.CreateResponse(value) and the run continues from the port. With a durable checkpoint store the answer can arrive days later in another process, and agent tool approvals inside workflows surface the same way. See human input with request ports, and HostedWorkflowState for doing it over HTTP. For tool-level approval inside a single agent, wrap the tool in ApprovalRequiredAIFunction; see the comprehensive guide.

The prebuilt multi-agent patterns (sequential, concurrent, group chat, handoff, Magentic) are on the orchestrations page. Two behaviours that catch people coming from Python: there is no superstep limit, so every cycle needs its own exit, and agent nodes only start when the run receives a TurnToken.


Microsoft.Agents.AI.Declarative (release candidate) builds agents from a YAML definition, so instructions, model options and output schema can live in configuration rather than code.

Terminal window
dotnet add package Microsoft.Agents.AI.Declarative --prerelease
agents/customer-service.yaml
kind: Prompt
name: CustomerServiceAgent
description: Handles customer enquiries
instructions: |
You are a helpful customer service agent.
Always be polite and professional.
model:
options:
temperature: 0.7
topP: 0.95
outputSchema:
properties:
category:
type: string
required: true
description: billing, technical or general
answer:
type: string
required: true
description: The reply to the customer.
using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;
public static class DeclarativeAgents
{
public static async Task<AIAgent> LoadAsync(IChatClient chatClient, string path)
{
var factory = new ChatClientPromptAgentFactory(chatClient);
string yaml = await File.ReadAllTextAsync(path);
return await factory.CreateFromYamlAsync(yaml);
}
public static async Task RunAsync()
{
AIAgent agent = await LoadAsync(Models.ChatClient(), "agents/customer-service.yaml");
Console.WriteLine(await agent.RunAsync("My invoice is wrong."));
}
}

The model is the chat client you pass in; the YAML sets the options. With the definition above, the request carries temperature 0.7, top_p 0.95, the instructions as the system prompt and a JSON schema built from outputSchema, so the reply is a JSON object with category and answer. Workflows have a declarative form too, covered on the workflows page.

Strongly-typed configuration with the options pattern

Section titled “Strongly-typed configuration with the options pattern”

When you would rather keep agent settings in appsettings.json, bind them with the ordinary .NET options pattern and build the agent from them. Nothing here is framework-specific, which is the point.

{
"Agents": {
"Support": {
"Name": "support",
"Instructions": "You are a helpful customer service agent.",
"Temperature": 0.7,
"MaxOutputTokens": 800
}
}
}
using Microsoft.Agents.AI;
using Microsoft.Agents.AI.Hosting;
using Microsoft.Extensions.AI;
using Microsoft.Extensions.Options;
public sealed class AgentSettings
{
public required string Name { get; init; }
public required string Instructions { get; init; }
public float Temperature { get; init; } = 0.7f;
public int MaxOutputTokens { get; init; } = 1000;
}
public static class ConfiguredAgentRegistration
{
public static void AddConfiguredSupportAgent(this IHostApplicationBuilder builder)
{
builder.Services.AddOptions<AgentSettings>()
.Bind(builder.Configuration.GetSection("Agents:Support"))
.ValidateDataAnnotations()
.ValidateOnStart();
builder.AddAIAgent("support", (sp, name) =>
{
AgentSettings settings = sp.GetRequiredService<IOptions<AgentSettings>>().Value;
return new ChatClientAgent(sp.GetRequiredService<IChatClient>(), new ChatClientAgentOptions
{
Name = name,
ChatOptions = new ChatOptions
{
Instructions = settings.Instructions,
Temperature = settings.Temperature,
MaxOutputTokens = settings.MaxOutputTokens,
},
});
});
}
}

Wrap an agent with .AsBuilder().UseOpenTelemetry(sourceName) and subscribe to that source with AddSource and AddMeter; workflows have WorkflowBuilder.WithOpenTelemetry(), whose spans go to Microsoft.Agents.AI.Workflows unless you pass your own ActivitySource. The spans follow the GenAI conventions (invoke_agent, chat, execute_tool) and carry token usage, and the meters record gen_ai.client.operation.duration and gen_ai.client.token.usage. Prompt text is excluded unless you set EnableSensitiveData. The observability page lists every span and attribute and has set-ups for OTLP, the Aspire dashboard and Azure Monitor, and your own business metrics.


There is no Microsoft.Agents.AI.Safety namespace and no contentSafety: option on ChatClientAgent. Content safety is middleware you write over Azure.AI.ContentSafety, attached with agent.AsBuilder().Use(...) or written as a DelegatingAIAgent. The full input-and-output screening example is on the enterprise page, and middleware in general on the middleware page.

Terminal window
dotnet add package Azure.AI.ContentSafety
dotnet add package Azure.AI.TextAnalytics # for PII redaction

The middleware can also be written as a class deriving from DelegatingAIAgent, which is easier to test and to register in DI.

using Azure.AI.ContentSafety;
using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;
using ChatMessage = Microsoft.Extensions.AI.ChatMessage;
public sealed class ContentSafetyAgent(AIAgent inner, ContentSafetyClient safety, int maxSeverity = 2)
: DelegatingAIAgent(inner)
{
protected override async Task<AgentResponse> RunCoreAsync(
IEnumerable<ChatMessage> messages, AgentSession? session, AgentRunOptions? options, CancellationToken cancellationToken)
{
var text = string.Join("\n", messages.Where(m => m.Role == ChatRole.User).Select(m => m.Text));
var analysis = await safety.AnalyzeTextAsync(new AnalyzeTextOptions(text), cancellationToken);
if (analysis.Value.CategoriesAnalysis.Any(c => c.Severity > maxSeverity))
{
return new AgentResponse(new ChatMessage(ChatRole.Assistant, "I can't help with that request."));
}
return await base.RunCoreAsync(messages, session, options, cancellationToken);
}
}
// AIAgent safe = new ContentSafetyAgent(agent, new ContentSafetyClient(endpoint, credential));

Override RunCoreStreamingAsync as well if callers stream; otherwise streaming calls bypass the check.

Azure AI Language (Azure.AI.TextAnalytics) redacts PII; run it on user messages before the model sees them.

using Azure.AI.TextAnalytics;
using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;
using ChatMessage = Microsoft.Extensions.AI.ChatMessage;
public static class PiiRedaction
{
public static AIAgent WithPiiRedaction(this AIAgent agent, TextAnalyticsClient language) =>
agent.AsBuilder()
.Use(
runFunc: async (messages, session, options, inner, ct) =>
{
var redacted = new List<ChatMessage>();
foreach (ChatMessage message in messages)
{
if (message.Role == ChatRole.User && !string.IsNullOrWhiteSpace(message.Text))
{
PiiEntityCollection entities = await language.RecognizePiiEntitiesAsync(message.Text, cancellationToken: ct);
redacted.Add(new ChatMessage(ChatRole.User, entities.RedactedText));
}
else
{
redacted.Add(message);
}
}
return await inner.RunAsync(redacted, session, options, ct);
},
runStreamingFunc: null)
.Build();
}

Microsoft.Agents.AI.Hosting registers agents (and workflows) as keyed AIAgent services. A workflow registered with AddWorkflow(...).AddAsAIAgent() is callable exactly like an agent, and both can then be mapped to OpenAI-compatible, A2A or AG-UI endpoints (see the hosting page).

Program.cs
using Microsoft.Agents.AI;
using Microsoft.Agents.AI.Hosting;
using Microsoft.Agents.AI.Workflows;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.AI;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddChatClient(Models.ChatClient());
builder.AddAIAgent("researcher", "You research topics thoroughly.");
builder.AddAIAgent("writer", "You turn research into a short, clear brief.");
builder.AddWorkflow("research-brief", (sp, name) =>
AgentWorkflowBuilder.BuildSequential(
name,
[sp.GetRequiredKeyedService<AIAgent>("researcher"), sp.GetRequiredKeyedService<AIAgent>("writer")]))
.AddAsAIAgent();
builder.AddOpenAIResponses();
var app = builder.Build();
app.MapPost("/brief", async (BriefRequest request, [FromKeyedServices("research-brief")] AIAgent workflow) =>
Results.Ok(new { brief = (await workflow.RunAsync(request.Topic)).Text }));
app.MapOpenAIResponses(); // POST /v1/responses with "agent": {"name": "researcher" | "writer" | "research-brief"}
app.Run();
public record BriefRequest(string Topic);

The shared Responses route selects the agent with agent.name in the request body (or metadata.entity_id); the model field does not select anything. Earlier versions of this page said otherwise.

  • Register the IChatClient as a singleton; it owns the HTTP connection pool.
  • Agents are safe to share as singletons (the default for AddAIAgent); keep per-user state in sessions.
  • Use ServiceLifetime.Scoped on AddAIAgent only when the agent depends on scoped services (for example a per-request DbContext used by its tools).
  • Build workflows per run (a factory, or AddWorkflow’s delegate) in services that run several at once: one Workflow instance can only be in one run at a time.

  • Use async/await throughout; never block on .Result or .Wait().
  • Flow CancellationTokens from the request into RunAsync and into workflow runs.
  • One IChatClient per model deployment, registered once.
  • Resolve agents as AIAgent (keyed by name) so implementations can change without touching callers.
  • Bind configuration with IOptions<T> and validate it on start-up.
  • Use records for workflow messages and structured output.
  • Prefer RunAsync<T> over parsing JSON out of response.Text.
  • Catch ClientResultException (OpenAI SDK) or RequestFailedException (Azure SDK) around model calls; add retries with Microsoft.Extensions.Http.Resilience on the HttpClient (production guide).
  • Workflow executors do not throw out of the run: watch for WorkflowErrorEvent and ExecutorFailedEvent.
  • Stream (RunStreamingAsync) for user-facing latency.
  • Use AgentWorkflowBuilder.BuildConcurrent or fan-out edges for independent work.
  • Keep histories bounded with compaction or a chat reducer.