Middleware Overview
Middleware is how you add cross-cutting behavior to an agent run without putting that behavior inside every tool, prompt, or model call. Use it for logging, policy checks, request shaping, retries, timeouts, event requests, safety gates, thread/session state updates, and result formatting.
For built-in logging, telemetry, and usage-aware middleware decisions, see Logging And Telemetry.
The main DX question is not only "how do I write middleware?" It is "where should this middleware attach?"
Choose Where It Attaches
| Use this when | Attach middleware here |
|---|---|
| Every agent the runtime runs should get the behavior | AgentRuntimeBuilder.WithMiddleware(...) |
Only one call to RunAsync should get the behavior | AgentRunConfig.RuntimeMiddleware |
| One agent should get the behavior, from code, JSON, or a stored definition | middlewares in that agent's AgentConfig, or AgentConfig.WithMiddleware<T>(config) |
| Every selected ToolHarness input should get the behavior, even before expansion | [ToolHarnessMiddleware] |
| The behavior only matters while a collapsed ToolHarness is expanded | [Collapse(Middlewares = ...)] |
| The behavior is a built-in product feature | A helper: AgentRuntimeBuilder.WithPermissions(...) for the shared permission gate, or AgentConfig policy helpers such as WithCircuitBreaker(...) and the error-handling helpers for one agent |
Start with the smallest attachment point that matches the behavior. If the middleware is just temporary telemetry for one request, do not make it part of the agent definition. If it protects one agent, declare it on that agent's definition. If it protects every agent of the application, register it on the runtime builder. If it protects one tool harness, scope it to that harness.
Memory and context enrichment usually starts as ordinary middleware. Retrieve context before the model turn, add it to the thread history for that turn, then store any small memory pointers or policy state through middleware state after the turn. Keep raw documents, embeddings, and large memory payloads in an application store or content store.
Shared Runtime Middleware
Shared middleware is registered on AgentRuntimeBuilder. One instance runs for every agent the runtime runs: the default agent, other code agents, stored agents, and subagents. Each agent's pipeline is assembled when the runtime builds that agent, the first time it runs.
var assistant = new AgentConfig()
.WithOpenAI(model: "gpt-5-mini")
.WithInstructions("You are concise.");
await using var runtime = await new AgentRuntimeBuilder()
.WithMiddleware(new RequestLoggingMiddleware())
.WithMiddleware(new RateLimitMiddleware(limitPerMinute: 60))
.AddAgent("assistant", assistant)
.BuildAsync();You can also register a middleware type with a parameterless constructor:
await using var runtime = await new AgentRuntimeBuilder()
.WithMiddleware<RequestLoggingMiddleware>()
.AddAgent("assistant", assistant)
.BuildAsync();Shared middleware is reusable and testable because dependencies can be passed in directly or resolved through the runtime's service provider. A middleware that takes IConfig<T> cannot be shared this way; WithMiddleware(instance) throws and points to AgentConfig.WithMiddleware<T>(config), because the framework constructs configurable middleware for each agent from its definition.
A middleware an agent's definition declares supersedes the shared instance of the same type for that agent. For what the runtime shares and what each definition carries, see The Runtime And Its Agents.
Adjust The Shared Pipeline
Change the order of the shared list with the runtime builder methods:
runtimeBuilder
.ReplaceMiddleware<RateLimitMiddleware>(
new RateLimitMiddleware(limitPerMinute: 120))
.InsertMiddlewareBefore<ContentLifecycleMiddleware>(
new RequestAuditMiddleware())
.MoveMiddlewareToStart<RequestLoggingMiddleware>()
.RemoveMiddleware<LegacyTelemetryMiddleware>();| Method | Behavior |
|---|---|
WithMiddleware(...) | Appends one middleware; null is rejected immediately. |
ReplaceMiddleware<T>(...) | Replaces the first matching middleware in place, removes additional matches, and appends when no match exists. |
InsertMiddlewareBefore<TAnchor>(...) | Inserts before the first anchor, or appends when the anchor has not been registered yet. |
MoveMiddlewareToStart<T>() | Moves the first matching middleware to the outermost position. |
RemoveMiddleware<T>() | Removes every matching middleware. |
The replacement type must be assignable to T. Configure the shared list before BuildAsync(); an AgentRuntimeBuilder builds one runtime, and the runtime keeps the list it was built with.
Runtime Middleware
Use runtime middleware when a single run needs extra behavior that should not become part of the agent definition. RuntimeMiddleware is C# only and is ignored by JSON serialization.
var result = await runtime.RunAsync(
"Summarize this trace.",
runConfig: new AgentRunConfig
{
RuntimeMiddleware =
[
new TraceOnlyThisRunMiddleware(traceId)
]
});Runtime middleware is applied outside the configured middleware for that run. That means its Before* hooks run before the agent's configured middleware, and its After* hooks run after the configured middleware.
Agent Config
Use config registration when middleware belongs to one agent's definition, whether the definition is written in code, read from a file, or kept in the agent store. Every agent built from the definition constructs its own instance. Custom middleware must be available to the app and declared with [Middleware("stableName")], so the runtime's composition contains it.
[Middleware("RateLimit")]
public sealed class RateLimitMiddleware : IAgentMiddleware
{
public RateLimitMiddleware() { }
public RateLimitMiddleware(RateLimitConfig config)
{
// Store options from the JSON "config" object.
}
}The declared identity is the exact, case-sensitive name used in configuration.
In code, AgentConfig.WithMiddleware<T>(config) declares a middleware that takes IConfig<T>. It appends the middleware's identity and its configuration, encoded through its generated contract, to the definition:
[Middleware("requestBudget")]
public sealed class RequestBudgetMiddleware(IConfig<RequestBudgetConfig> config) : IAgentMiddleware
{
}
public sealed record RequestBudgetConfig
{
public int MaxRequestsPerTurn { get; init; } = 10;
}
var assistant = new AgentConfig()
.WithOpenAI(model: "gpt-5-mini")
.WithMiddleware<RequestBudgetMiddleware>(new RequestBudgetConfig { MaxRequestsPerTurn = 5 });Simple config:
{
"middlewares": [
"RequestLoggingMiddleware",
"RateLimit"
]
}Config with middleware-specific options:
{
"middlewares": [
"RequestLoggingMiddleware",
{
"name": "RateLimit",
"config": {
"requestsPerMinute": 60
}
}
]
}Middleware listed in config is resolved in the order it appears in the middlewares array.
Every configured middleware reference is required. A name that is not a middleware of the runtime's composition is refused with agent_middleware_unknown, naming the path (middlewares[0].name) and the closest valid name: at BuildAsync() for a code agent, and when a stored definition is created or updated. runtime.Composition.Middleware lists the middleware a definition can declare.
Building the agent, the first time it runs, fails with a structured AgentRunConfigurationException when:
- a constructor dependency cannot be resolved;
- the middleware constructor throws; or
- the supplied middleware-config payload cannot be materialized.
Multiple failures are reported together under middleware_configuration_invalid. There is no implicit skip-and-continue path for configured middleware.
Scoped Function Middleware
Use scoped registration when one shared middleware instance should run only for a function, ToolHarness, or active skill:
await using var runtime = await new AgentRuntimeBuilder()
.WithMiddleware(new ToolLimitMiddleware().ForFunction("WriteFile"))
.WithMiddleware(new FileAuditMiddleware().ForToolHarness("FileSystemTools"))
.WithMiddleware(new AnalysisPolicyMiddleware().ForSkill("analyze_codebase"))
.AddAgent("assistant", assistant)
.BuildAsync();A harness scope names the harness class; it matches the harness of that name among the harnesses the running agent selects.
Scopes filter BeforeFunctionAsync, WrapFunctionCallAsync, and AfterFunctionAsync. They do not filter model or turn hooks, which remain global. Skill scope follows the active typed capability relationship between the skill and the functions it reveals.
The scope is checked against the current FunctionRequest, so replacing the function in an outer wrapper cannot bypass an inner scope.
Tool-Harness Scoped Middleware
ToolHarness middleware runs in an execution-local pipeline owned by one selected harness. It is narrower than global agent middleware and can use the harness's DI, configuration, and Agent resources.
Choose its activation policy deliberately:
| Policy | Declaration | Activation |
|---|---|---|
| Expansion-gated | [Collapse(Middlewares = ...)] | When the container expands |
| Eager | [ToolHarnessMiddleware] | At accepted-input admission, regardless of visibility |
Eager middleware is appropriate for authorization, audit, policy, context setup, and telemetry that must run before tools become visible.
Declare expansion-gated middleware:
[Collapse(Middlewares = [typeof(DatabaseAuditMiddleware)])]
public sealed class DatabaseToolHarness
{
// Tool functions live here.
}Declare eager middleware:
[ToolHarnessMiddleware(typeof(DatabaseAuthorizationMiddleware))]
public sealed class DatabaseToolHarness
{
// Tool functions live here.
}Eager middleware can preserve normal collapsing by using a description-only [Collapse]:
[Collapse("Database operations")]
[ToolHarnessMiddleware(typeof(DatabaseAuthorizationMiddleware))]
public sealed class DatabaseToolHarness;Both policies may coexist with different middleware types. Eager middleware is active from accepted-input admission; expansion-gated middleware is appended when the harness expands. A single middleware type cannot use both policies. See ToolHarness Middleware for hooks and lifecycle.
Use an exact-type activation override when declared middleware needs services:
var assistant = new AgentConfig()
.WithOpenAI(model: "gpt-5-mini")
.WithToolHarness<DatabaseToolHarness>(opts =>
opts.OverrideMiddleware<DatabaseAuditMiddleware>(context =>
ToolHarnessMiddlewareActivation.ExecutionOwned(
new DatabaseAuditMiddleware(
context.GetRequiredService<IAuditLog>()))));The override replaces the middleware at its declared position. It cannot add an undeclared type. The override is a process-local part of the harness reference: agents the runtime builds from this definition use it, and the definition cannot be stored.
Configurable middleware takes IConfig<T> and declares its identity once. Declaring it on a harness adds its configuration to the harness configuration; the harness config record does not repeat it:
[Middleware("databaseRateLimit")]
public sealed class DatabaseRateLimitMiddleware(
IConfig<DatabaseRateLimitConfig> config)
: IToolHarnessMiddleware
{
}
[ToolHarnessMiddleware(typeof(DatabaseRateLimitMiddleware))]
public partial class DatabaseToolHarness;Consumers configure it with the same name and config entry used globally:
{
"toolHarnesses": [
{
"name": "MyApp:MyApp.Tools:DatabaseToolHarness",
"config": {
"middlewares": [
{
"name": "databaseRateLimit",
"config": { "requestsPerMinute": 20 }
}
]
}
}
]
}The harness entry names the harness by its exact activation identity (Assembly:Namespace:Name). A harness entry only configures middleware the harness declares. See Harness Configuration for run overrides and resets.
Built-In Helpers
Some middleware is easier to add through feature helpers than by constructing the middleware yourself. Prefer the helper when it exists because it usually wires the matching options and state correctly.
var assistant = new AgentConfig()
.WithOpenAI(model: "gpt-5-mini")
.WithCircuitBreaker(maxConsecutiveCalls: 3);
await using var runtime = await new AgentRuntimeBuilder()
.WithPermissions()
.AddAgent("assistant", assistant)
.BuildAsync();WithPermissions() adds the one shared permission gate every agent passes through. Policy helpers on AgentConfig, such as WithCircuitBreaker(...), WithRetry(...), and WithPIIProtection(...), write the agent's definition only; the runtime derives the matching middleware from each agent's own definition when it builds that agent, so a policy set on one agent never runs for another.
Use the focused guide for the feature you are enabling:
PermissionMiddleware is the framework call gate. It evaluates the registered function or action through a trusted IPermissionPolicy, validates the exact choice set, journals the request and resolution, and issues an invocation-bound grant. Applications customize the decision by selecting a policy descriptor; they do not replace the request/response protocol. Resource-level checks such as path, network, or workspace capability use the same shared permission lifecycle with a different permission domain.
Events From Middleware
Middleware can emit events when the app needs to observe or respond to what is happening inside the agent loop.
For one-way observability, publish an event from a hook context:
public async Task BeforeFunctionAsync(
BeforeFunctionContext context,
CancellationToken cancellationToken)
{
await context.PublishAsync(
new FunctionAuditEvent(context.Function?.Name),
cancellationToken);
}Durable events commit through the canonical journal before subscribers receive them. Live-only events remain process-local with ThreadSequenceNumber == 0, even when the context has session and thread scope.
For a request/response interaction, emit a bidirectional event and wait for a response. Permissions use this pattern: middleware asks the host whether a sensitive action is allowed, and the host responds through the agent event coordinator.
var response = await context.RequestAsync<PermissionRequestEvent, PermissionResponseEvent>(
request,
timeout: TimeSpan.FromSeconds(30));In direct in-process code, answer by running a RespondInputEvent that carries the matching response event. In ASP.NET Core hosted clients, read the request from canonical SSE or restore it from /state, then send the matching IResponseEvent envelope through the active coordinator's /responses route. Preserve descendant child scope fields when the parent state surfaced a subagent request.
Use this pattern when the user, UI, policy engine, bot adapter, or hosted runtime needs to make a decision during the run.
Runtime Context Surfaces
HPD exposes several context surfaces. Choose the narrowest one that matches the job:
| Surface | Use It For |
|---|---|
AgentRunConfig | Per-run provider/model selection, harness setting overrides, runtime middleware, tool context instances, attachments, compaction controls, and temporary behavior. |
| Middleware hook context | Turn, iteration, tool, function, thread, event, service, session, and thread data that belongs to the agent scheduler. |
[MiddlewareState] | Private middleware-owned state that should persist by session or thread. |
FunctionExecutionContext | Narrow tool/function access to event emission, bidirectional requests, services, content store, runtime-owned operations, struct events, and run metadata. |
| Application storage | Business records, secrets, large documents, embeddings, durable memory bodies, audit archives, and tenant policy. |
Do not mutate scheduler-owned session or thread state from tool bodies. Tool functions receive FunctionExecutionContext so they can interact with the runtime without taking over middleware state management.
Order And Lifecycle
Registration order matters. For Before* hooks, middleware runs in registration order. For After* hooks and error notification, middleware runs in reverse order. Wrapper hooks form nested calls around the model or function body.
For the full hook-by-hook model, read Middleware Lifecycle. For writing your own middleware, read Custom Middleware.