## Executive Summary

The convergence of modern **.NET 11** and **Azure AI Foundry (`ai.azure.com`)** represents the enterprise standard for building, evaluating, deploying, and governing AI applications and autonomous agents. While foundational .NET libraries—such as **`Microsoft.Extensions.AI`**, the **Microsoft Agent Framework**, and the **Model Context Protocol (MCP) C# SDK**—provide unified developer abstractions on local machines, Azure AI Foundry delivers the production cloud infrastructure required to scale them securely.

In this capstone session of .NET Conf 2026, Bruno Capuano demonstrates how .NET developers can maximize their impact with Foundry. He showcases how to benchmark diverse foundation models (**GPT-4 Luna**, **xAI Grok**, and **Moonshot AI's Kimi 3.1**) using identical C# code authenticated through **Microsoft Entra ID Managed Identity** without a single API key. He then details the evolution of agents from portal-managed **Prompt Agents** with real-time web search and memory to code-first **Hosted Agents** authored in C#, tested locally with `azd`, packaged as containerized microservices, hardened with enterprise **Guardrails** (jailbreak and URL egress filtering), and driven by deterministic **Decision Models** with real-time **Voice Mode**.

---

## Visual Timeline & Key Moments

| Timestamp | Screenshot | Core Technical Topic |
|---|---|---|
| `00:00:15` | [01-title-dotnet-foundry-better-together.jpg](/dotnetconf2026/archive/43-dotnet-and-foundry/screenshots/01-title-dotnet-foundry-better-together.webp) | Session introduction: Bruno Capuano on the synergy between .NET 11 and Azure AI Foundry. |
| `00:01:15` | [02-foundational-ai-stack-dotnet.jpg](/dotnetconf2026/archive/43-dotnet-and-foundry/screenshots/02-foundational-ai-stack-dotnet.webp) | The Foundational AI Stack: `Microsoft.Extensions.AI`, Agent Framework, MCP C# SDK, and Foundry. |
| `00:02:15` | [03-foundry-model-catalog-providers.jpg](/dotnetconf2026/archive/43-dotnet-and-foundry/screenshots/03-foundry-model-catalog-providers.webp) | Model Catalog: Exploring frontier model deployments across OpenAI, Anthropic, Mistral, xAI, and Moonshot. |
| `00:03:30` | [04-code-reusable-chatclient-managed-identity.jpg](/dotnetconf2026/archive/43-dotnet-and-foundry/screenshots/04-code-reusable-chatclient-managed-identity.webp) | C# Code: Multi-model evaluation using `IChatClient` and passwordless Entra Managed Identity. |
| `00:04:45` | [05-multi-model-benchmark-gpt-grok-kimi.jpg](/dotnetconf2026/archive/43-dotnet-and-foundry/screenshots/05-multi-model-benchmark-gpt-grok-kimi.webp) | Benchmark results: Comparing GPT-4 Luna (12s, 128 tok) vs. Grok (fast/concise) vs. Kimi 3.1 (500 tok). |
| `00:06:40` | [06-agent-harness-architecture.jpg](/dotnetconf2026/archive/43-dotnet-and-foundry/screenshots/06-agent-harness-architecture.webp) | Anatomy of an Agent: Harness framework, models, system instructions, tools, memory, and safety filters. |
| `00:08:15` | [07-demo-agent-without-tools-weather-fail.jpg](/dotnetconf2026/archive/43-dotnet-and-foundry/screenshots/07-demo-agent-without-tools-weather-fail.webp) | Prompt Agent v2: Base LLM without tools fails live weather query ("I can't get live data"). |
| `00:09:40` | [08-demo-agent-with-web-search-weather-success.jpg](/dotnetconf2026/archive/43-dotnet-and-foundry/screenshots/08-demo-agent-with-web-search-weather-success.webp) | Prompt Agent v3: Web Search tool attached; successfully retrieves real-time Toronto weather with trace logging. |
| `00:10:45` | [09-demo-agent-with-memory-identity.jpg](/dotnetconf2026/archive/43-dotnet-and-foundry/screenshots/09-demo-agent-with-memory-identity.webp) | Prompt Agent v4: Memory connected; agent accurately recalls user profile ("Your name is Bruno"). |
| `00:12:30` | [10-csharp-hosted-agent-azure-yaml-spec.jpg](/dotnetconf2026/archive/43-dotnet-and-foundry/screenshots/10-csharp-hosted-agent-azure-yaml-spec.webp) | Hosted Agent Architecture: Defining containerized C# microservices via `azure.yaml`. |
| `00:14:15` | [11-local-test-harness-azd-run.jpg](/dotnetconf2026/archive/43-dotnet-and-foundry/screenshots/11-local-test-harness-azd-run.webp) | Local Inner Loop: `azd ai agent run` hosting C# agent on port 8088 and chat UI on port 8087. |
| `00:16:15` | [12-foundry-hosted-agent-container-cicd.jpg](/dotnetconf2026/archive/43-dotnet-and-foundry/screenshots/12-foundry-hosted-agent-container-cicd.webp) | Production Hosting: Container registry integration, immutable code assets, and CI/CD pipelines. |
| `00:18:20` | [13-custom-csharp-rss-blog-tools.jpg](/dotnetconf2026/archive/43-dotnet-and-foundry/screenshots/13-custom-csharp-rss-blog-tools.webp) | Custom C# Tools: Deploying an agent with custom RSS blog ingestion tools indexing .NET feeds. |
| `00:20:15` | [14-enterprise-guardrails-url-filtering-jailbreak.jpg](/dotnetconf2026/archive/43-dotnet-and-foundry/screenshots/14-enterprise-guardrails-url-filtering-jailbreak.webp) | Enterprise Guardrails: Enforcing URL network egress filtering (whitelisting microsoft.com) & jailbreak filters. |
| `00:22:20` | [15-code-decision-model-custom-aiagent.jpg](/dotnetconf2026/archive/43-dotnet-and-foundry/screenshots/15-code-decision-model-custom-aiagent.webp) | Non-Generative Decision Agents: Overriding `RunCoreAsync` with `Microsoft.Decision-1` model. |
| `00:24:45` | [16-demo-real-time-voice-mode-decision-agent.jpg](/dotnetconf2026/archive/43-dotnet-and-foundry/screenshots/16-demo-real-time-voice-mode-decision-agent.webp) | Live Voice Mode: Spoken conversation driving the C# decision agent in Foundry with zero code changes. |

---

## 1. The .NET AI Foundational Stack

Capuano outlines the architectural layers unifying .NET 11 and Azure AI Foundry:

```mermaid
flowchart TD
    subgraph Layer1["1. Foundational C# Libraries"]
        MEAI["Microsoft.Extensions.AI<br/>(IChatClient, Embeddings, Caching, OTel)"]
        MAF["Microsoft Agent Framework<br/>(AIAgent, AIProjectClient, Orchestration)"]
        MCP["Model Context Protocol C# SDK<br/>(Tooling & Resource Contracts)"]
    end

    subgraph Layer2["2. Developer Inner Loop"]
        LOCAL["localhost:8088 (ASP.NET Core Agent Host)"]
        AZD["azd ai agent run (localhost:8087 Test Inspector)"]
        LOCAL <==> AZD
    end

    subgraph Layer3["3. Azure AI Foundry Cloud Fabric"]
        CATALOG["Multi-Model Catalog (OpenAI, xAI Grok, Moonshot Kimi)"]
        HOSTED["Hosted Agents (Containerized C# Microservices)"]
        PROMPT["Prompt Agents (Portal-managed Metadata)"]
        GUARD["Enterprise Guardrails (Jailbreak & URL Egress Filters)"]
        DECISION["Microsoft Decision Models (Deterministic Classification)"]
        VOICE["Real-Time Voice Mode & Multi-Channel Deployment"]
    end

    Layer1 ==> Layer2 ==> Layer3
```

---

## 2. Multi-Model Benchmarking in Pure C# (Passwordless Entra ID)

Using `Microsoft.Extensions.AI`, developers can evaluate multiple foundation models using **100% identical C# code** without storing sensitive API keys:

```csharp
// Program.cs
using Azure.Identity;
using Azure.AI.Projects;
using Microsoft.Extensions.AI;

// Connect to Azure AI Foundry project using Microsoft Entra ID Managed Identity:
var projectClient = new AIProjectClient(
    new Uri("https://my-foundry-resource.services.ai.azure.com/api/projects/prod"),
    new AzureCliCredential());

// Query three different deployed models using the exact same IChatClient interface:
string[] models = { "gpt-4-luna", "grok-1-47", "moonshot-kimi-k3.1" };
string prompt = "In two sentences, explain how .NET and Microsoft Foundry work together.";

foreach (var modelName in models)
{
    var chatClient = projectClient.AsChatClient(modelName);
    var stopwatch = Stopwatch.StartNew();
    
    var response = await chatClient.GetResponseAsync(prompt);
    stopwatch.Stop();

    Console.WriteLine($"[Model: {modelName}]");
    Console.WriteLine($"Response: {response.Message.Text}");
    Console.WriteLine($"Elapsed: {stopwatch.ElapsedMilliseconds} ms | Total Tokens: {response.Usage.TotalTokenCount}\n");
}
```

### Real-World Benchmark Results

| Model Deployed | Elapsed Time | Token Consumption | Architectural Sweet Spot |
|---|---|---|---|
| **GPT-4 Luna** | ~12 seconds | **128 tokens** | Cost-effective, lightweight general reasoning and everyday chat. |
| **xAI Grok (Grok-1 47)** | **~6 seconds** | **94 tokens** | High-speed concise generation, code critique, and fast evaluation. |
| **Moonshot Kimi 3.1** | ~8 seconds | **500 tokens** | Deep multi-step reasoning, hierarchical planning, and document synthesis. |

---

## 3. The Evolutionary Anatomy of Agents

An AI agent combines a model with an execution **harness**, system instructions, dynamic tools, memory, and guardrails:

```
┌─────────────────────────────────────────────────────────────┐
│                    THE EVOLUTION OF AN AGENT                │
│                                                             │
│   v1: Raw Foundation Model (No Tools, No Memory)           │
│       Prompt: "How is the weather in Toronto?"              │
│       Response: ❌ "I cannot get live weather data."        │
│                                                             │
│   v2: Model + Web Search Tool                               │
│       Prompt: "How is the weather in Toronto?"              │
│       Response: ✅ "It is mostly cloudy, 5°–10°C in Toronto."│
│                                                             │
│   v3: Model + Web Search + Enterprise Memory               │
│       Prompt: "What is my name?"                            │
│       Response: ✅ "Your name is Bruno Capuano."            │
└─────────────────────────────────────────────────────────────┘
```

### Semantic Versioning & A/B Testing in Foundry
Every iteration of an agent in Foundry mints a discrete version (e.g. `v1`, `v2`, `v3`). Developers can designate an active production version while simultaneously routing test traffic to experimental versions for comparative evaluation.

---

## 4. C# Hosted Agents: Bringing Code-First Power to the Cloud

While Prompt Agents suffice for simple text retrieval, enterprise applications require complex business logic, custom C# tools, and private database connections. **Hosted Agents** allow developers to package their C# code directly into Foundry:

### 1. The ASP.NET Core Agent Host
```csharp
// HostedAgent / Program.cs
var builder = WebApplication.CreateBuilder(args);

// Register custom C# tools (e.g. RSS Feed Ingestion):
builder.Services.AddSingleton<BlogSearchTools>();

// Register the Foundry Response Protocol builder:
builder.Services.AddFoundryResponses(options =>
{
    options.Agent = new MyCustomAIAgent();
    options.EnableStreaming = true;
});

var app = builder.Build();
app.MapFoundryProtocol();
app.Run("http://localhost:8088");
```

### 2. Declarative Container Specification (`azure.yaml`)
```yaml
# azure.yaml
name: dotnet-foundry-hosted-agent
services:
  agent:
    project: ./src/HostedAgent.csproj
    host: containerapp
    language: dotnet
    env:
      - name: AZURE_AI_PROJECT_ENDPOINT
        value: "https://my-foundry.services.ai.azure.com/api/projects/prod"
      - name: FOUNDRY_RESPONSE_PROTOCOL
        value: "enabled"
```

### 3. Local Inner Loop with `azd`
Executing `azd ai agent run` spins up the local C# agent on port `8088` and launches an interactive chat harness on port `8087`. Developers can test tool calls, inspect token usage, and examine logs in real time before triggering a cloud build.

---

## 5. Enterprise Guardrails: Egress & Security Filtering

When exposing autonomous agents to end users, security boundaries must be enforced outside the model's stochastic reasoning. Foundry provides declarative **Guardrails**:

```mermaid
flowchart LR
    UserInput["User Request"] --> JailbreakFilter{"Jailbreak Defense"}
    JailbreakFilter -- "Prompt Injection Detected" --> Blocked["HTTP 403 / Violation Blocked"]
    JailbreakFilter -- "Clean Input" --> Agent["C# Hosted Agent (Blog Tools)"]
    
    Agent --> EgressFilter{"URL Egress Policy"}
    EgressFilter -- "microsoft.com (.NET Blog)" --> Allowed["HTTP 200: Allowed Fetch"]
    EgressFilter -- "Personal Blog / Untrusted URLs" --> Denied["Policy Violation: Egress Denied"]
    
    Allowed --> FinalResponse["Structured Response"]
```

### Live Guardrail Demonstration
In the session demo, Capuano configures a network rule:
- **Whitelisted Domain:** `microsoft.com` (allowing retrieval of official .NET blog posts).
- **Blocked Domains:** Personal external websites.

When prompted: *"Show me the latest posts from Bruno Capuano on the .NET blog and on his personal blog"*, the agent successfully retrieves .NET blog updates, but its attempt to access the personal blog is intercepted and blocked by the Foundry policy engine. The trace graph documents the exact syscall denial.

---

## 6. Non-Generative Decision Models & Real-Time Voice Mode

### Why Decision Models?
Generative LLMs are inefficient for deterministic routing and classification. They burn tokens, introduce latency, and can hallucinate invalid categories. **Microsoft Decision Models** (`Microsoft.Decision-1`) solve this by accepting input text and candidate choices, outputting **pure probability distributions**:

```csharp
// Implementing a custom AIAgent with Decision Models:
public class SupportRoutingAgent : AIAgent
{
    private readonly DecisionClient _client;

    public SupportRoutingAgent(DecisionClient client) => _client = client;

    protected override async Task<AgentResponse> RunCoreAsync(
        AgentContext context, CancellationToken ct)
    {
        var choices = new[]
        {
            new DecisionChoice("Billing", "Inquiries regarding invoices, double charges, refunds."),
            new DecisionChoice("TechnicalSupport", "Issues regarding service crashes or code bugs."),
            new DecisionChoice("AccountAccess", "Password resets or MFA issues."),
            new DecisionChoice("ManualReview", "Uncertain or high-risk inquiries.")
        };

        var result = await _client.EvaluateAsync(context.UserPrompt, choices, ct);
        return new AgentResponse { Output = result.TopChoice.Name, Confidence = result.TopChoice.Probability };
    }
}
```

### Single-Click Voice Mode
With a single checkbox toggle in the Foundry portal, Capuano enables **Voice Mode** on the hosted C# Decision Agent. Speaking aloud (*"I was charged twice for my subscription, what can I do?"*), the agent routes the ticket to **Billing (Confidence: 0.997)** and speaks the routing action aloud in real time.

---

## Technical Recommendations for .NET Engineering Teams

1. **Adopt `Microsoft.Extensions.AI` as Standard:** Decouple your application code from specific model vendors by programming against `IChatClient`. Swap between OpenAI, Grok, and Kimi with zero code rewrites.
2. **Never Store API Keys in Code or Config:** Authenticate all Foundry connections using Microsoft Entra ID Managed Identity (`DefaultAzureCredential`).
3. **Use Hosted Agents for Custom C# Logic:** When agents require domain logic, EF Core queries, or proprietary calculations, package them as Hosted Agents via `azure.yaml` rather than relying on portal prompt agents.
4. **Enforce Network Egress Guardrails:** Lock down outbound network traffic from agent tools to verified domains using Foundry Guardrail policies.
5. **Replace Generative Triage with Decision Models:** Utilize `Microsoft.Decision-1` for classification, intent routing, and triage to reduce token expenditure and eliminate hallucinations.
