@mastra/mcp-docs-server 1.0.0-beta.6 → 1.0.0-beta.8
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.
- package/.docs/organized/changelogs/%40mastra%2Fagent-builder.md +12 -12
- package/.docs/organized/changelogs/%40mastra%2Fai-sdk.md +10 -10
- package/.docs/organized/changelogs/%40mastra%2Fastra.md +10 -10
- package/.docs/organized/changelogs/%40mastra%2Fchroma.md +12 -12
- package/.docs/organized/changelogs/%40mastra%2Fclickhouse.md +48 -48
- package/.docs/organized/changelogs/%40mastra%2Fclient-js.md +65 -65
- package/.docs/organized/changelogs/%40mastra%2Fcloudflare-d1.md +48 -48
- package/.docs/organized/changelogs/%40mastra%2Fcloudflare.md +48 -48
- package/.docs/organized/changelogs/%40mastra%2Fcodemod.md +6 -0
- package/.docs/organized/changelogs/%40mastra%2Fconvex.md +47 -0
- package/.docs/organized/changelogs/%40mastra%2Fcore.md +196 -196
- package/.docs/organized/changelogs/%40mastra%2Fcouchbase.md +11 -11
- package/.docs/organized/changelogs/%40mastra%2Fdeployer-cloud.md +19 -19
- package/.docs/organized/changelogs/%40mastra%2Fdeployer.md +27 -27
- package/.docs/organized/changelogs/%40mastra%2Fdynamodb.md +48 -48
- package/.docs/organized/changelogs/%40mastra%2Felasticsearch.md +9 -0
- package/.docs/organized/changelogs/%40mastra%2Flance.md +48 -48
- package/.docs/organized/changelogs/%40mastra%2Flibsql.md +48 -48
- package/.docs/organized/changelogs/%40mastra%2Floggers.md +40 -40
- package/.docs/organized/changelogs/%40mastra%2Fmcp-docs-server.md +16 -16
- package/.docs/organized/changelogs/%40mastra%2Fmcp.md +43 -43
- package/.docs/organized/changelogs/%40mastra%2Fmemory.md +10 -10
- package/.docs/organized/changelogs/%40mastra%2Fmongodb.md +48 -48
- package/.docs/organized/changelogs/%40mastra%2Fmssql.md +48 -48
- package/.docs/organized/changelogs/%40mastra%2Fopensearch.md +10 -10
- package/.docs/organized/changelogs/%40mastra%2Fpg.md +52 -52
- package/.docs/organized/changelogs/%40mastra%2Fpinecone.md +10 -10
- package/.docs/organized/changelogs/%40mastra%2Fplayground-ui.md +41 -41
- package/.docs/organized/changelogs/%40mastra%2Fqdrant.md +10 -10
- package/.docs/organized/changelogs/%40mastra%2Freact.md +14 -0
- package/.docs/organized/changelogs/%40mastra%2Fs3vectors.md +9 -0
- package/.docs/organized/changelogs/%40mastra%2Fserver.md +65 -65
- package/.docs/organized/changelogs/%40mastra%2Fturbopuffer.md +10 -10
- package/.docs/organized/changelogs/%40mastra%2Fupstash.md +48 -48
- package/.docs/organized/changelogs/%40mastra%2Fvectorize.md +10 -10
- package/.docs/organized/changelogs/create-mastra.md +7 -7
- package/.docs/organized/changelogs/mastra.md +14 -14
- package/.docs/organized/code-examples/ai-elements.md +1 -1
- package/.docs/organized/code-examples/ai-sdk-useChat.md +1 -1
- package/.docs/organized/code-examples/ai-sdk-v5.md +1 -1
- package/.docs/organized/code-examples/assistant-ui.md +1 -1
- package/.docs/organized/code-examples/bird-checker-with-nextjs-and-eval.md +1 -1
- package/.docs/organized/code-examples/bird-checker-with-nextjs.md +1 -1
- package/.docs/organized/code-examples/crypto-chatbot.md +1 -1
- package/.docs/organized/code-examples/mcp-server-adapters.md +2 -2
- package/.docs/organized/code-examples/server-app-access.md +2 -2
- package/.docs/organized/code-examples/server-express-adapter.md +87 -0
- package/.docs/organized/code-examples/server-hono-adapter.md +85 -0
- package/.docs/raw/agents/overview.mdx +2 -111
- package/.docs/raw/agents/processors.mdx +1 -1
- package/.docs/raw/agents/structured-output.mdx +224 -0
- package/.docs/raw/guides/build-your-ui/ai-sdk-ui.mdx +381 -431
- package/.docs/raw/guides/getting-started/quickstart.mdx +11 -0
- package/.docs/raw/guides/migrations/upgrade-to-v1/workflows.mdx +40 -1
- package/.docs/raw/memory/working-memory.mdx +1 -0
- package/.docs/raw/observability/tracing/bridges/otel.mdx +25 -1
- package/.docs/raw/observability/tracing/exporters/arize.mdx +19 -0
- package/.docs/raw/observability/tracing/exporters/langfuse.mdx +63 -0
- package/.docs/raw/observability/tracing/exporters/otel.mdx +30 -19
- package/.docs/raw/observability/tracing/exporters/posthog.mdx +20 -0
- package/.docs/raw/observability/tracing/overview.mdx +6 -1
- package/.docs/raw/reference/ai-sdk/chat-route.mdx +127 -0
- package/.docs/raw/reference/ai-sdk/handle-chat-stream.mdx +117 -0
- package/.docs/raw/reference/ai-sdk/handle-network-stream.mdx +64 -0
- package/.docs/raw/reference/ai-sdk/handle-workflow-stream.mdx +116 -0
- package/.docs/raw/reference/ai-sdk/network-route.mdx +99 -0
- package/.docs/raw/reference/ai-sdk/to-ai-sdk-stream.mdx +289 -0
- package/.docs/raw/reference/ai-sdk/workflow-route.mdx +110 -0
- package/.docs/raw/reference/observability/tracing/bridges/otel.mdx +27 -0
- package/.docs/raw/reference/observability/tracing/exporters/arize.mdx +25 -0
- package/.docs/raw/reference/observability/tracing/exporters/langfuse.mdx +43 -0
- package/.docs/raw/reference/observability/tracing/exporters/otel.mdx +27 -43
- package/.docs/raw/reference/server/create-route.mdx +314 -0
- package/.docs/raw/reference/server/express-adapter.mdx +193 -0
- package/.docs/raw/reference/server/hono-adapter.mdx +174 -0
- package/.docs/raw/reference/server/mastra-server.mdx +316 -0
- package/.docs/raw/reference/server/routes.mdx +250 -0
- package/.docs/raw/reference/streaming/workflows/timeTravelStream.mdx +170 -0
- package/.docs/raw/reference/tools/mcp-client.mdx +54 -1
- package/.docs/raw/reference/workflows/run-methods/timeTravel.mdx +310 -0
- package/.docs/raw/reference/workflows/run.mdx +14 -0
- package/.docs/raw/server-db/custom-adapters.mdx +380 -0
- package/.docs/raw/server-db/custom-api-routes.mdx +5 -5
- package/.docs/raw/server-db/mastra-server.mdx +11 -32
- package/.docs/raw/server-db/server-adapters.mdx +286 -0
- package/.docs/raw/workflows/workflow-state.mdx +4 -5
- package/CHANGELOG.md +15 -0
- package/package.json +4 -4
|
@@ -0,0 +1,380 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: "Custom Adapters | Server & DB"
|
|
3
|
+
description: "Create a custom server adapter for frameworks other than Hono or Express."
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
import PropertiesTable from "@site/src/components/PropertiesTable";
|
|
7
|
+
|
|
8
|
+
# Custom Adapters
|
|
9
|
+
|
|
10
|
+
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.
|
|
11
|
+
|
|
12
|
+
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.
|
|
13
|
+
|
|
14
|
+
:::info
|
|
15
|
+
|
|
16
|
+
For Hono or Express, use the provided adapters instead:
|
|
17
|
+
- [@mastra/hono](/reference/v1/server/hono-adapter)
|
|
18
|
+
- [@mastra/express](/reference/v1/server/express-adapter)
|
|
19
|
+
|
|
20
|
+
:::
|
|
21
|
+
|
|
22
|
+
## Abstract class
|
|
23
|
+
|
|
24
|
+
The `MastraServer` abstract class from `@mastra/server` 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.
|
|
25
|
+
|
|
26
|
+
The class takes three type parameters that represent your framework's types:
|
|
27
|
+
|
|
28
|
+
```typescript title="my-framework-adapter.ts" copy showLineNumbers
|
|
29
|
+
import { MastraServer } from '@mastra/server';
|
|
30
|
+
|
|
31
|
+
export class MyFrameworkServer extends MastraServer<
|
|
32
|
+
MyApp, // Your framework's app type (e.g., FastifyInstance)
|
|
33
|
+
MyRequest, // Your framework's request type (e.g., FastifyRequest)
|
|
34
|
+
MyResponse // Your framework's response type (e.g., FastifyReply)
|
|
35
|
+
> {
|
|
36
|
+
// Implement abstract methods
|
|
37
|
+
}
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
These type parameters ensure type safety throughout your adapter implementation and enable proper typing when accessing framework-specific APIs.
|
|
41
|
+
|
|
42
|
+
## Required methods
|
|
43
|
+
|
|
44
|
+
You must implement these six abstract methods. Each handles a specific part of the request lifecycle, from attaching context to sending responses.
|
|
45
|
+
|
|
46
|
+
### registerContextMiddleware()
|
|
47
|
+
|
|
48
|
+
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.
|
|
49
|
+
|
|
50
|
+
```typescript copy showLineNumbers
|
|
51
|
+
registerContextMiddleware(): void {
|
|
52
|
+
this.app.use('*', (req, res, next) => {
|
|
53
|
+
// Attach context to your framework's request/response
|
|
54
|
+
res.locals.mastra = this.mastra;
|
|
55
|
+
res.locals.requestContext = new RequestContext();
|
|
56
|
+
res.locals.tools = this.tools;
|
|
57
|
+
res.locals.abortSignal = createAbortSignal(req);
|
|
58
|
+
next();
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
Context to attach:
|
|
64
|
+
|
|
65
|
+
| Key | Type | Description |
|
|
66
|
+
|-----|------|-------------|
|
|
67
|
+
| `mastra` | `Mastra` | The Mastra instance |
|
|
68
|
+
| `requestContext` | `RequestContext` | Request-scoped context map |
|
|
69
|
+
| `tools` | `Record<string, Tool>` | Available tools |
|
|
70
|
+
| `abortSignal` | `AbortSignal` | Request cancellation signal |
|
|
71
|
+
| `taskStore` | `InMemoryTaskStore` | A2A task storage (if configured) |
|
|
72
|
+
|
|
73
|
+
### registerAuthMiddleware()
|
|
74
|
+
|
|
75
|
+
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).
|
|
76
|
+
|
|
77
|
+
```typescript copy showLineNumbers
|
|
78
|
+
registerAuthMiddleware(): void {
|
|
79
|
+
const authConfig = this.mastra.getServer()?.auth;
|
|
80
|
+
if (!authConfig) return;
|
|
81
|
+
|
|
82
|
+
// Register authentication (validate token, set user)
|
|
83
|
+
this.app.use('*', async (req, res, next) => {
|
|
84
|
+
const token = extractToken(req);
|
|
85
|
+
const user = await authConfig.authenticateToken?.(token, req);
|
|
86
|
+
if (!user) {
|
|
87
|
+
return res.status(401).json({ error: 'Unauthorized' });
|
|
88
|
+
}
|
|
89
|
+
res.locals.user = user;
|
|
90
|
+
next();
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
// Register authorization (check permissions)
|
|
94
|
+
this.app.use('*', async (req, res, next) => {
|
|
95
|
+
const allowed = await authConfig.authorize?.(
|
|
96
|
+
req.path,
|
|
97
|
+
req.method,
|
|
98
|
+
res.locals.user,
|
|
99
|
+
res
|
|
100
|
+
);
|
|
101
|
+
if (!allowed) {
|
|
102
|
+
return res.status(403).json({ error: 'Forbidden' });
|
|
103
|
+
}
|
|
104
|
+
next();
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
### registerRoute()
|
|
110
|
+
|
|
111
|
+
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.
|
|
112
|
+
|
|
113
|
+
```typescript copy showLineNumbers
|
|
114
|
+
async registerRoute(
|
|
115
|
+
app: MyApp,
|
|
116
|
+
route: ServerRoute,
|
|
117
|
+
{ prefix }: { prefix?: string }
|
|
118
|
+
): Promise<void> {
|
|
119
|
+
const path = `${prefix || ''}${route.path}`;
|
|
120
|
+
const method = route.method.toLowerCase();
|
|
121
|
+
|
|
122
|
+
app[method](path, async (req, res) => {
|
|
123
|
+
try {
|
|
124
|
+
// 1. Extract parameters
|
|
125
|
+
const params = await this.getParams(route, req);
|
|
126
|
+
|
|
127
|
+
// 2. Validate with Zod schemas
|
|
128
|
+
const queryParams = await this.parseQueryParams(route, params.queryParams);
|
|
129
|
+
const body = await this.parseBody(route, params.body);
|
|
130
|
+
|
|
131
|
+
// 3. Build handler params
|
|
132
|
+
const handlerParams = {
|
|
133
|
+
...params.urlParams,
|
|
134
|
+
...queryParams,
|
|
135
|
+
...(typeof body === 'object' ? body : {}),
|
|
136
|
+
mastra: this.mastra,
|
|
137
|
+
requestContext: res.locals.requestContext,
|
|
138
|
+
tools: res.locals.tools,
|
|
139
|
+
abortSignal: res.locals.abortSignal,
|
|
140
|
+
taskStore: this.taskStore,
|
|
141
|
+
};
|
|
142
|
+
|
|
143
|
+
// 4. Call handler
|
|
144
|
+
const result = await route.handler(handlerParams);
|
|
145
|
+
|
|
146
|
+
// 5. Send response
|
|
147
|
+
return this.sendResponse(route, res, result);
|
|
148
|
+
} catch (error) {
|
|
149
|
+
const status = error.status ?? error.details?.status ?? 500;
|
|
150
|
+
return res.status(status).json({ error: error.message });
|
|
151
|
+
}
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
### getParams()
|
|
157
|
+
|
|
158
|
+
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.
|
|
159
|
+
|
|
160
|
+
```typescript copy showLineNumbers
|
|
161
|
+
async getParams(
|
|
162
|
+
route: ServerRoute,
|
|
163
|
+
request: MyRequest
|
|
164
|
+
): Promise<{
|
|
165
|
+
urlParams: Record<string, string>;
|
|
166
|
+
queryParams: Record<string, string>;
|
|
167
|
+
body: unknown;
|
|
168
|
+
}> {
|
|
169
|
+
return {
|
|
170
|
+
urlParams: request.params, // From route path (e.g., :agentId)
|
|
171
|
+
queryParams: request.query, // From URL query string
|
|
172
|
+
body: request.body, // From request body
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
### sendResponse()
|
|
178
|
+
|
|
179
|
+
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.
|
|
180
|
+
|
|
181
|
+
```typescript copy showLineNumbers
|
|
182
|
+
async sendResponse(
|
|
183
|
+
route: ServerRoute,
|
|
184
|
+
response: MyResponse,
|
|
185
|
+
result: unknown
|
|
186
|
+
): Promise<unknown> {
|
|
187
|
+
switch (route.responseType) {
|
|
188
|
+
case 'json':
|
|
189
|
+
return response.json(result);
|
|
190
|
+
|
|
191
|
+
case 'stream':
|
|
192
|
+
return this.stream(route, response, result);
|
|
193
|
+
|
|
194
|
+
case 'datastream-response':
|
|
195
|
+
// Return AI SDK Response directly
|
|
196
|
+
return result;
|
|
197
|
+
|
|
198
|
+
case 'mcp-http':
|
|
199
|
+
// Handle MCP HTTP transport
|
|
200
|
+
return this.handleMcpHttp(response, result);
|
|
201
|
+
|
|
202
|
+
case 'mcp-sse':
|
|
203
|
+
// Handle MCP SSE transport
|
|
204
|
+
return this.handleMcpSse(response, result);
|
|
205
|
+
|
|
206
|
+
default:
|
|
207
|
+
return response.json(result);
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
```
|
|
211
|
+
|
|
212
|
+
### stream()
|
|
213
|
+
|
|
214
|
+
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).
|
|
215
|
+
|
|
216
|
+
```typescript copy showLineNumbers
|
|
217
|
+
async stream(
|
|
218
|
+
route: ServerRoute,
|
|
219
|
+
response: MyResponse,
|
|
220
|
+
result: unknown
|
|
221
|
+
): Promise<unknown> {
|
|
222
|
+
const isSSE = route.streamFormat === 'sse';
|
|
223
|
+
|
|
224
|
+
// Set streaming headers based on format
|
|
225
|
+
response.setHeader('Content-Type', isSSE ? 'text/event-stream' : 'text/plain');
|
|
226
|
+
response.setHeader('Transfer-Encoding', 'chunked');
|
|
227
|
+
|
|
228
|
+
const reader = result.fullStream.getReader();
|
|
229
|
+
|
|
230
|
+
try {
|
|
231
|
+
while (true) {
|
|
232
|
+
const { done, value } = await reader.read();
|
|
233
|
+
if (done) break;
|
|
234
|
+
|
|
235
|
+
// Apply redaction if enabled
|
|
236
|
+
const chunk = this.streamOptions.redact
|
|
237
|
+
? redactChunk(value)
|
|
238
|
+
: value;
|
|
239
|
+
|
|
240
|
+
// Format based on stream format
|
|
241
|
+
if (isSSE) {
|
|
242
|
+
response.write(`data: ${JSON.stringify(chunk)}\n\n`);
|
|
243
|
+
} else {
|
|
244
|
+
response.write(JSON.stringify(chunk) + '\x1E');
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
// Send completion marker (SSE uses data: [DONE], other formats use record separator)
|
|
249
|
+
if (isSSE) {
|
|
250
|
+
response.write('data: [DONE]\n\n');
|
|
251
|
+
}
|
|
252
|
+
response.end();
|
|
253
|
+
} catch (error) {
|
|
254
|
+
reader.cancel();
|
|
255
|
+
throw error;
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
```
|
|
259
|
+
|
|
260
|
+
## Helper methods
|
|
261
|
+
|
|
262
|
+
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:
|
|
263
|
+
|
|
264
|
+
| Method | Description |
|
|
265
|
+
|--------|-------------|
|
|
266
|
+
| `parsePathParams(route, params)` | Validate path params with Zod schema |
|
|
267
|
+
| `parseQueryParams(route, params)` | Validate query params with Zod schema |
|
|
268
|
+
| `parseBody(route, body)` | Validate body with Zod schema |
|
|
269
|
+
| `mergeRequestContext({ paramsRequestContext, bodyRequestContext })` | Merge request context from multiple sources |
|
|
270
|
+
| `registerRoutes()` | Register all Mastra routes (calls `registerRoute` for each) |
|
|
271
|
+
| `registerOpenAPIRoute(app, config, { prefix })` | Register OpenAPI spec endpoint |
|
|
272
|
+
|
|
273
|
+
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.
|
|
274
|
+
|
|
275
|
+
## Constructor
|
|
276
|
+
|
|
277
|
+
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:
|
|
278
|
+
|
|
279
|
+
```typescript copy showLineNumbers
|
|
280
|
+
constructor(options: {
|
|
281
|
+
app: MyApp;
|
|
282
|
+
mastra: Mastra;
|
|
283
|
+
prefix?: string;
|
|
284
|
+
openapiPath?: string;
|
|
285
|
+
bodyLimitOptions?: BodyLimitOptions;
|
|
286
|
+
streamOptions?: StreamOptions;
|
|
287
|
+
customRouteAuthConfig?: Map<string, boolean>;
|
|
288
|
+
}) {
|
|
289
|
+
super(options);
|
|
290
|
+
}
|
|
291
|
+
```
|
|
292
|
+
|
|
293
|
+
See [Server Adapters](/docs/v1/server-db/server-adapters#constructor-options) for full documentation on each option.
|
|
294
|
+
|
|
295
|
+
## Full example
|
|
296
|
+
|
|
297
|
+
Here's a skeleton implementation showing all the required methods. This uses pseudocode for framework-specific parts—replace with your framework's actual APIs:
|
|
298
|
+
|
|
299
|
+
```typescript title="my-framework-adapter.ts" copy showLineNumbers
|
|
300
|
+
import { MastraServer, ServerRoute } from '@mastra/server';
|
|
301
|
+
import type { Mastra } from '@mastra/core';
|
|
302
|
+
|
|
303
|
+
export class MyFrameworkServer extends MastraServer<MyApp, MyRequest, MyResponse> {
|
|
304
|
+
constructor(options: { app: MyApp; mastra: Mastra; prefix?: string }) {
|
|
305
|
+
super(options);
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
registerContextMiddleware(): void {
|
|
309
|
+
this.app.use('*', (req, res, next) => {
|
|
310
|
+
res.locals.mastra = this.mastra;
|
|
311
|
+
res.locals.requestContext = this.mergeRequestContext({
|
|
312
|
+
paramsRequestContext: req.query.requestContext,
|
|
313
|
+
bodyRequestContext: req.body?.requestContext,
|
|
314
|
+
});
|
|
315
|
+
res.locals.tools = this.tools ?? {};
|
|
316
|
+
res.locals.abortSignal = createAbortSignal(req);
|
|
317
|
+
next();
|
|
318
|
+
});
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
registerAuthMiddleware(): void {
|
|
322
|
+
const authConfig = this.mastra.getServer()?.auth;
|
|
323
|
+
if (!authConfig) return;
|
|
324
|
+
// ... implement auth middleware
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
async registerRoute(app: MyApp, route: ServerRoute, { prefix }: { prefix?: string }): Promise<void> {
|
|
328
|
+
// ... implement route registration
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
async getParams(route: ServerRoute, request: MyRequest) {
|
|
332
|
+
return {
|
|
333
|
+
urlParams: request.params,
|
|
334
|
+
queryParams: request.query,
|
|
335
|
+
body: request.body,
|
|
336
|
+
};
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
async sendResponse(route: ServerRoute, response: MyResponse, result: unknown) {
|
|
340
|
+
if (route.responseType === 'stream') {
|
|
341
|
+
return this.stream(route, response, result);
|
|
342
|
+
}
|
|
343
|
+
return response.json(result);
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
async stream(route: ServerRoute, response: MyResponse, result: unknown) {
|
|
347
|
+
// ... implement streaming
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
```
|
|
351
|
+
|
|
352
|
+
## Usage
|
|
353
|
+
|
|
354
|
+
Once your adapter is implemented, use it the same way as the provided adapters:
|
|
355
|
+
|
|
356
|
+
```typescript title="server.ts" copy showLineNumbers
|
|
357
|
+
import { MyFrameworkServer } from './my-framework-adapter';
|
|
358
|
+
import { mastra } from './mastra';
|
|
359
|
+
|
|
360
|
+
const app = createMyFrameworkApp();
|
|
361
|
+
const server = new MyFrameworkServer({ app, mastra });
|
|
362
|
+
|
|
363
|
+
await server.init();
|
|
364
|
+
|
|
365
|
+
app.listen(4111);
|
|
366
|
+
```
|
|
367
|
+
|
|
368
|
+
:::tip
|
|
369
|
+
|
|
370
|
+
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
|
+
:::
|
|
373
|
+
|
|
374
|
+
## Related
|
|
375
|
+
|
|
376
|
+
- [Server Adapters](/docs/v1/server-db/server-adapters) - Overview and shared concepts
|
|
377
|
+
- [Hono Adapter](/reference/v1/server/hono-adapter) - Reference implementation
|
|
378
|
+
- [Express Adapter](/reference/v1/server/express-adapter) - Reference implementation
|
|
379
|
+
- [MastraServer Reference](/reference/v1/server/mastra-server) - Full API reference
|
|
380
|
+
- [createRoute() Reference](/reference/v1/server/create-route) - Creating type-safe custom routes
|
|
@@ -5,11 +5,11 @@ description: "Expose additional HTTP endpoints from your Mastra server."
|
|
|
5
5
|
|
|
6
6
|
# Custom API Routes
|
|
7
7
|
|
|
8
|
-
By default Mastra automatically exposes registered agents and workflows via
|
|
8
|
+
By default, Mastra automatically exposes registered agents and workflows via its server. For additional behavior you can define your own HTTP routes.
|
|
9
9
|
|
|
10
|
-
Routes are provided with a helper `registerApiRoute` from `@mastra/core/server`. Routes can live in the same file as the `Mastra` instance but separating them helps keep configuration concise.
|
|
10
|
+
Routes are provided with a helper `registerApiRoute()` from `@mastra/core/server`. Routes can live in the same file as the `Mastra` instance but separating them helps keep configuration concise.
|
|
11
11
|
|
|
12
|
-
```typescript title="src/mastra/index.ts" copy
|
|
12
|
+
```typescript title="src/mastra/index.ts" copy
|
|
13
13
|
import { Mastra } from "@mastra/core";
|
|
14
14
|
import { registerApiRoute } from "@mastra/core/server";
|
|
15
15
|
|
|
@@ -39,9 +39,9 @@ curl http://localhost:4111/my-custom-route
|
|
|
39
39
|
|
|
40
40
|
Each route's handler receives the Hono `Context`. Within the handler you can access the `Mastra` instance to fetch or call agents and workflows.
|
|
41
41
|
|
|
42
|
-
To add route-specific middleware pass a `middleware` array when calling `registerApiRoute`.
|
|
42
|
+
To add route-specific middleware pass a `middleware` array when calling `registerApiRoute()`.
|
|
43
43
|
|
|
44
|
-
```typescript title="src/mastra/index.ts" copy
|
|
44
|
+
```typescript title="src/mastra/index.ts" copy
|
|
45
45
|
import { Mastra } from "@mastra/core";
|
|
46
46
|
import { registerApiRoute } from "@mastra/core/server";
|
|
47
47
|
|
|
@@ -1,12 +1,18 @@
|
|
|
1
1
|
---
|
|
2
|
-
title: "
|
|
3
|
-
description: "
|
|
2
|
+
title: "Server Configuration | Server & DB"
|
|
3
|
+
description: "Configure the Mastra server with custom settings for port, timeout, CORS, and more."
|
|
4
4
|
---
|
|
5
5
|
|
|
6
|
-
#
|
|
6
|
+
# Server Configuration
|
|
7
7
|
|
|
8
8
|
When deploying your Mastra application to production, it runs as an HTTP server that exposes your agents, workflows, and other functionality as API endpoints. This page covers how to configure and customize the server for a production environment.
|
|
9
9
|
|
|
10
|
+
:::info
|
|
11
|
+
|
|
12
|
+
This page covers the `server` configuration options passed to the `Mastra` constructor. For running Mastra with your own HTTP server (Hono, Express, etc.), see [Server Adapters](/docs/v1/server-db/server-adapters).
|
|
13
|
+
|
|
14
|
+
:::
|
|
15
|
+
|
|
10
16
|
## Server architecture
|
|
11
17
|
|
|
12
18
|
Mastra uses [Hono](https://hono.dev) as its underlying HTTP server framework. When you build a Mastra application using `mastra build`, it generates a Hono-based HTTP server in the `.mastra` directory.
|
|
@@ -41,10 +47,6 @@ export const mastra = new Mastra({
|
|
|
41
47
|
});
|
|
42
48
|
```
|
|
43
49
|
|
|
44
|
-
The `method` option can be one of `"GET"`, `"POST"`, `"PUT"`,
|
|
45
|
-
`"DELETE"` or `"ALL"`. Using `"ALL"` will cause the handler to be
|
|
46
|
-
invoked for any HTTP method that matches the path.
|
|
47
|
-
|
|
48
50
|
## TypeScript configuration
|
|
49
51
|
|
|
50
52
|
Mastra requires `module` and `moduleResolution` values that support modern Node.js versions. Older settings like `CommonJS` or `node` are incompatible with Mastra’s packages and will cause resolution errors.
|
|
@@ -90,29 +92,6 @@ export const mastra = new Mastra({
|
|
|
90
92
|
|
|
91
93
|
## Stream data redaction
|
|
92
94
|
|
|
93
|
-
When streaming agent responses
|
|
94
|
-
|
|
95
|
-
- System prompts and agent instructions
|
|
96
|
-
- Tool definitions and their parameters
|
|
97
|
-
- API keys and other credentials in request bodies
|
|
98
|
-
- Internal configuration data
|
|
99
|
-
|
|
100
|
-
This redaction happens at the HTTP boundary, so internal callbacks like `onStepFinish` still have access to the full request data for debugging and observability purposes.
|
|
101
|
-
|
|
102
|
-
### Configuring redaction
|
|
103
|
-
|
|
104
|
-
By default, redaction is enabled. If you're using the server adapters directly (e.g., `@mastra/hono` or `@mastra/express`), you can configure this behavior:
|
|
105
|
-
|
|
106
|
-
```typescript title="Custom server setup" copy
|
|
107
|
-
import { HonoServerAdapter } from "@mastra/hono";
|
|
108
|
-
import { mastra } from "./mastra";
|
|
109
|
-
|
|
110
|
-
const adapter = new HonoServerAdapter({
|
|
111
|
-
mastra,
|
|
112
|
-
streamOptions: {
|
|
113
|
-
redact: true,
|
|
114
|
-
},
|
|
115
|
-
});
|
|
116
|
-
```
|
|
95
|
+
When streaming agent responses, the HTTP streaming layer redacts system prompts, tool definitions, API keys, and similar data from each chunk before sending it to clients. This is enabled by default.
|
|
117
96
|
|
|
118
|
-
|
|
97
|
+
If you're using server adapters directly, you can configure redaction behavior. See [Stream data redaction](/docs/v1/server-db/server-adapters#stream-data-redaction) in the Server Adapters docs.
|