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 — the framework-agnostic headless client for managing chat state and streaming transports."
6keywords:
7 - tanstack ai
8 - "@tanstack/ai-client"
9 - headless client
10 - ChatClient
11 - chat state
12 - connection adapters
13 - api reference
14---
15
16Framework-agnostic headless client for managing chat state and streaming.
17
18For typed headless chat UI types and selectors, import `@tanstack/ai-client/ui`. See [Custom Chat UI Adapters](../ui/custom-adapters).
19
20## Installation
21
22<!-- ::start:tabs variant="package-manager" mode="install" -->
23
24react: @tanstack/ai-client
25vue: @tanstack/ai-client
26solid: @tanstack/ai-client
27svelte: @tanstack/ai-client
28preact: @tanstack/ai-client
29angular: @tanstack/ai-client
30vanilla: @tanstack/ai-client
31octane: @tanstack/ai-client
32
33<!-- ::end:tabs -->
34
35## `registerWebMCPTools(tools, options)`
36
37Expose executable client tools through the browser WebMCP API. Abort the required signal to remove all tools from this registration.
38
39For a complete setup and behavior guide, see [WebMCP Tools](../tools/webmcp).
40
41```typescript
42import {
43 registerWebMCPTools,
44 type RegisterWebMCPToolsOptions,
45} from "@tanstack/ai-client";
46import { searchProducts } from "./tools";
47
48const controller = new AbortController();
49const tools = [searchProducts];
50const options: RegisterWebMCPToolsOptions<typeof tools> = {
51 signal: controller.signal,
52 toolOptions: {
53 searchProducts: {
54 title: "Search products",
55 annotations: { readOnlyHint: true },
56 },
57 },
58};
59
60await registerWebMCPTools(tools, options);
61
62// Remove these tools when their owner is no longer active.
63controller.abort();
64```
65
66The function returns `Promise<void>`. It resolves without registration during server rendering, in an insecure context, or when WebMCP is unavailable.
67
68It validates Standard Schema inputs and outputs. A tool with `needsApproval: true` causes registration to fail.
69
70### Public option types
71
72- `RegisterWebMCPToolsOptions<TTools, TContext>` - Requires `signal`. It also contains `toolOptions` and the client tool runtime `context`.
73- `WebMCPToolOptionsByName<TTools>` - A partial options map keyed by the inferred tool names.
74- `WebMCPToolOptions` - Contains the optional `title` and `annotations` fields for one tool.
75- `WebMCPToolAnnotations` - Contains the optional `readOnlyHint` and `untrustedContentHint` fields.
76
77`context` is required when a tool declares a required runtime context. If registration fails, the function removes tools that it registered during the call.
78
79## `ChatClient`
80
81The main client class for managing chat state.
82
83```typescript
84import {
85 ChatClient,
86 fetchServerSentEvents,
87 type UIMessage,
88} from "@tanstack/ai-client";
89import { myClientTool } from "./tools";
90
91const client = new ChatClient({
92 connection: fetchServerSentEvents("/api/chat"),
93 initialMessages: [],
94 tools: [myClientTool],
95 onMessagesChange: (messages: UIMessage[]) => {
96 console.log("Messages updated:", messages);
97 },
98});
99
100// A new client is IDLE. Attach it when your view appears, detach when it goes.
101client.attach();
102```
103
104### Lifecycle: `attach()` and `detach()`
105
106One page can hold many chats. A browser allows only about six connections to one
107origin, and a chat that is tailing a run holds one for as long as that run lasts. If
108every chat held a connection, a handful of open views would use every slot and every
109other request would queue behind them, including the request that loads your messages.
110
111So the connection follows the view. A new client holds none, `attach()` starts it, and
112`detach()` stops it.
113
114If you use a framework package (`@tanstack/ai-react`, `-vue`, `-solid`, `-svelte`,
115`-preact`, `-angular`), the hook already does this: it attaches when its view mounts
116and detaches when it unmounts. Call these yourself only when you use `ChatClient`
117directly.
118
119```typescript
120import { ChatClient, fetchServerSentEvents } from "@tanstack/ai-client";
121
122const client = new ChatClient({
123 connection: fetchServerSentEvents("/api/chat"),
124 threadId: "thread-1",
125 persistence: true,
126});
127
128client.attach(); // start: rejoin a run in progress, and load the thread
129client.detach(); // stop: drop the connection, keep messages and the run pointer
130```
131
132What each one guarantees:
133
134- `attach()` is safe to call more than once. Attaching an attached client does nothing.
135- `detach()` keeps the transcript, the resume pointer and the run id. The run keeps
136 going on the server while nobody watches, so re-attaching repaints at once and picks
137 it back up from the durable log.
138- `detach()` is neither `stop()` (which ends the run) nor `dispose()` (which ends the
139 client). It says only that no view is watching right now.
140- A chat with no persistence has no resume pointer and no stored thread, so `attach()`
141 issues no request at all.
142
143#### Migrating from constructor tailing
144
145Earlier versions started tailing inside the constructor. If you build a `ChatClient`
146yourself, add `client.attach()` where your view appears and `client.detach()` where it
147goes away. Users of the framework hooks need no change.
148
149### Constructor Options
150
151- `connection` - Connection adapter for streaming
152- `initialMessages?` - Initial messages array
153- `threadId?` - The only identity for this chat. Required when persistence is on. If omitted, minted after mount.
154- `forwardedProps?` - Arbitrary client-controlled JSON forwarded to the server in the AG-UI `RunAgentInput.forwardedProps` field
155- `body?` - **Deprecated.** Use `forwardedProps` instead. Still works — values are merged into `forwardedProps` on the wire and mirrored under the legacy `data` field for backward compatibility
156- `byok?` - Optional BYOK keyring from [`defineByok`](#definebyok). On each send the client prepares the resolved provider and stamps `x-byok-*` request headers. Keys never go in the body
157- `byokProvider?` - Optional function that returns the provider slug for this chat. If it returns a slug, only that key is prepared and sent. Otherwise the merged `provider` from `forwardedProps`, `body`, and per-call `sendMessage` `body` is used. Later sources win. If no slug resolves, the send throws instead of attaching every stored key
158- `context?` - Typed client-local runtime context passed to client tool implementations. This value is not serialized to the server
159- `tools?` - Registered `.client()` tool implementations. The client automatically executes matching tools when the model calls them
160- `onResponse?` - Callback when response is received
161- `onChunk?` - Callback when stream chunk is received
162- `onFinish?` - Callback when response finishes
163- `onError?` - Callback when error occurs
164- `onInterruptStateChange?` - Callback when interrupt state changes; context source is `hydrate` for restored state and `live` for streamed or client-initiated updates
165- `onMessagesChange?` - Callback when messages change
166- `onLoadingChange?` - Callback when loading state changes
167- `onErrorChange?` - Callback when error state changes
168- `streamProcessor?` - Stream processing configuration
169
170### Methods
171
172#### `sendMessage(content: string | MultimodalContent, body?, sendOptions?)`
173
174Sends a user message and starts the run.
175
176`MultimodalContent` is `{ content, id?, metadata? }`. The string form has no metadata. Pass the object form to stamp `metadata` on the user `UIMessage`. TanStack writes the `tanstack` key. Your keys stay at the top of the bag.
177
178The second argument is extra JSON merged into this request's `forwardedProps`. The third argument is `SendMessageOptions`. `{ whenBusy }` overrides the queue policy for this send. `{ body }` is extra JSON too.
179
180Chat-level `body`, the positional argument, and `sendOptions.body` shallow-merge. `sendOptions.body` wins on key collisions.
181
182Framework hooks expose `sendMessage(content, sendOptions)` with no positional body. Pass `{ body }` there. It merges with the hook's `body` the same way.
183
184```typescript
185import { client } from "./client";
186
187await client.sendMessage("Hello!");
188
189await client.sendMessage({
190 content: "Show me failed logins",
191 metadata: { author: { id: "user-42", name: "Dana" } },
192});
193
194await client.sendMessage("Summarize the attached files", undefined, {
195 body: { attachmentIds: ["att_1", "att_2"] },
196 whenBusy: "interrupt",
197});
198```
199
200Your server reads the merged JSON from `chatParamsFromRequest`:
201
202```typescript
203import {
204 chat,
205 chatParamsFromRequest,
206 toServerSentEventsResponse,
207} from "@tanstack/ai";
208import { openaiText } from "@tanstack/ai-openai";
209
210export async function POST(request: Request) {
211 const { messages, forwardedProps } = await chatParamsFromRequest(request);
212 const stream = chat({
213 adapter: openaiText("gpt-5.5"),
214 messages,
215 });
216 if (
217 forwardedProps &&
218 typeof forwardedProps === "object" &&
219 "attachmentIds" in forwardedProps
220 ) {
221 const { attachmentIds } = forwardedProps;
222 if (Array.isArray(attachmentIds) && attachmentIds.length > 0) {
223 // Look up the uploads. Do not add them to `messages`.
224 }
225 }
226 return toServerSentEventsResponse(stream);
227}
228```
229
230#### `append(message: ModelMessage | UIMessage)`
231
232Appends a message to the conversation. If you pass a `UIMessage`, `append` copies `uiMessage.metadata` onto the stored message.
233
234`append()` resolves after the full HTTP response is processed when this call starts the stream. If a stream is already in progress, this call queues the send and the returned promise can resolve before that queued response is processed. A `RUN_FINISHED` with `finishReason: "tool_calls"` does not end the wait when the agent loop continues in that response.
235
236```typescript
237import { client } from "./client";
238import type { UIMessage } from "@tanstack/ai-client";
239
240await client.append({
241 role: "user",
242 content: "Additional context",
243});
244
245const stamped: UIMessage = {
246 id: "user-1",
247 role: "user",
248 parts: [{ type: "text", content: "Show me failed logins" }],
249 metadata: { author: { id: "user-42", name: "Dana" } },
250};
251await client.append(stamped);
252```
253
254#### `reload()`
255
256Reloads the last assistant message.
257
258```typescript
259import { client } from "./client";
260
261await client.reload();
262```
263
264#### `attach()`
265
266Start tailing. Rejoins a run that is still in progress and, in server-authoritative
267mode, loads the stored thread. Idempotent. See
268[Lifecycle](#lifecycle-attach-and-detach).
269
270#### `detach()`
271
272Stop tailing and drop the connection. Keeps messages, the run pointer and the run
273id, so a later `attach()` continues where it left off. See
274[Lifecycle](#lifecycle-attach-and-detach).
275
276#### `stop()`
277
278Stops the current response generation. It aborts the in-flight request.
279Pending client-tool results for that turn are ignored. A later
280`addToolResult()` call for that turn is ignored. It does not start a resume.
281
282```typescript
283import { client } from "./client";
284
285client.stop();
286```
287
288#### `clear()`
289
290Clears all messages.
291
292```typescript
293import { client } from "./client";
294
295client.clear();
296```
297
298#### `setMessagesManually(messages: UIMessage[])`
299
300Manually sets the messages array.
301
302```typescript
303import { client } from "./client";
304import type { UIMessage } from "@tanstack/ai-client";
305
306const newMessages: UIMessage[] = [];
307client.setMessagesManually([...newMessages]);
308```
309
310#### `addToolResult(result)`
311
312Adds the result of a client-side tool execution. After `stop()`, a result for
313the stopped turn is ignored. A new user message starts a new turn. Then
314`addToolResult()` applies to that turn.
315
316```typescript
317import { client } from "./client";
318
319await client.addToolResult({
320 toolCallId: "call_123",
321 tool: "toolName",
322 output: { result: "..." },
323 state: "output-available",
324});
325```
326
327#### `addToolApprovalResponse(response)`
328
329Responds to a tool approval request.
330
331```typescript
332import { client } from "./client";
333
334await client.addToolApprovalResponse({
335 id: "approval_123",
336 approved: true,
337});
338```
339
340### Properties
341
342- `messages: UIMessage[]` - Current messages
343- `isLoading: boolean` - Whether a response is being generated
344- `error: Error | undefined` - Current error, if any
345
346## Connection Adapters
347
348For a complete transport walkthrough, see
349[Connection Adapters](../chat/connection-adapters). For React Native and Expo,
350see [Quick Start: React Native](../getting-started/quick-start-react-native).
351
352### `fetchServerSentEvents(url, options?)`
353
354Creates an SSE connection adapter.
355
356```typescript
357import { fetchServerSentEvents } from "@tanstack/ai-client";
358
359const adapter = fetchServerSentEvents("/api/chat", {
360 headers: {
361 Authorization: "Bearer token",
362 },
363});
364```
365
366### `fetchHttpStream(url, options?)`
367
368Creates a newline-delimited JSON HTTP stream connection adapter. Pair it with
369`toHttpResponse()` on the server.
370
371```typescript
372import { fetchHttpStream } from "@tanstack/ai-client";
373
374const adapter = fetchHttpStream("/api/chat");
375```
376
377`fetchHttpStream()` requires a runtime with streaming `fetch`,
378`Response.body.getReader()`, and `TextDecoder`. If the runtime cannot expose an
379incremental response body, it throws `UnsupportedResponseStreamError`; use the
380XHR adapters in React Native or Expo.
381
382### `xhrHttpStream(url, options?)`
383
384Creates an `XMLHttpRequest`-backed newline-delimited JSON stream adapter. This
385is the recommended default for React Native and Expo chat screens. Pair it with
386`toHttpResponse()` on the server.
387
388```typescript
389import { xhrHttpStream } from "@tanstack/ai-client";
390
391const adapter = xhrHttpStream("http://192.168.1.10:8787/chat/http", {
392 headers: { Authorization: "Bearer token" },
393 withCredentials: true,
394});
395```
396
397### `xhrServerSentEvents(url, options?)`
398
399Creates an `XMLHttpRequest`-backed SSE adapter for runtimes where XHR progress
400events are more reliable than streaming `fetch`. Pair it with
401`toServerSentEventsResponse()` on the server.
402
403```typescript
404import { xhrServerSentEvents } from "@tanstack/ai-client";
405
406const adapter = xhrServerSentEvents("http://192.168.1.10:8787/chat/sse");
407```
408
409### Adapter options
410
411Fetch adapters accept:
412
413- `headers?: Record<string, string> | Headers`
414- `credentials?: RequestCredentials`
415- `signal?: AbortSignal`
416- `body?: Record<string, any>`
417- `fetchClient?: typeof globalThis.fetch`
418
419XHR adapters accept:
420
421- `headers?: Record<string, string> | Headers`
422- `withCredentials?: boolean`
423- `signal?: AbortSignal`
424- `body?: Record<string, any>`
425- `xhrFactory?: () => XMLHttpRequest`
426
427`body` is merged into the AG-UI `forwardedProps` payload. Values from
428`forwardedProps` on the client and per-message `sendMessage` `body` (positional
429or `sendOptions.body`) override static adapter `body` values.
430
431### Stream errors
432
433- `UnsupportedResponseStreamError` - thrown by fetch-based adapters when
434 `Response.body`, `Response.body.getReader()`, or `TextDecoder` is missing.
435- `StreamTruncatedError` - thrown when an SSE or NDJSON stream ends with
436 unterminated trailing data, usually because the server, proxy, or network cut
437 the connection mid-line.
438
439### `stream(connectFn)`
440
441Creates a custom connection adapter.
442
443```typescript ignore
444import { stream } from "@tanstack/ai-client";
445
446const adapter = stream(async (messages, data, signal) => {
447 // `data` here carries the merged forwardedProps. The fetch-based
448 // adapters serialize it as the AG-UI `RunAgentInput.forwardedProps`
449 // field on the wire (with a backward-compat `data` mirror).
450 const response = await fetch("/api/chat", {
451 method: "POST",
452 body: JSON.stringify({ messages, forwardedProps: data }),
453 signal,
454 });
455 return processStream(response);
456});
457```
458
459## Helper Functions
460
461### `clientTools(...tools)`
462
463**Optional.** A plain array — `tools: [tool1, tool2]` — already narrows tool names, inputs and outputs without any wrapper or `as const`. `clientTools()` is an identity helper that performs the same capture explicitly; reach for it only when you want to build a shared, reusable tools tuple outside the hook/options call.
464
465```typescript
466import {
467 clientTools,
468 createChatClientOptions,
469 fetchServerSentEvents,
470 type UIMessage,
471} from "@tanstack/ai-client";
472import { toolDefinition } from "@tanstack/ai";
473import { z } from "zod";
474
475const messages: UIMessage[] = [];
476
477const myTool1 = toolDefinition({
478 name: "myTool1",
479 description: "First tool",
480 inputSchema: z.object({ query: z.string() }),
481 outputSchema: z.object({ result: z.string() }),
482});
483
484const myTool2 = toolDefinition({
485 name: "myTool2",
486 description: "Second tool",
487 inputSchema: z.object({ query: z.string() }),
488 outputSchema: z.object({ result: z.string() }),
489});
490
491// Create client implementations
492const tool1Client = myTool1.client((input) => {
493 // Implementation
494 return { result: input.query };
495});
496
497const tool2Client = myTool2.client((input) => {
498 // Implementation
499 return { result: input.query };
500});
501
502// The explicit-capture form (equivalent to `[tool1Client, tool2Client]`).
503const tools = clientTools(tool1Client, tool2Client);
504
505// Now when you use these tools in chat options:
506const chatOptions = createChatClientOptions({
507 connection: fetchServerSentEvents("/api/chat"),
508 tools, // Fully typed with literal tool names
509});
510
511// In your component:
512messages.forEach((message) => {
513 message.parts.forEach((part) => {
514 if (part.type === "tool-call" && part.name === "myTool1") {
515 // ✅ TypeScript knows part.name is literally "myTool1"
516 // ✅ part.input is typed from myTool1's input schema
517 // ✅ part.output is typed from myTool1's output schema
518 }
519 });
520});
521```
522
523### `createChatClientOptions(options)`
524
525Helper function to create typed chat client options with proper type inference.
526
527```typescript
528import {
529 createChatClientOptions,
530 fetchServerSentEvents,
531 type InferChatMessages,
532} from "@tanstack/ai-client";
533import { tool1, tool2 } from "./tools";
534
535const tools = [tool1, tool2];
536
537const chatOptions = createChatClientOptions({
538 connection: fetchServerSentEvents("/api/chat"),
539 tools,
540});
541
542// Use InferChatMessages to extract message types
543type ChatMessages = InferChatMessages<typeof chatOptions>;
544```
545
546`createChatClientOptions` also preserves typed client runtime context:
547
548```typescript
549import {
550 createChatClientOptions,
551 fetchServerSentEvents,
552} from "@tanstack/ai-client";
553import { toolDefinition } from "@tanstack/ai";
554import { z } from "zod";
555
556type ClientContext = {
557 activeProjectId: string;
558};
559
560const projectTool = toolDefinition({
561 name: "projectAction",
562 description: "Run a project action",
563 inputSchema: z.object({ action: z.string() }),
564 outputSchema: z.object({ ok: z.boolean() }),
565});
566
567const tool = projectTool.client<ClientContext>((input, ctx: { context: ClientContext }) => {
568 console.log(ctx.context.activeProjectId, input.action);
569 return { ok: true };
570});
571
572const chatOptions = createChatClientOptions({
573 connection: fetchServerSentEvents("/api/chat"),
574 tools: [tool],
575 context: {
576 activeProjectId: "project_123",
577 },
578});
579```
580
581Client runtime context is local to the client instance. Use `forwardedProps` for explicit client-to-server handoff of serializable values, then validate and map those values into server `chat({ context })`.
582
583## `defineByok`
584
585Factory for a headless BYOK keyring. Import it from `@tanstack/ai-client/byok`. Pass the instance into `ChatClient`, `useChat`, or a generation hook. See [Bring Your Own Key](../advanced/byok) for a full client and relay walkthrough.
586
587```typescript
588import { defineByok, defaultByokStorage } from "@tanstack/ai-client/byok";
589
590export const byok = defineByok({
591 storage: defaultByokStorage(),
592});
593```
594
595### Factory options
596
597- `storage?` - A `KeyringStorage` implementation. Default is `memoryStorage()` (session only, not saved)
598- `providers?` - Descriptors whose `with` companions the store expands. With `[cloudflareByok, cloudflareAccountByok]`, a send for `cloudflare` carries the token and the account id headers, and `prepare` prompts for each missing one
599
600### Methods
601
602- `update(provider, key)` - Persist a key for a provider slug (`[a-z][a-z0-9-]{0,63}`), then update the snapshot. Throws if the id is not a slug, the key is empty, or storage fails
603- `update(key)` - Persist a key for the current `prompt` provider. Throws if `prompt` is null
604- `clear(provider?)` - Persist the removal, then drop one key, or all keys when you omit `provider`
605- `unlock()` - Decrypt unlockable storage (passkey). No-op for memory storage
606- `headers(provider)` - Return `x-byok-*` headers for that slug and its companions. Chat and generation clients throw if no slug resolves — they do not send every stored key
607- `prepare(provider?)` - Wait for hydration, then unlock if needed. If `provider` is set and the key for it or a companion is empty with no server coverage, throw `ByokBlockedError` and set `prompt` for that slug
608- `ready()` - Resolve when constructor hydration (peek/load) finishes
609- `setServerCoverage(flags)` - `true` means do not block a send when the browser has no key (the relay can fill from env). `false` restores the default: block. A record merges per-slug flags
610- `request(provider, reason)` - Set `prompt` to `{ provider, reason }` (`missing` | `locked` | `invalid`)
611- `getSnapshot()` - Return the current [`ByokSnapshot`](#snapshot)
612- `subscribe(listener)` - Call `listener` on each change. Returns an unsubscribe function
613- `keys()` - Return a copy of the raw keyring. Do not render this in the UI
614
615### Snapshot
616
617`getSnapshot()` (and framework readers such as `useByok`) return:
618
619```typescript ignore
620type ByokSnapshot = {
621 status: Partial<Record<string, KeyStatus>>;
622 locked: boolean;
623 prompt: { provider: string; reason: "missing" | "locked" | "invalid" } | null;
624 storageError: string | null;
625};
626
627type KeyStatus =
628 | { state: "empty" }
629 | { state: "set"; masked: string }
630 | { state: "locked"; masked: string }
631 | { state: "validating"; masked: string }
632 | { state: "valid"; masked: string }
633 | { state: "invalid"; masked: string }
634 | { state: "error"; masked: string; message: string };
635```
636
637`status` is sparse: only slugs that have a key, a lock, or a validation result appear. A missing entry means no key. `masked` is the last four characters of the key (`maskKey`). Read it with `"masked" in status` — `{ state: "empty" }` has no `masked`. `storageError` is set when peek/load fails. The snapshot never includes the raw key.
638
639### Storage
640
641- `defaultByokStorage(options?)` - Passkey-encrypted IndexedDB when WebAuthn is available in a secure context. Otherwise `memoryStorage()` with a warning. WebAuthn support is not the same as PRF — first save still throws if the authenticator lacks PRF
642- `memoryStorage()` - In-memory on the `ByokClient` instance. This backend does not persist. Keys are gone when the client is dropped or the page reloads
643- `passkeyStorage(options?)` - Encrypt the keyring with a WebAuthn passkey. First save throws if the authenticator does not support PRF
644- `KeyringStorage` - `{ id, label, persistent, unlockable?, peek?, load, save, clear }`
645
646This library does not ship a dialog. Call `byok.update(provider, value)` from your own UI.
647
648## Types
649
650### `UIMessage`
651
652```typescript ignore
653interface UIMessage {
654 id: string;
655 role: "system" | "user" | "assistant";
656 parts: MessagePart[];
657 name?: string;
658 createdAt?: Date;
659 metadata?: Record<string, any>;
660}
661```
662
663`metadata` is an optional AG-UI bag (`Record<string, any>`). TanStack writes the `tanstack` key. Your keys stay at the top.
664
665### `MessagePart`
666
667```typescript ignore
668type MessagePart = TextPart | ThinkingPart | ToolCallPart | ToolResultPart;
669```
670
671### `TextPart`
672
673```typescript
674interface TextPart {
675 type: "text";
676 content: string;
677}
678```
679
680### `ThinkingPart`
681
682```typescript
683interface ThinkingPart {
684 type: "thinking";
685 content: string;
686}
687```
688
689Thinking parts represent the model's internal reasoning process. They are typically displayed in a collapsible format and automatically collapse when the response text appears. Thinking parts are UI-only and are not sent back to the model in subsequent requests.
690
691**Note:** Thinking parts are only available when using models that support reasoning/thinking (e.g., Anthropic Claude with thinking enabled, OpenAI GPT-5 with reasoning enabled).
692
693### `ToolCallPart`
694
695```typescript ignore
696interface ToolCallPart {
697 type: "tool-call";
698 id: string;
699 name: string;
700 arguments: string; // JSON string (may be incomplete during streaming)
701 input?: any; // Parsed tool input (typed from tool's inputSchema)
702 state: ToolCallState;
703 approval?: ApprovalRequest; // only on tools declared `needsApproval: true`
704 output?: any; // Tool execution output (typed from tool's outputSchema)
705}
706```
707
708When you pass a typed `tools` array (a plain array works — `clientTools()` is optional), the `input` and `output` fields are automatically typed based on your tool's Zod schemas, and `name` becomes a discriminated union enabling type narrowing. The `approval` field is present **only** on parts for tools declared with `needsApproval: true` — narrow by `part.name` (or guard with `'approval' in part`) before accessing it.
709
710### `ToolResultPart`
711
712```typescript ignore
713interface ToolResultPart {
714 type: "tool-result";
715 id?: string;
716 name?: string;
717 toolCallId: string;
718 content: string | ContentPart[];
719 state: ToolResultState;
720 error?: string;
721 metadata?: Record<string, unknown>;
722 createdAt?: Date;
723}
724```
725
726### `ToolCallState`
727
728```typescript ignore
729type ToolCallState =
730 | "awaiting-input"
731 | "input-streaming"
732 | "input-complete"
733 | "approval-requested"
734 | "approval-responded"
735 | "complete";
736```
737
738### `ToolResultState`
739
740```typescript ignore
741type ToolResultState =
742 | "streaming"
743 | "complete"
744 | "error";
745```
746
747## Stream Processing
748
749Configure stream processing with chunk strategies:
750
751```typescript
752import {
753 ChatClient,
754 ImmediateStrategy,
755 fetchServerSentEvents,
756} from "@tanstack/ai-client";
757
758const client = new ChatClient({
759 connection: fetchServerSentEvents("/api/chat"),
760 streamProcessor: {
761 chunkStrategy: new ImmediateStrategy(), // Emit every chunk
762 },
763});
764```
765
766## Next Steps
767
768- [Getting Started](../getting-started/quick-start) - Learn the basics
769- [Bring Your Own Key](../advanced/byok) - Store keys in the browser and send `x-byok-*` headers
770- [Connection Adapters](../chat/connection-adapters) - Learn about adapters
771- [@tanstack/ai-react API](./ai-react) - React hooks wrapper