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

tool-approval.md

328 lines10.6 KB

1---
2title: Tool Approval Flow
3id: tool-approval-flow
4order: 5
5description: 'Require user approval before executing sensitive tools in TanStack AI — approval states, deny flows, and batched approvals with needsApproval.'
6keywords:
7 - tanstack ai
8 - tool approval
9 - needsApproval
10 - user consent
11 - sensitive tools
12 - approval flow
13 - human-in-the-loop
14---
15​
16The tool approval flow allows you to require user approval before executing sensitive tools, giving users control over actions like sending emails, making purchases, or deleting data. A tool call moves through the `ToolCallState` lifecycle:
17​
18The current client API exposes approvals as bound AG-UI interrupts. For the
19complete server/client lifecycle, atomic batch controls, generic interrupts,
20and recovery, see [Interrupts](../interrupts/overview). For deprecated API mapping,
21see [Migrate to AG-UI interrupts](../interrupts/migration).
22​
231. **`awaiting-input`** — Tool call started, no arguments yet
242. **`input-streaming`** — Arguments arriving incrementally
253. **`input-complete`** — All arguments received
264. **`approval-requested`** — Waiting for user approval (only if `needsApproval: true`)
275. **`approval-responded`** — User approved or denied
28​
29After `approval-responded` the call executes (if approved). Although `complete` exists in the `ToolCallState` union, the runtime never transitions the tool-call part to it — the result surfaces as a populated `part.output` plus a sibling `tool-result` part whose own state is `complete` or `error`.
30​
31Approvals run ephemerally: the run resumes from the full client message
32history that the browser sends back, so a stateless route needs no server
33storage to rebuild the paused call.
34​
35When a tool requires approval, the typical flow is:
36​
371. Model calls the tool
382. Tool execution is paused
393. User is prompted to approve or deny
404. Tool executes (if approved) or produces a denied/cancelled result
415. Conversation continues with the result
42​
43## Resolve an approval interrupt
44​
45Without an `approvalSchema`, use the boolean shorthand. Approval uses the
46original tool input by default:
47​
48```ts ignore
49const approval = interrupts.find(
50 (interrupt) => interrupt.kind === 'tool-approval',
52​
53if (approval?.kind === 'tool-approval') {
54 approval.resolveInterrupt(true)
56```
57​
58An `approvalSchema` can define separate application payloads for approval and
59rejection:
60​
61```ts
62import { toolDefinition } from '@tanstack/ai'
63import { z } from 'zod'
64​
65const transferDefinition = toolDefinition({
66 name: 'transfer',
67 description: 'Transfer funds',
68 needsApproval: true,
69 inputSchema: z.object({
70 amount: z.number().positive(),
71 recipient: z.string(),
72 }),
73 approvalSchema: {
74 approve: z.object({ note: z.string() }),
75 reject: z.object({ reason: z.string() }),
76 },
77})
78```
79​
80Keep branch data under `payload`. Approved arguments can optionally be replaced
81in full with `editedArgs`; rejection never accepts edits:
82​
83```ts ignore
84approval.resolveInterrupt(true, {
85 editedArgs: { amount: 12, recipient: 'Ada' },
86 payload: { note: 'Reviewed' },
87})
88​
89approval.resolveInterrupt(false, {
90 payload: { reason: 'Policy limit' },
91})
92```
93​
94Denial and cancellation are different. `resolveInterrupt(false, ...)` records a
95resolved rejection for the continuation. `cancel()` is payloadless and
96does not select the reject schema:
97​
98```ts ignore
99approval.cancel()
100```
101​
102A singleton submits after its valid resolution. Multiple items stage until all
103are valid, then submit atomically. Use root `resolveInterrupts(...)` for one
104synchronous batch transaction. See [Multiple Interrupts](../interrupts/multiple).
105​
106## Enabling Approval
107​
108Tools can be marked as requiring approval by setting `needsApproval: true` in the definition:
109​
110```typescript
111import { toolDefinition } from '@tanstack/ai'
112import { z } from 'zod'
113import { emailService } from './email-service'
114​
115// Step 1: Define tool with approval requirement
116const sendEmailDef = toolDefinition({
117 name: 'send_email',
118 description: 'Send an email to a recipient',
119 inputSchema: z.object({
120 to: z.string().email(),
121 subject: z.string(),
122 body: z.string(),
123 }),
124 outputSchema: z.object({
125 success: z.boolean(),
126 messageId: z.string(),
127 }),
128 needsApproval: true, // This tool requires approval
129})
130​
131// Step 2: Create server implementation
132const sendEmail = sendEmailDef.server(async ({ to, subject, body }) => {
133 // Only executes if approved
134 await emailService.send({ to, subject, body })
135 return { success: true, messageId: '...' }
136})
137```
138​
139## Server-Side Approval
140​
141On the server, tools with `needsApproval: true` will pause execution and wait for approval:
142​
143```typescript
144import { chat, toServerSentEventsResponse } from '@tanstack/ai'
145import { openaiText } from '@tanstack/ai-openai'
146import { sendEmail } from './tools'
147​
148export async function POST(request: Request) {
149 const { messages } = await request.json()
150​
151 const stream = chat({
152 adapter: openaiText('gpt-5.5'),
153 messages,
154 tools: [sendEmail],
155 })
156​
157 return toServerSentEventsResponse(stream)
159```
160​
161## Approval UI
162​
163Render pending approvals from the hook's `interrupts` array. Each
164`tool-approval` interrupt carries the tool name, the original arguments, and a
165`resolveInterrupt` you call with the user's decision. The array is already
166tool-agnostic, so one block handles every tool marked `needsApproval: true` —
167no per-tool `part.name` branch and no reading `part.approval` off a mixed union:
168​
169```tsx ignore
170import { useChat, fetchServerSentEvents } from '@tanstack/ai-react'
171import { sendEmail } from './tools'
172​
173function ChatComponent() {
174 const { messages, sendMessage, interrupts, resuming } = useChat({
175 connection: fetchServerSentEvents('/api/chat'),
176 tools: [sendEmail],
177 })
178​
179 return (
180 <div>
181 {/* ...render messages... */}
182 {interrupts.map((interrupt) =>
183 interrupt.kind === 'tool-approval' ? (
184 <div key={interrupt.id} className="approval-prompt">
185 <p>🔒 Approve {interrupt.toolName}?</p>
186 <pre>{JSON.stringify(interrupt.originalArgs, null, 2)}</pre>
187 <button
188 disabled={!interrupt.canResolve || resuming}
189 onClick={() => interrupt.resolveInterrupt(true)}
190 >
191 Approve
192 </button>
193 <button
194 disabled={!interrupt.canResolve || resuming}
195 onClick={() => interrupt.resolveInterrupt(false)}
196 >
197 Deny
198 </button>
199 </div>
200 ) : null,
201 )}
202 </div>
203 )
205```
206​
207`canResolve` stays `false` until the interrupt is bound and ready; `resuming` is
208`true` while a resolution is in flight, so gate the buttons on both.
209​
210## Migrating from `addToolApprovalResponse`
211​
212Older UIs read `part.approval` off tool-call parts and called
213`addToolApprovalResponse({ id, approved })`. That API is deprecated. Render from
214the `interrupts` array and call `resolveInterrupt` instead (see [Approval
215UI](#approval-ui) above) — it is tool-agnostic by default, so the per-tool
216narrowing the part-based pattern needed goes away. For the full mapping, see
217[Migrate to AG-UI interrupts](../interrupts/migration).
218​
219## Client Tools with Approval
220​
221Client tools can also require approval:
222​
223```typescript
224import { toolDefinition } from '@tanstack/ai'
225import { z } from 'zod'
226import { useChat, fetchServerSentEvents } from '@tanstack/ai-react'
227​
228// tools/definitions.ts
229const deleteLocalDataDef = toolDefinition({
230 name: 'delete_local_data',
231 description: 'Delete data from local storage',
232 inputSchema: z.object({
233 key: z.string(),
234 }),
235 outputSchema: z.object({
236 deleted: z.boolean(),
237 }),
238 needsApproval: true, // Requires approval even on client
239})
240​
241// Client: Create implementation
242const deleteLocalData = deleteLocalDataDef.client((input) => {
243 // This will only execute after approval
244 localStorage.removeItem(input.key)
245 return { deleted: true }
246})
247​
248const { messages, interrupts } = useChat({
249 connection: fetchServerSentEvents('/api/chat'),
250 // Pass client tools as a plain array — literal tool-name inference works
251 // without a wrapper. The approval surfaces as a `tool-approval` interrupt you
252 // resolve from `interrupts` (see Approval UI); the tool runs on approval.
253 tools: [deleteLocalData], // Automatic execution after approval
254})
255```
256​
257## Example: E-commerce Purchase
258​
259```typescript
260import { toolDefinition } from '@tanstack/ai'
261import { z } from 'zod'
262import { createOrder } from './orders'
263​
264// Define tool with approval requirement
265const purchaseItemDef = toolDefinition({
266 name: 'purchase_item',
267 description: 'Purchase an item from the store',
268 inputSchema: z.object({
269 itemId: z.string(),
270 quantity: z.number(),
271 price: z.number(),
272 }),
273 outputSchema: z.object({
274 orderId: z.string(),
275 total: z.number(),
276 }),
277 needsApproval: true,
278})
279​
280// Create server implementation
281const purchaseItem = purchaseItemDef.server(
282 async ({ itemId, quantity, price }) => {
283 const order = await createOrder({ itemId, quantity, price })
284 return { orderId: order.id, total: price * quantity }
285 },
287```
288​
289The user will see an approval prompt showing the item, quantity, and price before the purchase is made. The tool will only execute after the user approves.
290​
291## Best Practices
292​
293- **Use approval for sensitive operations** - Sending emails, making payments, deleting data
294- **Show clear information** - Display what the tool will do before approval
295- **Provide context** - Show tool arguments in a readable format
296- **Handle denial gracefully** - Check `part.outcome` when a tool is denied.
297- **Timeout handling** - Consider timeouts for approval requests
298​
299## Tool Result Outcomes
300​
301Cancelled and denied tool results keep the existing `state: 'error'` and wire
302`output-error` behavior for compatibility, but `ToolResultPart.outcome` is set
303to `'cancelled'` or `'denied'`. Ordinary tool execution failures do not set an
304`outcome`. The outcome can be produced by the user decision or by middleware
305policy.
306​
307When a result is persisted as a `ModelMessage`, the outcome is stored in
308`metadata.tanstack.toolResultOutcome` and restored to the UI part. Consumers
309should use this structured value instead of matching the fixed error text:
310​
311```tsx ignore
312const denied = message.parts.some(
313 (part) => part.type === 'tool-result' && part.outcome === 'denied',
315```
316​
317The `@tanstack/ai-client` package exposes the same value on the
318`tool-result` part. Use `part.outcome` to distinguish a denial or cancellation
319from an ordinary tool execution failure.
320​
321The structured outcome is emitted by both the AG-UI interrupt resume path and
322the deprecated `addToolApprovalResponse` path. Both paths keep the existing
323error content.
324​
325## Next Steps
326​
327- [Server Tools](./server-tools) - Learn about server-side tool execution
328- [Client Tools](./client-tools) - Learn about client-side tool execution