@mastra/mcp-docs-server 1.3.13-alpha.15 → 1.3.13-alpha.17

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 (30) hide show
  1. package/.docs/docs/auth/custom-auth-provider.md +66 -0
  2. package/.docs/docs/auth/jwt.md +1 -1
  3. package/.docs/docs/connections/mcp.md +2 -65
  4. package/.docs/docs/memory/multi-user-threads.md +57 -127
  5. package/.docs/docs/memory/observational-memory.md +196 -756
  6. package/.docs/docs/memory/overview.md +4 -0
  7. package/.docs/docs/server/mcp.md +315 -0
  8. package/.docs/docs/server/request-context.md +35 -0
  9. package/.docs/docs/studio/deployment.md +0 -1
  10. package/.docs/docs/studio/overview.md +4 -4
  11. package/.docs/integrations/voice/openai.md +2 -2
  12. package/.docs/models/gateways/custom-gateways.md +74 -44
  13. package/.docs/reference/auth/jwt.md +26 -2
  14. package/.docs/reference/configuration.md +64 -0
  15. package/.docs/reference/index.md +1 -0
  16. package/.docs/reference/memory/observational-memory.md +350 -151
  17. package/.docs/reference/observability/tracing/advanced-queries.md +2 -1
  18. package/.docs/reference/observability/tracing/spans.md +7 -1
  19. package/.docs/reference/rag/chunk.md +1 -1
  20. package/.docs/reference/rag/graph-rag-guide.md +3 -1
  21. package/.docs/reference/server/dispatch-route.md +124 -0
  22. package/.docs/reference/server/elysia-adapter.md +1 -1
  23. package/.docs/reference/server/express-adapter.md +1 -1
  24. package/.docs/reference/server/fastify-adapter.md +1 -1
  25. package/.docs/reference/server/hono-adapter.md +1 -1
  26. package/.docs/reference/server/invoke-route.md +10 -0
  27. package/.docs/reference/server/koa-adapter.md +1 -1
  28. package/.docs/reference/server/nestjs-adapter.md +1 -1
  29. package/.docs/reference/workspace/factory-sandbox.md +4 -1
  30. package/package.json +3 -3
@@ -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
 
@@ -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
 
@@ -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`\
@@ -330,6 +330,7 @@ The Reference section provides documentation of Mastra's API, including paramete
330
330
  - [.chunk()](https://mastra.ai/reference/rag/chunk)
331
331
  - [Overview](https://mastra.ai/reference/schedules/overview)
332
332
  - [createRoute()](https://mastra.ai/reference/server/create-route)
333
+ - [dispatchRoute()](https://mastra.ai/reference/server/dispatch-route)
333
334
  - [Elysia Adapter](https://mastra.ai/reference/server/elysia-adapter)
334
335
  - [Express Adapter](https://mastra.ai/reference/server/express-adapter)
335
336
  - [Fastify Adapter](https://mastra.ai/reference/server/fastify-adapter)