Skip to main content

How to Add Middleware to an Agent in the Microsoft 365 Agents SDK in C#

· 8 min read
Jagdish Kumawat
Founder @ Dewiride

Middleware in the Microsoft 365 Agents SDK runs for every activity, before your agent sees it and after your agent has finished, and it can change what your agent sends. That makes it the place for anything that applies to every conversation, whichever route answers: here, a disclaimer under every message the agent sends.

Syntax​

C#
public class MiddlewareName : IMiddleware
{
public async Task OnTurnAsync(ITurnContext turnContext, NextDelegate next, CancellationToken cancellationToken = default)
{
// Before the agent
await next(cancellationToken);
// After the agent
}
}

builder.AddAgentMiddleware(new MiddlewareName());
  • IMiddleware is the Agents SDK's middleware interface, in the Microsoft.Agents.Builder namespace. Its one method, OnTurnAsync, gets the turn and next, the rest of the pipeline.
  • await next(cancellationToken) passes the activity on, to the next middleware or, after the last one, to your agent. Code after this line runs once the agent's whole turn has finished.
  • Returning without calling next stops the activity there: your agent never sees it.
  • builder.AddAgentMiddleware(...) in Program.cs adds a middleware object to the adapter's pipeline. Call it once for each middleware; they run in the order you add them.

The Example​

The agent for this post answers questions about a shop's refunds. Answers like these are often written automatically, so every message the agent sends should carry a short disclaimer, whatever route sent it. A middleware adds it in one place:

DisclaimerMiddleware.cs
using Microsoft.Agents.Builder;
using Microsoft.Agents.Core.Models;
using IMiddleware = Microsoft.Agents.Builder.IMiddleware;

namespace MiddlewareDemo;

// Adds a disclaimer to every message the agent sends.
public class DisclaimerMiddleware(string disclaimer) : IMiddleware
{
public async Task OnTurnAsync(ITurnContext turnContext, NextDelegate next, CancellationToken cancellationToken = default)
{
turnContext.OnSendActivities(async (context, activities, nextSend) =>
{
foreach (IActivity activity in activities)
{
if (activity.Type == ActivityTypes.Message && !string.IsNullOrEmpty(activity.Text))
{
activity.Text += $"\n\n_{disclaimer}_";
}
}

return await nextSend();
});

await next(cancellationToken);
}
}

DisclaimerMiddleware.cs in a macOS-style editor window: a class implementing IMiddleware with a disclaimer string in its primary constructor; OnTurnAsync registers turnContext.OnSendActivities to append the disclaimer in italics to the text of every outgoing message activity, then calls next

The agent itself knows nothing about the disclaimer. It has a route for refunds and a catch-all:

PolicyAgent.cs
using Microsoft.Agents.Builder;
using Microsoft.Agents.Builder.App;
using Microsoft.Agents.Builder.State;
using Microsoft.Agents.Core.Models;

namespace MiddlewareDemo;

public class PolicyAgent : AgentApplication
{
public PolicyAgent(AgentApplicationOptions options) : base(options)
{
OnMessage("refunds", RefundsAsync);
OnActivity(ActivityTypes.Message, HelpAsync, rank: RouteRank.Last);
}

private async Task RefundsAsync(ITurnContext turnContext, ITurnState turnState, CancellationToken cancellationToken)
{
await turnContext.SendActivityAsync("You can return any item within **30 days** of delivery.", cancellationToken: cancellationToken);
}

private async Task HelpAsync(ITurnContext turnContext, ITurnState turnState, CancellationToken cancellationToken)
{
await turnContext.SendActivityAsync("Ask me about **refunds**.", cancellationToken: cancellationToken);
}
}

It's an ASP.NET Core project with the Agents SDK, hosted with AddAgent<PolicyAgent>() and listening on port 3978.

Prerequisites​

  • The Microsoft 365 Agents Playground, to chat with the agent on your own machine. agentsplayground --version should print 0.2.30; if the command isn't found, install it with npm install -g @microsoft/m365agentsplayground.

Step 1: Write the Middleware Class​

Create DisclaimerMiddleware.cs, starting with its using directives and the class declaration:

DisclaimerMiddleware.cs (the start)
using Microsoft.Agents.Builder;
using Microsoft.Agents.Core.Models;
using IMiddleware = Microsoft.Agents.Builder.IMiddleware;

namespace MiddlewareDemo;

// Adds a disclaimer to every message the agent sends.
public class DisclaimerMiddleware(string disclaimer) : IMiddleware
  • The using IMiddleware = ... line picks the Agents SDK's interface. ASP.NET Core has an IMiddleware interface of its own, and every web project imports its namespace automatically, so without this line the build fails with error CS0104, an ambiguous reference.
  • string disclaimer is a parameter of the class's primary constructor, so Program.cs decides the text, and the same middleware can serve agents with different disclaimers.

Step 2: Change What the Agent Sends​

Inside OnTurnAsync, the middleware registers a handler for everything the agent sends in this turn, then passes the activity on:

DisclaimerMiddleware.cs (OnTurnAsync)
public async Task OnTurnAsync(ITurnContext turnContext, NextDelegate next, CancellationToken cancellationToken = default)
{
turnContext.OnSendActivities(async (context, activities, nextSend) =>
{
foreach (IActivity activity in activities)
{
if (activity.Type == ActivityTypes.Message && !string.IsNullOrEmpty(activity.Text))
{
activity.Text += $"\n\n_{disclaimer}_";
}
}

return await nextSend();
});

await next(cancellationToken);
}
  • turnContext.OnSendActivities(...) registers a handler that runs whenever anything in this turn sends activities, before they go out. It gets the turn, the list of activities about to be sent, and nextSend, which sends them.
  • The loop appends the disclaimer, in italics, to each message with text. Other activities, such as a typing indicator, are left alone.
  • return await nextSend() sends the changed activities and hands back the ids the channel gave them. Forget it, and nothing is sent at all.
  • await next(cancellationToken) then lets the agent handle the activity. Because the send handler was registered first, it sees every reply the agent sends.

Step 3: Register the Middleware​

In Program.cs, add the middleware to the AddAgentDefaults() chain:

Program.cs
using MiddlewareDemo;
using Microsoft.Agents.Hosting.AspNetCore;
using Microsoft.Agents.Storage;

var builder = WebApplication.CreateBuilder(args);

builder.AddAgentDefaults()
.AddAgent<PolicyAgent>()
.AddAgentMiddleware(new DisclaimerMiddleware("Answers are written automatically. Check anything important with our team."));
builder.Services.AddSingleton<IStorage, MemoryStorage>();

var app = builder.Build();

app.UseAgents();
app.MapDefaultAgentEndpoints();

app.Run();

AddAgentMiddleware takes a middleware object you create, here with the disclaimer's text, and the adapter runs it for every activity.

Step 4: Try It​

Run the agent with dotnet run, start the Agents Playground in a second terminal, and send refunds, then Can I swap a size?:

Terminal 2
agentsplayground -e http://localhost:3978/api/messages -c emulator

The Agents Playground chat: refunds gets You can return any item within 30 days of delivery., and Can I swap a size? gets Ask me about refunds.; both replies end with the line Answers are written automatically. Check anything important with our team. in italics

Both replies carry the disclaimer, although they came from two different routes and neither of them mentions it. Any route you add later gets it too.

Common Mistakes​

MistakeWhat happensDo this instead
Leaving out the using IMiddleware = ... alias in a web projecterror CS0104, an ambiguous referenceAdd the alias, as in Step 1
Forgetting await next(cancellationToken)The agent never sees any activityCall next on every path that should reach the agent
Forgetting return await nextSend() in the send handlerThe agent's replies are never sentAlways end the send handler with it
Appending to every activityTyping indicators and other activities get text they shouldn't haveChange only messages with text

Troubleshooting​

SymptomLikely causeFix
No disclaimer under the repliesThe middleware isn't registeredAdd .AddAgentMiddleware(...) to Program.cs
The agent stopped answeringnext or nextSend isn't calledCheck both calls
The disclaimer appears twiceThe middleware is registered twiceRegister it once

FAQ​

In what order do several middleware run?​

In the order you add them with AddAgentMiddleware. Each one's code before next runs in that order, and its code after next runs in reverse, as the turn unwinds.

Can middleware stop an activity?​

Yes: return without calling next, and the agent never sees the activity. A middleware that answers over-long messages itself, for example, does exactly that.

Does middleware see activities that no route handles?​

Yes. It runs for every activity the adapter receives, before the agent decides whether any route wants it.

Can my middleware use a logger or other services?​

AddAgentMiddleware takes an object you create, so give the middleware what it needs through its constructor, as this one gets its disclaimer. The SDK's own middleware does the same: TranscriptLoggerMiddleware, for example, takes the transcript store it writes to.

Is this the same as the AI label in Teams?​

No. This is plain text, so it works in every channel. Microsoft Teams also has a built-in label for AI-generated messages, which is set differently.

Conclusion​

Implement IMiddleware, do your work in OnTurnAsync around await next(cancellationToken), and register the object with AddAgentMiddleware. The middleware then runs for every activity, before and after your agent, and with turnContext.OnSendActivities it can change everything the agent sends, without touching a single route.

Additional Resources​