Open History to see the last commit
1---
2title: "Server Tools: Advanced"
3id: server-tools-advanced
4order: 3
5description: "Input checks and repair, JSON Schema tools, progress events, long-running hosts, and file layout for TanStack AI server tools."
6keywords:
7 - tanstack ai
8 - server tools
9 - repairToolInput
10 - json schema
11 - emitCustomEvent
12 - tool validation
13---
14
15This page is for when your [server tool](./server-tools) works and you need more control. Each section stands alone.
16
17## How `chat()` checks the input
18
19The `inputSchema` checks the input right before the tool runs:
20
21- 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.
22- An async validator is awaited.
23- The tool gets the output of the schema, so a transform such as `z.string().transform(Number)` applies once.
24
25Malformed JSON arguments and failed input checks (Standard Schema or JSON Schema) become tool errors. The tool does not run. The agent loop can send the error back to the model, so the model can correct the call. This also applies to Chat Completions tools with no required input fields.
26
27For OpenAI-compatible providers, an omitted `.optional()` field is absent when your tool runs. A `.nullable()` field keeps `null`.
28
29### The built-in repair
30
31Models often send a value with the wrong type, such as `"5"` for a number. Before the check fails the call, it repairs these values against the schema:
32
33| The model sends | The schema wants | The tool gets |
34| --- | --- | --- |
35| `"5"` | `number` or `integer` | `5` |
36| `"true"` | `boolean` | `true` |
37| `5` | `string` | `"5"` |
38| `null` for an optional field | a type with no `null` | no field |
39| `null` for a required field | `string`, `number`, or `boolean` | `""`, `0`, or `false` |
40
41- A JSON Schema tool, and an MCP tool, gets the repair when its input fails the check. A valid input runs as it is.
42- 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.
43- An input that cannot be repaired, such as `"many"` for a number, becomes a tool error.
44
45## Turn off or replace the repair
46
47Sometimes the built-in repair is wrong for your tool. 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()`.
48
49Turn the repair off, so a bad input always goes back to the model as an error:
50
51```typescript
52import { chat, toServerSentEventsResponse } from "@tanstack/ai";
53import { openaiText } from "@tanstack/ai-openai";
54import { transferFunds } from "./tools";
55
56export async function POST(request: Request) {
57 const { messages, threadId } = await request.json();
58
59 const stream = chat({
60 adapter: openaiText("gpt-6.1-sol"),
61 messages,
62 threadId,
63 tools: [transferFunds],
64 repairToolInput: false,
65 });
66
67 return toServerSentEventsResponse(stream);
68}
69```
70
71Or write your own fix. Say the model keeps sending `"limit": "all"` to `search_products`. Map it to a number:
72
73```typescript
74import { chat, toServerSentEventsResponse } from "@tanstack/ai";
75import { openaiText } from "@tanstack/ai-openai";
76import { searchProducts } from "./tools";
77
78export async function POST(request: Request) {
79 const { messages, threadId } = await request.json();
80
81 const stream = chat({
82 adapter: openaiText("gpt-6.1-sol"),
83 messages,
84 threadId,
85 tools: [searchProducts],
86 repairToolInput: ({ tool, input }) => {
87 if (
88 tool.name === "search_products" &&
89 typeof input === "object" &&
90 input !== null &&
91 "limit" in input &&
92 input.limit === "all"
93 ) {
94 return { ...input, limit: 100 };
95 }
96 return undefined;
97 },
98 });
99
100 return toServerSentEventsResponse(stream);
101}
102```
103
104How your function works:
105
106- It runs only when an input fails the check. A valid input never gets to it.
107- It replaces the built-in repair. A `"5"` stays a string unless your function changes it.
108- It gets `tool`, `toolCall`, `input`, and `error` (the validation error).
109- Return the new input, and the check runs again. If that check fails, the model gets the original error.
110- Return `undefined` to send the original error to the model. If your function throws, the model gets the thrown message.
111
112The option works the same for Standard Schema tools, JSON Schema tools, and MCP tools.
113
114A client tool, or a tool that waits for approval, is checked two times: once before it goes out, and once when it comes back. So your function can run two times for one call.
115
116## Use a JSON Schema
117
118Do you already have JSON Schema definitions? Pass them as `inputSchema` and `outputSchema`:
119
120```typescript
121import { toolDefinition } from "@tanstack/ai";
122import type { JSONSchema } from "@tanstack/ai";
123import { db } from "./db";
124
125const inputSchema: JSONSchema = {
126 type: "object",
127 properties: {
128 userId: {
129 type: "string",
130 description: "The user ID to look up",
131 },
132 },
133 required: ["userId"],
134};
135
136const outputSchema: JSONSchema = {
137 type: "object",
138 properties: {
139 name: { type: "string" },
140 email: { type: "string" },
141 },
142 required: ["name", "email"],
143};
144
145const getUserDataDef = toolDefinition({
146 name: "get_user_data",
147 description: "Get user information from the database",
148 inputSchema,
149 outputSchema,
150});
151
152// With a raw JSON Schema, args is typed as `unknown`. Narrow it before use.
153const getUserData = getUserDataDef.server(async (args) => {
154 if (typeof args !== "object" || args === null || !("userId" in args)) {
155 throw new Error("Invalid input: expected a userId");
156 }
157 const user = await db.users.findUnique({ where: { id: String(args.userId) } });
158 return { name: user.name, email: user.email };
159});
160```
161
162TypeScript cannot get types from a JSON Schema, so `args` is `unknown`. A Zod schema gives you the types too.
163
164The 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:
165
166```text
167Input validation failed for tool get_user_data: #: Instance does not have required property "userId".
168```
169
170- The check uses the draft that `$schema` names: draft-04, draft-07, 2019-09, or 2020-12. With no `$schema`, it uses 2020-12.
171- OpenAPI 3.0 schemas work. `nullable: true` lets the field be `null`. A boolean `exclusiveMinimum` or `exclusiveMaximum` works too.
172- The check does not test `format` (such as `uri` or `email`). A `format` only describes the value.
173- The check does not compile code, so it also runs on Cloudflare Workers.
174
175## Stream progress while a tool runs
176
177The second argument of a `.server()` function is the `ToolExecutionContext`:
178
179- `context`: your runtime context from `chat({ context })`.
180- `toolCallId`: the ID of this tool call.
181- `threadId`: the thread id of the chat run. Use it to keep tool state for each conversation. It is missing when the tool runs outside a chat (an MCP server, WebMCP, or a direct `execute()` call).
182- `abortSignal`: aborts when the run aborts. Pass it to long work, so the work stops too.
183- `emitCustomEvent`: sends a custom event to the client while the tool runs.
184
185Use `emitCustomEvent` to show progress:
186
187```typescript
188import { toolDefinition } from "@tanstack/ai";
189import { z } from "zod";
190
191type ImportContext = {
192 db: {
193 read(source: string): Promise<unknown[]>;
194 write(rows: unknown[]): Promise<void>;
195 };
196};
197
198const importData = toolDefinition({
199 name: "import_data",
200 description: "Import data from a source",
201 inputSchema: z.object({ source: z.string() }),
202 outputSchema: z.object({ imported: z.number() }),
203}).server<ImportContext>(async (input, { context, emitCustomEvent }) => {
204 emitCustomEvent("progress", { step: 1, total: 3 });
205 const rows = await context.db.read(input.source);
206
207 emitCustomEvent("progress", { step: 2, total: 3 });
208 await context.db.write(rows);
209
210 emitCustomEvent("progress", { step: 3, total: 3 });
211 return { imported: rows.length };
212});
213```
214
215Each `emitCustomEvent` call flushes through durability at once, so the client can show progress while the tool still runs. Pass `{ batch: true }` only for a high-volume stream. To read the events on the client, see [Custom Events](../protocol/custom-events).
216
217## Support a host that runs long sessions
218
219Some 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.
220
221- `replay` tells the host if it can run the tool again after a crash.
222 - `'safe'` means the host can run it again. Use it for a read or another call that you can repeat.
223 - When a second run is not safe, omit the field or set `'never'`. The host then writes a note for the model.
224 - `chat()` does not read `replay`.
225- `detach` is set by the host when it can move this call to the background.
226 - Pass the work to `detach`, and race that promise with the work.
227 - 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.
228 - An object `outputSchema` rejects that string.
229 - `chat()` does not set `detach`.
230
231```typescript
232import { toolDefinition } from "@tanstack/ai";
233import { z } from "zod";
234
235declare function runBuild(target: string): Promise<string>;
236
237const build = toolDefinition({
238 name: "build",
239 description: "Build a target",
240 inputSchema: z.object({ target: z.string() }),
241 replay: "safe",
242}).server(async ({ target }, ctx) => {
243 const work = runBuild(target);
244 return ctx?.detach ? Promise.race([work, ctx.detach(work)]) : work;
245});
246```
247
248## Keep definitions and implementations in separate files
249
250Put the definitions in a shared file. Then the server and the client can import the same definitions:
251
252```typescript ignore
253// tools/definitions.ts
254import { toolDefinition } from "@tanstack/ai";
255import { z } from "zod";
256
257export const getUserDataDef = toolDefinition({
258 name: "get_user_data",
259 description: "Get user information",
260 inputSchema: z.object({
261 userId: z.string(),
262 }),
263 outputSchema: z.object({
264 name: z.string(),
265 email: z.string(),
266 }),
267});
268
269export const searchProductsDef = toolDefinition({
270 name: "search_products",
271 description: "Search products",
272 inputSchema: z.object({
273 query: z.string(),
274 }),
275});
276
277// tools/server.ts
278import { getUserDataDef, searchProductsDef } from "./definitions";
279import { db } from "@/lib/db";
280
281export const getUserData = getUserDataDef.server(async ({ userId }) => {
282 const user = await db.users.findUnique({ where: { id: userId } });
283 return { name: user.name, email: user.email };
284});
285
286export const searchProducts = searchProductsDef.server(async ({ query }) => {
287 const products = await db.products.search(query);
288 return products;
289});
290
291// api/chat/route.ts
292import { chat } from "@tanstack/ai";
293import { openaiText } from "@tanstack/ai-openai";
294import { getUserData, searchProducts } from "@/tools/server";
295
296const stream = chat({
297 adapter: openaiText("gpt-6.1-sol"),
298 messages,
299 threadId: "thread-1",
300 tools: [getUserData, searchProducts],
301});
302```
303
304## Tips for good server tools
305
3061. **Keep tools focused.** One tool does one job.
3072. **Write clear descriptions.** The model reads them to pick a tool.
3083. **Return errors as data.** Give the model a message that it can act on.
3094. **Keep secrets on the server.** API keys stay in `.server()` code and never go to the client.
3105. **Prefer a Zod schema.** It checks every call and also gives you types.