Open History to see the last commit
1---
2title: Tool Architecture
3id: tool-architecture
4order: 2
5description: "How a tool call moves between the browser, your server, and the model, and the states that a tool call goes through. Use it to show tool progress and to debug tools."
6keywords:
7 - tanstack ai
8 - tool architecture
9 - server tools
10 - client tools
11 - call states
12 - approval flow
13 - agentic cycle
14---
15
16A tool call moves from the model, to your server or the browser, then back as a result. This page shows that path.
17
18Each tool call is a `tool-call` part in the assistant message. It has a `state` that changes as the call moves forward. The result arrives as a sibling `tool-result` part.
19
20## Show tool progress in your UI
21
22Render the two part types next to your text parts:
23
24```tsx
25import type { MessagePart } from "@tanstack/ai-client";
26
27export function ToolStatus({ part }: { part: MessagePart }) {
28 if (part.type === "tool-call") {
29 switch (part.state) {
30 case "awaiting-input":
31 case "input-streaming":
32 return <p>Preparing {part.name}...</p>;
33 case "approval-requested":
34 return <p>{part.name} waits for your approval</p>;
35 case "input-complete":
36 return <p>Running {part.name}...</p>;
37 default:
38 // The tool-result part below shows the outcome.
39 return null;
40 }
41 }
42
43 if (part.type === "tool-result") {
44 if (part.state === "error") {
45 return <p>Tool failed: {part.error}</p>;
46 }
47 return <p>Tool done</p>;
48 }
49
50 return null;
51}
52```
53
54Use it in your message list, for example `message.parts.map((part, index) => <ToolStatus key={index} part={part} />)`. While the model runs your tool, you now see "Running get_weather...", then "Tool done".
55
56To get typed `part.name`, `part.input`, and `part.output`, pass your tools to the chat hook. See [Client Tools](./client-tools#show-the-tool-call-in-your-ui).
57
58## How a tool call flows
59
60```mermaid
61sequenceDiagram
62 participant User
63 participant Browser
64 participant Server
65 participant LLM Service
66
67 User->>Browser: Types message
68 Browser->>Server: POST /api/chat<br/>{messages, ...}
69 Server->>Server: Build tool definitions<br/>from tool array
70 Server->>LLM Service: Send request with:<br/>- messages<br/>- tool definitions<br/>- model config
71
72 Note over LLM Service: Model analyzes tools<br/>and decides to use one
73
74 LLM Service-->>Server: Stream chunks:<br/>tool_call, content, done
75 Server-->>Browser: Forward chunks via SSE/HTTP
76 Browser->>Browser: Parse chunks &<br/>update UI
77 Browser->>User: Show response
78```
79
801. The user types a message.
812. The browser sends a POST request to your route. It has the conversation history (`messages`) and optional extra data.
823. Your route calls `chat()`. `chat()` turns each tool into the format of the provider and sends the request to the model.
834. The model reads the conversation and the tools. It decides whether to call a tool, and with which arguments.
845. The model streams back chunks:
85 - `tool_call` chunks with the tool name and arguments.
86 - `content` chunks with text.
87 - A `done` chunk at the end.
886. Where the tool runs depends on how you defined it:
89 - A [server tool](./server-tools) runs inside `chat()`.
90 - A [client tool](./client-tools) runs in the browser, and the result comes back in a new request.
91 - A tool with `needsApproval: true` waits for the user first. See [Tool Approval Flow](./tool-approval).
927. `chat()` sends the result to the model, and the model continues. This loop is the [agentic cycle](../chat/agentic-cycle).
938. The browser updates the UI as each chunk arrives.
94
95## Advanced
96
97### Call states
98
99The `state` of a `tool-call` part:
100
101| State | Meaning | What to show |
102|-------|---------|--------------|
103| `awaiting-input` | The call started. No arguments yet. | A loading state |
104| `input-streaming` | Partial arguments arrive. | Progress |
105| `input-complete` | All arguments are in. | The tool is about to run |
106| `approval-requested` | The call waits for the user. | The approval UI |
107| `approval-responded` | The user approved or denied. | Running, or a denied note |
108| `complete` | The result arrived. | The result |
109| `error` | The call failed or was denied. | The error |
110
111When the result arrives, the call part also gets `output`.
112
113### Result states
114
115The `state` of the sibling `tool-result` part:
116
117| State | Meaning | What to show |
118|-------|---------|--------------|
119| `streaming` | Reserved for streamed results. Not used yet. | Progress |
120| `complete` | The result is complete. | The result |
121| `error` | An error occurred before or during the run. `part.error` has the message. | The error |
122
123A denied or cancelled result is also `error`. Read `part.outcome` to tell it apart from a failure. See [Tool Approval Flow](./tool-approval#tell-a-denial-from-a-failure).
124
125### The full lifecycle
126
127```mermaid
128stateDiagram-v2
129 state "tool-call part (ToolCallState)" as Call {
130 [*] --> AwaitingInput: tool_call received
131 AwaitingInput --> InputStreaming: partial arguments
132 InputStreaming --> InputComplete: all arguments received
133 InputComplete --> ApprovalRequested: needsApproval=true
134 ApprovalRequested --> ApprovalResponded: user approves / denies
135 }
136 InputComplete --> ResultComplete: needsApproval=false, success
137 InputComplete --> ResultError: parsing, validation, or execution error
138 ApprovalResponded --> ResultComplete: approved + success (output set)
139 ApprovalResponded --> ResultError: approved + error
140 ApprovalResponded --> Denied: user denied (no execution)
141 state "tool-result part" as Results {
142 ResultComplete: complete
143 ResultError: error
144 }
145 ResultComplete --> [*]
146 ResultError --> [*]
147 Denied --> [*]
148```
149
150### The approval flow
151
152```mermaid
153sequenceDiagram
154 participant User
155 participant Client
156 participant Server
157 participant LLM
158 participant Tool
159
160 LLM->>Server: tool_call: send_email
161 Server->>Server: Check needsApproval
162 Server->>Client: RUN_FINISHED with an interrupt
163 Client->>Client: Show approval UI
164 User->>Client: Clicks "Approve"
165 Client->>Server: resolveInterrupt, new run resumes
166 Server->>Tool: execute(args)
167 Tool-->>Server: result
168 Server->>LLM: tool_result
169 LLM-->>Client: Generate response
170```
171
172For the code, see [Tool Approval Flow](./tool-approval).
173
174### Server and client tools in one task
175
176The model can chain tools that run in different places. Here, a server tool reads preferences from the database, and a client tool applies them to the page:
177
178```typescript
179import { toolDefinition } from "@tanstack/ai";
180import { z } from "zod";
181import { db } from "./db";
182import { i18n } from "./i18n";
183
184// Server: read the preferences from the database
185const fetchUserPrefsDef = toolDefinition({
186 name: "fetch_user_preferences",
187 description: "Get user preferences from server",
188 inputSchema: z.object({
189 userId: z.string(),
190 }),
191});
192
193const fetchUserPreferences = fetchUserPrefsDef.server(async ({ userId }) => {
194 const prefs = await db.userPreferences.findUnique({ where: { userId } });
195 return prefs;
196});
197
198// Client: apply the preferences to the UI
199const applyPrefsDef = toolDefinition({
200 name: "apply_preferences",
201 description: "Apply user preferences to the UI",
202 inputSchema: z.object({
203 theme: z.string(),
204 language: z.string(),
205 }),
206});
207
208const applyPreferences = applyPrefsDef.client(async ({ theme, language }) => {
209 document.body.className = theme;
210 i18n.changeLanguage(language);
211 return { applied: true };
212});
213
214// The model can call fetch_user_preferences on the server,
215// then apply_preferences in the browser with the result.
216```
217
218Pass `fetchUserPreferences` and `applyPrefsDef` to `chat()` on the server, and `applyPreferences` to the chat hook.
219
220### Parallel tool calls
221
222The model can call several tools in one turn:
223
224```mermaid
225graph TD
226 A[LLM decides to call 3 tools] --> B[tool_call index: 0]
227 A --> C[tool_call index: 1]
228 A --> D[tool_call index: 2]
229 B --> E[Execute in parallel]
230 C --> E
231 D --> E
232 E --> F[Collect all results]
233 F --> G[Continue with results]
234```
235
236For example, "Compare the weather in NYC, SF, and LA" can give three calls: `get_weather` for each city. All three run at the same time, then the model writes the comparison.
237
238The server tools of one model turn start together. 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).
239
240### Design tips
241
242Tool design:
243
244- **One job per tool.** Small tools are easier for the model to pick.
245- **Clear descriptions.** The model reads them to decide when to call the tool.
246- **Schemas for input and output.** Zod schemas give you checks and types.
247- **Errors as data.** Return a clear error message instead of throwing.
248- **Safe repeats.** Make a tool safe to call more than once with the same input.
249
250Security:
251
252- **Sensitive work on the server.** Keys and private data stay in server tools.
253- **Approval for destructive actions.** Use `needsApproval`.
254- **Input checks.** Every call goes through `inputSchema`. Add your own business rules in the tool.
255- **Rate limits.** Limit expensive tools.
256- **Audit logs.** Log tool runs for debugging and security.
257
258Performance:
259
260- **Caching.** If the data allows it, cache tool results.
261- **Parallel calls.** Let independent tools run together.
262- **Progress events.** Stream progress for long tools. See [Server Tools: Advanced](./server-tools-advanced#stream-progress-while-a-tool-runs).
263- **Timeouts.** Set timeouts on external API calls.
264- **Lazy tools.** Make rarely used tools lazy. The model then gets them only on request. See [Lazy Tool Discovery](./lazy-tool-discovery).
265
266The streaming protocol under all of this is AG-UI. See the [AG-UI docs](https://docs.ag-ui.com/introduction).