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

tool-approval.md

313 lines9.8 KB

1---
2title: Tool Approval Flow
3id: tool-approval-flow
4order: 5
5description: 'Make a tool wait for a yes from the user before it runs. Mark it with needsApproval, then show Approve and Deny buttons in your chat.'
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​
16Set `needsApproval: true` on a tool that sends email, pays, or deletes data. The tool runs after a person approves the call.
17​
18Add `needsApproval: true` to the tool. The run pauses before the tool runs. Your UI shows the call with Approve and Deny buttons. Then the run continues with the answer of the user.
19​
20## Add an approval
21​
22### 1. Mark the tool in a shared file
23​
24The server and the browser both import this definition:
25​
26```typescript
27// tools/definitions.ts
28import { toolDefinition } from '@tanstack/ai'
29import { z } from 'zod'
30​
31export const sendEmailDef = toolDefinition({
32 name: 'send_email',
33 description: 'Send an email to a recipient',
34 inputSchema: z.object({
35 to: z.string(),
36 subject: z.string(),
37 body: z.string(),
38 }),
39 outputSchema: z.object({
40 sent: z.boolean(),
41 }),
42 needsApproval: true,
43})
44```
45​
46### 2. Add the server function and forward the resume fields
47​
48The answer of the user arrives in a second request. Forward `parentRunId` and `resume`, so `chat()` can rebuild the paused call:
49​
50```typescript
51// api/chat.ts
52import {
53 chat,
54 chatParamsFromRequest,
55 toServerSentEventsResponse,
56 toolDefinition,
57} from '@tanstack/ai'
58import { openaiText } from '@tanstack/ai-openai'
59import { z } from 'zod'
60​
61// The same definition as tools/definitions.ts. In your app, import it from that file.
62const sendEmailDef = toolDefinition({
63 name: 'send_email',
64 description: 'Send an email to a recipient',
65 inputSchema: z.object({
66 to: z.string(),
67 subject: z.string(),
68 body: z.string(),
69 }),
70 outputSchema: z.object({
71 sent: z.boolean(),
72 }),
73 needsApproval: true,
74})
75​
76const sendEmail = sendEmailDef.server(async ({ to, subject }) => {
77 // This runs only after the user approves. Call your email service here.
78 console.log(`Sending "${subject}" to ${to}`)
79 return { sent: true }
80})
81​
82export async function POST(request: Request) {
83 const params = await chatParamsFromRequest(request)
84​
85 const stream = chat({
86 adapter: openaiText('gpt-6.1-sol'),
87 messages: params.messages,
88 threadId: params.threadId,
89 runId: params.runId,
90 parentRunId: params.parentRunId,
91 ...(params.resume ? { resume: params.resume } : {}),
92 tools: [sendEmail],
93 })
94​
95 return toServerSentEventsResponse(stream)
97```
98​
99### 3. Show the approval in your chat
100​
101Pass the definition to `useChat`, so `toolName` and `originalArgs` are typed. Pending approvals come in `interrupts`:
102​
103```tsx
104// app/chat.tsx
105import { useState } from 'react'
106import { useChat, fetchServerSentEvents } from '@tanstack/ai-react'
107import { sendEmailDef } from '../tools/definitions'
108​
109export function Chat() {
110 const [input, setInput] = useState('')
111 const { messages, sendMessage, interrupts, resuming } = useChat({
112 connection: fetchServerSentEvents('/api/chat'),
113 threadId: 'support-chat',
114 tools: [sendEmailDef],
115 })
116​
117 return (
118 <div>
119 {messages.map((message) => (
120 <div key={message.id}>
121 {message.parts.map((part, index) =>
122 part.type === 'text' ? <p key={index}>{part.content}</p> : null,
123 )}
124 </div>
125 ))}
126​
127 {interrupts.map((interrupt) =>
128 interrupt.kind === 'tool-approval' ? (
129 <div key={interrupt.id}>
130 <p>Send this email?</p>
131 <pre>{JSON.stringify(interrupt.originalArgs, null, 2)}</pre>
132 <button
133 disabled={!interrupt.canResolve || resuming}
134 onClick={() => interrupt.resolveInterrupt(true)}
135 >
136 Approve
137 </button>
138 <button
139 disabled={!interrupt.canResolve || resuming}
140 onClick={() => interrupt.resolveInterrupt(false)}
141 >
142 Deny
143 </button>
144 </div>
145 ) : null,
146 )}
147​
148 <form
149 onSubmit={(event) => {
150 event.preventDefault()
151 void sendMessage(input)
152 setInput('')
153 }}
154 >
155 <input value={input} onChange={(event) => setInput(event.target.value)} />
156 <button type="submit">Send</button>
157 </form>
158 </div>
159 )
161```
162​
163- `canResolve` is `false` until the interrupt is ready.
164- `resuming` is `true` while an answer is on its way to the server.
165​
166Disable the buttons on both.
167​
168### 4. Try it
169​
170Ask your chat "Email ada@example.com and say hello." The Approve and Deny buttons show the email.
171​
172- Click **Approve**. Your server logs the email, and the model confirms that it sent it.
173- Click **Deny**. The tool does not run. The model gets a denied result and can tell the user.
174​
175## How it works
176​
1771. The model calls `send_email`.
1782. `chat()` sees `needsApproval: true`. It does not run the tool. It ends the run with an interrupt.
1793. `useChat` puts the pending call in `interrupts`.
1804. The user clicks a button. `resolveInterrupt` sends the answer to the server in a new request.
1815. `chat()` runs the tool if the user approved, or records a denied result. Then the model continues.
182​
183No database is necessary. The browser sends the full message history back with the answer, so a stateless route can rebuild the paused call.
184​
185For the full interrupt lifecycle, batch controls, generic interrupts, and recovery, see [Interrupts](../interrupts/overview) and [Tool Approval](../interrupts/tool-approval). To move from the 0.x approval APIs, see [Migrate to AG-UI interrupts](../interrupts/migration).
186​
187## Advanced
188​
189### Tool call states
190​
191A tool call that needs approval moves through these `ToolCallState` values on the `tool-call` part:
192​
1931. `awaiting-input`: the call started, with no arguments yet.
1942. `input-streaming`: the arguments arrive.
1953. `input-complete`: all arguments are in.
1964. `approval-requested`: the call waits for the user.
1975. `approval-responded`: the user approved or denied.
198​
199When the result comes in, the call part gets `output`, and a sibling `tool-result` part shows `complete` or `error`. See [Tool Architecture](./tool-architecture#call-states).
200​
201### Approve with a note, or deny with a reason
202​
203An `approvalSchema` gives each answer its own typed data:
204​
205```ts
206import { toolDefinition } from '@tanstack/ai'
207import { z } from 'zod'
208​
209const transferDefinition = toolDefinition({
210 name: 'transfer',
211 description: 'Transfer funds',
212 needsApproval: true,
213 inputSchema: z.object({
214 amount: z.number().positive(),
215 recipient: z.string(),
216 }),
217 approvalSchema: {
218 approve: z.object({ note: z.string() }),
219 reject: z.object({ reason: z.string() }),
220 },
221})
222```
223​
224Put that data under `payload`. When the user approves, you can also replace the arguments in full with `editedArgs`. A rejection never takes edits:
225​
226```ts ignore
227approval.resolveInterrupt(true, {
228 editedArgs: { amount: 12, recipient: 'Ada' },
229 payload: { note: 'Reviewed' },
230})
231​
232approval.resolveInterrupt(false, {
233 payload: { reason: 'Policy limit' },
234})
235```
236​
237`approvalSchema` needs `needsApproval: true`. Without it, `toolDefinition()` throws. If edited arguments do not fit `inputSchema`, the resume stops with an `invalid-edited-args` error.
238​
239### Deny or cancel
240​
241Deny and cancel are different:
242​
243- `resolveInterrupt(false, ...)` records a rejection. The rejection can carry the `reject` payload.
244- `cancel()` takes no payload and does not use the `reject` schema.
245​
246```ts ignore
247approval.cancel()
248```
249​
250### Several approvals at once
251​
252- One pending approval submits as soon as it has a valid answer.
253- Several pending approvals wait until all of them have valid answers. Then they submit together.
254- To answer several in one step, call `resolveInterrupts(...)` on the hook.
255​
256See [Multiple Interrupts](../interrupts/multiple).
257​
258### Approval on a client tool
259​
260A client tool can also need approval. The approval interrupt is the same, so your UI does not change. After the user approves, the browser runs the `.client()` function:
261​
262```typescript
263import { toolDefinition } from '@tanstack/ai'
264import { z } from 'zod'
265import { useChat, fetchServerSentEvents } from '@tanstack/ai-react'
266​
267const deleteLocalDataDef = toolDefinition({
268 name: 'delete_local_data',
269 description: 'Delete data from local storage',
270 inputSchema: z.object({
271 key: z.string(),
272 }),
273 outputSchema: z.object({
274 deleted: z.boolean(),
275 }),
276 needsApproval: true,
277})
278​
279// Runs only after the user approves
280const deleteLocalData = deleteLocalDataDef.client((input) => {
281 localStorage.removeItem(input.key)
282 return { deleted: true }
283})
284​
285const { messages, interrupts } = useChat({
286 connection: fetchServerSentEvents('/api/chat'),
287 threadId: 'support-chat',
288 tools: [deleteLocalData],
289})
290```
291​
292### Tell a denial from a failure
293​
294A denied or cancelled tool result has `state: 'error'` and the wire state `output-error`. To tell it apart from a real tool failure, read `outcome` on the `tool-result` part:
295​
296- `'denied'`: the user or a middleware policy denied the call.
297- `'cancelled'`: the call was cancelled.
298- No `outcome`: a normal tool failure.
299​
300```tsx ignore
301const denied = message.parts.some(
302 (part) => part.type === 'tool-result' && part.outcome === 'denied',
304```
305​
306Use `outcome`, not the error text. When a result is saved as a `ModelMessage`, the outcome goes in `metadata.tanstack.toolResultOutcome`, and it comes back on the UI part. The AG-UI interrupt resume path also sends the outcome and keeps the error content.
307​
308### Tips for approval prompts
309​
310- **Use approval for actions that you cannot undo.** Emails, payments, and deletes are good examples.
311- **Show what will happen.** Show the arguments in a form that a person can read, not raw JSON.
312- **Handle a denial.** Read `outcome` and show the user that nothing happened.
313- **Think about time limits.** A user can leave an approval open for a long time.