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## Client Tools With Other AG-UI Servers
283
284Your 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.
285
286Register the client tools as in [Client-Side](#client-side), and point the connection at the endpoint of that server, for example `fetchServerSentEvents("/agent")`.
287
288The 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:
289
290- The client runs each tool call that the run started and did not answer.
291- If the server names the calls in `outcome.pendingToolCallIds`, the client runs only those of them that this run started.
292- The next request carries each result as a `role: "tool"` message.
293
294If no client tool has the name of the call, the call does not run. If the arguments of the call are not complete JSON, the call does not run. A client tool with `needsApproval: true` does not run on this path, because the server did not ask for approval.
295
296## Expose Client Tools Through WebMCP
297
298The normal client-tool path belongs to a TanStack chat run. It returns the browser result to the server and continues the conversation.
299
300WebMCP provides a separate execution path for browser agents. It calls the client handler and returns the result directly to WebMCP.
301
302WebMCP execution does not call `addToolResult`. It does not continue a TanStack chat run.
303
304Register the same executable client tools with a framework lifecycle wrapper or `registerWebMCPTools`. See [WebMCP Tools](./webmcp) for setup and security rules.
305
306## Client Runtime Context
307
308Client 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.
309
310```typescript
311import { createChatClientOptions } from "@tanstack/ai-client";
312import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
313import { toolDefinition } from "@tanstack/ai";
314import { toast } from "./toast";
315
316const activeProjectId = "";
317
318type ClientContext = {
319 activeProjectId: string;
320 toast(message: string): void;
321};
322
323const showToast = toolDefinition({
324 name: "show_toast",
325 description: "Show a browser notification",
326}).client<ClientContext>((_input, ctx) => {
327 ctx.context.toast(`Project ${ctx.context.activeProjectId} updated`);
328 return { ok: true };
329});
330
331const chatOptions = createChatClientOptions({
332 connection: fetchServerSentEvents("/api/chat"),
333 tools: [showToast],
334 context: {
335 activeProjectId,
336 toast: (message) => toast(message),
337 },
338});
339
340const chat = useChat(chatOptions);
341```
342
343Use `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.
344
345## The `clientTools()` helper (optional)
346
347Passing 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:
348
349```ts
350import { clientTools } from "@tanstack/ai-client";
351import { toolDefinition } from "@tanstack/ai";
352
353const notify = toolDefinition({
354 name: "notify",
355 description: "Show a notification",
356}).client(() => ({ ok: true }));
357
358// Equivalent to `const tools = [notify]` — just captured explicitly.
359const tools = clientTools(notify);
360```
361
362## Type Safety Benefits
363
364The isomorphic architecture provides complete end-to-end type safety:
365
366```typescript
367import type { UIMessage } from "@tanstack/ai-client";
368
369const messages: UIMessage[] = [];
370
371messages.forEach((message) => {
372 message.parts.forEach((part) => {
373 if (part.type === "tool-call" && part.name === "update_ui") {
374 // ✅ TypeScript knows part.name is literally "update_ui"
375 // ✅ part.input is typed as { message: string, type: "success" | "error" | "info" }
376 // ✅ part.output is typed as { success: boolean } | undefined
378 console.log(part.input.message); // ✅ Fully typed!
380 if (part.output) {
381 console.log(part.output.success); // ✅ Fully typed!
382 }
383 }
384 });
385});
386```
387
388## Tool States
389
390A `tool-call` part moves through a small set of observable `ToolCallState` values you can surface in the UI to indicate progress:
391
392- `awaiting-input` — the model intends to call the tool but arguments haven't arrived yet.
393- `input-streaming` — the model is streaming the tool arguments (partial input may be available).
394- `input-complete` — all arguments have been received and the tool can run.
395- `approval-requested` — the tool is waiting for user approval before it can run.
396- `approval-responded` — the user has approved or denied the tool call.
397
398The `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.
399
400```tsx
401import type { ToolCallPart } from "@tanstack/ai-client";
402
403function ToolCallDisplay({ part }: { part: ToolCallPart }) {
404 if (part.state === "awaiting-input") {
405 return <div>🔄 Waiting for arguments...</div>;
406 }
408 if (part.state === "input-streaming") {
409 return <div>📥 Receiving arguments...</div>;
410 }
412 if (part.state === "input-complete") {
413 return <div>✓ Arguments received, running tool...</div>;
414 }
415
416 // Completion shows up as a populated `part.output` (and as a sibling
417 // `tool-result` part whose state is `complete` / `error`).
418 if (part.output) {
419 return <div>✅ Tool complete</div>;
420 }
422 return null;
423}
424```
425
426## Hybrid Tools
427
428Tools can be implemented for both server and client, enabling flexible execution:
429
430```typescript
431import { toolDefinition, chat } from "@tanstack/ai";
432import { openaiText } from "@tanstack/ai-openai";
433import { z } from "zod";
434import { db } from "./db";
435
436// Define once
437const addToCartDef = toolDefinition({
438 name: "add_to_cart",
439 description: "Add item to shopping cart",
440 inputSchema: z.object({
441 itemId: z.string(),
442 quantity: z.number(),
443 }),
444 outputSchema: z.object({
445 success: z.boolean(),
446 cartId: z.string(),
447 }),
448});
449
450// Server implementation - Store in database
451const addToCartServer = addToCartDef.server(async (input) => {
452 const cart = await db.carts.create({
453 data: { itemId: input.itemId, quantity: input.quantity },
454 });
455 return { success: true, cartId: cart.id };
456});
457
458// Client implementation - Update local wishlist
459const addToCartClient = addToCartDef.client((input) => {
460 const wishlist = JSON.parse(localStorage.getItem("wishlist") || "[]");
461 wishlist.push(input.itemId);
462 localStorage.setItem("wishlist", JSON.stringify(wishlist));
463 return { success: true, cartId: "local" };
464});
465
466// Server: Pass definition for client execution
467chat({ adapter: openaiText('gpt-5.5'), messages: [], tools: [addToCartDef] }); // Client will execute
468
469// Or pass server implementation for server execution
470chat({ adapter: openaiText('gpt-5.5'), messages: [], tools: [addToCartServer] }); // Server will execute
471```
472
473## Best Practices
474
475- **Keep client tools simple** - Since client tools run in the browser, avoid heavy computations or large dependencies that could bloat your bundle size.
476- **Handle errors gracefully** - Define clear error handling in your tool implementations and return meaningful error messages in your output schema.
477- **Update UI reactively** - Use your framework's state management (eg. React/Vue/Solid) to update the UI in response to tool executions.
478- **Secure sensitive data** - Never store sensitive data (like API keys or personal info) in local storage or expose it via client tools.
479- **Provide feedback** - Use tool states to inform users about ongoing operations and results of client tool executions (loading spinners, success messages, error alerts).
480- **Type everything** - Leverage TypeScript and Zod schemas for full type safety from tool definitions to implementations to usage.
481
482## Common Use Cases
483
484- **UI Updates** - Show notifications, update forms, toggle visibility
485- **Local Storage** - Save user preferences, cache data
486- **Browser APIs** - Access geolocation, camera, clipboard
487- **State Management** - Update React/Vue/Solid state
488- **Navigation** - Change routes, scroll to sections
489- **Analytics** - Track user interactions
490
491## Next Steps
492
493- [How Tools Work](./tool-architecture) - Deep dive into the tool architecture
494- [Server Tools](./server-tools) - Learn about server-side tool execution
495- [Tool Approval Flow](./tool-approval) - Add approval workflows for sensitive operations