@mastra/server 1.7.0 → 1.8.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 (42) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/dist/{chunk-TTU35R4T.cjs → chunk-6OM4GWXC.cjs} +11 -5
  3. package/dist/chunk-6OM4GWXC.cjs.map +1 -0
  4. package/dist/{chunk-ITRPAZYO.js → chunk-7YBAROHQ.js} +11 -5
  5. package/dist/chunk-7YBAROHQ.js.map +1 -0
  6. package/dist/{chunk-3BKGGOC6.cjs → chunk-PLW5CELE.cjs} +3 -3
  7. package/dist/{chunk-3BKGGOC6.cjs.map → chunk-PLW5CELE.cjs.map} +1 -1
  8. package/dist/{chunk-WGKHH2YW.cjs → chunk-RU5PL7RD.cjs} +32 -23
  9. package/dist/chunk-RU5PL7RD.cjs.map +1 -0
  10. package/dist/{chunk-M3GN2NCJ.js → chunk-TWPNGPJQ.js} +33 -24
  11. package/dist/chunk-TWPNGPJQ.js.map +1 -0
  12. package/dist/{chunk-PGB5HYV7.js → chunk-W6M2H2OZ.js} +3 -3
  13. package/dist/{chunk-PGB5HYV7.js.map → chunk-W6M2H2OZ.js.map} +1 -1
  14. package/dist/docs/SKILL.md +28 -0
  15. package/dist/docs/assets/SOURCE_MAP.json +6 -0
  16. package/dist/docs/references/docs-server-custom-adapters.md +378 -0
  17. package/dist/docs/references/reference-server-create-route.md +262 -0
  18. package/dist/docs/references/reference-server-mastra-server.md +298 -0
  19. package/dist/docs/references/reference-server-routes.md +306 -0
  20. package/dist/{observational-memory-AJWSMZVP-J3OYOGXO.js → observational-memory-KAFD4QZK-BJ3EY54G.js} +60 -16
  21. package/dist/observational-memory-KAFD4QZK-BJ3EY54G.js.map +1 -0
  22. package/dist/{observational-memory-AJWSMZVP-HI6EWRCH.cjs → observational-memory-KAFD4QZK-UEZ333UM.cjs} +60 -16
  23. package/dist/observational-memory-KAFD4QZK-UEZ333UM.cjs.map +1 -0
  24. package/dist/server/handlers/agent-builder.cjs +16 -16
  25. package/dist/server/handlers/agent-builder.js +1 -1
  26. package/dist/server/handlers/tools.cjs +6 -6
  27. package/dist/server/handlers/tools.d.ts.map +1 -1
  28. package/dist/server/handlers/tools.js +1 -1
  29. package/dist/server/handlers/workspace.cjs +26 -26
  30. package/dist/server/handlers/workspace.d.ts.map +1 -1
  31. package/dist/server/handlers/workspace.js +1 -1
  32. package/dist/server/handlers.cjs +6 -6
  33. package/dist/server/handlers.js +3 -3
  34. package/dist/server/server-adapter/index.cjs +27 -27
  35. package/dist/server/server-adapter/index.js +3 -3
  36. package/package.json +7 -7
  37. package/dist/chunk-ITRPAZYO.js.map +0 -1
  38. package/dist/chunk-M3GN2NCJ.js.map +0 -1
  39. package/dist/chunk-TTU35R4T.cjs.map +0 -1
  40. package/dist/chunk-WGKHH2YW.cjs.map +0 -1
  41. package/dist/observational-memory-AJWSMZVP-HI6EWRCH.cjs.map +0 -1
  42. package/dist/observational-memory-AJWSMZVP-J3OYOGXO.js.map +0 -1
@@ -0,0 +1,28 @@
1
+ ---
2
+ name: mastra-server
3
+ description: Documentation for @mastra/server. Use when working with @mastra/server APIs, configuration, or implementation.
4
+ metadata:
5
+ package: "@mastra/server"
6
+ version: "1.8.0"
7
+ ---
8
+
9
+ ## When to use
10
+
11
+ Use this skill whenever you are working with @mastra/server to obtain the domain-specific knowledge.
12
+
13
+ ## How to use
14
+
15
+ Read the individual reference documents for detailed explanations and code examples.
16
+
17
+ ### Docs
18
+
19
+ - [Custom Adapters](references/docs-server-custom-adapters.md) - Create a custom server adapter for frameworks other than Hono or Express.
20
+
21
+ ### Reference
22
+
23
+ - [Reference: createRoute()](references/reference-server-create-route.md) - API reference for createRoute() function used to define type-safe routes with validation and OpenAPI generation.
24
+ - [Reference: MastraServer](references/reference-server-mastra-server.md) - API reference for the MastraServer abstract class used to create server adapters.
25
+ - [Reference: Server Routes](references/reference-server-routes.md) - API reference for HTTP routes registered by Mastra server adapters.
26
+
27
+
28
+ Read [assets/SOURCE_MAP.json](assets/SOURCE_MAP.json) for source code references.
@@ -0,0 +1,6 @@
1
+ {
2
+ "version": "1.8.0",
3
+ "package": "@mastra/server",
4
+ "exports": {},
5
+ "modules": {}
6
+ }
@@ -0,0 +1,378 @@
1
+ # Custom Adapters
2
+
3
+ Create a custom adapter when you need to run Mastra with a framework other than Hono or Express. This might be necessary if you have specific request/response handling requirements that `@mastra/hono` and `@mastra/express` don't support.
4
+
5
+ A custom adapter translates between Mastra's route definitions and your framework's routing system. You'll implement methods that register middleware, handle requests, and send responses using your framework's APIs.
6
+
7
+ > **Info:** Use any of these prebuilt server adapters:
8
+ >
9
+ > - [@mastra/hono](https://mastra.ai/reference/server/hono-adapter)
10
+ > - [@mastra/express](https://mastra.ai/reference/server/express-adapter)
11
+ > - [@mastra/fastify](https://mastra.ai/reference/server/fastify-adapter)
12
+ > - [@mastra/koa](https://mastra.ai/reference/server/koa-adapter)
13
+
14
+ ## Abstract class
15
+
16
+ The `MastraServer` abstract class from `@mastra/server/server-adapter` provides the foundation for all adapters. It handles route registration logic, parameter validation, and other shared functionality. Your custom adapter extends this class and implements the framework-specific parts.
17
+
18
+ The class takes three type parameters that represent your framework's types:
19
+
20
+ ```typescript
21
+ import { MastraServer } from '@mastra/server/server-adapter'
22
+
23
+ export class MyFrameworkServer extends MastraServer<
24
+ // Your framework's app type (e.g., FastifyInstance)
25
+ MyApp,
26
+ // Your framework's request type (e.g., FastifyRequest)
27
+ MyRequest,
28
+ // Your framework's response type (e.g., FastifyReply)
29
+ MyResponse
30
+ > {
31
+ // Implement abstract methods
32
+ }
33
+ ```
34
+
35
+ These type parameters ensure type safety throughout your adapter implementation and enable proper typing when accessing framework-specific APIs.
36
+
37
+ ## Required methods
38
+
39
+ You must implement these six abstract methods. Each handles a specific part of the request lifecycle, from attaching context to sending responses.
40
+
41
+ ### registerContextMiddleware()
42
+
43
+ This method runs first and attaches Mastra context to every incoming request. Route handlers need access to the Mastra instance, tools, and other context to function. How you attach this context depends on your framework — Express uses `res.locals`, Hono uses `c.set()`, and other frameworks have their own patterns.
44
+
45
+ ```typescript
46
+ registerContextMiddleware(): void {
47
+ this.app.use('*', (req, res, next) => {
48
+ // Attach context to your framework's request/response
49
+ res.locals.mastra = this.mastra;
50
+ res.locals.requestContext = new RequestContext();
51
+ res.locals.tools = this.tools;
52
+ res.locals.abortSignal = createAbortSignal(req);
53
+ next();
54
+ });
55
+ }
56
+ ```
57
+
58
+ Context to attach:
59
+
60
+ | Key | Type | Description |
61
+ | ---------------- | ---------------------- | -------------------------------- |
62
+ | `mastra` | `Mastra` | The Mastra instance |
63
+ | `requestContext` | `RequestContext` | Request-scoped context map |
64
+ | `tools` | `Record<string, Tool>` | Available tools |
65
+ | `abortSignal` | `AbortSignal` | Request cancellation signal |
66
+ | `taskStore` | `InMemoryTaskStore` | A2A task storage (if configured) |
67
+
68
+ ### registerAuthMiddleware()
69
+
70
+ Register authentication and authorization middleware. This method should check if authentication is configured on the Mastra instance and skip registration entirely if not. When auth is configured, you'll typically register two middleware functions: one for authentication (validating tokens and setting the user) and one for authorization (checking if the user can access the requested resource).
71
+
72
+ ```typescript
73
+ registerAuthMiddleware(): void {
74
+ const authConfig = this.mastra.getServer()?.auth;
75
+ if (!authConfig) return;
76
+
77
+ // Register authentication (validate token, set user)
78
+ this.app.use('*', async (req, res, next) => {
79
+ const token = extractToken(req);
80
+ const user = await authConfig.authenticateToken?.(token, req);
81
+ if (!user) {
82
+ return res.status(401).json({ error: 'Unauthorized' });
83
+ }
84
+ res.locals.user = user;
85
+ next();
86
+ });
87
+
88
+ // Register authorization (check permissions)
89
+ this.app.use('*', async (req, res, next) => {
90
+ const allowed = await authConfig.authorize?.(
91
+ req.path,
92
+ req.method,
93
+ res.locals.user,
94
+ res
95
+ );
96
+ if (!allowed) {
97
+ return res.status(403).json({ error: 'Forbidden' });
98
+ }
99
+ next();
100
+ });
101
+ }
102
+ ```
103
+
104
+ ### registerRoute()
105
+
106
+ Register a single route with your framework. This method is called once for each Mastra route during initialization. It receives a `ServerRoute` object containing the path, HTTP method, handler function, and Zod schemas for validation. Your implementation should wire this up to your framework's routing system.
107
+
108
+ ```typescript
109
+ async registerRoute(
110
+ app: MyApp,
111
+ route: ServerRoute,
112
+ { prefix }: { prefix?: string }
113
+ ): Promise<void> {
114
+ const path = `${prefix || ''}${route.path}`;
115
+ const method = route.method.toLowerCase();
116
+
117
+ app[method](path, async (req, res) => {
118
+ try {
119
+ // 1. Extract parameters
120
+ const params = await this.getParams(route, req);
121
+
122
+ // 2. Validate with Zod schemas
123
+ const queryParams = await this.parseQueryParams(route, params.queryParams);
124
+ const body = await this.parseBody(route, params.body);
125
+
126
+ // 3. Build handler params
127
+ const handlerParams = {
128
+ ...params.urlParams,
129
+ ...queryParams,
130
+ ...(typeof body === 'object' ? body : {}),
131
+ mastra: this.mastra,
132
+ requestContext: res.locals.requestContext,
133
+ tools: res.locals.tools,
134
+ abortSignal: res.locals.abortSignal,
135
+ taskStore: this.taskStore,
136
+ };
137
+
138
+ // 4. Call handler
139
+ const result = await route.handler(handlerParams);
140
+
141
+ // 5. Send response
142
+ return this.sendResponse(route, res, result);
143
+ } catch (error) {
144
+ const status = error.status ?? error.details?.status ?? 500;
145
+ return res.status(status).json({ error: error.message });
146
+ }
147
+ });
148
+ }
149
+ ```
150
+
151
+ ### getParams()
152
+
153
+ Extract URL parameters, query parameters, and request body from the incoming request. Different frameworks expose these values in different ways—Express uses `req.params`, `req.query`, and `req.body`, while other frameworks may use different property names or require method calls. This method normalizes the extraction for your framework.
154
+
155
+ ```typescript
156
+ async getParams(
157
+ route: ServerRoute,
158
+ request: MyRequest
159
+ ): Promise<{
160
+ urlParams: Record<string, string>;
161
+ queryParams: Record<string, string>;
162
+ body: unknown;
163
+ }> {
164
+ return {
165
+ // From route path (e.g., :agentId)
166
+ urlParams: request.params,
167
+ // From URL query string
168
+ queryParams: request.query,
169
+ // From request body
170
+ body: request.body,
171
+ };
172
+ }
173
+ ```
174
+
175
+ ### sendResponse()
176
+
177
+ Send the response back to the client based on the route's response type. Mastra routes can return different response types: JSON for most API responses, streams for agent generation, and special types for MCP transports. Your implementation should handle each type appropriately for your framework.
178
+
179
+ ```typescript
180
+ async sendResponse(
181
+ route: ServerRoute,
182
+ response: MyResponse,
183
+ result: unknown
184
+ ): Promise<unknown> {
185
+ switch (route.responseType) {
186
+ case 'json':
187
+ return response.json(result);
188
+
189
+ case 'stream':
190
+ return this.stream(route, response, result);
191
+
192
+ case 'datastream-response':
193
+ // Return AI SDK Response directly
194
+ return result;
195
+
196
+ case 'mcp-http':
197
+ // Handle MCP HTTP transport
198
+ return this.handleMcpHttp(response, result);
199
+
200
+ case 'mcp-sse':
201
+ // Handle MCP SSE transport
202
+ return this.handleMcpSse(response, result);
203
+
204
+ default:
205
+ return response.json(result);
206
+ }
207
+ }
208
+ ```
209
+
210
+ ### stream()
211
+
212
+ Handle streaming responses for agent generation. When an agent generates a response, it produces a stream of chunks that should be sent to the client as they become available. This method reads from the stream, optionally applies redaction to hide sensitive data, and writes chunks to the response in the appropriate format (SSE or newline-delimited JSON).
213
+
214
+ ```typescript
215
+ async stream(
216
+ route: ServerRoute,
217
+ response: MyResponse,
218
+ result: unknown
219
+ ): Promise<unknown> {
220
+ const isSSE = route.streamFormat === 'sse';
221
+
222
+ // Set streaming headers based on format
223
+ response.setHeader('Content-Type', isSSE ? 'text/event-stream' : 'text/plain');
224
+ response.setHeader('Transfer-Encoding', 'chunked');
225
+
226
+ const reader = result.fullStream.getReader();
227
+
228
+ try {
229
+ while (true) {
230
+ const { done, value } = await reader.read();
231
+ if (done) break;
232
+
233
+ // Apply redaction if enabled
234
+ const chunk = this.streamOptions.redact
235
+ ? redactChunk(value)
236
+ : value;
237
+
238
+ // Format based on stream format
239
+ if (isSSE) {
240
+ response.write(`data: ${JSON.stringify(chunk)}\n\n`);
241
+ } else {
242
+ response.write(JSON.stringify(chunk) + '\x1E');
243
+ }
244
+ }
245
+
246
+ // Send completion marker (SSE uses data: [DONE], other formats use record separator)
247
+ if (isSSE) {
248
+ response.write('data: [DONE]\n\n');
249
+ }
250
+ response.end();
251
+ } catch (error) {
252
+ reader.cancel();
253
+ throw error;
254
+ }
255
+ }
256
+ ```
257
+
258
+ ## Helper methods
259
+
260
+ The base class provides helper methods you can use in your implementation. These handle common tasks like parameter validation and route registration, so you don't need to reimplement them:
261
+
262
+ | Method | Description |
263
+ | ------------------------------------------------------------------- | ----------------------------------------------------------- |
264
+ | `parsePathParams(route, params)` | Validate path params with Zod schema |
265
+ | `parseQueryParams(route, params)` | Validate query params with Zod schema |
266
+ | `parseBody(route, body)` | Validate body with Zod schema |
267
+ | `mergeRequestContext({ paramsRequestContext, bodyRequestContext })` | Merge request context from multiple sources |
268
+ | `registerRoutes()` | Register all Mastra routes (calls `registerRoute` for each) |
269
+ | `registerOpenAPIRoute(app, config, { prefix })` | Register OpenAPI spec endpoint |
270
+
271
+ The `parse*` methods use Zod schemas defined on each route to validate input and return typed results. If validation fails, they throw an error with details about what went wrong.
272
+
273
+ ## Constructor
274
+
275
+ Your adapter's constructor should accept the same options as the base class and pass them to `super()`. You can add additional framework-specific options if needed:
276
+
277
+ ```typescript
278
+ constructor(options: {
279
+ app: MyApp;
280
+ mastra: Mastra;
281
+ prefix?: string;
282
+ openapiPath?: string;
283
+ bodyLimitOptions?: BodyLimitOptions;
284
+ streamOptions?: StreamOptions;
285
+ customRouteAuthConfig?: Map<string, boolean>;
286
+ }) {
287
+ super(options);
288
+ }
289
+ ```
290
+
291
+ See [Server Adapters](https://mastra.ai/docs/server/server-adapters) for full documentation on each option.
292
+
293
+ ## Full example
294
+
295
+ Here's a skeleton implementation showing all the required methods. This uses pseudocode for framework-specific parts—replace with your framework's actual APIs:
296
+
297
+ ```typescript
298
+ import { MastraServer, ServerRoute } from '@mastra/server/server-adapter'
299
+ import type { Mastra } from '@mastra/core'
300
+
301
+ export class MyFrameworkServer extends MastraServer<MyApp, MyRequest, MyResponse> {
302
+ constructor(options: { app: MyApp; mastra: Mastra; prefix?: string }) {
303
+ super(options)
304
+ }
305
+
306
+ registerContextMiddleware(): void {
307
+ this.app.use('*', (req, res, next) => {
308
+ res.locals.mastra = this.mastra
309
+ res.locals.requestContext = this.mergeRequestContext({
310
+ paramsRequestContext: req.query.requestContext,
311
+ bodyRequestContext: req.body?.requestContext,
312
+ })
313
+ res.locals.tools = this.tools ?? {}
314
+ res.locals.abortSignal = createAbortSignal(req)
315
+ next()
316
+ })
317
+ }
318
+
319
+ registerAuthMiddleware(): void {
320
+ const authConfig = this.mastra.getServer()?.auth
321
+ if (!authConfig) return
322
+ // ... implement auth middleware
323
+ }
324
+
325
+ async registerRoute(
326
+ app: MyApp,
327
+ route: ServerRoute,
328
+ { prefix }: { prefix?: string },
329
+ ): Promise<void> {
330
+ // ... implement route registration
331
+ }
332
+
333
+ async getParams(route: ServerRoute, request: MyRequest) {
334
+ return {
335
+ urlParams: request.params,
336
+ queryParams: request.query,
337
+ body: request.body,
338
+ }
339
+ }
340
+
341
+ async sendResponse(route: ServerRoute, response: MyResponse, result: unknown) {
342
+ if (route.responseType === 'stream') {
343
+ return this.stream(route, response, result)
344
+ }
345
+ return response.json(result)
346
+ }
347
+
348
+ async stream(route: ServerRoute, response: MyResponse, result: unknown) {
349
+ // ... implement streaming
350
+ }
351
+ }
352
+ ```
353
+
354
+ ## Usage
355
+
356
+ Once your adapter is implemented, use it the same way as the provided adapters:
357
+
358
+ ```typescript
359
+ import { MyFrameworkServer } from './my-framework-adapter'
360
+ import { mastra } from './mastra'
361
+
362
+ const app = createMyFrameworkApp()
363
+ const server = new MyFrameworkServer({ app, mastra })
364
+
365
+ await server.init()
366
+
367
+ app.listen(4111)
368
+ ```
369
+
370
+ > **Tip:** The existing [@mastra/hono](https://github.com/mastra-ai/mastra/blob/main/server-adapters/hono/src/index.ts) and [@mastra/express](https://github.com/mastra-ai/mastra/blob/main/server-adapters/express/src/index.ts) implementations are good references when building your custom adapter. They show how to handle framework-specific patterns for context storage, middleware registration, and response handling.
371
+
372
+ ## Related
373
+
374
+ - [Server Adapters](https://mastra.ai/docs/server/server-adapters) - Overview and shared concepts
375
+ - [Hono Adapter](https://mastra.ai/reference/server/hono-adapter) - Reference implementation
376
+ - [Express Adapter](https://mastra.ai/reference/server/express-adapter) - Reference implementation
377
+ - [MastraServer Reference](https://mastra.ai/reference/server/mastra-server) - Full API reference
378
+ - [createRoute() Reference](https://mastra.ai/reference/server/create-route) - Creating type-safe custom routes
@@ -0,0 +1,262 @@
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
186
+ .object({
187
+ required: z.string(),
188
+ })
189
+ .passthrough() // Allow unknown fields
190
+ ```
191
+
192
+ ### Date coercion
193
+
194
+ ```typescript
195
+ const querySchema = z.object({
196
+ fromDate: z.coerce.date().optional(),
197
+ toDate: z.coerce.date().optional(),
198
+ })
199
+ ```
200
+
201
+ ### Union types
202
+
203
+ ```typescript
204
+ const bodySchema = z.object({
205
+ messages: z.union([z.array(z.any()), z.string()]),
206
+ })
207
+ ```
208
+
209
+ ## Error handling
210
+
211
+ 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`:
212
+
213
+ ```typescript
214
+ import { createRoute } from '@mastra/server/server-adapter'
215
+ import { HTTPException } from 'hono/http-exception'
216
+
217
+ const getAgent = createRoute({
218
+ method: 'GET',
219
+ path: '/api/agents/:agentId',
220
+ responseType: 'json',
221
+ pathParamSchema: z.object({ agentId: z.string() }),
222
+ handler: async ({ agentId, mastra }) => {
223
+ const agent = mastra.getAgent(agentId)
224
+ if (!agent) {
225
+ throw new HTTPException(404, { message: `Agent '${agentId}' not found` })
226
+ }
227
+ return agent
228
+ },
229
+ })
230
+ ```
231
+
232
+ For Express or framework-agnostic code, throw an error with a `status` property:
233
+
234
+ ```typescript
235
+ class HttpError extends Error {
236
+ constructor(
237
+ public status: number,
238
+ message: string,
239
+ ) {
240
+ super(message)
241
+ }
242
+ }
243
+
244
+ // In handler:
245
+ throw new HttpError(404, `Agent '${agentId}' not found`)
246
+ ```
247
+
248
+ Common status codes:
249
+
250
+ | Code | Meaning |
251
+ | ---- | --------------------- |
252
+ | 400 | Bad Request |
253
+ | 401 | Unauthorized |
254
+ | 403 | Forbidden |
255
+ | 404 | Not Found |
256
+ | 500 | Internal Server Error |
257
+
258
+ ## Related
259
+
260
+ - [Server Routes](https://mastra.ai/reference/server/routes) - Default Mastra routes
261
+ - [MastraServer](https://mastra.ai/reference/server/mastra-server) - Server adapter class
262
+ - [Server Adapters](https://mastra.ai/docs/server/server-adapters) - Using adapters