@mastra/client-js 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 (127) hide show
  1. package/CHANGELOG.md +9405 -3
  2. package/LICENSE.md +15 -0
  3. package/README.md +11 -13
  4. package/dist/_types/@ai-sdk_provider/dist/index.d.ts +1587 -0
  5. package/dist/_types/@ai-sdk_provider-utils/dist/index.d.ts +379 -0
  6. package/dist/_types/@ai-sdk_ui-utils/dist/index.d.ts +820 -0
  7. package/dist/agent-learning.d.ts +182 -0
  8. package/dist/agent-learning.d.ts.map +1 -0
  9. package/dist/client.d.ts +767 -80
  10. package/dist/client.d.ts.map +1 -1
  11. package/dist/docs/SKILL.md +52 -0
  12. package/dist/docs/assets/SOURCE_MAP.json +6 -0
  13. package/dist/docs/references/docs-agents-a2a.md +340 -0
  14. package/dist/docs/references/docs-editor-overview.md +349 -0
  15. package/dist/docs/references/docs-long-running-agents-schedules.md +201 -0
  16. package/dist/docs/references/docs-long-running-agents-signals.md +426 -0
  17. package/dist/docs/references/docs-server-auth-auth0.md +262 -0
  18. package/dist/docs/references/docs-server-auth-clerk.md +154 -0
  19. package/dist/docs/references/docs-server-auth-firebase.md +294 -0
  20. package/dist/docs/references/docs-server-auth-jwt.md +116 -0
  21. package/dist/docs/references/docs-server-auth-supabase.md +139 -0
  22. package/dist/docs/references/docs-server-auth-workos.md +271 -0
  23. package/dist/docs/references/docs-server-mastra-client.md +323 -0
  24. package/dist/docs/references/reference-ai-sdk-to-ai-sdk-messages.md +97 -0
  25. package/dist/docs/references/reference-ai-sdk-to-ai-sdk-stream.md +282 -0
  26. package/dist/docs/references/reference-ai-sdk-to-ai-sdk-v4-messages.md +81 -0
  27. package/dist/docs/references/reference-ai-sdk-to-ai-sdk-v5-messages.md +78 -0
  28. package/dist/docs/references/reference-client-js-agents.md +959 -0
  29. package/dist/docs/references/reference-client-js-conversations.md +137 -0
  30. package/dist/docs/references/reference-client-js-error-handling.md +18 -0
  31. package/dist/docs/references/reference-client-js-logs.md +26 -0
  32. package/dist/docs/references/reference-client-js-mastra-client.md +96 -0
  33. package/dist/docs/references/reference-client-js-memory.md +237 -0
  34. package/dist/docs/references/reference-client-js-observability.md +183 -0
  35. package/dist/docs/references/reference-client-js-responses.md +219 -0
  36. package/dist/docs/references/reference-client-js-telemetry.md +22 -0
  37. package/dist/docs/references/reference-client-js-tools.md +46 -0
  38. package/dist/docs/references/reference-client-js-vectors.md +81 -0
  39. package/dist/docs/references/reference-client-js-workflows.md +393 -0
  40. package/dist/docs/references/reference-editor-versioning.md +130 -0
  41. package/dist/index.cjs +7638 -3257
  42. package/dist/index.cjs.map +1 -1
  43. package/dist/index.d.ts +9 -0
  44. package/dist/index.d.ts.map +1 -1
  45. package/dist/index.js +7606 -3252
  46. package/dist/index.js.map +1 -1
  47. package/dist/observability/collector.d.ts +45 -0
  48. package/dist/observability/collector.d.ts.map +1 -0
  49. package/dist/observability/index.d.ts +14 -0
  50. package/dist/observability/index.d.ts.map +1 -0
  51. package/dist/observability/types.d.ts +27 -0
  52. package/dist/observability/types.d.ts.map +1 -0
  53. package/dist/resources/a2a.d.ts +80 -11
  54. package/dist/resources/a2a.d.ts.map +1 -1
  55. package/dist/resources/agent-builder.d.ts +57 -72
  56. package/dist/resources/agent-builder.d.ts.map +1 -1
  57. package/dist/resources/agent-controller.d.ts +589 -0
  58. package/dist/resources/agent-controller.d.ts.map +1 -0
  59. package/dist/resources/agent.d.ts +368 -59
  60. package/dist/resources/agent.d.ts.map +1 -1
  61. package/dist/resources/base.d.ts +2 -1
  62. package/dist/resources/base.d.ts.map +1 -1
  63. package/dist/resources/channels.d.ts +63 -0
  64. package/dist/resources/channels.d.ts.map +1 -0
  65. package/dist/resources/conversations.d.ts +15 -0
  66. package/dist/resources/conversations.d.ts.map +1 -0
  67. package/dist/resources/index.d.ts +14 -0
  68. package/dist/resources/index.d.ts.map +1 -1
  69. package/dist/resources/mcp-tool.d.ts +5 -5
  70. package/dist/resources/mcp-tool.d.ts.map +1 -1
  71. package/dist/resources/memory-thread.d.ts +51 -16
  72. package/dist/resources/memory-thread.d.ts.map +1 -1
  73. package/dist/resources/observability.d.ts +222 -19
  74. package/dist/resources/observability.d.ts.map +1 -1
  75. package/dist/resources/processor-provider.d.ts +15 -0
  76. package/dist/resources/processor-provider.d.ts.map +1 -0
  77. package/dist/resources/processor.d.ts +20 -0
  78. package/dist/resources/processor.d.ts.map +1 -0
  79. package/dist/resources/responses.d.ts +22 -0
  80. package/dist/resources/responses.d.ts.map +1 -0
  81. package/dist/resources/run.d.ts +256 -0
  82. package/dist/resources/run.d.ts.map +1 -0
  83. package/dist/resources/stored-agent.d.ts +112 -0
  84. package/dist/resources/stored-agent.d.ts.map +1 -0
  85. package/dist/resources/stored-mcp-client.d.ts +30 -0
  86. package/dist/resources/stored-mcp-client.d.ts.map +1 -0
  87. package/dist/resources/stored-prompt-block.d.ts +83 -0
  88. package/dist/resources/stored-prompt-block.d.ts.map +1 -0
  89. package/dist/resources/stored-scorer.d.ts +83 -0
  90. package/dist/resources/stored-scorer.d.ts.map +1 -0
  91. package/dist/resources/stored-skill.d.ts +40 -0
  92. package/dist/resources/stored-skill.d.ts.map +1 -0
  93. package/dist/resources/stored-workflow.d.ts +18 -0
  94. package/dist/resources/stored-workflow.d.ts.map +1 -0
  95. package/dist/resources/tool-provider.d.ts +80 -0
  96. package/dist/resources/tool-provider.d.ts.map +1 -0
  97. package/dist/resources/tool.d.ts +4 -4
  98. package/dist/resources/vector.d.ts +9 -9
  99. package/dist/resources/vector.d.ts.map +1 -1
  100. package/dist/resources/workflow.d.ts +32 -231
  101. package/dist/resources/workflow.d.ts.map +1 -1
  102. package/dist/resources/workspace.d.ts +129 -0
  103. package/dist/resources/workspace.d.ts.map +1 -0
  104. package/dist/route-types.generated.d.ts +18087 -0
  105. package/dist/route-types.generated.d.ts.map +1 -0
  106. package/dist/tools.d.ts +3 -6
  107. package/dist/tools.d.ts.map +1 -1
  108. package/dist/types.d.ts +2740 -197
  109. package/dist/types.d.ts.map +1 -1
  110. package/dist/utils/client-tool-model-output.d.ts +16 -0
  111. package/dist/utils/client-tool-model-output.d.ts.map +1 -0
  112. package/dist/utils/index.d.ts +65 -4
  113. package/dist/utils/index.d.ts.map +1 -1
  114. package/dist/utils/process-a2a-stream.d.ts +4 -0
  115. package/dist/utils/process-a2a-stream.d.ts.map +1 -0
  116. package/dist/utils/process-client-tools.d.ts.map +1 -1
  117. package/dist/utils/process-mastra-stream.d.ts +8 -7
  118. package/dist/utils/process-mastra-stream.d.ts.map +1 -1
  119. package/dist/utils/stream-transforms.d.ts +9 -0
  120. package/dist/utils/stream-transforms.d.ts.map +1 -0
  121. package/dist/utils/verify-agent-card-signature.d.ts +21 -0
  122. package/dist/utils/verify-agent-card-signature.d.ts.map +1 -0
  123. package/dist/utils/zod-to-json-schema.d.ts +11 -2
  124. package/dist/utils/zod-to-json-schema.d.ts.map +1 -1
  125. package/package.json +26 -19
  126. package/dist/resources/network-memory-thread.d.ts +0 -47
  127. package/dist/resources/network-memory-thread.d.ts.map +0 -1
@@ -0,0 +1,959 @@
1
+ > Discover all available pages from the documentation index: https://mastra.ai/llms.txt
2
+
3
+ # Agents API
4
+
5
+ The Agents API provides methods to interact with Mastra AI agents, including generating responses and streaming interactions. It also provides methods for managing agent tools.
6
+
7
+ ## Getting all agents
8
+
9
+ Retrieve a list of all available agents:
10
+
11
+ ```typescript
12
+ const agents = await mastraClient.listAgents()
13
+ ```
14
+
15
+ Returns a record of agent IDs to their serialized agent configurations.
16
+
17
+ ## Working with a specific agent
18
+
19
+ Get an instance of a specific agent by its ID:
20
+
21
+ ```typescript
22
+ export const myAgent = new Agent({
23
+ id: 'my-agent',
24
+ })
25
+ ```
26
+
27
+ ```typescript
28
+ const agent = mastraClient.getAgent('my-agent')
29
+ ```
30
+
31
+ ## Agent methods
32
+
33
+ ### `details()`
34
+
35
+ Retrieve detailed information about an agent:
36
+
37
+ ```typescript
38
+ const details = await agent.details()
39
+ ```
40
+
41
+ ### `generate()`
42
+
43
+ Generate a response from the agent:
44
+
45
+ ```typescript
46
+ const response = await agent.generate(
47
+ [
48
+ {
49
+ role: 'user',
50
+ content: 'Hello, how are you?',
51
+ },
52
+ ],
53
+ {
54
+ memory: {
55
+ thread: 'thread-abc', // Optional: Thread ID for conversation context
56
+ resource: 'user-123', // Optional: Resource ID
57
+ },
58
+ structuredOutput: {}, // Optional: Structured Output configuration
59
+ },
60
+ )
61
+ ```
62
+
63
+ You can also use the simplified string format with memory options:
64
+
65
+ ```typescript
66
+ const response = await agent.generate('Hello, how are you?', {
67
+ memory: {
68
+ thread: 'thread-1',
69
+ resource: 'resource-1',
70
+ },
71
+ })
72
+ ```
73
+
74
+ ### `stream()`
75
+
76
+ Stream responses from the agent for real-time interactions:
77
+
78
+ ```typescript
79
+ const response = await agent.stream('Tell me a story')
80
+
81
+ // Process data stream with the processDataStream util
82
+ response.processDataStream({
83
+ onChunk: async chunk => {
84
+ console.log(chunk)
85
+ },
86
+ })
87
+ ```
88
+
89
+ You can also use the simplified string format with memory options:
90
+
91
+ ```typescript
92
+ const response = await agent.stream('Tell me a story', {
93
+ memory: {
94
+ thread: 'thread-1',
95
+ resource: 'resource-1',
96
+ },
97
+ clientTools: { colorChangeTool },
98
+ })
99
+
100
+ response.processDataStream({
101
+ onChunk: async chunk => {
102
+ if (chunk.type === 'text-delta') {
103
+ console.log(chunk.payload.text)
104
+ }
105
+ },
106
+ })
107
+ ```
108
+
109
+ You can also read from response body directly:
110
+
111
+ ```typescript
112
+ const reader = response.body.getReader()
113
+ while (true) {
114
+ const { done, value } = await reader.read()
115
+ if (done) break
116
+ console.log(new TextDecoder().decode(value))
117
+ }
118
+ ```
119
+
120
+ #### AI SDK compatible format
121
+
122
+ To stream AI SDK-formatted parts on the client from an `agent.stream(...)` response, wrap `response.processDataStream` into a `ReadableStream<ChunkType>` and use `toAISdkStream`:
123
+
124
+ ```typescript
125
+ import { createUIMessageStream } from 'ai'
126
+ import { toAISdkStream } from '@mastra/ai-sdk'
127
+ import type { ChunkType, MastraModelOutput } from '@mastra/core/stream'
128
+
129
+ const response = await agent.stream('Tell me a story')
130
+
131
+ const chunkStream: ReadableStream<ChunkType> = new ReadableStream<ChunkType>({
132
+ start(controller) {
133
+ response
134
+ .processDataStream({
135
+ onChunk: async chunk => controller.enqueue(chunk as ChunkType),
136
+ })
137
+ .finally(() => controller.close())
138
+ },
139
+ })
140
+
141
+ const uiMessageStream = createUIMessageStream({
142
+ execute: async ({ writer }) => {
143
+ for await (const part of toAISdkStream(chunkStream as unknown as MastraModelOutput, {
144
+ from: 'agent',
145
+ })) {
146
+ writer.write(part)
147
+ }
148
+ },
149
+ })
150
+
151
+ for await (const part of uiMessageStream) {
152
+ console.log(part)
153
+ }
154
+ ```
155
+
156
+ ### `sendMessage()`
157
+
158
+ Send user-authored input to an active agent run or idle memory thread. Use this with `subscribeToThread()` so the client can render the stream that wakes from, or receives the message.
159
+
160
+ ```typescript
161
+ const agent = mastraClient.getAgent('support-agent')
162
+
163
+ const result = await agent.sendMessage({
164
+ message: {
165
+ contents: 'Also consider the customer note I just added.',
166
+ attributes: { sentFrom: 'web' },
167
+ },
168
+ resourceId: 'user-123',
169
+ threadId: 'thread-abc',
170
+ })
171
+
172
+ console.log(result.runId)
173
+ ```
174
+
175
+ `message` accepts a string, an array of text/file parts, or an object with `contents`, `attributes`, `metadata`, and `providerOptions`.
176
+
177
+ ### `queueMessage()`
178
+
179
+ Queue user-authored input for the next thread turn. If the thread is active, Mastra starts a new run after the current run completes. If the thread is idle, Mastra starts a run immediately.
180
+
181
+ ```typescript
182
+ await agent.queueMessage({
183
+ message: 'Also check whether the tests need updates.',
184
+ resourceId: 'user-123',
185
+ threadId: 'thread-abc',
186
+ })
187
+ ```
188
+
189
+ ### `sendSignal()`
190
+
191
+ Send a lower-level signal to an active agent run or memory thread. Use this for system-generated context such as reactive reminders or notification-shaped context that doesn't need inbox storage. For durable notification records, use the server-side [`Agent.sendNotificationSignal()`](https://mastra.ai/reference/agents/agent) API. For user-authored input, prefer `sendMessage()` or `queueMessage()`.
192
+
193
+ ```typescript
194
+ const agent = mastraClient.getAgent('support-agent')
195
+
196
+ const result = await agent.sendSignal({
197
+ signal: {
198
+ type: 'reactive',
199
+ tagName: 'system-reminder',
200
+ contents: 'Also consider the latest customer note.',
201
+ },
202
+ resourceId: 'user-123',
203
+ threadId: 'thread-abc',
204
+ })
205
+
206
+ console.log(result.runId)
207
+ ```
208
+
209
+ Use `ifActive.behavior` and `ifIdle.behavior` to control whether Mastra delivers, persists, discards, or wakes from a signal:
210
+
211
+ ```typescript
212
+ await agent.sendSignal({
213
+ signal: { type: 'reactive', tagName: 'system-reminder', contents: 'Store this for later.' },
214
+ resourceId: 'user-123',
215
+ threadId: 'thread-abc',
216
+ ifIdle: {
217
+ behavior: 'persist',
218
+ },
219
+ })
220
+ ```
221
+
222
+ Pass `ifIdle.streamOptions` when the idle wake-up stream needs options such as model settings, tools, or runtime context:
223
+
224
+ ```typescript
225
+ await agent.sendSignal({
226
+ signal: { type: 'reactive', tagName: 'system-reminder', contents: 'Start from this signal.' },
227
+ resourceId: 'user-123',
228
+ threadId: 'thread-abc',
229
+ ifIdle: {
230
+ behavior: 'wake',
231
+ streamOptions: {
232
+ maxSteps: 3,
233
+ },
234
+ },
235
+ })
236
+ ```
237
+
238
+ Returns `{ accepted: true, runId: string }`.
239
+
240
+ **signal** (`{ type: 'user' | 'reactive' | 'notification' | string; tagName?: string; contents: string | Array<TextPart | FilePart>; attributes?: Record<string, JSONValue>; metadata?: Record<string, unknown>; providerOptions?: ProviderMetadata }`): Lower-level signal payload. Use type for the semantic signal category and tagName for the XML tag shown to the model. providerOptions is attached to the resulting prompt turn and persisted on the stored signal message.
241
+
242
+ **runId** (`string`): Run ID to target directly.
243
+
244
+ **resourceId** (`string`): Resource ID for the memory thread. Use with threadId for thread-targeted signals.
245
+
246
+ **threadId** (`string`): Thread ID to target. Use with resourceId for thread-targeted signals.
247
+
248
+ **ifActive.behavior** (`'deliver' | 'persist' | 'discard'`): Controls what happens when the target thread is active. Defaults to deliver.
249
+
250
+ **ifActive.attributes** (`Record<string, string | number | boolean>`): Attributes merged into the signal when Mastra accepts it while the target thread is active.
251
+
252
+ **ifIdle.behavior** (`'wake' | 'persist' | 'discard'`): Controls what happens when the target thread is idle. Defaults to wake.
253
+
254
+ **ifIdle.streamOptions** (`Omit<AgentExecutionOptions, 'messages'>`): Options for the stream that starts when ifIdle.behavior is wake.
255
+
256
+ **ifIdle.attributes** (`Record<string, string | number | boolean>`): Attributes merged into the signal when Mastra accepts it while the target thread is idle.
257
+
258
+ ### `subscribeToThread()`
259
+
260
+ Subscribe to raw stream chunks for a memory thread. Use this to render output from a thread that may be started or continued by `sendMessage()`, `queueMessage()`, `sendSignal()`, or server-side notification dispatch.
261
+
262
+ ```typescript
263
+ const agent = mastraClient.getAgent('support-agent')
264
+
265
+ const subscription = await agent.subscribeToThread({
266
+ resourceId: 'user-123',
267
+ threadId: 'thread-abc',
268
+ })
269
+
270
+ await subscription.processDataStream({
271
+ onChunk: chunk => {
272
+ console.log(chunk)
273
+ },
274
+ reconnect: true,
275
+ })
276
+ ```
277
+
278
+ `subscribeToThread()` returns the underlying `Response` plus a `processDataStream()` helper. The helper reads the subscription stream until the connection closes or the request is aborted. Pass `reconnect: true` to resubscribe when the transport closes or a reconnect request fails, such as after a proxy idle timeout.
279
+
280
+ **resourceId** (`string`): Resource ID for the memory thread.
281
+
282
+ **threadId** (`string`): Thread ID to subscribe to.
283
+
284
+ **processDataStream().reconnect** (`boolean | { maxRetries?: number; delayMs?: number }`): Reconnects the subscription stream after it closes or a reconnect request fails. true retries indefinitely with a one-second delay.
285
+
286
+ ### `streamUntilIdle()`
287
+
288
+ Stream a response and keep the stream open until every [background task](https://mastra.ai/docs/long-running-agents/background-tasks) dispatched during the run completes. The server re-enters the agentic loop on each task completion so the LLM can react to results in the same call. Requires background tasks to be [enabled on the Mastra instance](https://mastra.ai/reference/configuration) and a memory thread; otherwise the call uses a plain `stream()`.
289
+
290
+ ```typescript
291
+ const response = await agent.streamUntilIdle('Research solana for me', {
292
+ memory: {
293
+ thread: 'thread-1',
294
+ resource: 'resource-1',
295
+ },
296
+ maxIdleMs: 5 * 60_000, //optional
297
+ })
298
+
299
+ response.processDataStream({
300
+ onChunk: async chunk => {
301
+ if (chunk.type === 'background-task-completed') {
302
+ console.log('task complete:', chunk.payload.taskId)
303
+ }
304
+ },
305
+ })
306
+ ```
307
+
308
+ ### `resumeStreamUntilIdle()`
309
+
310
+ Resume a suspended agent stream with custom data and keep the stream open until every [background task](https://mastra.ai/docs/long-running-agents/background-tasks) dispatched during the run completes. Use this to continue execution after a suspension point, such as a workflow suspend within an agent. Requires background tasks to be [enabled on the Mastra instance](https://mastra.ai/reference/configuration) and a memory thread; otherwise the call uses a plain `resumeStream()`:
311
+
312
+ ```typescript
313
+ const response = await agent.resumeStreamUntilIdle(
314
+ { approved: true, selectedOption: 'plan-b' },
315
+ {
316
+ memory: {
317
+ thread: 'thread-1',
318
+ resource: 'resource-1',
319
+ },
320
+ runId: 'run-123',
321
+ toolCallId: 'tool-call-456', // optional
322
+ maxIdleMs: 5 * 60_000, //optional
323
+ },
324
+ )
325
+
326
+ await response.processDataStream({
327
+ onChunk: chunk => {
328
+ console.log(chunk)
329
+ },
330
+ })
331
+ ```
332
+
333
+ The stream emits the same chunk types as `stream()`, plus `background-task-*` chunks for task lifecycle events. Visit [`Agent.streamUntilIdle()`](https://mastra.ai/reference/streaming/agents/streamUntilIdle) for the full server-side API and [background task chunks](https://mastra.ai/reference/streaming/ChunkType) for the payload shapes.
334
+
335
+ ### `getTool()`
336
+
337
+ Retrieve information about a specific tool available to the agent:
338
+
339
+ ```typescript
340
+ const tool = await agent.getTool('tool-id')
341
+ ```
342
+
343
+ ### `executeTool()`
344
+
345
+ Execute a specific tool for the agent:
346
+
347
+ ```typescript
348
+ const result = await agent.executeTool('tool-id', {
349
+ data: { input: 'value' },
350
+ })
351
+ ```
352
+
353
+ ### `network()`
354
+
355
+ Stream responses from an agent network for multi-agent interactions:
356
+
357
+ ```typescript
358
+ const response = await agent.network('Research this topic and write a summary')
359
+
360
+ response.processDataStream({
361
+ onChunk: async chunk => {
362
+ console.log(chunk)
363
+ },
364
+ })
365
+ ```
366
+
367
+ ### `listSuspendedRuns()`
368
+
369
+ List suspended runs for the agent from storage: runs waiting on a tool-call approval or on a tool that suspended. Discovery is backed by storage, so it works after a server restart and across server instances. Pass the returned `runId` to `approveToolCall()`, `declineToolCall()`, or `resumeStream()`.
370
+
371
+ ```typescript
372
+ const { runs, total } = await agent.listSuspendedRuns({
373
+ threadId: 'thread-456',
374
+ resourceId: 'user-123',
375
+ })
376
+
377
+ if (runs[0]) {
378
+ console.log(runs[0].toolCalls) // [{ toolCallId, toolName, args, requiresApproval }]
379
+ await agent.approveToolCall({
380
+ runId: runs[0].runId,
381
+ toolCallId: runs[0].toolCalls[0].toolCallId,
382
+ })
383
+ }
384
+ ```
385
+
386
+ Accepts optional filters (`threadId`, `resourceId`, `fromDate`, `toDate`) and pagination (`perPage`, `page`). Returns `{ runs, total }`, where `total` is the number of matching runs before pagination. See [`Agent.listSuspendedRuns()`](https://mastra.ai/reference/agents/listSuspendedRuns) for details on the returned run shape.
387
+
388
+ ### `approveToolCall()`
389
+
390
+ Approve a pending tool call and return a continuation stream. Use this when you are rendering the resumed chunks from the approval response.
391
+
392
+ ```typescript
393
+ const response = await agent.approveToolCall({
394
+ runId: 'run-123',
395
+ toolCallId: 'tool-call-456',
396
+ })
397
+
398
+ response.processDataStream({
399
+ onChunk: async chunk => {
400
+ console.log(chunk)
401
+ },
402
+ })
403
+ ```
404
+
405
+ ### `sendToolApproval()`
406
+
407
+ Approve or decline a pending tool call for a subscribed thread. Use this with `subscribeToThread()` when the resumed chunks should arrive through the existing thread subscription instead of a separate continuation stream.
408
+
409
+ ```typescript
410
+ const result = await agent.sendToolApproval({
411
+ resourceId: 'user-123',
412
+ threadId: 'thread-456',
413
+ toolCallId: 'tool-call-456',
414
+ approved: true,
415
+ })
416
+
417
+ console.log(result.accepted)
418
+ ```
419
+
420
+ Returns `{ accepted: true, runId: string, toolCallId?: string }`.
421
+
422
+ ### `declineToolCall()`
423
+
424
+ Decline a pending tool call and return a continuation stream. Use this when you are rendering the resumed chunks from the decline response.
425
+
426
+ ```typescript
427
+ const response = await agent.declineToolCall({
428
+ runId: 'run-123',
429
+ toolCallId: 'tool-call-456',
430
+ })
431
+
432
+ response.processDataStream({
433
+ onChunk: async chunk => {
434
+ console.log(chunk)
435
+ },
436
+ })
437
+ ```
438
+
439
+ ### `resumeStream()`
440
+
441
+ Resume a suspended agent stream with custom data. Use this to continue execution after a suspension point, such as a workflow suspend within an agent:
442
+
443
+ ```typescript
444
+ const response = await agent.resumeStream(
445
+ { approved: true, selectedOption: 'plan-b' },
446
+ {
447
+ runId: 'run-123',
448
+ toolCallId: 'tool-call-456', // optional
449
+ },
450
+ )
451
+
452
+ await response.processDataStream({
453
+ onChunk: chunk => {
454
+ console.log(chunk)
455
+ },
456
+ })
457
+ ```
458
+
459
+ ### `approveToolCallGenerate()`
460
+
461
+ Approve a pending tool call when using `generate()` (non-streaming). Returns the complete response:
462
+
463
+ ```typescript
464
+ const output = await agent.generate('Find user John', {
465
+ requireToolApproval: true,
466
+ })
467
+
468
+ if (output.finishReason === 'suspended') {
469
+ const result = await agent.approveToolCallGenerate({
470
+ runId: output.runId,
471
+ toolCallId: output.suspendPayload.toolCallId,
472
+ })
473
+
474
+ console.log(result.text)
475
+ }
476
+ ```
477
+
478
+ ### `declineToolCallGenerate()`
479
+
480
+ Decline a pending tool call when using `generate()` (non-streaming). Returns the complete response:
481
+
482
+ ```typescript
483
+ const output = await agent.generate('Find user John', {
484
+ requireToolApproval: true,
485
+ })
486
+
487
+ if (output.finishReason === 'suspended') {
488
+ const result = await agent.declineToolCallGenerate({
489
+ runId: output.runId,
490
+ toolCallId: output.suspendPayload.toolCallId,
491
+ })
492
+
493
+ console.log(result.text)
494
+ }
495
+ ```
496
+
497
+ ## Agent schedules
498
+
499
+ Use the client SDK schedule methods to manage persisted agent schedules over the `/api/schedules` routes. For concepts and server-side examples, see [Schedules](https://mastra.ai/docs/long-running-agents/schedules) and the [`mastra.schedules` reference](https://mastra.ai/reference/schedules/overview).
500
+
501
+ ### `createSchedule()`
502
+
503
+ Create an agent schedule by passing `agentId`.
504
+
505
+ ```typescript
506
+ const schedule = await mastraClient.createSchedule({
507
+ agentId: 'pinger',
508
+ cron: '0 * * * *',
509
+ prompt: 'Give me a status update.',
510
+ })
511
+ ```
512
+
513
+ ### `listSchedules()`
514
+
515
+ List agent schedules. Filter by fields such as `agentId`, `threadId`, `resourceId`, `name`, or `status`.
516
+
517
+ ```typescript
518
+ const schedules = await mastraClient.listSchedules({
519
+ agentId: 'pinger',
520
+ status: 'active',
521
+ })
522
+ ```
523
+
524
+ ### `getSchedule()`
525
+
526
+ Fetch a single agent schedule by ID.
527
+
528
+ ```typescript
529
+ const schedule = await mastraClient.getSchedule('agent_pinger')
530
+ ```
531
+
532
+ ### `updateSchedule()`
533
+
534
+ Update an agent schedule. Agent schedules can update fields such as `cron`, `timezone`, `prompt`, `name`, signal delivery options, metadata, and `status`.
535
+
536
+ ```typescript
537
+ const updated = await mastraClient.updateSchedule('agent_pinger', {
538
+ cron: '*/30 * * * *',
539
+ prompt: 'Give me a status update every 30 minutes.',
540
+ })
541
+ ```
542
+
543
+ ### `deleteSchedule()`
544
+
545
+ Delete an agent schedule.
546
+
547
+ ```typescript
548
+ await mastraClient.deleteSchedule('agent_pinger')
549
+ ```
550
+
551
+ ### `runSchedule()`
552
+
553
+ Fire an agent schedule once immediately without changing its cron cadence.
554
+
555
+ ```typescript
556
+ const run = await mastraClient.runSchedule('agent_pinger')
557
+ ```
558
+
559
+ ### `pauseSchedule()`
560
+
561
+ Pause an agent schedule so the scheduler stops firing it. Returns the updated schedule.
562
+
563
+ ```typescript
564
+ await mastraClient.pauseSchedule('agent_pinger')
565
+ ```
566
+
567
+ ### `resumeSchedule()`
568
+
569
+ Resume a paused agent schedule. The next fire time is recomputed from now, so a long-paused schedule doesn't fire a backlog. Returns the updated schedule.
570
+
571
+ ```typescript
572
+ await mastraClient.resumeSchedule('agent_pinger')
573
+ ```
574
+
575
+ ### `listScheduleTriggers()`
576
+
577
+ List the trigger history for an agent schedule, including the joined run summary for each fire.
578
+
579
+ ```typescript
580
+ const { triggers } = await mastraClient.listScheduleTriggers('agent_pinger', {
581
+ limit: 50,
582
+ })
583
+ ```
584
+
585
+ ## Client tools
586
+
587
+ Client-side tools allow you to execute custom functions on the client side when the agent requests them.
588
+
589
+ ```typescript
590
+ import { createTool } from '@mastra/client-js'
591
+ import { z } from 'zod'
592
+
593
+ const colorChangeTool = createTool({
594
+ id: 'changeColor',
595
+ description: 'Changes the background color',
596
+ inputSchema: z.object({
597
+ color: z.string(),
598
+ }),
599
+ execute: async inputData => {
600
+ document.body.style.backgroundColor = inputData.color
601
+ return { success: true }
602
+ },
603
+ })
604
+
605
+ // Use with generate
606
+ const response = await agent.generate('Change the background to blue', {
607
+ clientTools: { colorChangeTool },
608
+ })
609
+
610
+ // Use with stream
611
+ const response = await agent.stream('Tell me a story', {
612
+ memory: {
613
+ thread: 'thread-1',
614
+ resource: 'resource-1',
615
+ },
616
+ clientTools: { colorChangeTool },
617
+ })
618
+
619
+ response.processDataStream({
620
+ onChunk: async chunk => {
621
+ if (chunk.type === 'text-delta') {
622
+ console.log(chunk.payload.text)
623
+ } else if (chunk.type === 'tool-call') {
624
+ console.log(
625
+ `calling tool ${chunk.payload.toolName} with args ${JSON.stringify(
626
+ chunk.payload.args,
627
+ null,
628
+ 2,
629
+ )}`,
630
+ )
631
+ }
632
+ },
633
+ })
634
+ ```
635
+
636
+ ### Shape client tool output for the model
637
+
638
+ Client tools support `toModelOutput` to control what the model receives, including multimodal content such as images. Because client tools execute locally, the mapping also runs on the client after `execute` completes. The transformed output is sent back to the server alongside the raw result, so the raw result stays available for storage and application logic.
639
+
640
+ ```typescript
641
+ const screenshotTool = createTool({
642
+ id: 'takeScreenshot',
643
+ description: 'Takes a screenshot of the current page',
644
+ inputSchema: z.object({}),
645
+ execute: async () => {
646
+ const base64 = await captureScreenshot()
647
+ return { ok: true, data: base64 }
648
+ },
649
+ toModelOutput: output => ({
650
+ type: 'content',
651
+ value: [{ type: 'media', data: output.data, mediaType: 'image/jpeg' }],
652
+ }),
653
+ })
654
+ ```
655
+
656
+ ### Tracing client tools
657
+
658
+ When `@mastra/observability` is installed and configured on the server, a client-side tool records a `CLIENT_TOOL_CALL` span as a child of the current `AGENT_RUN` span. The server creates that span when the model emits the client tool call and injects a W3C trace carrier into the outgoing tool-call chunk. It ends the span once the tool arguments are available. Without server-side observability configured, client tool tracing is a no-op.
659
+
660
+ The client SDK also measures the wall-clock duration of each client tool's `execute` function and sends it back to the server, where it's emitted as a `mastra_tool_duration_ms` metric with `toolType: "client"`.
661
+
662
+ For richer telemetry from inside your tool's `execute` function, use the `observe` helper on the execution context to add child spans and structured logs:
663
+
664
+ ```typescript
665
+ import { createTool } from '@mastra/client-js'
666
+ import { z } from 'zod'
667
+
668
+ const fetchUserTool = createTool({
669
+ id: 'fetchUser',
670
+ description: 'Fetches the current user profile',
671
+ inputSchema: z.object({ userId: z.string() }),
672
+ execute: async ({ userId }, { observe }) => {
673
+ observe.log('info', 'fetching user', { userId })
674
+ const user = await observe.span('http GET /users', async () => {
675
+ const res = await fetch(`/api/users/${userId}`)
676
+ return res.json()
677
+ })
678
+ return user
679
+ },
680
+ })
681
+ ```
682
+
683
+ `observe` is always available: when no tracing context is active (e.g. running outside a traced agent), `span` runs the function directly and `log` is a no-op. No null-checking needed.
684
+
685
+ The SDK serializes everything the collector buffered as OTLP/JSON and sends it back in the next request body. The server's `@mastra/observability` package validates that the spans belong to the correct trace (preventing cross-trace injection) and forwards each span/log into the same observability bus that server-side telemetry uses. Your existing exporters pick them up automatically after observability is configured.
686
+
687
+ ## Stored agents
688
+
689
+ Stored agents are agent configurations stored in a database that can be created, updated, and deleted at runtime. They reference primitives (tools, workflows, other agents, scorers) by key, which are resolved from the Mastra registry when the agent is instantiated. Memory is configured inline as a `SerializedMemoryConfig` object with options such as `lastMessages` and `semanticRecall`.
690
+
691
+ ### `listStoredAgents()`
692
+
693
+ Retrieve a paginated list of all stored agents:
694
+
695
+ ```typescript
696
+ const result = await mastraClient.listStoredAgents()
697
+ console.log(result.agents) // Array of stored agents
698
+ console.log(result.total) // Total count
699
+ ```
700
+
701
+ With pagination and ordering:
702
+
703
+ ```typescript
704
+ const result = await mastraClient.listStoredAgents({
705
+ page: 0,
706
+ perPage: 20,
707
+ orderBy: {
708
+ field: 'createdAt',
709
+ direction: 'DESC',
710
+ },
711
+ })
712
+ ```
713
+
714
+ ### `createStoredAgent()`
715
+
716
+ Create a new stored agent:
717
+
718
+ ```typescript
719
+ const agent = await mastraClient.createStoredAgent({
720
+ id: 'my-agent',
721
+ name: 'My Assistant',
722
+ instructions: 'You are a helpful assistant.',
723
+ model: {
724
+ provider: 'openai',
725
+ name: 'gpt-5.4',
726
+ },
727
+ })
728
+ ```
729
+
730
+ By default, `createStoredAgent()` publishes the initial version immediately. Set `autoPublish` to `false` to create an unpublished draft that you can review before calling [`activateVersion()`](#activateversion):
731
+
732
+ ```typescript
733
+ const draft = await mastraClient.createStoredAgent({
734
+ id: 'draft-agent',
735
+ name: 'Draft Assistant',
736
+ instructions: 'You are a helpful assistant.',
737
+ model: {
738
+ provider: 'openai',
739
+ name: 'gpt-5',
740
+ },
741
+ autoPublish: false,
742
+ })
743
+ ```
744
+
745
+ Editors configured with the `code` source always publish the initial version because saving writes the agent configuration to the file system.
746
+
747
+ With all options:
748
+
749
+ ```typescript
750
+ const agent = await mastraClient.createStoredAgent({
751
+ id: 'full-agent',
752
+ name: 'Full Agent',
753
+ description: 'A fully configured agent',
754
+ instructions: 'You are a helpful assistant.',
755
+ model: {
756
+ provider: 'openai',
757
+ name: 'gpt-5.4',
758
+ },
759
+ tools: { calculator: {}, weather: {} },
760
+ workflows: { 'data-processing': {} },
761
+ agents: { 'subagent-1': {} },
762
+ memory: {
763
+ options: {
764
+ lastMessages: 20,
765
+ semanticRecall: false,
766
+ },
767
+ },
768
+ scorers: {
769
+ 'quality-scorer': {
770
+ sampling: { type: 'ratio', rate: 0.1 },
771
+ },
772
+ },
773
+ defaultOptions: {
774
+ maxSteps: 10,
775
+ },
776
+ metadata: {
777
+ version: '1.0',
778
+ team: 'engineering',
779
+ },
780
+ })
781
+ ```
782
+
783
+ ### `getStoredAgent()`
784
+
785
+ Get an instance of a specific stored agent:
786
+
787
+ ```typescript
788
+ const storedAgent = mastraClient.getStoredAgent('my-agent')
789
+ ```
790
+
791
+ ## Stored agent methods
792
+
793
+ ### `details()`
794
+
795
+ Retrieve the stored agent configuration:
796
+
797
+ ```typescript
798
+ const details = await storedAgent.details()
799
+ console.log(details.name)
800
+ console.log(details.instructions)
801
+ console.log(details.model)
802
+ ```
803
+
804
+ ### `update()`
805
+
806
+ Update specific fields of a stored agent. All fields are optional:
807
+
808
+ ```typescript
809
+ const updated = await storedAgent.update({
810
+ name: 'Updated Agent Name',
811
+ instructions: 'New instructions for the agent.',
812
+ })
813
+ ```
814
+
815
+ ```typescript
816
+ // Update just the tools
817
+ await storedAgent.update({
818
+ tools: { 'new-tool-1': {}, 'new-tool-2': {} },
819
+ })
820
+
821
+ // Update metadata
822
+ await storedAgent.update({
823
+ metadata: {
824
+ version: '2.0',
825
+ lastModifiedBy: 'admin',
826
+ },
827
+ })
828
+ ```
829
+
830
+ ### `delete()`
831
+
832
+ Delete a stored agent:
833
+
834
+ ```typescript
835
+ const result = await storedAgent.delete()
836
+ console.log(result.success) // true
837
+ ```
838
+
839
+ ## Version management
840
+
841
+ Both `Agent` (code-defined) and `StoredAgent` instances have methods for managing configuration versions. See [Editor versioning](https://mastra.ai/docs/editor/overview) for lifecycle and selection behavior.
842
+
843
+ ### Getting an agent with a specific version
844
+
845
+ Pass a version identifier when getting an agent:
846
+
847
+ ```typescript
848
+ // Load the published version (default)
849
+ const agent = mastraClient.getAgent('support-agent')
850
+
851
+ // Load the latest draft
852
+ const draftAgent = mastraClient.getAgent('support-agent', { status: 'draft' })
853
+
854
+ // Load a specific version
855
+ const versionedAgent = mastraClient.getAgent('support-agent', { versionId: 'abc-123' })
856
+ ```
857
+
858
+ For stored agents, pass a status option to `details()`:
859
+
860
+ ```typescript
861
+ const storedAgent = mastraClient.getStoredAgent('my-agent')
862
+ const draft = await storedAgent.details(undefined, { status: 'draft' })
863
+ ```
864
+
865
+ ### `listVersions()`
866
+
867
+ List all versions for an agent:
868
+
869
+ ```typescript
870
+ const versions = await agent.listVersions()
871
+ console.log(versions.items) // Array of version snapshots
872
+ console.log(versions.total)
873
+ ```
874
+
875
+ With pagination and sorting:
876
+
877
+ ```typescript
878
+ const versions = await agent.listVersions({
879
+ page: 0,
880
+ perPage: 10,
881
+ orderBy: {
882
+ field: 'createdAt',
883
+ direction: 'DESC',
884
+ },
885
+ })
886
+ ```
887
+
888
+ ### `createVersion()`
889
+
890
+ Create a new version snapshot:
891
+
892
+ ```typescript
893
+ const version = await agent.createVersion({
894
+ changeMessage: 'Updated tone to be more friendly',
895
+ })
896
+ ```
897
+
898
+ ### `getVersion()`
899
+
900
+ Get a specific version by ID:
901
+
902
+ ```typescript
903
+ const version = await agent.getVersion('version-123')
904
+ console.log(version.versionNumber)
905
+ console.log(version.changedFields)
906
+ console.log(version.createdAt)
907
+ ```
908
+
909
+ ### `activateVersion()`
910
+
911
+ Set a version as the active published version:
912
+
913
+ ```typescript
914
+ await agent.activateVersion('version-123')
915
+ ```
916
+
917
+ ### `restoreVersion()`
918
+
919
+ Restore a previous version by creating a new version with the same configuration:
920
+
921
+ ```typescript
922
+ await agent.restoreVersion('version-456')
923
+ ```
924
+
925
+ ### `deleteVersion()`
926
+
927
+ Delete a version:
928
+
929
+ ```typescript
930
+ await agent.deleteVersion('version-789')
931
+ ```
932
+
933
+ ### `compareVersions()`
934
+
935
+ Compare two versions and return their differences:
936
+
937
+ ```typescript
938
+ const diff = await agent.compareVersions('version-123', 'version-456')
939
+ console.log(diff.changes) // Fields that changed between versions
940
+ ```
941
+
942
+ ### React SDK
943
+
944
+ In the React SDK, pass an `agentVersionId` through `requestContext` when using the `useChat` hook:
945
+
946
+ ```typescript
947
+ import { useChat } from '@mastra/react'
948
+
949
+ function Chat() {
950
+ const { messages, input, handleInputChange, handleSubmit } = useChat({
951
+ agentId: 'support-agent',
952
+ requestContext: {
953
+ agentVersionId: 'abc-123',
954
+ },
955
+ })
956
+
957
+ // ... render chat UI
958
+ }
959
+ ```