@mastra/mcp-docs-server 1.3.14-alpha.0 → 1.3.14-alpha.2

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 (33) hide show
  1. package/.docs/docs/agents/guardrails.md +3 -3
  2. package/.docs/docs/agents/human-in-the-loop.md +14 -0
  3. package/.docs/docs/agents/processors.md +3 -3
  4. package/.docs/docs/deployment/web-framework.md +1 -1
  5. package/.docs/docs/deployment/workers.md +16 -4
  6. package/.docs/docs/harness/agent-controller.md +2 -0
  7. package/.docs/docs/harness/background-tasks.md +3 -1
  8. package/.docs/docs/harness/durable-agents.md +1 -1
  9. package/.docs/docs/sandbox/overview.md +25 -2
  10. package/.docs/docs/server/request-context.md +1 -1
  11. package/.docs/docs/server/server-adapters.md +1 -0
  12. package/.docs/docs/studio/knowledge.md +34 -0
  13. package/.docs/docs/workflows/overview.md +21 -3
  14. package/.docs/integrations/deploy/kubernetes-helm.md +8 -9
  15. package/.docs/integrations/frameworks/next-js.md +22 -6
  16. package/.docs/integrations/observability/opentelemetry.md +27 -2
  17. package/.docs/integrations/sandboxes/daytona.md +6 -6
  18. package/.docs/reference/agent-controller/session.md +4 -1
  19. package/.docs/reference/agents/agent.md +1 -1
  20. package/.docs/reference/agents/channels.md +4 -4
  21. package/.docs/reference/code-sdk/mount-agent-controller.md +4 -0
  22. package/.docs/reference/configuration.md +1 -1
  23. package/.docs/reference/core/mastra-class.md +8 -4
  24. package/.docs/reference/observability/metrics/queries.md +9 -9
  25. package/.docs/reference/observability/tracing/interfaces.md +49 -15
  26. package/.docs/reference/pubsub/base.md +2 -0
  27. package/.docs/reference/pubsub/redis-streams.md +3 -3
  28. package/.docs/reference/pubsub/valkey-streams.md +2 -2
  29. package/.docs/reference/workflows/run-methods/startAsync.md +14 -11
  30. package/.docs/reference/workflows/workflow-methods/map.md +2 -2
  31. package/.docs/reference/workflows/workflow.md +2 -2
  32. package/.docs/reference/workspace/workspace-class.md +3 -3
  33. package/package.json +2 -2
@@ -324,7 +324,7 @@ For output guardrails, run `TokenLimiterProcessor` and `BatchPartsProcessor` seq
324
324
  ```typescript
325
325
  import { createWorkflow, createStep } from '@mastra/core/workflows'
326
326
  import {
327
- ProcessorStepSchema,
327
+ ProcessorStepOutputSchema,
328
328
  PIIDetector,
329
329
  ModerationProcessor,
330
330
  SystemPromptScrubber,
@@ -334,8 +334,8 @@ import {
334
334
 
335
335
  export const outputGuardrails = createWorkflow({
336
336
  id: 'output-guardrails',
337
- inputSchema: ProcessorStepSchema,
338
- outputSchema: ProcessorStepSchema,
337
+ inputSchema: ProcessorStepOutputSchema,
338
+ outputSchema: ProcessorStepOutputSchema,
339
339
  })
340
340
  // Sequential: limit tokens first, then batch stream chunks
341
341
  .then(createStep(new TokenLimiterProcessor({ limit: 1000 })))
@@ -577,6 +577,20 @@ The same discovery is available over HTTP as `GET /agents/:agentId/suspended-run
577
577
 
578
578
  > **Note:** Suspended runs only survive restarts when your Mastra instance is configured with a persistent [storage provider](https://mastra.ai/docs/storage). The default in-memory store loses snapshots when the process exits.
579
579
 
580
+ ### Recovering a decision after a crash
581
+
582
+ When `approveToolCall()`, `declineToolCall()`, or `resumeStream()` runs, the run is claimed in storage together with the decision or resume data and the targeted `toolCallId`. If the process handling the resume stops before the run finishes, call `recoverResume()` from any process to finish the run with that stored decision:
583
+
584
+ ```typescript
585
+ const stream = await agent.recoverResume({ runId })
586
+
587
+ for await (const chunk of stream.textStream) process.stdout.write(chunk)
588
+ ```
589
+
590
+ `recoverResume()` takes over a claim once it's abandoned: claimed but not started for 60 seconds, or, on storage with run fencing, started and its lease not renewed for 60 seconds. Before that, it rejects with `AGENT_RESUME_ALREADY_CLAIMED`. For a run that no resume has claimed, it rejects with `AGENT_RESUME_NOTHING_TO_RECOVER`.
591
+
592
+ > **Warning:** The resumed tool call runs again. A claim counts as abandoned by its age, so a process that stalled for 60 seconds may still be running the tool when the recovery runs it. Make tools with side effects safe to repeat, for example with an idempotency key.
593
+
580
594
  ## Tool approval: Supervisor agents
581
595
 
582
596
  A [supervisor agent](https://mastra.ai/docs/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:
@@ -905,7 +905,7 @@ You can use Mastra workflows as processors to create complex processing pipeline
905
905
  ```typescript
906
906
  import { createWorkflow, createStep } from '@mastra/core/workflows'
907
907
  import {
908
- ProcessorStepSchema,
908
+ ProcessorStepOutputSchema,
909
909
  PromptInjectionDetector,
910
910
  PIIDetector,
911
911
  ModerationProcessor,
@@ -915,8 +915,8 @@ import { Agent } from '@mastra/core/agent'
915
915
  // Create a workflow that runs multiple checks in parallel
916
916
  const moderationWorkflow = createWorkflow({
917
917
  id: 'moderation-pipeline',
918
- inputSchema: ProcessorStepSchema,
919
- outputSchema: ProcessorStepSchema,
918
+ inputSchema: ProcessorStepOutputSchema,
919
+ outputSchema: ProcessorStepOutputSchema,
920
920
  })
921
921
  .parallel([
922
922
  createStep(
@@ -15,7 +15,7 @@ Integration guides:
15
15
 
16
16
  ## With Next.js on Vercel
17
17
 
18
- If you've integrated Mastra with Next.js [by following our guide](https://mastra.ai/integrations/frameworks/next-js) and plan to deploy to Vercel, add `serverExternalPackages: ["@mastra/*"]` to your `next.config.ts`:
18
+ If you've integrated Mastra with Next.js and plan to deploy to Vercel, make sure your `next.config.ts` sets `serverExternalPackages: ["@mastra/*"]`. The [Next.js guide](https://mastra.ai/integrations/frameworks/next-js) adds it during setup. If your config doesn't have it, add it:
19
19
 
20
20
  ```typescript
21
21
  import type { NextConfig } from 'next'
@@ -48,7 +48,15 @@ When a schedule is created at runtime, Mastra publishes a wake event on the PubS
48
48
 
49
49
  To poll from startup regardless of whether schedules exist (for example, when your processes don't share a PubSub backend), set `scheduler: { enabled: true }` on the worker or run it with `MASTRA_WORKERS=scheduler`.
50
50
 
51
- **Don't run more than one scheduler instance.** Multiple schedulers polling the same storage would fire duplicate events for the same schedule.
51
+ You can run more than one scheduler instance against the same storage. Before it publishes, a scheduler claims each occurrence with a compare-and-swap update of the schedule's next fire time. Only one instance wins the claim, and the others skip that occurrence. The built-in storage adapters (PostgreSQL, LibSQL, MySQL, MongoDB, Spanner, Convex) all perform this update atomically. A custom storage adapter must do the same in `updateScheduleNextFire`, or instances can fire the same occurrence twice.
52
+
53
+ The claim stops other scheduler instances from publishing the same occurrence. It doesn't make firing exactly-once:
54
+
55
+ - **Claim and publish aren't one transaction.** If the instance that won the claim crashes, or fails to publish after three attempts, that occurrence can be lost. Mastra records a failed publish as a `failed` trigger with an unknown publication outcome and doesn't replay it automatically.
56
+ - **Retries can publish an occurrence twice.** If a publish reaches the PubSub backend but still reports an error, the retry publishes the occurrence again with the same run ID. For workflows on the default engine, the worker skips a start for a run that already exists, but a duplicate that arrives before the first run is stored can still start. Evented workflows have no such check: a duplicate start sets the existing run back to `running` and executes it again.
57
+ - **Occurrences can overlap.** A new occurrence fires on time even if the run from the previous one hasn't finished.
58
+
59
+ Extra scheduler instances add availability, not throughput. Each one polls storage on every tick.
52
60
 
53
61
  ### Background task worker
54
62
 
@@ -75,6 +83,8 @@ The server generated by `mastra build` starts these workers automatically. If yo
75
83
 
76
84
  This setup needs no external infrastructure beyond your storage adapter. It doesn't survive process crashes, and you can't scale individual components.
77
85
 
86
+ > **Warning:** The in-memory PubSub delivers events only inside the process that published them. Running several Mastra instances on one storage with it isn't supported for evented workflows: each instance restarts the others' active runs when it boots. Configure a distributed PubSub backend for a multi-instance deployment.
87
+
78
88
  ### Split processes
79
89
 
80
90
  To run workers in their own processes, configure a distributed [PubSub](https://mastra.ai/docs/server/pubsub) backend and use the `MASTRA_WORKERS` environment variable to control which workers start in each process.
@@ -374,7 +384,7 @@ kubectl scale deployment/orchestration-worker --replicas=3
374
384
  kubectl scale deployment/background-task-worker --replicas=2
375
385
  ```
376
386
 
377
- Run exactly one scheduler worker. Multiple schedulers polling the same storage can publish duplicate events for a schedule.
387
+ You can run more than one scheduler worker. Each schedule occurrence is claimed by one instance, as described in [Scheduler worker](#scheduler-worker).
378
388
 
379
389
  ### Health checks
380
390
 
@@ -384,16 +394,18 @@ Worker build artifacts expose `GET /health` on `PORT`, or port `4111` when `PORT
384
394
 
385
395
  A distributed PubSub backend persists unacknowledged events, which lets orchestration and background task workers resume after a restart. When the API is unavailable, a failed step-execution request causes the event to be delivered again.
386
396
 
397
+ When a worker stops during an evented workflow step, the broker redelivers the step's event to another worker after `reclaimIdleMs` (60 seconds by default) with Redis or Valkey Streams, or after the ack deadline with Google Cloud Pub/Sub, so instances that boot meanwhile don't restart the run. Keep `reclaimIdleMs` at 30 seconds or more: an event reclaimed sooner can arrive while the stopped worker's hold on the step is still active, and is dropped.
398
+
387
399
  A step can run more than once. If a worker stops during a step, or after the step finishes but before it publishes the result, the step runs again when its event is redelivered. Make steps with side effects idempotent. See [restarting active workflow runs](https://mastra.ai/docs/workflows/overview) for how to build an idempotency key for a step, and [make tools safe to repeat](https://mastra.ai/docs/harness/durable-agents) for agent tools.
388
400
 
389
401
  The scheduler calculates the next fire time from the current time after it restarts. It doesn't replay schedules that elapsed while it was unavailable.
390
402
 
391
- If the API crashes while a step is executing, that work can be lost and the workflow run can remain in a `running` state. See [known limitations](#known-limitations) and [durable agent crash recovery](https://mastra.ai/docs/harness/durable-agents).
403
+ If an instance crashes while a default-engine workflow run is executing, the [recovery loop](https://mastra.ai/docs/workflows/overview) of an instance running the orchestration worker restarts the run at the first pass after the run's lease expired and `recovery.workflowGraceMs` passed. A `mastra worker` process calls `stopWorkers()` on `SIGTERM` and exits without `shutdown()`. The default-engine runs it was executing wait as long as a crashed instance's. See [known limitations](#known-limitations) and [durable agent crash recovery](https://mastra.ai/docs/harness/durable-agents).
392
404
 
393
405
  ## Known limitations
394
406
 
395
407
  - **No dead-letter queue**: Failed events are nacked and retried, but there's no DLQ for events that fail after all retries.
396
- - **Scheduler is single-instance**: Running multiple scheduler processes causes duplicate schedule fires.
408
+ - **Schedule occurrences can be lost**: If a scheduler crashes or can't publish after claiming an occurrence, that occurrence might not fire, and Mastra doesn't replay it automatically.
397
409
  - **Runs stuck in "running" after API crash**: A crash during workflow-step execution leaves the run in `running` status without an automatic retry. For [durable agents](https://mastra.ai/docs/harness/durable-agents), configure `recovery.durableAgents: 'auto'` so a server restart automatically re-drives orphaned runs. See [Crash recovery](https://mastra.ai/docs/harness/durable-agents) for details.
398
410
 
399
411
  ## Related
@@ -280,6 +280,8 @@ const controller = new AgentController({
280
280
  })
281
281
  ```
282
282
 
283
+ Calls to tools the rules allow don't pause the run. On a regular `Agent`, tool calls in one step run concurrently when none of them needs approval or can suspend. Durable agents run them one at a time unless the session's `yolo` state is on.
284
+
283
285
  Configure category policies with [`session.permissions.setForCategory()`](https://mastra.ai/reference/agent-controller/session) and tool policies with [`session.permissions.setForTool()`](https://mastra.ai/reference/agent-controller/session):
284
286
 
285
287
  ```typescript
@@ -123,6 +123,8 @@ The `_background` override only _modifies_ tools the developer has already opted
123
123
 
124
124
  When a tool call is dispatched, agent-level and tool-level settings determine eligibility and fallback values. For an eligible tool, the LLM `_background` fields override the corresponding values for that call. Manager defaults fill timeout and retry values that remain unset. An `_background` field can't enable a tool that's not eligible.
125
125
 
126
+ A timeout of `0` means no timeout. Set `timeoutMs: 0` on a tool or agent tool entry, or `defaultTimeoutMs: 0` on the manager, for tasks that should run until they finish or are cancelled.
127
+
126
128
  If the agent has `backgroundTasks.disabled: true`, every tool call runs synchronously regardless of the layers above.
127
129
 
128
130
  ## Background tasks related stream chunks
@@ -191,7 +193,7 @@ export const mastra = new Mastra({
191
193
 
192
194
  When a deferred task finishes and no `untilIdle` stream is open for its thread, Mastra sends the agent a `notification` signal with the tag `background-task`. The signal names the tool call and task, and tells the agent the result is now on the tool call. It doesn't copy the result into the prompt. This covers a `stream()` call without `untilIdle`, a client that disconnected, and a task resumed after it [suspended](#suspending-and-resuming).
193
195
 
194
- - If the thread is idle, the signal wakes the agent, which runs a turn on the thread to report the outcome. The woken run uses the request context of the run that dispatched the task, so a model, instructions, or memory resolved from that context resolve the same way.
196
+ - If the thread is idle, the signal wakes the agent, which runs a turn on the thread to report the outcome. The woken run uses the request context of the run that dispatched the task, so a model, instructions, or memory resolved from that context resolve the same way. This also holds when the agent that claimed the thread runs on another server: the context is sent along with the signal, minus the auth token, the signed-in user, and any values that can't be sent as JSON or are too large to serialize. That server's run keeps its own auth token and user.
195
197
  - If a run is already active on the thread, including the run that dispatched the task, the signal is delivered to that run's next model request. If that run ends without making another request, the signal runs as its own turn.
196
198
  - If another agent's run holds the thread, for example while it waits for a tool approval, the signal waits and wakes the agent once that run ends.
197
199
  - If an `untilIdle` stream is open for the thread, no signal is sent, because that stream runs its own follow-up turn.
@@ -403,7 +403,7 @@ A lease only coordinates the processes that share it. `EventEmitterPubSub`, the
403
403
 
404
404
  ### Stop work after ownership loss
405
405
 
406
- Durable and evented agents request cancellation of in-flight tool and model calls when their step detects that it no longer owns the run. Evented workers in another process check ownership at the claim renewal interval without renewing the original execution's claim. By default that's every 5 seconds, a third of `MASTRA_AGENT_THREAD_LEASE_TTL_MS`. Detection depends on backend response time. If ownership checks keep failing or stop responding, the step stops trusting its claim after one lease TTL, 15 seconds by default.
406
+ Durable and evented agents request cancellation of in-flight tool and model calls when their step detects that it no longer owns the run. Evented workers in another process check ownership at the claim renewal interval without renewing the original execution's claim. By default that's every 5 seconds, a third of `MASTRA_AGENT_THREAD_LEASE_TTL_MS`. Detection depends on backend response time. A step in the process that holds the claim stops when an ownership check fails, or when the claim can't be renewed before it expires. A step that only observes another process's claim also stops when no check succeeds within one lease TTL (15 seconds by default).
407
407
 
408
408
  Cancellation is cooperative. Use the tool execution context's `abortSignal` for cancellable operations, and check it before starting another side effect. A tool that ignores the signal can keep running. Work already completed outside Mastra isn't rolled back.
409
409
 
@@ -192,8 +192,13 @@ import { Workspace } from '@mastra/core/workspace'
192
192
  import { DaytonaSandbox } from '@mastra/daytona'
193
193
  import { S3Filesystem } from '@mastra/s3'
194
194
 
195
- const getThreadId = (requestContext: RequestContext) =>
196
- requestContext.get(MASTRA_THREAD_ID_KEY) as string
195
+ const getThreadId = (requestContext: RequestContext) => {
196
+ const threadId = requestContext.get(MASTRA_THREAD_ID_KEY)
197
+ if (typeof threadId !== 'string' || !threadId) {
198
+ throw new Error('MASTRA_THREAD_ID_KEY is not set on the request context')
199
+ }
200
+ return threadId
201
+ }
197
202
 
198
203
  const createThreadFilesystem = (threadId: string) =>
199
204
  new S3Filesystem({
@@ -219,6 +224,22 @@ const workspace = new Workspace({
219
224
  })
220
225
  ```
221
226
 
227
+ Resolvers receive only the request context, so the thread ID has to be on it. `agent.stream()` and `agent.generate()` don't copy `memory.thread` to `MASTRA_THREAD_ID_KEY`, so set the key yourself from a trusted thread ID, either in [server middleware](https://mastra.ai/docs/server/request-context) or when you call the agent:
228
+
229
+ ```typescript
230
+ import { MASTRA_THREAD_ID_KEY, RequestContext } from '@mastra/core/request-context'
231
+
232
+ const requestContext = new RequestContext()
233
+ requestContext.set(MASTRA_THREAD_ID_KEY, threadId)
234
+
235
+ await agent.stream(message, {
236
+ memory: { thread: threadId, resource: userId },
237
+ requestContext,
238
+ })
239
+ ```
240
+
241
+ `getThreadId()` throws when the key is missing, so a request without a thread fails instead of sharing a `threads/undefined` prefix and sandbox with every other such request.
242
+
222
243
  The first request in a thread runs the resolver and starts the sandbox. Later requests with the same thread ID reuse the cached sandbox. A different thread ID creates a different sandbox and storage prefix.
223
244
 
224
245
  The example mounts the filesystem inside the resolver because static `mounts` can't be combined with a sandbox resolver. Generated tools resolve the filesystem and sandbox from the request context automatically.
@@ -260,6 +281,8 @@ const workspace = new Workspace({
260
281
 
261
282
  These callbacks fire for all background processes started by the agent through `execute_command`.
262
283
 
284
+ Each callback receives the process `pid` and, when available, the `toolCallId`, `agentId`, `threadId`, `resourceId`, and `runId` of the call that started it, so you can route an exit notice back to the right conversation. `onExit` also gets `killedByAbort`, which is `true` when the abort signal fired (the run's signal by default) and stopped the process, and `false` when it exited on its own or was stopped with `kill_process`.
285
+
263
286
  By default, background processes inherit the agent's abort signal and stop when the agent disconnects. Set `abortSignal` to a custom signal, or use `null` or `false` when the process should continue after the request ends.
264
287
 
265
288
  For the full `SandboxProcessManager` API, including programmatic process spawning, output, and standard input, see the [`SandboxProcessManager` reference](https://mastra.ai/reference/workspace/process-manager).
@@ -328,7 +328,7 @@ requestContext.set(MASTRA_THREAD_ID_KEY, threadId)
328
328
  | Key | Purpose |
329
329
  | --------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
330
330
  | `MASTRA_RESOURCE_ID_KEY` | Forces all memory operations to use this resource ID. The server validates that accessed threads belong to this resource and returns 403 if not. |
331
- | `MASTRA_THREAD_ID_KEY` | Forces thread operations to use this thread ID, overriding client-provided values |
331
+ | `MASTRA_THREAD_ID_KEY` | Forces thread operations to use this thread ID, overriding client-provided values. Passing `memory.thread` to an agent call leaves this key unset, so set it yourself wherever you rely on it, such as for a workspace resolver. Tools can read the current run's thread from `context.agent.threadId` instead. |
332
332
  | `MASTRA_SCOPES_KEY` | Sets the [scopes](https://mastra.ai/docs/memory/overview) the agent run acts as, as an array of `<type>:<value>` strings. Combined with per-call `scopes`; the agent's `scopes` list adds to them, and a `scopes` function replaces them. A `resource:` or `thread:` scope that conflicts with another resource or thread value returns a 400 error. |
333
333
  | `MASTRA_MESSAGE_AUTHOR_KEY` | Names who sent a user message as `{ id, name?, avatarUrl? }`. Agent-controller sessions persist it at `content.metadata.signal.author` and mirror it to `providerMetadata.mastra.author` for compatibility, so a thread shared by several people can show who wrote what. |
334
334
 
@@ -448,6 +448,7 @@ Without this call, the following features never run:
448
448
  - [Scheduled workflows](https://mastra.ai/docs/workflows/scheduled-workflows): Schedule rows aren't created and cron triggers don't fire.
449
449
  - [Agent schedules](https://mastra.ai/docs/harness/schedules) created with `mastra.schedules`
450
450
  - Event listeners you've registered on the Mastra instance
451
+ - The [recovery loop](https://mastra.ai/docs/workflows/overview): Default-engine workflow runs whose instance stops after this server booted aren't restarted.
451
452
 
452
453
  Call `startWorkers()` once, after the server starts listening:
453
454
 
@@ -91,6 +91,40 @@ An `authorize` function replaces the server's rules and role checks for every ro
91
91
 
92
92
  Set the value to an array of scopes, or `'all'` for someone who should see the whole instance. An empty array reads nothing. See [Knowledge access and errors](https://mastra.ai/reference/server/routes) for what other values return. If you configure `studio.auth`, Studio requests use it instead of `server.auth`, so set the key in that `authorize`.
93
93
 
94
+ ### Providers with `authorizeUser`
95
+
96
+ The server never calls `authorize` when the auth provider defines `authorizeUser`. This includes any `MastraAuthProvider` subclass that implements it, and every `CompositeAuth`. For these providers, set the key in a [server middleware](https://mastra.ai/docs/server/middleware) instead:
97
+
98
+ ```typescript
99
+ import { Mastra } from '@mastra/core/mastra'
100
+ import { KNOWLEDGE_ROUTES, MASTRA_KNOWLEDGE_PRINCIPALS_KEY } from '@mastra/server/server-adapter'
101
+ import { auth, getSessionUser } from './auth' // your provider and session lookup
102
+
103
+ export const mastra = new Mastra({
104
+ server: {
105
+ apiRoutes: [...KNOWLEDGE_ROUTES],
106
+ auth,
107
+ middleware: [
108
+ {
109
+ path: '/api/knowledge/*',
110
+ handler: async (c, next) => {
111
+ const user = await getSessionUser(c.req.raw)
112
+ if (user) {
113
+ c.get('requestContext').set(
114
+ MASTRA_KNOWLEDGE_PRINCIPALS_KEY,
115
+ user.isAdmin ? 'all' : [`org:${user.orgId}`, `team:${user.orgId}:${user.teamId}`],
116
+ )
117
+ }
118
+ await next()
119
+ },
120
+ },
121
+ ],
122
+ },
123
+ })
124
+ ```
125
+
126
+ Server middleware runs before the route's auth check, so the signed-in user isn't on the request context yet. Look the user up from the request with your app's own session check, as above. The route's auth still runs afterwards and rejects callers your provider doesn't accept. Change the middleware `path` if you set a different prefix.
127
+
94
128
  ### Deployment notes
95
129
 
96
130
  - **No RBAC provider:** the `knowledge:read` check is skipped, so any authenticated user with a principal mapping can read the pages those principals cover, in every instance.
@@ -500,9 +500,13 @@ Runs restart concurrently, up to `recovery.workflowConcurrency` at a time (defau
500
500
 
501
501
  To exclude a workflow from automatic boot-time restarts triggered by `Mastra.restartAllActiveWorkflowRuns()`, set `autoRestartActiveRuns: false` in the workflow's `options`. This is useful for workflows with side effects that must not be re-driven by a blanket restart. Durable agent workflows set this automatically because their recovery is owned by the opt-in `recovery.durableAgents: 'auto'` path.
502
502
 
503
- While a run executes, Mastra holds a storage lease on it and renews it in the background. `restart()` refuses to take over a run whose lease hasn't expired: it throws a `WORKFLOW_RESTART_RUN_OWNED` error and the sweep skips the run. The lease is advisory and doesn't fence writes. If a process stops renewing its lease but keeps executing a step, for example because its event loop is blocked for longer than the lease TTL, recovery can run that step a second time. The boot-time sweep, `mastra.restartAllActiveWorkflowRuns()`, rechecks a skipped run once its lease could have expired, so a run whose process crashed is still recovered. `workflow.restartAllActiveWorkflowRuns()` skips the run without a recheck, so call it after the lease expires if you need to recover that run. Storage adapters without run-ownership support keep the previous behavior and restart every active run.
503
+ While a run executes, Mastra holds a storage lease on it and renews it in the background. `restart()` refuses to take over a run whose lease hasn't expired: it throws a `WORKFLOW_RESTART_RUN_OWNED` error and the sweep skips the run. The lease is advisory and doesn't fence writes. If a process stops renewing its lease but keeps executing a step, for example because its event loop is blocked for longer than the lease TTL, recovery can run that step a second time. `workflow.restartAllActiveWorkflowRuns()` skips such a run without a recheck, so call it after the lease expires if you need to recover that run. Storage adapters without run-ownership support keep the previous behavior and restart every active run.
504
504
 
505
- A restarted run runs the interrupted step again, even if that step finished before the process stopped but its result wasn't saved. On the evented engine, a step also runs again when its event is redelivered to a worker. Make steps with side effects idempotent, so a repeated step has no additional effect.
505
+ `mastra.restartAllActiveWorkflowRuns()`, which the server calls on boot, restarts a default-engine run only once it stopped: no instance holds its lease, and neither the run nor its lease changed for `recovery.workflowGraceMs` (2 seconds by default). A run that's still running, or stopped more recently, is left to the [recovery loop](#recovery-loop).
506
+
507
+ Evented runs on a pubsub whose broker redelivers unacknowledged events (Redis Streams, Valkey Streams, Google Cloud Pub/Sub) are left to the broker: when a worker stops mid-step, the broker redelivers the step's event to another worker, and booting instances don't restart the run. Scheduled runs are the exception, because their events stay in the process that fired them, so recovery restarts them. On any other pubsub, including the default in-process one, recovery restarts every active evented run at once. The in-process pubsub delivers events only inside one process, so running several instances on one storage with it isn't supported for evented workflows.
508
+
509
+ A restarted run runs the interrupted step again, even if that step finished before the process stopped but its result wasn't saved. On the evented engine, a step that already saved its result doesn't run again when its event arrives late, for example after a broker redelivery or a `restart()` that ran while the step was saving its result. The run continues from the saved result instead. This needs a storage adapter with run-ownership support. Workflows that set `autoRestartActiveRuns: false`, including durable agent workflows, run the step again. Make steps with side effects idempotent, so a repeated step has no additional effect.
506
510
 
507
511
  A step's `execute` function receives `runId` and `workflowId`. Combine them with the `id` you gave the step in `createStep()`, plus a name for each side effect when the step performs more than one, to build an idempotency key.
508
512
 
@@ -514,6 +518,20 @@ Some steps need part of the key to come from their input:
514
518
 
515
519
  For tools that agents call, see [make tools safe to repeat](https://mastra.ai/docs/harness/durable-agents).
516
520
 
521
+ ### Recovery loop
522
+
523
+ `mastra.startWorkers()` also starts a recovery loop on an instance that runs the orchestration worker. Every `recovery.workflowScanIntervalMs` (60 seconds by default, give or take a fifth), it restarts the default-engine runs that stopped, by the same rule as `restartAllActiveWorkflowRuns()`. A run whose instance crashed is restarted at the first pass after its lease expired (`MASTRA_AGENT_THREAD_LEASE_TTL_MS`, 15 seconds by default) and `recovery.workflowGraceMs` passed. When a pass finds a run in its grace period, the next pass runs once that period ends, but no sooner than a second later.
524
+
525
+ Instances that share a storage adapter elect one loop leader through a lease row in storage. Only the leader's loop lists runs. The loops of the other instances only try to take its place. The leader keeps the role until its `stopWorkers()` or `shutdown()` hands it back, or until its lease expires after a crash. With `restartAllActiveWorkflowRuns()` at boot, each instance still restarts its own stopped default-engine runs, whichever instance leads. Between boots, the loop recovers only the workflows the leader registers, so instances that register different workflows on one storage get loop recovery for the leader's workflows only and the others' runs at their next boot. A run the loop restarts executes on the leader.
526
+
527
+ ```typescript
528
+ export const mastra = new Mastra({
529
+ recovery: { workflowScanIntervalMs: 30_000 },
530
+ })
531
+ ```
532
+
533
+ The loop never restarts evented runs. A broker that redelivers unacknowledged events recovers them, and on other pubsubs `restartAllActiveWorkflowRuns()` restarts them at boot. The loop also leaves workflows that set `autoRestartActiveRuns: false` alone, and an instance that registers no other default-engine workflow never claims the leader row. It doesn't run when `recovery.workflows` is `'off'`, on an instance started with `workers: false` or a `MASTRA_WORKERS` filter without `orchestration`, or on a storage adapter without run-ownership support. A process that calls `restartAllActiveWorkflowRuns()` but never `startWorkers()` runs no loop.
534
+
517
535
  ### Restarting an active workflow run with `restart()`
518
536
 
519
537
  Use `restart()` to restart an active workflow run from the last active step. This will resume execution from the last active step, and the workflow will continue from there.
@@ -537,7 +555,7 @@ if (activeRuns.runs.length > 0) {
537
555
  }
538
556
  ```
539
557
 
540
- > **Note:** When running the local mastra server, all active workflow runs will be restarted automatically when the server starts.
558
+ > **Note:** When the Mastra server starts, it restarts the active workflow runs no instance is running anymore, and its recovery loop keeps doing so for default-engine runs.
541
559
 
542
560
  ## Using `RequestContext`
543
561
 
@@ -280,7 +280,7 @@ Before setting `replicaCount` above one or enabling `mastra-server.autoscaling`:
280
280
  - Configure a distributed PubSub backend and shared cache. The [Kubernetes guide](https://mastra.ai/integrations/deploy/kubernetes) uses `RedisStreamsPubSub` and `RedisServerCache`, with `REDIS_URL` stored in the application Secret.
281
281
  - Use [durable agents](https://mastra.ai/docs/harness/durable-agents) for streams, approvals, and runs that must continue when requests reach different pods.
282
282
  - Start with one replica to initialize the database schema before scaling. For stricter deployments, initialize the schema in a Kubernetes Job and disable initialization in each pod.
283
- - Review [worker roles](https://mastra.ai/docs/deployment/workers). Run only one scheduler instance when your application uses scheduled workflows.
283
+ - Review [worker roles](https://mastra.ai/docs/deployment/workers). Multiple scheduler instances are safe, because each schedule occurrence is claimed by one instance.
284
284
 
285
285
  After those requirements are in place, set resource requests and enable autoscaling:
286
286
 
@@ -309,7 +309,7 @@ Before enabling workers:
309
309
 
310
310
  - **A pull-capable PubSub backend** configured in your Mastra application: Redis Streams, Valkey Streams, or Google Cloud Pub/Sub. Workers pull events from the broker, so request/response-only backends won't work. Put its connection string (for example `REDIS_URL`) in the same Secret the Server uses.
311
311
  - **A storage backend that supports the `schedules` domain**, if you enable the scheduler: PostgreSQL, LibSQL, MySQL, MongoDB, Spanner, or Convex. Redis and ClickHouse don't support it, and the scheduler won't find due schedules on them.
312
- - **`mastra-server.workers.splitDeployment: true`.** Without it the API keeps running workers in-process and every worker runs twice, double-firing every cron schedule. The chart refuses to render if you enable workers without it.
312
+ - **`mastra-server.workers.splitDeployment: true`.** Without it the API keeps running workers in-process, so every worker also runs in the API pods alongside the worker Deployments. The chart refuses to render if you enable workers without it.
313
313
 
314
314
  > **Redis eviction policy:** Set `maxmemory-policy` to `noeviction` on Redis or Valkey. Every evicting policy deletes live Mastra state under memory pressure: `allkeys-*` policies evict unacknowledged workflow events, and `volatile-*` policies evict lease keys and streams, which carry a TTL by default. Runs then stall without a run error. `RedisStreamsPubSub` and `ValkeyStreamsPubSub` log a one-time warning after they first connect when the policy can evict. On managed Redis this is a parameter-group setting, and Amazon ElastiCache defaults to `volatile-lru`.
315
315
 
@@ -388,11 +388,11 @@ Worker pods mount the **Server's** ConfigMap and Secret rather than defining the
388
388
 
389
389
  ### Roles and scaling
390
390
 
391
- | Role | Scales | Notes |
392
- | ----------------- | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
393
- | `orchestration` | Yes | Consumes the `workflows` topic and calls back into the API to execute steps. The consumer group distributes work across replicas. |
394
- | `scheduler` | **No — always 1** | Polls storage for due cron schedules. The chart pins it to one replica and uses the `Recreate` strategy, because a rolling update would briefly run two schedulers and fire every schedule twice. |
395
- | `backgroundTasks` | Yes | Executes agent tool calls marked `background: { enabled: true }` off the request path. |
391
+ | Role | Scales | Notes |
392
+ | ----------------- | ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
393
+ | `orchestration` | Yes | Consumes the `workflows` topic and calls back into the API to execute steps. The consumer group distributes work across replicas. |
394
+ | `scheduler` | **No — always 1** | Polls storage for due cron schedules. The chart pins it to one replica and uses the `Recreate` strategy. Extra schedulers are safe but add polling load without adding throughput. |
395
+ | `backgroundTasks` | Yes | Executes agent tool calls marked `background: { enabled: true }` off the request path. |
396
396
 
397
397
  The two scalable roles support autoscaling. Utilization targets need matching resource requests, and the chart fails the render if you enable autoscaling without them:
398
398
 
@@ -443,7 +443,7 @@ kubectl rollout restart deploy -n mastra -l app.kubernetes.io/name=mastra-work
443
443
  - Set resource requests via `mastra-server.resources` and `mastra-studio.resources`.
444
444
  - Prefer standalone cert-manager and ingress controller installs over the bundled toggles; CRD lifecycle inside an umbrella chart complicates upgrades.
445
445
  - Enable multiple replicas only after configuring shared storage, distributed PubSub, shared cache, and the required process roles.
446
- - When running background workers, set `mastra-server.workers.splitDeployment: true`, run exactly one scheduler, and set `maxmemory-policy` to `noeviction` on Redis or Valkey.
446
+ - When running background workers, set `mastra-server.workers.splitDeployment: true` and set `maxmemory-policy` to `noeviction` on Redis or Valkey.
447
447
  - The chart applies hardened defaults: non-root containers, read-only root filesystem, seccomp `RuntimeDefault`, and no service account token automount.
448
448
 
449
449
  ## Upgrade and uninstall
@@ -476,7 +476,6 @@ Your database and object store are unaffected, because the chart never manages s
476
476
  - **Pods crash-loop with a license error.** Production mode requires a valid `MASTRA_EE_LICENSE` in your secret when enterprise features are configured.
477
477
  - **Studio shows the server API instead of the UI.** The image was built without Studio assets. Rebuild with `mastra build --studio`.
478
478
  - **Worker pods crash-loop with `Cannot find module '/app/.mastra/worker/index.mjs'`.** The image was built without the worker artifact. Run `mastra worker build --output-dir .mastra/worker` and copy it into the image, or override `mastra-workers.command` to match your layout.
479
- - **Scheduled workflows fire twice.** The API is still running workers in-process alongside the worker Deployments. Set `mastra-server.workers.splitDeployment: true`.
480
479
  - **Workflows stall with no error.** The orchestration worker can't reach the API, or Redis evicted unacknowledged events. Check `mastra-workers.server.port` against `mastra-server.service.port`, confirm any restrictive NetworkPolicy admits worker pods, and verify `maxmemory-policy` is `noeviction`.
481
480
  - **Worker pods stay in `CreateContainerConfigError`.** They mount the Server's ConfigMap and Secret, so `mastra-workers.server.existingSecret` must match `mastra-server.existingSecret`, and `mastra-workers` can't be installed as a standalone release.
482
481
  - **Ingress has no address.** Confirm an ingress controller is running, or set `ingressController.install=true`.
@@ -97,6 +97,22 @@ You'll call `weather-agent.ts` from your Next.js routes in the next steps.
97
97
  >
98
98
  > Relative paths resolve based on each process's working directory, which differs between `next dev` and `mastra dev`.
99
99
 
100
+ ### Configure Next.js
101
+
102
+ Mastra packages load native Node.js modules, such as the DuckDB bindings that store observability data, which the Next.js bundler can't bundle. Add `serverExternalPackages` to `next.config.ts` so Next.js loads Mastra packages from `node_modules` at runtime:
103
+
104
+ ```ts
105
+ import type { NextConfig } from 'next'
106
+
107
+ const nextConfig: NextConfig = {
108
+ serverExternalPackages: ['@mastra/*'],
109
+ }
110
+
111
+ export default nextConfig
112
+ ```
113
+
114
+ If your `next.config.ts` already sets other options, add `serverExternalPackages` alongside them.
115
+
100
116
  ### Install AI SDK UI & AI elements
101
117
 
102
118
  Install AI SDK UI along with the Mastra adapter:
@@ -125,37 +141,37 @@ yarn add @mastra/ai-sdk@latest @ai-sdk/react ai
125
141
  bun add @mastra/ai-sdk@latest @ai-sdk/react ai
126
142
  ```
127
143
 
128
- Next, initialize AI Elements. When prompted to select a component library, choose **Radix UI**, then accept the defaults for the remaining prompts:
144
+ Next, add the AI Elements components the chat page uses. When prompted to select a component library, choose **Radix UI**, then accept the defaults for the remaining prompts:
129
145
 
130
146
  **npm**:
131
147
 
132
148
  ```bash
133
- npx ai-elements@latest
149
+ npx ai-elements@latest add prompt-input conversation message tool
134
150
  ```
135
151
 
136
152
  **pnpm**:
137
153
 
138
154
  ```bash
139
- pnpm dlx ai-elements@latest
155
+ pnpm dlx ai-elements@latest add prompt-input conversation message tool
140
156
  ```
141
157
 
142
158
  **Yarn**:
143
159
 
144
160
  ```bash
145
- yarn dlx ai-elements@latest
161
+ yarn dlx ai-elements@latest add prompt-input conversation message tool
146
162
  ```
147
163
 
148
164
  **Bun**:
149
165
 
150
166
  ```bash
151
- bun x ai-elements@latest
167
+ bun x ai-elements@latest add prompt-input conversation message tool
152
168
  ```
153
169
 
154
170
  > **Note:** The `ai-elements` command runs `shadcn add` against the AI Elements registry, which currently publishes Radix UI components only. Installing them into a Base UI project produces TypeScript errors, tracked in [vercel/ai-elements#383](https://github.com/vercel/ai-elements/issues/383).
155
171
  >
156
172
  > The component library prompt only appears when your project has no `components.json`. If you already have one, check that its `style` is a Radix option, such as `new-york` or a `radix-*` style, and not a `base-*` style, before running the command.
157
173
 
158
- This downloads the entire AI Elements UI component library into a `@/components/ai-elements` folder.
174
+ This downloads those components and their dependencies into a `@/components/ai-elements` folder.
159
175
 
160
176
  ### Create a chat route
161
177
 
@@ -8,13 +8,13 @@ Mastra supports OpenTelemetry (OTEL) through an exporter for sending traces and
8
8
 
9
9
  ## Exporter
10
10
 
11
- The OpenTelemetry exporter sends your traces and logs using standardized [OpenTelemetry Semantic Conventions for GenAI](https://opentelemetry.io/docs/specs/semconv/gen-ai/). This ensures broad compatibility with platforms like Datadog, New Relic, Sentry, SigNoz, MLflow, Latitude, Dash0, Traceloop, Laminar, telemetry.dev, Sazabi, and more.
11
+ The OpenTelemetry exporter sends your traces and logs using standardized [OpenTelemetry Semantic Conventions for GenAI](https://opentelemetry.io/docs/specs/semconv/gen-ai/). This ensures broad compatibility with platforms like Datadog, New Relic, Sentry, SigNoz, MLflow, Latitude, Dash0, Traceloop, Laminar, telemetry.dev, Sazabi, Agnost AI, and more.
12
12
 
13
13
  ### Installation
14
14
 
15
15
  Each provider requires specific protocol packages. Install the base exporter plus the protocol package for your provider:
16
16
 
17
- #### For HTTP/Protobuf providers (SigNoz, New Relic, Sentry, Laminar, MLflow, Latitude, telemetry.dev)
17
+ #### For HTTP/Protobuf providers (SigNoz, New Relic, Sentry, Laminar, MLflow, Latitude, telemetry.dev, Agnost AI)
18
18
 
19
19
  **npm**:
20
20
 
@@ -222,6 +222,31 @@ new OtelExporter({
222
222
 
223
223
  See [Sazabi's Mastra guide](https://docs.sazabi.com/catalogs/log-sources/send-to-an-endpoint/mastra) for the full setup.
224
224
 
225
+ #### Agnost AI
226
+
227
+ [Agnost AI](https://agnost.ai) ingests OTLP/HTTP protobuf traces and groups them into conversations and users for production agent monitoring. Use the `custom` provider with your organization ID:
228
+
229
+ ```bash
230
+ AGNOST_ORG_ID=your-org-id
231
+ ```
232
+
233
+ ```typescript
234
+ new OtelExporter({
235
+ provider: {
236
+ custom: {
237
+ endpoint: 'https://otel.agnost.ai/v1/traces',
238
+ protocol: 'http/protobuf',
239
+ headers: {
240
+ 'X-Agnost-Org-ID': process.env.AGNOST_ORG_ID!,
241
+ },
242
+ },
243
+ },
244
+ signals: { logs: false },
245
+ })
246
+ ```
247
+
248
+ Agnost AI reads `userId` and `conversationId` (or `threadId`) from `tracingOptions.metadata` to group traces by user and conversation. It stores traces only, so `signals: { logs: false }` skips the log export. See [Agnost AI's Mastra guide](https://docs.agnost.ai/mastra) for the full setup.
249
+
225
250
  #### Dash0
226
251
 
227
252
  [Dash0](https://www.dash0.com/) provides real-time observability with automatic insights.
@@ -11,25 +11,25 @@ Executes commands in isolated [Daytona](https://www.daytona.io) cloud sandboxes.
11
11
  **npm**:
12
12
 
13
13
  ```bash
14
- npm install @mastra/daytona
14
+ npm install @mastra/daytona @daytona/sdk
15
15
  ```
16
16
 
17
17
  **pnpm**:
18
18
 
19
19
  ```bash
20
- pnpm add @mastra/daytona
20
+ pnpm add @mastra/daytona @daytona/sdk
21
21
  ```
22
22
 
23
23
  **Yarn**:
24
24
 
25
25
  ```bash
26
- yarn add @mastra/daytona
26
+ yarn add @mastra/daytona @daytona/sdk
27
27
  ```
28
28
 
29
29
  **Bun**:
30
30
 
31
31
  ```bash
32
- bun add @mastra/daytona
32
+ bun add @mastra/daytona @daytona/sdk
33
33
  ```
34
34
 
35
35
  Set your Daytona API key in one of three ways.
@@ -495,7 +495,7 @@ By default, `s3fs` and `gcsfuse` are installed at first mount via `apt`, which a
495
495
  **Option 1: Declarative image build**
496
496
 
497
497
  ```typescript
498
- import { Daytona, Image } from '@daytonaio/sdk'
498
+ import { Daytona, Image } from '@daytona/sdk'
499
499
 
500
500
  const template = Image.base('daytonaio/sandbox')
501
501
  .runCommands('sudo apt-get update -qq')
@@ -533,7 +533,7 @@ RUN sudo apt-get update -qq && sudo apt-get install -y gcsfuse
533
533
  ```
534
534
 
535
535
  ```typescript
536
- import { Daytona, Image } from '@daytonaio/sdk'
536
+ import { Daytona, Image } from '@daytona/sdk'
537
537
 
538
538
  const daytona = new Daytona()
539
539
 
@@ -226,12 +226,15 @@ Returns: `boolean`
226
226
 
227
227
  ### Tool approvals
228
228
 
229
- #### `resolveToolApproval(toolName)`
229
+ #### `resolveToolApproval(toolName, scope?)`
230
230
 
231
231
  Return the effective policy after applying explicit tool rules, session grants, and category rules.
232
232
 
233
+ Rules belong to each thread. Pass a run's `RequestContext` as `scope` to use the rules and grants of the thread that run belongs to. A thread ID as `scope` checks that thread's grants against the current thread's rules. Without `scope`, the current thread is used.
234
+
233
235
  ```typescript
234
236
  const policy = session.resolveToolApproval('execute_command')
237
+ const policyForRun = session.resolveToolApproval('write_file', requestContext)
235
238
  ```
236
239
 
237
240
  Returns: `PermissionPolicy`
@@ -593,7 +593,7 @@ Returns an `AgentThreadSubscription` object with these members:
593
593
 
594
594
  **voice** (`IMastraVoice | ({ requestContext: RequestContext }) => IMastraVoice | Promise<IMastraVoice>`): Voice provider for speech input and output, such as OpenAIVoice or CompositeVoice. Pass a function to create one per request.
595
595
 
596
- **inputProcessors** (`(Processor | ProcessorWorkflow)[] | ({ requestContext: RequestContext }) => (Processor | ProcessorWorkflow)[] | Promise<(Processor | ProcessorWorkflow)[]>`): Input processors that can modify or validate messages before they are processed by the agent. Can be individual Processor objects or workflows created with createWorkflow() using ProcessorStepSchema.
596
+ **inputProcessors** (`(Processor | ProcessorWorkflow)[] | ({ requestContext: RequestContext }) => (Processor | ProcessorWorkflow)[] | Promise<(Processor | ProcessorWorkflow)[]>`): Input processors that can modify or validate messages before they are processed by the agent. Can be individual Processor objects or workflows created with createWorkflow() using ProcessorStepOutputSchema.
597
597
 
598
598
  **outputProcessors** (`(Processor | ProcessorWorkflow)[] | ({ requestContext: RequestContext }) => (Processor | ProcessorWorkflow)[] | Promise<(Processor | ProcessorWorkflow)[]>`): Output processors that can modify or validate messages from the agent before they are sent to the client. Can be individual Processor objects or workflows.
599
599
 
@@ -104,7 +104,7 @@ const agent = new Agent({
104
104
 
105
105
  **formatToolCall** (`(info: { toolName: string; args: Record<string, unknown>; result: unknown; isError?: boolean }) => PostableMessage | null`): \*\*Deprecated\*\* — use toolDisplay (function form) instead. When set, runs as a ToolDisplayFn that only fires on result/error events; running and approval events fall through to no render. Mutually exclusive with toolDisplay at the type level.
106
106
 
107
- **streaming** (`boolean | { updateIntervalMs?: number }`): Stream agent text deltas to the channel as the agent generates them instead of buffering and posting once per step. Requires the underlying adapter to support post-and-edit streaming. Slack defaults to true; other adapters default to false. (Default: `false (true for Slack)`)
107
+ **streaming** (`boolean | { updateIntervalMs?: number }`): Stream agent text deltas to the channel as the agent generates them instead of buffering and posting once per step. Requires the underlying adapter to support post-and-edit streaming. Defaults to false on every adapter, including Slack; set it to true to stream. (Default: `false`)
108
108
 
109
109
  **generativeUI** (`boolean`): \*\*Experimental. Slack only; ignored on other adapters.\*\* Gives runs on the Slack adapter a render_card tool. The agent calls it with a json-render spec and the card is posted to the thread as Block Kit. Invalid specs return a list of issues to the agent instead of posting. Requires the optional @json-render/chat package. See Generative UI cards. (Default: `false`)
110
110
 
@@ -112,7 +112,7 @@ const agent = new Agent({
112
112
 
113
113
  **textDisplay** (`'show' | 'hidden'`): Whether the agent's reply text is posted to the channel. 'hidden' never posts reply text, so the agent's own messages reach the channel only through tools you give it, such as a reply tool. Tool display, approval prompts, error messages, and typing status are unaffected, and the text still reaches the agent's stream and memory. (Default: `'show'`)
114
114
 
115
- **toolDisplay** (`'cards' | 'text' | 'timeline' | 'grouped' | 'hidden' | ToolDisplayFn`): How tool calls are rendered in the channel. "cards" posts per-tool running/result cards as rich Block Kit. "text" posts the same lifecycle as plain text (no Block Kit). "timeline" and "grouped" stream tool state as inline task_update chunks (requires streaming: true; Slack only today — other adapters may render a placeholder). "hidden" executes tools silently. Pass a function to render tool events yourself; return { kind: "post", message } for a discrete post/edit, { kind: "stream", chunk } to push into the streaming widget, or undefined to skip rendering that event. Add openIfEmpty: false to a stream result when its chunk should only apply to an active streaming session. Approve/deny prompts render as a separate built-in card in every string mode; a toolDisplay function receives the approval event and may replace the card by returning { kind: "post", message }. (Default: `'cards' ('grouped' for Slack)`)
115
+ **toolDisplay** (`'cards' | 'text' | 'timeline' | 'grouped' | 'hidden' | ToolDisplayFn`): How tool calls are rendered in the channel. "cards" posts per-tool running/result cards as rich Block Kit. "text" posts the same lifecycle as plain text (no Block Kit). "timeline" and "grouped" stream tool state as inline task_update chunks (requires streaming: true; Slack only today — other adapters may render a placeholder). "hidden" executes tools silently. Pass a function to render tool events yourself; return { kind: "post", message } for a discrete post/edit, { kind: "stream", chunk } to push into the streaming widget, or undefined to skip rendering that event. Add openIfEmpty: false to a stream result when its chunk should only apply to an active streaming session. Approve/deny prompts render as a separate built-in card in every string mode; a toolDisplay function receives the approval event and may replace the card by returning { kind: "post", message }. (Default: `'cards'`)
116
116
 
117
117
  **toolApprovers** (`'requester' | 'anyone'`): Who may approve or deny a pending tool call in this adapter's channel. By default, only the user who triggered the call can respond when their identity was recorded; runs without a recorded requester (such as scheduled runs) may allow another channel member to respond. Set 'anyone' to allow another channel member to respond even when a requester was recorded. Pending-approval and thread-mapping checks still apply. (Default: `'requester'`)
118
118
 
@@ -120,7 +120,7 @@ const agent = new Agent({
120
120
 
121
121
  ## Tool display modes
122
122
 
123
- `toolDisplay` controls how tool calls render in chat. The default `'cards'` posts a "Running…" card per tool and edits it with the result, matching the behavior in earlier versions. `'text'` is the same lifecycle but without rich Block Kit, useful for platforms that don't render cards well.
123
+ `toolDisplay` controls how tool calls render in chat. The default `'cards'` posts a "Running…" card per tool and edits it with the result, matching the behavior in earlier versions. This is the default on every adapter, including Slack. To get grouped tool state on Slack, set `streaming: true` and `toolDisplay: 'grouped'` explicitly. `'text'` is the same lifecycle but without rich Block Kit, useful for platforms that don't render cards well.
124
124
 
125
125
  `'timeline'` and `'grouped'` stream tool state as inline `task_update` chunks alongside the agent's text. These modes require `streaming: true` and rely on the chat adapter to render the chunks. Slack supports both natively; other adapters may render a placeholder until they add support. If `streaming` is disabled, the channel logs a one-time warning and falls back to `'cards'`.
126
126
 
@@ -164,7 +164,7 @@ const agent = new Agent({
164
164
  adapters: {
165
165
  slack: {
166
166
  adapter: createSlackAdapter(),
167
- streaming: true, // already the Slack default
167
+ streaming: true, // off by default on every adapter
168
168
  toolDisplay: 'timeline',
169
169
  },
170
170
  },
@@ -76,6 +76,10 @@ const { controller } = await mountAgentControllerOnMastra({ mastra })
76
76
 
77
77
  **storage** (`StorageConfig | MastraCompositeStore`): Custom storage config instead of the auto-detected default, or a pre-built store instance. An injected instance has no connection test or LibSQL fallback. In both cases the SDK wraps the store: scorer results are discarded unless disableScoreStorage is false, and local observability goes to a separate DuckDB store only when local tracing is enabled and that store opens; otherwise local observability is disabled. Cloud export runs independently when cloud credentials are configured.
78
78
 
79
+ **scorers** (`AgentConfig["scorers"]`): Scorers to run for the code agent. No scorers are registered by default.
80
+
81
+ **disableScoreStorage** (`boolean`): Discard rich scorer results instead of saving them to configured storage. (Default: `true`)
82
+
79
83
  **storageBackend** (`'libsql' | 'pg'`): Backend of an injected storage instance. Inferred for LibSQLStore and PostgresStore; required for any other injected store, otherwise mounting throws.
80
84
 
81
85
  **vector** (`MastraVector`): Pre-built vector store for recall search. Skips creating the default vector store. When storage is a pre-built instance, no default vector store is created, so pass vector to keep semantic recall search; without it, recall still browses history but can't search semantically.
@@ -77,7 +77,7 @@ export const mastra = new Mastra({
77
77
 
78
78
  **backpressure** (`'queue' | 'reject' | 'fallback-sync'`): Behavior when a concurrency limit is reached. 'queue' waits for a slot, 'reject' throws on enqueue, 'fallback-sync' runs the tool synchronously in the agentic loop instead. (Default: `'queue'`)
79
79
 
80
- **defaultTimeoutMs** (`number`): Default per-task timeout in milliseconds. Can be overridden per-tool or per-call. (Default: `300000`)
80
+ **defaultTimeoutMs** (`number`): Default per-task timeout in milliseconds. 0 means no timeout. Can be overridden per-tool or per-call. (Default: `300000`)
81
81
 
82
82
  **defaultRetries** (`RetryConfig`): Default retry policy applied to tasks that fail.
83
83
 
@@ -127,7 +127,7 @@ Visit the [Configuration reference](https://mastra.ai/reference/configuration) f
127
127
 
128
128
  **backgroundTasks.backpressure** (`'queue' | 'reject' | 'fallback-sync'`): Behavior when concurrency limit is reached.
129
129
 
130
- **backgroundTasks.defaultTimeoutMs** (`number`): Default task timeout in milliseconds.
130
+ **backgroundTasks.defaultTimeoutMs** (`number`): Default task timeout in milliseconds. 0 means no timeout.
131
131
 
132
132
  **backgroundTasks.defaultRetries** (`RetryConfig`): Default retry configuration.
133
133
 
@@ -135,13 +135,17 @@ Visit the [Configuration reference](https://mastra.ai/reference/configuration) f
135
135
 
136
136
  **scheduler.enabled** (`boolean`): Explicitly enable or disable the scheduler.
137
137
 
138
- **recovery** (`MastraRecoveryConfig`): Boot-time recovery behavior for orphaned agent and workflow runs. See Crash recovery. (Default: `{ durableAgents: 'off', workflows: 'auto', workflowConcurrency: 5 }`)
138
+ **recovery** (`MastraRecoveryConfig`): Boot-time recovery behavior for orphaned agent and workflow runs. See Crash recovery. (Default: `{ durableAgents: 'off', workflows: 'auto', workflowConcurrency: 5, workflowGraceMs: 2000, workflowScanIntervalMs: 60000 }`)
139
139
 
140
140
  **recovery.durableAgents** (`'auto' | 'off'`): Set to 'auto' to automatically re-drive orphaned RUNNING durable agent runs on server boot. This also controls the default snapshot-persistence policy for durable agents: running checkpoints are only written when set to 'auto' (or when an agent sets a custom shouldPersistSnapshot that includes running). Recovery can run an interrupted tool call again and request a new model response in place of one that wasn't saved, so tools must be idempotent. See make tools safe to repeat.
141
141
 
142
- **recovery.workflows** (`'auto' | 'off'`): Set to 'off' to skip restarting active workflow runs on server boot. Individual workflows can also opt out with autoRestartActiveRuns: false.
142
+ **recovery.workflows** (`'auto' | 'off'`): Set to 'off' to skip restarting active workflow runs on server boot and to run no workflow recovery loop. Individual workflows can also opt out with autoRestartActiveRuns: false.
143
143
 
144
- **recovery.workflowConcurrency** (`number`): Maximum number of workflow runs restarted at the same time during boot recovery. Use Infinity for no limit. Workflow and durable agent recovery run in parallel.
144
+ **recovery.workflowConcurrency** (`number`): Maximum number of workflow runs restarted at the same time by boot recovery and the recovery loop. Use Infinity for no limit. A restarted run holds its slot until it finishes. Workflow and durable agent recovery run in parallel.
145
+
146
+ **recovery.workflowGraceMs** (`number`): How long a running or waiting default-engine workflow run must go without an instance holding its lease, and without any change, before recovery restarts it. A run that stopped more recently is left to the recovery loop. The grace applies on a storage adapter with run-ownership support; without it, every active default-engine run is restarted, as before. Evented runs don't use it: a broker that redelivers unacknowledged events recovers them, and on any other pubsub they're restarted at once.
147
+
148
+ **recovery.workflowScanIntervalMs** (`number`): How often the recovery loop that startWorkers() starts looks for default-engine runs whose instance stopped. Each wait is up to a fifth shorter or longer, and shorter when a run the last pass saw comes out of its grace period sooner. Capped at 2^31 - 1 ms. One instance at a time runs the passes. A run whose instance crashed is restarted at the first pass after its lease (MASTRA_AGENT_THREAD_LEASE_TTL_MS, 15 seconds by default) expired and workflowGraceMs passed, so within about one interval of that. A lower interval recovers such runs sooner and lists runs more often.
145
149
 
146
150
  ## Methods
147
151
 
@@ -181,15 +181,15 @@ Groups matching records by one or more dimensions and aggregates each group. The
181
181
 
182
182
  #### Arguments
183
183
 
184
- | Field | Type | Required | Description |
185
- | ---------------- | ---------------------- | -------------------- | ----------------------------------------------------------------------------------- |
186
- | `name` | `string[]` | Yes | One or more metric names |
187
- | `groupBy` | `string[]` | Yes | One or more fields to group by |
188
- | `aggregation` | `AggregationType` | Yes | Aggregation for each group |
189
- | `distinctColumn` | `MetricDistinctColumn` | For `count_distinct` | Column whose distinct values are counted |
190
- | `filters` | `MetricsFilter` | No | Shared metric filters |
191
- | `limit` | `number` | No | Positive integer up to 1,000. Required for high-cardinality groupings. |
192
- | `orderDirection` | `'ASC' \| 'DESC'` | No | Sort direction for the aggregated value. Storage implementations default to `DESC`. |
184
+ | Field | Type | Required | Description |
185
+ | ---------------- | ---------------------- | -------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
186
+ | `name` | `string[]` | Yes | One or more metric names |
187
+ | `groupBy` | `string[]` | Yes | One or more fields to group by |
188
+ | `aggregation` | `AggregationType` | Yes | Aggregation for each group |
189
+ | `distinctColumn` | `MetricDistinctColumn` | For `count_distinct` | Column whose distinct values are counted |
190
+ | `filters` | `MetricsFilter` | No | Shared metric filters |
191
+ | `limit` | `number` | No | Positive integer up to 1,000. Keeps only the top groups after sorting by `orderDirection`. When omitted, all groups are returned. Set it for high-cardinality groupings such as `threadId` to bound the response. When grouping by a label key, some stores, such as PostgreSQL, exclude rows where the label is missing or empty, so the groups might not add up to the overall total even without a `limit`. Use `getMetricAggregate()` for that total. |
192
+ | `orderDirection` | `'ASC' \| 'DESC'` | No | Sort direction for the aggregated value. Storage implementations default to `DESC`. |
193
193
 
194
194
  #### Returns
195
195
 
@@ -198,6 +198,11 @@ interface Span<TType extends SpanType> {
198
198
  readonly type: TType
199
199
  readonly name: string
200
200
 
201
+ /** Entity that created the span */
202
+ entityType?: EntityType
203
+ entityId?: string
204
+ entityName?: string
205
+
201
206
  /** Is an internal span? (spans internal to the operation of mastra) */
202
207
  isInternal: boolean
203
208
 
@@ -528,8 +533,8 @@ Agent Run attributes.
528
533
 
529
534
  ```typescript
530
535
  interface AgentRunAttributes {
531
- /** Agent identifier */
532
- agentId: string
536
+ /** Conversation/thread/session identifier for multi-turn interactions */
537
+ conversationId?: string
533
538
 
534
539
  /** Agent Instructions */
535
540
  instructions?: string
@@ -585,13 +590,7 @@ interface ModelGenerationAttributes {
585
590
  resultType?: 'tool_selection' | 'response_generation' | 'reasoning' | 'planning'
586
591
 
587
592
  /** Token usage statistics */
588
- usage?: {
589
- promptTokens?: number
590
- completionTokens?: number
591
- totalTokens?: number
592
- promptCacheHitTokens?: number
593
- promptCacheMissTokens?: number
594
- }
593
+ usage?: UsageStats
595
594
 
596
595
  /** Model parameters */
597
596
  parameters?: {
@@ -879,9 +878,6 @@ Workflow Run attributes.
879
878
 
880
879
  ```typescript
881
880
  interface WorkflowRunAttributes {
882
- /** Workflow identifier */
883
- workflowId: string
884
-
885
881
  /** Workflow status */
886
882
  status?: WorkflowRunStatus
887
883
  }
@@ -893,11 +889,49 @@ Workflow Step attributes.
893
889
 
894
890
  ```typescript
895
891
  interface WorkflowStepAttributes {
896
- /** Step identifier */
897
- stepId: string
898
-
899
892
  /** Step status */
900
893
  status?: WorkflowStepStatus
894
+
895
+ /** Authored graph entry description */
896
+ entryDescription?: string
897
+
898
+ /** Authored graph entry metadata */
899
+ entryMetadata?: Record<string, any>
900
+ }
901
+ ```
902
+
903
+ `AgentRunAttributes`, `WorkflowRunAttributes`, and `WorkflowStepAttributes` don't include agent or workflow identifiers. Read them from the span's `entityType`, `entityId`, and `entityName` fields. On a `WORKFLOW_STEP` span, `entityId` is the step ID, and `entityName` is inherited from the enclosing workflow. To get the workflow ID, read `entityId` from the enclosing `WORKFLOW_RUN` span. If `excludeSpanTypes` excludes `WORKFLOW_RUN` spans, the step inherits `entityName` from the nearest ancestor that isn’t excluded instead. That ancestor can be an agent span, or there can be none, so `entityName` doesn’t reliably name the workflow in that case.
904
+
905
+ ### `UsageStats`
906
+
907
+ Token usage recorded on model spans.
908
+
909
+ ```typescript
910
+ interface UsageStats {
911
+ /** Total input tokens (sum of all input details) */
912
+ inputTokens?: number
913
+
914
+ /** Total output tokens (sum of all output details) */
915
+ outputTokens?: number
916
+
917
+ /** Detailed breakdown of input token usage */
918
+ inputDetails?: {
919
+ text?: number
920
+ cacheRead?: number
921
+ cacheWrite?: number
922
+ cacheWrite5m?: number
923
+ cacheWrite1h?: number
924
+ audio?: number
925
+ image?: number
926
+ }
927
+
928
+ /** Detailed breakdown of output token usage */
929
+ outputDetails?: {
930
+ text?: number
931
+ reasoning?: number
932
+ audio?: number
933
+ image?: number
934
+ }
901
935
  }
902
936
  ```
903
937
 
@@ -172,6 +172,8 @@ await pubsub.subscribeFromOffset('my-topic', 42, event => {
172
172
 
173
173
  **supportsOffsets** (`boolean`): Whether subscribeFromOffset() honors numeric offsets. Defaults to false. A non-zero offset on an unsupported implementation falls back to replay subscription and emits a diagnostic warning when a logger is configured.
174
174
 
175
+ **redeliversUnacked** (`boolean`): Whether an event delivered to a consumer that neither acks nor nacks it, for example because its process stopped, is delivered again to another consumer of the same group once the broker considers it abandoned. Defaults to false. Workflow recovery doesn't restart evented runs on a pubsub that returns true, so return true only when the broker does this, and only after 30 seconds or more.
176
+
175
177
  ## Types
176
178
 
177
179
  ### `Event`
@@ -103,9 +103,9 @@ const pubsub = new RedisStreamsPubSub({
103
103
 
104
104
  **streamIdleTtlMs** (`number`): Idle expiry in milliseconds: a sliding TTL refreshed on every write to a stream (publish, subscribe creating its consumer group, nack retry). Each write resets it, so an actively-written stream never expires mid-flight; a stream left idle for the full duration is deleted by Redis automatically, together with its entries and consumer groups. Only writes refresh the TTL — a consumer slowly draining a backlog does not — so keep it well above the longest expected gap between writes on a live topic, and above the longest a grouped worker may be offline while still expecting to replay its backlog on restart. For topics with a clear end of life (workflow and agent runs), clearTopic deletes the stream eagerly and the TTL only covers streams that never reach that call, such as a crashed run. For open-ended topics that are never cleared (for example, per-conversation streams), the TTL is the only mechanism that reclaims their memory. Set to 0 to disable expiry; streams that never reach clearTopic then stay in Redis forever. Must be a non-negative integer. (Default: `604800000 (7 days)`)
105
105
 
106
- **reclaimIntervalMs** (`number`): How often, in milliseconds, a subscription reclaims events that an earlier consumer read but never acknowledged. Set to 0 to disable. (Default: `30000`)
106
+ **reclaimIntervalMs** (`number`): How often, in milliseconds, a subscription reclaims events that an earlier consumer read but never acknowledged. Set to 0 to disable. While it's enabled, workflow recovery leaves evented runs to this reclaim instead of restarting them. With 0, the pubsub no longer redelivers a stopped worker's events, so workflow recovery restarts evented runs when an instance boots, as it does without a broker. (Default: `30000`)
107
107
 
108
- **reclaimIdleMs** (`number`): Minimum idle time, in milliseconds, before a pending event is eligible for reclaim. Keep this well above typical processing time to avoid double delivery. (Default: `60000`)
108
+ **reclaimIdleMs** (`number`): Minimum idle time, in milliseconds, before a pending event is eligible for reclaim. Keep this well above typical processing time to avoid double delivery, and at 30000 or more for evented workflows: a step event reclaimed sooner can be dropped as a duplicate. (Default: `60000`)
109
109
 
110
110
  **maxDeliveryAttempts** (`number`): Maximum times an event is redelivered through nack before it is dropped. Pass Infinity to disable the cap. (Default: `5`)
111
111
 
@@ -230,7 +230,7 @@ A subscription never reclaims an event its own handler is still processing, so a
230
230
 
231
231
  With Postgres storage, distributed evented agents publish worker orchestration events through Redis. If a worker exits before acknowledging an event, another worker can reclaim it and finish the run while the original API process stays alive. Configure the API process with `MASTRA_WORKERS=false` and worker processes with `MASTRA_WORKERS=orchestration`. All processes must share the same Postgres database, Redis connection settings, and `keyPrefix`.
232
232
 
233
- Keep `reclaimIdleMs` above 30 seconds (the default is 60 seconds). A lower value can reclaim an event while the stopped worker's step lease is still held, causing the event to be acknowledged without running.
233
+ Keep `reclaimIdleMs` above 30 seconds (the default is 60 seconds). A lower value can reclaim an event while the stopped worker still holds the step, causing the event to be acknowledged without running.
234
234
 
235
235
  Runs started on older versions can finish after upgrading, but don't have guaranteed crash recovery. Saved steps without occurrence identifiers keep their existing unguarded behavior. Other storage adapters keep distributed internal orchestration on the worker process.
236
236
 
@@ -61,9 +61,9 @@ export const mastra = new Mastra({
61
61
 
62
62
  **streamIdleTtlMs** (`number`): Sliding idle expiry in milliseconds, refreshed on every write to a stream. A stream left idle for the full duration is deleted with its entries and consumer groups. Keep it above the longest time a grouped worker may be offline while still expecting to replay its backlog. Set to 0 to disable expiry; streams that never reach clearTopic then stay in Valkey forever. (Default: `604800000 (7 days)`)
63
63
 
64
- **reclaimIntervalMs** (`number`): Interval for reclaiming unacknowledged events. Set to 0 to disable. (Default: `30000`)
64
+ **reclaimIntervalMs** (`number`): Interval for reclaiming unacknowledged events. Set to 0 to disable. While it's enabled, workflow recovery leaves evented runs to this reclaim instead of restarting them. With 0, the pubsub no longer redelivers a stopped worker's events, so workflow recovery restarts evented runs when an instance boots, as it does without a broker. (Default: `30000`)
65
65
 
66
- **reclaimIdleMs** (`number`): Minimum idle time before an event can be reclaimed. (Default: `60000`)
66
+ **reclaimIdleMs** (`number`): Minimum idle time before an event can be reclaimed. Keep it at 30000 or more for evented workflows: a step event reclaimed sooner can be dropped as a duplicate. (Default: `60000`)
67
67
 
68
68
  **maxDeliveryAttempts** (`number`): Maximum nack redeliveries. Pass Infinity to disable the cap. (Default: `5`)
69
69
 
@@ -19,7 +19,7 @@ const { runId } = await run.startAsync({
19
19
  })
20
20
 
21
21
  // Optionally poll for completion later
22
- const result = await workflow.getWorkflowRunExecutionResult(runId)
22
+ const state = await workflow.getWorkflowRunById(runId)
23
23
  ```
24
24
 
25
25
  ## Parameters
@@ -57,18 +57,21 @@ Use `startAsync()` instead of `start()` when:
57
57
 
58
58
  ## Checking workflow status
59
59
 
60
- After calling `startAsync()`, you can check the workflow status using:
60
+ After calling `startAsync()`, check the workflow status with `workflow.getWorkflowRunById()`. It returns the run state, including `status`, `steps`, `result`, and `error`, or `null` if the run isn't found.
61
+
62
+ Without configured [storage](https://mastra.ai/docs/storage), or before the run is persisted, the method returns an in-memory state with `isFromInMemory: true`, empty `steps`, and no `result` or `error`. Configure storage to read a run's result after it finishes.
61
63
 
62
64
  ```typescript
63
- // Get the execution result (including step outputs)
64
- const result = await workflow.getWorkflowRunExecutionResult(runId)
65
-
66
- if (result?.status === 'success') {
67
- console.log('Workflow completed:', result.steps)
68
- } else if (result?.status === 'failed') {
69
- console.log('Workflow failed:', result.error)
70
- } else if (result?.status === 'running') {
71
- console.log('Workflow still running...')
65
+ const state = await workflow.getWorkflowRunById(runId)
66
+
67
+ if (!state) {
68
+ console.log('Workflow run not found')
69
+ } else if (state.status === 'success') {
70
+ console.log('Workflow completed:', state.result)
71
+ } else if (state.status === 'failed') {
72
+ console.log('Workflow failed:', state.error)
73
+ } else {
74
+ console.log('Workflow status:', state.status)
72
75
  }
73
76
  ```
74
77
 
@@ -14,7 +14,7 @@ workflow.map(async ({ inputData }) => `${inputData.value} - map`)
14
14
 
15
15
  ## Parameters
16
16
 
17
- **mappingFunction** (`(params: { inputData: any }) => any`): Function that transforms input data and returns the mapped result
17
+ **mappingFunction** (`(params: { inputData: any }) => Promise<any>`): Async function that transforms input data and returns the mapped result. The function must return a Promise, so declare it with async.
18
18
 
19
19
  **stepOptions** (`object`): Optional identity and display metadata for the mapping entry. Preserved through serialization and storage; has no effect on execution.
20
20
 
@@ -28,7 +28,7 @@ Use `inputData` to access the full output of the previous step.
28
28
 
29
29
  ```typescript
30
30
  .then(step1)
31
- .map(({ inputData }) => {
31
+ .map(async ({ inputData }) => {
32
32
  console.log(inputData);
33
33
  })
34
34
  ```
@@ -127,9 +127,9 @@ export const testWorkflow = createWorkflow({
127
127
 
128
128
  **options.autoRestartActiveRuns** (`boolean`): Whether boot-time generic recovery (Mastra.restartAllActiveWorkflowRuns()) automatically restarts this workflow's active runs. Set to false for workflows whose side effects must not be re-driven by a blanket restart, or whose recovery is owned by another mechanism. Durable agent workflows set this to false because their recovery is owned by the opt-in recovery.durableAgents: 'auto' path.
129
129
 
130
- **options.shouldPersistSnapshot** (`(params: { stepResults: Record<string, StepResult<any, any, any, any>>; workflowStatus: WorkflowRunStatus }) => boolean`): Optional flag to determine whether to persist the workflow snapshot
130
+ **options.shouldPersistSnapshot** (`(params: { stepResults: Record<string, StepResult<any, any, any, any>>; workflowStatus: WorkflowRunStatus }) => boolean`): Optional flag to determine whether to persist the workflow snapshot. On the evented engine, returning false for a running run means a step delivered again after it finished runs again, along with the steps after it.
131
131
 
132
- **options.pruneSnapshot** (`(params: { snapshot: WorkflowRunState; workflowStatus: WorkflowRunStatus }) => WorkflowRunState`): Optional hook to transform the workflow snapshot immediately before it is persisted. Must return JSON-serializable data and preserve everything the workflow needs to resume (suspended step suspendPayloads, suspendedPaths, executionPath, etc.). Used internally by agent runs to keep snapshots minimal; user workflows persist full snapshots by default.
132
+ **options.pruneSnapshot** (`(params: { snapshot: WorkflowRunState; workflowStatus: WorkflowRunStatus }) => WorkflowRunState`): Optional hook to transform the workflow snapshot immediately before it is persisted. Must return JSON-serializable data and preserve everything the workflow needs to resume (suspended step suspendPayloads, suspendedPaths, executionPath, etc.). On the evented engine it must also keep the status, startedAt and endedAt of each step result, metadata.iterationCount on a loop step result, suspendPayload.\_\_workflow_meta.foreachOutput on a foreach step result, and activePaths. Without them, a step delivered again after it finished can run a second time. Used internally by agent runs to keep snapshots minimal; user workflows persist full snapshots by default.
133
133
 
134
134
  **options.storageVersion** (`1 | 2`): Experimental. How runs of this workflow are stored. 1 rewrites the whole run on every save. 2 saves only what changed at each step, which cuts storage writes for long workflows and loops. Version 2 requires the default execution engine and a storage adapter that supports it: in-memory, @mastra/pg, or @mastra/libsql. Creating a run on another adapter throws. It can't be combined with pruneSnapshot. Inside a version 2 run, read earlier steps with await getStepResultAsync(step) instead of getStepResult(step), and a shouldPersistSnapshot predicate sees earlier successful steps without their output. Workflow state is stored as JSON, so values such as Date are read back as strings. A run keeps the version it was stored with, so a run resumed after changing this option continues in that version. A nested workflow's runs use their parent run's version, so this option applies only when the workflow runs on its own.
135
135
 
@@ -521,11 +521,11 @@ The `execute_command` tool accepts these options:
521
521
 
522
522
  **backgroundProcesses** (`BackgroundProcessesConfig`): Configuration for handling background processes. Only applicable if the sandbox supports background execution.
523
523
 
524
- **backgroundProcesses.onStdout** (`(data: string, meta: BackgroundProcessMeta) => void`): Callback for stdout chunks from background processes.
524
+ **backgroundProcesses.onStdout** (`(data: string, meta: BackgroundProcessMeta) => void`): Callback for stdout chunks from background processes. Meta includes pid, toolCallId, agentId, threadId, resourceId, and runId of the call that started the process.
525
525
 
526
- **backgroundProcesses.onStderr** (`(data: string, meta: BackgroundProcessMeta) => void`): Callback for stderr chunks from background processes.
526
+ **backgroundProcesses.onStderr** (`(data: string, meta: BackgroundProcessMeta) => void`): Callback for stderr chunks from background processes. Meta matches onStdout.
527
527
 
528
- **backgroundProcesses.onExit** (`(meta: BackgroundProcessExitMeta) => void`): Callback when a background process exits. Meta includes pid, exitCode, stdout, and stderr.
528
+ **backgroundProcesses.onExit** (`(meta: BackgroundProcessExitMeta) => void`): Callback when a background process exits. Meta includes the onStdout fields plus exitCode, stdout, stderr, and killedByAbort (true when the abort signal killed the process, false for a normal exit or kill_process).
529
529
 
530
530
  **backgroundProcesses.abortSignal** (`AbortSignal | null | false`): Abort signal for background processes. undefined (default) uses the agent's signal. null or false disables abort — processes persist after agent shutdown.
531
531
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mastra/mcp-docs-server",
3
- "version": "1.3.14-alpha.0",
3
+ "version": "1.3.14-alpha.2",
4
4
  "description": "MCP server for accessing Mastra.ai documentation, changelogs, and news.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -26,7 +26,7 @@
26
26
  "@mastra/mcp-legacy": "npm:@mastra/mcp@^1.18.0",
27
27
  "local-pkg": "^1.2.1",
28
28
  "zod": "^4.6.7",
29
- "@mastra/core": "1.84.0-alpha.0",
29
+ "@mastra/core": "1.84.0-alpha.2",
30
30
  "@mastra/mcp": "^2.9.0"
31
31
  },
32
32
  "devDependencies": {