@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,298 @@
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
@@ -0,0 +1,306 @@
1
+ # Server Routes
2
+
3
+ Server adapters register these routes when you call `server.init()`. All routes are prefixed with the `prefix` option if configured.
4
+
5
+ ## Agents
6
+
7
+ | Method | Path | Description |
8
+ | ------ | -------------------------------------------- | ----------------------- |
9
+ | `GET` | `/api/agents` | List all agents |
10
+ | `GET` | `/api/agents/:agentId` | Get agent by ID |
11
+ | `POST` | `/api/agents/:agentId/generate` | Generate agent response |
12
+ | `POST` | `/api/agents/:agentId/stream` | Stream agent response |
13
+ | `GET` | `/api/agents/:agentId/tools` | List agent tools |
14
+ | `POST` | `/api/agents/:agentId/tools/:toolId/execute` | Execute agent tool |
15
+
16
+ ### Generate request body
17
+
18
+ ```typescript
19
+ {
20
+ messages: CoreMessage[] | string; // Required
21
+ instructions?: string; // System instructions
22
+ system?: string; // System prompt
23
+ context?: CoreMessage[]; // Additional context
24
+ memory?: { key: string } | boolean; // Memory config
25
+ resourceId?: string; // Resource identifier
26
+ threadId?: string; // Thread identifier
27
+ runId?: string; // Run identifier
28
+ maxSteps?: number; // Max tool steps
29
+ activeTools?: string[]; // Tools to enable
30
+ toolChoice?: ToolChoice; // Tool selection mode
31
+ requestContext?: Record<string, unknown>; // Request context
32
+ output?: ZodSchema; // Structured output schema
33
+ }
34
+ ```
35
+
36
+ ### Generate response
37
+
38
+ ```typescript
39
+ {
40
+ text: string;
41
+ toolCalls?: ToolCall[];
42
+ finishReason: string;
43
+ usage?: {
44
+ promptTokens: number;
45
+ completionTokens: number;
46
+ };
47
+ }
48
+ ```
49
+
50
+ ## Workflows
51
+
52
+ | Method | Path | Description |
53
+ | ------ | ----------------------------------------- | ------------------------------- |
54
+ | `GET` | `/api/workflows` | List all workflows |
55
+ | `GET` | `/api/workflows/:workflowId` | Get workflow by ID |
56
+ | `POST` | `/api/workflows/:workflowId/create-run` | Create a new workflow run |
57
+ | `POST` | `/api/workflows/:workflowId/start-async` | Start workflow and await result |
58
+ | `POST` | `/api/workflows/:workflowId/stream` | Stream workflow execution |
59
+ | `POST` | `/api/workflows/:workflowId/resume` | Resume suspended workflow |
60
+ | `POST` | `/api/workflows/:workflowId/resume-async` | Resume asynchronously |
61
+ | `GET` | `/api/workflows/:workflowId/runs` | List workflow runs |
62
+ | `GET` | `/api/workflows/:workflowId/runs/:runId` | Get specific run |
63
+
64
+ ### Create run request body
65
+
66
+ ```typescript
67
+ {
68
+ resourceId?: string; // Associate run with a resource (e.g., user ID)
69
+ disableScorers?: boolean; // Disable scorers for this run
70
+ }
71
+ ```
72
+
73
+ ### Start-async request body
74
+
75
+ ```typescript
76
+ {
77
+ resourceId?: string; // Associate run with a resource (e.g., user ID)
78
+ inputData?: unknown;
79
+ initialState?: unknown;
80
+ requestContext?: Record<string, unknown>;
81
+ tracingOptions?: {
82
+ spanName?: string;
83
+ attributes?: Record<string, unknown>;
84
+ };
85
+ }
86
+ ```
87
+
88
+ ### Stream workflow request body
89
+
90
+ ```typescript
91
+ {
92
+ resourceId?: string; // Associate run with a resource (e.g., user ID)
93
+ inputData?: unknown;
94
+ initialState?: unknown;
95
+ requestContext?: Record<string, unknown>;
96
+ closeOnSuspend?: boolean;
97
+ }
98
+ ```
99
+
100
+ ### Resume request body
101
+
102
+ ```typescript
103
+ {
104
+ step?: string | string[];
105
+ resumeData?: unknown;
106
+ requestContext?: Record<string, unknown>;
107
+ }
108
+ ```
109
+
110
+ ## Tools
111
+
112
+ | Method | Path | Description |
113
+ | ------ | ---------------------------- | -------------- |
114
+ | `GET` | `/api/tools` | List all tools |
115
+ | `GET` | `/api/tools/:toolId` | Get tool by ID |
116
+ | `POST` | `/api/tools/:toolId/execute` | Execute tool |
117
+
118
+ ### Execute tool request body
119
+
120
+ ```typescript
121
+ {
122
+ data: unknown; // Tool input data
123
+ requestContext?: Record<string, unknown>;
124
+ }
125
+ ```
126
+
127
+ ## Memory
128
+
129
+ | Method | Path | Description |
130
+ | -------- | ---------------------------------------- | ------------------- |
131
+ | `GET` | `/api/memory/threads` | List threads |
132
+ | `GET` | `/api/memory/threads/:threadId` | Get thread |
133
+ | `POST` | `/api/memory/threads` | Create thread |
134
+ | `DELETE` | `/api/memory/threads/:threadId` | Delete thread |
135
+ | `POST` | `/api/memory/threads/:threadId/clone` | Clone thread |
136
+ | `GET` | `/api/memory/threads/:threadId/messages` | Get thread messages |
137
+ | `POST` | `/api/memory/threads/:threadId/messages` | Add message |
138
+
139
+ ### Create thread request body
140
+
141
+ ```typescript
142
+ {
143
+ resourceId: string;
144
+ title?: string;
145
+ metadata?: Record<string, unknown>;
146
+ }
147
+ ```
148
+
149
+ ### Clone thread request body
150
+
151
+ ```typescript
152
+ {
153
+ newThreadId?: string; // Custom ID for cloned thread
154
+ resourceId?: string; // Override resource ID
155
+ title?: string; // Custom title for clone
156
+ metadata?: Record<string, unknown>; // Additional metadata
157
+ options?: {
158
+ messageLimit?: number; // Max messages to clone
159
+ messageFilter?: {
160
+ startDate?: Date; // Clone messages after this date
161
+ endDate?: Date; // Clone messages before this date
162
+ messageIds?: string[]; // Clone specific messages
163
+ };
164
+ };
165
+ }
166
+ ```
167
+
168
+ ### Clone thread response
169
+
170
+ ```typescript
171
+ {
172
+ thread: {
173
+ id: string;
174
+ resourceId: string;
175
+ title: string;
176
+ createdAt: Date;
177
+ updatedAt: Date;
178
+ metadata: {
179
+ clone: {
180
+ sourceThreadId: string;
181
+ clonedAt: Date;
182
+ lastMessageId?: string;
183
+ };
184
+ // ... other metadata
185
+ };
186
+ };
187
+ clonedMessages: MastraDBMessage[];
188
+ }
189
+ ```
190
+
191
+ ## Vectors
192
+
193
+ | Method | Path | Description |
194
+ | ------ | --------------------------------- | -------------- |
195
+ | `POST` | `/api/vectors/:vectorName/upsert` | Upsert vectors |
196
+ | `POST` | `/api/vectors/:vectorName/query` | Query vectors |
197
+ | `POST` | `/api/vectors/:vectorName/delete` | Delete vectors |
198
+
199
+ ### Upsert request body
200
+
201
+ ```typescript
202
+ {
203
+ vectors: Array<{
204
+ id: string
205
+ values: number[]
206
+ metadata?: Record<string, unknown>
207
+ }>
208
+ }
209
+ ```
210
+
211
+ ### Query request body
212
+
213
+ ```typescript
214
+ {
215
+ vector: number[];
216
+ topK?: number;
217
+ filter?: Record<string, unknown>;
218
+ includeMetadata?: boolean;
219
+ }
220
+ ```
221
+
222
+ ## MCP
223
+
224
+ | Method | Path | Description |
225
+ | ------ | ---------------------------------- | ------------------ |
226
+ | `GET` | `/api/mcp/servers` | List MCP servers |
227
+ | `GET` | `/api/mcp/servers/:serverId/tools` | List server tools |
228
+ | `POST` | `/api/mcp/:serverId` | MCP HTTP transport |
229
+ | `GET` | `/api/mcp/:serverId/sse` | MCP SSE transport |
230
+
231
+ ## Logs
232
+
233
+ | Method | Path | Description |
234
+ | ------ | ------------------ | ------------------ |
235
+ | `GET` | `/api/logs` | List logs |
236
+ | `GET` | `/api/logs/:runId` | Get logs by run ID |
237
+
238
+ ### Query parameters
239
+
240
+ ```typescript
241
+ {
242
+ page?: number;
243
+ perPage?: number;
244
+ transportId?: string;
245
+ }
246
+ ```
247
+
248
+ ## Telemetry
249
+
250
+ | Method | Path | Description |
251
+ | ------ | -------------------------------------- | --------------- |
252
+ | `GET` | `/api/telemetry/traces` | List traces |
253
+ | `GET` | `/api/telemetry/traces/:traceId` | Get trace |
254
+ | `GET` | `/api/telemetry/traces/:traceId/spans` | Get trace spans |
255
+
256
+ ## Common query parameters
257
+
258
+ ### Pagination
259
+
260
+ Most list endpoints support:
261
+
262
+ ```typescript
263
+ {
264
+ page?: number; // Page number (0-indexed)
265
+ perPage?: number; // Items per page (default: 10)
266
+ }
267
+ ```
268
+
269
+ ### Filtering
270
+
271
+ Workflow runs support:
272
+
273
+ ```typescript
274
+ {
275
+ fromDate?: string; // ISO date string
276
+ toDate?: string; // ISO date string
277
+ status?: string; // Run status filter
278
+ resourceId?: string; // Filter by resource
279
+ }
280
+ ```
281
+
282
+ ## Error responses
283
+
284
+ All routes return errors in this format:
285
+
286
+ ```typescript
287
+ {
288
+ error: string; // Error message
289
+ details?: unknown; // Additional details
290
+ }
291
+ ```
292
+
293
+ Common status codes:
294
+
295
+ | Code | Meaning |
296
+ | ---- | ------------------------------------ |
297
+ | 400 | Bad Request - Invalid parameters |
298
+ | 401 | Unauthorized - Missing/invalid auth |
299
+ | 403 | Forbidden - Insufficient permissions |
300
+ | 404 | Not Found - Resource doesn't exist |
301
+ | 500 | Internal Server Error |
302
+
303
+ ## Related
304
+
305
+ - [createRoute()](https://mastra.ai/reference/server/create-route) - Creating custom routes
306
+ - [Server Adapters](https://mastra.ai/docs/server/server-adapters) - Using adapters