@mastra/libsql 0.0.0-error-handler-fix-20251020202607 → 0.0.0-esbuild-bundle-worker-20260807182016

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/CHANGELOG.md +4789 -3
  2. package/LICENSE.md +15 -0
  3. package/README.md +30 -20
  4. package/dist/docs/SKILL.md +52 -0
  5. package/dist/docs/assets/SOURCE_MAP.json +6 -0
  6. package/dist/docs/references/docs-agents-agent-approval.md +664 -0
  7. package/dist/docs/references/docs-agents-networks.md +184 -0
  8. package/dist/docs/references/docs-deployment-workers.md +137 -0
  9. package/dist/docs/references/docs-editor-overview.md +349 -0
  10. package/dist/docs/references/docs-memory-memory-processors.md +385 -0
  11. package/dist/docs/references/docs-memory-message-history.md +348 -0
  12. package/dist/docs/references/docs-memory-multi-user-threads.md +208 -0
  13. package/dist/docs/references/docs-memory-overview.md +266 -0
  14. package/dist/docs/references/docs-memory-semantic-recall.md +401 -0
  15. package/dist/docs/references/docs-memory-working-memory.md +431 -0
  16. package/dist/docs/references/docs-storage-overview.md +214 -0
  17. package/dist/docs/references/docs-workflows-snapshots.md +240 -0
  18. package/dist/docs/references/guides-agent-frameworks-ai-sdk.md +142 -0
  19. package/dist/docs/references/guides-rag-retrieval.md +520 -0
  20. package/dist/docs/references/reference-core-getMemory.md +51 -0
  21. package/dist/docs/references/reference-core-listMemory.md +57 -0
  22. package/dist/docs/references/reference-core-mastra-class.md +153 -0
  23. package/dist/docs/references/reference-file-based-agents-memory.md +58 -0
  24. package/dist/docs/references/reference-file-based-agents-storage.md +30 -0
  25. package/dist/docs/references/reference-memory-memory-class.md +148 -0
  26. package/dist/docs/references/reference-storage-composite.md +397 -0
  27. package/dist/docs/references/reference-storage-dynamodb.md +284 -0
  28. package/dist/docs/references/reference-storage-libsql.md +143 -0
  29. package/dist/docs/references/reference-storage-retention.md +248 -0
  30. package/dist/docs/references/reference-vectors-libsql.md +307 -0
  31. package/dist/index.cjs +13164 -3390
  32. package/dist/index.cjs.map +1 -1
  33. package/dist/index.js +13134 -3383
  34. package/dist/index.js.map +1 -1
  35. package/dist/storage/db/index.d.ts +389 -0
  36. package/dist/storage/db/index.d.ts.map +1 -0
  37. package/dist/storage/db/utils.d.ts +84 -0
  38. package/dist/storage/db/utils.d.ts.map +1 -0
  39. package/dist/storage/db/write-lock.d.ts +8 -0
  40. package/dist/storage/db/write-lock.d.ts.map +1 -0
  41. package/dist/storage/domains/agents/index.d.ts +30 -0
  42. package/dist/storage/domains/agents/index.d.ts.map +1 -0
  43. package/dist/storage/domains/background-tasks/index.d.ts +27 -0
  44. package/dist/storage/domains/background-tasks/index.d.ts.map +1 -0
  45. package/dist/storage/domains/blobs/index.d.ts +17 -0
  46. package/dist/storage/domains/blobs/index.d.ts.map +1 -0
  47. package/dist/storage/domains/channels/index.d.ts +20 -0
  48. package/dist/storage/domains/channels/index.d.ts.map +1 -0
  49. package/dist/storage/domains/datasets/index.d.ts +43 -0
  50. package/dist/storage/domains/datasets/index.d.ts.map +1 -0
  51. package/dist/storage/domains/experiments/index.d.ts +54 -0
  52. package/dist/storage/domains/experiments/index.d.ts.map +1 -0
  53. package/dist/storage/domains/favorites/index.d.ts +17 -0
  54. package/dist/storage/domains/favorites/index.d.ts.map +1 -0
  55. package/dist/storage/domains/harness/index.d.ts +17 -0
  56. package/dist/storage/domains/harness/index.d.ts.map +1 -0
  57. package/dist/storage/domains/mcp-clients/index.d.ts +26 -0
  58. package/dist/storage/domains/mcp-clients/index.d.ts.map +1 -0
  59. package/dist/storage/domains/mcp-servers/index.d.ts +26 -0
  60. package/dist/storage/domains/mcp-servers/index.d.ts.map +1 -0
  61. package/dist/storage/domains/memory/index.d.ts +58 -54
  62. package/dist/storage/domains/memory/index.d.ts.map +1 -1
  63. package/dist/storage/domains/notifications/index.d.ts +23 -0
  64. package/dist/storage/domains/notifications/index.d.ts.map +1 -0
  65. package/dist/storage/domains/observability/index.d.ts +49 -29
  66. package/dist/storage/domains/observability/index.d.ts.map +1 -1
  67. package/dist/storage/domains/prompt-blocks/index.d.ts +25 -0
  68. package/dist/storage/domains/prompt-blocks/index.d.ts.map +1 -0
  69. package/dist/storage/domains/schedules/index.d.ts +27 -0
  70. package/dist/storage/domains/schedules/index.d.ts.map +1 -0
  71. package/dist/storage/domains/scorer-definitions/index.d.ts +26 -0
  72. package/dist/storage/domains/scorer-definitions/index.d.ts.map +1 -0
  73. package/dist/storage/domains/scores/index.d.ts +29 -31
  74. package/dist/storage/domains/scores/index.d.ts.map +1 -1
  75. package/dist/storage/domains/skills/index.d.ts +26 -0
  76. package/dist/storage/domains/skills/index.d.ts.map +1 -0
  77. package/dist/storage/domains/thread-state/index.d.ts +38 -0
  78. package/dist/storage/domains/thread-state/index.d.ts.map +1 -0
  79. package/dist/storage/domains/tool-provider-connections/index.d.ts +14 -0
  80. package/dist/storage/domains/tool-provider-connections/index.d.ts.map +1 -0
  81. package/dist/storage/domains/utils.d.ts +28 -54
  82. package/dist/storage/domains/utils.d.ts.map +1 -1
  83. package/dist/storage/domains/workflow-definitions/index.d.ts +14 -0
  84. package/dist/storage/domains/workflow-definitions/index.d.ts.map +1 -0
  85. package/dist/storage/domains/workflows/index.d.ts +27 -32
  86. package/dist/storage/domains/workflows/index.d.ts.map +1 -1
  87. package/dist/storage/domains/workspaces/index.d.ts +26 -0
  88. package/dist/storage/domains/workspaces/index.d.ts.map +1 -0
  89. package/dist/storage/factory-storage.d.ts +28 -0
  90. package/dist/storage/factory-storage.d.ts.map +1 -0
  91. package/dist/storage/index.d.ts +128 -255
  92. package/dist/storage/index.d.ts.map +1 -1
  93. package/dist/storage/retention.d.ts +77 -0
  94. package/dist/storage/retention.d.ts.map +1 -0
  95. package/dist/vector/index.d.ts +31 -4
  96. package/dist/vector/index.d.ts.map +1 -1
  97. package/dist/vector/sql-builder.d.ts.map +1 -1
  98. package/package.json +22 -16
  99. package/dist/storage/domains/legacy-evals/index.d.ts +0 -18
  100. package/dist/storage/domains/legacy-evals/index.d.ts.map +0 -1
  101. package/dist/storage/domains/operations/index.d.ts +0 -110
  102. package/dist/storage/domains/operations/index.d.ts.map +0 -1
  103. package/dist/storage/domains/traces/index.d.ts +0 -21
  104. package/dist/storage/domains/traces/index.d.ts.map +0 -1
@@ -0,0 +1,664 @@
1
+ > Discover all available pages from the documentation index: https://mastra.ai/llms.txt
2
+
3
+ # Agent approval
4
+
5
+ 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.
6
+
7
+ ## When to use agent approval
8
+
9
+ - **Destructive or irreversible actions** such as deleting records or sending emails, or alternatively processing payments.
10
+ - **Cost-heavy operations** like calling expensive third-party APIs where you want to verify arguments first.
11
+ - **Conditional confirmation** where a tool starts executing and then discovers it needs the user to confirm or supply extra data before finishing.
12
+
13
+ ## Quickstart
14
+
15
+ Mark a tool with `requireApproval: true`, then check for the `tool-call-approval` chunk in the stream to approve or decline:
16
+
17
+ ```typescript
18
+ import { Agent } from '@mastra/core/agent'
19
+ import { createTool } from '@mastra/core/tools'
20
+ import { z } from 'zod'
21
+
22
+ const deleteTool = createTool({
23
+ id: 'delete-record',
24
+ description: 'Delete a record by ID',
25
+ inputSchema: z.object({ id: z.string() }),
26
+ outputSchema: z.object({ deleted: z.boolean() }),
27
+ requireApproval: true,
28
+ execute: async ({ id }) => {
29
+ await db.delete(id)
30
+ return { deleted: true }
31
+ },
32
+ })
33
+
34
+ const agent = new Agent({
35
+ id: 'my-agent',
36
+ name: 'My Agent',
37
+ model: 'openai/gpt-5-mini',
38
+ tools: { deleteTool },
39
+ })
40
+
41
+ const stream = await agent.stream('Delete record abc-123')
42
+
43
+ for await (const chunk of stream.fullStream) {
44
+ if (chunk.type === 'tool-call-approval') {
45
+ const approved = await agent.approveToolCall({ runId: stream.runId })
46
+ for await (const c of approved.textStream) process.stdout.write(c)
47
+ }
48
+ }
49
+ ```
50
+
51
+ > **Note:** Agent approval uses snapshots to capture request state. Configure a [storage provider](https://mastra.ai/docs/storage/overview) on your Mastra instance or you'll see a "snapshot not found" error.
52
+ >
53
+ > Snapshots for agent runs are minimal resume artifacts: they hold only what's needed to resume the suspended run and are deleted once the run finishes. Use [tracing](https://mastra.ai/docs/observability/overview) for the execution record and [memory](https://mastra.ai/docs/memory/overview) for the conversation history.
54
+
55
+ ## How approval works
56
+
57
+ Mastra offers two distinct mechanisms for pausing tool calls: **pre-execution approval** and **runtime suspension**.
58
+
59
+ ### Pre-execution approval
60
+
61
+ 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.
62
+
63
+ The flags control this, combined with OR logic. If _either_ is `true`, the call pauses:
64
+
65
+ | Flag | Where to set it | Scope |
66
+ | --------------------------- | --------------------------------- | ------------------------------------------- |
67
+ | `requireToolApproval: true` | `stream()` / `generate()` options | Pauses **every** tool call for that request |
68
+ | `requireApproval: true` | `createTool()` definition | Pauses calls to **that specific tool** |
69
+
70
+ The stream emits a `tool-call-approval` chunk containing the `toolCallId`, `toolName`, and `args`. Call `approveToolCall()` or `declineToolCall()` with the stream's `runId` to continue:
71
+
72
+ ```typescript
73
+ const stream = await agent.stream("What's the weather in London?", {
74
+ requireToolApproval: true,
75
+ })
76
+
77
+ for await (const chunk of stream.fullStream) {
78
+ if (chunk.type === 'tool-call-approval') {
79
+ console.log('Tool:', chunk.payload.toolName)
80
+ console.log('Args:', chunk.payload.args)
81
+
82
+ // Approve
83
+ const approved = await agent.approveToolCall({ runId: stream.runId })
84
+ for await (const c of approved.textStream) process.stdout.write(c)
85
+
86
+ // Or decline
87
+ const declined = await agent.declineToolCall({ runId: stream.runId })
88
+ for await (const c of declined.textStream) process.stdout.write(c)
89
+ }
90
+ }
91
+ ```
92
+
93
+ #### Conditional approval with a function
94
+
95
+ Instead of a boolean, `requireToolApproval` accepts a function that decides per tool call. It receives the `toolName`, the `args` the model passed, the `requestContext`, and the `workspace`. Return `true` to require approval for that call, or `false` to allow it. This lets you gate approval at runtime, for example, only for tools whose name matches a pattern:
96
+
97
+ ```typescript
98
+ const stream = await agent.stream('Clean up old records', {
99
+ requireToolApproval: ({ toolName }) => /^delete_/.test(toolName),
100
+ })
101
+ ```
102
+
103
+ A tool's own `requireApproval` setting takes precedence over the function above. Its rule decides whether that tool needs approval. If the function throws, the call requires approval as a fail-safe.
104
+
105
+ > **Note:** Function-based `requireToolApproval` is only available on regular `stream()` / `generate()` calls. Durable agents and stored agents persist their options, and a function can't be serialized, so they accept only a boolean. If you pass a function in those contexts it falls back to requiring approval for every tool call.
106
+
107
+ #### Bind approval to the exact tool arguments
108
+
109
+ For sensitive tools, bind the approval to the exact tool name and arguments that were shown to the reviewer. If those arguments drift before execution, the tool shouldn't run under the old approval.
110
+
111
+ The `tool-call-approval` chunk already includes `toolName`, `toolCallId`, and `args`. You can fingerprint those fields when the approval request is shown. The example below uses a JSON string as the fingerprint, but in production you should use a stable hash of the tool name and arguments:
112
+
113
+ ```typescript
114
+ import { Agent } from '@mastra/core/agent'
115
+
116
+ // For your production usecase, build a stable hash of the tool name and args
117
+ function actionFingerprint(toolName: string, args: unknown) {
118
+ const payload = JSON.stringify({ toolName, args })
119
+ return `fingerprint-${payload}`
120
+ }
121
+
122
+ const sensitiveTools = new Set(['issue_refund', 'delete_record'])
123
+ const approvedFingerprints = new Set<string>()
124
+
125
+ export const approvalBoundAgent = new Agent({
126
+ id: 'approval-bound-agent',
127
+ name: 'Approval Bound Agent',
128
+ model: 'openai/gpt-5.6-sol',
129
+ tools: { issueRefundTool, deleteRecordTool },
130
+ hooks: {
131
+ beforeToolCall: ({ toolName, input }) => {
132
+ if (!sensitiveTools.has(toolName)) return
133
+
134
+ const fingerprint = actionFingerprint(toolName, input)
135
+ if (!approvedFingerprints.delete(fingerprint)) {
136
+ return {
137
+ proceed: false,
138
+ output: `Tool call blocked: approval did not match ${toolName} arguments.`,
139
+ }
140
+ }
141
+ },
142
+ },
143
+ })
144
+ ```
145
+
146
+ ```typescript
147
+ const stream = await approvalBoundAgent.stream('Refund order ord-1042', {
148
+ requireToolApproval: ({ toolName }) => sensitiveTools.has(toolName),
149
+ })
150
+
151
+ async function consumeApprovalStream(currentStream: typeof stream) {
152
+ for await (const chunk of currentStream.fullStream) {
153
+ if (chunk.type === 'tool-call-approval') {
154
+ const { toolName, toolCallId, args } = chunk.payload
155
+ const fingerprint = actionFingerprint(toolName, args)
156
+
157
+ // Present toolName, args, and fingerprint to your approval UI.
158
+ const approved = await showApprovalDialog({ toolName, args, fingerprint })
159
+
160
+ const nextStream = approved
161
+ ? await approveReviewedToolCall(currentStream.runId, toolCallId, fingerprint)
162
+ : await approvalBoundAgent.declineToolCall({ runId: currentStream.runId, toolCallId })
163
+
164
+ await consumeApprovalStream(nextStream)
165
+ }
166
+ }
167
+ }
168
+
169
+ async function approveReviewedToolCall(runId: string, toolCallId: string, fingerprint: string) {
170
+ approvedFingerprints.add(fingerprint)
171
+ return approvalBoundAgent.approveToolCall({ runId, toolCallId })
172
+ }
173
+
174
+ await consumeApprovalStream(stream)
175
+ ```
176
+
177
+ In production, store the approved fingerprint in durable storage scoped to the user, run, tool call, and policy version. The `Set` above is intentionally small so the boundary is clear: the approval is consumed once, and only for the same canonical tool arguments that were reviewed.
178
+
179
+ ### Runtime suspension with `suspend()`
180
+
181
+ 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.
182
+
183
+ 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`.
184
+
185
+ ```typescript
186
+ const weatherTool = createTool({
187
+ id: 'get-weather',
188
+ inputSchema: z.object({
189
+ location: z.string().optional(),
190
+ }),
191
+ suspendSchema: z.object({
192
+ question: z.string(),
193
+ }),
194
+ resumeSchema: z.object({
195
+ location: z.string(),
196
+ }),
197
+ execute: async ({ location }, context) => {
198
+ if (!location) {
199
+ return await context?.agent?.suspend({
200
+ question: 'Which city would you like the weather for?',
201
+ })
202
+ }
203
+ return await fetchWeather(location)
204
+ },
205
+ })
206
+ ```
207
+
208
+ > **Note:** `suspend()` doesn't throw, return immediately after calling it (e.g. `return await suspend({ ... })`). Code after `await suspend(...)` still runs before the tool pauses.
209
+
210
+ ## Tool approval with `generate()`
211
+
212
+ Tool approval also works with `generate()` for non-streaming use cases. When a tool requires approval, `generate()` returns immediately with `finishReason: 'suspended'`, a `suspendPayload` containing the tool call details (`toolCallId`, `toolName`, `args`), and a `runId`:
213
+
214
+ ```typescript
215
+ const output = await agent.generate('Find user John', {
216
+ requireToolApproval: true,
217
+ })
218
+
219
+ if (output.finishReason === 'suspended') {
220
+ console.log('Tool requires approval:', output.suspendPayload.toolName)
221
+
222
+ // Approve
223
+ const result = await agent.approveToolCallGenerate({
224
+ runId: output.runId,
225
+ toolCallId: output.suspendPayload.toolCallId,
226
+ })
227
+ console.log('Final result:', result.text)
228
+
229
+ // Or decline
230
+ const result = await agent.declineToolCallGenerate({
231
+ runId: output.runId,
232
+ toolCallId: output.suspendPayload.toolCallId,
233
+ })
234
+ }
235
+ ```
236
+
237
+ ### Stream vs generate comparison
238
+
239
+ | Aspect | `stream()` | `generate()` |
240
+ | ------------------ | ---------------------------- | ------------------------------------------------ |
241
+ | Response type | Streaming chunks | Complete response |
242
+ | Approval detection | `tool-call-approval` chunk | `finishReason: 'suspended'` |
243
+ | Approve method | `approveToolCall({ runId })` | `approveToolCallGenerate({ runId, toolCallId })` |
244
+ | Decline method | `declineToolCall({ runId })` | `declineToolCallGenerate({ runId, toolCallId })` |
245
+ | Result | Stream to iterate | Full output object |
246
+
247
+ > **Note:** `toolCallId` is optional on all four methods. Pass it when multiple tool calls may be pending (common in supervisor agents). When omitted, the agent resumes the most recent suspended tool call.
248
+
249
+ ## Tool-level approval
250
+
251
+ Instead of pausing every tool call at the agent level, you can mark individual tools as requiring approval. You get fine-grained control: only specific tools pause, while others execute immediately.
252
+
253
+ ### Approval using `requireApproval`
254
+
255
+ Set `requireApproval: true` on a tool definition. The tool pauses before execution regardless of whether `requireToolApproval` is set on the agent:
256
+
257
+ ```typescript
258
+ export const testTool = createTool({
259
+ id: 'test-tool',
260
+ description: 'Fetches weather for a location',
261
+ inputSchema: z.object({
262
+ location: z.string(),
263
+ }),
264
+ outputSchema: z.object({
265
+ weather: z.string(),
266
+ }),
267
+ resumeSchema: z.object({
268
+ approved: z.boolean(),
269
+ }),
270
+ execute: async inputData => {
271
+ const response = await fetch(`https://wttr.in/${inputData.location}?format=3`)
272
+ const weather = await response.text()
273
+
274
+ return { weather }
275
+ },
276
+ requireApproval: true,
277
+ })
278
+ ```
279
+
280
+ When `requireApproval` is `true`, the stream emits `tool-call-approval` chunks the same way agent-level approval does. Use `approveToolCall()` or `declineToolCall()` to continue:
281
+
282
+ ```typescript
283
+ const stream = await agent.stream("What's the weather in London?")
284
+
285
+ for await (const chunk of stream.fullStream) {
286
+ if (chunk.type === 'tool-call-approval') {
287
+ console.log('Approval required for:', chunk.payload.toolName)
288
+ }
289
+ }
290
+
291
+ const handleApproval = async () => {
292
+ const approvedStream = await agent.approveToolCall({ runId: stream.runId })
293
+
294
+ for await (const chunk of approvedStream.textStream) {
295
+ process.stdout.write(chunk)
296
+ }
297
+ process.stdout.write('\n')
298
+ }
299
+ ```
300
+
301
+ ### Approval using `suspend()`
302
+
303
+ 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.
304
+
305
+ ```typescript
306
+ export const testToolB = createTool({
307
+ id: 'test-tool-b',
308
+ description: 'Fetches weather for a location',
309
+ inputSchema: z.object({
310
+ location: z.string(),
311
+ }),
312
+ outputSchema: z.object({
313
+ weather: z.string(),
314
+ }),
315
+ resumeSchema: z.object({
316
+ approved: z.boolean(),
317
+ }),
318
+ suspendSchema: z.object({
319
+ reason: z.string(),
320
+ }),
321
+ execute: async (inputData, context) => {
322
+ const { resumeData: { approved } = {}, suspend } = context?.agent ?? {}
323
+
324
+ if (!approved) {
325
+ return suspend?.({ reason: 'Approval required.' })
326
+ }
327
+
328
+ const response = await fetch(`https://wttr.in/${inputData.location}?format=3`)
329
+ const weather = await response.text()
330
+
331
+ return { weather }
332
+ },
333
+ })
334
+ ```
335
+
336
+ 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:
337
+
338
+ ```typescript
339
+ const stream = await agent.stream("What's the weather in London?")
340
+
341
+ for await (const chunk of stream.fullStream) {
342
+ if (chunk.type === 'tool-call-suspended') {
343
+ console.log(chunk.payload.suspendPayload)
344
+ }
345
+ }
346
+
347
+ const handleResume = async () => {
348
+ const resumedStream = await agent.resumeStream({ approved: true }, { runId: stream.runId })
349
+
350
+ for await (const chunk of resumedStream.textStream) {
351
+ process.stdout.write(chunk)
352
+ }
353
+ process.stdout.write('\n')
354
+ }
355
+ ```
356
+
357
+ ## Automatic tool resumption
358
+
359
+ When using tools that call `suspend()`, you can enable automatic resumption so the agent resumes suspended tools based on the user's next message. Set `autoResumeSuspendedTools` to `true` in the agent's default options or per-request:
360
+
361
+ ```typescript
362
+ import { Agent } from '@mastra/core/agent'
363
+ import { Memory } from '@mastra/memory'
364
+
365
+ const agent = new Agent({
366
+ id: 'my-agent',
367
+ name: 'My Agent',
368
+ instructions: 'You are a helpful assistant',
369
+ model: 'openai/gpt-5-mini',
370
+ tools: { weatherTool },
371
+ memory: new Memory(),
372
+ defaultOptions: {
373
+ autoResumeSuspendedTools: true,
374
+ },
375
+ })
376
+ ```
377
+
378
+ When enabled, the agent detects suspended tools from message history on the next user message. It extracts `resumeData` based on the tool's `resumeSchema`, then automatically resumes the tool.
379
+
380
+ The following example shows a complete conversational flow:
381
+
382
+ ```typescript
383
+ import { createTool } from '@mastra/core/tools'
384
+ import { z } from 'zod'
385
+
386
+ const weatherTool = createTool({
387
+ id: 'weather-tool',
388
+ description: 'Fetches weather for a city',
389
+ inputSchema: z.object({
390
+ city: z.string(),
391
+ }),
392
+ outputSchema: z.object({
393
+ weather: z.string(),
394
+ }),
395
+ suspendSchema: z.object({
396
+ message: z.string(),
397
+ }),
398
+ resumeSchema: z.object({
399
+ city: z.string(),
400
+ }),
401
+ execute: async (inputData, context) => {
402
+ const { resumeData, suspend } = context?.agent ?? {}
403
+
404
+ // If no city provided, ask the user
405
+ if (!inputData.city && !resumeData?.city) {
406
+ return suspend?.({ message: 'What city do you want to know the weather for?' })
407
+ }
408
+
409
+ const city = resumeData?.city ?? inputData.city
410
+ const response = await fetch(`https://wttr.in/${city}?format=3`)
411
+ const weather = await response.text()
412
+
413
+ return { weather: `${city}: ${weather}` }
414
+ },
415
+ })
416
+ ```
417
+
418
+ ```typescript
419
+ const stream = await agent.stream("What's the weather like?")
420
+
421
+ for await (const chunk of stream.fullStream) {
422
+ if (chunk.type === 'tool-call-suspended') {
423
+ console.log(chunk.payload.suspendPayload)
424
+ }
425
+ }
426
+
427
+ // User sends follow-up on the same thread
428
+ const resumedStream = await agent.stream('San Francisco')
429
+ for await (const chunk of resumedStream.textStream) {
430
+ process.stdout.write(chunk)
431
+ }
432
+ ```
433
+
434
+ ```text
435
+ User: "What's the weather like?"
436
+ Agent: "What city do you want to know the weather for?"
437
+
438
+ User: "San Francisco"
439
+ Agent: "The weather in San Francisco is: San Francisco: ☀️ +72°F"
440
+ ```
441
+
442
+ The second message automatically resumes the suspended tool. The agent extracts `{ city: "San Francisco" }` from the user's message and passes it as `resumeData`.
443
+
444
+ ### Requirements
445
+
446
+ For automatic tool resumption to work:
447
+
448
+ - **Memory configured**: The agent needs memory to track suspended tools across messages
449
+ - **Same thread**: The follow-up message must use the same memory thread and resource identifiers
450
+ - **`resumeSchema` defined**: The tool must define a `resumeSchema` so the agent knows what data structure to extract from the user's message
451
+
452
+ ### Manual vs automatic resumption
453
+
454
+ | Approach | Use case |
455
+ | -------------------------------------- | ------------------------------------------------------------------------ |
456
+ | Manual (`resumeStream()`) | Programmatic control, webhooks, button clicks, external triggers |
457
+ | Automatic (`autoResumeSuspendedTools`) | Conversational flows where users provide resume data in natural language |
458
+
459
+ 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.
460
+
461
+ ## Resuming after a restart
462
+
463
+ The examples above hold on to `stream.runId` between suspension and approval. That works while the process stays alive, but in production the approval often arrives later, after a page refresh, a server restart, or on a different server instance behind a load balancer.
464
+
465
+ Use [`listSuspendedRuns()`](https://mastra.ai/reference/agents/listSuspendedRuns) to rediscover the pending run for a conversation from storage:
466
+
467
+ ```typescript
468
+ // In the request handler that receives the user's decision
469
+ const { runs } = await agent.listSuspendedRuns({
470
+ threadId: 'thread-123',
471
+ resourceId: 'user-456',
472
+ })
473
+
474
+ const run = runs[0]
475
+ const toolCall = run?.toolCalls[0]
476
+
477
+ if (run && toolCall) {
478
+ let stream
479
+ if (toolCall.requiresApproval) {
480
+ // Suspended by requireApproval — approve or decline the tool call
481
+ stream = await agent.approveToolCall({ runId: run.runId, toolCallId: toolCall.toolCallId })
482
+ } else {
483
+ // Suspended by suspend() — resume with the data the tool asked for
484
+ console.log('Tool asked:', toolCall.suspendPayload)
485
+ stream = await agent.resumeStream({ name: 'San Francisco' }, { runId: run.runId })
486
+ }
487
+ for await (const chunk of stream.textStream) process.stdout.write(chunk)
488
+ }
489
+ ```
490
+
491
+ Each returned run includes the suspended tool calls (`toolCallId`, `toolName`, `args`, and `requiresApproval`). Approval suspensions (`requiresApproval: true`) are answered with `approveToolCall()` / `declineToolCall()`, while `suspend()`-based suspensions carry their `suspendPayload` and expect `resumeStream()` with resume data, so you can rebuild the right UI for either flow without keeping any state in memory.
492
+
493
+ `sendToolApproval()` uses the same storage-backed discovery automatically: when no active run is found in memory for the thread, it looks up the suspended run in storage before failing. If several suspended runs match the thread, pass a `toolCallId` to disambiguate.
494
+
495
+ The same discovery is available over HTTP as `GET /agents/:agentId/suspended-runs` and in the client SDK as [`agent.listSuspendedRuns()`](https://mastra.ai/reference/client-js/agents), so browser-based approval UIs can rediscover pending runs directly.
496
+
497
+ > **Note:** Suspended runs only survive restarts when your Mastra instance is configured with a persistent [storage provider](https://mastra.ai/docs/storage/overview). The default in-memory store loses snapshots when the process exits.
498
+
499
+ ## Tool approval: Supervisor agents
500
+
501
+ A [supervisor agent](https://mastra.ai/docs/capabilities/subagents) coordinates multiple subagents using `.stream()` or `.generate()`. When a subagent calls a tool that requires approval, the request propagates up through the delegation chain and surfaces at the supervisor level:
502
+
503
+ 1. The supervisor delegates a task to a subagent.
504
+ 2. The subagent calls a tool that has `requireApproval: true` or uses `suspend()`.
505
+ 3. The approval request bubbles up to the supervisor.
506
+ 4. You approve or decline at the supervisor level.
507
+ 5. The decision propagates back down to the subagent.
508
+
509
+ Tool approvals also propagate through multiple levels of delegation. If a supervisor delegates to subagent A, which delegates to subagent B that has a tool with `requireApproval: true`, the approval request still surfaces at the top-level supervisor.
510
+
511
+ ### Approve and decline in supervisor agents
512
+
513
+ The example below creates a subagent with a tool requiring approval. When the tool triggers an approval request, it surfaces in the supervisor's stream as a `tool-call-approval` chunk:
514
+
515
+ ```typescript
516
+ import { Agent } from '@mastra/core/agent'
517
+ import { createTool } from '@mastra/core/tools'
518
+ import { Memory } from '@mastra/memory'
519
+ import { z } from 'zod'
520
+
521
+ const findUserTool = createTool({
522
+ id: 'find-user',
523
+ description: 'Finds user by ID in the database',
524
+ inputSchema: z.object({
525
+ userId: z.string(),
526
+ }),
527
+ outputSchema: z.object({
528
+ user: z.object({
529
+ id: z.string(),
530
+ name: z.string(),
531
+ email: z.string(),
532
+ }),
533
+ }),
534
+ requireApproval: true,
535
+ execute: async input => {
536
+ const user = await database.findUser(input.userId)
537
+ return { user }
538
+ },
539
+ })
540
+
541
+ const dataAgent = new Agent({
542
+ id: 'data-agent',
543
+ name: 'Data Agent',
544
+ description: 'Handles database queries and user data retrieval',
545
+ model: 'openai/gpt-5-mini',
546
+ tools: { findUserTool },
547
+ })
548
+
549
+ const supervisorAgent = new Agent({
550
+ id: 'supervisor',
551
+ name: 'Supervisor Agent',
552
+ instructions: `You coordinate data retrieval tasks.
553
+ Delegate to data-agent for user lookups.`,
554
+ model: 'openai/gpt-5.6-sol',
555
+ agents: { dataAgent },
556
+ memory: new Memory(),
557
+ })
558
+
559
+ const stream = await supervisorAgent.stream('Find user with ID 12345')
560
+
561
+ for await (const chunk of stream.fullStream) {
562
+ if (chunk.type === 'tool-call-approval') {
563
+ console.log('Tool requires approval:', chunk.payload.toolName)
564
+ console.log('Arguments:', chunk.payload.args)
565
+
566
+ // Approve the tool call
567
+ const resumeStream = await supervisorAgent.approveToolCall({
568
+ runId: stream.runId,
569
+ toolCallId: chunk.payload.toolCallId,
570
+ })
571
+
572
+ for await (const resumeChunk of resumeStream.textStream) {
573
+ process.stdout.write(resumeChunk)
574
+ }
575
+
576
+ // To decline instead, use:
577
+ const declineStream = await supervisorAgent.declineToolCall({
578
+ runId: stream.runId,
579
+ toolCallId: chunk.payload.toolCallId,
580
+ })
581
+ }
582
+ }
583
+ ```
584
+
585
+ ### Use `suspend()` in supervisor agents
586
+
587
+ 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:
588
+
589
+ ```typescript
590
+ const conditionalTool = createTool({
591
+ id: 'conditional-operation',
592
+ description: 'Performs an operation that may require confirmation',
593
+ inputSchema: z.object({
594
+ operation: z.string(),
595
+ }),
596
+ suspendSchema: z.object({
597
+ message: z.string(),
598
+ }),
599
+ resumeSchema: z.object({
600
+ confirmed: z.boolean(),
601
+ }),
602
+ execute: async (input, context) => {
603
+ const { resumeData } = context?.agent ?? {}
604
+
605
+ if (!resumeData?.confirmed) {
606
+ return context?.agent?.suspend({
607
+ message: `Confirm: ${input.operation}?`,
608
+ })
609
+ }
610
+
611
+ // Proceed with operation
612
+ return await performOperation(input.operation)
613
+ },
614
+ })
615
+ ```
616
+
617
+ ```typescript
618
+ // When using this tool through a subagent in supervisor agents
619
+ for await (const chunk of stream.fullStream) {
620
+ if (chunk.type === 'tool-call-suspended') {
621
+ console.log('Tool suspended:', chunk.payload.suspendPayload.message)
622
+
623
+ // Resume with confirmation
624
+ const resumeStream = await supervisorAgent.resumeStream(
625
+ { confirmed: true },
626
+ { runId: stream.runId },
627
+ )
628
+
629
+ for await (const resumeChunk of resumeStream.textStream) {
630
+ process.stdout.write(resumeChunk)
631
+ }
632
+ }
633
+ }
634
+ ```
635
+
636
+ ### Supervisor approval with `generate()`
637
+
638
+ Tool approval propagation also works with `generate()` in supervisor agents:
639
+
640
+ ```typescript
641
+ const output = await supervisorAgent.generate('Find user with ID 12345', {
642
+ maxSteps: 10,
643
+ })
644
+
645
+ if (output.finishReason === 'suspended') {
646
+ console.log('Tool requires approval:', output.suspendPayload.toolName)
647
+
648
+ // Approve
649
+ const result = await supervisorAgent.approveToolCallGenerate({
650
+ runId: output.runId,
651
+ toolCallId: output.suspendPayload.toolCallId,
652
+ })
653
+
654
+ console.log('Final result:', result.text)
655
+ }
656
+ ```
657
+
658
+ ## Related
659
+
660
+ - [Tools](https://mastra.ai/docs/agents/using-tools)
661
+ - [Agent overview](https://mastra.ai/docs/agents/overview)
662
+ - [MCP overview](https://mastra.ai/docs/mcp/overview)
663
+ - [Memory](https://mastra.ai/docs/memory/overview)
664
+ - [Request context](https://mastra.ai/docs/server/request-context)