Open History to see the last commit
1---
2title: Tool Architecture
3id: tool-architecture
4order: 2
5description: "The architecture behind TanStack AI's tool system — server tools, client tools, call states, approval flow, and the agentic cycle."
6keywords:
7 - tanstack ai
8 - tool architecture
9 - server tools
10 - client tools
11 - call states
12 - approval flow
13 - agentic cycle
14---
15
16The TanStack AI tool system provides a powerful, flexible architecture for enabling AI agents to interact with external systems:
17
18- [**Server Tools**](./server-tools) execute securely on the backend with automatic handling
19- [**Client Tools**](./client-tools) execute in the browser for UI updates and local operations
20- [**The Agentic Cycle**](../chat/agentic-cycle) enables multi-step reasoning and complex workflows
21- [**Tool States**](#call-states) provide real-time feedback and enable robust UIs
22- [**Approval Flow**](#approval-flow) gives users control over sensitive operations
23This architecture enables building sophisticated AI applications that can:
24
25- Fetch data from APIs and databases
26- Perform calculations and transformations
27- Update UIs and manage state
28- Execute multi-step workflows
29- Require user approval for sensitive actions
30
31## Call Flow: Client to LLM Service
32
33When a user sends a message that requires tool usage, the following flow occurs:
34
35```mermaid
36sequenceDiagram
37 participant User
38 participant Browser
39 participant Server
40 participant LLM Service
42 User->>Browser: Types message
43 Browser->>Server: POST /api/chat<br/>{messages, ...}
44 Server->>Server: Build tool definitions<br/>from tool array
45 Server->>LLM Service: Send request with:<br/>- messages<br/>- tool definitions<br/>- model config
47 Note over LLM Service: Model analyzes tools<br/>and decides to use one
49 LLM Service-->>Server: Stream chunks:<br/>tool_call, content, done
50 Server-->>Browser: Forward chunks via SSE/HTTP
51 Browser->>Browser: Parse chunks &<br/>update UI
52 Browser->>User: Show response
53```
54
55### Step-by-Step Breakdown
56
571. **User Input**: The user types a message in the chat interface
582. **Client Request**: The browser sends a POST request to the server with:
59 - Current conversation history (`messages`)
60 - Optional data payload (`body`)
613. **Server Processing**: The server:
62 - Receives the request
63 - Extracts messages from the request body
64 - Converts tool definitions into the LLM's expected format
65 - Sends the request to the LLM service (OpenAI, Anthropic, etc.)
664. **LLM Decision**: The LLM service:
67 - Analyzes the conversation and available tools
68 - Decides whether to call a tool based on the user's request
69 - Generates tool calls with arguments
705. **Streaming Response**: The LLM streams back chunks:
71 - `tool_call` chunks with tool name and arguments
72 - `content` chunks with text responses
73 - `done` chunk when complete
746. **Client Updates**: The browser receives chunks and updates the UI in real-time
75
76### Code Example
77
78**Server (API Route):**
79
80```typescript
81import { chat, toServerSentEventsResponse } from "@tanstack/ai";
82import { openaiText } from "@tanstack/ai-openai";
83import { getWeather, sendEmail } from "./tools";
84
85export async function POST(request: Request) {
86 const { messages } = await request.json();
87
88 // Create streaming chat with tools
89 const stream = chat({
90 adapter: openaiText("gpt-5.5"),
91 messages,
92 tools: [getWeather, sendEmail], // Tool definitions passed here
93 });
94
95 return toServerSentEventsResponse(stream);
96}
97```
98
99**Client (React Component):**
100
101```tsx
102import { useState } from "react";
103import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
104
105function ChatComponent() {
106 const [input, setInput] = useState("");
107 const { messages, sendMessage, isLoading } = useChat({
108 connection: fetchServerSentEvents("/api/chat"),
109 });
110
111 return (
112 <div>
113 {messages.map((message) => (
114 <div key={message.id}>{/* Render message */}</div>
115 ))}
116 <form
117 onSubmit={(e) => {
118 e.preventDefault();
119 sendMessage(input);
120 setInput("");
121 }}
122 >
123 <input value={input} onChange={(e) => setInput(e.target.value)} />
124 <button type="submit" disabled={isLoading}>
125 Send
126 </button>
127 </form>
128 </div>
129 );
130}
131```
132
133## States and Lifecycle
134
135Tools progress through different states during their lifecycle. Understanding these states helps build robust UIs and debug tool execution.
136
137> **Two parts, two state sets — this page is the canonical reference.** Call states (`awaiting-input`, `input-streaming`, `input-complete`, `approval-requested`, `approval-responded`) live on the **`tool-call`** part as `part.state`. There is no `complete`/`error`/`executing`/`cancelled` value on the call part. The *result* lives on a separate sibling **`tool-result`** part whose own `state` is `streaming`, `complete`, or `error`; the resolved value is also mirrored onto the call part's `part.output`.
138
139The diagram below is conceptual: the nodes after `approval-responded` (executing, success, error, cancelled) are **not** `ToolCallState` values — they correspond to the sibling `tool-result` part's state (`complete` / `error`) and the call part's `output` field.
140
141```mermaid
142stateDiagram-v2
143 state "tool-call part (ToolCallState)" as Call {
144 [*] --> AwaitingInput: tool_call received
145 AwaitingInput --> InputStreaming: partial arguments
146 InputStreaming --> InputComplete: all arguments received
147 InputComplete --> ApprovalRequested: needsApproval=true
148 ApprovalRequested --> ApprovalResponded: user approves / denies
149 }
150 InputComplete --> ResultComplete: needsApproval=false, success
151 InputComplete --> ResultError: parsing, validation, or execution error
152 ApprovalResponded --> ResultComplete: approved + success (output set)
153 ApprovalResponded --> ResultError: approved + error
154 ApprovalResponded --> Denied: user denied (no execution)
155 state "tool-result part" as Results {
156 ResultComplete: complete
157 ResultError: error
158 }
159 ResultComplete --> [*]
160 ResultError --> [*]
161 Denied --> [*]
162```
163
164### Call States
165
166| State | Description | Client Action |
167|-------|-------------|---------------|
168| `awaiting-input` | Tool call received, no arguments yet | Show loading |
169| `input-streaming` | Partial arguments being received | Show progress |
170| `input-complete` | All arguments received | Ready to execute |
171| `approval-requested` | Waiting for user approval | Show approval UI |
172| `approval-responded` | User has approved/denied | Execute or cancel |
173
174### Result States
175
176| State | Description | Client Action |
177|-------|-------------|---------------|
178| `streaming` | Result being streamed (future feature) | Show progress |
179| `complete` | Result is complete | Show result |
180| `error` | Error occurred before or during execution | Show error message |
181
182### Monitoring Tool States in React
183
184```tsx
185import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
186import { createChatClientOptions } from "@tanstack/ai-client";
187import { getWeather, sendEmail } from "./tools";
188import { ApprovalUI } from "./approval-ui";
189
190// Wiring `tools` is what lets `part.name` / `part.input` / `part.output`
191// narrow to each tool's types below.
192const chatOptions = createChatClientOptions({
193 connection: fetchServerSentEvents("/api/chat"),
194 tools: [getWeather, sendEmail],
195});
196
197function ChatComponent() {
198 const { messages } = useChat(chatOptions);
199
200 return (
201 <div>
202 {messages.map((message) => (
203 <div key={message.id}>
204 {message.parts.map((part) => {
205 if (part.type === "tool-call") {
206 return (
207 <div key={part.id} className="tool-status">
208 {/* Show state-specific UI */}
209 {part.state === "awaiting-input" && (
210 <div>🔄 Calling {part.name}...</div>
211 )}
212 {part.state === "input-streaming" && (
213 <div>📥 Receiving arguments...</div>
214 )}
215 {part.state === "input-complete" && (
216 <div>✓ Arguments ready</div>
217 )}
218 {part.state === "approval-requested" && (
219 <ApprovalUI part={part} />
220 )}
221 </div>
222 );
223 }
224 if (part.type === "tool-result") {
225 return (
226 <div key={part.toolCallId}>
227 {part.state === "complete" && (
228 <div>✓ Tool completed</div>
229 )}
230 {part.state === "error" && (
231 <div>❌ Error: {part.error}</div>
232 )}
233 </div>
234 );
235 }
236 return null;
237 })}
238 </div>
239 ))}
240 </div>
241 );
242}
243```
244
245### Approval Flow
246
247For sensitive operations, tools can require user approval before execution:
248
249```mermaid
250sequenceDiagram
251 participant User
252 participant Client
253 participant Server
254 participant LLM
255 participant Tool
257 LLM->>Server: tool_call: send_email
258 Server->>Server: Check needsApproval
259 Server->>Client: approval-requested chunk
260 Client->>Client: Show approval UI
261 User->>Client: Clicks "Approve"
262 Client->>Server: POST approval response
263 Server->>Tool: execute(args)
264 Tool-->>Server: result
265 Server->>LLM: tool_result
266 LLM-->>Client: Generate response
267```
268
269**Define tool with approval:**
270
271```typescript
272import { toolDefinition } from "@tanstack/ai";
273import { z } from "zod";
274import { emailService } from "./email-service";
275
276const sendEmailDef = toolDefinition({
277 name: "send_email",
278 description: "Send an email",
279 inputSchema: z.object({
280 to: z.string().email(),
281 subject: z.string(),
282 body: z.string(),
283 }),
284 needsApproval: true, // Requires user approval
285});
286
287const sendEmail = sendEmailDef.server(async ({ to, subject, body }) => {
288 await emailService.send({ to, subject, body });
289 return { success: true };
290});
291```
292
293**Handle approval in client:**
294
295```tsx ignore
296const { messages, addToolApprovalResponse } = useChat({
297 connection: fetchServerSentEvents("/api/chat"),
298});
299
300// In your render (guard `type` and `approval` so `part.approval.id` is safe):
301{part.type === "tool-call" &&
302 part.state === "approval-requested" &&
303 part.approval && (
304 <div>
305 <p>Approve sending email to {part.input.to}?</p>
306 <button
307 onClick={() =>
308 addToolApprovalResponse({
309 id: part.approval.id,
310 approved: true,
311 })
312 }
313 >
314 Approve
315 </button>
316 <button
317 onClick={() =>
318 addToolApprovalResponse({
319 id: part.approval.id,
320 approved: false,
321 })
322 }
323 >
324 Deny
325 </button>
326 </div>
327 )}
328```
329
330### Hybrid Tools (Server + Client)
331
332Some tools need to execute in both environments:
333
334```typescript
335import { toolDefinition } from "@tanstack/ai";
336import { z } from "zod";
337import { db } from "./db";
338import { i18n } from "./i18n";
339
340// Server: Fetch data from database
341const fetchUserPrefsDef = toolDefinition({
342 name: "fetch_user_preferences",
343 description: "Get user preferences from server",
344 inputSchema: z.object({
345 userId: z.string(),
346 }),
347});
348
349const fetchUserPreferences = fetchUserPrefsDef.server(async ({ userId }) => {
350 const prefs = await db.userPreferences.findUnique({ where: { userId } });
351 return prefs;
352});
353
354// Client: Apply preferences to UI
355const applyPrefsDef = toolDefinition({
356 name: "apply_preferences",
357 description: "Apply user preferences to the UI",
358 inputSchema: z.object({
359 theme: z.string(),
360 language: z.string(),
361 }),
362});
363
364// On client, create client implementation
365const applyPreferences = applyPrefsDef.client(async ({ theme, language }) => {
366 // Update UI state with preferences
367 document.body.className = theme;
368 i18n.changeLanguage(language);
369 return { applied: true };
370});
371
372// Usage: LLM can chain these together
373// 1. Call fetchUserPreferences (server)
374// 2. Call applyPreferences with the result (client)
375```
376
377### Parallel Tool Execution
378
379The LLM can call multiple tools in parallel for efficiency:
380
381```mermaid
382graph TD
383 A[LLM decides to call 3 tools] --> B[tool_call index: 0]
384 A --> C[tool_call index: 1]
385 A --> D[tool_call index: 2]
386 B --> E[Execute in parallel]
387 C --> E
388 D --> E
389 E --> F[Collect all results]
390 F --> G[Continue with results]
391```
392
393**Example:**
394
395```
396User: "Compare the weather in NYC, SF, and LA"
397
398LLM calls:
399- get_weather({city: "NYC"}) [index: 0]
400- get_weather({city: "SF"}) [index: 1]
401- get_weather({city: "LA"}) [index: 2]
402
403All execute simultaneously, then LLM generates comparison.
404```
405
406The server tools of one model turn start together, and the model gets their results in the order of its calls. To run them one at a time, see [Run tools one at a time](./tools#run-tools-one-at-a-time).
407
408## Best Practices
409
410### Tool Design
411
412- **Single Responsibility**: Each tool should do one thing well
413- **Clear Descriptions**: Help the LLM understand when to use the tool
414- **Type Safety**: Use Zod schemas for input/output validation
415- **Error Handling**: Return meaningful error messages, don't throw
416- **Idempotency**: Tools should be safe to call multiple times
417
418### Security
419
420- **Server vs Client**: Put sensitive operations on the server
421- **Approval Flow**: Use `needsApproval` for destructive actions
422- **Input Validation**: Always validate tool inputs
423- **Rate Limiting**: Implement rate limits for expensive tools
424- **Audit Logs**: Log tool executions for debugging and security
425
426### Performance
427
428- **Caching**: Cache tool results when appropriate
429- **Parallel Execution**: Enable parallel tool calls when possible
430- **Streaming**: Use streaming for long-running operations
431- **Timeouts**: Set timeouts for external API calls
432- **Lazy Loading**: Load tools only when needed
433
434
435## Next Steps
436
437- [Tools Overview](./tools) - Basic tool concepts and examples
438- [Server Tools](./server-tools) - Deep dive into server-side tools
439- [Client Tools](./client-tools) - Deep dive into client-side tools
440- [Tool Approval Flow](./tool-approval) - Implementing approval workflows
441- [AG-UI protocol](https://docs.ag-ui.com/introduction) - Understanding the streaming protocol