@mastra/server 1.6.0 → 1.7.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 (48) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/dist/{chunk-P4O7OBGH.cjs → chunk-3BKGGOC6.cjs} +3 -3
  3. package/dist/{chunk-P4O7OBGH.cjs.map → chunk-3BKGGOC6.cjs.map} +1 -1
  4. package/dist/{chunk-CMYJ32N3.js → chunk-EFKPTKKF.js} +51 -15
  5. package/dist/chunk-EFKPTKKF.js.map +1 -0
  6. package/dist/{chunk-NC6UUX6D.js → chunk-KTGIAURI.js} +3 -2
  7. package/dist/chunk-KTGIAURI.js.map +1 -0
  8. package/dist/{chunk-NGFAF6WW.cjs → chunk-MJLQLQ6K.cjs} +51 -15
  9. package/dist/chunk-MJLQLQ6K.cjs.map +1 -0
  10. package/dist/{chunk-VHBLYGH7.js → chunk-PGB5HYV7.js} +3 -3
  11. package/dist/{chunk-VHBLYGH7.js.map → chunk-PGB5HYV7.js.map} +1 -1
  12. package/dist/{chunk-GPRCK7GP.cjs → chunk-ZE4IJKQD.cjs} +3 -2
  13. package/dist/chunk-ZE4IJKQD.cjs.map +1 -0
  14. package/dist/{observational-memory-ZNTAIUGT-565A3END.cjs → observational-memory-AJWSMZVP-HI6EWRCH.cjs} +29 -12
  15. package/dist/observational-memory-AJWSMZVP-HI6EWRCH.cjs.map +1 -0
  16. package/dist/{observational-memory-ZNTAIUGT-VIXA4SKE.js → observational-memory-AJWSMZVP-J3OYOGXO.js} +29 -12
  17. package/dist/observational-memory-AJWSMZVP-J3OYOGXO.js.map +1 -0
  18. package/dist/server/handlers/agent-builder.cjs +16 -16
  19. package/dist/server/handlers/agent-builder.js +1 -1
  20. package/dist/server/handlers/prompt-block-versions.cjs +8 -8
  21. package/dist/server/handlers/prompt-block-versions.d.ts +6 -0
  22. package/dist/server/handlers/prompt-block-versions.d.ts.map +1 -1
  23. package/dist/server/handlers/prompt-block-versions.js +1 -1
  24. package/dist/server/handlers/stored-prompt-blocks.cjs +6 -6
  25. package/dist/server/handlers/stored-prompt-blocks.d.ts +16 -4
  26. package/dist/server/handlers/stored-prompt-blocks.d.ts.map +1 -1
  27. package/dist/server/handlers/stored-prompt-blocks.js +1 -1
  28. package/dist/server/handlers.cjs +2 -2
  29. package/dist/server/handlers.js +1 -1
  30. package/dist/server/schemas/prompt-block-versions.d.ts +27 -0
  31. package/dist/server/schemas/prompt-block-versions.d.ts.map +1 -1
  32. package/dist/server/schemas/stored-prompt-blocks.d.ts +44 -4
  33. package/dist/server/schemas/stored-prompt-blocks.d.ts.map +1 -1
  34. package/dist/server/server-adapter/index.cjs +30 -30
  35. package/dist/server/server-adapter/index.js +3 -3
  36. package/package.json +6 -6
  37. package/dist/chunk-CMYJ32N3.js.map +0 -1
  38. package/dist/chunk-GPRCK7GP.cjs.map +0 -1
  39. package/dist/chunk-NC6UUX6D.js.map +0 -1
  40. package/dist/chunk-NGFAF6WW.cjs.map +0 -1
  41. package/dist/docs/SKILL.md +0 -28
  42. package/dist/docs/assets/SOURCE_MAP.json +0 -6
  43. package/dist/docs/references/docs-server-custom-adapters.md +0 -374
  44. package/dist/docs/references/reference-server-create-route.md +0 -260
  45. package/dist/docs/references/reference-server-mastra-server.md +0 -298
  46. package/dist/docs/references/reference-server-routes.md +0 -306
  47. package/dist/observational-memory-ZNTAIUGT-565A3END.cjs.map +0 -1
  48. package/dist/observational-memory-ZNTAIUGT-VIXA4SKE.js.map +0 -1
@@ -1,260 +0,0 @@
1
- # createRoute()
2
-
3
- The `createRoute()` function creates type-safe routes with Zod validation. When an `openapiPath` is configured on the server adapter, it generates OpenAPI schema entries from the supplied Zod schemas.
4
-
5
- ## Import
6
-
7
- ```typescript
8
- import { createRoute } from '@mastra/server/server-adapter';
9
- ```
10
-
11
- ## Signature
12
-
13
- ```typescript
14
- function createRoute<TPath, TQuery, TBody, TResponse, TResponseType>(
15
- config: RouteConfig<TPath, TQuery, TBody, TResponse, TResponseType>
16
- ): ServerRoute
17
- ```
18
-
19
- ## Parameters
20
-
21
- **method:** (`'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'ALL'`): HTTP method
22
-
23
- **path:** (`string`): Route path with optional params (e.g., \`/api/items/:id\`)
24
-
25
- **responseType:** (`'json' | 'stream'`): Response format. Internal routes may use additional types (\`datastream-response\`, \`mcp-http\`, \`mcp-sse\`).
26
-
27
- **handler:** (`ServerRouteHandler`): Route handler function
28
-
29
- **pathParamSchema?:** (`ZodSchema`): Validates URL path parameters
30
-
31
- **queryParamSchema?:** (`ZodSchema`): Validates query string parameters
32
-
33
- **bodySchema?:** (`ZodSchema`): Validates request body
34
-
35
- **responseSchema?:** (`ZodSchema`): Documents response shape for OpenAPI
36
-
37
- **streamFormat?:** (`'sse' | 'stream'`): Stream format (when responseType is 'stream')
38
-
39
- **maxBodySize?:** (`number`): Override default body size limit in bytes
40
-
41
- **summary?:** (`string`): OpenAPI summary
42
-
43
- **description?:** (`string`): OpenAPI description
44
-
45
- **tags?:** (`string[]`): OpenAPI tags
46
-
47
- **deprecated?:** (`boolean`): Mark route as deprecated
48
-
49
- ## Handler parameters
50
-
51
- The handler receives validated parameters plus runtime context:
52
-
53
- ```typescript
54
- handler: async (params) => {
55
- // From schemas (typed from Zod)
56
- params.id; // From pathParamSchema
57
- params.filter; // From queryParamSchema
58
- params.name; // From bodySchema
59
-
60
- // Runtime context (always available)
61
- params.mastra; // Mastra instance
62
- params.requestContext; // Request-scoped context
63
- params.tools; // Available tools
64
- params.abortSignal; // Request cancellation signal
65
- params.taskStore; // A2A task storage
66
- }
67
- ```
68
-
69
- ## Return value
70
-
71
- Returns a `ServerRoute` object that can be registered with an adapter.
72
-
73
- ## Examples
74
-
75
- ### GET route with path params
76
-
77
- ```typescript
78
- import { createRoute } from '@mastra/server/server-adapter';
79
- import { z } from 'zod';
80
-
81
- const getAgent = createRoute({
82
- method: 'GET',
83
- path: '/api/agents/:agentId',
84
- responseType: 'json',
85
- pathParamSchema: z.object({
86
- agentId: z.string(),
87
- }),
88
- responseSchema: z.object({
89
- name: z.string(),
90
- description: z.string().optional(),
91
- }),
92
- summary: 'Get agent by ID',
93
- tags: ['Agents'],
94
- handler: async ({ agentId, mastra }) => {
95
- return mastra.getAgent(agentId);
96
- },
97
- });
98
- ```
99
-
100
- ### POST route with body
101
-
102
- ```typescript
103
- const createItem = createRoute({
104
- method: 'POST',
105
- path: '/api/items',
106
- responseType: 'json',
107
- bodySchema: z.object({
108
- name: z.string(),
109
- value: z.number(),
110
- }),
111
- responseSchema: z.object({
112
- id: z.string(),
113
- name: z.string(),
114
- value: z.number(),
115
- }),
116
- handler: async ({ name, value, mastra }) => {
117
- // name and value are typed from bodySchema
118
- return { id: 'new-id', name, value };
119
- },
120
- });
121
- ```
122
-
123
- ### Query params with coercion
124
-
125
- ```typescript
126
- const listItems = createRoute({
127
- method: 'GET',
128
- path: '/api/items',
129
- responseType: 'json',
130
- queryParamSchema: z.object({
131
- page: z.coerce.number().default(0),
132
- limit: z.coerce.number().default(50),
133
- enabled: z.coerce.boolean().optional(),
134
- }),
135
- handler: async ({ page, limit, enabled, mastra }) => {
136
- // page, limit, enabled are typed and coerced
137
- return { items: [], page, limit };
138
- },
139
- });
140
- ```
141
-
142
- ### Streaming route
143
-
144
- ```typescript
145
- const streamAgent = createRoute({
146
- method: 'POST',
147
- path: '/api/agents/:agentId/stream',
148
- responseType: 'stream',
149
- streamFormat: 'sse',
150
- pathParamSchema: z.object({
151
- agentId: z.string(),
152
- }),
153
- bodySchema: z.object({
154
- messages: z.array(z.any()),
155
- }),
156
- handler: async ({ agentId, messages, mastra, abortSignal }) => {
157
- const agent = mastra.getAgent(agentId);
158
- return agent.stream(messages, { abortSignal });
159
- },
160
- });
161
- ```
162
-
163
- ### Custom body size limit
164
-
165
- ```typescript
166
- const uploadRoute = createRoute({
167
- method: 'POST',
168
- path: '/api/upload',
169
- responseType: 'json',
170
- maxBodySize: 50 * 1024 * 1024, // 50MB
171
- bodySchema: z.object({
172
- file: z.string(),
173
- }),
174
- handler: async ({ file }) => {
175
- return { uploaded: true };
176
- },
177
- });
178
- ```
179
-
180
- ## Schema patterns
181
-
182
- ### Passthrough for extensibility
183
-
184
- ```typescript
185
- const bodySchema = z.object({
186
- required: z.string(),
187
- }).passthrough(); // Allow unknown fields
188
- ```
189
-
190
- ### Date coercion
191
-
192
- ```typescript
193
- const querySchema = z.object({
194
- fromDate: z.coerce.date().optional(),
195
- toDate: z.coerce.date().optional(),
196
- });
197
- ```
198
-
199
- ### Union types
200
-
201
- ```typescript
202
- const bodySchema = z.object({
203
- messages: z.union([
204
- z.array(z.any()),
205
- z.string(),
206
- ]),
207
- });
208
- ```
209
-
210
- ## Error handling
211
-
212
- Throw an error with a `status` property to return specific HTTP status codes from handlers. If using Hono, you can use `HTTPException` from `hono/http-exception`:
213
-
214
- ```typescript
215
- import { createRoute } from '@mastra/server/server-adapter';
216
- import { HTTPException } from 'hono/http-exception';
217
-
218
- const getAgent = createRoute({
219
- method: 'GET',
220
- path: '/api/agents/:agentId',
221
- responseType: 'json',
222
- pathParamSchema: z.object({ agentId: z.string() }),
223
- handler: async ({ agentId, mastra }) => {
224
- const agent = mastra.getAgent(agentId);
225
- if (!agent) {
226
- throw new HTTPException(404, { message: `Agent '${agentId}' not found` });
227
- }
228
- return agent;
229
- },
230
- });
231
- ```
232
-
233
- For Express or framework-agnostic code, throw an error with a `status` property:
234
-
235
- ```typescript
236
- class HttpError extends Error {
237
- constructor(public status: number, message: string) {
238
- super(message);
239
- }
240
- }
241
-
242
- // In handler:
243
- throw new HttpError(404, `Agent '${agentId}' not found`);
244
- ```
245
-
246
- Common status codes:
247
-
248
- | Code | Meaning |
249
- | ---- | --------------------- |
250
- | 400 | Bad Request |
251
- | 401 | Unauthorized |
252
- | 403 | Forbidden |
253
- | 404 | Not Found |
254
- | 500 | Internal Server Error |
255
-
256
- ## Related
257
-
258
- - [Server Routes](https://mastra.ai/reference/server/routes) - Default Mastra routes
259
- - [MastraServer](https://mastra.ai/reference/server/mastra-server) - Server adapter class
260
- - [Server Adapters](https://mastra.ai/docs/server/server-adapters) - Using adapters
@@ -1,298 +0,0 @@
1
- # MastraServer
2
-
3
- The `MastraServer` abstract class is the base for all server adapters. Extend this class to create adapters for frameworks other than Hono or Express.
4
-
5
- ## Import
6
-
7
- ```typescript
8
- import { MastraServer } from '@mastra/server/server-adapter';
9
- ```
10
-
11
- ## Type parameters
12
-
13
- ```typescript
14
- MastraServer<TApp, TRequest, TResponse>
15
- ```
16
-
17
- | Parameter | Description |
18
- | ----------- | ------------------------------------------------ |
19
- | `TApp` | Framework app type (e.g., `Hono`, `Application`) |
20
- | `TRequest` | Framework request type |
21
- | `TResponse` | Framework response/context type |
22
-
23
- ## Constructor
24
-
25
- ```typescript
26
- constructor(options: MastraServerOptions<TApp>)
27
- ```
28
-
29
- ### Options
30
-
31
- **app:** (`TApp`): Framework app instance
32
-
33
- **mastra:** (`Mastra`): Mastra instance
34
-
35
- **prefix?:** (`string`): Route path prefix (e.g., \`/api/v2\`) (Default: `''`)
36
-
37
- **openapiPath?:** (`string`): Path to serve OpenAPI spec (Default: `''`)
38
-
39
- **bodyLimitOptions?:** (`BodyLimitOptions`): Request body size limits
40
-
41
- **streamOptions?:** (`StreamOptions`): Stream redaction config (Default: `{ redact: true }`)
42
-
43
- **customRouteAuthConfig?:** (`Map<string, boolean>`): Per-route auth overrides
44
-
45
- **tools?:** (`Record<string, Tool>`): Available tools for the server
46
-
47
- **taskStore?:** (`InMemoryTaskStore`): Task store for A2A (Agent-to-Agent) operations
48
-
49
- **mcpOptions?:** (`MCPOptions`): MCP transport options for serverless environments
50
-
51
- ## Abstract methods
52
-
53
- These methods must be implemented by adapters:
54
-
55
- ### registerContextMiddleware()
56
-
57
- Attach Mastra context to every request.
58
-
59
- ```typescript
60
- abstract registerContextMiddleware(): void
61
- ```
62
-
63
- **Context to attach:**
64
-
65
- - `mastra` - Mastra instance
66
- - `requestContext` - Request-scoped context
67
- - `tools` - Available tools
68
- - `abortSignal` - Request cancellation signal
69
-
70
- ### registerAuthMiddleware()
71
-
72
- Register authentication and authorization middleware.
73
-
74
- ```typescript
75
- abstract registerAuthMiddleware(): void
76
- ```
77
-
78
- ### registerRoute()
79
-
80
- Register a single route with the framework.
81
-
82
- ```typescript
83
- abstract registerRoute(
84
- app: TApp,
85
- route: ServerRoute,
86
- options: { prefix?: string }
87
- ): Promise<void>
88
- ```
89
-
90
- ### getParams()
91
-
92
- Extract parameters from the request.
93
-
94
- ```typescript
95
- abstract getParams(
96
- route: ServerRoute,
97
- request: TRequest
98
- ): Promise<{
99
- urlParams: Record<string, string>;
100
- queryParams: Record<string, string>;
101
- body: unknown;
102
- }>
103
- ```
104
-
105
- ### sendResponse()
106
-
107
- Send response based on route type.
108
-
109
- ```typescript
110
- abstract sendResponse(
111
- route: ServerRoute,
112
- response: TResponse,
113
- result: unknown
114
- ): Promise<unknown>
115
- ```
116
-
117
- ### stream()
118
-
119
- Handle streaming responses.
120
-
121
- ```typescript
122
- abstract stream(
123
- route: ServerRoute,
124
- response: TResponse,
125
- result: unknown
126
- ): Promise<unknown>
127
- ```
128
-
129
- ## Instance methods
130
-
131
- ### init()
132
-
133
- Initialize the server by registering all middleware and routes.
134
-
135
- ```typescript
136
- async init(): Promise<void>
137
- ```
138
-
139
- Calls in order:
140
-
141
- 1. `registerContextMiddleware()`
142
- 2. `registerAuthMiddleware()`
143
- 3. `registerRoutes()`
144
-
145
- ### registerRoutes()
146
-
147
- Register all Mastra routes.
148
-
149
- ```typescript
150
- async registerRoutes(): Promise<void>
151
- ```
152
-
153
- ### getApp()
154
-
155
- Get the framework app instance.
156
-
157
- ```typescript
158
- getApp<T = TApp>(): T
159
- ```
160
-
161
- ### parsePathParams()
162
-
163
- Validate path parameters with the route's Zod schema.
164
-
165
- ```typescript
166
- async parsePathParams(
167
- route: ServerRoute,
168
- params: Record<string, string>
169
- ): Promise<Record<string, unknown>>
170
- ```
171
-
172
- ### parseQueryParams()
173
-
174
- Validate query parameters with the route's Zod schema.
175
-
176
- ```typescript
177
- async parseQueryParams(
178
- route: ServerRoute,
179
- params: Record<string, string>
180
- ): Promise<Record<string, unknown>>
181
- ```
182
-
183
- ### parseBody()
184
-
185
- Validate request body with the route's Zod schema.
186
-
187
- ```typescript
188
- async parseBody(
189
- route: ServerRoute,
190
- body: unknown
191
- ): Promise<unknown>
192
- ```
193
-
194
- ### registerOpenAPIRoute()
195
-
196
- Register an endpoint that serves the OpenAPI specification.
197
-
198
- ```typescript
199
- async registerOpenAPIRoute(
200
- app: TApp,
201
- config: OpenAPIConfig,
202
- options: { prefix?: string }
203
- ): Promise<void>
204
- ```
205
-
206
- ## Protected methods
207
-
208
- ### mergeRequestContext()
209
-
210
- Merge request context from multiple sources (query params and body).
211
-
212
- ```typescript
213
- protected mergeRequestContext(options: {
214
- paramsRequestContext?: Record<string, any>;
215
- bodyRequestContext?: Record<string, any>;
216
- }): RequestContext
217
- ```
218
-
219
- ## Types
220
-
221
- ### BodyLimitOptions
222
-
223
- ```typescript
224
- interface BodyLimitOptions {
225
- maxSize: number;
226
- onError: (error: unknown) => unknown;
227
- }
228
- ```
229
-
230
- ### StreamOptions
231
-
232
- ```typescript
233
- interface StreamOptions {
234
- redact?: boolean;
235
- }
236
- ```
237
-
238
- ### MCPOptions
239
-
240
- ```typescript
241
- interface MCPOptions {
242
- serverless?: boolean;
243
- sessionIdGenerator?: () => string;
244
- }
245
- ```
246
-
247
- | Property | Description |
248
- | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
249
- | `serverless` | When `true`, runs MCP in stateless mode without session management. Use for serverless environments like Cloudflare Workers or Vercel Edge. |
250
- | `sessionIdGenerator` | Custom function to generate session IDs. |
251
-
252
- ## Example
253
-
254
- ```typescript
255
- import { MastraServer, ServerRoute } from '@mastra/server/server-adapter';
256
- import type { Mastra } from '@mastra/core';
257
-
258
- export class MyServer extends MastraServer<MyApp, MyRequest, MyResponse> {
259
- registerContextMiddleware(): void {
260
- this.app.use('*', (req, res, next) => {
261
- res.locals.mastra = this.mastra;
262
- next();
263
- });
264
- }
265
-
266
- registerAuthMiddleware(): void {
267
- const auth = this.mastra.getServer()?.auth;
268
- if (!auth) return;
269
- // Implement auth
270
- }
271
-
272
- async registerRoute(app, route, { prefix }) {
273
- // Implement route registration
274
- }
275
-
276
- async getParams(route, request) {
277
- return {
278
- urlParams: request.params,
279
- queryParams: request.query,
280
- body: request.body,
281
- };
282
- }
283
-
284
- async sendResponse(route, response, result) {
285
- return response.json(result);
286
- }
287
-
288
- async stream(route, response, result) {
289
- // Implement streaming
290
- }
291
- }
292
- ```
293
-
294
- ## Related
295
-
296
- - [Server Adapters](https://mastra.ai/docs/server/server-adapters) - Using adapters
297
- - [Custom Adapters](https://mastra.ai/docs/server/custom-adapters) - Creating custom adapters
298
- - [createRoute()](https://mastra.ai/reference/server/create-route) - Creating custom routes