@mastra/mcp-docs-server 1.3.9-alpha.9 → 1.3.9

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 (153) hide show
  1. package/.docs/docs/agents/guardrails.md +3 -0
  2. package/.docs/docs/agents/overview.md +1 -0
  3. package/.docs/docs/agents/processors.md +9 -4
  4. package/.docs/docs/auth/composite-auth.md +4 -2
  5. package/.docs/docs/auth/custom-auth-provider.md +1 -1
  6. package/.docs/docs/auth/overview.md +3 -1
  7. package/.docs/docs/connections/sdk-agents.md +18 -7
  8. package/.docs/docs/evals/experiments.md +27 -2
  9. package/.docs/docs/guides/mcp-authentication-authorization.md +2 -2
  10. package/.docs/docs/guides/mcp-events.md +306 -0
  11. package/.docs/docs/harness/agent-controller.md +11 -14
  12. package/.docs/docs/harness/background-tasks.md +11 -0
  13. package/.docs/docs/harness/durable-agents.md +10 -4
  14. package/.docs/docs/harness/schedules.md +8 -6
  15. package/.docs/docs/index.md +1 -0
  16. package/.docs/docs/mastra-platform/connect/end-user-connections.md +116 -0
  17. package/.docs/docs/mastra-platform/environments.md +1 -1
  18. package/.docs/docs/mastra-platform/server.md +1 -1
  19. package/.docs/docs/mastra-platform/studio.md +1 -1
  20. package/.docs/docs/memory/memory-processors.md +14 -8
  21. package/.docs/docs/memory/semantic-recall.md +20 -0
  22. package/.docs/docs/memory/working-memory.md +1 -1
  23. package/.docs/docs/sandbox/filesystem.md +25 -11
  24. package/.docs/docs/server/overview.md +27 -0
  25. package/.docs/docs/studio/auth.md +2 -2
  26. package/.docs/docs/studio/observability.md +5 -1
  27. package/.docs/docs/workflows/control-flow.md +14 -14
  28. package/.docs/docs/workflows/error-handling.md +1 -1
  29. package/.docs/integrations/deploy/aws-bedrock-agentcore.md +1 -0
  30. package/.docs/integrations/sandboxes/e2b.md +2 -0
  31. package/.docs/models/embeddings.md +2 -1
  32. package/.docs/models/environment-variables.md +1 -1
  33. package/.docs/models/gateways/merge-gateway.md +7 -1
  34. package/.docs/models/gateways/vercel.md +6 -2
  35. package/.docs/models/index.md +2 -2
  36. package/.docs/models/providers/aixy.md +3 -1
  37. package/.docs/models/providers/alibaba-cn.md +7 -55
  38. package/.docs/models/providers/alibaba-coding-plan-cn.md +8 -12
  39. package/.docs/models/providers/alibaba-coding-plan.md +8 -12
  40. package/.docs/models/providers/alibaba-token-plan-cn.md +0 -2
  41. package/.docs/models/providers/alibaba-token-plan.md +29 -30
  42. package/.docs/models/providers/alibaba.md +32 -61
  43. package/.docs/models/providers/ambient.md +0 -8
  44. package/.docs/models/providers/amd.md +13 -9
  45. package/.docs/models/providers/anthropic.md +4 -2
  46. package/.docs/models/providers/arcee.md +6 -4
  47. package/.docs/models/providers/baseten.md +0 -10
  48. package/.docs/models/providers/cloudflare-workers-ai.md +1 -1
  49. package/.docs/models/providers/crossmodel.md +70 -72
  50. package/.docs/models/providers/databricks.md +5 -10
  51. package/.docs/models/providers/digitalocean.md +2 -14
  52. package/.docs/models/providers/edenai.md +18 -4
  53. package/.docs/models/providers/empiriolabs.md +1 -7
  54. package/.docs/models/providers/fireworks-ai.md +22 -26
  55. package/.docs/models/providers/google.md +4 -1
  56. package/.docs/models/providers/groq.md +2 -7
  57. package/.docs/models/providers/huggingface.md +2 -5
  58. package/.docs/models/providers/inception.md +3 -2
  59. package/.docs/models/providers/iteracompute.md +2 -2
  60. package/.docs/models/providers/jalapeno.md +1 -1
  61. package/.docs/models/providers/kenari.md +1 -1
  62. package/.docs/models/providers/kilo.md +15 -30
  63. package/.docs/models/providers/liquid.md +77 -0
  64. package/.docs/models/providers/llmgateway-providers.md +3 -12
  65. package/.docs/models/providers/llmgateway.md +5 -15
  66. package/.docs/models/providers/longcat.md +6 -5
  67. package/.docs/models/providers/melious.md +16 -15
  68. package/.docs/models/providers/minimax-cn-coding-plan.md +4 -11
  69. package/.docs/models/providers/minimax-cn.md +4 -10
  70. package/.docs/models/providers/minimax-coding-plan.md +4 -11
  71. package/.docs/models/providers/minimax.md +4 -10
  72. package/.docs/models/providers/mistral.md +4 -4
  73. package/.docs/models/providers/modal.md +11 -7
  74. package/.docs/models/providers/moonshotai-cn.md +2 -2
  75. package/.docs/models/providers/nano-gpt.md +17 -26
  76. package/.docs/models/providers/nearai.md +1 -1
  77. package/.docs/models/providers/ofox.md +148 -156
  78. package/.docs/models/providers/ollama-cloud.md +6 -11
  79. package/.docs/models/providers/openai.md +4 -2
  80. package/.docs/models/providers/opencode.md +2 -1
  81. package/.docs/models/providers/perplexity-agent.md +53 -29
  82. package/.docs/models/providers/perplexity.md +2 -8
  83. package/.docs/models/providers/pioneer.md +8 -113
  84. package/.docs/models/providers/requesty.md +0 -4
  85. package/.docs/models/providers/runinfra.md +2 -1
  86. package/.docs/models/providers/scaleway.md +1 -3
  87. package/.docs/models/providers/snowflake-cortex.md +22 -22
  88. package/.docs/models/providers/stepfun-ai.md +1 -3
  89. package/.docs/models/providers/stepfun.md +4 -6
  90. package/.docs/models/providers/synthetic.md +2 -1
  91. package/.docs/models/providers/thinkingmachines.md +45 -9
  92. package/.docs/models/providers/togetherai.md +17 -23
  93. package/.docs/models/providers/wandb.md +1 -1
  94. package/.docs/models/providers/xai.md +3 -2
  95. package/.docs/models/providers/xiaomi-token-plan-ams.md +0 -1
  96. package/.docs/models/providers/xiaomi-token-plan-cn.md +0 -1
  97. package/.docs/models/providers/xiaomi-token-plan-sgp.md +0 -1
  98. package/.docs/models/providers/zai-coding-plan.md +0 -4
  99. package/.docs/models/providers/zhipuai-coding-plan.md +0 -1
  100. package/.docs/models/providers/zhipuai.md +12 -12
  101. package/.docs/models/providers.md +1 -1
  102. package/.docs/reference/agent-controller/agent-controller-class.md +17 -22
  103. package/.docs/reference/agent-controller/session.md +3 -3
  104. package/.docs/reference/agents/channels.md +7 -1
  105. package/.docs/reference/agents/durable-agent.md +12 -8
  106. package/.docs/reference/agents/getSkill.md +1 -1
  107. package/.docs/reference/agents/listSkills.md +1 -4
  108. package/.docs/reference/browser/mastra-browser.md +1 -1
  109. package/.docs/reference/client-js/agent-controller.md +13 -3
  110. package/.docs/reference/client-js/agents.md +20 -0
  111. package/.docs/reference/client-js/mastra-client.md +1 -1
  112. package/.docs/reference/client-js/observability.md +3 -3
  113. package/.docs/reference/configuration.md +30 -0
  114. package/.docs/reference/connect/credential.md +1 -1
  115. package/.docs/reference/connect/tools.md +3 -1
  116. package/.docs/reference/connect/user-connect-routes.md +68 -0
  117. package/.docs/reference/core/mastra-class.md +2 -2
  118. package/.docs/reference/core/mastra-model-gateway.md +33 -4
  119. package/.docs/reference/datasets/delete.md +6 -0
  120. package/.docs/reference/editor/mastra-editor.md +9 -7
  121. package/.docs/reference/editor/tool-provider.md +2 -2
  122. package/.docs/reference/evals/create-classifier-scorer.md +6 -2
  123. package/.docs/reference/file-based-agents/instructions.md +1 -1
  124. package/.docs/reference/file-based-agents/processors.md +2 -0
  125. package/.docs/reference/file-based-agents/schedules.md +1 -1
  126. package/.docs/reference/file-based-agents/skills.md +1 -1
  127. package/.docs/reference/file-based-agents/subagents.md +1 -1
  128. package/.docs/reference/index.md +1 -0
  129. package/.docs/reference/manual-install.md +1 -0
  130. package/.docs/reference/memory/cloneThread.md +1 -1
  131. package/.docs/reference/memory/copyThread.md +1 -1
  132. package/.docs/reference/memory/deleteMessages.md +4 -1
  133. package/.docs/reference/memory/memory-class.md +2 -0
  134. package/.docs/reference/memory/serialized-memory-config.md +1 -1
  135. package/.docs/reference/observability/tracing/advanced-queries.md +40 -31
  136. package/.docs/reference/processors/processor-interface.md +10 -2
  137. package/.docs/reference/server/routes.md +159 -0
  138. package/.docs/reference/signals/signal-provider.md +2 -0
  139. package/.docs/reference/signals/task-signal-provider.md +1 -1
  140. package/.docs/reference/streaming/agents/stream.md +1 -1
  141. package/.docs/reference/tools/mcp-client.md +236 -0
  142. package/.docs/reference/tools/mcp-server.md +170 -0
  143. package/.docs/reference/workflows/workflow-methods/branch.md +1 -1
  144. package/.docs/reference/workspace/filesystem.md +17 -17
  145. package/.docs/reference/workspace/local-filesystem.md +51 -26
  146. package/.docs/reference/workspace/platform-sandbox.md +2 -0
  147. package/.docs/reference/workspace/sandbox.md +16 -0
  148. package/.docs/reference/workspace/workspace-class.md +13 -12
  149. package/dist/index.js +1 -2
  150. package/dist/{src-Baf8l9Sp.js → src-DnH_jHt9.js} +2 -3
  151. package/dist/{src-Baf8l9Sp.js.map → src-DnH_jHt9.js.map} +1 -1
  152. package/dist/stdio.js +1 -1
  153. package/package.json +6 -6
@@ -21,18 +21,20 @@ For hosted traces, see [Query observability data on Mastra Platform](https://mas
21
21
 
22
22
  The configured observability store must support each API. Call `getObservabilityCapabilities()` or `GET /api/observability/capabilities` and check these flags before showing a feature:
23
23
 
24
- | Capability | Store feature | Enables |
25
- | ---------------------------- | --------------------------------- | -------------------------------------------------------------------------------------- |
26
- | `traceQuery` | `trace-query` | `queryTraces()` |
27
- | `traceAggregate` | `trace-aggregate` | `aggregateTraces()` |
28
- | `traceQueryRootDuration` | `trace-query-root-duration` | Trace-scope `durationMs` predicates |
29
- | `traceQueryTimeToFirstChunk` | `trace-query-time-to-first-chunk` | `timeToFirstChunkMs` predicates and results |
30
- | `traceQueryContextIds` | `trace-query-context-ids` | `runId`, `sessionId`, `userId`, and `organizationId` predicates |
31
- | `traceQueryRootSpanFields` | `trace-query-root-span-fields` | Trace-scope `name` and `spanType` predicates, dimensions, and `countDistinct` measures |
32
- | `traceQueryDiscovery` | `trace-query-discovery` | [Field and value discovery](#discover-fields-and-values) |
33
- | `traceQueryTenantScope` | `trace-query-tenant-scope` | [Trusted tenant scope](#trusted-tenant-scope) |
34
-
35
- A missing `traceAggregate` value means the server doesn't support aggregation. Servers without the aggregate route return `404`, and stores without the feature return `501 TRACE_AGGREGATE_UNSUPPORTED`. Against a store without a sub-feature, a request that uses a gated field returns `501` before storage runs. Root span `name` and `spanType` are the exception and return `422` with a `field_not_allowed` issue.
24
+ | Capability | Store feature | Enables |
25
+ | -------------------------------- | -------------------------------------- | -------------------------------------------------------------------------------------- |
26
+ | `traceQuery` | `trace-query` | `queryTraces()` |
27
+ | `traceAggregate` | `trace-aggregate` | `aggregateTraces()` |
28
+ | `traceQueryRootDuration` | `trace-query-root-duration` | Trace-scope `durationMs` predicates |
29
+ | `traceQueryTimeToFirstChunk` | `trace-query-time-to-first-chunk` | `timeToFirstChunkMs` predicates and results |
30
+ | `traceQueryTimeToFirstChunkSort` | `trace-query-time-to-first-chunk-sort` | `orderBy` on `timeToFirstChunkMs` |
31
+ | `traceQueryContextIds` | `trace-query-context-ids` | `runId`, `sessionId`, `userId`, and `organizationId` predicates |
32
+ | `traceQueryRootSpanFields` | `trace-query-root-span-fields` | Trace-scope `name` and `spanType` predicates, dimensions, and `countDistinct` measures |
33
+ | `traceQueryRootEntityId` | `trace-query-root-entity-id` | Trace-scope `entityId` predicates, dimensions, and `countDistinct` measures |
34
+ | `traceQueryDiscovery` | `trace-query-discovery` | [Field and value discovery](#discover-fields-and-values) |
35
+ | `traceQueryTenantScope` | `trace-query-tenant-scope` | [Trusted tenant scope](#trusted-tenant-scope) |
36
+
37
+ A missing `traceAggregate` value means the server doesn't support aggregation. Servers without the aggregate route return `404`, and stores without the feature return `501 TRACE_AGGREGATE_UNSUPPORTED`. Against a store without a sub-feature, a request that uses a gated field returns `501` before storage runs. Root span `name`, `spanType`, and `entityId` are the exception and return `422` with a `field_not_allowed` issue.
36
38
 
37
39
  ## Select traces
38
40
 
@@ -75,7 +77,7 @@ Span clauses examine the current root span and current child spans. The root `ti
75
77
 
76
78
  | Predicate context | Fields | Operators |
77
79
  | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------- |
78
- | Trace | `traceId`, `threadId`, `resourceId`, `runId`, `sessionId`, `userId`, `organizationId`, `entityName`, `entityType`, `name`, `spanType`, `environment`, `status` | `eq`, `ne`, `in`, `notIn`, `exists`, `notExists` |
80
+ | Trace | `traceId`, `threadId`, `resourceId`, `runId`, `sessionId`, `userId`, `organizationId`, `entityId`, `entityName`, `entityType`, `name`, `spanType`, `environment`, `status` | `eq`, `ne`, `in`, `notIn`, `exists`, `notExists` |
79
81
  | Trace metadata | `metadata.<key>` | `eq`, `ne`, `in`, `notIn`, `exists`, `notExists` |
80
82
  | Trace | `startedAt`, `endedAt`, `durationMs`, `timeToFirstChunkMs` | `eq`, `ne`, `in`, `notIn`, `lt`, `lte`, `gt`, `gte`, `exists`, `notExists` |
81
83
  | Trace | `tags` | `includes`, `notIncludes`, `exists`, `notExists` |
@@ -84,7 +86,7 @@ Span clauses examine the current root span and current child spans. The root `ti
84
86
  | Span | `startedAt`, `endedAt`, `durationMs`, `timeToFirstChunkMs` | `eq`, `ne`, `in`, `notIn`, `lt`, `lte`, `gt`, `gte`, `exists`, `notExists` |
85
87
  | Span | `error` | `exists`, `notExists` |
86
88
 
87
- 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.
89
+ Trace-scope `name`, `spanType`, and `entityId` 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.
88
90
 
89
91
  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).
90
92
 
@@ -128,7 +130,13 @@ const slowFirstChunk = {
128
130
 
129
131
  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.
130
132
 
131
- 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.
133
+ Trace query results include the root span's `timeToFirstChunkMs`, and `querySpans()` results include each span's value. 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.
134
+
135
+ #### Sort by time to first chunk
136
+
137
+ Pass `orderBy: [{ field: 'timeToFirstChunkMs', direction: 'desc' }]` to list the slowest first chunks first. Traces sort by the root span's value. Missing values sort last in both directions, and `0` sorts as a value. Ties break by `traceId` for traces and by span identity for `querySpans()`.
138
+
139
+ Stores advertise the sort through the `trace-query-time-to-first-chunk-sort` feature, and the server reports it as the `traceQueryTimeToFirstChunkSort` capability. Against an older store, the sort returns `501` before storage runs.
132
140
 
133
141
  #### Filter by context identifiers
134
142
 
@@ -437,16 +445,16 @@ curl --request POST \
437
445
 
438
446
  ### Request fields
439
447
 
440
- | Field | Required | Description |
441
- | ------------ | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
442
- | `timeRange` | Yes | Trace start-time boundary. `from` is inclusive and `to` is exclusive. Both values must be ISO timestamps, and `from` must be earlier than `to`. |
443
- | `where` | No | Recursive trace predicate. Supports scalar conditions and `spans.some` or `spans.none` clauses. |
444
- | `orderBy` | No | One item ordering results by `startedAt` or `endedAt`, in `asc` or `desc` order. Defaults to `startedAt desc`. Not accepted in delta mode. |
445
- | `page` | No | `{ limit, after }`. `limit` defaults to 100 and has a maximum of 1000. Pass the opaque `page.next` value as `after`. |
446
- | `pagination` | No | Numbered pages: `{ page, perPage }`. Defaults to page 0 and 10 results. `perPage` has a maximum of 100. |
447
- | `mode` | No | Set to `'delta'` to poll using a delta cursor instead of `page` or `pagination`. |
448
- | `after` | No | Delta mode only. Opaque `deltaCursor` from a numbered page or previous poll. Omit to establish the current watermark. |
449
- | `limit` | No | Delta mode only. Maximum results per batch. Defaults to 10 and has a maximum of 100. |
448
+ | Field | Required | Description |
449
+ | ------------ | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
450
+ | `timeRange` | Yes | Trace start-time boundary. `from` is inclusive and `to` is exclusive. Both values must be ISO timestamps, and `from` must be earlier than `to`. |
451
+ | `where` | No | Recursive trace predicate. Supports scalar conditions and `spans.some` or `spans.none` clauses. |
452
+ | `orderBy` | No | One item ordering results by `startedAt`, `endedAt`, or `timeToFirstChunkMs`, in `asc` or `desc` order. Defaults to `startedAt desc`. Not accepted in delta mode. |
453
+ | `page` | No | `{ limit, after }`. `limit` defaults to 100 and has a maximum of 1000. Pass the opaque `page.next` value as `after`. |
454
+ | `pagination` | No | Numbered pages: `{ page, perPage }`. Defaults to page 0 and 10 results. `perPage` has a maximum of 100. |
455
+ | `mode` | No | Set to `'delta'` to poll using a delta cursor instead of `page` or `pagination`. |
456
+ | `after` | No | Delta mode only. Opaque `deltaCursor` from a numbered page or previous poll. Omit to establish the current watermark. |
457
+ | `limit` | No | Delta mode only. Maximum results per batch. Defaults to 10 and has a maximum of 100. |
450
458
 
451
459
  Unknown fields are rejected. Requests can't select a projection, declare joins, request counts or measures, or control authorization. Use [`aggregateTraces()`](#aggregate-traces) for counts and measures. Request bodies are limited to 256 KiB.
452
460
 
@@ -657,12 +665,13 @@ Unknown fields are rejected. Aggregation isn't paginated. Narrow the selection,
657
665
 
658
666
  Dimensions read the current root span of each selected trace:
659
667
 
660
- | Dimension | Notes |
661
- | ------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- |
662
- | `entityType`, `entityName`, `environment`, `status`, `serviceName`, `executionSource` | Root span attributes. |
663
- | `threadId`, `resourceId`, `userId`, `sessionId`, `organizationId`, `experimentId` | Context identifiers recorded on the root span. |
664
- | `name`, `spanType` | Root span name and type. Requires the `traceQueryRootSpanFields` capability. |
665
- | `metadata.<key>` | One non-empty top-level metadata key. Values are trimmed. Missing, empty, and non-string values group as `null`. |
668
+ | Dimension | Notes |
669
+ | ------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
670
+ | `entityType`, `entityName`, `environment`, `status`, `serviceName`, `executionSource` | Root span attributes. |
671
+ | `threadId`, `resourceId`, `userId`, `sessionId`, `organizationId`, `experimentId` | Context identifiers recorded on the root span. |
672
+ | `name`, `spanType` | Root span name and type. Requires the `traceQueryRootSpanFields` capability. |
673
+ | `entityId` | Root span entity ID. Groups traces that have no `entityName`, such as scorer runs. Requires the `traceQueryRootEntityId` capability. |
674
+ | `metadata.<key>` | One non-empty top-level metadata key. Values are trimmed. Missing, empty, and non-string values group as `null`. |
666
675
 
667
676
  Every dimension except `serviceName`, `executionSource`, and `experimentId` is also a trace-scope `where` field, so you can drill into a group by adding its values to the predicate. `traceId`, `spanId`, `runId`, and `requestId` aren't groupable. Traces with no value for a dimension form their own group with a `null` value.
668
677
 
@@ -668,6 +668,14 @@ processOutputStep?(args: ProcessOutputStepArgs): ProcessorMessageResult;
668
668
 
669
669
  **requestContext** (`RequestContext`): Request-scoped context with execution metadata.
670
670
 
671
+ #### Return value
672
+
673
+ `processOutputStep` returns a `MessageList` or `MastraDBMessage[]`, directly or in a promise.
674
+
675
+ - Return the supplied `messageList` instance to keep it, including any in-place changes.
676
+ - Return a messages array to replace the current messages. Return the supplied `messages` array to leave them unchanged.
677
+ - Returning `[]` removes all current messages, including the conversation history and the latest response. It isn't a no-op.
678
+
671
679
  #### Use cases
672
680
 
673
681
  - Implementing quality guardrails that can request retries
@@ -683,7 +691,7 @@ import type { Processor } from '@mastra/core/processors'
683
691
  export class QualityGuardrail implements Processor {
684
692
  id = 'quality-guardrail'
685
693
 
686
- async processOutputStep({ text, abort, retryCount }) {
694
+ async processOutputStep({ messages, text, abort, retryCount }) {
687
695
  const score = await evaluateResponseQuality(text)
688
696
 
689
697
  if (score < 0.7) {
@@ -699,7 +707,7 @@ export class QualityGuardrail implements Processor {
699
707
  }
700
708
  }
701
709
 
702
- return []
710
+ return messages
703
711
  }
704
712
  }
705
713
  ```
@@ -261,6 +261,85 @@ On authenticated servers, the read routes require the `stored-workflows:read` pe
261
261
  }
262
262
  ```
263
263
 
264
+ ### Run result
265
+
266
+ `POST /api/workflows/:workflowId/start-async` awaits `run.start()` and returns its execution result, rather than returning immediately after starting the run. The `status` distinguishes success, failure, tripwire, suspension, and pause. The `steps` record is keyed by step ID, and each step has its own status and an `output` when one is available. The workflow's output is the top-level `result` on success.
267
+
268
+ The execution result includes the following fields. Status-specific fields are only present for the corresponding outcome:
269
+
270
+ ```typescript
271
+ {
272
+ status: 'success' | 'failed' | 'tripwire' | 'suspended' | 'paused';
273
+ input: unknown; // The inputData the run started with
274
+ state?: unknown; // Workflow state
275
+ result?: unknown; // Workflow output on success
276
+ error?: unknown; // Error on failure
277
+ tripwire?: unknown; // Tripwire details
278
+ suspendPayload?: unknown; // Payload returned on suspension
279
+ suspended?: string[][]; // Suspended step paths
280
+ steps: {
281
+ [stepId: string]: {
282
+ status: string;
283
+ output?: unknown;
284
+ error?: unknown;
285
+ startedAt: number; // Unix time in milliseconds
286
+ endedAt?: number;
287
+ };
288
+ };
289
+ }
290
+ ```
291
+
292
+ `GET /api/workflows/:workflowId/runs/:runId` returns run metadata and execution state, using a persisted snapshot when available and falling back to an in-memory run. Unlike the execution result above, it exposes the run's input as `payload` and state as `initialState`. `workflowName` is the workflow's `id`, which can differ from the registry key used in the path:
293
+
294
+ ```typescript
295
+ {
296
+ runId: string;
297
+ workflowName: string;
298
+ resourceId?: string | null;
299
+ createdAt: string; // ISO date string
300
+ updatedAt: string; // ISO date string
301
+ status: string; // Includes active states such as 'running' and 'waiting'
302
+ initialState?: Record<string, unknown>;
303
+ result?: unknown;
304
+ error?: unknown;
305
+ payload?: unknown; // The inputData the run started with
306
+ steps?: {
307
+ [stepId: string]: {
308
+ payload?: unknown; // This step's input
309
+ status: string;
310
+ output?: unknown;
311
+ error?: unknown; // Present when the step failed
312
+ startedAt: number;
313
+ endedAt?: number;
314
+ } | {
315
+ payload?: unknown;
316
+ status: string;
317
+ output?: unknown;
318
+ error?: unknown;
319
+ startedAt: number;
320
+ endedAt?: number;
321
+ }[]; // forEach iteration results
322
+ };
323
+ activeStepsPath?: Record<string, number[]>;
324
+ serializedStepGraph?: unknown[];
325
+ suspendedPaths?: Record<string, number[]>;
326
+ resumeLabels?: Record<string, unknown>;
327
+ waitingPaths?: Record<string, number[]>;
328
+ }
329
+ ```
330
+
331
+ For persisted runs, use the `fields` query parameter to trim the response. It accepts a comma-separated subset of `result`, `error`, `payload`, `steps`, `activeStepsPath`, and `serializedStepGraph`. Any other name is rejected with a 400. The metadata fields and `status` remain, along with `initialState` when nonempty:
332
+
333
+ ```bash
334
+ curl 'http://localhost:4111/api/workflows/my-workflow/runs/1faf6f91-b9ac-4db0-9fb3-326687ba1972?fields=result'
335
+ ```
336
+
337
+ A `steps` entry can be a single step result or an array of iteration results for a `forEach` step. Check whether the entry is an array before reading its `status` or `output`.
338
+
339
+ Pass `withNestedWorkflows=false` to skip expanding nested workflow executions inside `steps`. This doesn't remove the workflow's own step entries.
340
+
341
+ The in-memory fallback is identified by `isFromInMemory: true`. It returns run metadata, `status`, and empty `steps`, but omits `result`, `payload`, and `error`. Its `createdAt` and `updatedAt` timestamps use the current time, not the run's actual timestamps. It doesn't apply field filtering or nested-workflow expansion.
342
+
264
343
  ### Stream workflow request body
265
344
 
266
345
  ```typescript
@@ -543,6 +622,86 @@ Returns the persisted experiment result row.
543
622
  | `404` | Dataset, experiment, dataset item, or target not found (`EXPERIMENT_TARGET_NOT_FOUND`) |
544
623
  | `409` | Caller-supplied experiment `id` already exists for a different dataset or target (`EXPERIMENT_ID_CONFLICT`), or a call arrived after finalization (`EXPERIMENT_ALREADY_FINALIZED`) |
545
624
 
625
+ ## Scores
626
+
627
+ | Method | Path | Description |
628
+ | ------ | ------------------------------------------ | -------------------------------------------------------- |
629
+ | `GET` | `/api/scores/scorers` | List scorers with the agents and workflows that use them |
630
+ | `GET` | `/api/scores/scorers/:scorerId` | Get scorer by ID |
631
+ | `GET` | `/api/scores/run/:runId` | List scores for a run |
632
+ | `GET` | `/api/scores/scorer/:scorerId` | List scores produced by a scorer |
633
+ | `GET` | `/api/scores/entity/:entityType/:entityId` | List scores for an agent or workflow |
634
+ | `POST` | `/api/scores` | Save a score record |
635
+
636
+ ### List scorers response
637
+
638
+ The response is a record combining the scorers registered through the `scorers` option of the [`Mastra` class](https://mastra.ai/reference/core/mastra-class) with the scorers attached to agents and workflows. Agent and registered entries are keyed by scorer ID. Workflow entries currently use the scorer's name. Use the returned record key for `/api/scores/scorers/:scorerId`, and `scorer.config.id` when querying saved scores by scorer ID:
639
+
640
+ ```typescript
641
+ {
642
+ [scorerId: string]: {
643
+ scorer: {
644
+ config: {
645
+ id: string;
646
+ name?: string;
647
+ description: string;
648
+ type?: unknown;
649
+ judge?: unknown;
650
+ };
651
+ };
652
+ sampling?: object;
653
+ agentIds: string[];
654
+ agentNames: string[];
655
+ workflowIds: string[];
656
+ isRegistered: boolean; // True when the scorer is in the Mastra `scorers` option
657
+ source: 'code' | 'stored' | 'fs';
658
+ };
659
+ }
660
+ ```
661
+
662
+ Only `scorer.config` is part of the supported contract. The `scorer` object also carries implementation fields such as `steps`, which can change between releases.
663
+
664
+ `GET /api/scores/scorers/:scorerId` returns a single entry of the same shape. An unknown ID returns `null` with status 200 rather than a 404.
665
+
666
+ ### Score list query parameters
667
+
668
+ ```typescript
669
+ {
670
+ page?: number; // Page number (0-indexed)
671
+ perPage?: number; // Items per page (default: 10)
672
+ entityId?: string; // `/api/scores/scorer/:scorerId` only
673
+ entityType?: string; // `/api/scores/scorer/:scorerId` only
674
+ }
675
+ ```
676
+
677
+ For `/api/scores/entity/:entityType/:entityId`, use `AGENT` or `WORKFLOW` as `entityType` and the agent or workflow registry key as `entityId`. The server resolves the key to the entity's own `id` before querying storage. Other `entityType` values are passed to storage as-is.
678
+
679
+ ### Score list response
680
+
681
+ ```typescript
682
+ {
683
+ pagination: {
684
+ total: number;
685
+ page: number;
686
+ perPage: number;
687
+ hasMore: boolean;
688
+ };
689
+ scores: ScoreRowData[];
690
+ }
691
+ ```
692
+
693
+ Each record has the shape written by [score persistence](https://mastra.ai/docs/evals/overview). The fields you will read most often are `id`, `scorerId`, `runId`, `entityId`, `score`, `output`, `scorer`, `entity`, `source` (`LIVE` or `TEST`), the optional `entityType`, `input`, `reason`, `traceId`, `spanId`, `resourceId` and `threadId`, and the `createdAt` and `updatedAt` timestamps. Records also carry the scorer's intermediate step results and prompts. Without a `scores` store configured the list routes return an empty page instead of an error.
694
+
695
+ ### Save score request body
696
+
697
+ ```typescript
698
+ {
699
+ score: Omit<ScoreRowData, 'id' | 'createdAt' | 'updatedAt'> & { id?: string };
700
+ }
701
+ ```
702
+
703
+ How a supplied `id` is treated depends on the storage adapter. Some adapters upsert by it, others always generate a new ID, so retried submissions can create duplicate rows there. The response is `{ score: ScoreRowData }` with the stored record. Saving requires storage. Without it the route responds with a 500.
704
+
546
705
  ## MCP
547
706
 
548
707
  | Method | Path | Description |
@@ -396,6 +396,8 @@ Identifies a specific agent thread.
396
396
 
397
397
  **agentId** (`string`): Agent identifier.
398
398
 
399
+ **ifIdle** (`AgentSignalIfIdleOptions`): Options for signal delivery when the target thread is idle. Forwarded to sendNotificationSignal. See thread signals.
400
+
399
401
  ## Type guard
400
402
 
401
403
  ### `isSignalProvider(obj)`
@@ -8,7 +8,7 @@
8
8
 
9
9
  Bundles the built-in task tools (`task_write`, `task_update`, `task_complete`, `task_check`) and the `TaskStateProcessor` behind a single agent registration. Use it to add a structured, durable task list to an agent without wiring the tools and processor separately.
10
10
 
11
- Extends [`SignalProvider`](https://mastra.ai/reference/signals/signal-provider). The task list is stored in the thread-scoped `tasks` storage domain (the source of truth) and projected onto the agent state-signal lane by the processor, so it survives observational-memory truncation without invalidating the prompt cache.
11
+ Extends [`SignalProvider`](https://mastra.ai/reference/signals/signal-provider). The task list is stored under the `task` state type in the thread-scoped `threadState` storage domain, which is the source of truth, and projected onto the `tasks` agent state-signal lane by the processor, so it survives observational-memory truncation without invalidating the prompt cache.
12
12
 
13
13
  ## Usage example
14
14
 
@@ -238,7 +238,7 @@ const stream = await agent.stream('message for agent')
238
238
 
239
239
  **options.untilIdle** (`boolean | { maxIdleMs?: number }`): When set, keeps the stream open across background-task continuations. The agent will automatically re-invoke the LLM when background tasks complete, streaming continuation turns through the same fullStream. Pass true for default settings (5 min idle timeout), or an object with maxIdleMs to configure. Requires memory. Replaces the standalone streamUntilIdle() method.
240
240
 
241
- **options.untilIdle.maxIdleMs** (`number`): Closes the outer stream after this many ms of idleness between turns. The timer only runs while the wrapper is between turns. Default: 5 minutes.
241
+ **options.untilIdle.maxIdleMs** (`number`): Closes the outer stream after this many ms of idleness between turns. The timer only runs while the wrapper is between turns. Default: backgroundTasks.untilIdleMaxIdleMs from the Mastra config, or 5 minutes.
242
242
 
243
243
  ## Returns
244
244
 
@@ -31,6 +31,8 @@ constructor({
31
31
 
32
32
  **clientInfo** (`{ name?: string; version?: string }`): Client name and version every server receives on connect and with each request, so servers can attribute traffic to your application. Defaults to the server key as name and '1.0.0' as version. Individual server configs can override either field with their own clientInfo. Doesn't change tool name prefixes, which always use the server key.
33
33
 
34
+ **webhook** (`MCPClientWebhookOptions`): Experimental. Enables webhook delivery for MCP events. Servers POST occurrences to webhook.url, which must route to events.handleWebhook().
35
+
34
36
  ### `MastraMCPServerDefinition`
35
37
 
36
38
  Each server in the `servers` map is configured using the `MastraMCPServerDefinition` type. The transport type is detected based on the provided parameters:
@@ -761,6 +763,240 @@ Notes:
761
763
  - When `enableProgressTracking` is true, tool calls include a `progressToken` so you can correlate updates to a specific run. Servers only send progress for requests that carry a token.
762
764
  - If you pass a `runId` when executing a tool, it will be used as the `progressToken`.
763
765
 
766
+ ### `events` Property (experimental)
767
+
768
+ The `events` property lists and subscribes to server events from servers that implement the [MCP Events extension (SEP-3415)](https://github.com/modelcontextprotocol/modelcontextprotocol/pull/3415). Use it to react to things that happen on the server, such as a push to a repository, without polling a tool.
769
+
770
+ For an end-to-end walkthrough, see the [MCP events guide](https://mastra.ai/docs/guides/mcp-events).
771
+
772
+ > **Warning:** SEP-3415 is a draft. This API may change in any release.
773
+
774
+ ```typescript
775
+ const events = await mcpClient.events.list('github')
776
+
777
+ const subscription = await mcpClient.events.subscribe(
778
+ 'github',
779
+ 'repo.push',
780
+ { repo: 'mastra-ai/mastra' },
781
+ { cursor: await loadCursor() },
782
+ )
783
+
784
+ for await (const event of subscription) {
785
+ await handlePush(event.data)
786
+ // Safe to persist after each handled occurrence
787
+ await saveCursor(subscription.cursor)
788
+ }
789
+ ```
790
+
791
+ Servers that don't advertise the `io.modelcontextprotocol/events` extension receive no `events/*` requests. `list()` rejects with a `MastraError` whose id is `MCP_CLIENT_LIST_EVENTS_FAILED`, and `subscribe()` rejects with `MCP_CLIENT_SUBSCRIBE_EVENT_FAILED`. In both cases `error.cause.id` is `MCP_EVENTS_NOT_SUPPORTED`. Other `list()` and `subscribe()` failures use the same two ids, with the specific reason in `error.cause`.
792
+
793
+ #### `events.list(serverName: string)`
794
+
795
+ Returns every event type the server offers, following pagination. Each descriptor has a `name`, an optional `description`, the `delivery` modes the server supports, and optional `inputSchema` and `payloadSchema`.
796
+
797
+ ```typescript
798
+ async list(serverName: string): Promise<MCPEventDescriptor[]>
799
+ ```
800
+
801
+ The client doesn't receive notifications when the server's event list changes yet. Call `list()` again to pick up new event types.
802
+
803
+ #### `events.subscribe(serverName, eventName, args?, options?)`
804
+
805
+ Starts a subscription and resolves once the server confirms it. Errors such as an unknown event, invalid arguments, or a forbidden subscription reject the returned promise.
806
+
807
+ ```typescript
808
+ async subscribe(
809
+ serverName: string,
810
+ eventName: string,
811
+ args?: Record<string, unknown>,
812
+ options?: MCPEventSubscribeOptions,
813
+ ): Promise<MCPEventSubscription>
814
+ ```
815
+
816
+ The client picks the first mode the event offers in this order: `webhook` (only when the client has [`webhook` settings](#webhook-delivery)), `push` (a long-lived `events/stream` request), then `poll` (repeated `events/poll` requests). Pass `options.delivery` to force a mode.
817
+
818
+ **delivery** (`'webhook' | 'push' | 'poll'`): Forces a delivery mode. When the event doesn't offer it, or for webhook without client webhook settings, subscribe() rejects with MCP\_CLIENT\_SUBSCRIBE\_EVENT\_FAILED and error.cause.id is MCP\_EVENTS\_NO\_COMPATIBLE\_DELIVERY\_MODE or MCP\_EVENTS\_WEBHOOK\_NOT\_CONFIGURED.
819
+
820
+ **cursor** (`string | null`): Resumes from a cursor saved earlier. Omit or pass null to start from now.
821
+
822
+ **maxAgeMs** (`number`): Asks the server not to replay occurrences older than this.
823
+
824
+ **maxEvents** (`number`): Maximum occurrences per poll response. Poll mode only.
825
+
826
+ **minPollIntervalMs** (`number`): Lower bound for the wait between polls, applied to the server-suggested nextPollMs. (Default: `1000`)
827
+
828
+ **heartbeatTimeoutMs** (`number`): Push mode reopens the stream from the last cursor after this long without any message from the server. (Default: `60000`)
829
+
830
+ **streamOpenTimeoutMs** (`number`): How long to wait for the server to confirm a push stream. Defaults to the server request timeout.
831
+
832
+ **dedupWindow** (`number`): Number of recent event ids remembered to drop duplicate occurrences. (Default: `1000`)
833
+
834
+ **maxBufferedEvents** (`number`): Most occurrences held while your loop isn't reading. When full, the oldest unread occurrence is dropped, the next one has truncated set, and onError receives MCP\_EVENTS\_BUFFER\_OVERFLOW. (Default: `1000`)
835
+
836
+ **retry** (`{ initialDelayMs?: number; maxDelayMs?: number; factor?: number; maxAttempts?: number }`): Backoff with full jitter for transient failures. Defaults to 1000 ms initial delay, 30000 ms maximum, factor 2, unlimited retries.
837
+
838
+ **signal** (`AbortSignal`): Aborting it cancels the subscription.
839
+
840
+ The returned `MCPEventSubscription` is an async iterable of occurrences (`eventId`, `name`, `timestamp`, `data`) with these members:
841
+
842
+ - `cursor`: The latest position that's safe to persist. It never moves past an occurrence your loop hasn't received yet. It's `null` when the event type doesn't support replay.
843
+ - `truncated`: `true` when the server reported a gap right before the occurrence your loop received last, for example because the saved cursor was older than its retention window. Read it inside the loop: it's `true` for the first occurrence after the gap and `false` for the ones after it.
844
+ - `mode`: The delivery mode in use, `'webhook'`, `'push'`, or `'poll'`.
845
+ - `deliveryStatus`: Webhook mode only. The server's latest report on delivery to your webhook URL (`active`, `lastDeliveryAt`, `lastError`, `failedSince`), updated on each refresh.
846
+ - `onError(handler)`: Receives recoverable errors, such as a dropped stream that the client is reopening. Returns a function that removes the handler.
847
+ - `cancel()`: Stops the subscription and ends the iterator. Breaking out of a `for await` loop also cancels it.
848
+
849
+ The iterator throws a `MastraError` directly (not wrapped) when the subscription can't continue: `MCP_EVENTS_SUBSCRIPTION_FAILED` for a non-retryable server error, `MCP_EVENTS_SUBSCRIPTION_TERMINATED` when the server ends a push or webhook subscription, or `MCP_EVENTS_RETRIES_EXHAUSTED` after `retry.maxAttempts` failed attempts in a row. The client reopens dropped streams and resumes polling from the last cursor after a reconnect, including after `reconnectServer()`. `disconnect()` ends all subscriptions.
850
+
851
+ #### `events.handleWebhook(request: Request)`
852
+
853
+ Handles one webhook delivery and returns the response to send back. Mount it on the route that `webhook.url` points at.
854
+
855
+ ```typescript
856
+ async handleWebhook(request: Request): Promise<Response>
857
+ ```
858
+
859
+ It verifies the Standard Webhooks signature on the raw body before parsing it, answers the server's verification handshake, and routes occurrences to their subscription by the `X-MCP-Subscription-Id` header. It responds with:
860
+
861
+ - `200` after the occurrence is handed to its subscription, or with the echoed challenge for a verification request.
862
+ - `401` when the signature is invalid or the timestamp is more than 5 minutes old.
863
+ - `503` when the subscription id isn't known yet, so the server retries. This covers deliveries that arrive before the subscribe response.
864
+ - `400` for a signed but malformed body, and `405` for methods other than `POST`.
865
+ - `413` for a body over 1 MiB. The body is read only up to that limit, before any other check.
866
+ - `404` when the client has no `webhook` settings.
867
+
868
+ #### Webhook delivery
869
+
870
+ With `webhook` settings, the client registers each subscription with `events/subscribe` and the server POSTs occurrences to your URL. The server must authenticate the client, and the URL must be publicly reachable over `https`.
871
+
872
+ ```typescript
873
+ import { Mastra } from '@mastra/core'
874
+ import { registerApiRoute } from '@mastra/core/server'
875
+ import { MCPClient } from '@mastra/mcp'
876
+
877
+ export const mcpClient = new MCPClient({
878
+ servers: {
879
+ github: {
880
+ url: new URL('https://mcp.example.com/mcp'),
881
+ requestInit: { headers: { Authorization: `Bearer ${process.env.GITHUB_MCP_TOKEN}` } },
882
+ },
883
+ },
884
+ webhook: { url: 'https://agent.example.com/mcp/webhook' },
885
+ })
886
+
887
+ export const mastra = new Mastra({
888
+ server: {
889
+ apiRoutes: [
890
+ registerApiRoute('/mcp/webhook', {
891
+ method: 'POST',
892
+ // Deliveries are authenticated by their signature, not by Mastra auth
893
+ requiresAuth: false,
894
+ handler: c => mcpClient.events.handleWebhook(c.req.raw),
895
+ }),
896
+ ],
897
+ },
898
+ })
899
+ ```
900
+
901
+ **url** (`string`): Public https URL that routes to events.handleWebhook().
902
+
903
+ **secret** (`string`): A whsec\_ signing secret used for every subscription. By default the client generates a fresh secret for each subscription, so one server can't sign deliveries for another server's subscriptions.
904
+
905
+ **ttlMs** (`number | null`): Suggested subscription lifetime. null asks for no expiry, which the server may decline. Defaults to the server default.
906
+
907
+ **refreshMarginMs** (`number`): How long before the server-granted refreshBefore time to refresh the subscription. Defaults to the smaller of 60 seconds and 20% of the grant.
908
+
909
+ The client refreshes each subscription before it expires by repeating `events/subscribe` with the latest cursor. When the server reports failing delivery in `deliveryStatus`, for example because your endpoint timed out, `onError` receives `MCP_EVENTS_WEBHOOK_DELIVERY_FAILING` with `lastError` in its details. The next refresh resumes a suspended subscription. `cancel()` sends `events/unsubscribe`.
910
+
911
+ Webhook state lives in this process: run the receiving route in the same process as the `MCPClient` that subscribed.
912
+
913
+ Webhook delivery needs an authenticated HTTP connection to the server, because the server ties each webhook subscription to the caller. Over stdio, or over HTTP without authentication, the server rejects `events/subscribe`; it also rejects new subscriptions once its webhook subscription cap is reached (`-32025`). A subscription that didn't force a mode then falls back to `push` or `poll`, and the first `onError` handler receives `MCP_EVENTS_WEBHOOK_UNAVAILABLE` with the rejection `code` and the `fallback` mode in its details. Forcing `delivery: 'webhook'` rejects instead.
914
+
915
+ Subscriptions on one server with the same event name and arguments share a single server-side webhook subscription. Each one gets every occurrence through its own iterator, and the client sends `events/unsubscribe` only when the last of them is cancelled.
916
+
917
+ ### Events in agents and workflows (experimental)
918
+
919
+ `MCPEventsSignalProvider` delivers MCP server events to agent threads as notifications. Add it to an agent's `signals`, then subscribe threads to events. The agent needs a notifications storage domain, which `InMemoryStore` and the standard storage adapters provide.
920
+
921
+ > **Warning:** SEP-3415 is a draft. This API may change in any release.
922
+
923
+ ```typescript
924
+ import { Agent } from '@mastra/core/agent'
925
+ import { MCPClient, MCPEventsSignalProvider } from '@mastra/mcp'
926
+
927
+ const mcp = new MCPClient({
928
+ servers: { github: { url: new URL('https://example.com/mcp') } },
929
+ })
930
+
931
+ export const repoEvents = new MCPEventsSignalProvider({
932
+ client: mcp,
933
+ subscribeOptions: { maxAgeMs: 60 * 60 * 1000 },
934
+ })
935
+
936
+ export const repoAgent = new Agent({
937
+ id: 'repo-agent',
938
+ name: 'Repo Agent',
939
+ instructions: 'Triage repository activity.',
940
+ model: 'openai/gpt-5.6-sol',
941
+ signals: [repoEvents],
942
+ })
943
+
944
+ await repoEvents.subscribeThread(
945
+ { resourceId: 'user-1', threadId: 'thread-1' },
946
+ { server: 'github', event: 'repo.push', args: { repo: 'mastra-ai/mastra' } },
947
+ )
948
+ ```
949
+
950
+ Threads that subscribe to the same server, event and arguments share one MCP subscription. Argument key order doesn't matter. Each occurrence becomes a notification with `kind: 'mcp-event'` and `attributes: { server, event }`. The raw occurrence is in `payload`. The notification `summary`, which is the only part the model reads, labels the event as untrusted and wraps its data, together with the server-advertised event name, in an `<untrusted-mcp-event-data>` block that the content can't close. When the server reports a gap, `attributes.truncated` is `true` and the summary says that events may have been skipped.
951
+
952
+ If the subscription ends, for example because the server terminates it, each subscribed thread receives a `high` priority notification with `kind: 'mcp-event-subscription-ended'` and the threads are unsubscribed.
953
+
954
+ **client** (`Pick<MCPClient, 'events'>`): The client used to list and subscribe to events.
955
+
956
+ **id** (`string`): Provider id, used as the notification source. (Default: `'mcp-events'`)
957
+
958
+ **name** (`string`): Display name. (Default: `'MCP Events'`)
959
+
960
+ **cursorStore** (`MCPEventCursorStore`): Stores the resume cursor for each subscription. Implement get(key), set(key, cursor) and delete(key) with durable storage so a subscription continues from its last cursor when a thread is subscribed again after a restart. Only cursors are stored, not which threads are subscribed. Only non-null cursors are stored. (Default: `InMemoryMCPEventCursorStore`)
961
+
962
+ **subscribeOptions** (`Omit<MCPEventSubscribeOptions, 'cursor' | 'signal'>`): Options for every MCP subscription, for example maxAgeMs to bound the backlog replayed on resume.
963
+
964
+ **priority** (`NotificationPriority`): Priority of event notifications. (Default: `'medium'`)
965
+
966
+ **coalesce** (`boolean`): Sets coalesceKey: 'mcp-events:\<key>' on event notifications, whatever the provider id. Pending notifications from one subscription then merge, so a burst that arrives before the agent reads its inbox keeps only the latest occurrence. When off, every occurrence is its own notification. (Default: `false`)
967
+
968
+ **tools** (`boolean | { servers: string[] }`): Gives the agent the mcp\_events\_list, mcp\_events\_subscribe and mcp\_events\_unsubscribe tools, which act on the current thread and require memory. Event descriptions and error messages from the server reach the model inside the same untrusted-data block as event data. Subscriptions made through the tools are lost on restart. Pass servers to limit them to those servers. (Default: `false`)
969
+
970
+ **onError** (`(error: unknown, info: { server: string; event: string; key: string }) => void`): Receives delivery, cursor store and subscription errors.
971
+
972
+ The provider has these methods:
973
+
974
+ - `subscribeThread(thread, { server, event, args? })`: Subscribes a thread and resolves once the MCP subscription is confirmed. It resumes from the stored cursor. If the server rejects the subscription, the thread isn't subscribed and the promise rejects. Thread subscriptions are kept in memory only: after a restart, call `subscribeThread()` again for each thread that should keep receiving events.
975
+ - `unsubscribeThread(thread, { server, event, args? })`: Resolves to `true` when the thread was subscribed. When the last thread leaves, the MCP subscription is cancelled and its stored cursor is deleted.
976
+ - `stop()`: Cancels every MCP subscription and keeps the stored cursors, so a new provider with the same `cursorStore` resumes where this one stopped.
977
+ - `MCPEventsSignalProvider.key({ server, event, args? })`: Returns the subscription key used by the cursor store.
978
+
979
+ Delivery is at least once. The provider stores the cursor after it notifies the threads, so an occurrence notified right before a crash is replayed after the restart. The notification's `dedupeKey` includes the event id: if the first notification is still pending, the replay merges into it. If it was already delivered, the thread is notified again.
980
+
981
+ To start a workflow run for each occurrence, iterate a subscription directly:
982
+
983
+ ```typescript
984
+ const subscription = await mcp.events.subscribe(
985
+ 'github',
986
+ 'repo.push',
987
+ { repo: 'mastra-ai/mastra' },
988
+ { cursor: await loadCursor() },
989
+ )
990
+
991
+ process.once('SIGTERM', () => void subscription.cancel())
992
+
993
+ for await (const event of subscription) {
994
+ const run = await triagePushWorkflow.createRun()
995
+ await run.start({ inputData: { eventId: event.eventId, push: event.data } })
996
+ if (subscription.cursor) await saveCursor(subscription.cursor)
997
+ }
998
+ ```
999
+
764
1000
  ## Answering input requests
765
1001
 
766
1002
  A server tool, resource or prompt that needs something from the user ends its call with an `input_required` result instead of a value. The result carries one or more embedded requests, each with a server-chosen `key` and either a form (`requestedSchema`) or a URL the user must visit. Configure `inputRequests` on the server definition to answer them: the client calls the handler once per embedded request, retries the original call with the answers, and resolves the tool call with the final result. Without a handler an `input_required` result surfaces as an error.