loading experience

Guide

Guide to AI and agents in .NET: Extensions.AI, Semantic Kernel, Agent Framework and MCP

Guide to AI and agents in .NET: Extensions.AI, Semantic Kernel, Agent Framework and MCP

From the building blocks of Microsoft.Extensions.AI to Semantic Kernel, from the Microsoft Agent Framework to multi-agent systems, up to a Model Context Protocol server in C#: the articles on artificial intelligence in .NET, gathered in a single path.

In this guide

  1. Artificial intelligence in .NET with Microsoft.Extensions.AI
  2. Semantic Kernel: bringing AI into .NET applications with plugins
  3. Microsoft Agent Framework: agents and workflows in .NET
  4. Multi-agent systems (MAS) in .NET: when you need them and how to design them
  5. Model Context Protocol: building an MCP server in C#

Artificial intelligence in .NET with Microsoft.Extensions.AI

Integrating a language model into a .NET application used to mean tying yourself to a single provider's library. Microsoft.Extensions.AI introduces common abstractions: you write the code once and switch provider by changing configuration.

A single interface: switch provider without rewriting the application.
A single interface: switch provider without rewriting the application.

IChatClient

IChatClient client = CreateClient(); // OpenAI, Azure, a local model...

ChatResponse response = await client.GetResponseAsync(
    "Summarise in three points the benefits of .NET 10 for a company.");

Console.WriteLine(response.Text);

Each provider offers a package that implements the interface; models running locally, for example with Ollama, are used the same way. For long answers there is a streaming version, which returns the text as it is generated.

Composable middleware

As in ASP.NET Core, cross-cutting features are added as layers around the client:

IChatClient client = new ChatClientBuilder(baseClient)
    .UseFunctionInvocation()   // the model can call C# functions
    .UseOpenTelemetry()        // traces and metrics for calls
    .Build();

Calling application functions

With function invocation the model can ask to run methods exposed by the application, for example "look up order 4521", and use the result in its answer. Every exposed function must be treated like a public endpoint: argument validation, permissions and limits.

Be careful with data

  • Do not send personal or confidential data to an external service without a legal basis and a proper contract.
  • Consider local models when data must not leave the company.
  • Treat generated text as untrusted input: never execute it as code or insert it into a page without escaping.

Semantic Kernel: bringing AI into .NET applications with plugins

Semantic Kernel is Microsoft's open-source SDK for integrating language models into applications. Its central concept is the kernel: a container that brings together the AI service, the plugins with the application's functions and the configuration.

The model decides what it needs, the application's code provides the data.
The model decides what it needs, the application's code provides the data.

Creating the kernel

var builder = Kernel.CreateBuilder();
builder.AddOpenAIChatCompletion(
    modelId: "gpt-4o-mini",
    apiKey: configuration["OpenAI:ApiKey"]!);
builder.Plugins.AddFromType<WarehousePlugin>();

Kernel kernel = builder.Build();

A plugin

A plugin is a class with methods decorated with [KernelFunction]. Descriptions are essential: by reading them the model decides when to call a function.

public class WarehousePlugin(IWarehouse warehouse)
{
    [KernelFunction, Description("Returns the available quantity of an item given its code")]
    public Task<int> Stock([Description("Item code, e.g. ABC-123")] string code) =>
        warehouse.QuantityAsync(code);
}

Automatic function calling

var settings = new OpenAIPromptExecutionSettings
{
    FunctionChoiceBehavior = FunctionChoiceBehavior.Auto()
};

var answer = await kernel.InvokePromptAsync(
    "Do we have enough units of item ABC-123 for an order of 40?",
    new KernelArguments(settings));

Console.WriteLine(answer);

The model understands that it needs the stock level, calls Stock("ABC-123"), receives the number and formulates the answer. The application's code remains the one deciding and controlling the data.

Good practices

  • Expose few functions, with clear names and descriptions: too many functions confuse the model.
  • Always validate arguments and enforce the user's permissions inside the functions.
  • For operations that modify data, ask the user for confirmation before executing them.
  • Record traces and costs of calls: Semantic Kernel integrates with OpenTelemetry.

Semantic Kernel coexists with the Microsoft.Extensions.AI abstractions, and its evolution towards agents continues in the Microsoft Agent Framework.


Microsoft Agent Framework: agents and workflows in .NET

The Microsoft Agent Framework is Microsoft's open-source framework, for .NET and Python, dedicated to AI agents. It comes from the merger of two projects: Semantic Kernel, solid and designed for enterprises, and AutoGen, the research lab for multi-agent systems.

Agents build on the common Microsoft.Extensions.AI abstractions.
Agents build on the common Microsoft.Extensions.AI abstractions.

Key concepts

  • Agent: a language model with instructions, a name and tools, built on top of the IChatClient abstraction.
  • Thread: the conversation and its state, which can be stored and resumed.
  • Tools: C# functions and MCP servers the agent can use.
  • Workflows: graphs connecting agents and code steps, with sequential, concurrent, handoff and group chat patterns.

A first agent

using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;

IChatClient chatClient = CreateChatClient(); // Azure OpenAI, OpenAI, a local model...

AIAgent assistant = chatClient.CreateAIAgent(
    name: "OrderAssistant",
    instructions: "Answer questions about order status. Use only data returned by the tools.",
    tools: [AIFunctionFactory.Create(OrderStatus)]);

AgentThread thread = assistant.GetNewThread();
Console.WriteLine(await assistant.RunAsync("Where is order 4521?", thread));

[Description("Returns the status of an order given its number")]
static string OrderStatus(int number) => number == 4521 ? "shipped yesterday" : "not found";

The framework's APIs are still evolving quickly: before adopting them in production, check the documentation for the version you use.

What it adds compared to hand-written code

  • Management of conversation state and memory.
  • Workflows with checkpoints, resumption after a failure and human intervention at critical steps.
  • Integration with the Model Context Protocol to use external tools in a standard way.
  • Observability with OpenTelemetry: every step of every agent is traced.

And Semantic Kernel?

Existing projects based on Semantic Kernel keep working and are supported; the new framework is the direction for new agent-based projects, with documented migration paths.


Multi-agent systems (MAS) in .NET: when you need them and how to design them

A multi-agent system (MAS) splits a complex task across several AI agents, each with its own role, instructions and tools: one gathers information, one writes, one checks. It is the same principle as a team of people with different skills.

From simplest to most flexible: pick the minimum that solves the problem.
From simplest to most flexible: pick the minimum that solves the problem.

Orchestration patterns

  • Sequential: one agent's output becomes the next agent's input, like an assembly line.
  • Concurrent: several agents work in parallel on the same input and the results are combined.
  • Handoff: one agent routes the request to the most suitable specialised agent.
  • Group chat: agents take turns discussing, coordinated by a moderator, until they reach a solution.
  • Orchestrator and planner: a main agent breaks the task down, assigns subtasks and checks progress.

A simple sequential example

Even without dedicated frameworks, the basic pattern takes a few lines with IChatClient:

record Agent(string Name, string Instructions);

async Task<string> RunAsync(IChatClient client, Agent a, string input) =>
    (await client.GetResponseAsync(
    [
        new ChatMessage(ChatRole.System, a.Instructions),
        new ChatMessage(ChatRole.User, input)
    ])).Text;

var writer = new Agent("Writer", "Write a clear, concise draft of the requested text.");
var reviewer = new Agent("Reviewer", "Fix errors, check consistency and return only the final text.");

var draft = await RunAsync(client, writer, "Announcement of the new support service.");
var final = await RunAsync(client, reviewer, draft);

Frameworks such as the Microsoft Agent Framework offer these patterns ready-made, with state, tools and tracing.

When it really pays off

A multi-agent system adds cost, latency and points of failure. It pays off when the task has truly distinct phases, when each phase needs different tools or permissions, or when an independent check improves quality. For many requests, a single agent with good instructions and the right tools is more than enough.

Governing the risks

  • Limits: a maximum number of turns and calls, to avoid loops and runaway costs.
  • Least privilege for each agent: the one that writes must not be able to pay.
  • Human in the loop for important decisions.
  • Evaluation: a set of test cases to measure quality every time instructions or models change.

Model Context Protocol: building an MCP server in C#

The Model Context Protocol (MCP) is an open standard that lets AI assistants and agents use external tools and data in a uniform way. You write an MCP server once and every compatible client can use it: development environments, desktop assistants, agents built with .NET frameworks.

An open standard between agents and applications, with the security rules of an API.
An open standard between agents and applications, with the security rules of an API.

A minimal MCP server

The official C# SDK (the ModelContextProtocol package) integrates with the .NET generic host:

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using ModelContextProtocol.Server;
using System.ComponentModel;

var builder = Host.CreateApplicationBuilder(args);
builder.Services
    .AddMcpServer()
    .WithStdioServerTransport()
    .WithToolsFromAssembly();

await builder.Build().RunAsync();

[McpServerToolType]
public static class WarehouseTools
{
    [McpServerTool, Description("Returns the stock level of an item given its code.")]
    public static int Stock([Description("Item code")] string code) =>
        code == "ABC-123" ? 42 : 0;
}

With the stdio transport the client starts the server as a local process; for shared services you use the HTTP transport, hosted in an ASP.NET Core application.

Tools, resources and prompts

  • Tools: functions the agent can execute.
  • Resources: data the client can read, such as documents or records.
  • Prompts: predefined request templates offered to the user.

Security first

An MCP server opens your application to an agent acting on behalf of a user. The rules of any API apply: authentication for remote servers, least privilege, argument validation, rate limits and an operations log. Tools that modify data should require explicit confirmation, and text returned from external sources must be treated as untrusted, because it may contain malicious instructions aimed at the agent.


Comments (0)

No comments yet.

Leave a comment