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 — Preact hooks including useChat for streaming chat with full type safety in Preact apps."
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, providing convenient Preact bindings for the headless client.
16
17## Installation
18
19<!-- ::start:tabs variant="package-manager" mode="install" -->
20
21preact: @tanstack/ai-preact
22
23<!-- ::end:tabs -->
24
25## `useRegisterWebMCPTools(tools, options?)`
26
27Register executable client tools after the Preact component mounts. Preact removes them on cleanup and replaces them when `tools` or `options` change.
28
29For a complete setup and behavior guide, see [WebMCP Tools](../tools/webmcp).
30
31```tsx
32import {
33 useRegisterWebMCPTools,
34 type UseRegisterWebMCPToolsOptions,
35} from "@tanstack/ai-preact";
36import { searchProducts } from "./tools";
37
38const tools = [searchProducts];
39const options: UseRegisterWebMCPToolsOptions<typeof tools> = {
40 onError(error) {
41 console.error(error);
42 },
43};
44
45function ProductsPage() {
46 useRegisterWebMCPTools(tools, options);
47 return null;
48}
49```
50
51`UseRegisterWebMCPToolsOptions<TTools, TContext>` contains `toolOptions`, `context`, and `onError`. The hook owns the registration signal.
52
53The `context` field is required when a tool declares a required runtime context. Keep `tools` and `options` stable when their values do not change.
54
55## `usePageWebMCPTools(options?)`
56
57Read the WebMCP tools on the page as client tools. The array starts empty and updates when the page adds or removes a tool. Pass it to `useChat` as `tools`.
58
59```tsx
60import { usePageWebMCPTools } from "@tanstack/ai-preact";
61
62export function useSameOriginPageTools() {
63 return usePageWebMCPTools({
64 filter: (tool) => tool.origin === location.origin,
65 });
66}
67```
68
69`filter` skips a tool when it returns `false`. `onError` gets a failed WebMCP read. For a complete guide, see [Page WebMCP Tools in Chat](../tools/webmcp-page-tools).
70
71## `useChat(options?)`
72
73Main hook for managing chat state in Preact with full type safety.
74
75```tsx
76import { useChat, fetchServerSentEvents } from "@tanstack/ai-preact";
77import {
78 createChatClientOptions,
79 type InferChatMessages
80} from "@tanstack/ai-client";
81import { toolDefinition } from "@tanstack/ai";
82import { z } from "zod";
83import { useState } from "preact/hooks";
84
85const updateUIDef = toolDefinition({
86 name: "updateUI",
87 description: "Show a notification in the UI",
88 inputSchema: z.object({ message: z.string() }),
89});
90
91function ChatComponent() {
92 const [, setNotification] = useState<string | null>(null);
93 // Create client tool implementations
94 const updateUI = updateUIDef.client((input) => {
95 setNotification(input.message);
96 return { success: true };
97 });
98
99 // Create typed tools array (no 'as const' needed!)
100 const tools = [updateUI];
101
102 const chatOptions = createChatClientOptions({
103 connection: fetchServerSentEvents("/api/chat"),
104 tools,
105 });
106
107 // Fully typed messages!
108 type ChatMessages = InferChatMessages<typeof chatOptions>;
109
110 const { messages, sendMessage, isLoading, error, addToolApprovalResponse } =
111 useChat(chatOptions);
112
113 return <div>{/* Chat UI with typed messages */}</div>;
114}
115```
116
117### Options
118
119Extends `ChatClientOptions` from `@tanstack/ai-client`:
120
121- `connection` - Connection adapter (required)
122- `tools?` - Array of client tool implementations (with `.client()` method)
123- `initialMessages?` - Initial messages array
124- `threadId?` - The only identity for this chat. Required when persistence is on. If omitted, minted after mount.
125- `forwardedProps?` - Arbitrary client-controlled JSON forwarded to the server in the AG-UI `RunAgentInput.forwardedProps` field (e.g., `{ provider: 'openai', model: 'gpt-5.5' }`)
126- `body?` - **Deprecated.** Use `forwardedProps` instead. Still works for backward compatibility; values are merged into `forwardedProps` on the wire
127- `byok?` - Optional BYOK keyring from `defineByok`. On each send the client prepares the resolved provider and stamps `x-byok-*` request headers. Keys never go in the body
128- `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
129- `context?` - Typed client-local runtime context passed to client tool implementations. This value is not serialized to the server
130- `onResponse?` - Callback when response is received
131- `onChunk?` - Callback when stream chunk is received
132- `onFinish?` - Callback when response finishes
133- `onError?` - Callback when error occurs
134- `onInterruptStateChange?` - Callback when interrupt state changes; context source is `hydrate` for restored state and `live` for streamed or client-initiated updates
135- `streamProcessor?` - Stream processing configuration
136
137**Note:** Client tools are now automatically executed - no `onToolCall` callback needed!
138
139### Returns
140
141```typescript
142import type { UIMessage } from "@tanstack/ai-preact";
143import type { ModelMessage } from "@tanstack/ai/client";
144import type {
145 MultimodalContent,
146 SendMessageOptions,
147} from "@tanstack/ai-client";
148
149interface UseChatReturn {
150 messages: UIMessage[];
151 sendMessage: (
152 content: string | MultimodalContent,
153 options?: SendMessageOptions,
154 ) => Promise<void>;
155 append: (message: ModelMessage | UIMessage) => Promise<void>;
156 addToolResult: (result: {
157 toolCallId: string;
158 tool: string;
159 output: any;
160 state?: "output-available" | "output-error";
161 errorText?: string;
162 }) => Promise<void>;
163 addToolApprovalResponse: (response: {
164 id: string;
165 approved: boolean;
166 }) => Promise<void>;
167 reload: () => Promise<void>;
168 stop: () => void;
169 isLoading: boolean;
170 error: Error | undefined;
171 setMessages: (messages: UIMessage[]) => void;
172 clear: () => void;
173}
174```
175
176## `useByok(client)`
177
178Subscribe to a `ByokClient` snapshot in Preact.
179
180```tsx
181import { useByok } from "@tanstack/ai-preact";
182import { byok } from "./byok";
183
184export function KeyStatus() {
185 const snapshot = useByok(byok);
186 const openai = snapshot.status.openai;
187 const last4 = openai && "masked" in openai ? openai.masked : "No key";
188 return <p>{last4}</p>;
189}
190```
191
192`snapshot` has `status`, `locked`, and `prompt`. Call `byok.update(provider, value)` from your own UI to save a key. See [Bring Your Own Key](../advanced/byok).
193
194## Connection Adapters
195
196Re-exported from `@tanstack/ai-client` for convenience:
197
198```typescript
199import {
200 fetchServerSentEvents,
201 fetchHttpStream,
202 stream,
203 type ConnectionAdapter,
204} from "@tanstack/ai-preact";
205```
206
207## Example: Basic Chat
208
209```tsx
210import { useState } from "preact/hooks";
211import { useChat, fetchServerSentEvents } from "@tanstack/ai-preact";
212
213export function Chat() {
214 const [input, setInput] = useState("");
215
216 const { messages, sendMessage, isLoading } = useChat({
217 connection: fetchServerSentEvents("/api/chat"),
218 });
219
220 const handleSubmit = (e: Event) => {
221 e.preventDefault();
222 if (input.trim() && !isLoading) {
223 sendMessage(input);
224 setInput("");
225 }
226 };
227
228 return (
229 <div>
230 <div>
231 {messages.map((message) => (
232 <div key={message.id}>
233 <strong>{message.role}:</strong>
234 {message.parts.map((part, idx) => {
235 if (part.type === "thinking") {
236 return (
237 <div key={idx} class="text-sm text-gray-500 italic">
238 💭 Thinking: {part.content}
239 </div>
240 );
241 }
242 if (part.type === "text") {
243 return <span key={idx}>{part.content}</span>;
244 }
245 return null;
246 })}
247 </div>
248 ))}
249 </div>
250 <form onSubmit={handleSubmit}>
251 <input
252 value={input}
253 onInput={(e) => setInput(e.currentTarget.value)}
254 disabled={isLoading}
255 />
256 <button type="submit" disabled={isLoading}>
257 Send
258 </button>
259 </form>
260 </div>
261 );
262}
263```
264
265## Example: Tool Approval
266
267```tsx
268import { useChat, fetchServerSentEvents } from "@tanstack/ai-preact";
269
270export function ChatWithApproval() {
271 const { messages, sendMessage, addToolApprovalResponse } = useChat({
272 connection: fetchServerSentEvents("/api/chat"),
273 });
274
275 return (
276 <div>
277 {messages.map((message) =>
278 message.parts.map((part) => {
279 if (
280 part.type === "tool-call" &&
281 part.state === "approval-requested" &&
282 part.approval
283 ) {
284 return (
285 <div key={part.id}>
286 <p>Approve: {part.name}</p>
287 <button
288 onClick={() =>
289 addToolApprovalResponse({
290 id: part.approval!.id,
291 approved: true,
292 })
293 }
294 >
295 Approve
296 </button>
297 <button
298 onClick={() =>
299 addToolApprovalResponse({
300 id: part.approval!.id,
301 approved: false,
302 })
303 }
304 >
305 Deny
306 </button>
307 </div>
308 );
309 }
310 return null;
311 })
312 )}
313 </div>
314 );
315}
316```
317
318## Example: Client Tools with Type Safety
319
320```tsx
321import { useChat, fetchServerSentEvents } from "@tanstack/ai-preact";
322import {
323 createChatClientOptions,
324 type InferChatMessages
325} from "@tanstack/ai-client";
326import { toolDefinition } from "@tanstack/ai";
327import { z } from "zod";
328import { useState } from "preact/hooks";
329
330const updateUIDef = toolDefinition({
331 name: "updateUI",
332 description: "Show a notification in the UI",
333 inputSchema: z.object({ message: z.string(), type: z.string() }),
334});
335
336const saveToStorageDef = toolDefinition({
337 name: "saveToStorage",
338 description: "Save a value to localStorage",
339 inputSchema: z.object({ key: z.string(), value: z.string() }),
340});
341
342export function ChatWithClientTools() {
343 const [notification, setNotification] = useState<{ message: string; type: string } | null>(null);
344
345 // Create client implementations
346 const updateUI = updateUIDef.client((input) => {
347 // ✅ input is fully typed!
348 setNotification({ message: input.message, type: input.type });
349 return { success: true };
350 });
351
352 const saveToStorage = saveToStorageDef.client((input) => {
353 localStorage.setItem(input.key, input.value);
354 return { saved: true };
355 });
356
357 // Create typed tools array (no 'as const' needed!)
358 const tools = [updateUI, saveToStorage];
359
360 const { messages, sendMessage } = useChat({
361 connection: fetchServerSentEvents("/api/chat"),
362 tools, // ✅ Automatic execution, full type safety
363 });
364
365 return (
366 <div>
367 {messages.map((message) =>
368 message.parts.map((part) => {
369 if (part.type === "tool-call" && part.name === "updateUI") {
370 // ✅ part.input and part.output are fully typed!
371 return <div>Tool executed: {part.name}</div>;
372 }
373 return null;
374 })
375 )}
376 </div>
377 );
378}
379```
380
381## `createChatClientOptions(options)`
382
383Helper to create typed chat options (re-exported from `@tanstack/ai-client`).
384
385```typescript
386import {
387 createChatClientOptions,
388 type InferChatMessages
389} from "@tanstack/ai-client";
390import { fetchServerSentEvents } from "@tanstack/ai-preact";
391import { tool1, tool2 } from "./tools";
392
393// Create typed tools array (no 'as const' needed!)
394const tools = [tool1, tool2];
395
396const chatOptions = createChatClientOptions({
397 connection: fetchServerSentEvents("/api/chat"),
398 tools,
399});
400
401type Messages = InferChatMessages<typeof chatOptions>;
402```
403
404## Types
405
406Re-exported from `@tanstack/ai-client`:
407
408- `UIMessage<TTools>` - Message type with tool type parameter
409- `MessagePart<TTools>` - Message part with tool type parameter
410- `TextPart` - Text content part
411- `ThinkingPart` - Thinking content part
412- `ToolCallPart<TTools>` - Tool call part (discriminated union)
413- `ToolResultPart` - Tool result part
414- `ChatClientOptions<TTools, TContext>` - Chat client options with typed client runtime context
415- `ConnectionAdapter` - Connection adapter interface
416- `InferChatMessages<T>` - Extract message type from options
417
418Re-exported from `@tanstack/ai`:
419
420- `toolDefinition()` - Create isomorphic tool definition
421- `ToolDefinitionInstance` - Tool definition type
422- `ClientTool` - Client tool type
423- `ServerTool` - Server tool type
424
425## Next Steps
426
427- [Getting Started](../getting-started/quick-start) - Learn the basics
428- [Tools Guide](../tools/tools) - Learn about the isomorphic tool system
429- [Client Tools](../tools/client-tools) - Learn about client-side tools