# Agent approval

Agents sometimes require the same [human-in-the-loop](https://mastra.ai/docs/workflows/human-in-the-loop) oversight used in workflows when calling tools that handle sensitive operations, like deleting resources or running long processes. With agent approval you can suspend a tool call before it executes so a human can approve or decline it, or let tools suspend themselves to request additional context from the user.

## How approval works

Mastra offers two distinct mechanisms for pausing tool calls: **pre-execution approval** and **runtime suspension**.

### Pre-execution approval

Pre-execution approval pauses a tool call _before_ its `execute` function runs. The LLM still decides which tool to call and provides arguments, but `execute` doesn't run until you explicitly approve.

Two flags control this, combined with OR logic. If _either_ is `true`, the call pauses:

| Flag                        | Where to set it                   | Scope                                       |
| --------------------------- | --------------------------------- | ------------------------------------------- |
| `requireToolApproval: true` | `stream()` / `generate()` options | Pauses **every** tool call for that request |
| `requireApproval: true`     | `createTool()` definition         | Pauses calls to **that specific tool**      |

The stream emits a `tool-call-approval` chunk when a call is paused this way. You then call `approveToolCall()` or `declineToolCall()` to continue.

### Runtime suspension with `suspend()`

A tool can also pause _during_ its `execute` function by calling `suspend()`. This is useful when the tool starts running and then discovers it needs additional user input or confirmation before it can finish.

The stream emits a `tool-call-suspended` chunk with a custom payload defined by the tool's `suspendSchema`. You resume by calling `resumeStream()` with data matching the tool's `resumeSchema`.

### Storage

Agent approval uses a snapshot to capture the state of the request. Ensure you've enabled a storage provider in your main Mastra instance. If storage isn't enabled you'll see an error relating to snapshot not found.

```typescript
import { Mastra } from '@mastra/core/mastra'
import { LibSQLStore } from '@mastra/libsql'

export const mastra = new Mastra({
  storage: new LibSQLStore({
    id: 'mastra-storage',
    url: ':memory:',
  }),
})
```

## Agent-level approval

Pass `requireToolApproval: true` to `stream()` or `generate()` to pause every tool call before execution. The LLM still decides which tools to call and with what arguments but no tool runs until you approve or decline.

```typescript
const stream = await agent.stream("What's the weather in London?", {
  requireToolApproval: true,
})
```

When a tool call is paused, the stream emits a `tool-call-approval` chunk containing the `toolCallId`, `toolName`, and `args`. Use this to inspect the pending call and decide whether to approve or decline:

```typescript
for await (const chunk of stream.fullStream) {
  if (chunk.type === 'tool-call-approval') {
    console.log('Tool:', chunk.payload.toolName)
    console.log('Args:', chunk.payload.args)
  }
}
```

### Approving tool calls

Call `approveToolCall()` on the agent with the `runId` of the stream to resume the suspended tool call and let it execute:

```typescript
const handleApproval = async () => {
  const approvedStream = await agent.approveToolCall({ runId: stream.runId })

  for await (const chunk of approvedStream.textStream) {
    process.stdout.write(chunk)
  }
  process.stdout.write('\n')
}
```

### Declining tool calls

Call `declineToolCall()` on the agent to skip the tool call. The agent continues without executing the tool and responds accordingly:

```typescript
const handleDecline = async () => {
  const declinedStream = await agent.declineToolCall({ runId: stream.runId })

  for await (const chunk of declinedStream.textStream) {
    process.stdout.write(chunk)
  }
  process.stdout.write('\n')
}
```

## Tool approval with generate()

Tool approval also works with the `generate()` method for non-streaming use cases. When a tool requires approval during a `generate()` call, the method returns immediately instead of executing the tool.

### How it works

When a tool requires approval during a `generate()` call, the response includes:

- `finishReason: 'suspended'`: Indicates the agent is waiting for approval
- `suspendPayload`: Contains tool call details (`toolCallId`, `toolName`, `args`)
- `runId`: Needed to approve or decline the tool call

### Approving tool calls

Use `approveToolCallGenerate()` to approve the tool call and get the final result:

```typescript
const output = await agent.generate('Find user John', {
  requireToolApproval: true,
})

if (output.finishReason === 'suspended') {
  console.log('Tool requires approval:', output.suspendPayload.toolName)
  console.log('Arguments:', output.suspendPayload.args)

  // Approve the tool call and get the final result
  const result = await agent.approveToolCallGenerate({
    runId: output.runId,
    toolCallId: output.suspendPayload.toolCallId,
  })

  console.log('Final result:', result.text)
}
```

### Declining tool calls

Use `declineToolCallGenerate()` to skip the tool call:

```typescript
if (output.finishReason === 'suspended') {
  const result = await agent.declineToolCallGenerate({
    runId: output.runId,
    toolCallId: output.suspendPayload.toolCallId,
  })

  // Agent responds acknowledging the declined tool
  console.log(result.text)
}
```

### Stream vs generate comparison

| Aspect             | `stream()`                   | `generate()`                                     |
| ------------------ | ---------------------------- | ------------------------------------------------ |
| Response type      | Streaming chunks             | Complete response                                |
| Approval detection | `tool-call-approval` chunk   | `finishReason: 'suspended'`                      |
| Approve method     | `approveToolCall({ runId })` | `approveToolCallGenerate({ runId, toolCallId })` |
| Decline method     | `declineToolCall({ runId })` | `declineToolCallGenerate({ runId, toolCallId })` |
| Result             | Stream to iterate            | Full output object                               |

## Tool-level approval

Instead of pausing every tool call at the agent level, you can mark individual tools as requiring approval. This gives you granular control — only specific tools pause, while others execute immediately.

### Approval using `requireApproval`

Set `requireApproval: true` on a tool definition. The tool pauses before execution regardless of whether `requireToolApproval` is set on the agent:

```typescript
export const testTool = createTool({
  id: 'test-tool',
  description: 'Fetches weather for a location',
  inputSchema: z.object({
    location: z.string(),
  }),
  outputSchema: z.object({
    weather: z.string(),
  }),
  resumeSchema: z.object({
    approved: z.boolean(),
  }),
  execute: async inputData => {
    const response = await fetch(`https://wttr.in/${inputData.location}?format=3`)
    const weather = await response.text()

    return { weather }
  },
  requireApproval: true,
})
```

When `requireApproval` is `true`, the stream emits `tool-call-approval` chunks the same way agent-level approval does. Use `approveToolCall()` or `declineToolCall()` to continue:

```typescript
const stream = await agent.stream("What's the weather in London?")

for await (const chunk of stream.fullStream) {
  if (chunk.type === 'tool-call-approval') {
    console.log('Approval required for:', chunk.payload.toolName)
  }
}

const handleApproval = async () => {
  const approvedStream = await agent.approveToolCall({ runId: stream.runId })

  for await (const chunk of approvedStream.textStream) {
    process.stdout.write(chunk)
  }
  process.stdout.write('\n')
}
```

### Approval using `suspend`

With this approach, neither the agent nor the tool uses `requireApproval`. Instead, the tool's `execute` function calls `suspend` to pause at a specific point and return context or confirmation prompts to the user. This is useful when approval depends on runtime conditions rather than being unconditional.

```typescript
export const testToolB = createTool({
  id: 'test-tool-b',
  description: 'Fetches weather for a location',
  inputSchema: z.object({
    location: z.string(),
  }),
  outputSchema: z.object({
    weather: z.string(),
  }),
  resumeSchema: z.object({
    approved: z.boolean(),
  }),
  suspendSchema: z.object({
    reason: z.string(),
  }),
  execute: async (inputData, context) => {
    const { resumeData: { approved } = {}, suspend } = context?.agent ?? {}

    if (!approved) {
      return suspend?.({ reason: 'Approval required.' })
    }

    const response = await fetch(`https://wttr.in/${inputData.location}?format=3`)
    const weather = await response.text()

    return { weather }
  },
})
```

With this approach the stream includes a `tool-call-suspended` chunk, and the `suspendPayload` contains the `reason` defined by the tool's `suspendSchema`. Call `resumeStream` with the `resumeSchema` data and `runId` to continue:

```typescript
const stream = await agent.stream("What's the weather in London?")

for await (const chunk of stream.fullStream) {
  if (chunk.type === 'tool-call-suspended') {
    console.log(chunk.payload.suspendPayload)
  }
}

const handleResume = async () => {
  const resumedStream = await agent.resumeStream({ approved: true }, { runId: stream.runId })

  for await (const chunk of resumedStream.textStream) {
    process.stdout.write(chunk)
  }
  process.stdout.write('\n')
}
```

## Automatic tool resumption

When using tools that call `suspend()`, you can enable automatic resumption so the agent resumes suspended tools based on the user's next message. This creates a conversational flow where users provide the required information naturally, without your application needing to call `resumeStream()` explicitly.

### Enabling auto-resume

Set `autoResumeSuspendedTools` to `true` in the agent's default options or when calling `stream()`:

```typescript
import { Agent } from '@mastra/core/agent'
import { Memory } from '@mastra/memory'

// Option 1: In agent configuration
const agent = new Agent({
  id: 'my-agent',
  name: 'My Agent',
  instructions: 'You are a helpful assistant',
  model: 'openai/gpt-4o-mini',
  tools: { weatherTool },
  memory: new Memory(),
  defaultOptions: {
    autoResumeSuspendedTools: true,
  },
})

// Option 2: Per-request
const stream = await agent.stream("What's the weather?", {
  autoResumeSuspendedTools: true,
})
```

### How it works

When `autoResumeSuspendedTools` is enabled:

1. A tool suspends execution by calling `suspend()` with a payload (e.g., requesting more information)

2. The suspension is persisted to memory along with the conversation

3. When the user sends their next message on the same thread, the agent:

   - Detects the suspended tool from message history
   - Extracts `resumeData` from the user's message based on the tool's `resumeSchema`
   - Automatically resumes the tool with the extracted data

### Example

```typescript
import { createTool } from '@mastra/core/tools'
import { z } from 'zod'

export const weatherTool = createTool({
  id: 'weather-info',
  description: 'Fetches weather information for a city',
  suspendSchema: z.object({
    message: z.string(),
  }),
  resumeSchema: z.object({
    city: z.string(),
  }),
  execute: async (_inputData, context) => {
    // Check if this is a resume with data
    if (!context?.agent?.resumeData) {
      // First call - suspend and ask for the city
      return context?.agent?.suspend({
        message: 'What city do you want to know the weather for?',
      })
    }

    // Resume call - city was extracted from user's message
    const { city } = context.agent.resumeData
    const response = await fetch(`https://wttr.in/${city}?format=3`)
    const weather = await response.text()

    return { city, weather }
  },
})

const agent = new Agent({
  id: 'my-agent',
  name: 'My Agent',
  instructions: 'You are a helpful assistant',
  model: 'openai/gpt-4o-mini',
  tools: { weatherTool },
  memory: new Memory(),
  defaultOptions: {
    autoResumeSuspendedTools: true,
  },
})

const stream = await agent.stream("What's the weather like?")

for await (const chunk of stream.fullStream) {
  if (chunk.type === 'tool-call-suspended') {
    console.log(chunk.payload.suspendPayload)
  }
}

const handleResume = async () => {
  const resumedStream = await agent.stream('San Francisco')

  for await (const chunk of resumedStream.textStream) {
    process.stdout.write(chunk)
  }
  process.stdout.write('\n')
}
```

**Conversation flow:**

```text
User: "What's the weather like?"
Agent: "What city do you want to know the weather for?"

User: "San Francisco"
Agent: "The weather in San Francisco is: San Francisco: ☀️ +72°F"
```

The second message automatically resumes the suspended tool, the agent extracts `{ city: "San Francisco" }` from the user's message and passes it as `resumeData`.

### Requirements

For automatic tool resumption to work:

- **Memory configured**: The agent needs memory to track suspended tools across messages
- **Same thread**: The follow-up message must use the same memory thread and resource identifiers
- **`resumeSchema` defined**: The tool must define a `resumeSchema` so the agent knows what data structure to extract from the user's message

### Manual vs automatic resumption

| Approach                               | Use case                                                                 |
| -------------------------------------- | ------------------------------------------------------------------------ |
| Manual (`resumeStream()`)              | Programmatic control, webhooks, button clicks, external triggers         |
| Automatic (`autoResumeSuspendedTools`) | Conversational flows where users provide resume data in natural language |

Both approaches work with the same tool definitions. Automatic resumption triggers only when suspended tools exist in the message history and the user sends a new message on the same thread.

## Tool approval: Supervisor pattern

The [supervisor pattern](https://mastra.ai/docs/agents/networks) lets a supervisor agent coordinate multiple subagents using `.stream()` or `.generate()`. The supervisor delegates tasks to subagents, which may use tools that require approval. When this happens, tool approvals properly propagate through the delegation chain — the approval request surfaces at the supervisor level where you can handle it, regardless of which subagent triggered it.

### How it works

1. The supervisor agent delegates a task to a subagent.
2. The subagent calls a tool that has `requireApproval: true` or uses `suspend()`.
3. The approval request bubbles up through the delegation chain to the supervisor.
4. You handle the approval or decline at the supervisor level.
5. The decision propagates back down to the subagent, which continues or terminates accordingly.

### Example

The following example creates a subagent with a database lookup tool that requires approval. The supervisor delegates to this subagent, and when the tool triggers an approval request, it surfaces in the supervisor's stream as a `tool-call-approval` chunk. You then approve the tool call using `approveToolCall` with the stream's `runId`.

```typescript
import { Agent } from '@mastra/core/agent'
import { createTool } from '@mastra/core/tools'
import { Memory } from '@mastra/memory'
import { z } from 'zod'

// subagent with approval-required tool
const findUserTool = createTool({
  id: 'find-user',
  description: 'Finds user by ID in the database',
  inputSchema: z.object({
    userId: z.string(),
  }),
  outputSchema: z.object({
    user: z.object({
      id: z.string(),
      name: z.string(),
      email: z.string(),
    }),
  }),
  requireApproval: true, // Requires approval before execution
  execute: async input => {
    const user = await database.findUser(input.userId)
    return { user }
  },
})

const dataAgent = new Agent({
  id: 'data-agent',
  name: 'Data Agent',
  description: 'Handles database queries and user data retrieval',
  model: 'openai/gpt-4o-mini',
  tools: { findUserTool },
})

const supervisorAgent = new Agent({
  id: 'supervisor',
  name: 'Supervisor Agent',
  instructions: `You coordinate data retrieval tasks.
    Delegate to data-agent for user lookups.`,
  model: 'openai/gpt-5.1',
  agents: { dataAgent },
  memory: new Memory(),
})

// When supervisor delegates to dataAgent and tool requires approval
const stream = await supervisorAgent.stream('Find user with ID 12345')

for await (const chunk of stream.fullStream) {
  if (chunk.type === 'tool-call-approval') {
    console.log('Tool requires approval:', chunk.payload.toolName)
    console.log('Arguments:', chunk.payload.args)

    // Approve the tool call
    const resumeStream = await supervisorAgent.approveToolCall({
      runId: stream.runId,
      toolCallId: chunk.payload.toolCallId,
    })

    // Process resumed stream
    for await (const resumeChunk of resumeStream.textStream) {
      process.stdout.write(resumeChunk)
    }
  }
}
```

### Declining tool calls in supervisor pattern

Decline tool calls at the supervisor level by calling `declineToolCall`. The supervisor responds acknowledging the declined tool without executing it:

```typescript
for await (const chunk of stream.fullStream) {
  if (chunk.type === 'tool-call-approval') {
    console.log('Declining tool call:', chunk.payload.toolName)

    // Decline the tool call
    const declineStream = await supervisorAgent.declineToolCall({
      runId: stream.runId,
      toolCallId: chunk.payload.toolCallId,
    })

    // The supervisor responds acknowledging the declined tool
    for await (const declineChunk of declineStream.textStream) {
      process.stdout.write(declineChunk)
    }
  }
}
```

### Using suspend() in supervisor pattern

Tools can also use [`suspend()`](#approval-using-suspend) to pause execution and return context to the user. This approach works through the supervisor delegation chain the same way `requireApproval` does — the suspension surfaces at the supervisor level:

```typescript
const conditionalTool = createTool({
  id: 'conditional-operation',
  description: 'Performs an operation that may require confirmation',
  inputSchema: z.object({
    operation: z.string(),
  }),
  suspendSchema: z.object({
    message: z.string(),
  }),
  resumeSchema: z.object({
    confirmed: z.boolean(),
  }),
  execute: async (input, context) => {
    const { resumeData } = context?.agent ?? {}

    if (!resumeData?.confirmed) {
      return context?.agent?.suspend({
        message: `Confirm: ${input.operation}?`,
      })
    }

    // Proceed with operation
    return await performOperation(input.operation)
  },
})

// When using this tool through a subagent in supervisor pattern
for await (const chunk of stream.fullStream) {
  if (chunk.type === 'tool-call-suspended') {
    console.log('Tool suspended:', chunk.payload.suspendPayload.message)

    // Resume with confirmation
    const resumeStream = await supervisorAgent.resumeStream(
      { confirmed: true },
      { runId: stream.runId },
    )

    for await (const resumeChunk of resumeStream.textStream) {
      process.stdout.write(resumeChunk)
    }
  }
}
```

### Tool approval with generate()

Tool approval propagation also works with `generate()` in supervisor pattern:

```typescript
const output = await supervisorAgent.generate('Find user with ID 12345', {
  maxSteps: 10,
})

if (output.finishReason === 'suspended') {
  console.log('Tool requires approval:', output.suspendPayload.toolName)

  // Approve
  const result = await supervisorAgent.approveToolCallGenerate({
    runId: output.runId,
    toolCallId: output.suspendPayload.toolCallId,
  })

  console.log('Final result:', result.text)
}
```

### Multi-level delegation

Tool approvals propagate through multiple levels of delegation. For example, if a supervisor delegates to subagent A, which in turn delegates to subagent B that has a tool with `requireApproval: true`, the approval request still surfaces at the top-level supervisor. You handle the approval or decline there, and the result flows back down through the entire delegation chain to the tool that requested it.

## Related

- [Using Tools](https://mastra.ai/docs/agents/using-tools)
- [Agent Overview](https://mastra.ai/docs/agents/overview)
- [Tools Overview](https://mastra.ai/docs/mcp/overview)
- [Agent Memory](https://mastra.ai/docs/agents/agent-memory)
- [Request Context](https://mastra.ai/docs/server/request-context)