Open History to see the last commit
1---
2title: Client Tools
3id: client-tools
4order: 4
5description: "Client tools in TanStack AI run in the browser for UI updates, localStorage, and browser API access with automatic execution."
6keywords:
7 - tanstack ai
8 - client tools
9 - browser tools
10 - ui tools
11 - automatic execution
12 - clientTools
13 - localStorage
14---
15
16Client tools execute in the browser, enabling UI updates, local storage access, and browser API interactions. Unlike server tools, client tools don't have an `execute` function in their server definition.
17
18```mermaid
19sequenceDiagram
20 participant LLM Service
21 participant Server
22 participant Browser
23 participant ClientTool
25 LLM Service->>Server: tool_call chunk<br/>{name: "updateUI", args: {...}}
26 Server->>Server: Check if tool has<br/>server execute
28 Note over Server: No execute function<br/>= client tool
30 Server->>Browser: RUN_FINISHED client-tool<br/>interrupt via SSE/HTTP
31 Browser->>Browser: Find registered<br/>client tool
32 Browser->>ClientTool: execute(args)
33 ClientTool->>ClientTool: Update UI,<br/>localStorage, etc.
34 ClientTool-->>Browser: Return result
35 Browser->>Server: POST tool result
36 Server->>LLM Service: Add tool_result<br/>to conversation
38 Note over LLM Service: Model uses result<br/>to continue
40 LLM Service-->>Server: Stream response
41 Server-->>Browser: Forward chunks
42```
43
44## When to Use Client Tools
45
46- **UI Updates**: Show notifications, update forms, toggle visibility
47- **Local Storage**: Save user preferences, cache data
48- **Browser APIs**: Access geolocation, camera, clipboard
49- **State Management**: Update React/Vue/Solid state
50- **Navigation**: Change routes, scroll to sections
51
52## How It Works
53
541. **Tool Call from LLM**: LLM decides to call a client tool
552. **Server Detection**: Server sees the tool has no `execute` function
563. **Client Notification**: Server emits an internal `client-tool-execution`
57 pause on the interrupt wire (not a public item in `interrupts`)
584. **Client Execution**: The browser finds the registered `.client()`
59 implementation by tool name and runs it with the parsed input
605. **Result Return**: Client auto-submits the result via the resume batch
616. **Server Update**: Successful output is validated. Execution and output
62 validation failures are added as failed tool results.
637. **LLM Continuation**: LLM receives the result and continues the conversation
64
65Native client-tool execution shares the atomic interrupt **batch** lifecycle
66(it can gate multi-item submits) but is **auto-resolved** — you do not call
67`resolveInterrupt` for it. See [Interrupts](../interrupts/overview) for the
68ephemeral lifecycle, batches, and migration from the historical
69`tool-input-available` custom event. After hydration, a pending client-tool
70execution is restored but not run again. See
71[Client persistence](../persistence/client-persistence#handle-restored-client-tools)
72for recovery policies.
73
74## Approval is a separate axis
75
76A client tool can also require approval, and approval is separate from the
77browser result. Add `needsApproval: true` and the tool pauses on a
78`tool-approval` interrupt first. You resolve **that decision only** — once
79approved, the client runs the `.client()` implementation automatically and
80returns its result:
81
82```ts ignore
83const approval = interrupts.find(
84 (interrupt) =>
85 interrupt.kind === 'tool-approval' &&
86 interrupt.toolName === 'delete_local_data',
87)
88
89if (
90 approval?.kind === 'tool-approval' &&
91 approval.toolName === 'delete_local_data'
92) {
93 approval.resolveInterrupt(true)
94}
95```
96
97You never resolve the execution by hand — that is what the `.client()`
98implementation is for. If you register a tool **without** a `.client()`
99implementation and want to supply the result yourself, use `addToolResult`
100(validated against the tool's output schema); it also preserves the historical
101path for legacy streams. See [Tool approval flow](./tool-approval) for approval
102forms and [Interrupts](../interrupts/overview) for the approval lifecycle.
103
104## Defining Client Tools
105
106Client tools use the same `toolDefinition()` API but with the `.client()` method:
107
108```typescript
109// tools/definitions.ts - Shared between server and client
110import { toolDefinition } from "@tanstack/ai";
111import { z } from "zod";
112
113export const updateUIDef = toolDefinition({
114 name: "update_ui",
115 description: "Update the UI with new information",
116 inputSchema: z.object({
117 message: z.string().meta({ description: "Message to display" }),
118 type: z.enum(["success", "error", "info"]).meta({ description: "Message type" }),
119 }),
120 outputSchema: z.object({
121 success: z.boolean(),
122 }),
123});
124
125export const saveToLocalStorageDef = toolDefinition({
126 name: "save_to_local_storage",
127 description: "Save data to browser local storage",
128 inputSchema: z.object({
129 key: z.string().meta({ description: "Storage key" }),
130 value: z.string().meta({ description: "Value to store" }),
131 }),
132 outputSchema: z.object({
133 saved: z.boolean(),
134 }),
135});
136```
137
138## Using Client Tools
139
140### Server-Side
141
142To give the LLM access to client tools, pass the tool definitions (not implementations) to the server when creating the chat:
143
144```typescript
145// api/chat/route.ts
146import { chat, toServerSentEventsResponse } from "@tanstack/ai";
147import { openaiText } from "@tanstack/ai-openai";
148import { updateUIDef, saveToLocalStorageDef } from "./tools/definitions";
149
150export async function POST(request: Request) {
151 const { messages } = await request.json();
152
153 const stream = chat({
154 adapter: openaiText("gpt-5.5"),
155 messages,
156 tools: [updateUIDef, saveToLocalStorageDef], // Pass definitions
157 });
158
159 return toServerSentEventsResponse(stream);
160}
161```
162
163> **Security:** registering the definitions statically (as above) is the safe
164> default — the server alone decides which tools the model sees, so a client
165> can't advertise tools you didn't sanction. If you'd instead like the client
166> to declare its tools per request via AG-UI `RunAgentInput.tools`, use
167> [`mergeAgentTools`](../migration/ag-ui-compliance#tier-3--optional-let-the-client-advertise-its-tools) —
168> read its security note first, since `params.tools` is client-controlled.
169
170### Client-Side
171
172Create client implementations with automatic execution and full type safety:
173
174```tsx
175// app/chat.tsx
176import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
177import {
178 createChatClientOptions,
179 type InferChatMessages,
180 type ToolCallPart,
181 type MessagePart,
182} from "@tanstack/ai-client";
183import { toolDefinition } from "@tanstack/ai";
184import { z } from "zod";
185
186const updateUIDef = toolDefinition({
187 name: "update_ui",
188 description: "Update the UI with new information",
189 inputSchema: z.object({
190 message: z.string().meta({ description: "Message to display" }),
191 type: z.enum(["success", "error", "info"]).meta({ description: "Message type" }),
192 }),
193 outputSchema: z.object({ success: z.boolean() }),
194});
195
196const saveToLocalStorageDef = toolDefinition({
197 name: "save_to_local_storage",
198 description: "Save data to browser local storage",
199 inputSchema: z.object({
200 key: z.string().meta({ description: "Storage key" }),
201 value: z.string().meta({ description: "Value to store" }),
202 }),
203 outputSchema: z.object({ saved: z.boolean() }),
204});
205
206// Step 1: Create client implementations (module scope)
207const updateUI = updateUIDef.client((input) => {
208 // Update UI state - fully typed!
209 console.log(input.message, input.type);
210 return { success: true };
211});
212
213const saveToLocalStorage = saveToLocalStorageDef.client((input) => {
214 localStorage.setItem(input.key, input.value);
215 return { saved: true };
216});
217
218// Step 2: A plain array is all you need — literal tool names, inputs and
219// outputs are inferred without any wrapper or `as const`.
220const tools = [updateUI, saveToLocalStorage];
221
222const chatOptions = createChatClientOptions({
223 connection: fetchServerSentEvents("/api/chat"),
224 tools,
225});
226
227// Step 3: Infer message types for full type safety
228type ChatMessages = InferChatMessages<typeof chatOptions>;
229
230function ChatComponent() {
231 const { messages, sendMessage, isLoading } = useChat(chatOptions);
232
233 // Step 4: Render with full type safety
234 return (
235 <div>
236 {messages.map((message) => (
237 <MessageComponent key={message.id} message={message} />
238 ))}
239 </div>
240 );
241}
242
243// Messages component with full type safety
244function MessageComponent({ message }: { message: ChatMessages[number] }) {
245 return (
246 <div>
247 {message.parts.map((part: MessagePart) => {
248 if (part.type === "text") {
249 return <p>{part.content}</p>;
250 }
252 if (part.type === "tool-call") {
253 // ✅ part.name is narrowed to specific tool names
254 if (part.name === "update_ui") {
255 // ✅ part.input is typed as { message: string, type: "success" | "error" | "info" }
256 // ✅ part.output is typed as { success: boolean } | undefined
257 return (
258 <div>
259 Tool: {part.name}
260 {part.output && <span>✓ Success</span>}
261 </div>
262 );
263 }
264 }
265 return null;
266 })}
267 </div>
268 );
269}
270```
271
272## Automatic Execution
273
274Client tools are **automatically executed** when the model calls them. The flow is:
275
2761. LLM calls a client tool
2772. Server sends a `client-tool-execution` interrupt to the browser
2783. Client automatically executes the matching tool implementation
2794. Result is sent back to server
2805. Conversation continues with the result
281
282## Expose Client Tools Through WebMCP
283
284The normal client-tool path belongs to a TanStack chat run. It returns the browser result to the server and continues the conversation.
285
286WebMCP provides a separate execution path for browser agents. It calls the client handler and returns the result directly to WebMCP.
287
288WebMCP execution does not call `addToolResult`. It does not continue a TanStack chat run.
289
290Register the same executable client tools with a framework lifecycle wrapper or `registerWebMCPTools`. See [WebMCP Tools](./webmcp) for setup and security rules.
291
292## Client Runtime Context
293
294Client tools can receive typed runtime context as their second argument. This context is local to the `ChatClient` or framework hook instance and is not serialized to the server.
295
296```typescript
297import { createChatClientOptions } from "@tanstack/ai-client";
298import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
299import { toolDefinition } from "@tanstack/ai";
300import { toast } from "./toast";
301
302const activeProjectId = "";
303
304type ClientContext = {
305 activeProjectId: string;
306 toast(message: string): void;
307};
308
309const showToast = toolDefinition({
310 name: "show_toast",
311 description: "Show a browser notification",
312}).client<ClientContext>((_input, ctx) => {
313 ctx.context.toast(`Project ${ctx.context.activeProjectId} updated`);
314 return { ok: true };
315});
316
317const chatOptions = createChatClientOptions({
318 connection: fetchServerSentEvents("/api/chat"),
319 tools: [showToast],
320 context: {
321 activeProjectId,
322 toast: (message) => toast(message),
323 },
324});
325
326const chat = useChat(chatOptions);
327```
328
329Use `context` for local browser dependencies. If the server also needs a value from the client, send it with `forwardedProps`, validate it in your route, and map it into server `chat({ context })` explicitly. See [Runtime Context](../advanced/runtime-context) for the full pattern.
330
331## The `clientTools()` helper (optional)
332
333Passing a plain array — `tools: [toolA, toolB]` — is all you need: tool names, inputs and outputs are inferred without any wrapper and without `as const`. `clientTools()` is an optional 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:
334
335```ts
336import { clientTools } from "@tanstack/ai-client";
337import { toolDefinition } from "@tanstack/ai";
338
339const notify = toolDefinition({
340 name: "notify",
341 description: "Show a notification",
342}).client(() => ({ ok: true }));
343
344// Equivalent to `const tools = [notify]` — just captured explicitly.
345const tools = clientTools(notify);
346```
347
348## Type Safety Benefits
349
350The isomorphic architecture provides complete end-to-end type safety:
351
352```typescript
353import type { UIMessage } from "@tanstack/ai-client";
354
355const messages: UIMessage[] = [];
356
357messages.forEach((message) => {
358 message.parts.forEach((part) => {
359 if (part.type === "tool-call" && part.name === "update_ui") {
360 // ✅ TypeScript knows part.name is literally "update_ui"
361 // ✅ part.input is typed as { message: string, type: "success" | "error" | "info" }
362 // ✅ part.output is typed as { success: boolean } | undefined
364 console.log(part.input.message); // ✅ Fully typed!
366 if (part.output) {
367 console.log(part.output.success); // ✅ Fully typed!
368 }
369 }
370 });
371});
372```
373
374## Tool States
375
376A `tool-call` part moves through a small set of observable `ToolCallState` values you can surface in the UI to indicate progress:
377
378- `awaiting-input` — the model intends to call the tool but arguments haven't arrived yet.
379- `input-streaming` — the model is streaming the tool arguments (partial input may be available).
380- `input-complete` — all arguments have been received and the tool can run.
381- `approval-requested` — the tool is waiting for user approval before it can run.
382- `approval-responded` — the user has approved or denied the tool call.
383
384The `ToolCallState` union includes a `complete` value, but the runtime never transitions a tool-call part to it — a finished call settles at `input-complete`. Once the tool runs, the result appears two ways: `part.output` becomes populated on the tool-call part, and a sibling `tool-result` part is emitted whose own `state` is `complete` or `error` (the `error` case carries `part.error`). Use the tool-call states for loading/streaming progress and the tool-result part for final success/error feedback.
385
386```tsx
387import type { ToolCallPart } from "@tanstack/ai-client";
388
389function ToolCallDisplay({ part }: { part: ToolCallPart }) {
390 if (part.state === "awaiting-input") {
391 return <div>🔄 Waiting for arguments...</div>;
392 }
394 if (part.state === "input-streaming") {
395 return <div>📥 Receiving arguments...</div>;
396 }
398 if (part.state === "input-complete") {
399 return <div>✓ Arguments received, running tool...</div>;
400 }
401
402 // Completion shows up as a populated `part.output` (and as a sibling
403 // `tool-result` part whose state is `complete` / `error`).
404 if (part.output) {
405 return <div>✅ Tool complete</div>;
406 }
408 return null;
409}
410```
411
412## Hybrid Tools
413
414Tools can be implemented for both server and client, enabling flexible execution:
415
416```typescript
417import { toolDefinition, chat } from "@tanstack/ai";
418import { openaiText } from "@tanstack/ai-openai";
419import { z } from "zod";
420import { db } from "./db";
421
422// Define once
423const addToCartDef = toolDefinition({
424 name: "add_to_cart",
425 description: "Add item to shopping cart",
426 inputSchema: z.object({
427 itemId: z.string(),
428 quantity: z.number(),
429 }),
430 outputSchema: z.object({
431 success: z.boolean(),
432 cartId: z.string(),
433 }),
434});
435
436// Server implementation - Store in database
437const addToCartServer = addToCartDef.server(async (input) => {
438 const cart = await db.carts.create({
439 data: { itemId: input.itemId, quantity: input.quantity },
440 });
441 return { success: true, cartId: cart.id };
442});
443
444// Client implementation - Update local wishlist
445const addToCartClient = addToCartDef.client((input) => {
446 const wishlist = JSON.parse(localStorage.getItem("wishlist") || "[]");
447 wishlist.push(input.itemId);
448 localStorage.setItem("wishlist", JSON.stringify(wishlist));
449 return { success: true, cartId: "local" };
450});
451
452// Server: Pass definition for client execution
453chat({ adapter: openaiText('gpt-5.5'), messages: [], tools: [addToCartDef] }); // Client will execute
454
455// Or pass server implementation for server execution
456chat({ adapter: openaiText('gpt-5.5'), messages: [], tools: [addToCartServer] }); // Server will execute
457```
458
459## Best Practices
460
461- **Keep client tools simple** - Since client tools run in the browser, avoid heavy computations or large dependencies that could bloat your bundle size.
462- **Handle errors gracefully** - Define clear error handling in your tool implementations and return meaningful error messages in your output schema.
463- **Update UI reactively** - Use your framework's state management (eg. React/Vue/Solid) to update the UI in response to tool executions.
464- **Secure sensitive data** - Never store sensitive data (like API keys or personal info) in local storage or expose it via client tools.
465- **Provide feedback** - Use tool states to inform users about ongoing operations and results of client tool executions (loading spinners, success messages, error alerts).
466- **Type everything** - Leverage TypeScript and Zod schemas for full type safety from tool definitions to implementations to usage.
467
468## Common Use Cases
469
470- **UI Updates** - Show notifications, update forms, toggle visibility
471- **Local Storage** - Save user preferences, cache data
472- **Browser APIs** - Access geolocation, camera, clipboard
473- **State Management** - Update React/Vue/Solid state
474- **Navigation** - Change routes, scroll to sections
475- **Analytics** - Track user interactions
476
477## Next Steps
478
479- [How Tools Work](./tool-architecture) - Deep dive into the tool architecture
480- [Server Tools](./server-tools) - Learn about server-side tool execution
481- [Tool Approval Flow](./tool-approval) - Add approval workflows for sensitive operations