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

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 (68) hide show
  1. package/.docs/docs/agents/code-mode.md +4 -0
  2. package/.docs/docs/agents/tools.md +12 -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/guides/authentication-identity.md +13 -1
  8. package/.docs/docs/harness/schedules.md +1 -1
  9. package/.docs/docs/knowledge/scopes-and-access.md +1 -1
  10. package/.docs/docs/memory/multi-user-threads.md +57 -127
  11. package/.docs/docs/memory/observational-memory.md +196 -756
  12. package/.docs/docs/memory/overview.md +4 -0
  13. package/.docs/docs/observability/feedback.md +5 -7
  14. package/.docs/docs/sandbox/overview.md +2 -0
  15. package/.docs/docs/sandbox/search.md +25 -0
  16. package/.docs/docs/server/mcp.md +347 -0
  17. package/.docs/docs/server/overview.md +1 -0
  18. package/.docs/docs/server/request-context.md +35 -0
  19. package/.docs/docs/server/server-adapters.md +2 -0
  20. package/.docs/docs/studio/auth.md +5 -1
  21. package/.docs/docs/studio/deployment.md +0 -1
  22. package/.docs/docs/studio/editor.md +17 -0
  23. package/.docs/docs/studio/overview.md +5 -5
  24. package/.docs/docs/workflows/scheduled-workflows.md +26 -5
  25. package/.docs/integrations/sandboxes/docker.md +39 -0
  26. package/.docs/integrations/sandboxes/e2b.md +1 -1
  27. package/.docs/integrations/voice/openai.md +2 -2
  28. package/.docs/models/gateways/custom-gateways.md +74 -44
  29. package/.docs/reference/agents/generate.md +1 -1
  30. package/.docs/reference/agents/generateLegacy.md +7 -23
  31. package/.docs/reference/auth/auth0.md +2 -0
  32. package/.docs/reference/auth/clerk.md +4 -0
  33. package/.docs/reference/auth/jwt.md +30 -2
  34. package/.docs/reference/cli/mastra.md +74 -6
  35. package/.docs/reference/client-js/observability.md +13 -5
  36. package/.docs/reference/configuration.md +64 -0
  37. package/.docs/reference/connect/tools.md +59 -0
  38. package/.docs/reference/editor/mastra-editor.md +1 -1
  39. package/.docs/reference/index.md +2 -0
  40. package/.docs/reference/knowledge/knowledge-class.md +1 -1
  41. package/.docs/reference/knowledge/knowledge-memory-scopes.md +44 -4
  42. package/.docs/reference/knowledge/scope-declarations.md +7 -3
  43. package/.docs/reference/memory/observational-memory.md +350 -151
  44. package/.docs/reference/observability/feedback.md +57 -14
  45. package/.docs/reference/observability/tracing/advanced-queries.md +3 -1
  46. package/.docs/reference/observability/tracing/exporters/langfuse.md +24 -1
  47. package/.docs/reference/observability/tracing/exporters/mastra-platform-exporter.md +19 -16
  48. package/.docs/reference/observability/tracing/exporters/otel.md +1 -1
  49. package/.docs/reference/observability/tracing/interfaces.md +2 -2
  50. package/.docs/reference/observability/tracing/spans.md +7 -1
  51. package/.docs/reference/processors/processor-interface.md +23 -0
  52. package/.docs/reference/rag/chunk.md +1 -1
  53. package/.docs/reference/rag/graph-rag-guide.md +3 -1
  54. package/.docs/reference/schedules/overview.md +25 -5
  55. package/.docs/reference/server/builtin-mcp-tools.md +135 -0
  56. package/.docs/reference/server/dispatch-route.md +124 -0
  57. package/.docs/reference/server/elysia-adapter.md +1 -1
  58. package/.docs/reference/server/express-adapter.md +17 -11
  59. package/.docs/reference/server/fastify-adapter.md +1 -1
  60. package/.docs/reference/server/hono-adapter.md +1 -1
  61. package/.docs/reference/server/invoke-route.md +10 -0
  62. package/.docs/reference/server/koa-adapter.md +1 -1
  63. package/.docs/reference/server/nestjs-adapter.md +1 -1
  64. package/.docs/reference/streaming/agents/stream.md +1 -1
  65. package/.docs/reference/tools/mcp-server.md +2 -0
  66. package/.docs/reference/workspace/factory-sandbox.md +20 -1
  67. package/.docs/reference/workspace/platform-sandbox.md +1 -1
  68. package/package.json +5 -5
@@ -55,6 +55,8 @@ Chat with your agent directly, switch [models](https://mastra.ai/models), and tw
55
55
 
56
56
  Model pickers show newer releases first within each provider when the catalog includes release dates. Models with the same release date, or without a release date, use alphabetical order. Models without dates appear after dated models.
57
57
 
58
+ To limit the model picker to models from your own [custom gateways](https://mastra.ai/models/gateways/custom-gateways), set `AUTO_BLOCK_EXTERNAL_PROVIDERS=true`. See [Showing only custom gateways in Studio](https://mastra.ai/models/gateways/custom-gateways).
59
+
58
60
  When you interact with your agent, you can follow its reasoning and view tool call outputs. You can also [observe](#observability) traces and logs to see how responses are generated.
59
61
 
60
62
  For a markdown table in a response, select **Copy table as markdown** above the table to copy it without the surrounding message. The copied table preserves markdown formatting and includes any link and footnote definitions it uses. To download the table as CSV, open the arrow beside the copy button and select **Download CSV**. Both actions become available once the text segment containing the table finishes streaming and displaying. The agent may still be running tools or writing later segments.
@@ -85,7 +87,7 @@ Visualize your workflow as a graph and run it step by step with a custom input.
85
87
 
86
88
  Workflow traces show tool calls and raw JSON outputs, along with any execution errors.
87
89
 
88
- Select **Run Options** beside the run button to set a **Resource ID** for the runs you start. Studio remembers the value per workflow, and the runs it creates are listed by `GET /api/workflows/:workflowId/runs?resourceId=...`. Leave it empty to create runs without a resource. When your server derives the resource ID from the authenticated user, that value takes precedence over the one you type.
90
+ Select **Run options** beside the run button to set a **Resource ID** for the runs you start. Studio remembers the value per workflow, and the runs it creates are listed by `GET /api/workflows/:workflowId/runs?resourceId=...`. Leave it empty to create runs without a resource. When your server derives the resource ID from the authenticated user, that value takes precedence over the one you type.
89
91
 
90
92
  ### Processors
91
93
 
@@ -95,7 +97,7 @@ See [processors](https://mastra.ai/docs/agents/processors) and [guardrails](http
95
97
 
96
98
  ### MCP servers
97
99
 
98
- List the MCP servers attached to your Mastra instance and explore their available tools.
100
+ List the MCP servers attached to your Mastra instance and explore their available tools. The list starts with **Mastra (built-in)**, the [built-in MCP server](https://mastra.ai/docs/server/mcp) at `/api/mcp`, with its endpoint URL, whether it needs a token, and setup for Claude Code, Cursor, VS Code, and the MCP Inspector.
99
101
 
100
102
  ### Tools
101
103
 
@@ -103,7 +105,7 @@ Run tools on their own to observe behavior and test them before assigning them t
103
105
 
104
106
  ### Workspaces
105
107
 
106
- Browse the files in your agent's workspace filesystem using a built-in file browser. Switch between workspace mounts, create directories, and view file contents with syntax highlighting. Writable workspaces allow directory creation and file deletion; read-only workspaces are labeled accordingly. The Skills tab lists all discovered skills with their instructions, references, and metadata. Install community skills from [skills.sh](https://skills.sh) or remove existing ones.
108
+ Browse the files in your agent's workspace filesystem using a built-in file browser. Switch between workspace mounts, create directories, and view file contents with syntax highlighting. Writable workspaces allow directory creation and file deletion; read-only workspaces are labeled accordingly. Skills appear in the file tree. Install community skills from [skills.sh](https://skills.sh), update installed skills, or delete a skill folder to remove that skill.
107
109
 
108
110
  See [workspaces](https://mastra.ai/docs/sandbox/overview) for configuration details.
109
111
 
@@ -115,8 +117,6 @@ See [request context](https://mastra.ai/docs/server/request-context) for configu
115
117
 
116
118
  ## Evaluation
117
119
 
118
- Use the date filter to limit score metrics to a preset or custom time range.
119
-
120
120
  ### Scorers
121
121
 
122
122
  The Scorers tab displays the results of your agent's scorers as they run. When messages pass through your agent, the defined scorers evaluate each output asynchronously and render their results here. You can understand how your scorers respond to different interactions and compare performance across test cases, plus identify areas for improvement.
@@ -74,13 +74,29 @@ const dailyReport = createWorkflow({
74
74
 
75
75
  Fields:
76
76
 
77
- - `cron` (required): a 5-, 6-, or 7-part cron expression. Validated at workflow construction time.
77
+ - `cron`: a 5-, 6-, or 7-part cron expression. Validated at workflow construction time. Provide exactly one of `cron` or `runAt`.
78
+ - `runAt` (optional): fire once at this time (epoch milliseconds or `Date`) instead of on a cron. After it fires, the schedule moves to `completed` and later deploys don't re-arm it unless you change `runAt`. A `runAt` that has already passed when the schedule is first registered is recorded as `completed` without firing.
79
+ - `endAt` (optional): only with `cron`. Stop firing after this time. The schedule moves to `completed` once its next occurrence would fall after `endAt`.
78
80
  - `timezone` (optional): IANA timezone, for example `America/New_York`. Defaults to the host's local timezone. Set this explicitly in production so fire times don't depend on server locale.
79
81
  - `inputData` (optional): payload passed as the workflow's input on every fire.
80
82
  - `initialState` (optional): initial state for the run.
81
83
  - `requestContext` (optional): request context attached to the run.
82
84
  - `metadata` (optional): arbitrary metadata persisted alongside the schedule row.
83
85
 
86
+ To run a workflow once at a fixed time, use `runAt`:
87
+
88
+ ```typescript
89
+ const launchAnnouncement = createWorkflow({
90
+ id: 'launch-announcement',
91
+ schedule: {
92
+ // Set this to a stable future ISO timestamp in your deployment environment.
93
+ runAt: new Date(process.env.LAUNCH_ANNOUNCEMENT_AT!),
94
+ inputData: { userId: 'system' },
95
+ },
96
+ // ...
97
+ })
98
+ ```
99
+
84
100
  ## Multiple schedules
85
101
 
86
102
  Pass an array to fire the same workflow on multiple cadences. Each entry needs a unique stable `id`:
@@ -147,8 +163,9 @@ In Studio, open the schedule detail page and select **Pause** or **Resume** in t
147
163
 
148
164
  A few rules to know:
149
165
 
150
- - Pause is durable. The status is written to the schedules table and survives process restarts and redeploys. The declarative-config upsert never overwrites a user-set status, even when you change `cron`, `timezone`, or other fields.
151
- - Resume recomputes `nextFireAt` from now. A schedule paused for a week doesn't fire seven backlogged runs the moment you resume it. It fires on the next regular cron tick.
166
+ - Pause is durable. The status is written to the schedules table and survives process restarts and redeploys. The declarative-config upsert never overwrites a user-set status, even when you change `cron`, `timezone`, `runAt`, `endAt`, or other fields.
167
+ - Resuming a cron schedule recomputes `nextFireAt` from now. A schedule paused for a week doesn't fire seven backlogged runs. It fires on the next regular cron tick.
168
+ - Resuming a one-off keeps its configured `runAt`. If that time passed while the schedule was paused, it fires on the next scheduler tick.
152
169
  - Unpause with `resumeSchedule` or the **Resume** button in Studio. Editing the workflow's `schedule` config doesn't unpause a paused row.
153
170
  - Pause and resume are idempotent. Calling pause on an already-paused schedule is a no-op.
154
171
  - This operational override controls existing schedules. Author declarative schedules in code. Declarative schedules are created, deleted, and edited in code via the `schedule` field on `createWorkflow`. To create schedules imperatively at runtime instead, use the unified [`mastra.schedules`](https://mastra.ai/docs/harness/schedules) service with a `workflowId`.
@@ -159,9 +176,13 @@ The underlying HTTP routes are `POST /api/schedules/:scheduleId/pause` and `POST
159
176
 
160
177
  When you change the `schedule` config and redeploy, Mastra diffs the existing schedule row against the new config:
161
178
 
162
- - If `cron` or `timezone` changed, `nextFireAt` is recomputed. A cadence with no future occurrence completes the schedule. A recomputed cadence that can still fire reactivates a completed schedule.
179
+ - If `cron`, `timezone`, or `endAt` changes on a recurring schedule, `nextFireAt` is recomputed. A cadence with no future occurrence completes the schedule. A recomputed cadence that can still fire reactivates a completed schedule.
180
+ - If `runAt` changes on a one-off schedule, `nextFireAt` is updated to that time. A future `runAt` reactivates a completed one-off. A past `runAt` leaves it completed.
181
+ - If an active one-off's unchanged `runAt` passed while the app was offline, it remains due and fires on the next scheduler tick. A one-off first registered with a past `runAt` is instead created as `completed` and doesn't fire.
163
182
  - If only `inputData`, `initialState`, or `metadata` changed, the row is patched in place and the next fire time is preserved.
164
- - User-set status (for example, paused via `client.pauseSchedule`) and fire history are never overwritten, unless the cadence change above requires a status update.
183
+ - User-set status (for example, paused via `client.pauseSchedule`) and fire history are never overwritten, unless a timing change above requires a status update.
184
+
185
+ The `completed` status means the schedule has no automatic fires remaining: its one-off fire was claimed, its recurring cadence was exhausted, or its configured timing was already exhausted during registration or reconciliation. It doesn't confirm that the workflow run completed successfully.
165
186
 
166
187
  Removing a schedule entry from a workflow's `schedule` array deletes its row on the next boot.
167
188
 
@@ -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' }),
@@ -72,6 +72,8 @@ The `Auth0User` type used in the `authorizeUser` function corresponds to the dec
72
72
 
73
73
  The exact properties available depend on your Auth0 configuration, scopes requested, and any custom claims you've configured.
74
74
 
75
+ The authenticated user's `id` is the token's `id` claim, or its `sub` claim when the token has no `id`. RBAC looks up roles by this `id`, and it owns the records the user creates unless `mapUserToResourceId` is set. See [user IDs from JWT providers](https://mastra.ai/docs/guides/authentication-identity).
76
+
75
77
  ## Related
76
78
 
77
79
  [MastraAuthAuth0 Class](https://mastra.ai/integrations/auth/auth0)
@@ -43,6 +43,10 @@ export const mastra = new Mastra({
43
43
  })
44
44
  ```
45
45
 
46
+ ## User ID
47
+
48
+ The authenticated user's `id` is the token's `id` claim, or its `sub` claim when the token has no `id`. RBAC looks up roles by this `id`, and it owns the records the user creates unless `mapUserToResourceId` is set. See [user IDs from JWT providers](https://mastra.ai/docs/guides/authentication-identity).
49
+
46
50
  ## Constructor parameters
47
51
 
48
52
  **publishableKey** (`string`): Your Clerk publishable key. Can be found in your Clerk Dashboard under API Keys. (Default: `process.env.CLERK_PUBLISHABLE_KEY`)
@@ -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,37 @@ 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
+
40
+ ## User ID
41
+
42
+ The authenticated user's `id` is the token's `id` claim, or its `sub` claim when the token has no `id`. RBAC looks up roles by this `id`, and it owns the records the user creates unless `mapUserToResourceId` is set. See [user IDs from JWT providers](https://mastra.ai/docs/guides/authentication-identity).
43
+
24
44
  ## Constructor parameters
25
45
 
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`)
46
+ **secret** (`string`): A unique string used to sign and verify JSON Web Tokens (JWTs) for authenticating incoming requests. Falls back to JWT_AUTH_SECRET when omitted. Either a secret or jwksUri is required: the constructor throws an error if neither is set, or if this option is an empty string (an empty string does not fall back to JWT_AUTH_SECRET). (Default: `process.env.JWT_AUTH_SECRET`)
47
+
48
+ **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`)
49
+
50
+ **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`)
51
+
52
+ **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.
53
+
54
+ 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
55
 
28
56
  ## Related
29
57
 
@@ -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`