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

server-tools.md

397 lines12.2 KB

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);
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);
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## Tool Organization Pattern
232​
233For better organization, define tool schemas and implementations separately:
234​
235```typescript ignore
236// tools/definitions.ts
237import { toolDefinition } from "@tanstack/ai";
238import { z } from "zod";
239​
240export const getUserDataDef = toolDefinition({
241 name: "get_user_data",
242 description: "Get user information",
243 inputSchema: z.object({
244 userId: z.string(),
245 }),
246 outputSchema: z.object({
247 name: z.string(),
248 email: z.string(),
249 }),
250});
251​
252export const searchProductsDef = toolDefinition({
253 name: "search_products",
254 description: "Search products",
255 inputSchema: z.object({
256 query: z.string(),
257 }),
258});
259​
260// tools/server.ts
261import { getUserDataDef, searchProductsDef } from "./definitions";
262import { db } from "@/lib/db";
263​
264export const getUserData = getUserDataDef.server(async ({ userId }) => {
265 const user = await db.users.findUnique({ where: { id: userId } });
266 return { name: user.name, email: user.email };
267});
268​
269export const searchProducts = searchProductsDef.server(async ({ query }) => {
270 const products = await db.products.search(query);
271 return products;
272});
273​
274// api/chat/route.ts
275import { chat } from "@tanstack/ai";
276import { openaiText } from "@tanstack/ai-openai";
277import { getUserData, searchProducts } from "@/tools/server";
278​
279const stream = chat({
280 adapter: openaiText("gpt-5.5"),
281 messages,
282 tools: [getUserData, searchProducts],
283});
284```
285​
286## Automatic Execution
287​
288Server tools are automatically executed when the model calls them. The SDK:
289​
2901. Receives the tool call from the model
2912. Executes the tool's `execute` function
2923. Adds the result to the conversation
2934. Continues the chat with the tool result
294​
295You don't need to manually handle tool execution - it's automatic!
296​
297## Error Handling
298​
299Tools should handle errors gracefully:
300​
301```typescript
302import { toolDefinition } from "@tanstack/ai";
303import { z } from "zod";
304import { db } from "./db";
305​
306const getUserDataDef = toolDefinition({
307 name: "get_user_data",
308 description: "Get user information",
309 inputSchema: z.object({
310 userId: z.string(),
311 }),
312 outputSchema: z.object({
313 name: z.string().optional(),
314 email: z.string().optional(),
315 error: z.string().optional(),
316 }),
317});
318​
319const getUserData = getUserDataDef.server(async ({ userId }) => {
320 try {
321 const user = await db.users.findUnique({ where: { id: userId } });
322 if (!user) {
323 return { error: "User not found" };
324 }
325 return { name: user.name, email: user.email };
326 } catch {
327 return { error: "Failed to fetch user data" };
328 }
329});
330```
331​
332**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.
333​
334Malformed JSON arguments and Standard Schema input validation failures 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.
335​
336## Using JSON Schema
337​
338If you have existing JSON Schema definitions or prefer not to use Zod, you can define tool schemas using raw JSON Schema objects:
339​
340```typescript
341import { toolDefinition } from "@tanstack/ai";
342import type { JSONSchema } from "@tanstack/ai";
343import { db } from "./db";
344​
345const inputSchema: JSONSchema = {
346 type: "object",
347 properties: {
348 userId: {
349 type: "string",
350 description: "The user ID to look up",
351 },
352 },
353 required: ["userId"],
354};
355​
356const outputSchema: JSONSchema = {
357 type: "object",
358 properties: {
359 name: { type: "string" },
360 email: { type: "string" },
361 },
362 required: ["name", "email"],
363};
364​
365const getUserDataDef = toolDefinition({
366 name: "get_user_data",
367 description: "Get user information from the database",
368 inputSchema,
369 outputSchema,
370});
371​
372// With a raw JSON Schema, args is typed as `unknown` — narrow it before use
373const getUserData = getUserDataDef.server(async (args) => {
374 if (typeof args !== "object" || args === null || !("userId" in args)) {
375 throw new Error("Invalid input: expected a userId");
376 }
377 const user = await db.users.findUnique({ where: { id: String(args.userId) } });
378 return { name: user.name, email: user.email };
379});
380```
381​
382> **Note:** JSON Schema tools skip runtime validation. Zod schemas are recommended for full type safety and validation.
383​
384> **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).
385​
386## Best Practices
387​
3881. **Keep tools focused** - Each tool should do one thing well
3892. **Validate inputs** - Use Zod schemas to ensure type safety (JSON Schema skips validation)
3903. **Handle errors** - Return meaningful error messages
3914. **Use descriptions** - Clear descriptions help the model use tools correctly
3925. **Secure sensitive operations** - Never expose API keys or secrets to the client
393​
394## Next Steps
395​
396- [Client Tools](./client-tools) - Learn about client-side tool execution
397- [Tool Approval Flow](./tool-approval) - Add approval workflows for sensitive operations