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

server-tools.md

219 lines6.4 KB

1---
2title: Server Tools
3id: server-tools
4order: 3
5description: "Run a tool on your server, where it can read your database, call APIs with secret keys, and use environment variables. TanStack AI runs it when the model calls it."
6keywords:
7 - tanstack ai
8 - server tools
9 - function calling
10 - backend tools
11 - tool execute
12 - database access
13---
14​
15A server tool runs on your server. Use it for a database row, a secret, or an environment variable. That code never runs in the browser.
16​
17Write the function with `.server()`, and `chat()` runs it each time the model calls it.
18​
19## Add a server tool
20​
21### 1. Define the tool
22​
23This tool looks up an order. The `Map` stands in for your database:
24​
25```typescript
26// tools.ts
27import { toolDefinition } from "@tanstack/ai";
28import { z } from "zod";
29​
30const orders = new Map([
31 ["1001", { status: "shipped", eta: "2026-10-24" }],
32 ["1002", { status: "processing", eta: "2026-10-28" }],
33]);
34​
35export const getOrderStatus = toolDefinition({
36 name: "get_order_status",
37 description: "Get the shipping status of an order by its order number",
38 inputSchema: z.object({
39 orderId: z.string().meta({ description: "The order number, for example 1001" }),
40 }),
41 outputSchema: z.object({
42 found: z.boolean(),
43 status: z.string().optional(),
44 eta: z.string().optional(),
45 }),
46}).server(async ({ orderId }) => {
47 // This runs on your server. Query your database here.
48 const order = orders.get(orderId);
49 if (!order) {
50 return { found: false };
51 }
52 return { found: true, ...order };
53});
54```
55​
56### 2. Pass the tool to `chat()`
57​
58```typescript
59// api/chat.ts
60import {
61 chat,
62 chatParamsFromRequest,
63 toServerSentEventsResponse,
64} from "@tanstack/ai";
65import { openaiText } from "@tanstack/ai-openai";
66import { getOrderStatus } from "./tools";
67​
68export async function POST(request: Request) {
69 const { messages, threadId, runId } = await chatParamsFromRequest(request);
70​
71 const stream = chat({
72 adapter: openaiText("gpt-6.1-sol"),
73 messages,
74 threadId,
75 runId,
76 tools: [getOrderStatus],
77 });
78​
79 return toServerSentEventsResponse(stream);
81```
82​
83### 3. Try it
84​
85Ask your chat "Where is order 1001?" The model calls `get_order_status` and answers that the order shipped and arrives on 2026-10-24.
86​
87You did not change the client. Server tools need no client code.
88​
89## How it works
90​
91```mermaid
92sequenceDiagram
93 participant LLM Service
94 participant Server
95 participant Tool
96 participant Database/API
97​
98 LLM Service->>Server: tool_call chunk<br/>{name: "get_order_status", args: {...}}
99 Server->>Server: Parse and check<br/>the arguments
100 Server->>Tool: execute(parsedArgs)
101 Tool->>Database/API: Query/Fetch data
102 Database/API-->>Tool: Return data
103 Tool-->>Server: Return result
104 Server->>Server: Create tool_result<br/>message
105 Server->>LLM Service: Continue chat with<br/>tool_result in history
106​
107 Note over LLM Service: Model uses result<br/>to generate response
108​
109 LLM Service-->>Server: Stream content chunks
110 Server-->>Server: Stream to client
111```
112​
1131. The model sends a tool call. The arguments are a JSON string.
1142. `chat()` parses the arguments and checks them against `inputSchema`.
1153. `chat()` runs your `.server()` function with the parsed input.
1164. If you set an `outputSchema`, `chat()` checks the result against it. Then it adds the result to the conversation.
1175. The model reads the result and continues.
118​
119If the tool has `needsApproval: true`, the run pauses before step 3 until the user says yes. See [Tool Approval Flow](./tool-approval).
120​
121## Use the signed-in user
122​
123A tool often needs data from the request, such as the user ID or a database client. Pass it as `context` on `chat()`. The tool gets it as the second argument:
124​
125```typescript
126import { chat, toolDefinition, toServerSentEventsResponse } from "@tanstack/ai";
127import { openaiText } from "@tanstack/ai-openai";
128import { z } from "zod";
129import { getSession, getDb } from "./auth";
130​
131type AppContext = {
132 userId: string;
133 db: {
134 users: {
135 findUnique(args: { where: { id: string } }): Promise<{ name: string } | null>;
136 };
137 };
138};
139​
140const getCurrentUser = toolDefinition({
141 name: "get_current_user",
142 description: "Get the current authenticated user",
143 inputSchema: z.object({}),
144 outputSchema: z.object({
145 name: z.string().nullable(),
146 }),
147}).server<AppContext>(async (_input, ctx) => {
148 const user = await ctx.context.db.users.findUnique({
149 where: { id: ctx.context.userId },
150 });
151​
152 return { name: user?.name ?? null };
153});
154​
155export async function POST(request: Request) {
156 const { messages, threadId } = await request.json();
157 // `getSession` and `getDb` are your own app code, not part of TanStack AI.
158 const session = await getSession(request);
159 const db = getDb();
160​
161 const stream = chat({
162 adapter: openaiText("gpt-6.1-sol"),
163 messages,
164 threadId,
165 tools: [getCurrentUser],
166 context: {
167 userId: session.user.id,
168 db,
169 },
170 });
171​
172 return toServerSentEventsResponse(stream);
174```
175​
176- If a tool sets a context type, such as `.server<AppContext>()`, `chat()` requires a `context` that matches it.
177- A tool with no context type gets `unknown` context.
178​
179For middleware and values that come from the client, see [Runtime Context](../advanced/runtime-context).
180​
181## Return an error the model can use
182​
183If a lookup fails, return the error as data. The model can then tell the user or try again:
184​
185```typescript
186import { toolDefinition } from "@tanstack/ai";
187import { z } from "zod";
188import { db } from "./db";
189​
190const getUserData = toolDefinition({
191 name: "get_user_data",
192 description: "Get user information",
193 inputSchema: z.object({
194 userId: z.string(),
195 }),
196 outputSchema: z.object({
197 name: z.string().optional(),
198 email: z.string().optional(),
199 error: z.string().optional(),
200 }),
201}).server(async ({ userId }) => {
202 try {
203 const user = await db.users.findUnique({ where: { id: userId } });
204 if (!user) {
205 return { error: "User not found" };
206 }
207 return { name: user.name, email: user.email };
208 } catch {
209 return { error: "Failed to fetch user data" };
210 }
211});
212```
213​
214- **Return `{ error }`**: you write the message that the model sees. Put the `error` field in `outputSchema`, because `chat()` checks the result against it.
215- **Throw**: `chat()` catches the error and sends a tool error to the model. You do not control the message.
216​
217## Advanced
218​
219For input checks and repair, JSON Schema tools, progress events, long-running hosts, and file layout, see [Server Tools: Advanced](./server-tools-advanced).