# AI SDK Human in the Loop: Approve Tool Calls Before They Run

How to add human approval to AI agent tool calls with the Vercel AI SDK: toolApproval, useChat approval UI, conditional rules, denial handling and forged-approval protection.

By Waseem Anjum · Published 2026-11-18 · https://fabwaseem.com/blog/ai-sdk-human-in-the-loop-tool-approval

> **TL;DR:** Set toolApproval: { yourTool: 'user-approval' } on streamText, render Approve and Deny buttons for the approval-requested state with addToolApprovalResponse, and pass sendAutomaticallyWhen so the chat continues after the click. Use an async function to gate only risky inputs.

AI SDK human in the loop means pausing an agent before a tool runs, showing the user what the model wants to do, and continuing only after they click Approve. In the Vercel AI SDK you set this up with the `toolApproval` option on `streamText`, then handle the `approval-requested` state in `useChat` with `addToolApprovalResponse`. This guide walks through the server, the client, conditional rules and the mistakes that make an approval flow silently stop working.

## Why add human approval to AI tool calls?

An agent that can send email, refund an order or delete a file will eventually do it at the wrong moment. Approval gates are the cheapest control against that. The model still decides *what* to call, but a person decides *whether* it runs.

The AI SDK documentation describes the gate as sitting between the model's tool call and the tool's execution. Approval-gated tools still run on your server, and only after the user approves. If you also expose tools over MCP, pair this with the guidance in [MCP security](https://fabwaseem.com/blog/mcp-security).

![Flow of an AI SDK tool call from model request to approval request, user decision and execute or deny](https://res.cloudinary.com/wasicloudinary/image/upload/v1794975133/fabwaseem/projects/ue7y7x5bkf54ptabwvmk.jpg)

## Which AI SDK version do you need?

The current stable line on npm is `ai` 7.x. In that line the docs configure approval with `toolApproval` on `generateText`, `streamText` or `ToolLoopAgent`. The older tool-level `needsApproval: true` property is documented as deprecated, so new code should not use it. Some older guides, including the AI SDK cookbook recipe, still show `needsApproval`; it keeps working but is deprecated. If you are still on an earlier major, start with [the AI SDK 7 migration guide](https://fabwaseem.com/blog/ai-sdk-7-migration).

## How do you set up tool approval on the server?

Define the tool as usual, then name it in `toolApproval` with the status `'user-approval'`. This follows the official [Chatbot Tool Usage](https://ai-sdk.dev/docs/ai-sdk-ui/chatbot-tool-usage) example:

```ts
// app/api/chat/route.ts
import {
  createUIMessageStreamResponse,
  streamText,
  tool,
  toUIMessageStream,
} from 'ai';
import { z } from 'zod';

export async function POST(req: Request) {
  const { messages } = await req.json();

  const result = streamText({
    model: 'anthropic/claude-sonnet-5.5',
    messages,
    tools: {
      getWeather: tool({
        description: 'Get the weather in a location',
        inputSchema: z.object({ city: z.string() }),
        execute: async ({ city }) => fetchWeather(city), // your own function
      }),
    },
    toolApproval: {
      getWeather: 'user-approval',
    },
  });

  return createUIMessageStreamResponse({
    stream: toUIMessageStream({ stream: result.stream }),
  });
}
```

Swap `getWeather` for your real tool, such as `refundOrder` or `sendEmail`. The `execute` function stays exactly where it was.

## What are the four approval statuses?

Each key in `toolApproval` takes one of four statuses, as a string or as an object with a `type` field:

| Status | What happens |
| --- | --- |
| `'not-applicable'` | Runs with no approval flow. This is the default. |
| `'approved'` | Records an automatic approval, then executes. |
| `'denied'` | Records an automatic denial and returns a denied tool output. |
| `'user-approval'` | Emits an approval request and waits for a response. |

![Four toolApproval statuses: not-applicable, approved, denied and user-approval](https://res.cloudinary.com/wasicloudinary/image/upload/v1794975034/fabwaseem/projects/t001v5ehnjvoj3cblw3y.jpg)

Object statuses accept a `reason`. For manual approval the reason goes on the request so the approver can see why a gate fired:

```ts
toolApproval: {
  runCommand: {
    type: 'user-approval',
    reason: 'filesystem changes require operator review',
  },
}
```

## How do you build the approval UI with useChat?

On the client, `useChat` exposes `addToolApprovalResponse`. Each tool call arrives as a message part whose `state` tells you where it is in the flow. You render Approve and Deny buttons while the state is `approval-requested`:

```tsx
'use client';

import { useChat } from '@ai-sdk/react';

export default function Chat() {
  const { messages, addToolApprovalResponse } = useChat();

  return (
    <>
      {messages.map(message => (
        <div key={message.id}>
          {message.parts.map(part => {
            if (part.type !== 'tool-getWeather') return null;

            switch (part.state) {
              case 'approval-requested': {
                if (part.approval.isAutomatic) {
                  return <div key={part.toolCallId}>Checking approval…</div>;
                }
                return (
                  <div key={part.toolCallId}>
                    <p>Get weather for {part.input.city}?</p>
                    {part.approval.requestReason && (
                      <p>{part.approval.requestReason}</p>
                    )}
                    <button
                      onClick={() =>
                        addToolApprovalResponse({
                          id: part.approval.id,
                          approved: true,
                        })
                      }
                    >
                      Approve
                    </button>
                    <button
                      onClick={() =>
                        addToolApprovalResponse({
                          id: part.approval.id,
                          approved: false,
                        })
                      }
                    >
                      Deny
                    </button>
                  </div>
                );
              }
              case 'approval-responded':
                return (
                  <div key={part.toolCallId}>
                    {part.approval.approved ? 'Approved' : 'Denied'}
                  </div>
                );
              case 'output-available':
                return (
                  <div key={part.toolCallId}>
                    Weather in {part.input.city}: {part.output}
                  </div>
                );
              case 'output-denied':
                return <div key={part.toolCallId}>Denied.</div>;
            }
            return null;
          })}
        </div>
      ))}
    </>
  );
}
```

The docs list three states to handle: `approval-requested` (the user must decide), `approval-responded` (a decision exists, readable from `part.approval.approved`) and `output-denied`. Call `addToolApprovalResponse` only for manual approvals. Automatic decisions have `part.approval.isAutomatic === true` and already arrive in the stream.

## Why does nothing happen after I click Approve?

This is the most common problem. Without auto-submit, nothing continues after an approval. Either call `sendMessage` yourself or pass `sendAutomaticallyWhen`:

```tsx
import { useChat } from '@ai-sdk/react';
import { lastAssistantMessageIsCompleteWithApprovalResponses } from 'ai';

const { messages, addToolApprovalResponse } = useChat({
  sendAutomaticallyWhen: lastAssistantMessageIsCompleteWithApprovalResponses,
});
```

With that in place, the message is resubmitted once every approval in the last step has an answer. The server then runs `execute` for approved calls and tells the model about denied ones.

## How do you require approval only for risky inputs?

Gating every call trains users to click Approve without reading. Make the gate conditional by passing an async function that inspects the input and returns `'user-approval'` or `undefined`:

```ts
const result = await generateText({
  model: 'anthropic/claude-sonnet-5.5',
  tools: { processPayment: paymentTool },
  toolApproval: {
    processPayment: async ({ amount }) =>
      amount > 1000 ? 'user-approval' : undefined,
  },
  prompt: 'Send $1500 to the contractor',
});
```

Per the docs, only transactions over 1000 need approval and smaller ones run automatically. You can also pass a single generic function that receives `toolCall`, `tools`, `toolsContext`, `messages` and `runtimeContext` and decides for every tool in one place.

## What happens when the user denies a tool call?

On denial the model receives an `execution-denied` tool result, including the `reason` you pass to `addToolApprovalResponse`. Left alone, a model may simply retry the same call. The docs suggest adding an instruction such as "When a tool execution is not approved, do not retry it" so the assistant explains that the action was not performed instead.

An approval `reason` behaves differently: it is recorded on the message part for your UI or audit trail and is not sent to the model. It is not a channel for passing data to a tool. If you need extra input from the user, use a client-side tool with `addToolOutput` instead.

## How do you stop a forged approval?

`useChat` resends the whole message history on every turn, so a modified client could fake an approval. For sensitive tools the docs add a server secret so the server can verify it issued the approval:

```ts
const result = streamText({
  model: 'anthropic/claude-sonnet-5.5',
  messages,
  tools: { deleteFile },
  toolApproval: { deleteFile: 'user-approval' },
  experimental_toolApprovalSecret: process.env.TOOL_APPROVAL_SECRET,
});
```

The option is prefixed `experimental_`, so pin your `ai` version and re-check the docs on upgrades.

## What about generateText and background agents?

Server-side calls do not pause. With `generateText` the call completes and returns `tool-approval-request` parts in `result.content`. You collect those, create a `tool-approval-response` for each (`approvalId`, `approved`, optional `reason`), push them as a `tool` message and call the model again. That makes manual approval a two-call flow, which suits an agent that waits for a human in Slack, a dashboard or a queue. For queue-driven agents, see [an AI automation pipeline with BullMQ](https://fabwaseem.com/blog/ai-automation-pipeline-nodejs-bullmq). Provider-executed tools ignore `toolApproval`, because it only governs tools the SDK runs locally.

## Key takeaways

- Use `toolApproval` with `'user-approval'`; the tool-level `needsApproval` is deprecated.
- Handle `approval-requested`, `approval-responded` and `output-denied` in your UI.
- Set `sendAutomaticallyWhen: lastAssistantMessageIsCompleteWithApprovalResponses` (or call `sendMessage` yourself), or nothing continues after a click.
- Gate by input (for example amount thresholds) so approvals stay meaningful.
- Tell the model not to retry denied calls.
- Add a server secret for destructive tools so a client cannot forge an approval.

## Questions

### What is human in the loop in the AI SDK?

It is a pattern where the SDK pauses before running a tool, sends an approval request to the client, and only executes the tool after a person approves. You enable it with the toolApproval option set to 'user-approval' for a tool.

### Is needsApproval deprecated in the AI SDK?

Yes. The AI SDK docs say the older tool-level needsApproval property is deprecated. Configure approval with toolApproval on generateText, streamText or ToolLoopAgent instead.

### Why does nothing happen after I click Approve in useChat?

Without auto-submit, the chat does not continue after an approval. Pass sendAutomaticallyWhen: lastAssistantMessageIsCompleteWithApprovalResponses to useChat, or call sendMessage yourself.

### How do I require approval only for some tool calls?

Pass an async function in toolApproval that inspects the tool input and returns 'user-approval' or undefined, for example approving automatically when an amount is 1000 or less.

### What does the model see when a tool call is denied?

It receives an execution-denied tool result that includes the reason passed to addToolApprovalResponse. Add an instruction telling the model not to retry unapproved tools.

### Can a user forge a tool approval?

A modified client could, because useChat resends the message history. For sensitive tools, set experimental_toolApprovalSecret on streamText so the server can verify that it issued the approval.
