@mastra/mcp-docs-server 1.3.9-alpha.4 → 1.3.9-alpha.7

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 (73) hide show
  1. package/.docs/docs/agents/human-in-the-loop.md +2 -1
  2. package/.docs/docs/harness/agent-controller.md +1 -1
  3. package/.docs/docs/harness/durable-agents.md +17 -5
  4. package/.docs/docs/harness/signals.md +3 -1
  5. package/.docs/docs/memory/observational-memory.md +4 -2
  6. package/.docs/docs/studio/overview.md +8 -0
  7. package/.docs/docs/workflows/control-flow.md +3 -1
  8. package/.docs/docs/workflows/overview.md +2 -0
  9. package/.docs/docs/workflows/time-travel.md +1 -1
  10. package/.docs/integrations/voice/google.md +6 -0
  11. package/.docs/models/gateways/merge-gateway.md +3 -1
  12. package/.docs/models/gateways/netlify.md +7 -4
  13. package/.docs/models/gateways/openrouter.md +7 -4
  14. package/.docs/models/gateways/vercel.md +7 -1
  15. package/.docs/models/index.md +1 -1
  16. package/.docs/models/providers/alibaba-token-plan-cn.md +31 -30
  17. package/.docs/models/providers/baseten.md +27 -25
  18. package/.docs/models/providers/cloudflare-workers-ai.md +2 -1
  19. package/.docs/models/providers/coralbricks.md +5 -8
  20. package/.docs/models/providers/cortecs.md +4 -4
  21. package/.docs/models/providers/deepinfra.md +2 -1
  22. package/.docs/models/providers/edenai.md +12 -6
  23. package/.docs/models/providers/empiriolabs.md +3 -1
  24. package/.docs/models/providers/engy.md +12 -11
  25. package/.docs/models/providers/fireworks-ai.md +2 -1
  26. package/.docs/models/providers/huggingface.md +2 -1
  27. package/.docs/models/providers/hyper.md +26 -25
  28. package/.docs/models/providers/kilo.md +23 -20
  29. package/.docs/models/providers/llmgateway-providers.md +9 -5
  30. package/.docs/models/providers/llmgateway.md +3 -1
  31. package/.docs/models/providers/minimax-cn-coding-plan.md +2 -1
  32. package/.docs/models/providers/minimax-cn.md +3 -2
  33. package/.docs/models/providers/minimax-coding-plan.md +2 -1
  34. package/.docs/models/providers/minimax.md +3 -2
  35. package/.docs/models/providers/nano-gpt.md +52 -55
  36. package/.docs/models/providers/nearai.md +1 -1
  37. package/.docs/models/providers/nebius.md +2 -1
  38. package/.docs/models/providers/novita-ai.md +2 -1
  39. package/.docs/models/providers/nvidia.md +2 -1
  40. package/.docs/models/providers/ofox.md +2 -1
  41. package/.docs/models/providers/ollama-cloud.md +31 -29
  42. package/.docs/models/providers/opencode-go.md +2 -2
  43. package/.docs/models/providers/opencode.md +87 -89
  44. package/.docs/models/providers/prime.md +3 -1
  45. package/.docs/models/providers/requesty.md +4 -1
  46. package/.docs/models/providers/standardcompute.md +47 -8
  47. package/.docs/models/providers/togetherai.md +4 -1
  48. package/.docs/models/providers/upstage.md +8 -7
  49. package/.docs/models/providers/wandb.md +3 -2
  50. package/.docs/models/providers/zenmux.md +2 -1
  51. package/.docs/reference/agents/channels.md +5 -1
  52. package/.docs/reference/agents/durable-agent.md +11 -6
  53. package/.docs/reference/classifier/classifier.md +29 -5
  54. package/.docs/reference/client-js/agent-controller.md +2 -0
  55. package/.docs/reference/client-js/observability.md +117 -0
  56. package/.docs/reference/core/mastra-class.md +7 -1
  57. package/.docs/reference/evals/create-classifier-scorer.md +1 -0
  58. package/.docs/reference/memory/observational-memory.md +2 -2
  59. package/.docs/reference/observability/tracing/trace-query.md +39 -10
  60. package/.docs/reference/processors/classifier-processor.md +8 -6
  61. package/.docs/reference/processors/model-selection-processor.md +2 -2
  62. package/.docs/reference/processors/moderation-processor.md +5 -1
  63. package/.docs/reference/processors/system-prompt-scrubber.md +4 -0
  64. package/.docs/reference/signals/create-notification-inbox-tool.md +11 -9
  65. package/.docs/reference/tools/create-tool.md +2 -2
  66. package/.docs/reference/tools/mcp-client.md +2 -2
  67. package/.docs/reference/workflows/dynamic-workflow-definition.md +1 -1
  68. package/.docs/reference/workflows/run-methods/resume.md +1 -1
  69. package/.docs/reference/workflows/run-methods/timeTravel.md +15 -16
  70. package/.docs/reference/workflows/step.md +1 -0
  71. package/.docs/reference/workflows/workflow-methods/classifier.md +1 -0
  72. package/.docs/reference/workspace/factory-sandbox.md +2 -0
  73. package/package.json +8 -9
@@ -328,6 +328,10 @@ interface DurableAgentListActiveRunsResult {
328
328
 
329
329
  Discovers runs stuck in `running` status for this agent and re-drives them from the last persisted snapshot. Accepts the same filters and pagination as `listActiveRuns()`, plus `runId`. Returns the outcome for each run.
330
330
 
331
+ Attempts run serially. Each attempt has a single 30-second wait budget covering both `recover()` setup and settlement of the whole recovered workflow. When the budget expires, recovery moves to the next run and returns `status: 'skipped'` with `reason: 'recovery-timeout'` and no `retryAt`. The timeout doesn't cancel setup or execution, release a live claim, or count as success or failure. The attempt continues in the background, and its eventual outcome doesn't change the returned results. Mastra doesn't automatically retry a timed-out attempt.
332
+
333
+ The budget applies only to each run attempt in `recoverActiveRuns()`, not to discovery, a direct `recover()` call, or overridden custom recovery methods. When shutdown begins, recovery stops dispatching new runs. The original attempt remains tracked for Mastra's shared shutdown drain even after the wait times out.
334
+
331
335
  ```typescript
332
336
  const result = await durableAgent.recoverActiveRuns()
333
337
  // {
@@ -348,11 +352,12 @@ await durableAgent.recoverActiveRuns({ runId: 'run-abc-123' })
348
352
 
349
353
  A run that another execution still drives isn't taken over. Its entry has `status: 'skipped'` and a `reason`, and `recoverActiveRuns()` doesn't check it again. For a run held by another process, `retryAt` is the time after which that claim lapses unless renewed. Call `recoverActiveRuns({ runId })` after it to recover the run if its process crashed. [`mastra.recoverAllDurableAgents()`](https://mastra.ai/reference/core/mastra-class) schedules these re-checks itself.
350
354
 
351
- | `reason` | Meaning |
352
- | --------------------- | ------------------------------------------------------------------------------ |
353
- | `run-active` | Another execution, possibly in another process, holds the run. Sets `retryAt`. |
354
- | `run-active-locally` | This process is executing the run. |
355
- | `already-in-progress` | This process is already recovering the run. |
355
+ | `reason` | Meaning |
356
+ | --------------------- | ----------------------------------------------------------------------------------------------------------------- |
357
+ | `run-active` | Another execution, possibly in another process, holds the run. Sets `retryAt`. |
358
+ | `run-active-locally` | This process is executing the run. |
359
+ | `already-in-progress` | This process is already recovering the run. |
360
+ | `recovery-timeout` | The 30-second wait budget expired. The attempt continues in the background, with no `retryAt` or automatic retry. |
356
361
 
357
362
  Returns:
358
363
 
@@ -362,7 +367,7 @@ interface DurableAgentRecoverActiveRunsResult {
362
367
  runId: string
363
368
  status: 'success' | 'failed' | 'skipped'
364
369
  error?: Error
365
- reason?: 'run-active' | 'run-active-locally' | 'already-in-progress'
370
+ reason?: 'run-active' | 'run-active-locally' | 'already-in-progress' | 'recovery-timeout'
366
371
  // Epoch milliseconds
367
372
  retryAt?: number
368
373
  }>
@@ -72,10 +72,12 @@ const result = await classifier.decide({
72
72
  },
73
73
  })
74
74
 
75
- result.answers.route.choice // 'billing' | 'support'
76
- result.answers.urgent.probability // P(true), from 0 to 1
75
+ result.answers.route.choice // 'billing' | 'support' | undefined
76
+ result.answers.urgent.probability // P(true), from 0 to 1, or undefined
77
77
  ```
78
78
 
79
+ A field is `undefined` only when the decision model refused the question. See [refused questions](#refused-questions).
80
+
79
81
  The decision model receives every question with the same `state`. When a question omits `instructions`, its question name is used instead.
80
82
 
81
83
  ## Decision models
@@ -198,6 +200,28 @@ const answer = {
198
200
  }
199
201
  ```
200
202
 
203
+ ### Refused questions
204
+
205
+ A decision model can refuse any question, for example when a safety policy prevents it from answering. A refused question returns a `RefusalAnswer` instead of a choice, score, or boolean answer. The other questions in the same call keep their answers.
206
+
207
+ ```typescript
208
+ const answer = {
209
+ type: 'refusal',
210
+ }
211
+ ```
212
+
213
+ A refusal has no `choice`, `score`, or `probability`. Equality checks such as `answers.route.choice === 'billing'` evaluate to `false`. Check `type` before you read a numeric field, and decide how your application handles the refusal:
214
+
215
+ ```typescript
216
+ const urgent = result.answers.urgent
217
+
218
+ if (urgent.type === 'refusal') {
219
+ // Route to a human, block the input, or apply a default.
220
+ } else if (urgent.probability > 0.8) {
221
+ // Escalate.
222
+ }
223
+ ```
224
+
201
225
  ## Designing questions
202
226
 
203
227
  These rules keep a question answerable from the state:
@@ -205,7 +229,7 @@ These rules keep a question answerable from the state:
205
229
  - Ask for one judgment. A question that moves when either of two fields changes can't be routed on.
206
230
  - Keep criteria exclusive. `strong: 'A good fit'` and `partial: 'Maybe a fit'` leak probability between them.
207
231
  - Give a score enough levels to represent intermediate values.
208
- - Add an escape level when the list isn't closed. Three teams and no `other` forces every input into a team.
232
+ - Add an escape level when the list isn't closed. Without an `other` level, the classifier must assign every input to one of the listed teams.
209
233
  - Put fields in `state`, not in `instructions`. One changed field then moves one answer.
210
234
 
211
235
  To check a question, change one field of the state and confirm one answer moves.
@@ -252,7 +276,7 @@ const result = await classifier.decide({
252
276
  },
253
277
  })
254
278
 
255
- result.answers.tone.choice // 'empathetic' | 'neutral'
279
+ result.answers.tone.choice // 'empathetic' | 'neutral' | undefined
256
280
  ```
257
281
 
258
282
  ## Return value
@@ -300,7 +324,7 @@ Input validation includes:
300
324
  - Every question type must be supported by the decision model.
301
325
  - `maxRetries` must be a non-negative integer.
302
326
 
303
- Provider responses must contain exactly one matching answer for each question. The classifier also rejects invalid choices, out-of-range scores or probabilities, incomplete probability distributions, non-finite token counts, malformed warnings, and invalid response timestamps.
327
+ Provider responses must contain exactly one answer for each question. Each answer must match the question type or be a refusal. The classifier also rejects invalid choices, out-of-range scores or probabilities, incomplete probability distributions, non-finite token counts, malformed warnings, and invalid response timestamps.
304
328
 
305
329
  Only retryable AI SDK `APICallError` failures are retried. Other errors reject immediately. When all retries fail, `decide()` rethrows the last provider error. Aborting the supplied signal rejects with the signal's abort reason, including when cancellation occurs during retry backoff.
306
330
 
@@ -111,6 +111,8 @@ Subscribes to the session's event stream over SSE. The promise resolves once the
111
111
 
112
112
  **reconnect** (`boolean | { maxRetries?: number; delayMs?: number; maxDelayMs?: number }`): Re-establishes the stream after an established stream drops. Retries back off exponentially from delayMs (default 1000) up to maxDelayMs (default 30000). maxRetries (default Infinity) bounds the attempts per outage and resets once a connection is re-established. When retries are exhausted, onError fires. A reconnect request that fails with a 4xx (other than 408 and 429) or 501 stops reconnecting immediately and passes that MastraClientError to onError.
113
113
 
114
+ **idleTimeoutMs** (`number`): Treats the stream as dropped after this many milliseconds without receiving any data. Server heartbeats, sent every 25 seconds, reset the timer, so only a silent connection, such as one left half-open by laptop sleep or a proxy timeout, trips it. A timeout is handled like any other drop: it triggers reconnect and onReconnect when reconnect is enabled, otherwise onError. Also bounds opening the stream: subscribe() rejects, and a reconnect attempt counts as failed, when no response arrives in time. Set to 0 to disable. (Default: `60000`)
115
+
114
116
  Returns: `Promise<AgentControllerSubscription>`, an object with an `unsubscribe()` method that stops reading and releases the stream.
115
117
 
116
118
  ### `sendMessage(message, options?)`
@@ -109,6 +109,121 @@ The additional identity, context and parent/root entity filters require an updat
109
109
 
110
110
  DuckDB returns `null` for parent/root entity type, ID and name, and for `executionSource`. Equality filters on these fields match no spans. Parent/root entity version IDs remain available.
111
111
 
112
+ ## Querying threads
113
+
114
+ `queryTraceThreads()` returns thread summaries from completed traces through `POST /observability/threads/query`. Each row includes activity timestamps, trace counts, context and previews. Traces without a thread ID aren't included.
115
+
116
+ ```typescript
117
+ const result = await mastraClient.queryTraceThreads({
118
+ timeRange: {
119
+ traces: {
120
+ from: '2026-10-01T00:00:00.000Z',
121
+ to: '2026-10-02T00:00:00.000Z',
122
+ },
123
+ },
124
+ where: { op: 'eq', left: { path: 'status' }, right: { literal: 'error' } },
125
+ orderBy: [{ field: 'endedAt', direction: 'desc' }],
126
+ page: { limit: 100 },
127
+ })
128
+
129
+ for (const thread of result.threads) {
130
+ console.log(thread.firstTraceId, thread.lastTraceId, thread.traceCount, thread.outputPreview)
131
+ }
132
+ ```
133
+
134
+ ### Thread time ranges
135
+
136
+ Choose exactly one time selector. Each range requires ISO timestamps with `from` earlier than `to`. The range includes `from` and excludes `to`.
137
+
138
+ | Selector | Matches threads with |
139
+ | ----------------------------------------------------- | --------------------------------------------- |
140
+ | `timeRange.traces: { from, to }` | At least one trace that started in the window |
141
+ | `timeRange.threads: { field: 'startedAt', from, to }` | Their first activity in the window |
142
+ | `timeRange.threads: { field: 'endedAt', from, to }` | Their last activity in the window |
143
+
144
+ For example, find threads whose most recent activity falls on October 1:
145
+
146
+ ```typescript
147
+ const result = await mastraClient.queryTraceThreads({
148
+ timeRange: {
149
+ threads: {
150
+ field: 'endedAt',
151
+ from: '2026-10-01T00:00:00.000Z',
152
+ to: '2026-10-02T00:00:00.000Z',
153
+ },
154
+ },
155
+ })
156
+ ```
157
+
158
+ Rows include the full retained history within the authorized scope, including traces before and after the window. Filters apply to these complete rows. An `environment` filter checks the first trace's environment.
159
+
160
+ ### Thread filters
161
+
162
+ Use `where` to filter thread rows. Combine predicates with `and`, `or` and `not`.
163
+
164
+ | Fields | Operators |
165
+ | -------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------- |
166
+ | `threadId`, `organizationId`, `firstTraceId`, `lastTraceId` | `eq`, `ne`, `in`, `notIn`, `exists`, `notExists` |
167
+ | `resourceId`, `userId`, `runId`, `sessionId`, `requestId`, `serviceName`, `experimentId`, `environment`, `executionSource` | Same string operators |
168
+ | `entityType`, `entityId`, `entityName`, `entityVersionId` | Same string operators |
169
+ | `status` | `eq`, `ne`, `in`, `notIn`, with values `success` or `error` |
170
+ | `startedAt`, `endedAt`, `timeToFirstChunkMs` | `eq`, `ne`, `lt`, `lte`, `gt`, `gte`, `in`, `notIn`, `exists`, `notExists` |
171
+ | `traceCount` | `eq`, `ne`, `lt`, `lte`, `gt`, `gte` |
172
+
173
+ For example, filter for threads from selected agents with at least three traces:
174
+
175
+ ```typescript
176
+ const result = await mastraClient.queryTraceThreads({
177
+ timeRange: {
178
+ traces: {
179
+ from: '2026-10-01T00:00:00.000Z',
180
+ to: '2026-10-02T00:00:00.000Z',
181
+ },
182
+ },
183
+ where: {
184
+ op: 'and',
185
+ args: [
186
+ { op: 'in', value: { path: 'entityId' }, set: ['support-agent', 'sales-agent'] },
187
+ { op: 'gte', left: { path: 'traceCount' }, right: { literal: 3 } },
188
+ ],
189
+ },
190
+ })
191
+ ```
192
+
193
+ Presence filters use `{ op: 'exists', path: 'userId' }` to check for a non-null value. Model/provider and previews are available in returned rows but aren't filterable.
194
+
195
+ ### Thread response
196
+
197
+ The response is `{ threads, page: { next } }`, without a total count. Each entry in `threads` contains these fields:
198
+
199
+ | Returned fields | Meaning |
200
+ | -------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
201
+ | `threadId`, `organizationId` | Thread identity. Equal thread IDs in different organizations remain separate. |
202
+ | `firstTraceId`, `lastTraceId` | Earliest and latest trace by start time. Equal start times use trace ID as a deterministic tie-breaker. |
203
+ | `resourceId`, `userId`, `runId`, `sessionId`, `requestId`, `serviceName`, `experimentId`, `environment`, `executionSource` | First-trace context, or `null` when missing. |
204
+ | `entityType`, `entityId`, `entityName`, `entityVersionId` | First-trace entity. |
205
+ | `startedAt`, `endedAt` | Earliest start and maximum end time across the thread. |
206
+ | `status` | `error` when the last-started trace's root span has an error, otherwise `success`. |
207
+ | `traceCount` | Number of logical traces in the thread. |
208
+ | `inputPreview` | First trace's input preview. |
209
+ | `outputPreview`, `errorPreview` | Last-started trace's previews. |
210
+ | `timeToFirstChunkMs` | First trace's root agent time to first chunk, in milliseconds. `null` when unavailable or the root isn't an agent. |
211
+ | `model`, `provider` | Model/provider from the first completed model generation directly under the first trace's root agent. `null` when unavailable. |
212
+
213
+ An earlier-started trace can finish last. In that case, it supplies `endedAt`, while the last-started trace still supplies status and output/error previews. Missing first-trace values aren't replaced with values from a later trace.
214
+
215
+ ### Thread ordering and pagination
216
+
217
+ Ordering accepts exactly one of `startedAt` or `endedAt`, with direction `asc` or `desc`. The default is `endedAt` descending. Pages default to 100 rows and allow at most 1,000. Pass `result.page.next` as `page.after` with the same time selector, filters, scope and ordering. A `null` cursor means no more pages are available. Pagination reflects live data, so new traces can move a thread between pages.
218
+
219
+ To load the traces within a thread, use [`queryTraces()`](#querying-traces) with a `threadId` filter and a time range covering the thread's activity.
220
+
221
+ ### Thread query support
222
+
223
+ Check `capabilities.threadQueryRows` from `getObservabilityCapabilities()` before using this contract. A missing or false value means full thread rows aren't available. Older core or storage packages return a structured `501` for these requests. Legacy identity requests remain supported for mixed package versions.
224
+
225
+ ClickHouse rejects broad thread queries when the authorized history exceeds 250,000 stored trace-root rows, including duplicate copies. A narrower time range can still succeed by selecting fewer candidate threads. Rejected queries return `503 TRACE_QUERY_RESOURCE_LIMIT` without partial results.
226
+
112
227
  ## Querying traces
113
228
 
114
229
  `queryTraces()` finds completed logical traces using trace fields and conditions over related spans. Every query requires an ISO timestamp range.
@@ -185,6 +300,8 @@ if (capabilities.traceAggregate) {
185
300
  }
186
301
  ```
187
302
 
303
+ `groupBy` accepts the root span's `name` and `spanType` as well as entity and context fields. Every `groupBy` field can also be used in `where` to drill into a group, except `serviceName`, `executionSource`, and `experimentId`, which are groupable only.
304
+
188
305
  Each row has `dimensions` keyed by `groupBy` field, `measures` keyed by measure name, a `bucket` timestamp when `interval` is set, and `cost` coverage when a cost measure is requested. `truncated` is `true` when more groups matched than `limit`.
189
306
 
190
307
  Check `capabilities.traceAggregate` before calling. Unlike `traceQuery`, a missing value means the server doesn't support aggregation. The client retries server errors like `queryTraces()` but doesn't retry `422` validation errors.
@@ -147,6 +147,12 @@ Re-drives every orphaned `running` durable-agent run across all registered durab
147
147
 
148
148
  Requires persistent storage. With an in-memory store, there's nothing to recover after a process restart.
149
149
 
150
+ Agents and their runs are attempted serially. Each built-in `recoverActiveRuns()` attempt waits up to 30 seconds in total for `recover()` setup and settlement of the whole recovered workflow, then traversal can continue to later runs and agents. This isn't an overall recovery deadline: discovery and overridden custom recovery methods aren't bounded by this budget.
151
+
152
+ A timed-out attempt continues in the background. Its outcome is `status: 'skipped'` with `reason: 'recovery-timeout'` and no `retryAt`. It contributes only to `skipped`, not `recovered`, `succeeded`, or `failed`, and Mastra doesn't automatically retry it. Late settlement doesn't change the returned counts.
153
+
154
+ When shutdown begins, recovery stops dispatching new agents and runs. The recovery traversal and original attempts, including timed-out setup or execution, participate in the same shared shutdown drain as active executions. A recovery wait timeout doesn't cancel the attempt or give it a separate shutdown drain window.
155
+
150
156
  A run that another execution still drives isn't taken over. It's counted in `skipped` and checked again once that execution's claim could have lapsed, so a run whose process crashed is recovered without another call. `shutdown()` cancels pending re-checks. See [run ownership](https://mastra.ai/docs/harness/durable-agents).
151
157
 
152
158
  ```typescript
@@ -164,4 +170,4 @@ Returns:
164
170
 
165
171
  **failed** (`number`): Runs whose restart threw an error.
166
172
 
167
- **skipped** (`number`): Runs that another execution still drives. Each is checked again later.
173
+ **skipped** (`number`): Runs skipped because they are already active, recovery is already in progress, or the recovery wait timed out. Only ownership skips eligible for re-checks are checked again; recovery timeouts are not automatically retried.
@@ -183,6 +183,7 @@ The factory also accepts `name` and `description` from `createScorer()`.
183
183
  Failures while the scorer runs reject `scorer.run()` with a `ScorerRunError` whose `failedStep` is `analyze`, and the original error is available as its `cause`. This covers:
184
184
 
185
185
  - Classifier evaluation fails or doesn't return an answer for the selected question.
186
+ - The decision model refuses the selected question. The error names the classifier, the question, and the scorer.
186
187
  - A classifier ID is used before the scorer is registered with Mastra, or the ID isn't present in `classifiers`.
187
188
  - A registered classifier has an invalid configuration for this scorer.
188
189
 
@@ -75,7 +75,7 @@ OM performs thresholding with fast local token estimation. Text uses `tokenx`, a
75
75
 
76
76
  **observation.maxRetries** (`number`): Retries after the initial Observer model call on transient provider errors. Governs OM's own retry ladder; the Observer model call itself is configured with no provider-level retries.
77
77
 
78
- **observation.failurePolicy** (`'abort' | 'continue'`): Terminal policy once Observer retries are exhausted. 'abort' aborts the agent turn. 'continue' emits the existing failure diagnostic, keeps the failed input pending for a later cycle, and allows the main agent turn to continue. Persistence, indexing, transform, locking, invariant, and explicit abort failures remain fatal. This setting doesn't prevent the underlying provider error or change blockAfter or attachment handling, and it has no backstop for a sustained outage: pending messages keep accruing in the main agent's context until they reach the model's context limit.
78
+ **observation.failurePolicy** (`'abort' | 'continue'`): Terminal policy once Observer retries are exhausted in a synchronous observation. Background buffered observation failures are reported as om\_buffering\_failed and never stop the turn. 'abort' aborts the agent turn. 'continue' emits the existing failure diagnostic, keeps the failed input pending for a later cycle, and allows the main agent turn to continue. Persistence, indexing, transform, locking, invariant, and explicit abort failures remain fatal. This setting doesn't prevent the underlying provider error or change blockAfter or attachment handling, and it has no backstop for a sustained outage: pending messages keep accruing in the main agent's context until they reach the model's context limit.
79
79
 
80
80
  **observation.messageTokens** (`number`): Token count of unobserved messages that triggers observation. When unobserved message tokens exceed this threshold, the Observer agent is called. Text is estimated locally with tokenx. Image parts are included with model-aware heuristics when possible, with deterministic fallbacks when image metadata is incomplete. Image-like file parts are counted the same way when uploads are normalized as files.
81
81
 
@@ -111,7 +111,7 @@ OM performs thresholding with fast local token estimation. Text uses `tokenx`, a
111
111
 
112
112
  **reflection.maxRetries** (`number`): Retries after the initial Reflector model call on transient provider errors. Governs OM's own retry ladder; the Reflector model call itself is configured with no provider-level retries.
113
113
 
114
- **reflection.failurePolicy** (`'abort' | 'continue'`): Terminal policy once Reflector retries are exhausted. 'abort' aborts the agent turn. 'continue' emits the failure diagnostic and allows the turn to continue, leaving already-persisted observations committed and deferring reflection to the next threshold crossing. A provider outage usually takes out both stages, so set the policy on observation too if the turn should survive one.
114
+ **reflection.failurePolicy** (`'abort' | 'continue'`): Terminal policy once Reflector retries are exhausted in a synchronous reflection. Background buffered reflection failures are reported as om\_buffering\_failed and never stop the turn. 'abort' aborts the agent turn. 'continue' emits the failure diagnostic and allows the turn to continue, leaving already-persisted observations committed and deferring reflection to the next threshold crossing. A provider outage usually takes out both stages, so set the policy on observation too if the turn should survive one.
115
115
 
116
116
  **reflection.instruction** (`string`): Custom instruction appended to the Reflector's system prompt. Use this to customize how the Reflector consolidates observations, such as prioritizing certain types of information.
117
117
 
@@ -157,18 +157,20 @@ Hono and Fastify enforce the request-body limit before JSON parsing. Express and
157
157
 
158
158
  | Predicate context | Fields | Operators |
159
159
  | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------- |
160
- | Trace | `traceId`, `threadId`, `resourceId`, `runId`, `sessionId`, `userId`, `organizationId`, `entityName`, `entityType`, `environment`, `status` | `eq`, `ne`, `in`, `notIn`, `exists`, `notExists` |
160
+ | Trace | `traceId`, `threadId`, `resourceId`, `runId`, `sessionId`, `userId`, `organizationId`, `entityName`, `entityType`, `name`, `spanType`, `environment`, `status` | `eq`, `ne`, `in`, `notIn`, `exists`, `notExists` |
161
161
  | Trace metadata | `metadata.<key>` | `eq`, `ne`, `in`, `notIn`, `exists`, `notExists` |
162
- | Trace | `startedAt`, `endedAt`, `durationMs` | `eq`, `ne`, `in`, `notIn`, `lt`, `lte`, `gt`, `gte`, `exists`, `notExists` |
162
+ | Trace | `startedAt`, `endedAt`, `durationMs`, `timeToFirstChunkMs` | `eq`, `ne`, `in`, `notIn`, `lt`, `lte`, `gt`, `gte`, `exists`, `notExists` |
163
163
  | Trace | `tags` | `includes`, `notIncludes`, `exists`, `notExists` |
164
164
  | Span | `name` | `eq`, `ne`, `in`, `notIn`, `exists`, `notExists`, `matches`, `notMatches` |
165
165
  | Span | `spanType`, `model`, `provider`, `status`, `entityType`, `entityId`, `entityName`, `entityVersionId`, `parentEntityVersionId`, `rootEntityVersionId`, `runId`, `sessionId`, `userId`, `organizationId` | `eq`, `ne`, `in`, `notIn`, `exists`, `notExists` |
166
- | Span | `startedAt`, `endedAt`, `durationMs` | `eq`, `ne`, `in`, `notIn`, `lt`, `lte`, `gt`, `gte`, `exists`, `notExists` |
166
+ | Span | `startedAt`, `endedAt`, `durationMs`, `timeToFirstChunkMs` | `eq`, `ne`, `in`, `notIn`, `lt`, `lte`, `gt`, `gte`, `exists`, `notExists` |
167
167
  | Span | `error` | `exists`, `notExists` |
168
168
 
169
+ Trace-scope `name` and `spanType` read the current root span, so `{ op: 'eq', left: { path: 'spanType' }, right: { literal: 'workflow_run' } }` selects traces started by a workflow run. Inside `spans.some` or `spans.none`, the same fields match any span in the trace.
170
+
169
171
  Compose predicates with `{ op: 'and', args: [...] }`, `{ op: 'or', args: [...] }`, and `{ op: 'not', arg: ... }`. Comparison predicates place a field reference on the left and a literal on the right. Membership predicates use a field reference in `value` and a homogeneous literal array in `set`. Tag predicates name the stored tag collection in `path`. `includes` and `notIncludes` also take one tag in `value`, while `exists` and `notExists` take only `op` and `path`. See [Filter by tags](#filter-by-tags). Text predicates use the comparison shape with a string literal. See [Filter by text](#filter-by-text).
170
172
 
171
- String comparisons are case-sensitive, and literals are never coerced. `matches` and `notMatches` are the exception: they compare words case-insensitively. Canonical string fields compare exact stored values. Metadata string values are trimmed before comparison, as described below. Duration predicates require numbers, while timestamp predicates require ISO timestamp strings. A missing value satisfies neither positive nor ordered predicates, although it does satisfy the negative operators `ne` and `notIn`. Combine a negative predicate with `exists` when the field must also be present.
173
+ String comparisons are case-sensitive, and literals are never coerced. `matches` and `notMatches` are the exception: they compare words case-insensitively. Canonical string fields compare exact stored values. Metadata string values are trimmed before comparison, as described below. Duration and time-to-first-chunk predicates require numbers, while timestamp predicates require ISO timestamp strings. A missing value satisfies neither positive nor ordered predicates, although it does satisfy the negative operators `ne` and `notIn`. Combine a negative predicate with `exists` when the field must also be present.
172
174
 
173
175
  ### Filter by root duration
174
176
 
@@ -186,6 +188,30 @@ This top-level predicate doesn't inspect child spans. In contrast, `spans.some`
186
188
 
187
189
  Trace queries exclude incomplete roots before evaluating predicates. As a result, `{ op: 'notExists', path: 'durationMs' }` doesn't find running traces or malformed roots without a usable `endedAt`.
188
190
 
191
+ ### Filter by time to first chunk
192
+
193
+ `timeToFirstChunkMs` is the time in milliseconds from a span's start to the first chunk of its model response. Agent run and model spans record it when the model streams a response. At trace scope, the field reads the current root span's value. Inside `spans.some` or `spans.none`, it reads each related span.
194
+
195
+ This predicate finds traces with a model call that took more than 2 seconds to stream its first chunk:
196
+
197
+ ```typescript
198
+ const slowFirstChunk = {
199
+ spans: {
200
+ some: {
201
+ op: 'and',
202
+ args: [
203
+ { op: 'eq', left: { path: 'spanType' }, right: { literal: 'model_generation' } },
204
+ { op: 'gt', left: { path: 'timeToFirstChunkMs' }, right: { literal: 2000 } },
205
+ ],
206
+ },
207
+ },
208
+ }
209
+ ```
210
+
211
+ The value is `null` when the span didn't stream a chunk, for example a tool call or a workflow run. A `null` value counts as missing, so it matches `notExists` and never matches ordered predicates. A value of `0` isn't missing. It means the first chunk arrived in the same millisecond the span started.
212
+
213
+ Trace query results include the root span's `timeToFirstChunkMs`, and `querySpans()` results include each span's value. Sorting by this field isn't supported. Stores advertise support through the `trace-query-time-to-first-chunk` feature, and the server reports it as the `traceQueryTimeToFirstChunk` capability. Against an older store, results omit the field, a predicate on it returns `501` before storage runs, and field discovery omits it.
214
+
189
215
  ### Filter by context identifiers
190
216
 
191
217
  `runId`, `sessionId`, `userId`, and `organizationId` are available at trace scope and inside `spans.some` / `spans.none`. Trace-scope predicates read the current root span. Span-scope predicates bind to one related current span, so a run recorded only on a child span is found through `spans.some`:
@@ -382,13 +408,16 @@ A query using keyset pagination returns lightweight completed traces and a curso
382
408
  "entityName": "support-agent",
383
409
  "entityType": "agent",
384
410
  "environment": "production",
385
- "status": "success"
411
+ "status": "success",
412
+ "timeToFirstChunkMs": 412
386
413
  }
387
414
  ],
388
415
  "page": { "next": null }
389
416
  }
390
417
  ```
391
418
 
419
+ `timeToFirstChunkMs` is present only when the configured store supports it. See [Filter by time to first chunk](#filter-by-time-to-first-chunk).
420
+
392
421
  The response doesn't include the related spans that matched the predicate. Use [`getTrace()`](https://mastra.ai/reference/client-js/observability) to load the full trace after selecting a result.
393
422
 
394
423
  ### CLI responses
@@ -591,12 +620,12 @@ Discovery returns string values only. Missing values, empty strings, and strings
591
620
 
592
621
  Value suggestions are available for these canonical fields:
593
622
 
594
- | Scope | Fields |
595
- | ----- | ----------------------------------------------------------------------------- |
596
- | Trace | `entityName`, `entityType`, `environment`, `status`, `tags` |
597
- | Spans | `name`, `spanType`, `model`, `provider`, `status`, `entityType`, `entityName` |
623
+ | Scope | Fields |
624
+ | ----- | ------------------------------------------------------------------------------- |
625
+ | Trace | `entityName`, `entityType`, `name`, `spanType`, `environment`, `status`, `tags` |
626
+ | Spans | `name`, `spanType`, `model`, `provider`, `status`, `entityType`, `entityName` |
598
627
 
599
- Each executable top-level string `metadata.<key>` field also supports value suggestions in the `trace` scope. Identifiers, timestamps, durations, errors, and version IDs don't. The fields response still includes canonical fields with `valueSuggestions: false`. The values endpoint rejects those paths with `422 TRACE_QUERY_INVALID`.
628
+ Each executable top-level string `metadata.<key>` field also supports value suggestions in the `trace` scope. Identifiers, timestamps, durations, time to first chunk, errors, and version IDs don't. The fields response still includes canonical fields with `valueSuggestions: false`. The values endpoint rejects those paths with `422 TRACE_QUERY_INVALID`.
600
629
 
601
630
  Both discovery requests require a half-open time range. They use the same current-record semantics as `queryTraces()`: qualifying completed roots satisfy `from <= startedAt < to`, and related values come only from current records joined to those roots by `traceId`. Discovery doesn't accept or apply a draft `where` predicate.
602
631
 
@@ -29,12 +29,14 @@ const safety = new Classifier({
29
29
  const processor = new ClassifierProcessor({
30
30
  classifier: safety,
31
31
  onResult: (answers, { abort }) => {
32
- if (answers.unsafe.probability > 0.8) abort('Message rejected by safety policy')
32
+ if ((answers.unsafe.probability ?? 1) > 0.8) abort('Message rejected by safety policy')
33
33
  },
34
34
  lastMessageOnly: true,
35
35
  })
36
36
  ```
37
37
 
38
+ A decision model can refuse a question. A refused answer is `{ type: 'refusal' }` and has no `choice`, `score`, or `probability`. The example treats a refusal as unsafe.
39
+
38
40
  Several conditions can share one `onResult`, or use separate processors when they need different classifiers. Give each processor a unique `id`. Processor instances with the same `id` share per-run state, including accumulated stream chunks.
39
41
 
40
42
  ```typescript
@@ -43,14 +45,14 @@ inputProcessors: [
43
45
  id: 'safety-check',
44
46
  classifier: safety,
45
47
  onResult: (a, { abort }) => {
46
- if (a.unsafe.probability > 0.8) abort('Rejected by safety policy')
48
+ if ((a.unsafe.probability ?? 1) > 0.8) abort('Rejected by safety policy')
47
49
  },
48
50
  }),
49
51
  new ClassifierProcessor({
50
52
  id: 'topic-check',
51
53
  classifier: topic,
52
54
  onResult: (a, { abort }) => {
53
- if (a.topic.choice === 'other') abort('Support questions only')
55
+ if (a.topic.type === 'refusal' || a.topic.choice === 'other') abort('Support questions only')
54
56
  },
55
57
  }),
56
58
  ]
@@ -121,7 +123,7 @@ export const agent = new Agent({
121
123
  classifier: topic,
122
124
  lastMessageOnly: true,
123
125
  onResult: (answers, { abort }) => {
124
- if (answers.topic.choice === 'other') {
126
+ if (answers.topic.type === 'refusal' || answers.topic.choice === 'other') {
125
127
  abort('This assistant only handles billing and account questions')
126
128
  }
127
129
  },
@@ -159,7 +161,7 @@ export const agent = new Agent({
159
161
  new ClassifierProcessor({
160
162
  classifier: quality,
161
163
  onResult: (answers, { filter }) => {
162
- if (answers.quality.score < 1) filter()
164
+ if ((answers.quality.score ?? 0) < 1) filter()
163
165
  },
164
166
  }),
165
167
  ],
@@ -196,7 +198,7 @@ type SafetyQuestions = {
196
198
  const processor = new ClassifierProcessor<SafetyQuestions>({
197
199
  classifier: 'safety',
198
200
  onResult: (answers, { abort }) => {
199
- if (answers.unsafe.probability > 0.8) abort('Message rejected by safety policy')
201
+ if ((answers.unsafe.probability ?? 1) > 0.8) abort('Message rejected by safety policy')
200
202
  },
201
203
  })
202
204
  ```
@@ -104,7 +104,7 @@ The decision carries the model that was applied, the criterion that was chosen,
104
104
 
105
105
  **probability** (`number`): Confidence in the selected choice, taken from the answer distribution. Absent when the decision model returns no distribution.
106
106
 
107
- **abstained** (`'below-threshold' | 'no-model-for-choice' | 'no-text' | 'error'`): Why no model was applied. Absent on a successful routing decision and when select returns undefined.
107
+ **abstained** (`'below-threshold' | 'no-model-for-choice' | 'no-text' | 'error' | 'refused'`): Why no model was applied. Absent on a successful routing decision and when select returns undefined.
108
108
 
109
109
  ## Existing classifiers
110
110
 
@@ -200,7 +200,7 @@ If your decision model doesn't report choice distributions, the processor abstai
200
200
 
201
201
  ## Failure behavior
202
202
 
203
- Routing fails open. If the classifier errors or the classifier ID isn't registered, the processor logs a warning and the agent's configured model is used. If the request has no user text to classify, the processor abstains without logging and reports `abstained: 'no-text'` to `onDecision`. This is the safe direction for a cost optimization: the worst case is that you pay for the model you already configured.
203
+ Routing fails open. If the classifier errors or the classifier ID isn't registered, the processor logs a warning and the agent's configured model is used. If the request has no user text to classify, the processor abstains without logging and reports `abstained: 'no-text'` to `onDecision`. With the `choices` form, if the decision model refuses the routing question, the processor abstains and reports `abstained: 'refused'`. With the `select` form, your callback receives the refusal answer and decides whether to return a model or `undefined`. This is the safe direction for a cost optimization: the worst case is that you pay for the model you already configured.
204
204
 
205
205
  This is the opposite of the fail-closed stance appropriate for [tool approval](https://mastra.ai/docs/agents/human-in-the-loop), where uncertainty should escalate rather than pass through.
206
206
 
@@ -40,7 +40,9 @@ const processor = new ModerationProcessor({
40
40
 
41
41
  **options.lastMessageOnly** (`boolean`): Whether to run moderation only on the most recent message in the batch instead of checking every message. Use this to avoid an extra LLM call for each earlier message in long conversations.
42
42
 
43
- **options.chunkWindow** (`number`): Number of previous chunks to include for context when moderating stream chunks. If set to 1, includes the previous part, etc.
43
+ **options.chunkWindow** (`number`): Number of previous chunks to include for context when moderating stream chunks. If set to 1, includes the previous part, etc. Only applies when bufferSize is 0.
44
+
45
+ **options.bufferSize** (`number`): Opt-in buffering for streamed text. When greater than 0, streamed text is held back and moderated in one LLM call when it ends a sentence, reaches this many characters, or a non-text part arrives. This makes far fewer LLM calls and catches content split across chunks. Recommended for production streaming, for example bufferSize: 200. With 0, every text chunk gets its own LLM call.
44
46
 
45
47
  **options.providerOptions** (`ProviderOptions`): Provider-specific options passed to the internal moderation agent. Use this to control model behavior like reasoning effort for thinking models (e.g., { openai: { reasoningEffort: 'low' } })
46
48
 
@@ -82,6 +84,8 @@ export const agent = new Agent({
82
84
 
83
85
  ### Output processing with batching
84
86
 
87
+ For production streaming, set `bufferSize` (for example `bufferSize: 200`) so `ModerationProcessor` makes one moderation call per sentence instead of one per chunk. Buffering also catches content that is split across chunks. Text then reaches the client in sentence-sized pieces.
88
+
85
89
  When using `ModerationProcessor` as an output processor, it's recommended to combine it with `BatchPartsProcessor` to optimize performance. The `BatchPartsProcessor` batches stream chunks together before passing them to the moderator, reducing the number of LLM calls required for moderation.
86
90
 
87
91
  ```typescript
@@ -42,6 +42,8 @@ const processor = new SystemPromptScrubber({
42
42
 
43
43
  **options.placeholderText** (`string`): Custom placeholder text for redaction when redactionMethod is 'placeholder'
44
44
 
45
+ **options.bufferSize** (`number`): Opt-in buffering for streamed text. When greater than 0, streamed text is held back and checked in one LLM call when it ends a sentence, reaches this many characters, or a non-text part arrives. This makes far fewer LLM calls and catches content split across chunks. Recommended for production streaming, for example bufferSize: 200. With 0, every text chunk gets its own LLM call.
46
+
45
47
  ## Returns
46
48
 
47
49
  **id** (`string`): Processor identifier set to 'system-prompt-scrubber'
@@ -54,6 +56,8 @@ const processor = new SystemPromptScrubber({
54
56
 
55
57
  ## Extended usage example
56
58
 
59
+ For production streaming, set `bufferSize` (for example `bufferSize: 200`) so `SystemPromptScrubber` makes one detection call per sentence instead of one per chunk. Buffering also catches content that is split across chunks. Text then reaches the client in sentence-sized pieces.
60
+
57
61
  When using `SystemPromptScrubber` as an output processor, it's recommended to combine it with `BatchPartsProcessor` to optimize performance. The `BatchPartsProcessor` batches stream chunks together before passing them to the scrubber, reducing the number of LLM calls required for detection.
58
62
 
59
63
  ```typescript
@@ -47,7 +47,7 @@ The generated tool has the id `notification-inbox` and accepts these input field
47
47
 
48
48
  **id** (`string`): Notification ID. Required for markSeen, dismiss, and archive. Optional for read.
49
49
 
50
- **status** (`'pending' | 'delivered' | 'seen' | 'dismissed' | 'archived' | 'discarded'`): Status filter for list, read, or search actions.
50
+ **status** (`'pending' | 'delivered' | 'seen' | 'dismissed' | 'archived' | 'discarded' | 'failed'`): Status filter for list, read, or search actions.
51
51
 
52
52
  **priority** (`'low' | 'medium' | 'high' | 'urgent'`): Priority filter for list, read, or search actions.
53
53
 
@@ -59,13 +59,15 @@ The generated tool has the id `notification-inbox` and accepts these input field
59
59
 
60
60
  ## Actions
61
61
 
62
- | Action | Description |
63
- | ---------- | --------------------------------------------------------------------------------------- |
64
- | `list` | Returns matching notifications. |
65
- | `read` | Delivers readable notification contents as signals and marks delivered records as seen. |
66
- | `markSeen` | Marks one notification as seen. |
67
- | `dismiss` | Marks one notification as dismissed. |
68
- | `archive` | Marks one notification as archived. |
69
- | `search` | Searches notifications by query and optional filters. |
62
+ | Action | Description |
63
+ | ---------- | --------------------------------------------------------------------------------------------------------------------------- |
64
+ | `list` | Returns matching notifications. Without `status`, returns pending, delivered, and failed notifications and marks them seen. |
65
+ | `read` | Delivers readable notification contents as signals and marks delivered records as seen. |
66
+ | `markSeen` | Marks one notification as seen. |
67
+ | `dismiss` | Marks one notification as dismissed. |
68
+ | `archive` | Marks one notification as archived. |
69
+ | `search` | Searches notifications by query and optional filters. |
70
+
71
+ A notification is `failed` when Mastra ran out of delivery attempts for it. The default `list` includes failed notifications. Any `list` or `search` that returns a failed notification shows it with `status: 'failed'` and its `lastDeliveryError`, then marks it seen, so later lists don't repeat it. Filtering by `status: 'failed'` finds the notification only until it's first returned; after that it's `seen`, and `deliveryAttempts` and `lastDeliveryError` stay on the record.
70
72
 
71
73
  When `read` finds pending or delivered notifications, the tool delivers their contents as notification signals instead of returning the full contents as normal tool output. Use this after a `<notification-summary>` signal when the agent needs the full records behind the summary.
@@ -59,9 +59,9 @@ The first `execute` parameter is the validated value from `inputSchema`. Destruc
59
59
 
60
60
  **resumeSchema** (`StandardJSONSchemaV1`): A Standard JSON Schema defining the expected structure of resumeData when the tool is resumed. Used by the agent to extract data from user messages when autoResumeSuspendedTools is enabled.
61
61
 
62
- **requireApproval** (`boolean`): When true, the tool requires explicit approval before execution. The agent will emit a tool-call-approval chunk and pause until approved or declined.
62
+ **requireApproval** (`boolean`): When true, the tool requires explicit approval before execution. The agent will emit a tool-call-approval chunk and pause until approved or declined. Input is validated against inputSchema first: if it is invalid, the validation error is returned to the model and no approval is requested.
63
63
 
64
- **beforeApproval** (`(input, context) => void | { proceed: false; output: unknown } | Promise<...>`): Runs before the approval gate for calls that require approval, receiving the input validated against inputSchema (defaults applied) and a context with toolCallId, toolName, requestContext, and workspace. Return { proceed: false, output } to reject the call: the agent does not pause for approval, execute is not called, and output is returned to the model as the tool result. Return nothing to continue to the approval gate. Not run when the input fails inputSchema validation (execute reports the validation error after approval) or when resuming after an approval decision. If the hook throws, the error is logged and the call proceeds to the approval gate, so keep validating inside execute as well.
64
+ **beforeApproval** (`(input, context) => void | { proceed: false; output: unknown } | Promise<...>`): Runs before the approval gate for calls that require approval, receiving the input validated against inputSchema (defaults applied) and a context with toolCallId, toolName, requestContext, and workspace. Return { proceed: false, output } to reject the call: the agent does not pause for approval, execute is not called, and output is returned to the model as the tool result. Return nothing to continue to the approval gate. Not run when the input fails inputSchema validation (the validation error is returned to the model without asking for approval) or when resuming after an approval decision. If the hook throws, the error is logged and the call proceeds to the approval gate, so keep validating inside execute as well.
65
65
 
66
66
  **mcp** (`MCPToolProperties`): MCP-specific properties for tools exposed via Model Context Protocol. Includes annotations (tool behavior hints like title, readOnlyHint, destructiveHint, idempotentHint, openWorldHint) and \_meta (arbitrary metadata passed through to MCP clients).
67
67
 
@@ -38,7 +38,7 @@ Each server in the `servers` map is configured using the `MastraMCPServerDefinit
38
38
  - If `command` is provided, it uses the Stdio transport.
39
39
  - If `url` is provided, it uses the Streamable HTTP transport.
40
40
 
41
- The client speaks the MCP `2026-07-28` revision. On connect it asks the server which revisions it offers (`server/discover`) and falls back to the pre-2026 `initialize` handshake for servers that haven't upgraded, so tools, resources and prompts keep working against either. Features the older revisions lack (`resources.subscribe()`, `inputRequests`) fail with an error naming the negotiated revision. Set `protocolVersion` to skip the probe.
41
+ The client speaks the MCP `2026-07-28` revision. On connect it asks the server which revisions it offers (`server/discover`) and falls back to the pre-2026 `initialize` handshake for servers that haven't upgraded, so tools, resources and prompts keep working against either. Features the older revisions lack (`resources.subscribe()`, `inputRequests`) fail with an error naming the negotiated revision. `onListChanged()` handlers work against either revision, since older servers send list-changed notifications without a `subscriptions/listen` stream. Set `protocolVersion` to skip the probe.
42
42
 
43
43
  **command** (`string`): For Stdio servers: The command to execute.
44
44
 
@@ -84,7 +84,7 @@ The client speaks the MCP `2026-07-28` revision. On connect it asks the server w
84
84
 
85
85
  **requireToolApproval** (`boolean | (params: RequireToolApprovalContext) => boolean | Promise<boolean>`): Require human approval before executing tools from this server. When set to true, all tools require approval. When set to a function, the function is called with the tool name, arguments, request context, and any tool annotations advertised by the server to dynamically decide whether approval is needed.
86
86
 
87
- **onToolError** (`'throw' | 'return'`): How to handle tool execution failures the server reports in-band with isError: true. 'throw' raises a MastraError carrying the server's error text, so the failure reaches tool spans, stream chunks, scorers, and the model. 'return' resolves with the raw result and ignores isError. (Default: `'throw'`)
87
+ **onToolError** (`'throw' | 'return'`): How to handle tool execution failures the server reports in-band with isError: true. 'throw' raises a MastraError carrying the server's error text, so the failure reaches tool spans, stream chunks, scorers, and the model. Any structuredContent is kept on error.details.structuredContent as a JSON string. 'return' resolves with the full CallToolResult (isError, content, and structuredContent) instead of throwing. (Default: `'throw'`)
88
88
 
89
89
  **jsonSchemaValidator** (`JsonSchemaValidator`): Validator used for MCP tool schemas and structured results. The default supports JSON Schema 2020-12. Provide a compatible validator such as CfWorkerJsonSchemaValidator in runtimes that disallow dynamic code generation.
90
90
 
@@ -164,7 +164,7 @@ The classifier evaluates the complete entry input. Add a preceding `mapping` ent
164
164
 
165
165
  Classifier output has two stable paths:
166
166
 
167
- - `answers.<question>` contains the typed answer. Route on its `choice`, `score`, or `probability` field according to the question type. Choice and score answers may include distributions.
167
+ - `answers.<question>` contains the typed answer. Route on its `choice`, `score`, or `probability` field according to the question type. Choice and score answers may include distributions. A refused question is `{ "type": "refusal" }` with no `choice`, `score`, or `probability`, so it matches no condition on those fields. Compare `answers.<question>.type` with `"refusal"` to route refusals explicitly.
168
168
  - `usage` contains normalized token usage.
169
169
 
170
170
  Use an existing `conditional` entry to route on classifier output. For example, a following condition can compare `{ "path": "stepResults.classify-ticket.answers.route.choice" }` with `{ "literal": "billing" }`.