Open History to see the last commit
1---
2title: "@tanstack/ai-preact"
3slug: /api/ai-preact
4order: 5
5description: "API reference for @tanstack/ai-preact: the useChat hook and Preact bindings for the headless TanStack AI client."
6keywords:
7 - tanstack ai
8 - "@tanstack/ai-preact"
9 - preact
10 - useChat
11 - preact hooks
12 - api reference
13---
14
15Preact hooks for TanStack AI. To build your first chat, start with the [Quick Start](../getting-started/quick-start). For a typed chat layout, see [Preact Chat UI](../ui/preact).
16
17## Installation
18
19<!-- ::start:tabs variant="package-manager" mode="install" -->
20
21preact: @tanstack/ai-preact
22
23<!-- ::end:tabs -->
24
25## `useChat(options)`
26
27Holds the messages and the run state of one chat, and talks to your server route.
28
29```tsx
30import { useState } from "preact/hooks";
31import { useChat, fetchServerSentEvents } from "@tanstack/ai-preact";
32
33export function Chat() {
34 const [input, setInput] = useState("");
35 const { messages, sendMessage, isLoading } = useChat({
36 connection: fetchServerSentEvents("/api/chat"),
37 threadId: "support-chat",
38 });
39
40 return (
41 <div>
42 {messages.map((message) => (
43 <div key={message.id}>
44 <strong>{message.role}:</strong>
45 {message.parts.map((part, idx) =>
46 part.type === "text" ? <span key={idx}>{part.content}</span> : null,
47 )}
48 </div>
49 ))}
50 <form
51 onSubmit={(e) => {
52 e.preventDefault();
53 if (input.trim() && !isLoading) {
54 sendMessage(input);
55 setInput("");
56 }
57 }}
58 >
59 <input
60 value={input}
61 onInput={(e) => setInput(e.currentTarget.value)}
62 />
63 <button type="submit" disabled={isLoading}>
64 Send
65 </button>
66 </form>
67 </div>
68 );
69}
70```
71
72### Options
73
74You must pass `threadId`. You must also pass `connection` or `fetcher`, not both.
75
76| Option | What it does |
77| --- | --- |
78| `connection` | Connection adapter, for example `fetchServerSentEvents("/api/chat")`. See [Transports](../transports/overview). |
79| `fetcher` | A function that returns a `Response` or a stream. Use it with server functions. |
80| `tools` | Client tools from `.client()`. They run when the model calls them. See [Client Tools](../tools/client-tools). |
81| `threadId` | Required. The id of this chat. Use a stable id for each conversation, for example the id from your route. |
82| `initialMessages` | The messages to show first. |
83| `forwardedProps` | JSON sent to the server in the AG-UI `forwardedProps` field, for example `{ model: "gpt-6.1-sol" }`. |
84| `persistence` | `true` to load the thread from the server, or a storage adapter. See [Chat Persistence](../persistence/chat-persistence). |
85| `outputSchema` | A Standard Schema. In Preact it only labels the chat in devtools. Read structured output from the `structured-output` part in `messages`. |
86| `context` | Client-only runtime context for client tools. It is not sent to the server. |
87| `live` | Subscribe on mount and unsubscribe on unmount. |
88| `queue` | What `sendMessage` does while a run is busy. Default: queue the message. See [Queueing](../chat/queueing). |
89| `interrupts` | Definitions from `defineInterrupt()`. See [Interrupts](../interrupts/overview). |
90| `byok`, `byokProvider` | A keyring from `defineByok()`. See [Bring Your Own Key](../advanced/byok). |
91| `devtools` | Display options for TanStack AI Devtools. |
92
93The hook also takes the `ChatClient` callbacks (`onResponse`, `onChunk`, `onFinish`, `onError`, `onInterruptStateChange`, `onCustomEvent`) and the other client options. See [`ChatClient` options](./ai-client#constructor-options).
94
95When `forwardedProps`, `tools`, `context`, or `queue` change, the hook updates the current chat.
96
97### Returns
98
99State values are plain Preact values. The hook renders again when they change.
100
101| Field | What it is |
102| --- | --- |
103| `messages` | The `UIMessage` array of the chat. |
104| `sendMessage(content, options?)` | Sends a user message. `content` is a string or `{ content, id?, metadata? }`. `options` takes `whenBusy` and `body`. |
105| `isLoading` | `true` while a response streams. |
106| `error` | The last error, or `undefined`. |
107| `status` | `"ready"`, `"submitted"`, `"streaming"`, or `"error"`. |
108| `stop()` | Stops the current response. |
109| `reload()` | Runs the last user message again. |
110| `append(message)` | Adds a `UIMessage` or `ModelMessage` and starts a run. |
111| `addToolResult(result)` | Gives the result of a client tool by hand: `{ toolCallId, tool, output, state?, errorText? }`. |
112| `setMessages(messages)`, `clear()` | Replace or clear the messages. |
113| `queue`, `cancelQueued(id)` | Messages that wait while a run is busy. See [Queueing](../chat/queueing). |
114| `runId` | The id of the run in flight, or `null`. |
115| `interrupts` | Pending interrupts. Each item has `resolveInterrupt(...)`. See [Interrupts](../interrupts/overview). |
116| `resolveInterrupts`, `cancelInterrupts`, `retryInterrupts`, `resumeInterruptsUnsafe` | Act on all pending interrupts at once. |
117| `interruptErrors`, `resuming` | Errors from the last resume, and `true` while a resume runs. |
118| `isHydrating` | `true` while the chat loads from persistence. |
119| `hasOlderMessages`, `loadOlderMessages()` | Page in older messages. See [Chat Persistence](../persistence/chat-persistence). |
120| `isSubscribed`, `connectionStatus`, `sessionGenerating` | State of the live subscription. |
121
122### Example: tool approval
123
124A tool with `needsApproval: true` pauses the run. The pending call shows up in `interrupts`.
125
126```tsx
127import { toolDefinition } from "@tanstack/ai";
128import { useChat, fetchServerSentEvents } from "@tanstack/ai-preact";
129import { z } from "zod";
130
131const deleteFileTool = toolDefinition({
132 name: "delete_file",
133 description: "Delete a file",
134 needsApproval: true,
135 inputSchema: z.object({ path: z.string() }),
136});
137
138export function ChatWithApproval() {
139 const { interrupts } = useChat({
140 connection: fetchServerSentEvents("/api/chat"),
141 threadId: "support-chat",
142 tools: [deleteFileTool],
143 });
144
145 return (
146 <div>
147 {interrupts.map((interrupt) =>
148 interrupt.kind === "tool-approval" ? (
149 <div key={interrupt.id}>
150 <p>Approve: {interrupt.toolName}</p>
151 <button onClick={() => interrupt.resolveInterrupt(true)}>
152 Approve
153 </button>
154 <button onClick={() => interrupt.resolveInterrupt(false)}>
155 Deny
156 </button>
157 </div>
158 ) : null,
159 )}
160 </div>
161 );
162}
163```
164
165See [Tool Approval](../interrupts/tool-approval) for the server side.
166
167## `createChatHook(options)`
168
169Binds chat options once at module scope and returns a `useChat` hook that uses them.
170
171```tsx
172import { createChatHook, fetchServerSentEvents } from "@tanstack/ai-preact";
173
174const { useChat: useSupportChat } = createChatHook({
175 connection: fetchServerSentEvents("/api/chat"),
176});
177
178export function SupportScreen() {
179 const chat = useSupportChat({ threadId: "support-1" });
180 return <p>{chat.messages.length} messages</p>;
181}
182```
183
184The bound hook takes these per-call overrides: `threadId`, `initialMessages`, `live`, and `forwardedProps`. Keep `tools` and `interrupts` on the factory options.
185
186`@tanstack/ai-preact/ui` has its own `createChatHook` that also returns typed UI components. See [Preact Chat UI](../ui/preact).
187
188## Generation hooks
189
190This package does not export generation hooks. Use `GenerationClient` or `VideoGenerationClient`, which this package re-exports. See [`GenerationClient`](./ai-client#generationclient).
191
192## Realtime chat
193
194This package does not export a realtime hook. Use `RealtimeClient`, which this package re-exports. See [Realtime Chat](../media/realtime-chat).
195
196## Audio recorder
197
198This package does not export a recorder hook. Use `AudioRecorder`, which this package re-exports. See [Audio Recording](../media/audio-recording).
199
200## `useByok(client)`
201
202Subscribes to a BYOK keyring and returns its snapshot. See [Bring Your Own Key](../advanced/byok).
203
204```tsx
205import { useByok } from "@tanstack/ai-preact";
206import { byok } from "./byok";
207
208export function KeyStatus() {
209 const snapshot = useByok(byok);
210 const openai = snapshot.status.openai;
211 return <p>{openai && "masked" in openai ? openai.masked : "No key"}</p>;
212}
213```
214
215The snapshot has `status`, `locked`, `prompt`, and `storageError`. Save a key from your own UI with `byok.update(provider, value)`.
216
217## `useMcpAppBridge(options)`
218
219Returns a stable MCP App bridge for one thread. It always calls the latest `chat.sendMessage` and `onLink`. Options: `threadId`, `callEndpoint`, `chat`, `fetchImpl`, `onLink`. See [MCP Apps](../mcp/apps).
220
221The `MCPAppResource` component, which renders a `ui-resource` part, is on the `@tanstack/ai-preact/mcp-apps` subpath.
222
223## `useRegisterWebMCPTools(tools, options?)`
224
225Exposes client tools to the browser WebMCP API while the component is mounted. See [WebMCP Tools](../tools/webmcp).
226
227```tsx
228import { useRegisterWebMCPTools } from "@tanstack/ai-preact";
229import { searchProducts } from "./tools";
230
231const tools = [searchProducts];
232
233export function ProductsPage() {
234 useRegisterWebMCPTools(tools, {
235 onError: (error) => console.error(error),
236 });
237 return null;
238}
239```
240
241Options: `toolOptions`, `context`, and `onError`. `context` is required when a tool declares a required runtime context. The hook registers the tools again when `tools` or `options` change, so keep them stable.
242
243## `usePageWebMCPTools(options?)`
244
245Reads the WebMCP tools that the page registered, as client tools. The array starts empty and updates when the page adds or removes a tool. Pass it to `useChat` as `tools`. See [Page WebMCP Tools in Chat](../tools/webmcp-page-tools).
246
247```tsx
248import { usePageWebMCPTools } from "@tanstack/ai-preact";
249
250export function useSameOriginPageTools() {
251 return usePageWebMCPTools({
252 filter: (tool) => tool.origin === location.origin,
253 });
254}
255```
256
257Options: `filter` (return `false` to skip a tool) and `onError`.
258
259## Re-exports from `@tanstack/ai-client`
260
261You can import these from `@tanstack/ai-preact` directly. See [`@tanstack/ai-client`](./ai-client) for details.
262
263| Group | Exports |
264| --- | --- |
265| Connection adapters | `fetchServerSentEvents`, `fetchHttpStream`, `fetchJson`, `xhrServerSentEvents`, `xhrHttpStream`, `webSocket`, `stream`, `rpcStream` |
266| Typed options | `createChatClientOptions`, `clientTools` |
267| Persistence | `localStoragePersistence`, `sessionStoragePersistence`, `indexedDBPersistence` |
268| Clients | `ChatClient`, `GenerationClient`, `VideoGenerationClient`, `RealtimeClient`, `AudioRecorder`, `InterruptManager` |
269| WebMCP and MCP Apps | `registerWebMCPTools`, `getWebMCPTools`, `subscribeWebMCPTools`, `createMcpAppBridge` |
270| Errors | `UnsupportedResponseStreamError`, `StreamTruncatedError`, `DurableStreamIncompleteError`, `StreamReconnectLimitError`, `StorageUnavailableError` |
271| Stream helpers | `StreamProcessor`, chunk strategies, `parsePartialJSON`, message converters |
272
273BYOK helpers (`defineByok`, `defaultByokStorage`, and more) are on the `@tanstack/ai-preact/byok` subpath.
274
275## Types
276
277| Type | What it is |
278| --- | --- |
279| `UseChatOptions`, `UseChatReturn` | The options and return value of `useChat`. |
280| `UIMessage<TTools>` | A chat message with typed parts. |
281| `InferChatMessages<T>` | The message type for a `createChatClientOptions` result. |
282| `SendMessageOptions`, `WhenBusy`, `QueueOption`, `QueuedMessage` | Send and queue types. |
283| `UseRegisterWebMCPToolsOptions`, `UsePageWebMCPToolsOptions`, `UseMcpAppBridgeOptions` | Options for the WebMCP and bridge hooks. |
284
285Pass a plain tools array to `useChat` or `createChatClientOptions`. Tool names, inputs, and outputs stay typed without `as const`. Import `toolDefinition` from `@tanstack/ai`.