@mastra/mcp-docs-server 1.3.13 → 1.3.14-alpha.1

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 (47) 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/agents/tools.md +2 -0
  5. package/.docs/docs/deployment/web-framework.md +1 -1
  6. package/.docs/docs/deployment/workers.md +16 -4
  7. package/.docs/docs/guides/authentication-identity.md +13 -1
  8. package/.docs/docs/harness/agent-controller.md +2 -0
  9. package/.docs/docs/harness/background-tasks.md +3 -1
  10. package/.docs/docs/knowledge/scopes-and-access.md +1 -1
  11. package/.docs/docs/sandbox/overview.md +23 -2
  12. package/.docs/docs/server/mcp.md +33 -1
  13. package/.docs/docs/server/overview.md +1 -0
  14. package/.docs/docs/server/request-context.md +1 -1
  15. package/.docs/docs/server/server-adapters.md +3 -0
  16. package/.docs/docs/studio/auth.md +5 -1
  17. package/.docs/docs/studio/editor.md +17 -0
  18. package/.docs/docs/studio/knowledge.md +34 -0
  19. package/.docs/docs/studio/overview.md +1 -1
  20. package/.docs/docs/workflows/overview.md +21 -3
  21. package/.docs/integrations/deploy/kubernetes-helm.md +8 -9
  22. package/.docs/integrations/frameworks/next-js.md +22 -6
  23. package/.docs/integrations/sandboxes/daytona.md +6 -6
  24. package/.docs/reference/agent-controller/session.md +4 -1
  25. package/.docs/reference/agents/agent.md +1 -1
  26. package/.docs/reference/agents/channels.md +4 -4
  27. package/.docs/reference/auth/auth0.md +2 -0
  28. package/.docs/reference/auth/clerk.md +4 -0
  29. package/.docs/reference/auth/jwt.md +4 -0
  30. package/.docs/reference/code-sdk/mount-agent-controller.md +4 -0
  31. package/.docs/reference/configuration.md +1 -1
  32. package/.docs/reference/core/mastra-class.md +8 -4
  33. package/.docs/reference/index.md +1 -0
  34. package/.docs/reference/knowledge/knowledge-class.md +1 -1
  35. package/.docs/reference/knowledge/knowledge-memory-scopes.md +44 -4
  36. package/.docs/reference/knowledge/scope-declarations.md +7 -3
  37. package/.docs/reference/observability/metrics/queries.md +9 -9
  38. package/.docs/reference/observability/tracing/interfaces.md +49 -15
  39. package/.docs/reference/pubsub/base.md +2 -0
  40. package/.docs/reference/pubsub/redis-streams.md +3 -3
  41. package/.docs/reference/pubsub/valkey-streams.md +2 -2
  42. package/.docs/reference/server/builtin-mcp-tools.md +135 -0
  43. package/.docs/reference/tools/mcp-server.md +2 -0
  44. package/.docs/reference/workflows/run-methods/startAsync.md +14 -11
  45. package/.docs/reference/workflows/workflow-methods/map.md +2 -2
  46. package/.docs/reference/workflows/workflow.md +2 -2
  47. package/package.json +4 -4
@@ -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
 
@@ -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
  },
@@ -72,6 +72,8 @@ The `Auth0User` type used in the `authorizeUser` function corresponds to the dec
72
72
 
73
73
  The exact properties available depend on your Auth0 configuration, scopes requested, and any custom claims you've configured.
74
74
 
75
+ The authenticated user's `id` is the token's `id` claim, or its `sub` claim when the token has no `id`. RBAC looks up roles by this `id`, and it owns the records the user creates unless `mapUserToResourceId` is set. See [user IDs from JWT providers](https://mastra.ai/docs/guides/authentication-identity).
76
+
75
77
  ## Related
76
78
 
77
79
  [MastraAuthAuth0 Class](https://mastra.ai/integrations/auth/auth0)
@@ -43,6 +43,10 @@ export const mastra = new Mastra({
43
43
  })
44
44
  ```
45
45
 
46
+ ## User ID
47
+
48
+ The authenticated user's `id` is the token's `id` claim, or its `sub` claim when the token has no `id`. RBAC looks up roles by this `id`, and it owns the records the user creates unless `mapUserToResourceId` is set. See [user IDs from JWT providers](https://mastra.ai/docs/guides/authentication-identity).
49
+
46
50
  ## Constructor parameters
47
51
 
48
52
  **publishableKey** (`string`): Your Clerk publishable key. Can be found in your Clerk Dashboard under API Keys. (Default: `process.env.CLERK_PUBLISHABLE_KEY`)
@@ -37,6 +37,10 @@ export const mastra = new Mastra({
37
37
  })
38
38
  ```
39
39
 
40
+ ## User ID
41
+
42
+ The authenticated user's `id` is the token's `id` claim, or its `sub` claim when the token has no `id`. RBAC looks up roles by this `id`, and it owns the records the user creates unless `mapUserToResourceId` is set. See [user IDs from JWT providers](https://mastra.ai/docs/guides/authentication-identity).
43
+
40
44
  ## Constructor parameters
41
45
 
42
46
  **secret** (`string`): A unique string used to sign and verify JSON Web Tokens (JWTs) for authenticating incoming requests. Falls back to JWT_AUTH_SECRET when omitted. Either a secret or jwksUri is required: the constructor throws an error if neither is set, or if this option is an empty string (an empty string does not fall back to JWT_AUTH_SECRET). (Default: `process.env.JWT_AUTH_SECRET`)
@@ -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
 
@@ -329,6 +329,7 @@ The Reference section provides documentation of Mastra's API, including paramete
329
329
  - [Vector Databases](https://mastra.ai/reference/rag/vector-databases)
330
330
  - [.chunk()](https://mastra.ai/reference/rag/chunk)
331
331
  - [Overview](https://mastra.ai/reference/schedules/overview)
332
+ - [Built-in MCP tools](https://mastra.ai/reference/server/builtin-mcp-tools)
332
333
  - [createRoute()](https://mastra.ai/reference/server/create-route)
333
334
  - [dispatchRoute()](https://mastra.ai/reference/server/dispatch-route)
334
335
  - [Elysia Adapter](https://mastra.ai/reference/server/elysia-adapter)
@@ -96,7 +96,7 @@ explainAccess(
96
96
  ): Promise<KnowledgeAccessExplanation>
97
97
  ```
98
98
 
99
- Explains why a run holding `runScopes` can or can't reach a scope or page. `runScopes` are raw run scopes, as you'd pass to an agent. `target.page` takes a page ID or a page path such as `org:acme#policies/refund`.
99
+ Explains why a run holding `runScopes` can or can't reach a scope or page. `runScopes` are canonical addresses, including `resource:` and `thread:` (`resource:slack%3AU123` for Memory resource `slack:U123`). `target.page` takes a page ID or a page path such as `org:acme#policies/refund`.
100
100
 
101
101
  ```typescript
102
102
  await knowledge.explainAccess(['org:acme'], { page: 'team:acme:support#refunds' })
@@ -55,9 +55,9 @@ knowledgeMemoryScopes({ org: 'workspace:$workspaceId', orgRole: 'contributor' })
55
55
  knowledgeScopeAddress(pattern: string, params: Record<string, string>): string
56
56
  ```
57
57
 
58
- Builds a canonical scope address from a pattern and raw parameter values. Use it in host code for Knowledge APIs, `pinnedContext` entries and page references.
58
+ Builds a canonical scope address from a pattern and raw parameter values. Use it in host code for agent scopes, Knowledge APIs, `pinnedContext` entries and page references.
59
59
 
60
- Inside values, `%`, `/` and `#` are encoded as `%25`, `%2F` and `%23`. `:` is encoded as `%3A` in every parameter except the last. It throws when a parameter is missing or empty.
60
+ Inside every value, `%`, `/`, `#` and `:` are encoded as `%25`, `%2F`, `%23` and `%3A`. Each value fills exactly one segment. It throws when a parameter is missing or empty.
61
61
 
62
62
  ```typescript
63
63
  import { knowledgeScopeAddress } from '@mastra/core/knowledge'
@@ -66,10 +66,50 @@ knowledgeScopeAddress('resource:$resourceId', { resourceId: 'acme/dana' })
66
66
  // 'resource:acme%2Fdana'
67
67
 
68
68
  knowledgeScopeAddress('team:$orgId:$teamId', { orgId: 'a:b', teamId: 'c:d' })
69
- // 'team:a%3Ab:c:d'
69
+ // 'team:a%3Ab:c%3Ad'
70
70
  ```
71
71
 
72
- > **Note:** Don't pass the result as an agent scope. Agent scopes take raw IDs (`resource:acme/dana`), and Knowledge encodes them at run start. See [set a run's scopes](https://mastra.ai/docs/knowledge/scopes-and-access).
72
+ ## `encodeKnowledgeScopeId()`
73
+
74
+ ```typescript
75
+ encodeKnowledgeScopeId(id: string): string
76
+ ```
77
+
78
+ Encodes one ID, such as a tenant or user ID, for one segment of a scope address. It applies the same encoding as `knowledgeScopeAddress()`. Use it when you build an address with a template string:
79
+
80
+ ```typescript
81
+ import { encodeKnowledgeScopeId } from '@mastra/core/knowledge'
82
+
83
+ const scope = `org:${encodeKnowledgeScopeId('auth0|a:b')}`
84
+ // 'org:auth0|a%3Ab'
85
+ ```
86
+
87
+ ## `decodeKnowledgeScopeId()`
88
+
89
+ ```typescript
90
+ decodeKnowledgeScopeId(segment: string): string | null
91
+ ```
92
+
93
+ Returns the ID in one segment of a scope address. It returns `null` when the segment isn't canonically encoded, for example when it holds a raw `:` or a lowercase escape such as `%3a`.
94
+
95
+ ```typescript
96
+ import { decodeKnowledgeScopeId } from '@mastra/core/knowledge'
97
+
98
+ decodeKnowledgeScopeId('slack%3AU123') // 'slack:U123'
99
+ decodeKnowledgeScopeId('a:b') // null
100
+ ```
101
+
102
+ ## Agent scopes
103
+
104
+ Agent scopes are canonical addresses. Encode any ID that contains `:`, `/`, `#` or `%`, with `encodeKnowledgeScopeId()` or `knowledgeScopeAddress()`. A raw ID, such as `org:a:b` for org `a:b`, fails at run start:
105
+
106
+ ```text
107
+ Knowledge run scope "org:a:b" does not match a declared scope type. Declare it in Knowledge `scopes` (for Memory's resource:/thread: scopes, spread `...knowledgeMemoryScopes()`), and encode ids containing ":", "/", "#" or "%" with encodeKnowledgeScopeId.
108
+ ```
109
+
110
+ `resource:` and `thread:` agent scopes are the exception. They set the run's Memory resource and thread, so they take Memory's raw IDs, and Knowledge encodes them. A run with Memory resource `slack:U123` holds `resource:slack%3AU123`. See [set a run's scopes](https://mastra.ai/docs/knowledge/scopes-and-access).
111
+
112
+ Scopes stored by earlier alpha releases with a raw `:` in their last segment aren't moved to the encoded address. See [Patterns and params](https://mastra.ai/reference/knowledge/scope-declarations).
73
113
 
74
114
  ## Related
75
115
 
@@ -56,9 +56,13 @@ export const knowledge = new Knowledge({
56
56
 
57
57
  A key such as `team:$orgId:$teamId` is a pattern. The text before the first `:` is the type, and each `$name` segment is a param. The address `team:acme:support` matches it with `$orgId = acme` and `$teamId = support`.
58
58
 
59
- The last param takes the rest of the value, so `resource:$resourceId` matches `resource:user:123` with `$resourceId = user:123`. Memory ids that contain `:` keep working.
59
+ Each param matches exactly one segment, so an address has as many segments as its pattern. `resource:user:123` doesn't match `resource:$resourceId`. An ID that contains `:`, `/`, `#` or `%` is encoded into one segment, so user `user:123` is `resource:user%3A123`. Build addresses with [`encodeKnowledgeScopeId()` or `knowledgeScopeAddress()`](https://mastra.ai/reference/knowledge/knowledge-memory-scopes). Memory IDs are encoded for you.
60
60
 
61
- A type can have several patterns only when no address can match two of them. Each pair must have different literal text at the same position:
61
+ > **Scopes stored by earlier alpha releases:** Earlier releases let the last param take the rest of the address, raw colons included. A scope stored that way, such as `resource:slack:U123` for Memory resource `slack:U123`, now has a new address, `resource:slack%3AU123`. Runs reach the new, empty scope. Pages, pins and notes under the old address stay in storage, but runs with that Memory resource no longer reach them, and Knowledge doesn't move them.
62
+ >
63
+ > A stored scope whose address now matches a different pattern, such as `org:acme:viewer` stored as an `org:$orgId` scope before you declared `org:$orgId:viewer`, gets no rules from the new pattern. Using it as a scope of the new pattern throws.
64
+
65
+ A type can have several patterns only when no address can match two of them. Patterns with different numbers of segments never overlap. Patterns with the same number must have different literal text at the same position:
62
66
 
63
67
  ```typescript
64
68
  scopes: {
@@ -73,7 +77,7 @@ Overlapping patterns fail at startup. There's no precedence between them:
73
77
  Knowledge scope patterns "role:$orgId:$role" and "role:$orgId:admin" overlap; patterns of a type must be pairwise disjoint.
74
78
  ```
75
79
 
76
- A pattern ending in a param overlaps a longer one with the same start, so `kb:$orgId` and `kb:$orgId:public` overlap too. Use two types, such as `kb-public:$orgId` and `kb-internal:$orgId`.
80
+ `kb:$orgId` and `kb:$orgId:public` can be declared together, because `kb:acme` and `kb:acme:public` have different numbers of segments. Each is its own scope with its own rules. Holding `kb:acme` gives no role on `kb:acme:public` unless a rule on `kb:$orgId:public` names `kb:$orgId`.
77
81
 
78
82
  ## Rules
79
83
 
@@ -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