@mastra/server 1.0.0-beta.19 → 1.0.0-beta.20

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 (110) hide show
  1. package/CHANGELOG.md +104 -0
  2. package/dist/{chunk-MZXGNP3J.cjs → chunk-3PZVR6W3.cjs} +70 -106
  3. package/dist/chunk-3PZVR6W3.cjs.map +1 -0
  4. package/dist/{chunk-K73YS7YB.cjs → chunk-AQI6GLTN.cjs} +74 -74
  5. package/dist/{chunk-K73YS7YB.cjs.map → chunk-AQI6GLTN.cjs.map} +1 -1
  6. package/dist/{chunk-3XI22UQR.cjs → chunk-GWLR6K3H.cjs} +7 -3
  7. package/dist/chunk-GWLR6K3H.cjs.map +1 -0
  8. package/dist/{chunk-E646Y4FQ.js → chunk-H66LLFDL.js} +3 -3
  9. package/dist/chunk-H66LLFDL.js.map +1 -0
  10. package/dist/{chunk-7ZYZHQRF.cjs → chunk-IMPZBQ5U.cjs} +350 -216
  11. package/dist/chunk-IMPZBQ5U.cjs.map +1 -0
  12. package/dist/{chunk-MXJEVTGK.js → chunk-J6DCK7KG.js} +5 -11
  13. package/dist/chunk-J6DCK7KG.js.map +1 -0
  14. package/dist/{chunk-OCJ3BRZM.js → chunk-JQPDZZLI.js} +178 -51
  15. package/dist/chunk-JQPDZZLI.js.map +1 -0
  16. package/dist/{chunk-5ZYHM57F.cjs → chunk-KXYDJIKD.cjs} +177 -49
  17. package/dist/chunk-KXYDJIKD.cjs.map +1 -0
  18. package/dist/{chunk-SV4AUWGY.js → chunk-LOA7RQYO.js} +3 -3
  19. package/dist/{chunk-SV4AUWGY.js.map → chunk-LOA7RQYO.js.map} +1 -1
  20. package/dist/{chunk-AWK2DVRO.js → chunk-OKURLPIJ.js} +275 -138
  21. package/dist/chunk-OKURLPIJ.js.map +1 -0
  22. package/dist/{chunk-E4ZPLXZT.js → chunk-Q4BOUQ2O.js} +66 -100
  23. package/dist/chunk-Q4BOUQ2O.js.map +1 -0
  24. package/dist/{chunk-WBLT2HL3.js → chunk-QKXZF7YS.js} +7 -3
  25. package/dist/chunk-QKXZF7YS.js.map +1 -0
  26. package/dist/{chunk-BVIEHV3I.cjs → chunk-T3ZHTCEI.cjs} +2 -2
  27. package/dist/{chunk-BVIEHV3I.cjs.map → chunk-T3ZHTCEI.cjs.map} +1 -1
  28. package/dist/{chunk-BMLUV4BH.cjs → chunk-VX3VN7FN.cjs} +3 -3
  29. package/dist/chunk-VX3VN7FN.cjs.map +1 -0
  30. package/dist/{chunk-VYNS3ZKV.cjs → chunk-Y3VSCOCE.cjs} +7 -13
  31. package/dist/chunk-Y3VSCOCE.cjs.map +1 -0
  32. package/dist/{chunk-T2AYFHKB.js → chunk-ZRBZESWG.js} +2 -2
  33. package/dist/{chunk-T2AYFHKB.js.map → chunk-ZRBZESWG.js.map} +1 -1
  34. package/dist/{dist-AF7EUPXA.cjs → dist-7NTDEVLP.cjs} +28 -28
  35. package/dist/{dist-AF7EUPXA.cjs.map → dist-7NTDEVLP.cjs.map} +1 -1
  36. package/dist/{dist-4CMHRWC4.js → dist-B5GMANA6.js} +3 -3
  37. package/dist/{dist-4CMHRWC4.js.map → dist-B5GMANA6.js.map} +1 -1
  38. package/dist/dist-EDO7GEGI.js +3 -0
  39. package/dist/{dist-MEN73GGI.js.map → dist-EDO7GEGI.js.map} +1 -1
  40. package/dist/{dist-Q2ST4SUQ.cjs → dist-OF24ZMHH.cjs} +30 -30
  41. package/dist/{dist-Q2ST4SUQ.cjs.map → dist-OF24ZMHH.cjs.map} +1 -1
  42. package/dist/{dist-Y5SYUVLY.cjs → dist-P6YSNLL3.cjs} +20 -20
  43. package/dist/{dist-Y5SYUVLY.cjs.map → dist-P6YSNLL3.cjs.map} +1 -1
  44. package/dist/{dist-AEJONJSS.js → dist-SMBO5KVB.js} +3 -3
  45. package/dist/{dist-AEJONJSS.js.map → dist-SMBO5KVB.js.map} +1 -1
  46. package/dist/{dist-TE7XRSWH.js → dist-THPMW5QR.js} +3 -3
  47. package/dist/{dist-TE7XRSWH.js.map → dist-THPMW5QR.js.map} +1 -1
  48. package/dist/{dist-NVXXJWBO.cjs → dist-VZTG56X2.cjs} +26 -26
  49. package/dist/{dist-NVXXJWBO.cjs.map → dist-VZTG56X2.cjs.map} +1 -1
  50. package/dist/dist-ZLC23RVC.cjs +16 -0
  51. package/dist/{dist-2J26LQO2.cjs.map → dist-ZLC23RVC.cjs.map} +1 -1
  52. package/dist/{dist-VPYZNWNG.js → dist-ZOZ6MHJH.js} +3 -3
  53. package/dist/{dist-VPYZNWNG.js.map → dist-ZOZ6MHJH.js.map} +1 -1
  54. package/dist/docs/README.md +31 -0
  55. package/dist/docs/SKILL.md +32 -0
  56. package/dist/docs/SOURCE_MAP.json +6 -0
  57. package/dist/docs/server/01-custom-adapters.md +377 -0
  58. package/dist/docs/server/02-reference.md +828 -0
  59. package/dist/server/handlers/a2a.cjs +9 -9
  60. package/dist/server/handlers/a2a.js +1 -1
  61. package/dist/server/handlers/agent-builder.cjs +16 -28
  62. package/dist/server/handlers/agent-builder.d.ts +51 -85
  63. package/dist/server/handlers/agent-builder.d.ts.map +1 -1
  64. package/dist/server/handlers/agent-builder.js +1 -1
  65. package/dist/server/handlers/agents.cjs +24 -24
  66. package/dist/server/handlers/agents.d.ts.map +1 -1
  67. package/dist/server/handlers/agents.js +1 -1
  68. package/dist/server/handlers/memory.cjs +28 -24
  69. package/dist/server/handlers/memory.d.ts +114 -30
  70. package/dist/server/handlers/memory.d.ts.map +1 -1
  71. package/dist/server/handlers/memory.js +1 -1
  72. package/dist/server/handlers/observability.d.ts +17 -17
  73. package/dist/server/handlers/observability.d.ts.map +1 -1
  74. package/dist/server/handlers/workflows.cjs +24 -36
  75. package/dist/server/handlers/workflows.d.ts +61 -108
  76. package/dist/server/handlers/workflows.d.ts.map +1 -1
  77. package/dist/server/handlers/workflows.js +1 -1
  78. package/dist/server/handlers.cjs +10 -10
  79. package/dist/server/handlers.js +5 -5
  80. package/dist/server/schemas/agent-builder.d.ts +1 -1
  81. package/dist/server/schemas/agent-builder.d.ts.map +1 -1
  82. package/dist/server/schemas/memory.d.ts +161 -31
  83. package/dist/server/schemas/memory.d.ts.map +1 -1
  84. package/dist/server/schemas/workflows.d.ts +214 -34
  85. package/dist/server/schemas/workflows.d.ts.map +1 -1
  86. package/dist/server/server-adapter/index.cjs +102 -94
  87. package/dist/server/server-adapter/index.cjs.map +1 -1
  88. package/dist/server/server-adapter/index.d.ts +24 -6
  89. package/dist/server/server-adapter/index.d.ts.map +1 -1
  90. package/dist/server/server-adapter/index.js +20 -13
  91. package/dist/server/server-adapter/index.js.map +1 -1
  92. package/dist/server/server-adapter/routes/agent-builder.d.ts.map +1 -1
  93. package/dist/server/server-adapter/routes/memory.d.ts.map +1 -1
  94. package/dist/server/server-adapter/routes/workflows.d.ts.map +1 -1
  95. package/dist/server/utils.d.ts.map +1 -1
  96. package/package.json +10 -9
  97. package/dist/chunk-3XI22UQR.cjs.map +0 -1
  98. package/dist/chunk-5ZYHM57F.cjs.map +0 -1
  99. package/dist/chunk-7ZYZHQRF.cjs.map +0 -1
  100. package/dist/chunk-AWK2DVRO.js.map +0 -1
  101. package/dist/chunk-BMLUV4BH.cjs.map +0 -1
  102. package/dist/chunk-E4ZPLXZT.js.map +0 -1
  103. package/dist/chunk-E646Y4FQ.js.map +0 -1
  104. package/dist/chunk-MXJEVTGK.js.map +0 -1
  105. package/dist/chunk-MZXGNP3J.cjs.map +0 -1
  106. package/dist/chunk-OCJ3BRZM.js.map +0 -1
  107. package/dist/chunk-VYNS3ZKV.cjs.map +0 -1
  108. package/dist/chunk-WBLT2HL3.js.map +0 -1
  109. package/dist/dist-2J26LQO2.cjs +0 -16
  110. package/dist/dist-MEN73GGI.js +0 -3
@@ -0,0 +1,377 @@
1
+ > Create a custom server adapter for frameworks other than Hono or Express.
2
+
3
+ # Custom Adapters
4
+
5
+ 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.
6
+
7
+ 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.
8
+
9
+ > **Note:**
10
+
11
+ For Hono or Express, use the provided adapters instead:
12
+ - [@mastra/hono](https://mastra.ai/reference/v1/server/hono-adapter)
13
+ - [@mastra/express](https://mastra.ai/reference/v1/server/express-adapter)
14
+
15
+ ## Abstract class
16
+
17
+ 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.
18
+
19
+ The class takes three type parameters that represent your framework's types:
20
+
21
+ ```typescript title="my-framework-adapter.ts"
22
+ import { MastraServer } from '@mastra/server/server-adapter';
23
+
24
+ export class MyFrameworkServer extends MastraServer<
25
+ // Your framework's app type (e.g., FastifyInstance)
26
+ MyApp,
27
+ // Your framework's request type (e.g., FastifyRequest)
28
+ MyRequest,
29
+ // Your framework's response type (e.g., FastifyReply)
30
+ MyResponse
31
+ > {
32
+ // Implement abstract methods
33
+ }
34
+ ```
35
+
36
+ These type parameters ensure type safety throughout your adapter implementation and enable proper typing when accessing framework-specific APIs.
37
+
38
+ ## Required methods
39
+
40
+ You must implement these six abstract methods. Each handles a specific part of the request lifecycle, from attaching context to sending responses.
41
+
42
+ ### registerContextMiddleware()
43
+
44
+ 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.
45
+
46
+ ```typescript
47
+ registerContextMiddleware(): void {
48
+ this.app.use('*', (req, res, next) => {
49
+ // Attach context to your framework's request/response
50
+ res.locals.mastra = this.mastra;
51
+ res.locals.requestContext = new RequestContext();
52
+ res.locals.tools = this.tools;
53
+ res.locals.abortSignal = createAbortSignal(req);
54
+ next();
55
+ });
56
+ }
57
+ ```
58
+
59
+ Context to attach:
60
+
61
+ | Key | Type | Description |
62
+ |-----|------|-------------|
63
+ | `mastra` | `Mastra` | The Mastra instance |
64
+ | `requestContext` | `RequestContext` | Request-scoped context map |
65
+ | `tools` | `Record<string, Tool>` | Available tools |
66
+ | `abortSignal` | `AbortSignal` | Request cancellation signal |
67
+ | `taskStore` | `InMemoryTaskStore` | A2A task storage (if configured) |
68
+
69
+ ### registerAuthMiddleware()
70
+
71
+ 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).
72
+
73
+ ```typescript
74
+ registerAuthMiddleware(): void {
75
+ const authConfig = this.mastra.getServer()?.auth;
76
+ if (!authConfig) return;
77
+
78
+ // Register authentication (validate token, set user)
79
+ this.app.use('*', async (req, res, next) => {
80
+ const token = extractToken(req);
81
+ const user = await authConfig.authenticateToken?.(token, req);
82
+ if (!user) {
83
+ return res.status(401).json({ error: 'Unauthorized' });
84
+ }
85
+ res.locals.user = user;
86
+ next();
87
+ });
88
+
89
+ // Register authorization (check permissions)
90
+ this.app.use('*', async (req, res, next) => {
91
+ const allowed = await authConfig.authorize?.(
92
+ req.path,
93
+ req.method,
94
+ res.locals.user,
95
+ res
96
+ );
97
+ if (!allowed) {
98
+ return res.status(403).json({ error: 'Forbidden' });
99
+ }
100
+ next();
101
+ });
102
+ }
103
+ ```
104
+
105
+ ### registerRoute()
106
+
107
+ 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.
108
+
109
+ ```typescript
110
+ async registerRoute(
111
+ app: MyApp,
112
+ route: ServerRoute,
113
+ { prefix }: { prefix?: string }
114
+ ): Promise<void> {
115
+ const path = `${prefix || ''}${route.path}`;
116
+ const method = route.method.toLowerCase();
117
+
118
+ app[method](path, async (req, res) => {
119
+ try {
120
+ // 1. Extract parameters
121
+ const params = await this.getParams(route, req);
122
+
123
+ // 2. Validate with Zod schemas
124
+ const queryParams = await this.parseQueryParams(route, params.queryParams);
125
+ const body = await this.parseBody(route, params.body);
126
+
127
+ // 3. Build handler params
128
+ const handlerParams = {
129
+ ...params.urlParams,
130
+ ...queryParams,
131
+ ...(typeof body === 'object' ? body : {}),
132
+ mastra: this.mastra,
133
+ requestContext: res.locals.requestContext,
134
+ tools: res.locals.tools,
135
+ abortSignal: res.locals.abortSignal,
136
+ taskStore: this.taskStore,
137
+ };
138
+
139
+ // 4. Call handler
140
+ const result = await route.handler(handlerParams);
141
+
142
+ // 5. Send response
143
+ return this.sendResponse(route, res, result);
144
+ } catch (error) {
145
+ const status = error.status ?? error.details?.status ?? 500;
146
+ return res.status(status).json({ error: error.message });
147
+ }
148
+ });
149
+ }
150
+ ```
151
+
152
+ ### getParams()
153
+
154
+ 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.
155
+
156
+ ```typescript
157
+ async getParams(
158
+ route: ServerRoute,
159
+ request: MyRequest
160
+ ): Promise<{
161
+ urlParams: Record<string, string>;
162
+ queryParams: Record<string, string>;
163
+ body: unknown;
164
+ }> {
165
+ return {
166
+ // From route path (e.g., :agentId)
167
+ urlParams: request.params,
168
+ // From URL query string
169
+ queryParams: request.query,
170
+ // From request body
171
+ body: request.body,
172
+ };
173
+ }
174
+ ```
175
+
176
+ ### sendResponse()
177
+
178
+ 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.
179
+
180
+ ```typescript
181
+ async sendResponse(
182
+ route: ServerRoute,
183
+ response: MyResponse,
184
+ result: unknown
185
+ ): Promise<unknown> {
186
+ switch (route.responseType) {
187
+ case 'json':
188
+ return response.json(result);
189
+
190
+ case 'stream':
191
+ return this.stream(route, response, result);
192
+
193
+ case 'datastream-response':
194
+ // Return AI SDK Response directly
195
+ return result;
196
+
197
+ case 'mcp-http':
198
+ // Handle MCP HTTP transport
199
+ return this.handleMcpHttp(response, result);
200
+
201
+ case 'mcp-sse':
202
+ // Handle MCP SSE transport
203
+ return this.handleMcpSse(response, result);
204
+
205
+ default:
206
+ return response.json(result);
207
+ }
208
+ }
209
+ ```
210
+
211
+ ### stream()
212
+
213
+ 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).
214
+
215
+ ```typescript
216
+ async stream(
217
+ route: ServerRoute,
218
+ response: MyResponse,
219
+ result: unknown
220
+ ): Promise<unknown> {
221
+ const isSSE = route.streamFormat === 'sse';
222
+
223
+ // Set streaming headers based on format
224
+ response.setHeader('Content-Type', isSSE ? 'text/event-stream' : 'text/plain');
225
+ response.setHeader('Transfer-Encoding', 'chunked');
226
+
227
+ const reader = result.fullStream.getReader();
228
+
229
+ try {
230
+ while (true) {
231
+ const { done, value } = await reader.read();
232
+ if (done) break;
233
+
234
+ // Apply redaction if enabled
235
+ const chunk = this.streamOptions.redact
236
+ ? redactChunk(value)
237
+ : value;
238
+
239
+ // Format based on stream format
240
+ if (isSSE) {
241
+ response.write(`data: ${JSON.stringify(chunk)}\n\n`);
242
+ } else {
243
+ response.write(JSON.stringify(chunk) + '\x1E');
244
+ }
245
+ }
246
+
247
+ // Send completion marker (SSE uses data: [DONE], other formats use record separator)
248
+ if (isSSE) {
249
+ response.write('data: [DONE]\n\n');
250
+ }
251
+ response.end();
252
+ } catch (error) {
253
+ reader.cancel();
254
+ throw error;
255
+ }
256
+ }
257
+ ```
258
+
259
+ ## Helper methods
260
+
261
+ 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:
262
+
263
+ | Method | Description |
264
+ |--------|-------------|
265
+ | `parsePathParams(route, params)` | Validate path params with Zod schema |
266
+ | `parseQueryParams(route, params)` | Validate query params with Zod schema |
267
+ | `parseBody(route, body)` | Validate body with Zod schema |
268
+ | `mergeRequestContext({ paramsRequestContext, bodyRequestContext })` | Merge request context from multiple sources |
269
+ | `registerRoutes()` | Register all Mastra routes (calls `registerRoute` for each) |
270
+ | `registerOpenAPIRoute(app, config, { prefix })` | Register OpenAPI spec endpoint |
271
+
272
+ 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.
273
+
274
+ ## Constructor
275
+
276
+ 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:
277
+
278
+ ```typescript
279
+ constructor(options: {
280
+ app: MyApp;
281
+ mastra: Mastra;
282
+ prefix?: string;
283
+ openapiPath?: string;
284
+ bodyLimitOptions?: BodyLimitOptions;
285
+ streamOptions?: StreamOptions;
286
+ customRouteAuthConfig?: Map<string, boolean>;
287
+ }) {
288
+ super(options);
289
+ }
290
+ ```
291
+
292
+ See [Server Adapters](https://mastra.ai/docs/v1/server/server-adapters#constructor-options) for full documentation on each option.
293
+
294
+ ## Full example
295
+
296
+ Here's a skeleton implementation showing all the required methods. This uses pseudocode for framework-specific parts—replace with your framework's actual APIs:
297
+
298
+ ```typescript title="my-framework-adapter.ts"
299
+ import { MastraServer, ServerRoute } from '@mastra/server/server-adapter';
300
+ import type { Mastra } from '@mastra/core';
301
+
302
+ export class MyFrameworkServer extends MastraServer<MyApp, MyRequest, MyResponse> {
303
+ constructor(options: { app: MyApp; mastra: Mastra; prefix?: string }) {
304
+ super(options);
305
+ }
306
+
307
+ registerContextMiddleware(): void {
308
+ this.app.use('*', (req, res, next) => {
309
+ res.locals.mastra = this.mastra;
310
+ res.locals.requestContext = this.mergeRequestContext({
311
+ paramsRequestContext: req.query.requestContext,
312
+ bodyRequestContext: req.body?.requestContext,
313
+ });
314
+ res.locals.tools = this.tools ?? {};
315
+ res.locals.abortSignal = createAbortSignal(req);
316
+ next();
317
+ });
318
+ }
319
+
320
+ registerAuthMiddleware(): void {
321
+ const authConfig = this.mastra.getServer()?.auth;
322
+ if (!authConfig) return;
323
+ // ... implement auth middleware
324
+ }
325
+
326
+ async registerRoute(app: MyApp, route: ServerRoute, { prefix }: { prefix?: string }): Promise<void> {
327
+ // ... implement route registration
328
+ }
329
+
330
+ async getParams(route: ServerRoute, request: MyRequest) {
331
+ return {
332
+ urlParams: request.params,
333
+ queryParams: request.query,
334
+ body: request.body,
335
+ };
336
+ }
337
+
338
+ async sendResponse(route: ServerRoute, response: MyResponse, result: unknown) {
339
+ if (route.responseType === 'stream') {
340
+ return this.stream(route, response, result);
341
+ }
342
+ return response.json(result);
343
+ }
344
+
345
+ async stream(route: ServerRoute, response: MyResponse, result: unknown) {
346
+ // ... implement streaming
347
+ }
348
+ }
349
+ ```
350
+
351
+ ## Usage
352
+
353
+ Once your adapter is implemented, use it the same way as the provided adapters:
354
+
355
+ ```typescript title="server.ts"
356
+ import { MyFrameworkServer } from './my-framework-adapter';
357
+ import { mastra } from './mastra';
358
+
359
+ const app = createMyFrameworkApp();
360
+ const server = new MyFrameworkServer({ app, mastra });
361
+
362
+ await server.init();
363
+
364
+ app.listen(4111);
365
+ ```
366
+
367
+ > **Note:**
368
+
369
+ 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.
370
+
371
+ ## Related
372
+
373
+ - [Server Adapters](https://mastra.ai/docs/v1/server/server-adapters) - Overview and shared concepts
374
+ - [Hono Adapter](https://mastra.ai/reference/v1/server/hono-adapter) - Reference implementation
375
+ - [Express Adapter](https://mastra.ai/reference/v1/server/express-adapter) - Reference implementation
376
+ - [MastraServer Reference](https://mastra.ai/reference/v1/server/mastra-server) - Full API reference
377
+ - [createRoute() Reference](https://mastra.ai/reference/v1/server/create-route) - Creating type-safe custom routes