@mastra/mcp-docs-server 1.3.13-alpha.9 → 1.3.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 (55) hide show
  1. package/.docs/docs/agents/code-mode.md +4 -0
  2. package/.docs/docs/agents/tools.md +10 -2
  3. package/.docs/docs/auth/custom-auth-provider.md +66 -0
  4. package/.docs/docs/auth/jwt.md +1 -1
  5. package/.docs/docs/connections/mcp.md +4 -65
  6. package/.docs/docs/evals/overview.md +4 -0
  7. package/.docs/docs/harness/schedules.md +1 -1
  8. package/.docs/docs/memory/multi-user-threads.md +57 -127
  9. package/.docs/docs/memory/observational-memory.md +196 -756
  10. package/.docs/docs/memory/overview.md +4 -0
  11. package/.docs/docs/observability/feedback.md +5 -7
  12. package/.docs/docs/sandbox/overview.md +2 -0
  13. package/.docs/docs/sandbox/search.md +25 -0
  14. package/.docs/docs/server/mcp.md +315 -0
  15. package/.docs/docs/server/request-context.md +35 -0
  16. package/.docs/docs/studio/deployment.md +0 -1
  17. package/.docs/docs/studio/overview.md +4 -4
  18. package/.docs/docs/workflows/scheduled-workflows.md +26 -5
  19. package/.docs/integrations/sandboxes/docker.md +39 -0
  20. package/.docs/integrations/sandboxes/e2b.md +1 -1
  21. package/.docs/integrations/voice/openai.md +2 -2
  22. package/.docs/models/gateways/custom-gateways.md +74 -44
  23. package/.docs/reference/agents/generate.md +1 -1
  24. package/.docs/reference/agents/generateLegacy.md +7 -23
  25. package/.docs/reference/auth/jwt.md +26 -2
  26. package/.docs/reference/cli/mastra.md +74 -6
  27. package/.docs/reference/client-js/observability.md +13 -5
  28. package/.docs/reference/configuration.md +64 -0
  29. package/.docs/reference/connect/tools.md +59 -0
  30. package/.docs/reference/editor/mastra-editor.md +1 -1
  31. package/.docs/reference/index.md +1 -0
  32. package/.docs/reference/memory/observational-memory.md +350 -151
  33. package/.docs/reference/observability/feedback.md +57 -14
  34. package/.docs/reference/observability/tracing/advanced-queries.md +3 -1
  35. package/.docs/reference/observability/tracing/exporters/langfuse.md +24 -1
  36. package/.docs/reference/observability/tracing/exporters/mastra-platform-exporter.md +19 -16
  37. package/.docs/reference/observability/tracing/exporters/otel.md +1 -1
  38. package/.docs/reference/observability/tracing/interfaces.md +2 -2
  39. package/.docs/reference/observability/tracing/spans.md +7 -1
  40. package/.docs/reference/processors/processor-interface.md +23 -0
  41. package/.docs/reference/rag/chunk.md +1 -1
  42. package/.docs/reference/rag/graph-rag-guide.md +3 -1
  43. package/.docs/reference/schedules/overview.md +25 -5
  44. package/.docs/reference/server/dispatch-route.md +124 -0
  45. package/.docs/reference/server/elysia-adapter.md +1 -1
  46. package/.docs/reference/server/express-adapter.md +17 -11
  47. package/.docs/reference/server/fastify-adapter.md +1 -1
  48. package/.docs/reference/server/hono-adapter.md +1 -1
  49. package/.docs/reference/server/invoke-route.md +10 -0
  50. package/.docs/reference/server/koa-adapter.md +1 -1
  51. package/.docs/reference/server/nestjs-adapter.md +1 -1
  52. package/.docs/reference/streaming/agents/stream.md +1 -1
  53. package/.docs/reference/workspace/factory-sandbox.md +20 -1
  54. package/.docs/reference/workspace/platform-sandbox.md +1 -1
  55. package/package.json +5 -5
@@ -118,6 +118,45 @@ Markers tell a session what the image already ran: `.mastra-sandbox/repos/<repo>
118
118
 
119
119
  If any entry's access or head can't be resolved, the whole resolution rejects and the sandbox falls back to its default template.
120
120
 
121
+ ## Docker Cloud Sandboxes
122
+
123
+ `DockerSandboxesSandbox` runs commands in a Docker Cloud Sandboxes microVM instead of a local container. Supply an authenticated `@docker/sandboxes` client to access Docker Cloud Sandboxes.
124
+
125
+ ```typescript
126
+ import { Sandboxes, pat } from '@docker/sandboxes'
127
+ import { Workspace } from '@mastra/core/workspace'
128
+ import { DockerSandboxesSandbox } from '@mastra/docker'
129
+
130
+ const client = new Sandboxes({
131
+ auth: pat({
132
+ username: process.env.DOCKER_USERNAME!,
133
+ personalAccessToken: process.env.DOCKER_PAT!,
134
+ }),
135
+ })
136
+ const workspace = new Workspace({
137
+ sandbox: new DockerSandboxesSandbox({
138
+ id: sessionId,
139
+ image: 'ubuntu:24.04',
140
+ environment: { NODE_ENV: 'production' },
141
+ client,
142
+ }),
143
+ })
144
+ ```
145
+
146
+ The `id` is used as the remote sandbox display name for reconnection lookup, so a new instance with the same `id` reconnects to an existing microVM and restarts it if it was stopped. Each instance uses a separate creation idempotency key. Pass `sandboxId` to reconnect directly to a known remote sandbox.
147
+
148
+ Commands run through `sh -lc`, so command strings can use pipes, redirects and `&&`. Separate `args` are shell-quoted. `executeCommand` supports `timeout`, `abortSignal`, streaming `onStdout`/`onStderr` callbacks and `maxRetainedBytes` (default 1 MiB per stream). Calling `destroy()` deletes the remote sandbox.
149
+
150
+ **image** (`string`): Image used to create the cloud sandbox.
151
+
152
+ **id** (`string`): Stable logical identifier used as the remote display name for reconnection lookup. (Default: `Auto-generated`)
153
+
154
+ **sandboxId** (`string`): Remote sandbox name to reconnect to directly.
155
+
156
+ **environment** (`Record<string, string>`): Environment variables set on a newly created cloud sandbox.
157
+
158
+ **client** (`Sandboxes`): Authenticated Docker Cloud Sandboxes client. Supply one to access Docker Cloud Sandboxes; caller-owned clients are not closed on destroy().
159
+
121
160
  ## Constructor parameters
122
161
 
123
162
  **id** (`string`): Unique identifier for this sandbox instance. Used for label-based reconnection. (Default: `Auto-generated`)
@@ -400,7 +400,7 @@ Private repositories build warm templates when `getRepositoryAccess` returns an
400
400
 
401
401
  Only pass short-lived credentials — the value stays in the template definition until the next rebuild, so its expiry is what bounds the exposure. Note that the cloned repository contents become part of a team-visible template image. When the access call returns no credential the clone is tokenless: public repositories build fine, and a private repository's build degrades to the fallback, where the session's own runtime setup (with runtime-injected auth) does the clone.
402
402
 
403
- Setup commands that need their own credentials — a registry token, a private index URL — take them through `buildEnv`, which accepts a record or an async resolver. Those values are part of the template's identity, so changing one produces a new template.
403
+ Setup commands that need their own credentials — a registry token, a private index URL — take them through `buildEnv`, which accepts a record or an async resolver. Those values are part of the template's identity, so changing one produces a new template. To keep values out of the template name, also pass a `buildEnvRevision`. The values still reach the build steps like the clone credential, but only the revision names the template. Change the revision whenever the values change.
404
404
 
405
405
  `repoTemplateRef` computes the tagged ref for a spec without building anything — useful for pruning old sha tags with the E2B CLI.
406
406
 
@@ -155,7 +155,7 @@ const voice = new OpenAIRealtimeVoice()
155
155
  // Or initialize with specific configuration
156
156
  const voiceWithConfig = new OpenAIRealtimeVoice({
157
157
  apiKey: 'your-openai-api-key',
158
- model: 'gpt-5.1-realtime-preview-2024-12-17',
158
+ model: 'gpt-realtime-2.1-mini',
159
159
  speaker: 'alloy', // Default voice
160
160
  })
161
161
 
@@ -198,7 +198,7 @@ voice.connect()
198
198
 
199
199
  #### Constructor options
200
200
 
201
- **model** (`string`): The model ID to use for real-time voice interactions. (Default: `'gpt-5.1-realtime-preview-2024-12-17'`)
201
+ **model** (`string`): The model ID to use for real-time voice interactions. (Default: `'gpt-realtime-2.1-mini'`)
202
202
 
203
203
  **apiKey** (`string`): OpenAI API key. Falls back to OPENAI_API_KEY environment variable.
204
204
 
@@ -15,16 +15,35 @@ Gateways handle provider-specific logic for accessing language models:
15
15
  - URL construction for API endpoints
16
16
  - Language model instance creation
17
17
 
18
- Create custom gateways to support:
18
+ ## When to use custom gateways
19
19
 
20
- - Private or enterprise LLM deployments
21
- - Custom authentication schemes
22
- - Specialized routing logic
23
- - Gateway versioning with unique IDs
20
+ Use a custom gateway to connect Mastra to open-weight models that you run yourself, such as gpt-oss, Llama, Gemma, Mistral, Qwen, or DeepSeek. Self-hosting fits when:
21
+
22
+ - Your industry's rules don't allow sending prompts or customer data to a third-party API (HIPAA, GDPR, finance, defense)
23
+ - You make enough model calls that per-token API pricing costs more than running your own GPUs
24
+ - You've fine-tuned an open-weight model on internal data and want your agents to use it
25
+ - You need a model that only changes when you upgrade it, so a provider update can't break your prompts
26
+ - Your agents run offline, on air-gapped networks, on edge hardware, or in the same data center as your app
27
+
28
+ The gateway lists the models behind your endpoint, so they get typed model IDs and appear in the Studio model picker. It can also resolve credentials on every call, and you can [limit the Studio model picker](#showing-only-custom-gateways-in-studio) to your own models.
29
+
30
+ To call a single endpoint with an OpenAI-compatible API, you don't need a gateway: set `url` in the model config instead. Mastra doesn't read an API key from environment variables for a `url` model, so also set `apiKey` when the endpoint requires authentication. See [Use local models with Mastra](https://mastra.ai/models).
24
31
 
25
32
  ## Creating a Custom Gateway
26
33
 
27
- Implement `MastraModelGatewayInterface` for a plain object gateway, or extend `MastraModelGateway` when you want base class defaults.
34
+ Implement `MastraModelGatewayInterface` for a plain object gateway, or extend the `MastraModelGateway` base class.
35
+
36
+ ### Choose a plain object or a class
37
+
38
+ Both work the same way at runtime. The base class provides default `getId()`, `shouldEnable()`, `handlesModel()`, and `serializeForSpan()` methods, and Mastra applies the same defaults to a plain object that leaves them out.
39
+
40
+ Use a plain object when the gateway has fixed configuration and no state. Extend `MastraModelGateway` when the gateway:
41
+
42
+ - Takes options in its constructor, such as a base URL or API key
43
+ - Keeps private state, such as cached tokens
44
+ - Runs as several instances, such as one per region or version
45
+
46
+ The following example implements the interface with a plain object:
28
47
 
29
48
  ```typescript
30
49
  import { type MastraModelGatewayInterface, type ProviderConfig } from '@mastra/core/llm';
@@ -50,35 +69,43 @@ const myPrivateGateway: MastraModelGatewayInterface = {
50
69
  async getApiKey() {
51
70
  return process.env.MY_API_KEY ?? '';
52
71
  },
53
- async resolveLanguageModel({ modelId, providerId, apiKey }) {
72
+ async resolveLanguageModel({ modelId, providerId, apiKey, headers }) {
54
73
  return createOpenAICompatible({
55
74
  name: providerId,
56
75
  apiKey,
76
+ headers,
57
77
  baseURL: 'https://api.myprovider.com/v1',
58
78
  }).chatModel(modelId);
59
79
  },
60
80
  };
61
81
  ```
62
82
 
63
- The following example extends the `MastraModelGateway` class:
83
+ The following example extends `MastraModelGateway` and takes its ID, base URL, and API key as constructor options:
64
84
 
65
85
  ```typescript
66
- import { MastraModelGateway, type ProviderConfig } from '@mastra/core/llm';
86
+ import { MastraModelGateway, type GatewayLanguageModel, type ProviderConfig } from '@mastra/core/llm';
67
87
  import { createOpenAICompatible } from '@ai-sdk/openai-compatible-v5';
68
- import type { LanguageModelV2 } from '@ai-sdk/provider-v5';
69
88
 
70
- class MyPrivateGateway extends MastraModelGateway {
71
- // Required: Unique identifier for the gateway
72
- // This ID is used as the prefix for all providers from this gateway
73
- readonly id = 'private';
89
+ interface MyPrivateGatewayOptions {
90
+ id?: string;
91
+ baseURL?: string;
92
+ apiKey?: string;
93
+ }
74
94
 
75
- // Required: Human-readable name
95
+ class MyPrivateGateway extends MastraModelGateway {
96
+ readonly id: string;
76
97
  readonly name = 'My Private Gateway';
77
98
 
78
- /**
79
- * Fetch provider configurations from your gateway
80
- * Returns a record of provider configurations
81
- */
99
+ private readonly baseURL: string;
100
+ private readonly apiKey?: string;
101
+
102
+ constructor(options: MyPrivateGatewayOptions = {}) {
103
+ super();
104
+ this.id = options.id ?? 'private';
105
+ this.baseURL = options.baseURL ?? 'https://api.myprovider.com/v1';
106
+ this.apiKey = options.apiKey;
107
+ }
108
+
82
109
  async fetchProviders(): Promise<Record<string, ProviderConfig>> {
83
110
  return {
84
111
  'my-provider': {
@@ -86,57 +113,60 @@ class MyPrivateGateway extends MastraModelGateway {
86
113
  models: ['openai/gpt-6.1-sol', 'anthropic/claude-sonnet-5-5'],
87
114
  apiKeyEnvVar: 'MY_API_KEY',
88
115
  gateway: this.id,
89
- url: 'https://api.myprovider.com/v1',
116
+ url: this.baseURL,
90
117
  },
91
118
  };
92
119
  }
93
120
 
94
- /**
95
- * Build the API URL for a model
96
- * @param modelId - Full model ID (e.g., "private/my-provider/model-1")
97
- * @param envVars - Environment variables (optional)
98
- */
99
- buildUrl(modelId: string, envVars?: Record<string, string>): string {
100
- return 'https://api.myprovider.com/v1';
121
+ buildUrl(): string {
122
+ return this.baseURL;
101
123
  }
102
124
 
103
- /**
104
- * Get the API key for authentication
105
- * @param modelId - Full model ID
106
- */
107
- async getApiKey(modelId: string): Promise<string> {
108
- const apiKey = process.env.MY_API_KEY;
125
+ async getApiKey(): Promise<string> {
126
+ const apiKey = this.apiKey ?? process.env.MY_API_KEY;
109
127
  if (!apiKey) {
110
- throw new Error(`Missing MY_API_KEY environment variable`);
128
+ throw new Error('Missing MY_API_KEY environment variable');
111
129
  }
112
130
  return apiKey;
113
131
  }
114
132
 
115
- /**
116
- * Create a language model instance
117
- * @param args - Model ID, provider ID, and API key
118
- */
119
- async resolveLanguageModel({
133
+ resolveLanguageModel({
120
134
  modelId,
121
135
  providerId,
122
136
  apiKey,
137
+ headers,
123
138
  }: {
124
139
  modelId: string;
125
140
  providerId: string;
126
141
  apiKey: string;
127
- }): Promise<LanguageModelV2> {
128
- const baseURL = this.buildUrl(`${providerId}/${modelId}`);
129
-
142
+ headers?: Record<string, string>;
143
+ }): GatewayLanguageModel {
130
144
  return createOpenAICompatible({
131
145
  name: providerId,
132
146
  apiKey,
133
- baseURL,
147
+ headers,
148
+ baseURL: this.baseURL,
134
149
  supportsStructuredOutputs: true,
135
150
  }).chatModel(modelId);
136
151
  }
137
152
  }
138
153
  ```
139
154
 
155
+ To run one instance per endpoint, give each instance its own `id`. Mastra keeps only the first gateway registered with a given ID, and the ID is the model ID prefix:
156
+
157
+ ```typescript
158
+ import { Mastra } from '@mastra/core';
159
+
160
+ const mastra = new Mastra({
161
+ gateways: {
162
+ privateEu: new MyPrivateGateway({ id: 'private-eu', baseURL: 'https://eu.api.myprovider.com/v1' }),
163
+ privateUs: new MyPrivateGateway({ id: 'private-us', baseURL: 'https://us.api.myprovider.com/v1' }),
164
+ },
165
+ });
166
+
167
+ // Models: 'private-eu/my-provider/openai/gpt-6.1-sol' and 'private-us/my-provider/openai/gpt-6.1-sol'
168
+ ```
169
+
140
170
  ### Gateway-owned authentication
141
171
 
142
172
  Add `resolveAuth` when the gateway owns credential lookup. Mastra uses this hook before falling back to `getApiKey()`.
@@ -625,7 +655,7 @@ By default, **Studio** lists every external model provider (such as OpenAI, Anth
625
655
  AUTO_BLOCK_EXTERNAL_PROVIDERS=true
626
656
  ```
627
657
 
628
- When this variable is set to `true` or `1`, Mastra returns only the providers from gateways you register yourself. The static provider registry and the built-in gateways (`models.dev`, `netlify`, and `mastra`) are hidden from the model picker. This is useful when you route all model traffic through a single private gateway and don't want the other providers to appear.
658
+ When this variable is set to `true` or `1`, Mastra returns only the providers from gateways you register yourself. The static provider registry and the built-in gateways (`models.dev`, `netlify`, and `mastra`) are hidden from the model picker. This is useful when you route all model traffic through a single private gateway and don't want the other providers to appear. The filter applies to the server's `GET /agents/providers` endpoint, which Studio uses for the model picker, so API clients don't see the external providers either. It only changes which providers are listed. It doesn't stop agents from calling other providers in code.
629
659
 
630
660
  With this variable set and no custom gateway registered, the model picker is empty. Register at least one custom gateway to expose its models.
631
661
 
@@ -178,7 +178,7 @@ const result = await agent.generate('message for agent')
178
178
 
179
179
  **options.clientTools** (`ToolsInput`): Client-side tools available during execution.
180
180
 
181
- **options.hooks** (`ToolHooks`): Per-execution hooks that run before and after tool calls. Overrides matching agent-level hooks for this execution. beforeToolCall can return { proceed: false, output } to skip the tool call.
181
+ **options.hooks** (`ToolHooks`): Per-execution hooks that run before and after tool calls, for example to log or save audit records. afterToolCall: (context) => void | Promise\<void> receives toolName, input, and output or error. beforeToolCall can return { proceed: false, output } to skip the tool call. Overrides matching agent-level hooks for this execution. See Run logic around tool calls.
182
182
 
183
183
  **options.savePerStep** (`boolean`): Save messages incrementally after each generation step completes (default: false). Disabled internally when observational memory is enabled.
184
184
 
@@ -30,23 +30,11 @@ Scorer judges with legacy model adapters call `generateLegacy()`. They don't rec
30
30
 
31
31
  **options.context** (`CoreMessage[]`): Additional context messages to provide to the agent.
32
32
 
33
- **options.structuredOutput** (`StructuredOutputOptions<S extends ZodTypeAny = ZodTypeAny>`): Enables structured output generation with better developer experience. Automatically creates and uses a StructuredOutputProcessor internally.
34
-
35
- **options.structuredOutput.schema** (`z.ZodSchema<S>`): Zod schema to validate the output against.
36
-
37
- **options.structuredOutput.model** (`MastraLanguageModel`): Model to use for the internal structuring agent.
38
-
39
- **options.structuredOutput.errorStrategy** (`'strict' | 'warn' | 'fallback'`): Strategy when parsing or validation fails. Defaults to 'strict'.
40
-
41
- **options.structuredOutput.fallbackValue** (`<S extends ZodTypeAny>`): Fallback value when errorStrategy is 'fallback'.
42
-
43
- **options.structuredOutput.instructions** (`string`): Custom instructions for the structuring agent.
44
-
45
33
  **options.outputProcessors** (`Processor[]`): Overrides the output processors set on the agent. Output processors that can modify or validate messages from the agent before they are returned to the user. Must implement either (or both) of the processOutputResult and processOutputStream functions.
46
34
 
47
35
  **options.inputProcessors** (`Processor[]`): Overrides the input processors set on the agent. Input processors that can modify or validate messages before they are processed by the agent. Must implement the processInput function.
48
36
 
49
- **options.experimental_output** (`Zod schema | JsonSchema7`): Note, the preferred route is to use the structuredOutput property. Enables structured output generation alongside text generation and tool calls. The model will generate responses that conform to the provided schema.
37
+ **options.experimental_output** (`Zod schema | JsonSchema7`): Enables structured output generation alongside text generation and tool calls. The model will generate responses that conform to the provided schema.
50
38
 
51
39
  **options.instructions** (`string`): Custom instructions that override the agent's default instructions for this specific generation. Useful for dynamically modifying agent behavior without creating a new agent instance.
52
40
 
@@ -120,7 +108,7 @@ Scorer judges with legacy model adapters call `generateLegacy()`. They don't rec
120
108
 
121
109
  **text** (`string`): The generated text response. Present when output is 'text' (no schema provided).
122
110
 
123
- **object** (`object`): The generated structured response. Present when a schema is provided via output, structuredOutput, or experimental_output.
111
+ **object** (`object`): The generated structured response when a schema is provided via output or experimental_output. With experimental_output, it may be undefined when generation finishes with a reason other than stop.
124
112
 
125
113
  **toolCalls** (`Array<ToolCall>`): The tool calls made during the generation process. Present in both text and object modes.
126
114
 
@@ -191,15 +179,11 @@ await agent.generateLegacy(
191
179
  reasoningEffort: 'high',
192
180
  },
193
181
  },
194
- // Structured output with better DX
195
- structuredOutput: {
196
- schema: z.object({
197
- sentiment: z.enum(['positive', 'negative', 'neutral']),
198
- confidence: z.number(),
199
- }),
200
- model: 'openai/gpt-6.1-sol',
201
- errorStrategy: 'warn',
202
- },
182
+ // Structured output alongside tool calls
183
+ experimental_output: z.object({
184
+ sentiment: z.enum(['positive', 'negative', 'neutral']),
185
+ confidence: z.number(),
186
+ }),
203
187
  // Output processors for response validation
204
188
  outputProcessors: [
205
189
  new ModerationProcessor({ model: 'openai/gpt-6-luna' }),
@@ -4,7 +4,7 @@
4
4
 
5
5
  # MastraJwtAuth class
6
6
 
7
- The `MastraJwtAuth` class provides a lightweight authentication mechanism for Mastra using JSON Web Tokens (JWTs). It verifies incoming requests based on a shared secret and integrates with the Mastra server using the `auth` option.
7
+ The `MastraJwtAuth` class provides a lightweight authentication mechanism for Mastra using JSON Web Tokens (JWTs). It verifies incoming requests with a shared secret or with the public keys from a JSON Web Key Set (JWKS) endpoint, and integrates with the Mastra server using the `auth` option.
8
8
 
9
9
  ## Usage example
10
10
 
@@ -21,9 +21,33 @@ export const mastra = new Mastra({
21
21
  })
22
22
  ```
23
23
 
24
+ To verify tokens signed by an identity provider, pass its JWKS URL and issuer instead of a secret:
25
+
26
+ ```typescript
27
+ import { Mastra } from '@mastra/core'
28
+ import { MastraJwtAuth } from '@mastra/auth'
29
+
30
+ export const mastra = new Mastra({
31
+ server: {
32
+ auth: new MastraJwtAuth({
33
+ jwksUri: 'https://auth.example.com/.well-known/jwks.json',
34
+ issuer: 'https://auth.example.com/',
35
+ }),
36
+ },
37
+ })
38
+ ```
39
+
24
40
  ## Constructor parameters
25
41
 
26
- **secret** (`string`): A unique string used to sign and verify JSON Web Tokens (JWTs) for authenticating incoming requests. Falls back to JWT_AUTH_SECRET when omitted. The resolved secret must be non-empty: the constructor throws an error if neither is set, or if this option is an empty string (an empty string does not fall back to JWT_AUTH_SECRET). (Default: `process.env.JWT_AUTH_SECRET`)
42
+ **secret** (`string`): A unique string used to sign and verify JSON Web Tokens (JWTs) for authenticating incoming requests. Falls back to JWT_AUTH_SECRET when omitted. Either a secret or jwksUri is required: the constructor throws an error if neither is set, or if this option is an empty string (an empty string does not fall back to JWT_AUTH_SECRET). (Default: `process.env.JWT_AUTH_SECRET`)
43
+
44
+ **jwksUri** (`string`): URL of a JWKS endpoint. Tokens are verified with the public key matching their kid header, using the algorithm of that key. Keys are cached, and fetches for unknown key IDs are limited to 10 per minute. Falls back to JWT_AUTH_JWKS_URI. Not combinable with secret: the constructor throws if both options are set, or if both JWT_AUTH_SECRET and JWT_AUTH_JWKS_URI are set. An explicit option wins over the environment variable for the other option, so jwksUri ignores JWT_AUTH_SECRET and secret ignores JWT_AUTH_JWKS_URI. (Default: `process.env.JWT_AUTH_JWKS_URI`)
45
+
46
+ **issuer** (`string`): Expected iss claim. Tokens from another issuer are rejected. The built-in MCP server also advertises it as the authorization server in its OAuth metadata. Falls back to JWT_AUTH_ISSUER. (Default: `process.env.JWT_AUTH_ISSUER`)
47
+
48
+ **mapUser** (`(payload: JwtPayload) => User | null`): Maps the verified token payload to the user returned by getCurrentUser(). Defaults to reading sub or id, email, name, and avatarUrl, avatar_url, or picture.
49
+
50
+ When the built-in MCP server's `server.mcp.oauth.resource` is set, `MastraJwtAuth` also requires the token's `aud` claim to include that URL on `/api/mcp`.
27
51
 
28
52
  ## Related
29
53
 
@@ -1880,26 +1880,94 @@ curl -sS "https://observability.mastra.ai/api/observability/traces/<trace-id>/sp
1880
1880
 
1881
1881
  #### `mastra api score create`
1882
1882
 
1883
- Creates an observability score. The input uses the server score body shape. Inspect it with `--schema`.
1883
+ Creates a score for a trace. Wrap the record in `score` with a required `traceId` and an optional `spanId`. The CLI generates an ID and timestamp when omitted and preserves them across retries. Pass `--schema` to inspect the request fields.
1884
1884
 
1885
1885
  ```bash
1886
- mastra api score create <input>
1886
+ mastra api score create '{"score":{"traceId":"trace_123","scorerId":"quality","score":0.95}}'
1887
1887
  ```
1888
1888
 
1889
+ Score and feedback creates accept an optional top-level `contextMode`. Use `"resolve"` to look up context from a stored trace or span, or `"provided"` to write the fields you supply without a lookup. When you omit `contextMode`, OSS uses `provided` and Platform uses `resolve`, regardless of any context fields you supply.
1890
+
1891
+ Successful writes on Platform mean the record is accepted for storage and may not be readable immediately. Output preserves the server's success response and any returned ID and timestamp. Older servers may return only `success`.
1892
+
1889
1893
  #### `mastra api score list`
1890
1894
 
1891
- Lists observability scores. Pass optional JSON input for filters such as run ID or pagination.
1895
+ Lists scores with optional filters and pagination.
1892
1896
 
1893
1897
  ```bash
1894
- mastra api score list [input]
1898
+ mastra api score list '{"traceId":"trace_123","page":0,"perPage":50}'
1895
1899
  ```
1896
1900
 
1897
1901
  #### `mastra api score get`
1898
1902
 
1899
- Gets one observability score by ID.
1903
+ Gets a score by ID. Missing scores return `{"data":{"score":null}}`.
1904
+
1905
+ ```bash
1906
+ mastra api score get score_123
1907
+ ```
1908
+
1909
+ #### `mastra api feedback create`
1910
+
1911
+ Creates feedback for a trace or span. Wrap the record in `feedback`. Feedback requires `traceId`, with IDs and timestamps generated when omitted.
1912
+
1913
+ ```bash
1914
+ mastra api feedback create '{"contextMode":"resolve","feedback":{"traceId":"trace_123","feedbackType":"comment","feedbackSource":"user","value":"actionable","feedbackUserId":"reviewer_123"}}'
1915
+ ```
1916
+
1917
+ `feedbackUserId` identifies the feedback author. `userId` describes the trace or span context and is separate from the author.
1918
+
1919
+ #### `mastra api feedback list`
1920
+
1921
+ Lists feedback with optional filters and pagination.
1922
+
1923
+ ```bash
1924
+ mastra api feedback list '{"traceId":"trace_123","reviewStatus":"needs-review","page":0,"perPage":50}'
1925
+ ```
1926
+
1927
+ #### `mastra api feedback get`
1928
+
1929
+ Gets feedback by ID. Missing feedback returns `{"data":{"feedback":null}}`.
1930
+
1931
+ ```bash
1932
+ mastra api feedback get feedback_123
1933
+ ```
1934
+
1935
+ #### `mastra api feedback replace`
1936
+
1937
+ Replaces the full feedback record. Send the original `feedbackId`, `traceId`, and `timestamp`, along with the complete replacement. Copy the timestamp from the create response or a subsequent read. The ID in the argument must match the body. Scores don't support replacement.
1938
+
1939
+ ```bash
1940
+ mastra api feedback replace feedback_123 '{"feedback":{"feedbackId":"feedback_123","traceId":"trace_123","timestamp":"2026-11-11T10:00:00.123Z","feedbackType":"comment","feedbackSource":"user","value":"corrected"}}'
1941
+ ```
1942
+
1943
+ Creates and replacements retry missing trace/span responses and transient failures within the command timeout, for at most six attempts or 30 seconds. Each accepted replacement retry counts as a new replacement. Older servers without PUT support return an error.
1944
+
1945
+ #### `mastra api feedback review-status`
1946
+
1947
+ Changes only the review status to `needs-review` or `reviewed`. No timestamp is required. Missing feedback returns an error, including records still waiting to be stored on Platform.
1948
+
1949
+ ```bash
1950
+ mastra api feedback review-status feedback_123 '{"reviewStatus":"reviewed"}'
1951
+ ```
1952
+
1953
+ #### Score and feedback analytics
1954
+
1955
+ Both command groups expose `aggregate`, `breakdown`, `timeseries`, and `percentiles` for numeric values. Select scores by `scorerId` and feedback by `feedbackType`. Use `--schema` on an operation to inspect its filters and options.
1956
+
1957
+ ```bash
1958
+ mastra api score aggregate '{"scorerId":"quality","aggregation":"avg"}'
1959
+ mastra api score breakdown '{"scorerId":"quality","aggregation":"avg","groupBy":["entityName"]}'
1960
+ mastra api feedback timeseries '{"feedbackType":"rating","aggregation":"avg","interval":"1d"}'
1961
+ mastra api feedback percentiles '{"feedbackType":"rating","percentiles":[0.5,0.95],"interval":"1d"}'
1962
+ ```
1963
+
1964
+ #### Score and feedback deletion
1965
+
1966
+ Deletes records by ID. Platform returns `accepted: true` when cleanup is queued. OSS returns `success` after deletion.
1900
1967
 
1901
1968
  ```bash
1902
- mastra api score get <scoreId>
1969
+ mastra api score delete '{"scoreIds":["score_123"]}'
1970
+ mastra api feedback delete '{"feedbackIds":["feedback_123"]}'
1903
1971
  ```
1904
1972
 
1905
1973
  #### `mastra api dataset list`
@@ -371,11 +371,17 @@ const result = await mastraClient.deleteTraces({
371
371
  traceIds: ['trace-1', 'trace-2'],
372
372
  })
373
373
 
374
- console.log(result.success)
374
+ if ('accepted' in result) {
375
+ console.log('Deletion requested')
376
+ } else {
377
+ console.log(result.success)
378
+ }
375
379
  ```
376
380
 
377
381
  Each request accepts up to 1,000 trace IDs and no tenant scope fields. Signals that aren't linked to a trace are preserved. Traces created by experiments are deleted like any other trace.
378
382
 
383
+ The client supports two response shapes: OSS returns `{ success: true }` after its delete operation, while a Platform backend that supports queued batch deletion returns `202 { accepted: true }` after accepting cleanup. Acceptance doesn't mean records have disappeared from reads, so check the response before reporting deletion as complete. Using these client methods with Platform requires a deployment that supports the batch deletion endpoints.
384
+
379
385
  ## Scoring traces
380
386
 
381
387
  Score specific traces using registered scorers for evaluation:
@@ -432,7 +438,7 @@ const response = await mastraClient.createScore({
432
438
 
433
439
  ## Feedback
434
440
 
435
- Feedback methods create, list, and query human-in-the-loop signals such as ratings, thumbs, comments, and corrections through the configured API server. Create methods support OSS and Platform. Full replacement uses Platform's PUT endpoint. 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.
441
+ Feedback methods create, list, and query human-in-the-loop signals such as ratings, thumbs, comments, and corrections through the configured API server. Create methods support OSS and Platform. Full replacement is supported by Platform and OSS servers with feedback replacement support. 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.
436
442
 
437
443
  ### Get feedback by ID
438
444
 
@@ -492,9 +498,9 @@ Create responses contain `success` and optional `data` with the generated or sup
492
498
 
493
499
  Explicit modes require server support. Older servers may ignore `contextMode`. Deploy Platform's supplied-context support before sending `"provided"` there.
494
500
 
495
- ### Replacing feedback on Platform
501
+ ### Replacing feedback
496
502
 
497
- `replaceFeedback()` sends a full replacement to `PUT /api/observability/feedback/:feedbackId`. Include the original `feedbackId`, `traceId`, and normalized `timestamp`, along with all feedback fields to retain. This method targets Platform. OSS server doesn't implement this replacement endpoint.
503
+ `replaceFeedback()` sends a full replacement to `PUT /api/observability/feedback/:feedbackId`. Include the original `feedbackId`, `traceId`, and normalized `timestamp`, along with all feedback fields to retain. Platform and OSS servers with feedback replacement support accept this method. OSS returns `501` when its storage adapter doesn't support replacement. For OSS, check `capabilities.feedbackReplacement` before offering edits. A missing capability means unavailable.
498
504
 
499
505
  ```typescript
500
506
  await mastraClient.replaceFeedback({
@@ -509,7 +515,7 @@ await mastraClient.replaceFeedback({
509
515
  })
510
516
  ```
511
517
 
512
- Use the normalized timestamp from the create response's `data` when available. A changed timestamp identifies a different Platform record. The client preserves the replacement body across retries, but each accepted PUT retry is a new replacement and can supersede another edit. Pass `{ retries: 0, anchorRetryTimeoutMs: 0 }` as the second argument to disable automatic retries.
518
+ Use the normalized timestamp from the create response's `data` when available. OSS rejects changes to the original trace or timestamp with `409`. Platform uses the timestamp as part of record identity, so preserve it there too. The client preserves the replacement body across retries, but each accepted PUT retry is a new replacement and can supersede another edit. Pass `{ retries: 0, anchorRetryTimeoutMs: 0 }` as the second argument to disable automatic retries.
513
519
 
514
520
  ### Deleting feedback and scores
515
521
 
@@ -529,6 +535,8 @@ await mastraClient.deleteScores({
529
535
  })
530
536
  ```
531
537
 
538
+ Both methods return `{ success: boolean }` from OSS or `{ accepted: true }` from a Platform backend that supports queued batch deletion. See [Deleting traces](#deleting-traces) for response handling. Accepted records can remain readable until cleanup runs. Platform uses authenticated organization/project scope, which request-body scope fields can't override.
539
+
532
540
  ### Listing feedback
533
541
 
534
542
  Retrieve paginated feedback records with optional filters:
@@ -720,6 +720,70 @@ export const mastra = new Mastra({
720
720
  })
721
721
  ```
722
722
 
723
+ ### server.mcp
724
+
725
+ **Type:** `object`\
726
+ **Default:** `undefined`
727
+
728
+ Configures the [built-in MCP server](https://mastra.ai/docs/server/mcp) that exposes your agents, workflows, and tools at `/api/mcp`.
729
+
730
+ | Property | Type | Default | Description |
731
+ | ------------ | ----------------------------------------------------------------------------------------------------------------------- | ------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
732
+ | `enabled` | `boolean \| 'dev'` | `'dev'` | `'dev'` serves the endpoint under `mastra dev`, and in production only when `server.auth` is configured. `true` always serves it and logs a warning when no auth is configured. `false` never serves it. |
733
+ | `path` | `string` | `'/mcp'` | Path of the endpoint, mounted under the API prefix. Each segment can use letters, digits, `-`, `.`, `_`, and `~`. Invalid paths and paths that collide with the `MCPServer` routes or any other server route fall back to `/mcp` and log an error. |
734
+ | `toolsets` | `('agents' \| 'workflows' \| 'tools' \| 'memory' \| 'observability' \| 'observability_analytics' \| 'stored_agents')[]` | All toolsets | Toolsets to serve. Clients can narrow this per request with `?toolsets=` or the `X-MCP-Toolsets` header. |
735
+ | `enumLimit` | `number` | `25` | Up to this many visible agents or workflows are listed as an enum on the id argument, and up to this many tools get an individual `tool_<id>` tool. |
736
+ | `featured` | `{ agents?: string[]; workflows?: string[] }` | `undefined` | Agents and workflows that also get a dedicated `agent_<id>` or `workflow_<id>` tool. |
737
+ | `readOnly` | `boolean` | `false` | Only serve tools whose backing route is a read operation. Clients can also request this with `?readonly=1` or the `X-MCP-Readonly` header. |
738
+ | `include` | `{ agents?: string[]; workflows?: string[]; tools?: string[] }` | `undefined` | When set for a primitive type, only these are exposed. Each entry matches a primitive's `id` or its registration key. |
739
+ | `exclude` | `{ agents?: string[]; workflows?: string[]; tools?: string[] }` | `undefined` | Never exposed. Each entry matches a primitive's `id` or its registration key. Takes precedence over `include`. |
740
+ | `serverInfo` | `{ name?: string; version?: string; title?: string; instructions?: string }` | `undefined` | Server identity reported to MCP clients. |
741
+ | `oauth` | `{ resource?: string; requireAudience?: boolean; authorizationServers?: string[]; scopesSupported?: string[] }` | `undefined` | OAuth discovery and token audience settings. See [`server.mcp.oauth`](#servermcpoauth). |
742
+
743
+ ```typescript
744
+ import { Mastra } from '@mastra/core'
745
+
746
+ export const mastra = new Mastra({
747
+ server: {
748
+ mcp: {
749
+ featured: { agents: ['support-agent'] },
750
+ exclude: { tools: ['delete-account'] },
751
+ },
752
+ },
753
+ })
754
+ ```
755
+
756
+ ### server.mcp.oauth
757
+
758
+ **Type:** `object`\
759
+ **Default:** `undefined`
760
+
761
+ OAuth protected-resource metadata for the [built-in MCP server](https://mastra.ai/docs/server/mcp). Used when `server.auth` is configured.
762
+
763
+ | Property | Type | Default | Description |
764
+ | ---------------------- | ---------- | ------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
765
+ | `resource` | `string` | Endpoint URL derived from the request | Canonical public URL of the MCP endpoint, for example `https://my-app.example.com/api/mcp`. Setting it also requires the token's `aud` claim to include this URL on `/api/mcp`, for auth providers that support audience checks. |
766
+ | `requireAudience` | `boolean` | `false` | Requires `resource`. Rejects MCP requests with a `401` when the auth provider that accepted the token can't check the audience, including such providers inside `CompositeAuth`. When `false`, those requests are accepted and Mastra logs a warning at startup. |
767
+ | `authorizationServers` | `string[]` | From the auth provider | Issuer URLs of the authorization servers that MCP clients get tokens from. |
768
+ | `scopesSupported` | `string[]` | From the auth provider | OAuth scopes advertised to MCP clients. Left out of the metadata when unset. |
769
+
770
+ ```typescript
771
+ import { Mastra } from '@mastra/core'
772
+ import { MastraJwtAuth } from '@mastra/auth'
773
+
774
+ export const mastra = new Mastra({
775
+ server: {
776
+ auth: new MastraJwtAuth({
777
+ jwksUri: 'https://auth.example.com/.well-known/jwks.json',
778
+ issuer: 'https://auth.example.com/',
779
+ }),
780
+ mcp: {
781
+ oauth: { resource: 'https://my-app.example.com/api/mcp' },
782
+ },
783
+ },
784
+ })
785
+ ```
786
+
723
787
  ### server.mcpOptions
724
788
 
725
789
  **Type:** `object`\