Open History to see the last commit
1---
2title: "@tanstack/ai-client"
3slug: /api/ai-client
4order: 2
5description: "API reference for @tanstack/ai-client: ChatClient, connection adapters, generation clients, and BYOK, with no UI framework."
6keywords:
7 - tanstack ai
8 - "@tanstack/ai-client"
9 - headless client
10 - ChatClient
11 - chat state
12 - connection adapters
13 - api reference
14---
15
16The headless client under every framework package. Use it directly for vanilla JavaScript or a custom binding. For typed chat UI types and selectors, import `@tanstack/ai-client/ui` and see [Custom Chat UI Adapters](../ui/custom-adapters).
17
18## Installation
19
20<!-- ::start:tabs variant="package-manager" mode="install" -->
21
22react: @tanstack/ai-client
23vue: @tanstack/ai-client
24solid: @tanstack/ai-client
25svelte: @tanstack/ai-client
26preact: @tanstack/ai-client
27angular: @tanstack/ai-client
28vanilla: @tanstack/ai-client
29octane: @tanstack/ai-client
30
31<!-- ::end:tabs -->
32
33## `ChatClient`
34
35Holds the messages and the run state of one chat, and talks to your server route.
36
37```typescript
38import { ChatClient, fetchServerSentEvents } from "@tanstack/ai-client";
39
40const client = new ChatClient({
41 connection: fetchServerSentEvents("/api/chat"),
42 threadId: "support-chat",
43});
44
45const unsubscribe = client.subscribeSnapshot(() => {
46 const { messages, isLoading } = client.getSnapshot();
47 console.log(messages.length, isLoading);
48});
49
50client.attach();
51await client.sendMessage("Hello!");
52```
53
54### Lifecycle: `attach()` and `detach()`
55
56A new client opens no connection. When your view appears, call `attach()`. When it goes away, call `detach()`. The framework hooks do this for you on mount and unmount.
57
58```typescript
59import { ChatClient, fetchServerSentEvents } from "@tanstack/ai-client";
60
61const client = new ChatClient({
62 connection: fetchServerSentEvents("/api/chat"),
63 threadId: "thread-1",
64 persistence: true,
65});
66
67client.attach(); // rejoin a run in progress, and load the thread
68client.detach(); // drop the connection, keep the messages and the run pointer
69```
70
71The connection follows the view because a browser allows only about six connections to one origin. A chat that follows a run holds one connection for as long as the run lasts. If every chat on a page held one, the other requests wait behind them.
72
73- `attach()` is safe to call more than once. A second call does nothing.
74- `detach()` keeps the messages, the resume pointer, and the run id. The run goes on at the server, and a later `attach()` picks it up from the durable log.
75- `detach()` does not end the run (that is `stop()`) or the client (that is `dispose()`).
76- A chat with no persistence has nothing to rejoin, so `attach()` sends no request.
77
78### Constructor options
79
80You must pass `threadId`. You must also pass `connection` or `fetcher`, not both.
81
82| Option | What it does |
83| --- | --- |
84| `connection` | Connection adapter. See [Connection adapters](#connection-adapters). |
85| `fetcher` | A function that gets `{ messages, data, threadId, runId, ... }` and an abort `signal`, and returns a `Response` or a stream. Use it with server functions. |
86| `tools` | Client tools from `.client()`. The client runs them when the model calls them. See [Client Tools](../tools/client-tools). |
87| `threadId` | Required. The id of this chat. Use a stable id for each conversation, for example the id from your route. |
88| `persistence` | `true` to load the thread from the server, or a storage adapter. See [Chat Persistence](../persistence/chat-persistence). |
89| `history` | `{ pageSize }`: load only the newest messages first. Only with `persistence: true`. |
90| `initialMessages` | The messages to show first. |
91| `forwardedProps` | JSON sent to the server in the AG-UI `RunAgentInput.forwardedProps` field. |
92| `context` | Client-only runtime context for client tools. It is not sent to the server. |
93| `queue` | What `sendMessage` does while a run is busy: `"queue"` (default), `"drop"`, `"interrupt"`, a config, or a function. See [Queueing](../chat/queueing). |
94| `interrupts` | Definitions from `defineInterrupt()`. See [Interrupts](../interrupts/overview). |
95| `byok` | A keyring from [`defineByok`](#definebyok). The client sends the key in `x-byok-*` headers, never in the body. |
96| `byokProvider` | A function that returns the provider slug for this chat. If it returns nothing, the client uses `provider` from the merged `forwardedProps` and send `body`. If no slug resolves, the send throws. It does not send every stored key. |
97| `streamProcessor` | `{ chunkStrategy }`. Controls when text updates are applied. Default: `ImmediateStrategy`, every chunk. |
98| `initialResumeSnapshot` | A saved resume state to restore pending interrupts after a reload. |
99| `devtools`, `devtoolsBridgeFactory` | Devtools metadata, and the bridge factory from `@tanstack/ai-client/devtools`. |
100
101Callbacks:
102
103| Callback | When it runs |
104| --- | --- |
105| `onResponse`, `onChunk`, `onFinish`, `onError` | When a response arrives, a chunk arrives, a response ends, or an error occurs. |
106| `onMessagesChange`, `onLoadingChange`, `onErrorChange`, `onStatusChange` | When that piece of state changes. |
107| `onSubscriptionChange`, `onConnectionStatusChange`, `onSessionGeneratingChange` | When the live subscription changes. |
108| `onHydratingChange` | When loading from persistence starts or stops. |
109| `onQueueChange`, `onRunIdChange` | When the queue or the run id changes. |
110| `onInterruptStateChange` | When interrupt state changes. The second argument is `{ source: "hydrate" }` for restored state and `{ source: "live" }` otherwise. |
111| `onResumeStateChange` | When the resume state or pending interrupts change. |
112| `onCustomEvent` | When a server tool calls `emitCustomEvent()`. See [Custom Events](../protocol/custom-events). |
113
114### Methods
115
116| Method | What it does |
117| --- | --- |
118| `sendMessage(content, body?, sendOptions?)` | Sends a user message and starts a run. |
119| `append(message)` | Adds a `UIMessage` or `ModelMessage` and starts a run. |
120| `reload()` | Removes the answer after the last user message and runs that message again. |
121| `stop()` | Aborts the request in flight. Client tool results for that turn are ignored. |
122| `clear()` | Clears all messages. |
123| `setMessagesManually(messages)` | Replaces the messages. |
124| `addToolResult(result)` | Gives a client tool result by hand: `{ toolCallId, tool, output, state?, errorText? }`. |
125| `attach()`, `detach()` | Start and stop the connection for a view. |
126| `subscribe(options?)`, `unsubscribe()` | Start and stop the live subscription loop. |
127| `getSnapshot()`, `subscribeSnapshot(listener)` | Read the UI state, and listen for changes. |
128| `getInterrupts()` | Pending interrupts, each with `resolveInterrupt(...)`. |
129| `resolveInterrupts(...)`, `cancelInterrupts()`, `retryInterrupts()`, `resumeInterruptsUnsafe(resume, state?)` | Act on all pending interrupts at once. |
130| `cancelQueued(id)`, `getQueue()` | Cancel or read queued messages. |
131| `loadOlderMessages()`, `getHasOlderMessages()` | Page in older messages. |
132| `updateOptions(options)` | Change the transport, `forwardedProps`, `tools`, `context`, `queue`, BYOK, or callbacks. |
133| `dispose()` | Ends the client: stops the subscription and releases devtools. |
134
135Read single values with `getMessages()`, `getIsLoading()`, `getStatus()`, `getError()`, `getIsHydrating()`, `getIsSubscribed()`, `getConnectionStatus()`, `getSessionGenerating()`, and `getCurrentRunId()`.
136
137#### `sendMessage(content, body?, sendOptions?)`
138
139`content` is a string or `MultimodalContent`: `{ content, id?, metadata? }`. Use the object form to put `metadata` on the user `UIMessage`. TanStack writes the `tanstack` key in `metadata`. Your keys stay at the top level.
140
141`body` and `sendOptions.body` are extra JSON for this request. They shallow-merge with the chat `forwardedProps`. On a key collision, `sendOptions.body` wins. `sendOptions.whenBusy` overrides the queue policy for this send.
142
143The framework hooks expose `sendMessage(content, sendOptions)` with no positional `body`. Pass `{ body }` there.
144
145```typescript
146import { client } from "./client";
147
148await client.sendMessage({
149 content: "Summarize the attached files",
150 metadata: { author: { id: "user-42", name: "Dana" } },
151});
152
153await client.sendMessage("Summarize the attached files", undefined, {
154 body: { attachmentIds: ["att_1", "att_2"] },
155 whenBusy: "interrupt",
156});
157```
158
159On the server, read the merged JSON from `chatParamsFromRequest`:
160
161```typescript
162import {
163 chat,
164 chatParamsFromRequest,
165 toServerSentEventsResponse,
166} from "@tanstack/ai";
167import { openaiText } from "@tanstack/ai-openai";
168
169export async function POST(request: Request) {
170 const { messages, forwardedProps, threadId } = await chatParamsFromRequest(request);
171 const attachmentIds = forwardedProps.attachmentIds;
172 if (Array.isArray(attachmentIds)) {
173 // Look up the uploads. Do not add them to `messages`.
174 }
175 const stream = chat({
176 adapter: openaiText("gpt-6.1-sol"),
177 messages,
178 threadId,
179 });
180 return toServerSentEventsResponse(stream);
181}
182```
183
184If `append()` starts the stream, it resolves after the full HTTP response is processed. If a stream is already in progress, the call queues the send, and the promise can resolve before the queued response is processed. A `RUN_FINISHED` with `finishReason: "tool_calls"` does not end the wait when the agent loop goes on in the same response.
185
186`append()` copies `metadata` from a `UIMessage` onto the stored message.
187
188After `stop()`, a later `addToolResult()` for the stopped turn is ignored. A new user message starts a new turn, and `addToolResult()` applies to that turn.
189
190#### `getSnapshot()` and `subscribeSnapshot(listener)`
191
192The snapshot has `messages`, `status`, `isLoading`, `error`, `queue`, `runId`, `isSubscribed`, `connectionStatus`, `sessionGenerating`, `hasOlderMessages`, `isHydrating`, and `interruptState`.
193
194- The snapshot, `messages`, `queue`, and their entries are frozen copies. `messages.push` throws. Use `setMessagesManually`.
195- `interruptState` is not copied.
196- `subscribeSnapshot(listener)` returns an unsubscribe function. It does not fire with the current value, so read `getSnapshot()` first.
197- `subscribeSnapshot` is not `subscribe()`. `subscribe()` starts the live connection loop.
198
199## Connection adapters
200
201Each adapter pairs with a server response helper from `@tanstack/ai`. See [Transports](../transports/overview).
202
203| Adapter | Server pair | Use it when |
204| --- | --- | --- |
205| `fetchServerSentEvents(url, options?)` | `toServerSentEventsResponse()` | Default for browsers. |
206| `fetchHttpStream(url, options?)` | `toHttpResponse()` | You want newline-delimited JSON. |
207| `fetchJson(url, options?)` | `toJsonResponse()` | The host cannot stream. See [JSON](../transports/json). |
208| `xhrHttpStream(url, options?)` | `toHttpResponse()` | React Native and Expo. See [React Native](../transports/react-native). |
209| `xhrServerSentEvents(url, options?)` | `toServerSentEventsResponse()` | XHR progress events work better than streaming `fetch`. |
210| `webSocket(url, options?)` | `toWebSocketResponse()` | You want one socket for many runs. See [WebSockets](../transports/websockets). |
211| `stream(factory)`, `rpcStream(call)` | Any `AsyncIterable<StreamChunk>` | You call a server function directly. See [Server Functions](../transports/server-functions). |
212
213```typescript
214import { fetchServerSentEvents } from "@tanstack/ai-client";
215
216const connection = fetchServerSentEvents("/api/chat", {
217 headers: { Authorization: "Bearer token" },
218});
219```
220
221`url` can be a string or a function that returns one. `options` can be an object or a function that returns one per request.
222
223### Adapter options
224
225Fetch adapters take `headers`, `credentials`, `signal`, `body`, `fetchClient`, and `reconnect`.
226
227XHR adapters take `headers`, `withCredentials`, `signal`, `body`, `xhrFactory`, and `reconnect`.
228
229`fetchJson()` also takes `pollIntervalMs` (default 250). When a reply has `done: false`, it waits that long and sends `GET ?runId=<id>&offset=<offset>`. Serve that `GET` with `resumeJsonResponse()`.
230
231The adapter `body` merges into the AG-UI `forwardedProps`. The chat `forwardedProps` and the per-send `body` override it.
232
233`fetchHttpStream()` needs streaming `fetch`, `Response.body.getReader()`, and `TextDecoder`. If the runtime has none of these, it throws `UnsupportedResponseStreamError`. Use the XHR adapters in React Native and Expo.
234
235### `stream(factory)`
236
237Builds a custom adapter from a function that returns `AsyncIterable<StreamChunk>`. The function gets `(messages, data, abortSignal, input)`. `data` is the merged `forwardedProps`. `input` is the AG-UI `RunAgentInput` for the run, the same body the HTTP adapters send. Read it on the server with `chatParamsFromRequestBody`.
238
239```typescript
240import { stream } from "@tanstack/ai-client";
241import { chatOnServer } from "./server";
242
243const connection = stream((_messages, _data, signal, input) =>
244 chatOnServer({ input, signal }),
245);
246```
247
248### Stream errors
249
250- `UnsupportedResponseStreamError`: a fetch adapter found no `Response.body`, `getReader()`, or `TextDecoder`.
251- `StreamTruncatedError`: an SSE or NDJSON stream ended in the middle of a line. A server, a proxy, or the network cut the connection.
252- `DurableStreamIncompleteError` and `StreamReconnectLimitError`: a resumable stream did not finish. See [Resumable Streams](../resumable-streams/overview).
253
254## Persistence adapters
255
256Browser storage adapters for `persistence`. Each one keeps the messages and the resume state for a `threadId`. See [Client Persistence](../persistence/client-persistence).
257
258| Adapter | Storage |
259| --- | --- |
260| `localStoragePersistence(options?)` | `localStorage` |
261| `sessionStoragePersistence(options?)` | `sessionStorage` |
262| `indexedDBPersistence(options?)` | IndexedDB. The default `databaseName` is `"tanstack-ai"`. |
263
264They throw `StorageUnavailableError` when the browser storage is not available.
265
266## `createChatClientOptions(options)`
267
268Returns the options unchanged, with full type inference. Use it to define options outside a hook and to get the message type.
269
270```typescript
271import {
272 createChatClientOptions,
273 fetchServerSentEvents,
274 type InferChatMessages,
275} from "@tanstack/ai-client";
276import { searchProducts } from "./tools";
277
278const chatOptions = createChatClientOptions({
279 connection: fetchServerSentEvents("/api/chat"),
280 threadId: "support-chat",
281 tools: [searchProducts],
282});
283
284type ChatMessages = InferChatMessages<typeof chatOptions>;
285```
286
287A plain tools array keeps tool names, inputs, and outputs typed. You do not need `as const`. When you narrow with `part.name === "searchProducts"`, `part.input` and `part.output` get their types from the schemas of that tool.
288
289Client context stays typed too. If a `.client<ClientContext>()` tool needs context, `context` becomes required. It stays on the client. To send values to the server, use `forwardedProps`, then validate them and pass them to `chat({ context })`.
290
291## `clientTools(...tools)`
292
293Returns its arguments as a typed tuple. A plain array already gives the same types, so use this only to build a shared tools tuple outside the options call.
294
295```typescript
296import { clientTools } from "@tanstack/ai-client";
297import { searchProducts, showToast } from "./tools";
298
299export const tools = clientTools(searchProducts, showToast);
300```
301
302## `GenerationClient`
303
304Runs one generation request (image, audio, speech, transcription, summary, or your own type) and keeps its result. The framework generation hooks wrap it. See [Generation Hooks](../media/generation-hooks).
305
306```typescript
307import type { ImageGenerationResult } from "@tanstack/ai";
308import {
309 GenerationClient,
310 fetchServerSentEvents,
311 type ImageGenerateInput,
312} from "@tanstack/ai-client";
313
314const generation = new GenerationClient<ImageGenerateInput, ImageGenerationResult>({
315 connection: fetchServerSentEvents("/api/generate/image"),
316 threadId: "generation",
317 onResult: (result) => console.log(result.images.length),
318});
319
320await generation.generate({ prompt: "A mountain at sunset" });
321```
322
323- Options: `threadId` (required), `connection` or `fetcher`, `body`, `persistence`, `byok`, `byokProvider`, `devtools`, `onResult`, `onError`, `onProgress`, `onChunk`.
324- Methods: `generate(input)`, `stop()`, `reset()`, `updateOptions(options)`, `dispose()`, `getResult()`, `getIsLoading()`, `getError()`, `getStatus()`.
325- Snapshot: `result`, `isLoading`, `error`, `status` (`"idle"`, `"generating"`, `"success"`, or `"error"`), and `runId`.
326
327`VideoGenerationClient` does the same for video jobs. Its snapshot adds `jobId` and `videoStatus`, and it takes `onJobCreated` and `onStatusUpdate`.
328
329## `RealtimeClient`
330
331Runs a voice conversation with a realtime model. Pass `getToken` and `adapter`. Methods: `connect()`, `disconnect()`, `startListening()`, `stopListening()`, `interrupt()`, `sendText(text)`, `sendImage(data, mimeType)`, `updateSession(config)`, and `destroy()`. See [Realtime Chat](../media/realtime-chat).
332
333When `connect()` succeeds, it clears the previous transcript. A transcript that arrives while the microphone starts is kept. A failed connection keeps the previous transcript. Snapshot `parts` are frozen at runtime, but their TypeScript type stays mutable. Tool `input`, `output`, and subagent transcripts on a snapshot are copies.
334
335## `AudioRecorder`
336
337Records audio from the microphone. Methods: `start()`, `stop()` (resolves to the recording), and `cancel()`. See [Audio Recording](../media/audio-recording).
338
339### Listeners on the other clients
340
341`GenerationClient`, `VideoGenerationClient`, `RealtimeClient`, and `ByokClient` use `subscribe(listener)` and `getSnapshot()`:
342
343- The listener gets no argument. Call `getSnapshot()` inside it.
344- A listener that throws does not stop the other listeners. The error goes to `reportError` in the browser and to `console.error` in other runtimes.
345
346`AudioRecorder.subscribe` passes the new state: `subscribe((state) => ...)`. `getSnapshot()` returns that same state.
347
348## `registerWebMCPTools(tools, options)`
349
350Exposes client tools through the browser WebMCP API. Abort `options.signal` to remove the tools. See [WebMCP Tools](../tools/webmcp).
351
352```typescript
353import { registerWebMCPTools } from "@tanstack/ai-client";
354import { searchProducts } from "./tools";
355
356const controller = new AbortController();
357
358await registerWebMCPTools([searchProducts], {
359 signal: controller.signal,
360 toolOptions: {
361 searchProducts: {
362 title: "Search products",
363 annotations: { readOnlyHint: true },
364 },
365 },
366});
367
368// Later, when the owner of these tools goes away:
369controller.abort();
370```
371
372| Option | What it does |
373| --- | --- |
374| `signal` | Required. Aborting it removes all tools of this call. |
375| `toolOptions` | Per tool name: `title` and `annotations` (`readOnlyHint`, `untrustedContentHint`). |
376| `context` | Client tool runtime context. Required when a tool declares a required context. |
377
378- It returns `Promise<void>`. During server rendering, in an insecure context, or when WebMCP is not there, it resolves and registers nothing.
379- It validates Standard Schema inputs and outputs.
380- A tool with `needsApproval: true` makes the registration fail. If registration fails, the function removes the tools it registered during the call.
381
382Option types: `RegisterWebMCPToolsOptions`, `WebMCPToolOptionsByName`, `WebMCPToolOptions`, `WebMCPToolAnnotations`.
383
384## `getWebMCPTools(options?)` and `subscribeWebMCPTools(listener, options)`
385
386Read the tools that the page registered with WebMCP, as client tools. See [Page WebMCP Tools in Chat](../tools/webmcp-page-tools).
387
388- `getWebMCPTools({ filter? })` resolves to the current tools, or `[]` when WebMCP is not there.
389- `subscribeWebMCPTools(listener, { signal, filter?, onError? })` calls `listener` with the tools each time the page adds or removes one. Abort `signal` to stop.
390
391`filter` gets a `WebMCPPageTool` (`name`, `title`, `description`, `inputSchema`, `origin`, `annotations`). Return `false` to skip it.
392
393## `createMcpAppBridge(options)`
394
395Creates the bridge that lets an MCP App widget call tools and send chat messages. Options: `threadId`, `callEndpoint`, `chat`, `fetchImpl`, `onLink`. See [MCP Apps](../mcp/apps).
396
397## `defineByok`
398
399Creates a headless BYOK keyring. Import it from `@tanstack/ai-client/byok`. Pass the keyring to `ChatClient`, `useChat`, or a generation hook. See [Bring Your Own Key](../advanced/byok).
400
401```typescript
402import { defineByok, defaultByokStorage } from "@tanstack/ai-client/byok";
403
404export const byok = defineByok({
405 storage: defaultByokStorage(),
406});
407```
408
409### Factory options
410
411- `storage`: a `KeyringStorage`. Default: `memoryStorage()`, which keeps keys for the session only.
412- `providers`: descriptors whose `with` companions the keyring adds. With `[cloudflareByok, cloudflareAccountByok]`, a send for `cloudflare` carries the token and the account id headers. `prepare` asks for each missing one.
413
414### Methods
415
416| Method | What it does |
417| --- | --- |
418| `update(provider, key)` | Saves a key for a provider slug (`[a-z][a-z0-9-]{0,63}`), then updates the snapshot. Throws if the id is not a slug, the key is empty, or storage fails. |
419| `update(key)` | Saves a key for the current `prompt` provider. Throws if `prompt` is null. |
420| `clear(provider?)` | Removes one key, or all keys when you omit `provider`. |
421| `unlock()` | Decrypts unlockable storage (passkey). Does nothing for memory storage. |
422| `headers(provider)` | Returns the `x-byok-*` headers for that slug and its companions. |
423| `prepare(provider?)` | Waits for hydration, then unlocks if needed. If the key for `provider` or a companion is empty and the server does not cover it, it throws `ByokBlockedError` and sets `prompt`. |
424| `ready()` | Resolves when the first load from storage ends. |
425| `setServerCoverage(flags)` | `true`: do not block a send when the browser has no key, because the relay can use its env. `false`: block (default). A record sets flags per slug. |
426| `request(provider, reason)` | Sets `prompt` to `{ provider, reason }`. `reason` is `"missing"`, `"locked"`, or `"invalid"`. |
427| `getSnapshot()`, `subscribe(listener)` | Read the [snapshot](#snapshot), and listen for changes. |
428| `keys()` | Returns a copy of the raw keyring. Do not show it in the UI. |
429
430The chat and generation clients throw if no provider slug resolves. They do not send every stored key.
431
432### Snapshot
433
434```typescript ignore
435type ByokSnapshot = {
436 status: Partial<Record<string, KeyStatus>>;
437 locked: boolean;
438 prompt: { provider: string; reason: "missing" | "locked" | "invalid" } | null;
439 storageError: string | null;
440};
441
442type KeyStatus =
443 | { state: "empty" }
444 | { state: "set"; masked: string }
445 | { state: "locked"; masked: string }
446 | { state: "validating"; masked: string }
447 | { state: "valid"; masked: string }
448 | { state: "invalid"; masked: string }
449 | { state: "error"; masked: string; message: string };
450```
451
452- `status` is sparse. Only slugs with a key, a lock, or a validation result appear. A missing entry means no key.
453- `masked` is the last four characters of the key. `{ state: "empty" }` has no `masked`, so check with `"masked" in status`.
454- `storageError` is set when loading from storage fails.
455- The snapshot never holds the raw key.
456
457### Storage
458
459| Storage | What it does |
460| --- | --- |
461| `defaultByokStorage(options?)` | Passkey-encrypted IndexedDB when WebAuthn is available in a secure context. Otherwise `memoryStorage()`, with a warning. The first save still throws if the authenticator has no PRF support. |
462| `memoryStorage()` | Keeps keys on the `ByokClient` instance. Keys are gone when the page reloads. |
463| `passkeyStorage(options?)` | Encrypts the keyring with a WebAuthn passkey. The first save throws if the authenticator has no PRF support. |
464| `KeyringStorage` | The storage interface: `{ id, label, persistent, unlockable?, peek?, load, save, clear }`. |
465
466The library ships no key dialog. Call `byok.update(provider, value)` from your own UI.
467
468## Types
469
470### `UIMessage`
471
472```typescript ignore
473interface UIMessage<TTools = any> {
474 id: string;
475 role: "system" | "user" | "assistant" | "activity";
476 name?: string;
477 parts: Array<MessagePart<TTools>>;
478 createdAt?: Date;
479 metadata?: Record<string, any>;
480}
481```
482
483`metadata` is an AG-UI bag. TanStack writes the `tanstack` key. Your keys stay at the top level.
484
485### `MessagePart`
486
487| Part | `type` | What it holds |
488| --- | --- | --- |
489| `TextPart` | `"text"` | `content`: the text. |
490| `ThinkingPart` | `"thinking"` | `content`: the model reasoning. See [Thinking Content](../chat/thinking-content). |
491| `ToolCallPart` | `"tool-call"` | `id`, `name`, `arguments` (JSON string, can be partial while it streams), `input`, `output`, `state`, and `approval` for tools with `needsApproval: true`. |
492| `ToolResultPart` | `"tool-result"` | `toolCallId`, `content`, `state`, `error`, `outcome`, `metadata`. |
493| `ImagePart`, `AudioPart`, `VideoPart`, `DocumentPart` | media types | Media content. See [Multimodal Content](../advanced/multimodal-content). |
494| `StructuredOutputPart` | `"structured-output"` | Typed `data` and `partial`. See [Structured Outputs](../structured-outputs/overview). |
495| `ActivityPart`, `UIResourcePart`, `SubagentPart` | other | Activity records, MCP App resources, and subagent runs. |
496
497Thinking parts are for the UI only. The client does not send them back to the model.
498
499With a typed tools array, `ToolCallPart` is a union with `name` as the key. Narrow on `part.name` to get typed `input` and `output`. The `approval` field exists only on tools with `needsApproval: true`, so narrow by `part.name` or check `"approval" in part` first.
500
501### States
502
503```typescript ignore
504type ToolCallState =
505 | "awaiting-input"
506 | "input-streaming"
507 | "input-complete"
508 | "approval-requested"
509 | "approval-responded"
510 | "complete"
511 | "error";
512
513type ToolResultState = "streaming" | "complete" | "error";
514```