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

tools.md

592 lines19.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## Choose when the model calls a tool
434​
435Your weather assistant gives advice before it looks up the weather. Or you want a plain text answer, with no tool calls at all. Set `toolChoice`, and the model does what you ask.
436​
437Make the model call `get_weather` first:
438​
439```ts group=tool-choice
440import {
441 chat,
442 toServerSentEventsResponse,
443 toolDefinition,
444 type ChatMiddleware,
445} from '@tanstack/ai'
446import { openaiText } from '@tanstack/ai-openai'
447import { z } from 'zod'
448​
449const getWeather = toolDefinition({
450 name: 'get_weather',
451 description: 'Get the current weather for a city',
452 inputSchema: z.object({ city: z.string() }),
453}).server(async ({ city }) => ({ city, temperature: 21 }))
454​
455// Force the tool on the first model call only.
456const weatherFirst: ChatMiddleware = {
457 name: 'weather-first',
458 onConfig: (ctx) => {
459 if (ctx.phase === 'beforeModel' && ctx.iteration === 0) {
460 return { toolChoice: { type: 'tool', name: 'get_weather' } }
461 }
462 },
464​
465export async function POST(request: Request) {
466 const { messages } = await request.json()
467​
468 const stream = chat({
469 adapter: openaiText('gpt-6.1-sol'),
470 messages,
471 tools: [getWeather],
472 middleware: [weatherFirst],
473 })
474​
475 return toServerSentEventsResponse(stream)
477```
478​
479The first call must call `get_weather`. The next call goes back to the default, so the model answers with the forecast.
480​
481Your client code does not change. `toolChoice` is a server option.
482​
483### The values
484​
485| Value | What the model does |
486| --- | --- |
487| `'auto'` | It decides. |
488| `'none'` | It calls no tool. |
489| `'required'` | It must call a tool. |
490| `{ type: 'tool', name }` | It must call the tool with this name. |
491​
492### Set it for the whole run
493​
494`chat({ toolChoice })` applies to every model call of the run. With `'required'` or a named tool, the model never writes a text answer. The run stops at the loop limit, after a tool result.
495​
496For one lookup and nothing more, stop after one call:
497​
498```ts group=tool-choice
499import { maxIterations } from '@tanstack/ai'
500​
501const oneLookup = chat({
502 adapter: openaiText('gpt-6.1-sol'),
503 messages: [{ role: 'user', content: 'Weather in Oslo?' }],
504 tools: [getWeather],
505 toolChoice: 'required',
506 agentLoopStrategy: maxIterations(1),
507})
508```
509​
510In `chat({ toolChoice: { type: 'tool', name } })`, your editor suggests the names of the tools that you pass. Any other string also works, for example the name of a provider tool.
511​
512Need a text answer on the last call? Return `{ toolChoice: 'none' }` from a middleware. See [Change the tool choice of a call](../advanced/middleware#change-the-tool-choice-of-a-call).
513​
514### Rules for every adapter
515​
516- If the request has no tools, the adapter sends no tool choice.
517- A tool choice in `modelOptions` wins over `toolChoice`, for example `tool_choice` on OpenAI.
518- The adapter sends the name as you give it. It does not make sure that a tool has this name.
519​
520### Provider notes
521​
522OpenAI, Grok, Groq, Mistral, OpenRouter, and the other OpenAI-compatible adapters send the value as it is. Some providers change it:
523​
524- **Claude** (Anthropic and Amazon Bedrock): some calls cannot force a tool. Then `'required'` and a named tool become `'auto'`.
525 - `claude-fable-5-1`, `claude-mythos-5-1`, `claude-opus-5-5`, and `claude-sonnet-5-5` never take a forced tool.
526 - No Claude model takes a forced tool while thinking is on. See [Reasoning](../chat/reasoning).
527- **Amazon Bedrock (Converse API)**: Converse has no `none` value, so `'none'` sends no tools. The tool calls in the history go out as text.
528- **Gemini**: the value becomes `functionCallingConfig` (`AUTO`, `NONE`, or `ANY`). A named tool is `ANY` with `allowedFunctionNames`. With only provider tools, such as Google Search, Gemini gets no tool config.
529- **Ollama**: Ollama has no tool choice. See [Ollama](../adapters/ollama#tool-choice).
530- **CLI-style adapters**: each page says which values work. See [Claude Code](../adapters/claude-code#tool-choice), [Codex](../adapters/codex#tool-choice), [OpenCode](../adapters/opencode#tool-choice), [Grok Build](../adapters/grok-build#tool-choice), and [ACP-compatible](../adapters/acp-compatible#tool-choice).
531​
532## Progress Events and Runtime Context
533​
534A 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.):
535​
536```typescript
537import { toolDefinition } from "@tanstack/ai";
538import { z } from "zod";
539​
540type ImportContext = {
541 db: {
542 read(source: string): Promise<unknown[]>;
543 write(rows: unknown[]): Promise<void>;
544 };
545};
546​
547const importDataDef = toolDefinition({
548 name: "import_data",
549 description: "Import data from a source",
550 inputSchema: z.object({ source: z.string() }),
551 outputSchema: z.object({ imported: z.number() }),
552});
553​
554const importData = importDataDef.server<ImportContext>(async (input, { context, emitCustomEvent }) => {
555 emitCustomEvent("progress", { step: 1, total: 3 });
556 const rows = await context.db.read(input.source);
557​
558 emitCustomEvent("progress", { step: 2, total: 3 });
559 await context.db.write(rows);
560​
561 emitCustomEvent("progress", { step: 3, total: 3 });
562 return { imported: rows.length };
563});
564```
565​
566Each `emitCustomEvent` call flushes through durability immediately, so the
567client can show progress while the tool still runs. Pass `{ batch: true }`
568only for a high-volume stream. See [Custom Events](../protocol/custom-events).
569​
570See [Server Tools](./server-tools) for the full runtime-context pattern.
571​
572## Tool States
573​
574Tools go through different states during execution:
575​
576- `awaiting-input` - Tool call received, waiting for arguments
577- `input-streaming` - Partial arguments being streamed
578- `input-complete` - All arguments received
579- `approval-requested` - Tool requires user approval (if `needsApproval: true`)
580- `approval-responded` - User has approved/denied
581​
582Once 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.
583​
584> **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.
585​
586## Next Steps
587​
588- [Server Tools](./server-tools) - Learn about server-side tool execution
589- [Client Tools](./client-tools) - Learn about client-side tool execution
590- [Tool Approval Flow](./tool-approval) - Implement approval workflows
591- [How Tools Work](./tool-architecture) - Deep dive into the tool architecture
592- [MCP Server Tools](./mcp) - Connect to external MCP servers for additional tools