Open History to see the last commit
1---
2title: Client Tools
3id: client-tools
4order: 4
5description: "Run a tool in the browser so the model can update the UI, use localStorage, or call browser APIs. The server sends the call, and the browser runs it and sends the result back."
6keywords:
7 - tanstack ai
8 - client tools
9 - browser tools
10 - ui tools
11 - automatic execution
12 - clientTools
13 - localStorage
14---
15
16A client tool runs in the browser. Use it for a notification, `localStorage`, the clipboard, or navigation.
17
18The server tells the model that the tool exists. When the model calls it, the browser runs your `.client()` function and sends the result back. Then the model continues.
19
20Good jobs for a client tool:
21
22- **UI changes**: show a notification, fill a form, open a panel.
23- **Local data**: save preferences, cache values in `localStorage`.
24- **Browser APIs**: geolocation, camera, clipboard.
25- **Navigation**: change the route, scroll to a section.
26- **App state**: update React, Vue, or Solid state, or send an analytics event.
27
28## Add a client tool
29
30### 1. Define the tool in a shared file
31
32The server and the browser both import this file. It has no implementation yet:
33
34```typescript
35// tools/definitions.ts
36import { toolDefinition } from "@tanstack/ai";
37import { z } from "zod";
38
39export const savePreferenceDef = toolDefinition({
40 name: "save_preference",
41 description: "Save a user preference in the browser, such as the color theme",
42 inputSchema: z.object({
43 key: z.string().meta({ description: "Preference name, for example theme" }),
44 value: z.string().meta({ description: "Preference value, for example dark" }),
45 }),
46 outputSchema: z.object({
47 saved: z.boolean(),
48 }),
49});
50```
51
52### 2. Pass the definition to `chat()`
53
54On the server, pass the definition, not an implementation:
55
56```typescript
57// api/chat.ts
58import {
59 chat,
60 chatParamsFromRequest,
61 toServerSentEventsResponse,
62} from "@tanstack/ai";
63import { openaiText } from "@tanstack/ai-openai";
64import { savePreferenceDef } from "../tools/definitions";
65
66export async function POST(request: Request) {
67 const params = await chatParamsFromRequest(request);
68
69 const stream = chat({
70 adapter: openaiText("gpt-6.1-sol"),
71 messages: params.messages,
72 threadId: params.threadId,
73 runId: params.runId,
74 parentRunId: params.parentRunId,
75 ...(params.resume ? { resume: params.resume } : {}),
76 tools: [savePreferenceDef],
77 });
78
79 return toServerSentEventsResponse(stream);
80}
81```
82
83The browser sends the tool result in a second request. `parentRunId` and `resume` let `chat()` find the paused call and continue it.
84
85### 3. Add the `.client()` function and pass it to your chat hook
86
87Create the implementation at module scope. Then add it to `tools`:
88
89```tsx
90// app/chat.tsx
91import { useState } from "react";
92import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
93import { toolDefinition } from "@tanstack/ai";
94import { z } from "zod";
95
96// The same definition as tools/definitions.ts. In your app, import it from that file.
97const savePreferenceDef = toolDefinition({
98 name: "save_preference",
99 description: "Save a user preference in the browser, such as the color theme",
100 inputSchema: z.object({
101 key: z.string().meta({ description: "Preference name, for example theme" }),
102 value: z.string().meta({ description: "Preference value, for example dark" }),
103 }),
104 outputSchema: z.object({
105 saved: z.boolean(),
106 }),
107});
108
109const savePreference = savePreferenceDef.client((input) => {
110 localStorage.setItem(input.key, input.value);
111 return { saved: true };
112});
113
114export function Chat() {
115 const [input, setInput] = useState("");
116 const { messages, sendMessage } = useChat({
117 connection: fetchServerSentEvents("/api/chat"),
118 threadId: "support-chat",
119 tools: [savePreference],
120 });
121
122 return (
123 <>
124 {messages.map((message) => (
125 <div key={message.id}>
126 {message.parts.map((part, index) =>
127 part.type === "text" ? <p key={index}>{part.content}</p> : null,
128 )}
129 </div>
130 ))}
131 <form
132 onSubmit={(event) => {
133 event.preventDefault();
134 sendMessage(input);
135 setInput("");
136 }}
137 >
138 <input value={input} onChange={(event) => setInput(event.target.value)} />
139 <button type="submit">Send</button>
140 </form>
141 </>
142 );
143}
144```
145
146Every framework takes the same `tools` option:
147
148- `useChat` in Vue, Solid, Preact, and Octane.
149- `createChat` in Svelte and Remix.
150- `injectChat` in Angular.
151
152### 4. Try it
153
154Ask your chat "Use the dark theme from now on." The model calls `save_preference`. Your browser saves `theme` as `dark` in `localStorage`, and the model confirms. Open the dev tools of your browser to see the saved value.
155
156## How it works
157
158```mermaid
159sequenceDiagram
160 participant LLM Service
161 participant Server
162 participant Browser
163 participant ClientTool
164
165 LLM Service->>Server: tool_call chunk<br/>{name: "save_preference", args: {...}}
166 Server->>Server: Check if tool has<br/>server execute
167
168 Note over Server: No execute function<br/>= client tool
169
170 Server->>Browser: RUN_FINISHED client-tool<br/>interrupt via SSE/HTTP
171 Browser->>Browser: Find registered<br/>client tool
172 Browser->>ClientTool: execute(args)
173 ClientTool->>ClientTool: Update UI,<br/>localStorage, etc.
174 ClientTool-->>Browser: Return result
175 Browser->>Server: POST tool result
176 Server->>LLM Service: Add tool_result<br/>to conversation
177
178 Note over LLM Service: Model uses result<br/>to continue
179
180 LLM Service-->>Server: Stream response
181 Server-->>Browser: Forward chunks
182```
183
1841. The model calls the tool.
1852. The server sees that the tool has no server function. It pauses the run and sends the call to the browser.
1863. The browser finds the `.client()` function with the same tool name and runs it with the parsed input.
1874. The browser sends the result back to the server and starts the next run.
1885. The server checks the result against `outputSchema`. If the function throws or the check fails, the model gets a tool error.
1896. The model reads the result and continues.
190
191You do not write code for steps 2 to 5. `useChat` does them for you.
192
193## Show the tool call in your UI
194
195Each tool call is a `tool-call` part in the assistant message. When you pass the tools to the hook, a check on `part.name` gives you typed `part.input` and `part.output`:
196
197```tsx
198import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
199import { createChatClientOptions, type InferChatMessages } from "@tanstack/ai-client";
200import { toolDefinition } from "@tanstack/ai";
201import { z } from "zod";
202
203// The same definition as tools/definitions.ts. In your app, import it from that file.
204const savePreferenceDef = toolDefinition({
205 name: "save_preference",
206 description: "Save a user preference in the browser, such as the color theme",
207 inputSchema: z.object({
208 key: z.string().meta({ description: "Preference name, for example theme" }),
209 value: z.string().meta({ description: "Preference value, for example dark" }),
210 }),
211 outputSchema: z.object({
212 saved: z.boolean(),
213 }),
214});
215
216const savePreference = savePreferenceDef.client((input) => {
217 localStorage.setItem(input.key, input.value);
218 return { saved: true };
219});
220
221const chatOptions = createChatClientOptions({
222 connection: fetchServerSentEvents("/api/chat"),
223 threadId: "support-chat",
224 tools: [savePreference],
225});
226
227type ChatMessages = InferChatMessages<typeof chatOptions>;
228
229function Message({ message }: { message: ChatMessages[number] }) {
230 return (
231 <div>
232 {message.parts.map((part, index) => {
233 if (part.type === "text") {
234 return <p key={index}>{part.content}</p>;
235 }
236 if (part.type === "tool-call" && part.name === "save_preference") {
237 // part.input is { key: string; value: string }
238 // part.output is { saved: boolean } | undefined
239 return (
240 <p key={part.id}>
241 Saving {part.input?.key}
242 {part.output?.saved ? " (done)" : "..."}
243 </p>
244 );
245 }
246 return null;
247 })}
248 </div>
249 );
250}
251
252export function Chat() {
253 const { messages } = useChat(chatOptions);
254 return (
255 <>
256 {messages.map((message) => (
257 <Message key={message.id} message={message} />
258 ))}
259 </>
260 );
261}
262```
263
264A plain array in `tools` is enough for this type inference. You do not need `as const` or a wrapper. For every state that a tool call goes through, see [Tool Architecture](./tool-architecture#call-states). For typed tool events, see [Type-safe tool call events](../chat/stream-events#type-safe-tool-call-events).
265
266## Advanced
267
268### Ask the user before a client tool runs
269
270Add `needsApproval: true` to the definition. The tool first pauses on a `tool-approval` interrupt. You resolve only that decision. After the user approves, the client runs the `.client()` function and sends its result:
271
272```ts ignore
273const approval = interrupts.find(
274 (interrupt) =>
275 interrupt.kind === 'tool-approval' &&
276 interrupt.toolName === 'delete_local_data',
277)
278
279if (
280 approval?.kind === 'tool-approval' &&
281 approval.toolName === 'delete_local_data'
282) {
283 approval.resolveInterrupt(true)
284}
285```
286
287You never resolve the run of the tool by hand. The `.client()` function does that. If you register a tool with no `.client()` function and want to give the result yourself, call `addToolResult`. It checks the result against the output schema of the tool.
288
289For approval forms, see [Tool Approval Flow](./tool-approval). For the approval lifecycle, see [Interrupts](../interrupts/overview).
290
291### The client-tool pause
292
293- The server pauses the run with an internal `client-tool-execution` item on the interrupt wire. It is not a public item in `interrupts`.
294- This pause uses the same atomic interrupt batch as approvals, so it can hold back a submit of several items. The client resolves it for you. You do not call `resolveInterrupt` for it.
295- After hydration, a pending client-tool call comes back, but it does not run again. For recovery policies, see [Client persistence](../persistence/client-persistence#handle-restored-client-tools).
296
297For the ephemeral lifecycle and batches, see [Interrupts](../interrupts/overview).
298
299### Pass local values to a client tool
300
301A client tool gets typed runtime context as its second argument. This context belongs to the `ChatClient` or the hook instance. It is not sent to the server.
302
303```typescript
304import { createChatClientOptions } from "@tanstack/ai-client";
305import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
306import { toolDefinition } from "@tanstack/ai";
307import { toast } from "./toast";
308
309const activeProjectId = "";
310
311type ClientContext = {
312 activeProjectId: string;
313 toast(message: string): void;
314};
315
316const showToast = toolDefinition({
317 name: "show_toast",
318 description: "Show a browser notification",
319}).client<ClientContext>((_input, ctx) => {
320 ctx.context.toast(`Project ${ctx.context.activeProjectId} updated`);
321 return { ok: true };
322});
323
324const chatOptions = createChatClientOptions({
325 connection: fetchServerSentEvents("/api/chat"),
326 threadId: "support-chat",
327 tools: [showToast],
328 context: {
329 activeProjectId,
330 toast: (message) => toast(message),
331 },
332});
333
334const chat = useChat(chatOptions);
335```
336
337Does the server also need a value from the client? Send it with `forwardedProps`, check it in your route, and put it in the server `chat({ context })`. See [Runtime Context](../advanced/runtime-context).
338
339### One definition, two implementations
340
341A definition can have a `.server()` and a `.client()` implementation. The tool that you pass to `chat()` decides where it runs:
342
343```typescript
344import { toolDefinition, chat } from "@tanstack/ai";
345import { openaiText } from "@tanstack/ai-openai";
346import { z } from "zod";
347import { db } from "./db";
348
349const addToCartDef = toolDefinition({
350 name: "add_to_cart",
351 description: "Add item to shopping cart",
352 inputSchema: z.object({
353 itemId: z.string(),
354 quantity: z.number(),
355 }),
356 outputSchema: z.object({
357 success: z.boolean(),
358 cartId: z.string(),
359 }),
360});
361
362// Server implementation: store the cart in the database
363const addToCartServer = addToCartDef.server(async (input) => {
364 const cart = await db.carts.create({
365 data: { itemId: input.itemId, quantity: input.quantity },
366 });
367 return { success: true, cartId: cart.id };
368});
369
370// Client implementation: update a local wishlist
371const addToCartClient = addToCartDef.client((input) => {
372 const wishlist = JSON.parse(localStorage.getItem("wishlist") || "[]");
373 wishlist.push(input.itemId);
374 localStorage.setItem("wishlist", JSON.stringify(wishlist));
375 return { success: true, cartId: "local" };
376});
377
378// Pass the definition: the client runs the tool
379chat({ adapter: openaiText("gpt-6.1-sol"), messages: [], tools: [addToCartDef], threadId: "thread-1" });
380
381// Or pass the server implementation: the server runs the tool
382chat({ adapter: openaiText("gpt-6.1-sol"), messages: [], tools: [addToCartServer], threadId: "thread-1" });
383```
384
385Pass only one of the two to a `chat()` call. Both have the same name, and the tool names in one `tools` array must be unique.
386
387### Let the client declare its tools
388
389Pass the definitions on the server, as in the quick setup. Then the server alone decides which tools the model sees, and a client cannot add tools that you did not allow.
390
391To let the client declare its tools for each request through AG-UI `RunAgentInput.tools`, use [`mergeAgentTools`](../migration/ag-ui-compliance#tier-3-let-the-client-advertise-its-tools). Read its security note first, because the client controls `params.tools`.
392
393### Client tools with other AG-UI servers
394
395Your agent runs on another AG-UI server, such as Pydantic AI. It calls a frontend tool, then ends the run. `useChat` runs the tool and starts the next run with the result.
396
397Register the client tools as in [step 3](#3-add-the-client-function-and-pass-it-to-your-chat-hook). Point the connection at the endpoint of that server, for example `fetchServerSentEvents("/agent")`.
398
399The AG-UI spec ends such a run with `RUN_FINISHED` and a success outcome. The tool call gets no `TOOL_CALL_RESULT`. When that run ends:
400
401- The client runs each tool call that the run started and did not answer.
402- If the server names the calls in `outcome.pendingToolCallIds`, the client runs only those of them that this run started.
403- The next request carries each result as a `role: "tool"` message.
404
405These calls do not run:
406
407- A call with a name that no client tool has.
408- A call with arguments that are not complete JSON.
409- A call to a client tool with `needsApproval: true`, because the server did not ask for approval.
410
411### Expose client tools through WebMCP
412
413WebMCP lets browser agents call your client tools. This path is separate from a TanStack chat run:
414
415- WebMCP calls the client function and returns the result to WebMCP.
416- It does not call `addToolResult`, and it does not continue a chat run.
417
418Register the same client tools with a framework wrapper or `registerWebMCPTools`. See [WebMCP Tools](./webmcp) for setup and security rules.
419
420### The `clientTools()` helper
421
422A plain array, `tools: [toolA, toolB]`, already gives you typed tool names, inputs, and outputs. `clientTools()` does the same capture by name. Use it only to build a shared tool list outside the hook or the options call:
423
424```ts
425import { clientTools } from "@tanstack/ai-client";
426import { toolDefinition } from "@tanstack/ai";
427
428const notify = toolDefinition({
429 name: "notify",
430 description: "Show a notification",
431}).client(() => ({ ok: true }));
432
433// Same as `const tools = [notify]`
434const tools = clientTools(notify);
435```
436
437### Tips for good client tools
438
439- **Keep them small.** They run in the browser, so heavy work and large dependencies make your bundle bigger.
440- **Return errors as data.** Put an error field in the output schema and give a clear message.
441- **Keep secrets out.** Do not put API keys or personal data in `localStorage` or in a client tool.
442- **Show progress.** Use the tool-call states to show a spinner, a result, or an error.