Files
Daniel Roth 9917bddc2b .NET: Update AG-UI samples for latest MAF + AG-UI SDK and align with docs (#7295)
* Simplify AG-UI Step04 human-in-the-loop sample to idiomatic pattern

The Step04 sample previously wrapped both the server and client agents in
custom ServerFunctionApproval*Agent middleware (~470 lines across two files)
to marshal a bespoke approval protocol over AG-UI. This is no longer needed:
MapAGUIServer natively emits the tool-approval interrupt when the model calls
an ApprovalRequiredAIFunction, and AGUIChatClient natively transports the
client's ToolApprovalResponseContent decision back to resume the run.

Changes:
- Server: map the ChatClientAgent directly with MapAGUIServer; remove the
  ServerFunctionApprovalAgent wrapper, the JsonOptions plumbing, and the
  ApprovalJsonContext registration.
- Client: use the AGUIChatClient-backed agent directly; the existing loop
  already handles ToolApprovalRequestContent -> CreateResponse idiomatically.
- Delete ServerFunctionApprovalServerAgent.cs and
  ServerFunctionApprovalClientAgent.cs.

Verified end-to-end (approval request -> approve -> tool executes -> final
response) against GitHub Models. Both projects build with 0 warnings.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot-Session: eeb2168d-2ecc-4f8d-9830-c287072eb7e1

* Update AG-UI Step04 README to describe native approval flow

The Step04 human-in-the-loop sample no longer uses the custom ServerFunctionApprovalServerAgent / ServerFunctionApprovalClientAgent wrappers. Update the README so it describes the idiomatic native flow: the server maps a plain agent with MapAGUIServer and relies on ApprovalRequiredAIFunction to raise the approval interrupt, and the client handles ToolApprovalRequestContent and replies with ToolApprovalResponseContent.

* Fix AG-UI Step04 README server port to match client default

The Step04 client defaults to http://localhost:5100 (and the server launchSettings also uses 5100), but the README told users to run the server on port 8888, so the client could not reach it. Align the Step04 server run command to 5100. Other steps intentionally keep 8888 because their clients default to that port.

* Update AG-UI .NET samples for latest MAF + AG-UI SDK and align with docs

- Bump AGUI.* packages 0.0.3 to 0.0.4 (Directory.Packages.props)
- Step01/02/03: drop AddHttpClient().AddLogging() server noise and simplify the
  client run-started output to match the getting-started doc (no thread plumbing)
- Step04 (HITL): remove HTTP body logging and MEAI001 pragmas, give the approval
  tool an explicit name, and align the resume decision message with the doc
- Step05 (state): replace the custom SharedStateAgent/StatefulAgent DataContent
  pattern (dropped by released AGUI.Server) with declarative
  AGUIStreamOptions.MapResultAsStateSnapshot plus a thin RecipeStateAgent that
  reads RunAgentInput.State, and align the Recipe models with the docs
- Refresh README to the shipped API (MapAGUIServer, ApprovalRequiredAIFunction,
  declarative state)

Verified: all 10 sample projects build; Step04 approval/resume and Step05 state
snapshot round-trip run end-to-end against GitHub Models.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot-Session: eeb2168d-2ecc-4f8d-9830-c287072eb7e1

* Name the Step02 backend tool search_restaurants to match the docs

Give the SearchRestaurants tool an explicit "search_restaurants" name so the
client displays an accurate tool name (not a compiler-mangled local-function
name) and stays aligned with the backend-tool-rendering doc.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot-Session: eeb2168d-2ecc-4f8d-9830-c287072eb7e1

* Add UTF-8 BOM to Step05 sample files to satisfy check-format

The check-format CI job enforces the repository's utf-8-bom charset rule via
dotnet format. The Step05 files added in this PR were saved without a BOM.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot-Session: eeb2168d-2ecc-4f8d-9830-c287072eb7e1

* Fix AG-UI sample conversation history

Let AgentSession own prior messages so clients send only each new turn, and give the frontend location tool a stable protocol name.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

---------

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Roger Barreto <19890735+RogerBarreto@users.noreply.github.com>
Copilot-Session: eeb2168d-2ecc-4f8d-9830-c287072eb7e1
2026-08-19 09:41:31 +00:00
..

AG-UI Getting Started Samples

This directory contains samples that demonstrate how to build AG-UI (Agent UI Protocol) servers and clients using the Microsoft Agent Framework.

Prerequisites

  • .NET 9.0 or later
  • Azure OpenAI service endpoint and deployment configured
  • Azure CLI installed and authenticated (az login)
  • User has the Cognitive Services OpenAI Contributor role for the Azure OpenAI resource

Environment Variables

All samples require the following environment variables:

export AZURE_OPENAI_ENDPOINT="https://your-resource.openai.azure.com/"
export AZURE_OPENAI_DEPLOYMENT_NAME="gpt-5.4-mini"

For the client samples, you can optionally set:

export AGUI_SERVER_URL="http://localhost:8888"

Samples

Step01_GettingStarted

A basic AG-UI server and client that demonstrate the foundational concepts.

Server (Step01_GettingStarted/Server)

A basic AG-UI server that hosts an AI agent accessible via HTTP. Demonstrates:

  • Creating an ASP.NET Core web application
  • Setting up an AG-UI server endpoint with MapAGUIServer
  • Creating an AI agent from an Azure OpenAI chat client
  • Streaming responses via Server-Sent Events (SSE)

Run the server:

cd Step01_GettingStarted/Server
dotnet run --urls http://localhost:8888

Client (Step01_GettingStarted/Client)

An interactive console client that connects to an AG-UI server. Demonstrates:

  • Creating an AG-UI client with AGUIChatClient
  • Managing multi-turn conversations with an AgentSession
  • Streaming responses with RunStreamingAsync
  • Displaying colored console output for different content types
  • Supporting both interactive and automated modes

Prerequisites: The Step01_GettingStarted server (or any AG-UI server) must be running.

Run the client:

cd Step01_GettingStarted/Client
dotnet run

Type messages and press Enter to interact with the agent. Type :q or quit to exit.

Step02_BackendTools

An AG-UI server with function tools that execute on the backend.

Server (Step02_BackendTools/Server)

Demonstrates:

  • Creating function tools using AIFunctionFactory.Create
  • Using [Description] attributes for tool documentation
  • Defining explicit request/response types for type safety
  • Setting up JSON serialization contexts for source generation
  • Backend tool rendering (tools execute on the server)

Run the server:

cd Step02_BackendTools/Server
dotnet run --urls http://localhost:8888

Client (Step02_BackendTools/Client)

A client that works with the backend tools server. Try asking: "Find Italian restaurants in Seattle" or "Search for Mexican food in Portland".

Run the client:

cd Step02_BackendTools/Client
dotnet run

Step03_FrontendTools

Demonstrates frontend tool rendering (tools defined on client, executed on server).

Server (Step03_FrontendTools/Server)

A basic AG-UI server that accepts tool definitions from the client.

Run the server:

cd Step03_FrontendTools/Server
dotnet run --urls http://localhost:8888

Client (Step03_FrontendTools/Client)

A client that defines and sends tools to the server for execution.

Run the client:

cd Step03_FrontendTools/Client
dotnet run

Step04_HumanInLoop

Demonstrates human-in-the-loop approval workflows for sensitive operations. This sample includes both a server and client component.

Server (Step04_HumanInLoop/Server)

An AG-UI server that implements approval workflows. Demonstrates:

  • Wrapping a tool with ApprovalRequiredAIFunction so it requires approval before running
  • Mapping a plain agent with MapAGUIServer, which natively emits an approval interrupt when the model calls the approval-required tool and resumes the run once the client sends the decision back

Run the server:

cd Step04_HumanInLoop/Server
dotnet run --urls http://localhost:5100

Client (Step04_HumanInLoop/Client)

An interactive client that handles approval requests from the server. Demonstrates:

  • Detecting ToolApprovalRequestContent in the streamed response
  • Displaying approval details to the user and prompting for approval or rejection
  • Sending the decision back as a ToolApprovalResponseContent created with approvalRequest.CreateResponse(approved)
  • Resuming the run so the server continues after the decision is received

Run the client:

cd Step04_HumanInLoop/Client
dotnet run

Try asking the agent to perform sensitive operations like "Approve expense report EXP-12345".

Step05_StateManagement

An AG-UI server and client that demonstrate shared state management.

Server (Step05_StateManagement/Server)

Demonstrates:

  • Exposing a generate_recipe tool that returns the complete recipe
  • Mapping the tool result to a STATE_SNAPSHOT event with AGUIStreamOptions.MapResultAsStateSnapshot
  • Reading the client's current recipe from RunAgentInput.State
  • Managing shared state between client and server
  • Using JSON serialization contexts for state types

Run the server:

cd Step05_StateManagement/Server
dotnet run

The server runs on port 8888 by default.

Client (Step05_StateManagement/Client)

A client that displays and updates shared state from the server. Try asking: "Create a recipe for chocolate chip cookies" or "Suggest a pasta dish".

Run the client:

cd Step05_StateManagement/Client
dotnet run

How AG-UI Works

Server-Side

  1. Client sends HTTP POST request with messages
  2. ASP.NET Core endpoint receives the request via MapAGUIServer
  3. Agent processes messages using Agent Framework
  4. Responses are streamed back as Server-Sent Events (SSE)

Client-Side

  1. AGUIChatClient sends HTTP POST request to server
  2. Server responds with SSE stream
  3. Client parses events into AgentResponseUpdate objects
  4. Updates are displayed based on content type
  5. The client sends the full message history each turn (the stateless AG-UI client does not rely on a server-assigned ConversationId)

Protocol Features

  • HTTP POST for requests
  • Server-Sent Events (SSE) for streaming responses
  • JSON for event serialization
  • Thread IDs (read from the RUN_STARTED event's raw representation) for conversation context. AGUIChatClient is stateless and intentionally does not surface a ConversationId.
  • Run IDs (as ResponseId) for tracking individual executions

Security considerations

ConversationId keeps request/response continuity. It is not proof that the caller owns that conversation. In multi-user deployments, authenticate each AG-UI request and authorize conversation access using your application's real boundary, such as the authenticated user, tenant, or workspace.

If your ASP.NET Core host shares session storage across users, pair MapAGUIServer with an isolation strategy such as UseClaimsBasedAgentIsolation(...) so the storage key includes a principal-specific dimension instead of relying on the conversation identifier alone.

Troubleshooting

Connection Refused

Ensure the server is running before starting the client:

# Terminal 1
cd AGUI_Step01_ServerBasic
dotnet run --urls http://localhost:8888

# Terminal 2 (after server starts)
cd AGUI_Step02_ClientBasic
dotnet run

Port Already in Use

If port 8888 is already in use, choose a different port:

# Server
dotnet run --urls http://localhost:8889

# Client (set environment variable)
export AGUI_SERVER_URL="http://localhost:8889"
dotnet run

Authentication Errors

Make sure you're authenticated with Azure:

az login

Verify you have the Cognitive Services OpenAI Contributor role on the Azure OpenAI resource.

Missing Environment Variables

If you see "AZURE_OPENAI_ENDPOINT is not set" errors, ensure environment variables are set in your current shell session before running the samples.

Streaming Not Working

Check that the client timeout is sufficient (default is 60 seconds). For long-running operations, you may need to increase the timeout in the client code.

Next Steps

After completing these samples, explore more AG-UI capabilities:

Currently Available in C#

The samples above demonstrate the AG-UI features currently available in C#:

  • Basic Server and Client: Setting up AG-UI communication
  • Backend Tool Rendering: Function tools that execute on the server
  • Streaming Responses: Real-time Server-Sent Events
  • State Management: State schemas with predictive updates
  • Human-in-the-Loop: Approval workflows for sensitive operations

Coming Soon to C#

The following advanced AG-UI features are available in the Python implementation and are planned for future C# releases:

  • Generative UI: Custom UI component generation
  • Advanced State Patterns: Complex state synchronization scenarios

For the most up-to-date AG-UI features, see the Python samples for working examples.