Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

middleware.md

1,451 lines60.3 KB

1---
2title: Middleware
3id: middleware
4order: 1
5description: "Hook into every stage of TanStack AI's chat() lifecycle with middleware — logging, analytics, stream transforms, tool interception, and side effects."
6keywords:
7 - tanstack ai
8 - middleware
9 - chat middleware
10 - lifecycle hooks
11 - observability
12 - logging
13 - tool interception
14 - stream transform
15---
16​
17Middleware lets you hook into every stage of the `chat()` lifecycle — from configuration to streaming, tool execution, usage tracking, and completion. You can observe, transform, or short-circuit behavior at each stage without modifying your adapter or tool implementations.
18​
19Common use cases include:
20​
21- **Logging and observability** — track token usage, tool execution timing, errors
22- **Configuration transforms** — inject system prompts, adjust temperature per iteration, filter tools
23- **Stream processing** — redact sensitive content, transform chunks, drop unwanted events
24- **Tool call interception** — validate arguments, cache results, abort on dangerous calls
25- **Side effects** — send analytics, update databases, trigger notifications
26​
27## Quick Start
28​
29Pass an array of middleware to the `chat()` function:
30​
31```typescript
32import { chat, type ChatMiddleware } from "@tanstack/ai";
33import { openaiText } from "@tanstack/ai-openai";
34​
35const logger: ChatMiddleware = {
36 name: "logger",
37 onStart: (ctx) => {
38 console.log(`[${ctx.requestId}] Chat started`);
39 },
40 onFinish: (ctx, info) => {
41 console.log(`[${ctx.requestId}] Finished in ${info.duration}ms`);
42 },
43};
44​
45const stream = chat({
46 adapter: openaiText("gpt-5.5"),
47 messages: [{ role: "user", content: "Hello" }],
48 middleware: [logger],
49});
50```
51​
52> **Just want to see chunks flowing through your middleware during development?**
53> Use `debug: { middleware: true }` on your `chat()` call — no custom middleware required. See [Debug Logging](./debug-logging).
54​
55## Lifecycle Overview
56​
57Every `chat()` invocation follows a predictable lifecycle. Middleware hooks fire at specific phases:
58​
59```mermaid
60graph TD
61 A["chat() called"] --> B["onConfig (phase: init)"]
62 B --> C[onStart]
63 C --> D["onConfig (phase: beforeModel)"]
64 D --> E["Adapter streams response"]
65 E --> F["onChunk (for each chunk)"]
66 F --> G{Tool calls?}
67 G -->|No| H[onUsage]
68 G -->|Yes| I[onBeforeToolCall]
69 I --> J[Tool executes]
70 J --> K[onAfterToolCall]
71 K --> L{Continue loop?}
72 L -->|Yes| D
73 L -->|No| H
74 H --> SO{"Structured output path?"}
75 SO -->|None| M{Outcome}
76 SO -->|"Native combined"| SOH["Post-loop structured-output harvest (onChunk)"]
77 SOH --> M
78 SO -->|"Separate finalization"| SOC[onStructuredOutputConfig]
79 SOC --> SOM["onConfig (phase: structuredOutput)"]
80 SOM --> SOS["Structured-output finalization (onChunk, onUsage)"]
81 SOS --> M
82 M -->|Success| N[onFinish]
83 M -->|Abort| O[onAbort]
84 M -->|Error| P[onError]
85​
86 style I fill:#e1f5ff
87 style J fill:#ffe1e1
88 style SOC fill:#e1f5ff
89 style SOM fill:#e1f5ff
90 style SOS fill:#e1f5ff
91 style SOH fill:#e1f5ff
92 style N fill:#e1ffe1
93 style O fill:#fff4e1
94 style P fill:#ffe1e1
95```
96​
97### Phase Transitions
98​
99The context's `phase` field tracks where you are in the lifecycle:
100​
101| Phase | When | Hooks Called |
102|-------|------|-------------|
103| `init` | Once at startup | `onConfig` |
104| `beforeModel` | Before each model call (per iteration) | `onConfig` |
105| `modelStream` | While adapter streams chunks | `onChunk`, `onUsage` |
106| `beforeTools` | Before tool execution | `onBeforeToolCall` |
107| `afterTools` | After tool execution | `onAfterToolCall` |
108| `structuredOutput` | During the final structured-output adapter call (when `outputSchema` is set **and** `supportsCombinedToolsAndSchema()` does not return `true` for the current model/options). Chunks from `adapter.structuredOutputStream` (or the synthesized non-streaming fallback) flow through `onChunk` with this phase, and `onUsage` fires for the final call's tokens. **Does not fire** for adapters that natively combine tools + schema in one streaming call (modern OpenAI Chat Completions, OpenAI Responses, Claude 4.5+, Gemini 3.x, Grok 4.x family, and OpenRouter when every routed model is in `OPENROUTER_COMBINED_TOOLS_AND_SCHEMA_MODELS`; see issue #605). On that path middleware observes the run through `beforeModel` / `modelStream` as usual. | `onStructuredOutputConfig`, `onConfig`, `onChunk`, `onUsage` |
109​
110## Hooks Reference
111​
112### onConfig
113​
114Called once during `init` (startup) and once per iteration during `beforeModel` (before each model call). On the separate-finalization path, `onConfig` additionally re-fires at the structured-output boundary with `ctx.phase === 'structuredOutput'`, receiving the post-`onStructuredOutputConfig` view of the config. A single-iteration separate-finalization run therefore fires `onConfig` three times (`init` + `beforeModel` + `structuredOutput`). Native-combined output does not add this third call. Use `onConfig` to transform the configuration that the model receives.
115​
116Return a **partial** config object with only the fields you want to change — they are shallow-merged with the current config automatically. No need to spread the existing config.
117​
118```typescript
119import { type ChatMiddleware } from "@tanstack/ai";
120​
121const dynamicTemperature: ChatMiddleware = {
122 name: "dynamic-temperature",
123 onConfig: (ctx, config) => {
124 if (ctx.phase === "init") {
125 // Add a system prompt at startup — only systemPrompts is overwritten
126 return {
127 systemPrompts: [
128 ...config.systemPrompts,
129 "You are a helpful assistant.",
130 ],
131 };
132 }
133​
134 if (ctx.phase === "beforeModel" && ctx.iteration > 0) {
135 // Increase temperature on retries. Sampling params live in the
136 // provider-native modelOptions object — `temperature` is universal,
137 // so it's the same key across providers. Spread the existing
138 // modelOptions so other model options stay unchanged.
139 const current =
140 typeof config.modelOptions?.temperature === "number"
141 ? config.modelOptions.temperature
142 : 0.7;
143 return {
144 modelOptions: {
145 ...config.modelOptions,
146 temperature: Math.min(current + 0.1, 1.0),
147 },
148 };
149 }
150 },
151};
152```
153​
154> Sampling parameters (`temperature`, `top_p` / `topP`, the various `max*Tokens` keys) live inside `modelOptions` under each provider's native name — they are no longer root config fields. `temperature` happens to be spelled the same across every provider, so the example above is provider-agnostic; if you mutate a token limit instead, use the provider-native key (e.g. `max_output_tokens` for OpenAI, `num_predict` nested under `modelOptions.options` for Ollama). See [Moving Sampling Options into modelOptions](../migration/sampling-options-to-model-options).
155​
156**Config fields you can transform:**
157​
158| Field | Type | Description |
159|-------|------|-------------|
160| `messages` | `ModelMessage[]` | Canonical conversation history. Persistence and `ctx.messages` use this field. |
161| `providerMessages` | `ModelMessage[]` | Temporary context sent to the provider. Defaults to `messages`. |
162| `systemPrompts` | `string[]` | System prompts |
163| `tools` | `Tool[]` | Available tools |
164| `metadata` | `Record<string, unknown>` | Request metadata |
165| `modelOptions` | `Record<string, unknown>` | Provider-native options — this is where sampling params (`temperature`, `top_p` / `topP`, the provider's `max*Tokens` key) now live, alongside every other model-specific knob. See [Moving Sampling Options into modelOptions](../migration/sampling-options-to-model-options). |
166| `toolChoice` | `ToolChoice \| undefined` | How the model uses the tools at the next model call. See [Change the tool choice of a call](#change-the-tool-choice-of-a-call). |
167| `wrapFetch` | `FetchWrapper \| undefined` | Wraps the HTTP fetch of the next model call. See [Change the HTTP requests of a call](#change-the-http-requests-of-a-call). |
168| `promptCache` | `ResolvedPromptCache \| undefined` | The prompt cache of the next model call: its `retention` and `key`. See [Change the prompt cache of a call](#change-the-prompt-cache-of-a-call). |
169​
170When multiple middleware define `onConfig`, the config is **piped** through them in order — each receives the merged config from the previous middleware.
171​
172Return `providerMessages` when a transform must affect only the model call. For
173compatibility, returning `messages` also updates provider input unless the same
174result sets `providerMessages` explicitly.
175​
176#### Change the tool choice of a call
177​
178Your agent hits its last model call, and the model calls a tool again. The run ends after the tool result, and the user gets no answer. Return `toolChoice: 'none'` on that last call, and the model answers in text:
179​
180```typescript
181import { chat, maxIterations, toolDefinition, type ChatMiddleware } from "@tanstack/ai";
182import { openaiText } from "@tanstack/ai-openai";
183import { z } from "zod";
184​
185const MAX_CALLS = 10;
186​
187const search = toolDefinition({
188 name: "search",
189 description: "Search the docs",
190 inputSchema: z.object({ query: z.string() }),
191}).server(async ({ query }) => ({ hits: [`A page about ${query}`] }));
192​
193const answerOnLastCall: ChatMiddleware = {
194 name: "answer-on-last-call",
195 onConfig: (ctx) => {
196 if (ctx.phase === "beforeModel" && ctx.iteration === MAX_CALLS - 1) {
197 return { toolChoice: "none" };
198 }
199 },
200};
201​
202const stream = chat({
203 adapter: openaiText("gpt-6.1-sol"),
204 messages: [{ role: "user", content: "How do I add a tool?" }],
205 tools: [search],
206 agentLoopStrategy: maxIterations(MAX_CALLS),
207 middleware: [answerOnLastCall],
208});
209```
210​
211- `config.toolChoice` is the `chat()` option.
212- The value you return applies to the next model call only. The call after it starts again from the `chat()` option.
213- Return it in the `beforeModel` phase. A value from the `init` phase does not reach a model call.
214- For the values, and what each provider does with them, see [Choose when the model calls a tool](../tools/tools#choose-when-the-model-calls-a-tool).
215​
216#### Change the HTTP requests of a call
217​
218Your proxy wants a header on each request. Or you want to log each model call. You do not need your own client for that. Return `wrapFetch` from `onConfig`:
219​
220```typescript
221import { type ChatMiddleware } from "@tanstack/ai";
222​
223const traceHeader: ChatMiddleware = {
224 name: "trace-header",
225 onConfig: (ctx) => {
226 if (ctx.phase !== "beforeModel") return;
227 return {
228 wrapFetch: (next) => (input, init) => {
229 const headers = new Headers(init?.headers);
230 headers.set("x-trace-id", `${ctx.requestId}-${ctx.iteration}`);
231 return next(input, { ...init, headers });
232 },
233 };
234 },
235};
236```
237​
238You want the same wrapper on every call of the run? Pass it to `chat()`:
239​
240```typescript
241import { chat } from "@tanstack/ai";
242import { openaiText } from "@tanstack/ai-openai";
243​
244const stream = chat({
245 adapter: openaiText("gpt-5.6"),
246 messages: [{ role: "user", content: "Hi" }],
247 wrapFetch: (next) => async (input, init) => {
248 const started = Date.now();
249 const response = await next(input, init);
250 console.log(`model call: ${response.status} in ${Date.now() - started} ms`);
251 return response;
252 },
253});
254```
255​
256- A wrapper gets the next `fetch` and gives back a new one. It can change the URL, the headers, the request, or the response.
257- A wrapper from `onConfig` applies to the next model call only.
258- Wrappers chain. The `chat()` wrapper runs first, then the middleware wrappers in middleware order, then the fetch of the adapter.
259- Each adapter page says if that adapter supports `wrapFetch`.
260​
261#### Change the prompt cache of a call
262​
263A slow tool, like a build or a test run, can pause your agent for more than 5 minutes. The short Claude cache is gone by then. Return `promptCache` from `onConfig` to keep the cache longer from the next call on:
264​
265```typescript
266import { type ChatMiddleware } from "@tanstack/ai";
267​
268const longCacheAfterTools: ChatMiddleware = {
269 name: "long-cache-after-tools",
270 onConfig: (ctx, config) => {
271 if (ctx.phase !== "beforeModel" || ctx.iteration === 0) return;
272 return { promptCache: { ...config.promptCache, retention: "long" } };
273 },
274};
275```
276​
277- `config.promptCache` is the current value, with its `retention` and its `key`.
278- The value you return goes to the adapter on the next model call. It stays until a middleware returns another one.
279- For the retention values and what they cost, see [Prompt Caching](./prompt-caching#turn-it-off-or-keep-it-longer).
280​
281### onStructuredOutputConfig
282​
283Called once at the start of the final structured-output adapter call — only when `chat()` was invoked with `outputSchema` **and** `supportsCombinedToolsAndSchema()` does not return `true` for the current model/options. Pipes through middleware in order, like `onConfig`, but with access to the **JSON Schema** being sent to the provider. Use this hook when you need to transform the schema (e.g., inject `$defs`, strip vendor-incompatible keywords) or apply structured-output-specific behavior (e.g., suppress system prompts on the final call).
284​
285> Native-combined adapters (modern OpenAI, Claude 4.5+, Gemini 3.x, Grok 4.x — see issue #605) skip the separate finalization call and never invoke this hook. The engine passes the converted schema directly to `chatStream` after `onConfig` runs, so middleware cannot transform the native-combined schema.
286​
287Return a **partial** `StructuredOutputMiddlewareConfig` with only the fields you want to change — they are shallow-merged with the current config. Return `void` to pass through.
288​
289```typescript
290import { type ChatMiddleware } from "@tanstack/ai";
291import { sharedDefs } from "./defs";
292​
293const injectDefs: ChatMiddleware = {
294 name: "inject-defs",
295 onStructuredOutputConfig: (_ctx, config) => {
296 // `config.outputSchema` is the JSON Schema being sent to the provider
297 return {
298 outputSchema: {
299 ...config.outputSchema,
300 $defs: { ...sharedDefs },
301 },
302 };
303 },
304};
305```
306​
307**Config fields you can transform:**
308​
309| Field | Type | Description |
310|-------|------|-------------|
311| `messages` | `ModelMessage[]` | Canonical conversation history |
312| `providerMessages` | `ModelMessage[]` | Temporary context sent to the final call |
313| `systemPrompts` | `SystemPrompt[]` | System prompts on the final call |
314| `metadata` | `Record<string, unknown>` | Request metadata |
315| `modelOptions` | `Record<string, unknown>` | Provider-native options — this is where sampling params (`temperature`, `top_p` / `topP`, the provider's `max*Tokens` key) now live, alongside every other model-specific knob. See [Moving Sampling Options into modelOptions](../migration/sampling-options-to-model-options). |
316| `outputSchema` | `JSONSchema` | JSON Schema being sent to the provider for structured output |
317​
318**Ordering at the structured-output boundary:**
319​
3201. `onStructuredOutputConfig` fires first, piping through every middleware in array order.
3212. `onConfig` then re-fires at the same boundary with `ctx.phase === 'structuredOutput'`, receiving the post-`onStructuredOutputConfig` view of the config (minus `outputSchema`). Use `onConfig` for general-purpose transforms that apply to every adapter call; use `onStructuredOutputConfig` when you need access to the schema.
322​
323When multiple middleware define `onStructuredOutputConfig`, the config is **piped** through them in order — each receives the merged config from the previous middleware.
324​
325### onStart
326​
327Called once after the initial `onConfig` completes. Use it for setup tasks like initializing timers or logging.
328​
329```typescript
330import { type ChatMiddleware } from "@tanstack/ai";
331​
332const timer: ChatMiddleware = {
333 name: "timer",
334 onStart: (ctx) => {
335 console.log(`Request ${ctx.requestId} started at iteration ${ctx.iteration}`);
336 },
337};
338```
339​
340### onChunk
341​
342Called for every chunk streamed from the adapter. You can observe, transform, expand, or drop chunks.
343​
344```typescript ignore
345import { type ChatMiddleware } from "@tanstack/ai";
346​
347const redactor: ChatMiddleware = {
348 name: "redactor",
349 onChunk: (ctx, chunk) => {
350 if (chunk.type === "TEXT_MESSAGE_CONTENT") {
351 // Transform: redact sensitive content
352 return {
353 ...chunk,
354 delta: chunk.delta.replace(/\b\d{3}-\d{2}-\d{4}\b/g, "[REDACTED]"),
355 };
356 }
357 // Return void to pass through unchanged
358 },
359};
360```
361​
362**Return values:**
363​
364| Return | Effect |
365|--------|--------|
366| `void` / `undefined` | Chunk passes through unchanged |
367| `StreamChunk` | Replaces the original chunk |
368| `StreamChunk[]` | Expands into multiple chunks |
369| `null` | Drops the chunk entirely |
370​
371When multiple middleware define `onChunk`, chunks flow through them in order. If one middleware drops a chunk (returns `null`), subsequent middleware never see it.
372​
373#### Chunk types you'll see
374​
375`onChunk` receives every [AG-UI event](https://docs.ag-ui.com/introduction) the run produces — not just text. Narrow on `chunk.type` (a discriminated union) before reading type-specific fields. The common ones:
376​
377| `chunk.type` | Meaning | Key fields |
378|--------------|---------|-----------|
379| `RUN_STARTED` / `RUN_FINISHED` / `RUN_ERROR` | Run lifecycle boundaries | `runId`, `finishReason`, `usage` (on finish), `message` (on error) |
380| `TEXT_MESSAGE_START` / `TEXT_MESSAGE_CONTENT` / `TEXT_MESSAGE_END` | Assistant text streaming | `messageId`, `delta` (content) |
381| `TOOL_CALL_START` / `TOOL_CALL_ARGS` / `TOOL_CALL_END` | Tool invocation streaming | `toolCallId`, `toolCallName`, `delta` (args), result on end |
382| `STEP_STARTED` / `STEP_FINISHED` | Thinking / reasoning steps | `delta`, `signature` |
383| `STATE_SNAPSHOT` / `STATE_DELTA` | Agent state sync | `snapshot`, `delta` |
384| `CUSTOM` | Extensibility events (incl. structured-output — see below) | `name`, `value` |
385​
386See the [AG-UI protocol docs](https://docs.ag-ui.com/introduction) for the full event catalogue and exact field shapes.
387​
388#### Transforming structured-output chunks
389​
390There is **no separate `onStructuredOutputChunk` hook** — and you don't need one. When `chat()` is invoked with `outputSchema`, the structured-output chunks (the JSON `TEXT_MESSAGE_CONTENT` deltas, plus the `structured-output.start` / `structured-output.complete` CUSTOM events and any finalization `RUN_ERROR`) flow through the **same `onChunk` hook** as everything else. You transform, expand, or drop them exactly like any other chunk.
391​
392How you distinguish them depends on which finalization path the adapter takes:
393​
394- **Separate-finalization adapters** (`supportsCombinedToolsAndSchema()` does not return `true` for the current model/options): `ctx.phase === 'structuredOutput'` during the finalization call. Discriminate on the phase.
395- **Native-combined adapters** (modern OpenAI Chat Completions / Responses, Claude 4.5+, Gemini 3.x, Grok 4.x — see issue #605): the schema-constrained JSON is produced on the model's natural final turn, so **`ctx.phase` stays `'modelStream'`** — the `'structuredOutput'` phase never fires. Discriminate on the CUSTOM event name (`structured-output.start` / `structured-output.complete`) instead.
396​
397```typescript ignore
398import { type ChatMiddleware } from "@tanstack/ai";
399​
400const redactStructuredOutput: ChatMiddleware = {
401 name: "redact-structured-output",
402 onChunk: (ctx, chunk) => {
403 // Separate-finalization path: the JSON streams as TEXT_MESSAGE_CONTENT
404 // during the 'structuredOutput' phase. Transform the delta like any
405 // other text chunk — here, redact anything that looks like an SSN before
406 // it reaches the client.
407 if (
408 ctx.phase === "structuredOutput" &&
409 chunk.type === "TEXT_MESSAGE_CONTENT"
410 ) {
411 return {
412 ...chunk,
413 delta: chunk.delta.replace(/\b\d{3}-\d{2}-\d{4}\b/g, "[REDACTED]"),
414 };
415 }
416​
417 // Both paths: the completed typed payload arrives as a CUSTOM
418 // `structured-output.complete` event. On the native-combined path this is
419 // your only signal (ctx.phase never flips to 'structuredOutput'), so key
420 // off the event name, not the phase. `chunk.value` carries { object, raw }.
421 if (chunk.type === "CUSTOM" && chunk.name === "structured-output.complete") {
422 console.log("final structured output:", chunk.value);
423 }
424​
425 // Return void to pass everything else through unchanged.
426 },
427};
428```
429​
430> Why is there `onStructuredOutputConfig` but no `onStructuredOutputChunk`? Because the **config** shape genuinely differs at the structured-output boundary — it carries an `outputSchema` field that plain `ChatMiddlewareConfig` doesn't (see [onStructuredOutputConfig](#onstructuredoutputconfig)). **Chunks** are all just `StreamChunk` regardless of phase, so one `onChunk` plus `ctx.phase` (or the CUSTOM event name) covers every case — a parallel chunk hook would be redundant.
431​
432### onShouldContinue
433​
434Called when the engine is deciding whether to start another agent-loop iteration (after a tool phase or between model turns). Combined with AND semantics across middleware **and** with `agentLoopStrategy` — any explicit `false` stops the loop. Return `true`, `void`, or `undefined` to allow continuation.
435​
436Does **not** abort the run: the stream finishes normally with the current messages. Use `ctx.abort()` only for a hard abort.
437​
438```typescript
439import { type ChatMiddleware } from "@tanstack/ai";
440​
441const budget: ChatMiddleware = {
442 name: "tool-budget",
443 onShouldContinue: (_ctx, state) => {
444 // Stop further turns once 20 tool calls have been emitted
445 if (state.toolCallCount >= 20) return false;
446 },
447};
448```
449​
450For a full per-turn + cumulative tool budget recipe, see [Tool-call budgets](../chat/agentic-cycle#tool-call-budgets-middleware-recipe).
451​
452### onModelError
453​
454Some model calls fail for a reason your middleware can fix. For example, the prompt is too long for the model. `onModelError` gets the `RUN_ERROR` before anyone else sees it. Fix the request and call `ctx.retry()`. While the call has retries left, the run goes on as if the call never failed.
455​
456Say your app sends retrieved documents as a second system prompt. When the call is too long, this middleware drops them and tries again:
457​
458```typescript
459import { CONTEXT_OVERFLOW_CODE } from "@tanstack/ai";
460import type { ChatMiddleware, ChatMiddlewareContext } from "@tanstack/ai";
461​
462// The runs that go on without the documents.
463const withoutDocs = new WeakSet<ChatMiddlewareContext>();
464​
465const dropDocsWhenTooLong: ChatMiddleware = {
466 name: "drop-docs-when-too-long",
467 onModelError: (ctx, error) => {
468 if (error.code !== CONTEXT_OVERFLOW_CODE) return;
469 withoutDocs.add(ctx);
470 ctx.retry();
471 },
472 onConfig: (ctx, config) => {
473 if (ctx.phase !== "beforeModel" || !withoutDocs.has(ctx)) return;
474 // Keep the main system prompt. Drop the documents after it.
475 return { systemPrompts: config.systemPrompts.slice(0, 1) };
476 },
477};
478```
479​
480What `ctx.retry()` does while the call has retries left:
481​
482- It drops the failed call. `onChunk` and the caller never see its `RUN_STARTED` or `RUN_ERROR`.
483- It runs `onConfig` again (phase `beforeModel`), then calls the model again.
484- It works only inside `onModelError`. In any other hook it throws.
485​
486When the hook runs:
487​
488- Only when the adapter sends a `RUN_ERROR` before any output. A call that already sent text is not retried, so no output repeats.
489- Not for an exception that the adapter throws. That error goes to `onError`.
490- Not for the separate structured-output call that runs after the agent loop. The model calls of the agent loop get the hook as usual.
491- Every time, also after the last retry. A model call retries at most 2 times. After that, the error goes to the caller.
492​
493`withCompaction` uses this hook to [compact and retry after a context overflow](./compaction#when-the-chat-is-still-too-long).
494​
495### onInterruptBoundary and onInterruptResolution
496​
497Use these hooks when middleware needs data from the client. Define the request
498with `defineInterrupt()` and register it with `chat({ interrupts })` and
499`useChat({ interrupts })`. Do not emit raw AG-UI events from middleware.
500​
501`onInterruptBoundary` runs at four points in an agent iteration:
502​
503- `beforeModel`, before the adapter starts.
504- `afterModel`, after the model response is complete.
505- `beforeTools`, before tool execution starts.
506- `afterTools`, after the tool phase is complete.
507​
508Each middleware can return requests from one boundary. The engine combines all
509requests from that boundary into one AG-UI interrupt batch. The batch ends the
510run with one interrupt outcome.
511​
512This hook cannot change config. Its only legal return is `{ interrupts }` or
513nothing. The continuation is a new `chat()` call, so the hook runs again. Skip
514the emit when `ctx.parentRunId` is set if this pause belongs to the original
515request only.
516​
517What is in `ctx` at each phase, and when to use each phase, is in
518[Lifecycle Boundaries](../interrupts/boundaries).
519​
520Create one shared definition. Both the server and the client import this value,
521so the definition ID and response shape stay the same on both sides.
522​
523```typescript title="review-plan.ts"
524import { defineInterrupt, type ChatMiddleware } from '@tanstack/ai'
525import { z } from 'zod'
526​
527export const reviewPlan = defineInterrupt({
528 id: 'review-plan',
529 payloadSchema: z.object({ title: z.string() }),
530 responseSchema: z.object({ approved: z.boolean() }),
531})
532​
533export const reviewMiddleware: ChatMiddleware<unknown, typeof reviewPlan> = {
534 name: 'review-plan',
535 onInterruptBoundary(ctx) {
536 if (ctx.phase !== 'beforeTools') return
537 if (ctx.parentRunId) return
538 return {
539 interrupts: [
540 reviewPlan.interrupt({
541 key: 'release-plan',
542 reason: 'review-required',
543 message: 'Approve this plan?',
544 payload: { title: 'Release plan' },
545 }),
546 ],
547 }
548 },
549 onInterruptResolution(_ctx, resumedInterrupts) {
550 for (const result of resumedInterrupts.for(reviewPlan)) {
551 if (result.status === 'resolved' && !result.response.approved) {
552 return { toolResume: 'stop' }
553 }
554 }
555 },
557```
558​
559Register the definition on the server. Forward `parentRunId` and `resume` so
560a client resolution starts the continuation with its full context.
561​
562```typescript title="route.ts"
563import {
564 chat,
565 chatParamsFromRequestBody,
566 toServerSentEventsResponse,
567} from '@tanstack/ai'
568import { openaiText } from '@tanstack/ai-openai'
569import { reviewMiddleware, reviewPlan } from './review-plan'
570​
571export async function POST(request: Request) {
572 const params = await chatParamsFromRequestBody(await request.json())
573 const stream = chat({
574 adapter: openaiText('gpt-5.5'),
575 messages: params.messages,
576 threadId: params.threadId,
577 runId: params.runId,
578 ...(params.parentRunId ? { parentRunId: params.parentRunId } : {}),
579 ...(params.resume ? { resume: params.resume } : {}),
580 interrupts: [reviewPlan],
581 middleware: [reviewMiddleware],
582 })
583​
584 return toServerSentEventsResponse(stream)
586```
587​
588Register the same definition on the client. Check `kind` and `definitionId`.
589TypeScript then treats the item as `GenericInterrupt<typeof reviewPlan>`.
590`resolveInterrupt` uses the response shape from `reviewPlan.responseSchema`.
591​
592```tsx title="review-plan-panel.tsx"
593import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'
594import type { GenericInterrupt } from '@tanstack/ai-react'
595import { reviewPlan } from './review-plan'
596​
597function ReviewCard({
598 interrupt,
599}: {
600 interrupt: GenericInterrupt<typeof reviewPlan>
601}) {
602 return (
603 <button
604 onClick={() => interrupt.resolveInterrupt({ approved: true })}
605 >
606 Approve plan
607 </button>
608 )
610​
611export function ReviewPlanPanel() {
612 const { interrupts, sendMessage } = useChat({
613 connection: fetchServerSentEvents('/api/chat'),
614 interrupts: [reviewPlan],
615 })
616​
617 return (
618 <>
619 <button onClick={() => sendMessage('Review the release plan')}>
620 Start review
621 </button>
622 {interrupts.map((interrupt) => {
623 if (interrupt.kind !== 'generic') return null
624 if (!('definitionId' in interrupt)) return null
625 if (interrupt.definitionId !== reviewPlan.id) return null
626 return <ReviewCard key={interrupt.id} interrupt={interrupt} />
627 })}
628 </>
629 )
631```
632​
633`onInterruptResolution` does not run in the `chat()` call that paused. It
634runs once at the start of the next `chat()` call, after the client answers.
635​
636```
637setup
638onConfig (phase is init)
639onInterruptResolution (phase is still init)
640onStart
641then stop, or continue the agent loop
642```
643​
644`useChat` sends `parentRunId` and `resume` on that second request. Each
645generic resume item includes the original request in `metadata`. If `resume`
646is present and `parentRunId` is missing, the server throws.
647​
648Use `resumedInterrupts.for(definition)` for one typed definition. Use
649`resumedInterrupts.all()` for every registered definition. Use
650`resumedInterrupts.all(definitionA, definitionB)` to read a typed subset.
651​
652The hook can return `toolResume: 'continue'`, `'cancel'`, or `'stop'`. Results
653from all middleware combine by the most restrictive rule: `stop` wins over
654`cancel`, and `cancel` wins over `continue`.
655​
656This hook cannot change prompts, tools, or messages. Store the answer on a
657capability, then return those fields from `onConfig` when
658`ctx.phase === 'beforeModel'`.
659​
660| Hook | Can change |
661| --- | --- |
662| `onInterruptBoundary` | Nothing. It can only pause. |
663| `onInterruptResolution` | Pending-tool policy (`toolResume`) |
664| `onConfig` | `messages`, `systemPrompts`, `tools`, `modelOptions`, `metadata`, `toolChoice` |
665​
666The full resume order, plus an example that writes a user note into the
667system prompt, is in [Apply Answers](../interrupts/apply-answers).
668​
669### onBeforeToolCall
670​
671Called before a server tool runs, and before a client tool goes to the client. The first middleware that returns a non-void decision skips the remaining middleware for that call.
672​
673Each tool call goes through these steps:
674​
6751. The engine parses the JSON arguments from the model.
6762. `onBeforeToolCall` gets the parsed input.
6773. The tool's `inputSchema` checks the final input. An async validator is awaited. A schema transform applies once, here.
6784. The server tool runs, or the client gets the call, with the checked input.
679​
680The schema checks the input after your hook:
681​
682- `hookCtx.args` has no schema defaults or transforms yet, and it can be invalid. Check its shape before you read it.
683- A `transformArgs` value or an in-place edit must fit the schema. If it does not fit, the call gets a tool error, `onAfterToolCall` runs with `ok: false`, and the tool does not run.
684​
685When the hook runs:
686​
687- A client tool runs the hook before the server sends the call to the client. The hook does not run when the client result comes back.
688- A client tool gets `onAfterToolCall` only when the hook skips the call or the schema check fails. The result from the client does not run it. If your middleware pairs the two hooks, return early when `hookCtx.tool?.execute` is missing.
689- A call that waits for approval does not run the hook. A denied call does not run it either.
690- After approval, the hook gets the approved input, including any `editedArgs`. See [Tool Approval](../interrupts/tool-approval).
691​
692```typescript
693import { type ChatMiddleware } from "@tanstack/ai";
694​
695function isRecord(v: unknown): v is Record<string, unknown> {
696 return typeof v === "object" && v !== null;
698​
699const guard: ChatMiddleware = {
700 name: "guard",
701 onBeforeToolCall: (ctx, hookCtx) => {
702 // Block dangerous tools
703 if (hookCtx.toolName === "deleteDatabase") {
704 return { type: "abort", reason: "Dangerous operation blocked" };
705 }
706​
707 // Validate and transform arguments
708 if (hookCtx.toolName === "search" && isRecord(hookCtx.args) && !hookCtx.args.limit) {
709 return {
710 type: "transformArgs",
711 args: { ...hookCtx.args, limit: 10 },
712 };
713 }
714 },
715};
716```
717​
718**Decision types:**
719​
720| Decision | Effect |
721|----------|--------|
722| `void` / `undefined` | Continue normally, next middleware can decide |
723| `{ type: 'transformArgs', args }` | Replace tool arguments before execution |
724| `{ type: 'skip', result }` | Skip execution entirely, use provided result |
725| `{ type: 'abort', reason? }` | Abort the entire chat run |
726​
727The `hookCtx` provides:
728​
729| Field | Type | Description |
730|-------|------|-------------|
731| `toolCall` | `ToolCall` | Raw tool call object |
732| `tool` | `Tool \| undefined` | Resolved tool definition |
733| `args` | `unknown` | Parsed arguments |
734| `toolName` | `string` | Tool name |
735| `toolCallId` | `string` | Tool call ID |
736​
737### onAfterToolCall
738​
739Called after each tool execution (or skip). Every middleware runs, in array order.
740​
741```typescript
742import { type ChatMiddleware } from "@tanstack/ai";
743​
744const toolLogger: ChatMiddleware = {
745 name: "tool-logger",
746 onAfterToolCall: (ctx, info) => {
747 if (info.ok) {
748 console.log(`${info.toolName} completed in ${info.duration}ms`);
749 } else {
750 console.error(`${info.toolName} failed:`, info.error);
751 }
752 },
753};
754```
755​
756The `info` object provides:
757​
758| Field | Type | Description |
759|-------|------|-------------|
760| `toolCall` | `ToolCall` | Raw tool call object |
761| `tool` | `Tool \| undefined` | Resolved tool definition |
762| `toolName` | `string` | Tool name |
763| `toolCallId` | `string` | Tool call ID |
764| `ok` | `boolean` | Whether execution succeeded |
765| `duration` | `number` | Execution time in milliseconds |
766| `result` | `unknown` | Result (when `ok` is true). After a `replaceResult` from an earlier middleware, the new result. |
767| `error` | `unknown` | Error (when `ok` is false) |
768​
769#### Replace a tool result
770​
771Some tools return way more than the model needs: 500 rows, a huge log, a secret you want to hide. The model reads every token of it. Return `{ type: 'replaceResult', result }` and the model gets your version instead:
772​
773```typescript
774import { type ChatMiddleware } from "@tanstack/ai";
775​
776const firstTwentyRows: ChatMiddleware = {
777 name: "first-twenty-rows",
778 onAfterToolCall: (ctx, info) => {
779 if (!info.ok || !Array.isArray(info.result)) return;
780 if (info.result.length <= 20) return;
781 return {
782 type: "replaceResult",
783 result: {
784 rows: info.result.slice(0, 20),
785 omitted: info.result.length - 20,
786 },
787 };
788 },
789};
790```
791​
792| Return | What happens |
793|--------|--------|
794| nothing | The result stays the same. |
795| `{ type: 'replaceResult', result }` | The model gets `result`. The stream sends it in `TOOL_CALL_RESULT`, so the client shows it too. |
796​
797Good to know:
798​
799- Each middleware gets the result of the one before it as `info.result`. The last replacement wins.
800- A failed call stays failed. Your replacement becomes the error that the model reads.
801- A `skip` result from `onBeforeToolCall` goes through this hook too. `info.result` is the parsed skip result, the same value the model gets.
802- A call that the output limit cut goes through this hook too. It did not run, so `ok` is false, and `error` has the code `max_tokens`. See [When the output limit cuts a tool call](../chat/agentic-cycle#when-the-output-limit-cuts-a-tool-call).
803​
804### Tool hook order in one turn
805​
806When the model calls several server tools in one turn, the tools run at the same time:
807​
808- `onBeforeToolCall` runs for each call in call order, before any tool starts.
809- `onAfterToolCall` runs for each tool when it finishes, so in finish order.
810- A call that `onBeforeToolCall` skips gets its `onAfterToolCall` right away, before the tools start.
811- If the run aborts before the tools start, no tool runs. Each call gets `onAfterToolCall` with `ok: false` and the error "Operation aborted".
812- If `onBeforeToolCall` aborts or throws for a call, the calls before it still run. The error is thrown after they finish.
813​
814With `toolExecution: 'sequential'`, each call finishes its `onBeforeToolCall`, its run, and its `onAfterToolCall` before the next call starts. See [Run tools one at a time](../tools/tools#run-tools-one-at-a-time).
815​
816### onUsage
817​
818Called once per model iteration when the `RUN_FINISHED` chunk includes usage data. Receives the usage object directly.
819​
820```typescript
821import { type ChatMiddleware } from "@tanstack/ai";
822​
823const usageTracker: ChatMiddleware = {
824 name: "usage-tracker",
825 onUsage: (ctx, usage) => {
826 console.log(
827 `Iteration ${ctx.iteration}: ${usage.totalTokens} tokens`
828 );
829 },
830};
831```
832​
833The `usage` object:
834​
835| Field | Type | Description |
836|-------|------|-------------|
837| `promptTokens` | `number` | Input tokens |
838| `completionTokens` | `number` | Output tokens |
839| `totalTokens` | `number` | Total tokens |
840​
841### Terminal Hooks: onFinish, onAbort, onError
842​
843Exactly **one** terminal hook fires per `chat()` invocation. They are mutually exclusive:
844​
845| Hook | When it fires |
846|------|--------------|
847| `onFinish` | Run completed normally |
848| `onAbort` | Run was aborted (via `ctx.abort()`, an external `AbortSignal`, or a `{ type: 'abort' }` decision from `onBeforeToolCall`) |
849| `onError` | An unhandled error occurred |
850​
851`onFinish` also fires when the invocation pauses at a client-tool or approval wait. The run is not complete yet. To tell a pause from a completion, look in `onChunk` for a `RUN_FINISHED` chunk with `outcome.type === 'interrupt'`.
852​
853> **Separate-finalization path:** Adapters without native-combined support make a separate structured-output provider call after the agent loop.
855> - `onStructuredOutputConfig` fires before the separate provider call, and `ctx.phase` is `'structuredOutput'` for its chunks.
856> - `onIteration` does **not** fire for finalization; it only fires for agent-loop iterations.
857> - `onFinish` fires after finalization completes. Its `info` object reflects the **agent loop's** terminal state.
858> - `info.content` — the agent loop's accumulated text. Separate-finalization JSON deltas are **not** included. Middleware can observe the completed result through the `structured-output.complete` CUSTOM event in `onChunk`.
859> - `info.usage` — the agent loop's last `RUN_FINISHED.usage`. For a tools-less structured-output run (no agent-loop iteration produces `RUN_FINISHED`), this is `undefined`. To capture finalization tokens, use `onUsage` — that hook fires for **every** `RUN_FINISHED` carrying usage, including the finalization call.
860> - `info.finishReason` — the agent loop's last `finishReason`. `null` when no agent-loop iteration produced `RUN_FINISHED` (e.g. a tools-less structured-output run).
861> - `info.duration` — wall-clock duration of the entire `chat()` invocation, including finalization.
863> **Native-combined output:** Adapters with native-combined support produce the schema-constrained JSON in the regular agent-loop stream. `onStructuredOutputConfig` does not fire, `ctx.phase` remains `'modelStream'`, and `onIteration` fires for the iteration that produces the JSON. The JSON is agent-loop text, so `info.content` includes it. Middleware observes the `structured-output.complete` event in `onChunk` during the same phase.
865> On successful completion in either path, `onFinish` receives the complete canonical transcript in `ctx.messages`. Native-combined output keeps the structured result on its terminal assistant message. The separate-finalization path can preserve the agent loop's plain-text assistant message followed by a distinct structured-output assistant message. This transcript is separate from the path-specific fields on `info`.
867> To aggregate usage across the whole run, accumulate from `onUsage` callbacks rather than relying on `info.usage`.
868​
869```typescript
870import { type ChatMiddleware } from "@tanstack/ai";
871​
872const terminal: ChatMiddleware = {
873 name: "terminal",
874 onFinish: (ctx, info) => {
875 console.log(`Finished: ${info.finishReason}, ${info.duration}ms`);
876 console.log(`Content: ${info.content}`);
877 if (info.usage) {
878 console.log(`Tokens: ${info.usage.totalTokens}`);
879 }
880 },
881 onAbort: (ctx, info) => {
882 console.log(`Aborted: ${info.reason}, ${info.duration}ms`);
883 },
884 onError: (ctx, info) => {
885 console.error(`Error after ${info.duration}ms:`, info.error);
886 },
887};
888```
889​
890The `info` object for `onFinish` (`FinishInfo`):
891​
892| Field | Type | Description |
893|-------|------|-------------|
894| `finishReason` | `string \| null` | The agent loop's last `finishReason`. `null` when no agent-loop iteration produced `RUN_FINISHED` (e.g. a tools-less `chat({ outputSchema })` run). |
895| `duration` | `number` | Total run duration in milliseconds, including any structured-output finalization. |
896| `content` | `string` | The agent loop's accumulated text content. Includes native-combined structured JSON; excludes separate-finalization JSON. Observe the completed result through the `structured-output.complete` CUSTOM event via `onChunk`. |
897| `usage` | `{ promptTokens; completionTokens; totalTokens } \| undefined` | **Optional.** The agent loop's last `RUN_FINISHED.usage`. **Does not include finalization tokens** — use `onUsage` to observe those. Always guard with `if (info.usage)` or `info.usage?.`. |
898​
899## Context Object
900​
901Every hook receives a `ChatMiddlewareContext` as its first argument. It provides request-scoped information and control functions:
902​
903| Field | Type | Description |
904|-------|------|-------------|
905| `requestId` | `string` | Unique ID for this chat request |
906| `streamId` | `string` | Unique ID for this stream |
907| `threadId` | `string` | AG-UI thread identifier. Resolves to caller-provided `threadId` (or legacy `conversationId`), or an auto-generated value if neither is supplied. Use this for event correlation. |
908| `conversationId` | `string \| undefined` | **Deprecated** alias of `threadId`. Always equals `ctx.threadId`; retained so middleware written before the AG-UI rename keeps working. New middleware should read `ctx.threadId`. |
909| `phase` | `ChatMiddlewarePhase` | Current lifecycle phase |
910| `iteration` | `number` | Agent loop iteration (0-indexed) |
911| `chunkIndex` | `number` | Running count of chunks yielded |
912| `signal` | `AbortSignal \| undefined` | External abort signal |
913| `abort(reason?)` | `function` | Abort the run from within middleware |
914| `retry()` | `function` | Call the model again. Works only in [`onModelError`](#onmodelerror) |
915| `emitCustomEvent(name, value, options?)` | `function` | Push a `CUSTOM` chunk onto the chat stream now. The engine yields it while the current hook is still running, including during `onConfig`. Durability flushes it immediately. Pass `{ batch: true }` to keep it in the durability batch. |
916| `context` | `TContext` | User-provided runtime context value |
917| `defer(promise)` | `function` | Register a non-blocking side-effect |
918​
919## Typed Runtime Context
920​
921`ChatMiddleware` accepts a context generic. This lets reusable middleware declared outside `chat()` access the same typed runtime context as your tools.
922​
923```typescript
924import { chat, type ChatMiddleware } from "@tanstack/ai";
925import { openaiText } from "@tanstack/ai-openai";
926import { session, audit } from "./server";
927​
928type AppContext = {
929 userId: string;
930 audit: {
931 write(event: { userId: string; requestId: string }): Promise<void>;
932 };
933};
934​
935export const auditMiddleware: ChatMiddleware<AppContext> = {
936 name: "audit",
937 onStart(ctx) {
938 ctx.defer(
939 ctx.context.audit.write({
940 userId: ctx.context.userId,
941 requestId: ctx.requestId,
942 })
943 );
944 },
945};
946​
947chat({
948 adapter: openaiText("gpt-5.5"),
949 messages: [{ role: "user", content: "Hello" }],
950 middleware: [auditMiddleware],
951 context: {
952 userId: session.user.id,
953 audit,
954 },
955});
956```
957​
958When typed middleware or typed tools are present, `chat()` checks that the provided `context` matches the required shape. Existing middleware typed as plain `ChatMiddleware` still works; its `ctx.context` remains `unknown` and does not force a `context` option.
959​
960Runtime context is process-local application state. It is separate from AG-UI `RunAgentInput.context`, which is protocol metadata parsed by `chatParamsFromRequest`. See [Runtime Context](./runtime-context) for server, client, and client-to-server handoff patterns.
961​
962### Aborting from Middleware
963​
964Call `ctx.abort()` to gracefully stop the run. This triggers the `onAbort` terminal hook:
965​
966```typescript
967import { type ChatMiddleware } from "@tanstack/ai";
968​
969const timeout: ChatMiddleware = {
970 name: "timeout",
971 onChunk: (ctx) => {
972 if (ctx.chunkIndex > 1000) {
973 ctx.abort("Too many chunks");
974 }
975 },
976};
977```
978​
979### Deferred Side Effects
980​
981Use `ctx.defer()` to register promises that run after the terminal hook without blocking the stream:
982​
983```typescript
984import { type ChatMiddleware } from "@tanstack/ai";
985​
986const analytics: ChatMiddleware = {
987 name: "analytics",
988 onFinish: (ctx, info) => {
989 ctx.defer(
990 fetch("/api/analytics", {
991 method: "POST",
992 body: JSON.stringify({
993 requestId: ctx.requestId,
994 duration: info.duration,
995 tokens: info.usage?.totalTokens,
996 }),
997 })
998 );
999 },
1001```
1002​
1003## Composing Multiple Middleware
1004​
1005Middleware execute in array order. The ordering matters for hooks that pipe or short-circuit:
1006​
1007```typescript
1008import { chat, type ChatMiddleware } from "@tanstack/ai";
1009import { openaiText } from "@tanstack/ai-openai";
1010import { authMiddleware, loggingMiddleware, cachingMiddleware } from "./middleware";
1011​
1012const stream = chat({
1013 adapter: openaiText("gpt-5.5"),
1014 messages: [{ role: "user", content: "Hello" }],
1015 middleware: [authMiddleware, loggingMiddleware, cachingMiddleware],
1016});
1017```
1018​
1019### Composition Rules
1020​
1021| Hook | Composition | Effect of Order |
1022|------|------------|----------------|
1023| `onConfig` | **Piped** — each receives previous output | Earlier middleware transforms first |
1024| `onStructuredOutputConfig` | **Piped** — each receives previous output | Earlier middleware transforms first |
1025| `onStart` | Sequential | All run in order |
1026| `onChunk` | **Piped** — chunks flow through each middleware | If first drops a chunk, later middleware never see it |
1027| `onBeforeToolCall` | **First-win** — first non-void decision wins | Earlier middleware has priority |
1028| `onShouldContinue` | **AND** — any explicit `false` stops the loop | Order only affects which middleware runs first when short-circuiting |
1029| `onModelError` | Sequential. If any middleware calls `ctx.retry()` and the call has retries left, the model is called again | All run in order, so each one sees the error |
1030| `onAfterToolCall` | **Piped**: each gets the result of the previous `replaceResult` | The last replacement wins |
1031| `onUsage` | Sequential | All run in order |
1032| `onFinish/onAbort/onError` | Sequential | All run in order |
1033​
1034## Capabilities
1035​
1036Middleware often need to **share state**. A provider middleware sets something up (a database handle, a per-request counter, a sandbox), and a consumer middleware reads it back later in the same run. Capabilities make that hand-off **type-safe and order-checked**: the consumer declares what it needs, the provider declares what it offers, and `chat()` refuses to run (at compile time _and_ at runtime) if a required capability was never provided.
1037​
1038### Creating a capability
1039​
1040A capability is created with `createCapability<TValue>()('name')` — a **curried** call:
1041​
1042```typescript
1043import { createCapability } from "@tanstack/ai";
1044​
1045const counterCapability = createCapability<{ value: number }>()("counter");
1046const [getCounter, provideCounter] = counterCapability;
1047```
1048​
1049The currying is deliberate: you supply the **value type** explicitly (`<{ value: number }>`) while the **name literal** is inferred from the argument (`"counter"`). A single `createCapability<T>('name')` call can't do both — supplying `T` explicitly stops TypeScript inferring the name, collapsing it to `string` and defeating the compile-time coverage check that keys on the literal name.
1050​
1051The returned `counterCapability` is a hybrid value:
1052​
1053- It **destructures to `[get, provide]`** — the two accessors you use inside hooks.
1054- It **is itself the identity** you list in `requires` / `provides`. There is no separate token to import.
1055​
1056The accessors:
1057​
1058| Accessor | Behavior |
1059|----------|----------|
1060| `getCounter(ctx)` | Returns the value. **Throws** if the capability was never provided. |
1061| `getCounter(ctx, { optional: true })` | Returns `TValue \| undefined` — no throw when absent. |
1062| `provideCounter(ctx, value)` | Sets the value for this run. Call it from `setup`. |
1063​
1064Equivalently, the context exposes `ctx.get(capability)`, `ctx.getOptional(capability)`, and `ctx.provide(capability, value)` — pass the capability handle directly. These are typed by the handle you pass (`ctx.get(counterCapability)` returns the value type), so `getCounter(ctx)` and `ctx.get(counterCapability)` are interchangeable — use whichever reads better in your hook.
1065​
1066> **Capability names must be unique across your app.** The compile-time coverage check keys on the name literal (runtime keys on the handle reference), so two capabilities sharing a name will conflate in the type-level check.
1067​
1068### The `setup` hook
1069​
1070Provisioning happens in a dedicated `setup(ctx)` hook. It **runs first** — before any `onConfig` (init), across all middleware in array order — so that by the time the rest of the lifecycle begins, every capability is in place. `setup` receives the stable `ChatMiddlewareContext` (not the mutable config), and may be async.
1071​
1072### `requires` / `provides` / `optionalRequires`
1073​
1074Three array fields on a middleware declare its capability contract. Each is a `ReadonlyArray<CapabilityHandle>` — you list the capability handles themselves:
1075​
1076| Field | Meaning |
1077|-------|---------|
1078| `provides` | Capabilities this middleware sets up. Each one **must** be `provide`d inside `setup`, or `chat()` throws after the setup phase. |
1079| `requires` | Capabilities this middleware reads. `chat()` validates (compile time + runtime) that some earlier middleware provides each one. |
1080| `optionalRequires` | Capabilities used **if present** but not required. Non-gating — never causes a validation error. Read with `getX(ctx, { optional: true })`. |
1081​
1082### Array example
1083​
1084Author middleware with `defineChatMiddleware` — it sharpens the `requires` / `provides` tuple types so the coverage check and builder can read them precisely. Here a **provider** sets up a counter in `setup`, and a **consumer** reads it in a hook:
1085​
1086```typescript
1087import {
1088 chat,
1089 createCapability,
1090 createChatMiddleware,
1091 defineChatMiddleware,
1092} from "@tanstack/ai";
1093import { openaiText } from "@tanstack/ai-openai";
1094​
1095const counterCapability = createCapability<{ value: number }>()("counter");
1096const [getCounter, provideCounter] = counterCapability;
1097​
1098// Provider: declares `provides` and provisions the value in `setup`.
1099const withCounter = defineChatMiddleware({
1100 name: "with-counter",
1101 provides: [counterCapability],
1102 setup(ctx) {
1103 provideCounter(ctx, { value: 0 });
1104 },
1105});
1106​
1107// Consumer: declares `requires` and reads the value via `get` in a hook.
1108const countsChunks = defineChatMiddleware({
1109 name: "counts-chunks",
1110 requires: [counterCapability],
1111 onChunk(ctx) {
1112 getCounter(ctx).value++;
1113 },
1114 onFinish(ctx) {
1115 console.log(`Saw ${getCounter(ctx).value} chunks`);
1116 },
1117});
1118​
1119const stream = chat({
1120 adapter: openaiText("gpt-5.5"),
1121 messages: [{ role: "user", content: "Hello" }],
1122 // Provider must come before the consumer.
1123 middleware: [withCounter, countsChunks],
1124});
1125```
1126​
1127If you drop `withCounter` from the array, `chat()` reports a compile-time error at the `middleware` option naming the missing `"counter"` capability — and throws at runtime before the adapter is ever called.
1128​
1129### Builder example
1130​
1131`createChatMiddleware()` builds the array through chained `.use()` calls and enforces **provider-before-consumer ordering at compile time**: each `.use()` requires that the middleware's `requires` are already covered by capabilities provided by earlier `.use()` calls.
1132​
1133```typescript
1134import {
1135 chat,
1136 createCapability,
1137 createChatMiddleware,
1138 defineChatMiddleware,
1139} from "@tanstack/ai";
1140import { openaiText } from "@tanstack/ai-openai";
1141​
1142const counterCapability = createCapability<{ value: number }>()("counter");
1143const [getCounter, provideCounter] = counterCapability;
1144​
1145const withCounter = defineChatMiddleware({
1146 name: "with-counter",
1147 provides: [counterCapability],
1148 setup(ctx) {
1149 provideCounter(ctx, { value: 0 });
1150 },
1151});
1152​
1153const countsChunks = defineChatMiddleware({
1154 name: "counts-chunks",
1155 requires: [counterCapability],
1156 onChunk(ctx) {
1157 getCounter(ctx).value++;
1158 },
1159});
1160​
1161const middleware = createChatMiddleware()
1162 .use(withCounter) // provides "counter"
1163 .use(countsChunks) // requires "counter" — OK, already provided above
1164 .build();
1165​
1166const stream = chat({
1167 adapter: openaiText("gpt-5.5"),
1168 messages: [{ role: "user", content: "Hello" }],
1169 middleware,
1170});
1171```
1172​
1173Swap the two `.use()` calls (`.use(countsChunks).use(withCounter)`) and the builder rejects it at the `.use(countsChunks)` line — the consumer is ordered before its provider, so `"counter"` isn't in the provided set yet.
1174​
1175### Validation guarantees
1176​
1177The capability system fails loudly and early:
1178​
1179- **Compile-time coverage.** A required capability that nothing provides surfaces as a type error at the `middleware` option. This is enforced two ways: an **array coverage check** on `middleware: [...]`, and the order-aware **`createChatMiddleware()` builder** (which additionally enforces ordering).
1180- **Runtime coverage.** Even if types are bypassed, `chat()` validates coverage and **throws before the adapter runs** if a required capability is missing.
1181- **Post-`setup` assertion.** If a middleware declares a capability in `provides` but never calls its `provide` accessor during `setup`, `chat()` throws after the setup phase — you can't silently forget to provision.
1182- **Duplicate provide → last-wins + warning.** If two middleware provide the same capability, the last write wins and a development warning is emitted.
1183- **Unique names.** Capability `name`s must be unique across your app; the compile-time coverage check keys on the name literal (runtime keys on the handle reference).
1184​
1185### Append records to the session log
1186​
1187A host is a middleware that keeps a session log and provides `LogRecordsCapability`. `chat()` does not provide it, so without a host there is no log. With a host, your middleware can write its own records to that log, for example a note that a run started. Read the writer with `getLogRecords`:
1188​
1189```typescript
1190import {
1191 LogRecordsCapability,
1192 defineChatMiddleware,
1193 getLogRecords,
1194} from "@tanstack/ai";
1195​
1196const noteStart = defineChatMiddleware({
1197 name: "note-start",
1198 optionalRequires: [LogRecordsCapability],
1199 async onStart(ctx) {
1200 const log = getLogRecords(ctx, { optional: true });
1201 await log?.append([{ type: "app.note", text: "run started" }]);
1202 },
1203});
1204```
1205​
1206- Each record needs a `type`. The other fields are yours.
1207- The host decides which record types it accepts. If the host refuses a record, `append` rejects.
1208- Without a host log, `getLogRecords(ctx, { optional: true })` returns `undefined`. Use the optional read when your middleware also runs without a log.
1209- If your middleware cannot work without the log, list the capability in `requires` and call `getLogRecords(ctx)`. Then `chat()` throws when no host provides the log.
1210​
1211If you write a host, provide the log in `setup` and list it in `provides`:
1212​
1213```typescript
1214import {
1215 LogRecordsCapability,
1216 defineChatMiddleware,
1217 provideLogRecords,
1218} from "@tanstack/ai";
1219​
1220const withSessionLog = defineChatMiddleware({
1221 name: "with-session-log",
1222 provides: [LogRecordsCapability],
1223 setup(ctx) {
1224 // One log per run. A real host writes to its durable store here.
1225 const records: Array<{ type: string }> = [];
1226 provideLogRecords(ctx, {
1227 append: async (batch) => {
1228 records.push(...batch);
1229 },
1230 });
1231 },
1232});
1233```
1234​
1235## Built-in Middleware
1236​
1237TanStack AI ships ready-made middleware for common cases — caching tool results, redacting streamed text, and OpenTelemetry tracing:
1238​
1239| Middleware | Import | What it does |
1240|------------|--------|--------------|
1241| `toolCacheMiddleware` | `@tanstack/ai/middlewares` | Cache tool-call results by name + arguments |
1242| `contentGuardMiddleware` | `@tanstack/ai/middlewares` | Redact / transform / block streamed text content |
1243| `otelMiddleware` | `@tanstack/ai/middlewares/otel` | Emit OpenTelemetry spans + GenAI metrics |
1244​
1245See [Built-in Middleware](./built-in-middleware) for full options and examples for each. The recipes below show how to build your own.
1246​
1247## Recipes
1248​
1249### Live custom events
1250​
1251A long `onConfig` hook can send progress to the client while it waits. Call `ctx.emitCustomEvent` when the work starts, then again when it finishes:
1252​
1253```typescript
1254import { type ChatMiddleware } from "@tanstack/ai";
1255​
1256async function prepare() {
1257 await new Promise<void>((resolve) => {
1258 setTimeout(resolve, 1);
1259 });
1261​
1262const progress: ChatMiddleware = {
1263 name: "progress",
1264 async onConfig(ctx) {
1265 if (ctx.phase !== "beforeModel") return;
1266 ctx.emitCustomEvent("job:started", { step: "prepare" });
1267 await prepare();
1268 ctx.emitCustomEvent("job:ended", { step: "prepare" });
1269 },
1271```
1272​
1273The engine yields each `CUSTOM` chunk as soon as you call `emitCustomEvent`. If `RUN_STARTED` is not on the wire yet, the engine sends it first. Durability then flushes the event so the client can render a live indicator. Read these events on the client the same way as tool `emitCustomEvent` calls. See [Custom Events](../protocol/custom-events).
1274​
1275### Rate Limiting
1276​
1277Limit the number of tool calls per request:
1278​
1279```typescript
1280import { type ChatMiddleware } from "@tanstack/ai";
1281​
1282function rateLimitMiddleware(maxCalls: number): ChatMiddleware {
1283 let toolCallCount = 0;
1284 return {
1285 name: "rate-limit",
1286 onBeforeToolCall: (ctx, hookCtx) => {
1287 toolCallCount++;
1288 if (toolCallCount > maxCalls) {
1289 return {
1290 type: "abort",
1291 reason: `Rate limit: exceeded ${maxCalls} tool calls`,
1292 };
1294 },
1295 };
1297```
1298​
1299### Audit Trail
1300​
1301Log every action for compliance:
1302​
1303```typescript
1304import { type ChatMiddleware } from "@tanstack/ai";
1305import { db } from "./db";
1306​
1307const auditTrail: ChatMiddleware = {
1308 name: "audit-trail",
1309 onStart: (ctx) => {
1310 ctx.defer(
1311 db.auditLog.create({
1312 requestId: ctx.requestId,
1313 event: "chat_started",
1314 timestamp: Date.now(),
1315 })
1316 );
1317 },
1318 onAfterToolCall: (ctx, info) => {
1319 ctx.defer(
1320 db.auditLog.create({
1321 requestId: ctx.requestId,
1322 event: "tool_executed",
1323 toolName: info.toolName,
1324 success: info.ok,
1325 duration: info.duration,
1326 timestamp: Date.now(),
1327 })
1328 );
1329 },
1330 onFinish: (ctx, info) => {
1331 ctx.defer(
1332 db.auditLog.create({
1333 requestId: ctx.requestId,
1334 event: "chat_finished",
1335 duration: info.duration,
1336 tokens: info.usage?.totalTokens,
1337 timestamp: Date.now(),
1338 })
1339 );
1340 },
1342```
1343​
1344### Per-Iteration Tool Swapping
1345​
1346Expose different tools at different stages of the agent loop:
1347​
1348```typescript
1349import { type ChatMiddleware } from "@tanstack/ai";
1350​
1351const toolSwapper: ChatMiddleware = {
1352 name: "tool-swapper",
1353 onConfig: (ctx, config) => {
1354 if (ctx.phase !== "beforeModel") return;
1355​
1356 if (ctx.iteration === 0) {
1357 // First iteration: only allow search
1358 return {
1359 tools: config.tools.filter((t) => t.name === "search"),
1360 };
1362 // Later iterations: allow all tools
1363 },
1365```
1366​
1367### Content Filtering
1368​
1369Drop or transform chunks before they reach the consumer:
1370​
1371```typescript ignore
1372import { type ChatMiddleware } from "@tanstack/ai";
1373import { containsProfanity } from "./filters";
1374​
1375const contentFilter: ChatMiddleware = {
1376 name: "content-filter",
1377 onChunk: (ctx, chunk) => {
1378 if (chunk.type === "TEXT_MESSAGE_CONTENT") {
1379 if (containsProfanity(chunk.delta)) {
1380 // Drop the chunk entirely
1381 return null;
1384 },
1386```
1387​
1388### Error Recovery with Retry Logging
1389​
1390```typescript
1391import { type ChatMiddleware } from "@tanstack/ai";
1392import { alertService } from "./services";
1393​
1394const errorRecovery: ChatMiddleware = {
1395 name: "error-recovery",
1396 onError: (ctx, info) => {
1397 ctx.defer(
1398 alertService.send({
1399 level: "error",
1400 message: `Chat ${ctx.requestId} failed after ${info.duration}ms`,
1401 error: String(info.error),
1402 })
1403 );
1404 },
1406```
1407​
1408## TypeScript Types
1409​
1410The core middleware types are exported from `@tanstack/ai`:
1411​
1412```typescript
1413import type {
1414 ChatMiddleware,
1415 ChatMiddlewareContext,
1416 ChatMiddlewarePhase,
1417 ChatMiddlewareConfig,
1418 StructuredOutputMiddlewareConfig,
1419 ToolCallHookContext,
1420 BeforeToolCallDecision,
1421 AfterToolCallInfo,
1422 AfterToolCallDecision,
1423 IterationInfo,
1424 ToolPhaseCompleteInfo,
1425 UsageInfo,
1426 FinishInfo,
1427 AbortInfo,
1428 ErrorInfo,
1429} from "@tanstack/ai";
1430```
1431​
1432The option/type surfaces for the [built-in middleware](./built-in-middleware) are exported from the `@tanstack/ai/middlewares` subpath (not the main barrel):
1433​
1434```typescript
1435import type {
1436 ToolCacheMiddlewareOptions,
1437 ToolCacheStorage,
1438 ToolCacheEntry,
1439 ContentGuardMiddlewareOptions,
1440 ContentGuardRule,
1441 ContentFilteredInfo,
1442} from "@tanstack/ai/middlewares";
1443```
1444​
1445## Next Steps
1446​
1447- [Built-in Middleware](./built-in-middleware) — `toolCacheMiddleware`, `contentGuardMiddleware`, `otelMiddleware`
1448- [Compaction](./compaction): keep long chats under the context limit with `withCompaction`
1449- [OpenTelemetry](./otel) — emit traces and metrics via `otelMiddleware`- [Tools](../tools/tools) — Learn about the isomorphic tool system
1450- [Agentic Cycle](../chat/agentic-cycle) — Understand the multi-step agent loop
1451- [Streaming](../chat/streaming) — How streaming works in TanStack AI