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 or a middleware change that does not fit the schema becomes a tool error. The resume goes on, the tool does not run, and the model gets the input error as the result of that call.
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- `get` and `getOptional`: read a capability that a middleware of the run provides. See [Read a middleware capability](#read-a-middleware-capability).
185
186Use `emitCustomEvent` to show progress:
187
188```typescript
189import { toolDefinition } from "@tanstack/ai";
190import { z } from "zod";
191
192type ImportContext = {
193 db: {
194 read(source: string): Promise<unknown[]>;
195 write(rows: unknown[]): Promise<void>;
196 };
197};
198
199const importData = toolDefinition({
200 name: "import_data",
201 description: "Import data from a source",
202 inputSchema: z.object({ source: z.string() }),
203 outputSchema: z.object({ imported: z.number() }),
204}).server<ImportContext>(async (input, { context, emitCustomEvent }) => {
205 emitCustomEvent("progress", { step: 1, total: 3 });
206 const rows = await context.db.read(input.source);
207
208 emitCustomEvent("progress", { step: 2, total: 3 });
209 await context.db.write(rows);
210
211 emitCustomEvent("progress", { step: 3, total: 3 });
212 return { imported: rows.length };
213});
214```
215
216Each `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).
217
218## Read a middleware capability
219
220Call `context.get(capability)` in a server tool. It returns the value that a middleware of the run provides, with the type of the capability.
221
222```typescript
223import {
224 chat,
225 createCapability,
226 defineChatMiddleware,
227 toolDefinition,
228} from "@tanstack/ai";
229import { openaiText } from "@tanstack/ai-openai";
230import { z } from "zod";
231
232const tenantCapability = createCapability<{ id: string }>()("tenant");
233
234const withTenant = defineChatMiddleware({
235 name: "with-tenant",
236 provides: [tenantCapability],
237 setup(ctx) {
238 ctx.provide(tenantCapability, { id: "acme" });
239 },
240});
241
242const whoAmI = toolDefinition({
243 name: "who_am_i",
244 description: "Return the tenant of this run",
245 inputSchema: z.object({}),
246}).server(async (_input, context) => {
247 // `tenant` has the type { id: string }
248 const tenant = context?.get?.(tenantCapability);
249 return tenant?.id ?? "unknown";
250});
251
252const stream = chat({
253 adapter: openaiText("gpt-6.1-sol"),
254 messages: [{ role: "user", content: "Who am I?" }],
255 threadId: "thread-1",
256 tools: [whoAmI],
257 middleware: [withTenant],
258});
259```
260
261- `get` throws if no middleware provides the capability.
262- `getOptional` returns `undefined` instead.
263- `chat()` sets both. They are missing when the tool runs outside a chat, so use `context?.get?.(...)`.
264
265To create and provide a capability, see [Capabilities](../advanced/middleware-advanced#capabilities). A harness turn gives the same accessors to its tools.
266
267## Support a host that runs long sessions
268
269Some 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.
270
271- `replay` tells the host if it can run the tool again after a crash.
272 - `'safe'` means the host can run it again. Use it for a read or another call that you can repeat.
273 - When a second run is not safe, omit the field or set `'never'`. The host then writes a note for the model.
274 - `chat()` does not read `replay`.
275- `detach` is set by the host when it can move this call to the background.
276 - Pass the work to `detach`, and race that promise with the work.
277 - 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.
278 - An object `outputSchema` rejects that string.
279 - `chat()` does not set `detach`.
280
281```typescript
282import { toolDefinition } from "@tanstack/ai";
283import { z } from "zod";
284
285declare function runBuild(target: string): Promise<string>;
286
287const build = toolDefinition({
288 name: "build",
289 description: "Build a target",
290 inputSchema: z.object({ target: z.string() }),
291 replay: "safe",
292}).server(async ({ target }, ctx) => {
293 const work = runBuild(target);
294 return ctx?.detach ? Promise.race([work, ctx.detach(work)]) : work;
295});
296```
297
298## Keep definitions and implementations in separate files
299
300Put the definitions in a shared file. Then the server and the client can import the same definitions:
301
302```typescript ignore
303// tools/definitions.ts
304import { toolDefinition } from "@tanstack/ai";
305import { z } from "zod";
306
307export const getUserDataDef = toolDefinition({
308 name: "get_user_data",
309 description: "Get user information",
310 inputSchema: z.object({
311 userId: z.string(),
312 }),
313 outputSchema: z.object({
314 name: z.string(),
315 email: z.string(),
316 }),
317});
318
319export const searchProductsDef = toolDefinition({
320 name: "search_products",
321 description: "Search products",
322 inputSchema: z.object({
323 query: z.string(),
324 }),
325});
326
327// tools/server.ts
328import { getUserDataDef, searchProductsDef } from "./definitions";
329import { db } from "@/lib/db";
330
331export const getUserData = getUserDataDef.server(async ({ userId }) => {
332 const user = await db.users.findUnique({ where: { id: userId } });
333 return { name: user.name, email: user.email };
334});
335
336export const searchProducts = searchProductsDef.server(async ({ query }) => {
337 const products = await db.products.search(query);
338 return products;
339});
340
341// api/chat/route.ts
342import { chat } from "@tanstack/ai";
343import { openaiText } from "@tanstack/ai-openai";
344import { getUserData, searchProducts } from "@/tools/server";
345
346const stream = chat({
347 adapter: openaiText("gpt-6.1-sol"),
348 messages,
349 threadId: "thread-1",
350 tools: [getUserData, searchProducts],
351});
352```
353
354## Tips for good server tools
355
3561. **Keep tools focused.** One tool does one job.
3572. **Write clear descriptions.** The model reads them to pick a tool.
3583. **Return errors as data.** Give the model a message that it can act on.
3594. **Keep secrets on the server.** API keys stay in `.server()` code and never go to the client.
3605. **Prefer a Zod schema.** It checks every call and also gives you types.