Open History to see the last commit
1---
2title: Server Tools
3id: server-tools
4order: 3
5description: "Server tools in TanStack AI execute automatically with full access to databases, APIs, and environment variables. Patterns, examples, and security."
6keywords:
7 - tanstack ai
8 - server tools
9 - function calling
10 - backend tools
11 - tool execute
12 - database access
13---
14
15Server tools execute automatically when called by the LLM. They have full access to server resources like databases, APIs, and environment variables.
16
17```mermaid
18sequenceDiagram
19 participant LLM Service
20 participant Server
21 participant Tool
22 participant Database/API
24 LLM Service->>Server: tool_call chunk<br/>{name: "getUserData", args: {...}}
25 Server->>Server: Parse tool call<br/>arguments
26 Server->>Tool: execute(parsedArgs)
27 Tool->>Database/API: Query/Fetch data
28 Database/API-->>Tool: Return data
29 Tool-->>Server: Return result
30 Server->>Server: Create tool_result<br/>message
31 Server->>LLM Service: Continue chat with<br/>tool_result in history
33 Note over LLM Service: Model uses result<br/>to generate response
35 LLM Service-->>Server: Stream content chunks
36 Server-->>Server: Stream to client
37```
38
39## How It Works
40
411. **Tool Call Received**: Server receives a `tool_call` chunk from the LLM
422. **Argument Parsing**: The tool arguments (JSON string) are parsed and validated against the input schema
433. **Execution**: The tool's `execute` function is called with the parsed arguments
444. **Result Processing**: The result is:
45 - Validated against the output schema (if defined)
46 - Converted to a tool result message
47 - Added to the conversation history
485. **Continuation**: The chat continues with the tool result, allowing the LLM to generate a response based on the result
50## Automatic Execution and Approval Pauses
51
52**Automatic (Default):**
53- Server tools with an `execute` function run automatically
54- Results are added to the conversation immediately
55- No client-side handling required
56
57**Approval-gated:**
58- Tools marked `needsApproval: true` still execute automatically — but only *after* the user approves
59- The run pauses at the `approval-requested` state and resumes (executing the tool, or skipping it on denial) once the client sends an approval response
60- See [Tool Approval Flow](./tool-approval) for the full pattern
61
62## Server Tool Definition
63
64```typescript
65import { toolDefinition } from "@tanstack/ai";
66import { z } from "zod";
67import { db } from "./db";
68
69const getUserDataDef = toolDefinition({
70 name: "get_user_data",
71 description: "Get user information from the database",
72 inputSchema: z.object({
73 userId: z.string().meta({ description: "The user ID to look up" }),
74 }),
75 outputSchema: z.object({
76 name: z.string(),
77 email: z.string().email(),
78 createdAt: z.string(),
79 }),
80});
81
82const getUserData = getUserDataDef.server(async ({ userId }) => {
83 // This runs on the server - secure access to database
84 const user = await db.users.findUnique({ where: { id: userId } });
85 return {
86 name: user.name,
87 email: user.email,
88 createdAt: user.createdAt.toISOString(),
89 };
90});
91```
92
93## Defining Server Tools
94
95Server tools use the isomorphic `toolDefinition()` API with the `.server()` method:
96
97```typescript
98import { toolDefinition } from "@tanstack/ai";
99import { z } from "zod";
100import { db } from "./db";
101
102// Step 1: Define the tool schema
103const getUserDataDef = toolDefinition({
104 name: "get_user_data",
105 description: "Get user information from the database",
106 inputSchema: z.object({
107 userId: z.string().meta({ description: "The user ID to look up" }),
108 }),
109 outputSchema: z.object({
110 name: z.string(),
111 email: z.string().email(),
112 createdAt: z.string(),
113 }),
114});
115
116// Step 2: Create server implementation
117const getUserData = getUserDataDef.server(async ({ userId }) => {
118 // This runs on the server - can access database, APIs, etc.
119 const user = await db.users.findUnique({ where: { id: userId } });
120 return {
121 name: user.name,
122 email: user.email,
123 createdAt: user.createdAt.toISOString(),
124 };
125});
126
127// Example: API call tool
128const searchProductsDef = toolDefinition({
129 name: "search_products",
130 description: "Search for products in the catalog",
131 inputSchema: z.object({
132 query: z.string().meta({ description: "Search query" }),
133 limit: z.number().optional().meta({ description: "Maximum number of results" }),
134 }),
135});
136
137const searchProducts = searchProductsDef.server(async ({ query, limit = 10 }) => {
138 const response = await fetch(
139 `https://api.example.com/products?q=${query}&limit=${limit}`,
140 {
141 headers: {
142 Authorization: `Bearer ${process.env.API_KEY}`, // Server-only access
143 },
144 }
145 );
146 return await response.json();
147});
148```
149
150## Using Server Tools
151
152Pass tools to the `chat` function:
153
154```typescript
155import { chat, toServerSentEventsResponse } from "@tanstack/ai";
156import { openaiText } from "@tanstack/ai-openai";
157import { getUserData, searchProducts } from "./tools";
158
159export async function POST(request: Request) {
160 const { messages } = await request.json();
161
162 const stream = chat({
163 adapter: openaiText("gpt-5.5"),
164 messages,
165 tools: [getUserData, searchProducts],
166 });
167
168 return toServerSentEventsResponse(stream);
169}
170```
171
172## Runtime Context
173
174Server tools can receive typed runtime context as their second argument. Use this for request-scoped dependencies like authenticated users, database clients, tenant IDs, or audit loggers.
175
176```typescript
177import { chat, toolDefinition, toServerSentEventsResponse } from "@tanstack/ai";
178import { openaiText } from "@tanstack/ai-openai";
179import { z } from "zod";
180import { getSession, getDb } from "./auth";
181
182type AppContext = {
183 userId: string;
184 db: {
185 users: {
186 findUnique(args: { where: { id: string } }): Promise<{ name: string } | null>;
187 };
188 };
189};
190
191const getCurrentUser = toolDefinition({
192 name: "get_current_user",
193 description: "Get the current authenticated user",
194 inputSchema: z.object({}),
195 outputSchema: z.object({
196 name: z.string().nullable(),
197 }),
198}).server<AppContext>(async (_input, ctx) => {
199 const user = await ctx.context.db.users.findUnique({
200 where: { id: ctx.context.userId },
201 });
202
203 return { name: user?.name ?? null };
204});
205
206export async function POST(request: Request) {
207 const { messages } = await request.json();
208 // `session` and `db` come from your own app setup (auth middleware,
209 // a DB client, etc.) — they are not provided by TanStack AI.
210 const session = await getSession(request);
211 const db = getDb();
212
213 const stream = chat({
214 adapter: openaiText("gpt-5.5"),
215 messages,
216 tools: [getCurrentUser],
217 context: {
218 userId: session.user.id,
219 db,
220 },
221 });
222
223 return toServerSentEventsResponse(stream);
224}
225```
226
227If a server tool declares a context generic, `chat()` requires a compatible `context` value. Untyped tools keep working and receive `unknown` context.
228
229For middleware and client-to-server handoff patterns, see [Runtime Context](../advanced/runtime-context).
230
231## Support a host that runs long sessions
232
233Some hosts run `chat()` for a long session. Such a host can restart a run after a crash, or move a slow tool call to the background. Two fields let your tool work with that host. `chat()` alone does not use them.
234
235- `replay` tells the host if it can run the tool again after a crash. `'safe'` means the host can run it again. Use it for a read or another call that you can repeat. When a second run is not safe, omit the field or set `'never'`. The host then writes a note for the model. `chat()` does not read `replay`.
236- The host sets `detach` when it can move this call to the background. Pass the work to `detach`. Race that promise with the work. When the host moves the call, `detach` resolves to a short string. The work keeps running. When the work ends, the host tells the model the result. An object `outputSchema` rejects that string. `chat()` does not set `detach`.
237
238```typescript
239import { toolDefinition } from "@tanstack/ai";
240import { z } from "zod";
241
242declare function runBuild(target: string): Promise<string>;
243
244const build = toolDefinition({
245 name: "build",
246 description: "Build a target",
247 inputSchema: z.object({ target: z.string() }),
248 replay: "safe",
249}).server(async ({ target }, ctx) => {
250 const work = runBuild(target);
251 return ctx?.detach ? Promise.race([work, ctx.detach(work)]) : work;
252});
253```
254
255## Tool Organization Pattern
256
257For better organization, define tool schemas and implementations separately:
258
259```typescript ignore
260// tools/definitions.ts
261import { toolDefinition } from "@tanstack/ai";
262import { z } from "zod";
263
264export const getUserDataDef = toolDefinition({
265 name: "get_user_data",
266 description: "Get user information",
267 inputSchema: z.object({
268 userId: z.string(),
269 }),
270 outputSchema: z.object({
271 name: z.string(),
272 email: z.string(),
273 }),
274});
275
276export const searchProductsDef = toolDefinition({
277 name: "search_products",
278 description: "Search products",
279 inputSchema: z.object({
280 query: z.string(),
281 }),
282});
283
284// tools/server.ts
285import { getUserDataDef, searchProductsDef } from "./definitions";
286import { db } from "@/lib/db";
287
288export const getUserData = getUserDataDef.server(async ({ userId }) => {
289 const user = await db.users.findUnique({ where: { id: userId } });
290 return { name: user.name, email: user.email };
291});
292
293export const searchProducts = searchProductsDef.server(async ({ query }) => {
294 const products = await db.products.search(query);
295 return products;
296});
297
298// api/chat/route.ts
299import { chat } from "@tanstack/ai";
300import { openaiText } from "@tanstack/ai-openai";
301import { getUserData, searchProducts } from "@/tools/server";
302
303const stream = chat({
304 adapter: openaiText("gpt-5.5"),
305 messages,
306 tools: [getUserData, searchProducts],
307});
308```
309
310## Automatic Execution
311
312Server tools are automatically executed when the model calls them. The SDK:
313
3141. Receives the tool call from the model
3152. Executes the tool's `execute` function
3163. Adds the result to the conversation
3174. Continues the chat with the tool result
318
319You don't need to manually handle tool execution - it's automatic!
320
321## Error Handling
322
323Tools should handle errors gracefully:
324
325```typescript
326import { toolDefinition } from "@tanstack/ai";
327import { z } from "zod";
328import { db } from "./db";
329
330const getUserDataDef = toolDefinition({
331 name: "get_user_data",
332 description: "Get user information",
333 inputSchema: z.object({
334 userId: z.string(),
335 }),
336 outputSchema: z.object({
337 name: z.string().optional(),
338 email: z.string().optional(),
339 error: z.string().optional(),
340 }),
341});
342
343const getUserData = getUserDataDef.server(async ({ userId }) => {
344 try {
345 const user = await db.users.findUnique({ where: { id: userId } });
346 if (!user) {
347 return { error: "User not found" };
348 }
349 return { name: user.name, email: user.email };
350 } catch {
351 return { error: "Failed to fetch user data" };
352 }
353});
354```
355
356**Throwing vs. returning an error:** if your `.server()` function throws, the SDK catches it and surfaces it as a tool-result *error* (the model sees the failure but you lose control over the message). Returning a structured `{ error }` shape keeps the model in control of how to recover and is usually preferable. Either way, when an `outputSchema` is defined the returned value is validated against it (Zod) before being added to the conversation — so include the `error` field in your `outputSchema` if you return it.
357
358Malformed JSON arguments and input validation failures (Standard Schema or JSON Schema) are also surfaced as tool-result errors. The tool implementation is not called, and the agent loop can return the error to the model so it can repair the tool call. This also applies to Chat Completions tools with no required input fields.
359
360The `inputSchema` checks the input just before the tool runs:
361
362- The check runs after approval edits and after middleware `onBeforeToolCall`. An approval edit that does not fit the schema stops the resume with an `invalid-edited-args` error. A middleware change that does not fit becomes a tool error.
363- An async validator is awaited.
364- The tool gets the schema's output, so a transform such as `z.string().transform(Number)` applies once.
365
366Models often send a value with the wrong type, such as `"5"` for a number. The check repairs these against the schema before it fails the call:
367
368| The model sends | The schema wants | The tool gets |
369| --- | --- | --- |
370| `"5"` | `number` or `integer` | `5` |
371| `"true"` | `boolean` | `true` |
372| `5` | `string` | `"5"` |
373| `null` for an optional field | a type with no `null` | no field |
374| `null` for a required field | `string`, `number`, or `boolean` | `""`, `0`, or `false` |
375
376- A JSON Schema tool, and an MCP tool, gets the repair when its input fails the check. A valid input runs as it is.
377- A Standard Schema that can export JSON Schema (Zod, ArkType, Valibot) runs first as written. If it fails, the input is repaired and the schema runs again. If it still fails, the error shows the issues of the first run.
378- An input that cannot be repaired, such as `"many"` for a number, becomes a tool error.
379
380### Turn off or replace the repair
381
382Sometimes the built-in repair is the wrong move. Maybe your tool moves money, and a `null` must never turn into `0`. Or maybe your model makes the same odd mistake every time, and you know the fix. Pass `repairToolInput` to `chat()` and take control.
383
384Turn the repair off, so a bad input always goes back to the model as an error:
385
386```typescript
387import { chat, toServerSentEventsResponse } from "@tanstack/ai";
388import { openaiText } from "@tanstack/ai-openai";
389import { transferFunds } from "./tools";
390
391export async function POST(request: Request) {
392 const { messages } = await request.json();
393
394 const stream = chat({
395 adapter: openaiText("gpt-6.1-sol"),
396 messages,
397 tools: [transferFunds],
398 repairToolInput: false,
399 });
400
401 return toServerSentEventsResponse(stream);
402}
403```
404
405Or write your own fix. Say the model keeps sending `"limit": "all"` to `search_products`. Map it to a number:
406
407```typescript
408import { chat, toServerSentEventsResponse } from "@tanstack/ai";
409import { openaiText } from "@tanstack/ai-openai";
410import { searchProducts } from "./tools";
411
412export async function POST(request: Request) {
413 const { messages } = await request.json();
414
415 const stream = chat({
416 adapter: openaiText("gpt-6.1-sol"),
417 messages,
418 tools: [searchProducts],
419 repairToolInput: ({ tool, input }) => {
420 if (
421 tool.name === "search_products" &&
422 typeof input === "object" &&
423 input !== null &&
424 "limit" in input &&
425 input.limit === "all"
426 ) {
427 return { ...input, limit: 100 };
428 }
429 return undefined;
430 },
431 });
432
433 return toServerSentEventsResponse(stream);
434}
435```
436
437How your function works:
438
439- It runs only when an input fails the check. A valid input never gets to it.
440- It replaces the built-in repair. A `"5"` stays a string unless your function changes it.
441- It gets `tool`, `toolCall`, `input`, and `error` (the validation error).
442- Return the new input, and the check runs again. If that check fails, the model gets the original error.
443- Return `undefined` to send the original error to the model. If your function throws, the model gets the thrown message.
444
445The option works the same for Standard Schema tools, JSON Schema tools, and MCP tools.
446
447A client tool, or a tool that waits for approval, is checked twice: once before it goes out, and once when it comes back. So your function can run twice for one call.
448
449## Using JSON Schema
450
451If you have existing JSON Schema definitions or prefer not to use Zod, you can define tool schemas using raw JSON Schema objects:
452
453```typescript
454import { toolDefinition } from "@tanstack/ai";
455import type { JSONSchema } from "@tanstack/ai";
456import { db } from "./db";
457
458const inputSchema: JSONSchema = {
459 type: "object",
460 properties: {
461 userId: {
462 type: "string",
463 description: "The user ID to look up",
464 },
465 },
466 required: ["userId"],
467};
468
469const outputSchema: JSONSchema = {
470 type: "object",
471 properties: {
472 name: { type: "string" },
473 email: { type: "string" },
474 },
475 required: ["name", "email"],
476};
477
478const getUserDataDef = toolDefinition({
479 name: "get_user_data",
480 description: "Get user information from the database",
481 inputSchema,
482 outputSchema,
483});
484
485// With a raw JSON Schema, args is typed as `unknown` — narrow it before use
486const getUserData = getUserDataDef.server(async (args) => {
487 if (typeof args !== "object" || args === null || !("userId" in args)) {
488 throw new Error("Invalid input: expected a userId");
489 }
490 const user = await db.users.findUnique({ where: { id: String(args.userId) } });
491 return { name: user.name, email: user.email };
492});
493```
494
495The JSON Schema checks each call before the tool runs. MCP tools get the same check. If the input does not fit, the call gets a tool error, and the error names each failed field:
496
497```text
498Input validation failed for tool get_user_data: #: Instance does not have required property "userId".
499```
500
501- The check uses the draft that `$schema` names: draft-04, draft-07, 2019-09, or 2020-12. With no `$schema`, it uses 2020-12.
502- Got an OpenAPI 3.0 schema? `nullable: true` works, so that field can be `null`. A boolean `exclusiveMinimum` or `exclusiveMaximum` works too.
503- The check does not test `format` (such as `uri` or `email`). A `format` only describes the value.
504- The check does not compile code, so it also runs on Cloudflare Workers.
505- `args` is still typed as `unknown`. A Zod schema gives you the type too.
506
507> **Tip:** 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).
508
509## Best Practices
510
5111. **Keep tools focused** - Each tool should do one thing well
5122. **Validate inputs** - The `inputSchema` checks every call. A Zod schema also gives you types
5133. **Handle errors** - Return meaningful error messages
5144. **Use descriptions** - Clear descriptions help the model use tools correctly
5155. **Secure sensitive operations** - Never expose API keys or secrets to the client
516
517## Next Steps
518
519- [Client Tools](./client-tools) - Learn about client-side tool execution
520- [Tool Approval Flow](./tool-approval) - Add approval workflows for sensitive operations