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