Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

tools.md

493 lines15.3 KB

1---
2title: Tools
3id: tools
4order: 1
5description: "Define isomorphic AI tools in TanStack AI with toolDefinition() for type-safe server- and client-side function calling across any framework."
6keywords:
7 - tanstack ai
8 - tools
9 - function calling
10 - toolDefinition
11 - isomorphic tools
12 - server tools
13 - client tools
14 - type safety
15---
16​
17Tools (also called "function calling") allow AI models to interact with external systems, APIs, or perform computations. TanStack AI provides an isomorphic tool system that enables type-safe, framework-agnostic tool definitions that work on both server and client.
18​
19Tools enable your AI application to:
20​
21- **Fetch data** from APIs or databases
22- **Perform calculations** or data transformations
23- **Interact with services** like email, calendars, or payment systems
24- **Execute client-side operations** like updating UI or local storage
25- **Create hybrid tools** that execute in both server and client contexts
26​
27> Looking for provider-native tools like Anthropic web search, OpenAI code
28> interpreter, or Gemini URL context? See [Provider Tools](./provider-tools.md).
29​
30## Framework Support
31​
32TanStack AI works with **any** JavaScript framework:
33- TanStack Start, Next.js, Express, Remix, Fastify, etc.
34- React, Vue, Solid, Svelte, vanilla JS, etc.
35​
36TanStack AI works with any JavaScript framework.
37​
38## Isomorphic Tool Architecture
39​
40TanStack AI uses a two-step tool definition process:
41​
421. **Define once** with `toolDefinition()` - Creates a shared tool schema
432. **Implement** with `.server()` or `.client()` - Add execution logic for each environment
44​
45This approach provides:
46​
47- **Type Safety**: Full TypeScript inference from Zod schemas
48- **Code Reuse**: Define schemas once, use everywhere
49- **Flexibility**: Tools can execute on server, client, or both
50- **Schema Options**: Use Zod schemas or raw JSON Schema objects
51​
52## Schema Options
53​
54TanStack AI supports two ways to define tool schemas:
55​
56### Option 1: Zod Schemas (Recommended)
57​
58Zod schemas provide full TypeScript type inference and runtime validation:
59​
60```typescript
61import { z } from "zod";
62​
63const inputSchema = z.object({
64 location: z.string().meta({ description: "City name" }),
65 unit: z.enum(["celsius", "fahrenheit"]).optional(),
66});
67```
68​
69> **Note:** For OpenAI-compatible providers, an omitted `.optional()` tool field is absent when your tool runs. A `.nullable()` field keeps `null`.
70​
71### Option 2: JSON Schema Objects
72​
73For cases where you already have JSON Schema definitions or prefer not to use Zod, you can pass raw JSON Schema objects directly:
74​
75```typescript
76import type { JSONSchema } from "@tanstack/ai";
77​
78const inputSchema: JSONSchema = {
79 type: "object",
80 properties: {
81 location: {
82 type: "string",
83 description: "City name",
84 },
85 unit: {
86 type: "string",
87 enum: ["celsius", "fahrenheit"],
88 },
89 },
90 required: ["location"],
91};
92```
93​
94> **Note:** When using JSON Schema, TypeScript infers `unknown` for input/output types (it cannot derive types from a JSON Schema at compile time), so you must narrow or cast `args` before use. Zod schemas are recommended for full type safety.
95​
96> **Tip:** Type safety from Zod schemas extends beyond tool execution. When you pass `.client()` tools to `useChat`, a check on `part.name` narrows `part.input` and `part.output`. See [Type-safe tool call events](../chat/stream-events#type-safe-tool-call-events).
97​
98## Tool Definition
99​
100Tools are defined using `toolDefinition()` from `@tanstack/ai`:
101​
102```typescript
103import { toolDefinition } from "@tanstack/ai";
104import { z } from "zod";
105​
106// Step 1: Define the tool schema
107const getWeatherDef = toolDefinition({
108 name: "get_weather",
109 description: "Get the current weather for a location",
110 inputSchema: z.object({
111 location: z.string().meta({ description: "The city and state, e.g. San Francisco, CA" }),
112 unit: z.enum(["celsius", "fahrenheit"]).optional(),
113 }),
114 outputSchema: z.object({
115 temperature: z.number(),
116 conditions: z.string(),
117 location: z.string(),
118 }),
119});
120​
121// Step 2: Create a server implementation
122const getWeatherServer = getWeatherDef.server(async ({ location, unit }) => {
123 const response = await fetch(
124 `https://api.weather.com/v1/current?location=${location}&unit=${
125 unit || "fahrenheit"
126 }`
127 );
128 const data = await response.json();
129 return {
130 temperature: data.temperature,
131 conditions: data.conditions,
132 location: data.location,
133 };
134});
135```
136​
137### Using JSON Schema
138​
139If you prefer JSON Schema or have existing schema definitions:
140​
141```typescript group=json-schema-tools
142import { toolDefinition } from "@tanstack/ai";
143import type { JSONSchema } from "@tanstack/ai";
144​
145// Define schemas using JSON Schema
146const inputSchema: JSONSchema = {
147 type: "object",
148 properties: {
149 location: {
150 type: "string",
151 description: "The city and state, e.g. San Francisco, CA",
152 },
153 unit: {
154 type: "string",
155 enum: ["celsius", "fahrenheit"],
156 },
157 },
158 required: ["location"],
159};
160​
161const outputSchema: JSONSchema = {
162 type: "object",
163 properties: {
164 temperature: { type: "number" },
165 conditions: { type: "string" },
166 location: { type: "string" },
167 },
168 required: ["temperature", "conditions", "location"],
169};
170​
171// Create the tool definition
172const getWeatherDef = toolDefinition({
173 name: "get_weather",
174 description: "Get the current weather for a location",
175 inputSchema,
176 outputSchema,
177});
178​
179// With a raw JSON Schema, `args` is `unknown` — narrow it before use
180// (prefer a Zod schema for automatic typing).
181const getWeatherServer = getWeatherDef.server(async (args) => {
182 if (typeof args !== "object" || args === null || !("location" in args)) {
183 throw new Error("Invalid input: expected a location");
184 }
185 const location = String(args.location);
186 const unit = "unit" in args ? String(args.unit) : "fahrenheit";
187 const response = await fetch(
188 `https://api.weather.com/v1/current?location=${location}&unit=${unit}`
189 );
190 return await response.json();
191});
192```
193​
194## Using Tools in Chat
195​
196### Server-Side
197​
198```typescript
199import { chat, toServerSentEventsResponse, toolDefinition } from "@tanstack/ai";
200import { openaiText } from "@tanstack/ai-openai";
201import { z } from "zod";
202​
203const getWeatherDef = toolDefinition({
204 name: "get_weather",
205 description: "Get the current weather for a location",
206 inputSchema: z.object({
207 location: z.string().meta({ description: "The city and state, e.g. San Francisco, CA" }),
208 unit: z.enum(["celsius", "fahrenheit"]).optional(),
209 }),
210 outputSchema: z.object({
211 temperature: z.number(),
212 conditions: z.string(),
213 location: z.string(),
214 }),
215});
216​
217export async function POST(request: Request) {
218 const { messages } = await request.json();
219​
220 // Create server implementation
221 const getWeather = getWeatherDef.server(async ({ location, unit }) => {
222 const response = await fetch(`https://api.weather.com/v1/current?...`);
223 return await response.json();
224 });
225​
226 const stream = chat({
227 adapter: openaiText("gpt-5.5"),
228 messages,
229 tools: [getWeather], // Pass server tools
230 });
231​
232 return toServerSentEventsResponse(stream);
234```
235​
236### Client-Side with Type Safety
237​
238```tsx
239import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
240import {
241 createChatClientOptions,
242 type InferChatMessages
243} from "@tanstack/ai-client";
244import { toolDefinition } from "@tanstack/ai";
245import { z } from "zod";
246​
247const updateUIDef = toolDefinition({
248 name: "updateUI",
249 description: "Update the UI with a notification message",
250 inputSchema: z.object({ message: z.string() }),
251 outputSchema: z.object({ success: z.boolean() }),
252});
253​
254const saveToStorageDef = toolDefinition({
255 name: "saveToStorage",
256 description: "Save data to storage",
257 inputSchema: z.object({ key: z.string(), value: z.string() }),
258 outputSchema: z.object({ saved: z.boolean() }),
259});
260​
261// Create client implementations
262const updateUI = updateUIDef.client((input) => {
263 // Update UI state
264 console.log(input.message);
265 return { success: true };
266});
267​
268const saveToStorage = saveToStorageDef.client((input) => {
269 localStorage.setItem(input.key, input.value);
270 return { saved: true };
271});
272​
273// Create typed tools array (no 'as const' needed!)
274const tools = [updateUI, saveToStorage];
275​
276const textOptions = createChatClientOptions({
277 connection: fetchServerSentEvents("/api/chat"),
278 tools,
279});
280​
281// Infer message types for full type safety
282type ChatMessages = InferChatMessages<typeof textOptions>;
283​
284function ChatComponent() {
285 const { messages } = useChat(textOptions);
287 // messages is now fully typed with tool names and outputs!
288 return (
289 <div>
290 {messages.map((m) => (
291 <div key={m.id}>{m.role}</div>
292 ))}
293 </div>
294 );
296```
297​
298## Hybrid Tools
299​
300Tools can be implemented for both server and client, enabling flexible execution patterns:
301​
302```typescript group=tools
303import { toolDefinition, chat } from "@tanstack/ai";
304import { openaiText } from "@tanstack/ai-openai";
305import { z } from "zod";
306import { db } from "./db";
307​
308// Define once
309const addToCartDef = toolDefinition({
310 name: "add_to_cart",
311 description: "Add item to shopping cart",
312 inputSchema: z.object({
313 itemId: z.string(),
314 quantity: z.number(),
315 }),
316 outputSchema: z.object({
317 success: z.boolean(),
318 cartId: z.string(),
319 }),
320 needsApproval: true,
321});
322​
323// Server implementation - Store in database
324const addToCartServer = addToCartDef.server(async (input) => {
325 const cart = await db.carts.create({
326 data: { itemId: input.itemId, quantity: input.quantity },
327 });
328 return { success: true, cartId: cart.id };
329});
330​
331// Client implementation - Update local wishlist
332const addToCartClient = addToCartDef.client((input) => {
333 const wishlist = JSON.parse(localStorage.getItem("wishlist") || "[]");
334 wishlist.push(input.itemId);
335 localStorage.setItem("wishlist", JSON.stringify(wishlist));
336 return { success: true, cartId: "local" };
337});
338```
339​
340On the server, pass either the definition (for client execution) or the server implementation — in separate `chat()` calls:
341​
342```typescript group=tools
343const messages = [{ role: 'user' as const, content: 'Add item abc to my cart' }]
344​
345// Pass the definition: the client will execute the tool
346chat({
347 adapter: openaiText("gpt-5.5"),
348 messages,
349 tools: [addToCartDef],
350});
351​
352// Or pass the server implementation: the server will execute the tool
353chat({
354 adapter: openaiText("gpt-5.5"),
355 messages,
356 tools: [addToCartServer],
357});
358```
359​
360## Type Safety Benefits
361​
362The isomorphic architecture provides complete type safety:
363​
364```tsx
365import { useChat } from "@tanstack/ai-react";
366import { fetchServerSentEvents } from "@tanstack/ai-client";
367​
368function CartChat() {
369 const { messages: uiMessages } = useChat({
370 connection: fetchServerSentEvents("/api/chat"),
371 });
372​
373 // In your React component
374 uiMessages.forEach((message) => {
375 message.parts.forEach((part) => {
376 if (part.type === 'tool-call' && part.name === 'add_to_cart') {
377 // ✅ TypeScript knows part.name is literally 'add_to_cart'
378 // ✅ part.input is typed as { itemId: string, quantity: number }
379 // ✅ part.output is typed as { success: boolean, cartId: string } | undefined
381 if (part.output) {
382 console.log(part.output.cartId); // ✅ Fully typed!
383 }
384 }
385 });
386 });
387​
388 return null;
390```
391​
392## Tool Execution Flow
393​
3941. **Model decides to call a tool** - Based on user input and tool descriptions
3952. **Tool is identified** - Server or client implementation
3963. **Tool executes** - Automatically on server or client
3974. **Result is returned** - To the model as a tool result message
3985. **Model continues** - Uses the result to generate a response
399​
400## Run tools one at a time
401​
402When the model calls several server tools in one turn, they start at the same time, and the model gets the results in the order of its calls. Some tools must not overlap, for example a tool that writes a file and a tool that runs the tests.
403​
404Set `toolExecution: 'sequential'` on `chat()` to run the tools of each turn one at a time, in call order:
405​
406```ts
407import { chat, toolDefinition } from '@tanstack/ai'
408import { openaiText } from '@tanstack/ai-openai'
409import { z } from 'zod'
410​
411const writeFile = toolDefinition({
412 name: 'write_file',
413 description: 'Write a file',
414 inputSchema: z.object({ path: z.string(), content: z.string() }),
415}).server(async ({ path }) => ({ written: path }))
416​
417const runTests = toolDefinition({
418 name: 'run_tests',
419 description: 'Run the test suite',
420 inputSchema: z.object({}),
421}).server(async () => ({ passed: true }))
422​
423const stream = chat({
424 adapter: openaiText('gpt-6.1-sol'),
425 messages: [{ role: 'user', content: 'Fix the bug, then run the tests.' }],
426 tools: [writeFile, runTests],
427 toolExecution: 'sequential',
428})
429```
430​
431Client tools do not change: the client runs them as their calls arrive.
432​
433## Progress Events and Runtime Context
434​
435A server tool's `.server()` implementation receives a second argument, the `ToolExecutionContext` — `{ context, toolCallId, emitCustomEvent }`. Use `emitCustomEvent` to stream typed progress to the client while the tool runs, and `context` to read request-scoped dependencies (auth, DB clients, etc.):
436​
437```typescript
438import { toolDefinition } from "@tanstack/ai";
439import { z } from "zod";
440​
441type ImportContext = {
442 db: {
443 read(source: string): Promise<unknown[]>;
444 write(rows: unknown[]): Promise<void>;
445 };
446};
447​
448const importDataDef = toolDefinition({
449 name: "import_data",
450 description: "Import data from a source",
451 inputSchema: z.object({ source: z.string() }),
452 outputSchema: z.object({ imported: z.number() }),
453});
454​
455const importData = importDataDef.server<ImportContext>(async (input, { context, emitCustomEvent }) => {
456 emitCustomEvent("progress", { step: 1, total: 3 });
457 const rows = await context.db.read(input.source);
458​
459 emitCustomEvent("progress", { step: 2, total: 3 });
460 await context.db.write(rows);
461​
462 emitCustomEvent("progress", { step: 3, total: 3 });
463 return { imported: rows.length };
464});
465```
466​
467Each `emitCustomEvent` call flushes through durability immediately, so the
468client can show progress while the tool still runs. Pass `{ batch: true }`
469only for a high-volume stream. See [Custom Events](../protocol/custom-events).
470​
471See [Server Tools](./server-tools) for the full runtime-context pattern.
472​
473## Tool States
474​
475Tools go through different states during execution:
476​
477- `awaiting-input` - Tool call received, waiting for arguments
478- `input-streaming` - Partial arguments being streamed
479- `input-complete` - All arguments received
480- `approval-requested` - Tool requires user approval (if `needsApproval: true`)
481- `approval-responded` - User has approved/denied
482​
483Once arguments (and approval, if required) are in, the result appears as `part.output` on the tool-call part and as a separate sibling `tool-result` part whose `state` is `complete` or `error`. See [Tool Architecture](./tool-architecture) for the full state model.
484​
485> **Tip:** If your use case involves calling multiple tools with complex logic (filtering, aggregation, parallel calls), consider [Code Mode](../code-mode/code-mode) — it lets the LLM write a TypeScript program that orchestrates tools in a single execution instead of one tool call at a time.
486​
487## Next Steps
488​
489- [Server Tools](./server-tools) - Learn about server-side tool execution
490- [Client Tools](./client-tools) - Learn about client-side tool execution
491- [Tool Approval Flow](./tool-approval) - Implement approval workflows
492- [How Tools Work](./tool-architecture) - Deep dive into the tool architecture
493- [MCP Server Tools](./mcp) - Connect to external MCP servers for additional tools