@mastra/mcp-docs-server 1.2.27-alpha.1 → 1.2.27-alpha.13

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 (94) hide show
  1. package/.docs/docs/agents/structured-output.md +17 -0
  2. package/.docs/docs/connections/a2a.md +4 -3
  3. package/.docs/docs/deployment/monorepo.md +2 -2
  4. package/.docs/docs/evals/datasets.md +53 -0
  5. package/.docs/docs/guides/build-an-eval-loop.md +395 -0
  6. package/.docs/docs/harness/agent-controller.md +4 -2
  7. package/.docs/docs/mastra-platform/alerts.md +83 -0
  8. package/.docs/docs/mastra-platform/api.md +21 -3
  9. package/.docs/docs/mastra-platform/observability.md +185 -1
  10. package/.docs/docs/mastra-platform/overview.md +2 -0
  11. package/.docs/docs/memory/message-history.md +58 -0
  12. package/.docs/docs/memory/observational-memory.md +33 -0
  13. package/.docs/docs/observability/feedback.md +3 -3
  14. package/.docs/docs/observability/tracing/overview.md +2 -0
  15. package/.docs/docs/server/custom-adapters.md +43 -0
  16. package/.docs/docs/subagents.md +38 -7
  17. package/.docs/integrations/channels/github.md +6 -2
  18. package/.docs/integrations/databases/clickhouse.md +1 -1
  19. package/.docs/integrations/observability/confident-ai.md +67 -43
  20. package/.docs/integrations/observability/langfuse.md +4 -0
  21. package/.docs/integrations/sandboxes/cloudflare-sandbox.md +36 -4
  22. package/.docs/models/environment-variables.md +5 -1
  23. package/.docs/models/gateways/netlify.md +8 -4
  24. package/.docs/models/gateways/openrouter.md +5 -2
  25. package/.docs/models/gateways/vercel.md +378 -379
  26. package/.docs/models/index.md +22 -1
  27. package/.docs/models/providers/ai21.md +78 -0
  28. package/.docs/models/providers/ainetcafe.md +77 -0
  29. package/.docs/models/providers/alibaba-cn.md +8 -6
  30. package/.docs/models/providers/alibaba-token-plan-cn.md +2 -1
  31. package/.docs/models/providers/alibaba-token-plan.md +3 -1
  32. package/.docs/models/providers/alibaba.md +2 -1
  33. package/.docs/models/providers/chutes.md +2 -2
  34. package/.docs/models/providers/cortecs.md +6 -7
  35. package/.docs/models/providers/digitalocean.md +1 -1
  36. package/.docs/models/providers/edenai.md +4 -7
  37. package/.docs/models/providers/empiriolabs.md +2 -1
  38. package/.docs/models/providers/fireworks-ai.md +11 -10
  39. package/.docs/models/providers/hyper.md +26 -37
  40. package/.docs/models/providers/inception.md +3 -3
  41. package/.docs/models/providers/inco.md +83 -0
  42. package/.docs/models/providers/iteracompute.md +14 -7
  43. package/.docs/models/providers/kilo.md +12 -9
  44. package/.docs/models/providers/llmgateway-providers.md +9 -7
  45. package/.docs/models/providers/llmgateway.md +2 -2
  46. package/.docs/models/providers/mistral.md +3 -2
  47. package/.docs/models/providers/nano-gpt.md +11 -18
  48. package/.docs/models/providers/nvidia.md +2 -1
  49. package/.docs/models/providers/oci.md +85 -0
  50. package/.docs/models/providers/ofox.md +24 -23
  51. package/.docs/models/providers/opencode.md +3 -2
  52. package/.docs/models/providers/ovhcloud.md +1 -1
  53. package/.docs/models/providers/privatemode-ai.md +3 -3
  54. package/.docs/models/providers/scnet-token-plan.md +2 -1
  55. package/.docs/models/providers/synthetic.md +2 -1
  56. package/.docs/models/providers/tensorx.md +2 -1
  57. package/.docs/models/providers/tinfoil.md +1 -1
  58. package/.docs/models/providers/umans-ai-coding-plan.md +3 -4
  59. package/.docs/models/providers/umans-ai.md +3 -4
  60. package/.docs/models/providers/vancine.md +10 -10
  61. package/.docs/models/providers/volcengine.md +3 -2
  62. package/.docs/models/providers/wandb.md +4 -4
  63. package/.docs/models/providers/xai.md +1 -3
  64. package/.docs/models/providers/zhipuai-coding-plan.md +2 -8
  65. package/.docs/models/providers.md +5 -1
  66. package/.docs/reference/agent-controller/agent-controller-class.md +70 -2
  67. package/.docs/reference/agents/generate.md +1 -1
  68. package/.docs/reference/auth/clerk.md +25 -1
  69. package/.docs/reference/cli/mastra.md +85 -1
  70. package/.docs/reference/client-js/agent-controller.md +77 -16
  71. package/.docs/reference/client-js/agents.md +25 -0
  72. package/.docs/reference/client-js/mastra-client.md +1 -1
  73. package/.docs/reference/client-js/observability.md +104 -5
  74. package/.docs/reference/code-sdk/mount-agent-controller.md +23 -0
  75. package/.docs/reference/core/getMCPServer.md +47 -0
  76. package/.docs/reference/index.md +3 -0
  77. package/.docs/reference/memory/memory-class.md +3 -1
  78. package/.docs/reference/memory/observational-memory.md +34 -4
  79. package/.docs/reference/memory/serialized-memory-config.md +1 -1
  80. package/.docs/reference/migrations/mcp-v2.md +268 -0
  81. package/.docs/reference/observability/feedback.md +31 -1
  82. package/.docs/reference/observability/tracing/interfaces.md +3 -1
  83. package/.docs/reference/observability/tracing/trace-query.md +219 -46
  84. package/.docs/reference/pubsub/redis-streams.md +34 -0
  85. package/.docs/reference/rag/vector-databases.md +73 -0
  86. package/.docs/reference/storage/retention.md +56 -4
  87. package/.docs/reference/streaming/agents/stream.md +2 -2
  88. package/.docs/reference/tools/mcp-client.md +36 -14
  89. package/.docs/reference/tools/mcp-server.md +24 -111
  90. package/.docs/reference/vectors/azure-ai-search.md +150 -0
  91. package/.docs/reference/vectors/weaviate.md +128 -0
  92. package/.docs/reference/workspace/workspace-class.md +10 -2
  93. package/package.json +10 -12
  94. package/.docs/docs/connections/connect-mcp-client.md +0 -211
@@ -108,7 +108,7 @@ const result = await agent.generate('message for agent')
108
108
 
109
109
  **options.structuredOutput.fallbackValue** (`<S extends ZodTypeAny>`): Fallback value to use when schema validation fails and errorStrategy is 'fallback'.
110
110
 
111
- **options.structuredOutput.instructions** (`string`): Additional instructions for the structured output model.
111
+ **options.structuredOutput.instructions** (`string`): Additional instructions for the structured output model. With jsonPromptInjection and no structuring model, this text is injected into the prompt in place of the serialized schema.
112
112
 
113
113
  **options.structuredOutput.jsonPromptInjection** (`boolean | 'system' | 'inline' | 'auto'`): Controls how the JSON schema reaches the model. Set to 'auto' to use native structured output when supported and inline prompt injection otherwise.
114
114
 
@@ -23,6 +23,26 @@ export const mastra = new Mastra({
23
23
  })
24
24
  ```
25
25
 
26
+ ## Restricting login to a single organization
27
+
28
+ Set `organizationId` or `organizationSlug` to only allow members of a specific Clerk organization to sign in. Non-members are rejected during authorization. Configure only one of the two. Setting both throws at startup, so login can't be granted to two different organizations.
29
+
30
+ ```typescript
31
+ import { Mastra } from '@mastra/core'
32
+ import { MastraAuthClerk } from '@mastra/auth-clerk'
33
+
34
+ export const mastra = new Mastra({
35
+ server: {
36
+ auth: new MastraAuthClerk({
37
+ jwksUri: process.env.CLERK_JWKS_URI,
38
+ publishableKey: process.env.CLERK_PUBLISHABLE_KEY,
39
+ secretKey: process.env.CLERK_SECRET_KEY,
40
+ organizationId: process.env.CLERK_ORGANIZATION_ID,
41
+ }),
42
+ },
43
+ })
44
+ ```
45
+
26
46
  ## Constructor parameters
27
47
 
28
48
  **publishableKey** (`string`): Your Clerk publishable key. Can be found in your Clerk Dashboard under API Keys. (Default: `process.env.CLERK_PUBLISHABLE_KEY`)
@@ -31,9 +51,13 @@ export const mastra = new Mastra({
31
51
 
32
52
  **jwksUri** (`string`): The JWKS URI from your Clerk application. Used to verify JWT signatures. (Default: `process.env.CLERK_JWKS_URI`)
33
53
 
54
+ **organizationId** (`string`): Restrict login to members of a single Clerk organization, identified by its ID. Users who are not members of this organization are denied access. (Default: `process.env.CLERK_ORGANIZATION_ID`)
55
+
56
+ **organizationSlug** (`string`): Restrict login to members of a single Clerk organization, identified by its slug. Users who are not members of this organization are denied access. (Default: `process.env.CLERK_ORGANIZATION_SLUG`)
57
+
34
58
  **name** (`string`): Custom name for the auth provider instance.
35
59
 
36
- **authorizeUser** (`(user: User, request: HonoRequest) => Promise<boolean> | boolean`): Custom authorization function to determine if a user should be granted access. Called after token verification. By default, allows all authenticated users.
60
+ **authorizeUser** (`(user: User, request: HonoRequest) => Promise<boolean> | boolean`): Custom authorization function to determine if a user should be granted access. Called after token verification. By default, allows all authenticated users, unless organizationId or organizationSlug is set, in which case only members of that organization are allowed.
37
61
 
38
62
  ## Related
39
63
 
@@ -1079,6 +1079,90 @@ See the [Storage migration guide](https://mastra.ai/reference/migrations/upgrade
1079
1079
 
1080
1080
  It accepts [common flags](#common-flags).
1081
1081
 
1082
+ ## `mastra traces import`
1083
+
1084
+ Imports historical traces from a supported observability provider into an existing Mastra Platform project. The command prepares complete traces locally, uploads whole-trace batches, supports resume, and verifies a sample through Mastra Platform.
1085
+
1086
+ ```bash
1087
+ mastra traces import <provider> [options]
1088
+ ```
1089
+
1090
+ The following provider is currently supported:
1091
+
1092
+ | Provider | Argument | Requirements |
1093
+ | -------- | ---------- | -------------------------------------------------- |
1094
+ | Langfuse | `langfuse` | Langfuse Cloud or self-hosted Langfuse v4 or later |
1095
+
1096
+ See [Import existing traces](https://mastra.ai/docs/mastra-platform/observability) for the complete workflow, data mapping, local-file lifecycle, and limits.
1097
+
1098
+ ### Options
1099
+
1100
+ #### `--project <name|slug|id>`
1101
+
1102
+ Selects the destination Mastra Platform project. `MASTRA_PROJECT_ID` takes precedence when set. Without either value, the command uses the project linked in `.mastra-project.json`.
1103
+
1104
+ #### `--from <date>`
1105
+
1106
+ Sets the inclusive start of the import window as an ISO 8601 date or timestamp. It defaults to 30 days before `--to`, clamped to the current 30-day Platform retention boundary.
1107
+
1108
+ #### `--to <date>`
1109
+
1110
+ Sets the exclusive end of the import window as an ISO 8601 date or timestamp. It defaults to the time when the import starts and can't be in the future.
1111
+
1112
+ The complete window must fall within the current 30-day Platform retention period, `--from` must be earlier than `--to`, and the window can't exceed 30 days.
1113
+
1114
+ #### `--dry-run`
1115
+
1116
+ Reads the source and prepares valid traces locally without uploading them. The command writes a report and prints a command that resumes the prepared import.
1117
+
1118
+ #### `--resume <import-id>`
1119
+
1120
+ Resumes a prepared import using its saved provider, destination project, date window, and acknowledged progress. Use the same destination project shown in the generated resume command. This option can't be combined with `--from`, `--to`, or `--dry-run`.
1121
+
1122
+ #### `-y, --yes`
1123
+
1124
+ Uploads without asking for confirmation.
1125
+
1126
+ ### Environment variables
1127
+
1128
+ The command loads `.env` and `.env.local` from the current directory.
1129
+
1130
+ | Variable | Required | Description |
1131
+ | ------------------------------ | ----------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- |
1132
+ | `LANGFUSE_PUBLIC_KEY` | For new Langfuse imports | Public project API key. |
1133
+ | `LANGFUSE_SECRET_KEY` | For new Langfuse imports | Secret project API key. |
1134
+ | `LANGFUSE_BASE_URL` | No | Langfuse host. Defaults to `https://cloud.langfuse.com`. |
1135
+ | `MASTRA_API_TOKEN` | For headless authentication | Mastra Platform API token. Without it, the command uses credentials from `mastra auth login`. |
1136
+ | `MASTRA_ORG_ID` | With `MASTRA_API_TOKEN` | Organization that owns the destination project. |
1137
+ | `MASTRA_PLATFORM_ACCESS_TOKEN` | For upload and read-back with interactive login | Mastra Platform access token for the destination. Not required for `--dry-run` or when `MASTRA_API_TOKEN` is set. |
1138
+ | `MASTRA_PROJECT_ID` | When no project is otherwise linked | Destination project ID. Takes precedence over `--project`. |
1139
+
1140
+ ### Examples
1141
+
1142
+ Preview the default 30-day window without uploading:
1143
+
1144
+ ```bash
1145
+ mastra traces import langfuse --project my-project --dry-run
1146
+ ```
1147
+
1148
+ Import a smaller date window without a confirmation prompt:
1149
+
1150
+ ```bash
1151
+ mastra traces import langfuse \
1152
+ --project my-project \
1153
+ --from "$FROM" \
1154
+ --to "$TO" \
1155
+ --yes
1156
+ ```
1157
+
1158
+ Resume an existing import:
1159
+
1160
+ ```bash
1161
+ mastra traces import langfuse \
1162
+ --resume 00000000-0000-0000-0000-000000000000 \
1163
+ --project my-project
1164
+ ```
1165
+
1082
1166
  ## `mastra api`
1083
1167
 
1084
1168
  Calls a Mastra runtime server with JSON input and JSON output. Use it for local development servers, deployed Mastra platform projects, self-hosted Mastra servers, or hosted Mastra Platform Observability APIs.
@@ -1617,7 +1701,7 @@ mastra api metric label-values '{"metricName":"latency_ms","labelKey":"model","p
1617
1701
 
1618
1702
  #### Observability with `curl`
1619
1703
 
1620
- You can call the hosted observability API directly with your platform access token and project ID. The examples below use the United States host. Substitute `https://observability.eu.mastra.ai` for a European Union environment. The [hosted feedback query API](https://mastra.ai/docs/mastra-platform/api) documents feedback endpoints that don't have CLI commands:
1704
+ You can call the hosted observability API directly with your platform access token and project ID. The examples below use the United States host. Substitute `https://observability.eu.mastra.ai` for a European Union environment. The [Feedback API](https://mastra.ai/docs/mastra-platform/api) documents feedback endpoints that don't have CLI commands:
1621
1705
 
1622
1706
  ```bash
1623
1707
  curl -sS "https://observability.mastra.ai/api/observability/traces?page=0&perPage=20" \
@@ -219,31 +219,92 @@ Returns: `Promise<SendNotificationResult>`
219
219
 
220
220
  `onEvent` receives every event the session emits, discriminated by `event.type`:
221
221
 
222
- | Group | Events |
223
- | ------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
224
- | Run | `agent_start`, `agent_end`, `usage_update`, `goal_evaluation`, `follow_up_queued` |
225
- | Messages | `message_start`, `message_update`, `message_end` |
226
- | Tools | `tool_input_start`, `tool_input_delta`, `tool_input_end`, `tool_start`, `tool_update`, `tool_end`, `shell_output`, `command_exit`, `tool_approval_required`, `tool_suspended`, `tool_suspension_cancelled`, `task_updated` |
227
- | Session | `state_changed`, `display_state_changed`, `mode_changed`, `model_changed`, `thread_changed`, `thread_created`, `thread_deleted`, `thread_title_updated` |
228
- | Subagents | `subagent_start`, `subagent_text_delta`, `subagent_tool_start`, `subagent_tool_end`, `subagent_end`, `subagent_model_changed` |
229
- | Memory | `om_observation_start`, `om_observation_end`, `om_observation_failed`, `om_reflection_start`, `om_reflection_end`, `om_reflection_failed`, `om_buffering_start`, `om_buffering_end`, `om_buffering_failed`, `om_model_changed`, `om_activation`, `om_status`, `om_thread_title_updated` |
230
- | Workspace | `workspace_ready`, `workspace_error`, `workspace_status_changed` |
231
- | Notification | `notification`, `notification_summary`, `info`, `error` |
222
+ | Group | Events |
223
+ | ----------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
224
+ | Run | `agent_start`, `agent_end`, `usage_update`, `goal_evaluation`, `follow_up_queued` |
225
+ | Messages | `message_start`, `message_update`, `message_end` |
226
+ | Tools | `tool_input_start`, `tool_input_delta`, `tool_input_end`, `tool_start`, `tool_update`, `tool_end`, `shell_output`, `command_exit`, `tool_approval_required`, `tool_suspended`, `tool_suspension_cancelled`, `task_updated` |
227
+ | Session | `state_changed`, `display_state_changed`, `mode_changed`, `model_changed`, `thread_changed`, `thread_created`, `thread_deleted`, `thread_title_updated` |
228
+ | Subagents | `subagent_start`, `subagent_text_delta`, `subagent_tool_start`, `subagent_tool_end`, `subagent_end`, `subagent_model_changed` |
229
+ | Memory | `om_observation_start`, `om_observation_end`, `om_observation_failed`, `om_reflection_start`, `om_reflection_end`, `om_reflection_failed`, `om_buffering_start`, `om_buffering_end`, `om_buffering_failed`, `om_model_changed`, `om_activation`, `om_status`, `om_thread_title_updated` |
230
+ | Workspace | `workspace_ready`, `workspace_error`, `workspace_status_changed` |
231
+ | Diagnostics | `info`, `error` |
232
232
 
233
- `message_*` events carry a `MastraDBMessage` and `thread_created` carries a thread, with timestamps hydrated to `Date`.
233
+ Notifications are delivered as agent signals carried on messages rather than as `notification` or `notification_summary` controller events.
234
234
 
235
- A controller can also emit events the SDK doesn't type. `AgentControllerEvent` is the union of `KnownAgentControllerEvent` and `OtherAgentControllerEvent`. Because `OtherAgentControllerEvent.type` is `string`, comparing `event.type` to a literal doesn't narrow the union. Narrow with `isKnownAgentControllerEvent(event)` first:
235
+ A message lifecycle uses three event shapes:
236
+
237
+ - `message_start` carries the initial `MastraDBMessage`, with `createdAt` hydrated to `Date`.
238
+ - `message_update` carries the message `id` and a compact text, reasoning, or part update.
239
+ - `message_end` carries the `id` of the completed message.
240
+
241
+ `thread_created` also carries a thread with timestamps hydrated to `Date`.
242
+
243
+ A controller can emit events the SDK doesn't type. `AgentControllerEvent` is the union of `KnownAgentControllerEvent` and `OtherAgentControllerEvent`. Because `OtherAgentControllerEvent.type` is `string`, comparing `event.type` to a literal doesn't narrow the union. Narrow with `isKnownAgentControllerEvent(event)` first, then reconstruct messages by ID:
236
244
 
237
245
  ```typescript
238
- import { isKnownAgentControllerEvent } from '@mastra/client-js'
246
+ import {
247
+ isKnownAgentControllerEvent,
248
+ type AgentControllerEvent,
249
+ type KnownAgentControllerEvent,
250
+ type MastraDBMessage,
251
+ } from '@mastra/client-js'
252
+
253
+ type MessageUpdate = Extract<KnownAgentControllerEvent, { type: 'message_update' }>['event']
254
+
255
+ const activeMessages = new Map<string, MastraDBMessage>()
256
+
257
+ function applyUpdate(message: MastraDBMessage, update: MessageUpdate): MastraDBMessage {
258
+ const parts = [...message.content.parts]
259
+
260
+ if (update.type === 'text-delta') {
261
+ const index = parts.findLastIndex(part => part.type === 'text')
262
+ const part = parts[index]
263
+
264
+ if (part?.type === 'text') {
265
+ parts[index] = { ...part, text: part.text + update.delta }
266
+ } else {
267
+ parts.push({ type: 'text', text: update.delta })
268
+ }
269
+ } else if (update.type === 'reasoning-delta') {
270
+ const part = parts[update.index]
271
+ const reasoning = part?.type === 'reasoning' ? part.reasoning + update.delta : update.delta
272
+ parts[update.index] = {
273
+ ...(part?.type === 'reasoning' ? part : { type: 'reasoning' as const }),
274
+ reasoning,
275
+ details: [{ type: 'text', text: reasoning }],
276
+ }
277
+ } else {
278
+ parts[update.index] = update.part
279
+ }
280
+
281
+ return { ...message, content: { ...message.content, parts } }
282
+ }
239
283
 
240
284
  function handleEvent(event: AgentControllerEvent) {
241
285
  if (!isKnownAgentControllerEvent(event)) return
242
286
 
243
287
  switch (event.type) {
244
- case 'message_update':
245
- render(event.message)
288
+ case 'message_start':
289
+ activeMessages.set(event.message.id, structuredClone(event.message))
290
+ break
291
+ case 'message_update': {
292
+ const message = activeMessages.get(event.id)
293
+ if (!message) break
294
+
295
+ const updated = applyUpdate(message, event.event)
296
+ activeMessages.set(event.id, updated)
297
+ render(updated)
298
+ break
299
+ }
300
+ case 'message_end': {
301
+ const message = activeMessages.get(event.id)
302
+ if (!message) break
303
+
304
+ renderComplete(message)
305
+ activeMessages.delete(event.id)
246
306
  break
307
+ }
247
308
  case 'tool_approval_required':
248
309
  showApproval(event.toolCallId)
249
310
  break
@@ -251,7 +312,7 @@ function handleEvent(event: AgentControllerEvent) {
251
312
  }
252
313
  ```
253
314
 
254
- Use `agentControllerMessageText(message)` to pull the plain text out of a message's nested content parts.
315
+ Use `agentControllerMessageText(message)` to pull the plain text out of a reconstructed message's nested content parts.
255
316
 
256
317
  ## Related
257
318
 
@@ -119,6 +119,31 @@ while (true) {
119
119
  }
120
120
  ```
121
121
 
122
+ #### Cancelling a stream
123
+
124
+ Cancelling the response body aborts the underlying HTTP request and stops any pending client tool executions and follow-up requests:
125
+
126
+ ```typescript
127
+ const response = await agent.stream('Tell me a story')
128
+ const reader = response.body.getReader()
129
+
130
+ const { value } = await reader.read()
131
+ await reader.cancel('user navigated away')
132
+ ```
133
+
134
+ You can also pass an `abortSignal` to cancel from outside the stream. The same option is available on `streamUntilIdle()`, `resumeStream()`, `resumeStreamUntilIdle()`, `approveToolCall()`, `declineToolCall()`, `generate()`, and `generateLegacy()`:
135
+
136
+ ```typescript
137
+ const controller = new AbortController()
138
+
139
+ const response = await agent.stream('Tell me a story', {
140
+ abortSignal: controller.signal,
141
+ })
142
+
143
+ // Later
144
+ controller.abort()
145
+ ```
146
+
122
147
  #### AI SDK compatible format
123
148
 
124
149
  To stream AI SDK-formatted parts on the client from an `agent.stream(...)` response, wrap `response.processDataStream` into a `ReadableStream<ChunkType>` and use `toAISdkStream`:
@@ -81,7 +81,7 @@ You can also pass `requestContext` as a `Record<string, any>`.
81
81
 
82
82
  **getWorkflow(workflowId)** (`Workflow`): Retrieves a specific workflow instance by ID.
83
83
 
84
- **getAgentBuilderActions()** (`Promise<Record<string, WorkflowInfo>>`): Returns all available Agent Builder actions. See Agent Builder API.
84
+ **getAgentBuilderActions()** (`Promise<GetAgentBuilderActionsResponse>`): Returns all available Agent Builder actions. See Agent Builder API.
85
85
 
86
86
  **getAgentBuilderAction(actionId)** (`AgentBuilder`): Retrieves an Agent Builder action by ID. See Agent Builder API.
87
87
 
@@ -65,9 +65,9 @@ const selected = await mastraClient.getTrace(list.spans[0].traceId)
65
65
 
66
66
  It accepts the same filtering, ordering and delta-polling arguments as `listTraces()`. Use `listTraces()` when you actually need the full span payloads.
67
67
 
68
- ## Querying traces with recursive predicates
68
+ ## Querying traces and threads
69
69
 
70
- `queryTraces()` finds completed logical traces using trace fields and conditions over related spans or scores. Every query requires an ISO timestamp range of at most 31 days.
70
+ `queryTraces()` finds completed logical traces using trace fields and conditions over related spans, scores, or feedback. Every query requires an ISO timestamp range of at most 31 days.
71
71
 
72
72
  ```typescript
73
73
  const result = await mastraClient.queryTraces({
@@ -89,9 +89,106 @@ const result = await mastraClient.queryTraces({
89
89
  })
90
90
  ```
91
91
 
92
- The API limits predicate depth, nodes, related clauses, set members, literal bytes, and the total literal budget before storage execution. Cursor pages are deterministic but aren't a database snapshot, so signals written between requests can change later pages. PostgreSQL and ClickHouse queries have a configurable 15-second execution timeout.
92
+ ### Discover trace-query fields and values
93
93
 
94
- See [Advanced trace queries](https://mastra.ai/reference/observability/tracing/trace-query) for the complete limits, request fields, predicates, grouping, cursor pagination, response shapes, and errors.
94
+ `getTraceQueryFields()` returns canonical query fields and observed top-level string metadata fields for one predicate scope. The response includes each field's value kind, supported operators, and whether value suggestions are available.
95
+
96
+ ```typescript
97
+ const timeRange = {
98
+ from: '2026-08-01T00:00:00.000Z',
99
+ to: '2026-08-08T00:00:00.000Z',
100
+ }
101
+
102
+ const fields = await mastraClient.getTraceQueryFields({
103
+ timeRange,
104
+ predicateScope: 'spans',
105
+ search: 'model',
106
+ limit: 25,
107
+ })
108
+ ```
109
+
110
+ Use the exact local path from the response with the same scope. For example, `model` belongs inside a `spans.some` or `spans.none` predicate. A global picker can fetch `trace`, `spans`, `scores`, and `feedback` in parallel.
111
+
112
+ Call `getTraceQueryValues()` only after selecting a field with `valueSuggestions: true`:
113
+
114
+ ```typescript
115
+ const controller = new AbortController()
116
+
117
+ const values = await mastraClient.getTraceQueryValues(
118
+ {
119
+ timeRange,
120
+ predicateScope: 'spans',
121
+ path: 'model',
122
+ search: 'claude',
123
+ limit: 25,
124
+ },
125
+ { signal: controller.signal },
126
+ )
127
+
128
+ // Cancel this autocomplete request when the search text changes.
129
+ controller.abort()
130
+ ```
131
+
132
+ Both methods use case-insensitive literal substring search and accept an empty search. Limits default to 25 and can't exceed 100. Results are ordered by occurrence count, then deterministically by path or value. `observedFieldsTruncated` and `valuesTruncated` indicate that the caller should refine `search`. Discovery has no cursor.
133
+
134
+ Suggestions are bounded and advisory. Manual values remain valid when suggestions are unavailable, empty, or truncated. Discovery doesn't accept a draft query predicate. The client doesn't retry either request, and a per-call `AbortSignal` takes precedence over the signal configured on `MastraClient`.
135
+
136
+ A discovery timeout rejects with `504 TRACE_QUERY_EXECUTION_TIMEOUT`. Backend memory or resource exhaustion rejects with `503 TRACE_QUERY_RESOURCE_LIMIT`. Neither error contains partial suggestions; truncation flags are only present on successful, completely ranked responses.
137
+
138
+ `queryTraceThreads()` returns thread identities derived from observability traces after applying eligibility and cross-trace conditions. It doesn't read or return memory thread records or messages. In this example, one production trace can have the low factuality score while another production trace in the same thread has the clinician correction:
139
+
140
+ ```typescript
141
+ const result = await mastraClient.queryTraceThreads({
142
+ traces: {
143
+ timeRange: {
144
+ from: '2026-08-01T00:00:00.000Z',
145
+ to: '2026-08-08T00:00:00.000Z',
146
+ },
147
+ where: {
148
+ op: 'eq',
149
+ left: { path: 'environment' },
150
+ right: { literal: 'production' },
151
+ },
152
+ },
153
+ where: {
154
+ op: 'and',
155
+ args: [
156
+ {
157
+ traces: {
158
+ some: {
159
+ scores: {
160
+ some: {
161
+ op: 'lt',
162
+ left: { path: 'score' },
163
+ right: { literal: 0.6 },
164
+ },
165
+ },
166
+ },
167
+ },
168
+ },
169
+ {
170
+ traces: {
171
+ some: {
172
+ feedback: {
173
+ some: {
174
+ op: 'eq',
175
+ left: { path: 'feedbackType' },
176
+ right: { literal: 'clinician-correction' },
177
+ },
178
+ },
179
+ },
180
+ },
181
+ },
182
+ ],
183
+ },
184
+ })
185
+
186
+ // { threads: [{ threadId: 'thread-123' }], page: { next: null } }
187
+ ```
188
+
189
+ The API limits predicate depth, nodes, related clauses, set members, literal bytes, and the total literal budget before storage execution. Cursor pages are deterministic but aren't a database snapshot, so signals written between requests can change later pages. PostgreSQL and ClickHouse trace and thread queries have a configurable 15-second execution timeout.
190
+
191
+ See [Advanced trace queries](https://mastra.ai/reference/observability/tracing/trace-query) for the complete limits, request fields, predicates, thread qualification semantics, cursor pagination, response shapes, and errors.
95
192
 
96
193
  ## Deleting traces
97
194
 
@@ -136,7 +233,7 @@ const scores = await mastraClient.listScoresBySpan({
136
233
 
137
234
  ## Feedback
138
235
 
139
- Feedback methods create, list, and query human-in-the-loop signals such as ratings, thumbs, comments, and corrections through the target Mastra runtime and its configured observability storage. They don't call the hosted Mastra Platform feedback query API. See the [feedback guide](https://mastra.ai/docs/observability/feedback) for examples and the [feedback reference](https://mastra.ai/reference/observability/feedback) for full schemas.
236
+ Feedback methods create, list, and query human-in-the-loop signals such as ratings, thumbs, comments, and corrections through the target Mastra runtime and its configured observability storage. They don't call the hosted Mastra Platform Feedback API. See the [feedback guide](https://mastra.ai/docs/observability/feedback) for examples and the [feedback reference](https://mastra.ai/reference/observability/feedback) for full schemas.
140
237
 
141
238
  ### Creating feedback
142
239
 
@@ -188,6 +285,8 @@ const feedback = await mastraClient.listFeedback({
188
285
  })
189
286
  ```
190
287
 
288
+ `filters` accepts every [`FeedbackFilter`](https://mastra.ai/reference/observability/feedback) field. The client sends them as query parameters on `GET /api/observability/feedback`. See [list query parameters](https://mastra.ai/reference/observability/feedback).
289
+
191
290
  ### Aggregating feedback
192
291
 
193
292
  Aggregate numeric feedback values, such as ratings or thumbs encoded as `1` and `-1`:
@@ -94,6 +94,29 @@ const { controller } = await mountAgentControllerOnMastra({ mastra })
94
94
 
95
95
  **authStorage** (`AuthStorage`): Credential storage used by the built-in model gateway.
96
96
 
97
+ ## Nested controllers in plugins
98
+
99
+ A plugin that boots another controller in the same process must borrow the host's storage instead of opening the same database files with its own native SQLite library.
100
+
101
+ ### `context.getStorage()`
102
+
103
+ The optional accessor on `MastraCodePluginContext` returns the host's `storage` (`MastraCompositeStore`), `storageBackend` (`'libsql' | 'pg'`), and optional `vector` (`MastraVector`). Call it when the tool runs, then pass the returned object to `bootLocalAgentController()`:
104
+
105
+ ```typescript
106
+ import { bootLocalAgentController } from '@mastra/code-sdk'
107
+ import type { MastraCodePluginContext } from '@mastra/code-sdk/plugin'
108
+
109
+ async function bootNestedController(context: MastraCodePluginContext) {
110
+ const sharedStorage = context.getStorage?.()
111
+ if (!sharedStorage) {
112
+ throw new Error('This plugin requires host-provided shared storage.')
113
+ }
114
+ return bootLocalAgentController({ cwd: context.cwd, ...sharedStorage })
115
+ }
116
+ ```
117
+
118
+ The host owns these instances. Stop the nested controller's workers and destroy its controller when finished, but don't close the borrowed stores or invoke its storage-maintenance methods. If the accessor is unavailable on an older host, don't fall back to opening the same database files.
119
+
97
120
  ## Related
98
121
 
99
122
  - [AgentController class](https://mastra.ai/reference/agent-controller/agent-controller-class)
@@ -38,6 +38,53 @@ const serverById = mastra.getMCPServerById('my-mcp-server')
38
38
 
39
39
  **server** (`MCPServerBase | undefined`): The MCP server instance with the specified registry key, or undefined if not found.
40
40
 
41
+ ## MCP 1.x and 2026-07-28 servers
42
+
43
+ Both `@mastra/mcp` 1.x and 2.x servers extend the same `MCPServerBase` from `@mastra/core/mcp`. A 2.x server sets `mcpVersion` to `2`, while 1.x servers leave it undefined and need no new properties or methods. The differences are limited to what the 2026-07-28 protocol changed: `startSSE` and `startHonoSSE` are no longer abstract and throw unless a 1.x server overrides them (only 1.x implements the standalone SSE transport, and both are deprecated), and a server with `mcpVersion` set to `2` resolves `executeTool` to a `MCPToolExecutionResultV2` that reports a suspended tool rather than a bare result.
44
+
45
+ The 1.x-only surfaces are marked `@deprecated` and are removed in the next major release of `@mastra/core`: `startSSE`, `startHonoSSE`, `MCPServerSSEOptions`, `MCPServerHonoSSEOptions`, `MCPServerHTTPOptions.options`, and on `context.mcp` the members `elicitation`, `extra.sendNotification` and `extra.sendRequest`.
46
+
47
+ ### Tools that ask for input
48
+
49
+ A 2026-07-28 server runs ordinary `createTool` definitions. A tool that needs something from the user before it can finish declares `suspendSchema` and `resumeSchema` and calls `suspend()`, exactly as it would for an agent or a workflow. Core reports the suspension as `{ status: 'suspended', suspendPayload, resumeSchema }` from `executeTool`. An `@mastra/mcp` 2.x server turns that into an `input_required` round on the wire, and resumes the tool with the answer in `resumeData`.
50
+
51
+ ```typescript
52
+ import { createTool } from '@mastra/core/tools'
53
+ import { z } from 'zod'
54
+
55
+ const confirm = createTool({
56
+ id: 'confirm',
57
+ description: 'Ask for confirmation before charging',
58
+ inputSchema: z.object({ amount: z.number() }),
59
+ outputSchema: z.boolean(),
60
+ suspendSchema: z.object({ phase: z.literal('confirm'), amount: z.number() }),
61
+ resumeSchema: z.object({ confirmed: z.boolean() }),
62
+ execute: async ({ amount }, context) => {
63
+ if (!context.resumeData) {
64
+ await context.suspend?.({ phase: 'confirm', amount })
65
+ return
66
+ }
67
+ return context.resumeData.confirmed
68
+ },
69
+ })
70
+ ```
71
+
72
+ On a 2026-07-28 server and in direct execution, `suspend`, `resumeData` and `suspendPayload` sit at the top level of the tool context. Agents and workflows still nest them under `context.agent` and `context.workflow` until the next major release of `@mastra/core`. `resumeSchema` must be a flat object of primitive fields so it can be presented as an input form.
73
+
74
+ Each round is a separate request. `resumeData` carries only the current round's answer, validated against `resumeSchema`, and `suspendPayload` carries what the tool last suspended with. Because the framework never replays earlier rounds, handlers branch on explicit named phases, every round is re-authorized, and writes rely on domain-owned idempotency. `suspendPayload` is also handed back to tools resumed by agents and workflows.
75
+
76
+ ### The `mcp` context
77
+
78
+ Both server versions hand a tool the same `context.mcp` (`MCPToolExecutionContext`): `extra` with the request's `signal`, `requestId`, `authInfo` and `_meta`, plus `log(level, message, data?)` and `progress({ progress, total?, message? })`. A tool that only uses these works unchanged on either version. A 2026-07-28 server also sets `context.mcp.protocolVersion` to `'2026-07-28'`.
79
+
80
+ The 2026-07-28 protocol removed server-initiated requests, so on a 2.x server the deprecated members `elicitation.sendRequest`, `extra.sendRequest` and `extra.sendNotification` throw with a message naming the replacement instead of doing nothing. A 1.x server keeps providing them as before. To ask the user for input, call `context.suspend()` and read `context.resumeData`.
81
+
82
+ ### Registration and execution
83
+
84
+ Tools are registered on the Mastra instance exactly as a 1.x server registers them. On a server with `mcpVersion` set to `2`, `executeTool(toolId, args, context?)` returns `{ status: 'completed', output }` or, when the tool suspended, `{ status: 'suspended', suspendPayload, resumeSchema }` with `resumeSchema` as JSON Schema. The result has no failure variant: a tool that throws, or input or resume data that fails its schema, rejects the promise. Shared REST execution endpoints return the suspended shape instead of pretending the tool finished, and accept `resumeData` plus the echoed `suspendPayload` on the next call to continue the tool. Legacy SSE routes remain available only to 1.x servers. A server with `mcpVersion` set to `2` gets a 404 there.
85
+
86
+ Registering another server under an occupied registry key keeps the existing instance. Registry keys and intrinsic server IDs remain distinct.
87
+
41
88
  ## Related methods
42
89
 
43
90
  - [Mastra.getMCPServerById()](https://mastra.ai/reference/core/getMCPServerById): Retrieve an MCP server by its intrinsic `id` property
@@ -229,6 +229,7 @@ The Reference section provides documentation of Mastra's API, including paramete
229
229
  - [.settled()](https://mastra.ai/reference/memory/settled)
230
230
  - [.summarizeThread()](https://mastra.ai/reference/memory/summarizeThread)
231
231
  - [.updateThreadResourceId()](https://mastra.ai/reference/memory/updateThreadResourceId)
232
+ - [@mastra/mcp v1 to v2](https://mastra.ai/reference/migrations/mcp-v2)
232
233
  - [AgentNetwork to .network()](https://mastra.ai/reference/migrations/agentnetwork)
233
234
  - [AI SDK v4 to v5](https://mastra.ai/reference/migrations/ai-sdk-v4-to-v5)
234
235
  - [Mastra Cloud to Mastra platform](https://mastra.ai/reference/migrations/mastra-cloud)
@@ -352,6 +353,7 @@ The Reference section provides documentation of Mastra's API, including paramete
352
353
  - [Task tools](https://mastra.ai/reference/tools/task-tools)
353
354
  - [Amazon S3 Vector Store](https://mastra.ai/reference/vectors/s3vectors)
354
355
  - [Astra Vector Store](https://mastra.ai/reference/vectors/astra)
356
+ - [Azure AI Search Vector Store](https://mastra.ai/reference/vectors/azure-ai-search)
355
357
  - [Chroma Vector Store](https://mastra.ai/reference/vectors/chroma)
356
358
  - [Cloudflare Vector Store](https://mastra.ai/reference/vectors/vectorize)
357
359
  - [Convex Vector Store](https://mastra.ai/reference/vectors/convex)
@@ -368,6 +370,7 @@ The Reference section provides documentation of Mastra's API, including paramete
368
370
  - [Qdrant Vector Store](https://mastra.ai/reference/vectors/qdrant)
369
371
  - [Turbopuffer Vector Store](https://mastra.ai/reference/vectors/turbopuffer)
370
372
  - [Upstash Vector Store](https://mastra.ai/reference/vectors/upstash)
373
+ - [Weaviate Vector Store](https://mastra.ai/reference/vectors/weaviate)
371
374
  - [Overview](https://mastra.ai/reference/voice/overview)
372
375
  - [Composite Voice](https://mastra.ai/reference/voice/composite-voice)
373
376
  - [Events](https://mastra.ai/reference/voice/voice.events)
@@ -41,6 +41,8 @@ export const agent = new Agent({
41
41
 
42
42
  **options.lastMessages** (`number | false`): Number of most recent messages to include in context. Set to false to disable the message history feature entirely (messages are not loaded into context or saved). Use Number.MAX\_SAFE\_INTEGER to retrieve all messages with no limit. To load messages without saving new ones, use the readOnly option. The window slides forward on every request, so once a thread exceeds the limit, each turn invalidates the provider prompt cache. For long-running conversations, use Observational Memory instead.
43
43
 
44
+ **options.messageHistory** (`{ maxTokens: number; atMaxRemoveTokens?: number }`): Token budget for the complete prompt, including remembered history, system instructions, context, and the current turn. When the prompt exceeds maxTokens, the oldest remembered messages are dropped until the prompt is at most maxTokens - atMaxRemoveTokens (defaults to 25% of maxTokens). Protected content is never removed. Linked tool calls and results are removed together. During agent runs, trimmed history is excluded from later turns via a persisted per-thread boundary, but the messages themselves stay in storage. When set without an explicit lastMessages, the default 10-message cap is not applied. Set maxTokens to 0 to disable message history. Prefer this over lastMessages, since message count is a poor proxy for context size.
45
+
44
46
  **options.readOnly** (`boolean`): When true, prevents memory from saving new messages and provides working memory as read-only context (without the updateWorkingMemory tool). Useful for read-only operations like previews, internal routing agents, or sub agents that should reference but not modify memory.
45
47
 
46
48
  **options.semanticRecall** (`boolean | { topK: number; messageRange: number | { before: number; after: number }; scope?: 'thread' | 'resource' }`): Enable semantic search in message history. Can be a boolean or an object with configuration options. When enabled, requires both vector store and embedder to be configured. Default topK is 4, default messageRange is {before: 1, after: 1}.
@@ -49,7 +51,7 @@ export const agent = new Agent({
49
51
 
50
52
  **options.observationalMemory** (`boolean | ObservationalMemoryOptions`): Enable Observational Memory for long-context agentic memory. Set to true for defaults, or pass a config object to customize token budgets, models, and scope. See Observational Memory reference for configuration details.
51
53
 
52
- **options.generateTitle** (`boolean | { model: DynamicArgument<MastraLanguageModel>; instructions?: DynamicArgument<string> }`): Controls automatic thread title generation from the conversation transcript. Can be a boolean or an object with custom model and instructions.
54
+ **options.generateTitle** (`boolean | { model?: DynamicArgument<MastraModelConfig>; instructions?: DynamicArgument<string>; minMessages?: number; emitEvent?: boolean }`): Controls automatic thread title generation from the conversation transcript. Accepts a boolean or an object with a custom model (any MastraModelConfig: a model instance, a "provider/model" ID, or an OpenAI-compatible config; defaults to the agent's own model), custom instructions, a minimum message count, and emitEvent. With emitEvent: true the run's stream waits for the title and emits it as a transient data-thread-title chunk before finish (durable and evented agents persist the title but don't emit the chunk yet).
53
55
 
54
56
  ## Returns
55
57