MastraServer
The MastraServer abstract class is the base for all server adapters. Extend this class to create adapters for frameworks other than Hono or Express.
ImportImport的直接链接
import { MastraServer } from '@mastra/server/server-adapter'
Type parametersType parameters的直接链接
MastraServer<TApp, TRequest, TResponse>
| Parameter | Description |
|---|---|
TApp | Framework app type (e.g., Hono, Application) |
TRequest | Framework request type |
TResponse | Framework response/context type |
ConstructorConstructor的直接链接
constructor(options: MastraServerOptions<TApp>)
OptionsOptions的直接链接
app:
mastra:
prefix?:
/api/v2)openapiPath?:
bodyLimitOptions?:
streamOptions?:
customRouteAuthConfig?:
tools?:
taskStore?:
mcpOptions?:
Abstract methodsAbstract methods的直接链接
These methods must be implemented by adapters:
registerContextMiddleware()registercontextmiddleware的直接链接
Attach Mastra context to every request.
abstract registerContextMiddleware(): void
Context to attach:
mastra- Mastra instancerequestContext- Request-scoped contexttools- Available toolsabortSignal- Request cancellation signal
registerAuthMiddleware()registerauthmiddleware的直接链接
Run the adapter auth hook during initialization. Official adapters may implement this as a no-op when auth is enforced per-route.
abstract registerAuthMiddleware(): void
registerRoute()registerroute的直接链接
Register a single route with the framework.
abstract registerRoute(
app: TApp,
route: ServerRoute,
options: { prefix?: string }
): Promise<void>
getParams()getparams的直接链接
Extract parameters from the request.
abstract getParams(
route: ServerRoute,
request: TRequest
): Promise<{
urlParams: Record<string, string>;
queryParams: Record<string, string | string[]>;
body: unknown;
}>
sendResponse()sendresponse的直接链接
Send response based on route type.
abstract sendResponse(
route: ServerRoute,
response: TResponse,
result: unknown
): Promise<unknown>
stream()stream的直接链接
Handle streaming responses.
abstract stream(
route: ServerRoute,
response: TResponse,
result: unknown
): Promise<unknown>
Instance methodsInstance methods的直接链接
init()init的直接链接
Initialize the server by registering all middleware and routes.
async init(): Promise<void>
Calls in order:
registerContextMiddleware()registerAuthMiddleware()registerRoutes()
registerRoutes()registerroutes的直接链接
Register all Mastra routes.
async registerRoutes(): Promise<void>
getApp()getapp的直接链接
Get the framework app instance.
getApp<T = TApp>(): T
parsePathParams()parsepathparams的直接链接
Validate path parameters with the route's Zod schema.
async parsePathParams(
route: ServerRoute,
params: Record<string, string>
): Promise<Record<string, unknown>>
parseQueryParams()parsequeryparams的直接链接
Validate query parameters with the route's Zod schema.
async parseQueryParams(
route: ServerRoute,
params: Record<string, string>
): Promise<Record<string, unknown>>
parseBody()parsebody的直接链接
Validate request body with the route's Zod schema.
async parseBody(
route: ServerRoute,
body: unknown
): Promise<unknown>
registerOpenAPIRoute()registeropenapiroute的直接链接
Register an endpoint that serves the OpenAPI specification.
async registerOpenAPIRoute(
app: TApp,
config: OpenAPIConfig,
options: { prefix?: string }
): Promise<void>
Protected methodsProtected methods的直接链接
mergeRequestContext()mergerequestcontext的直接链接
Merge request context from multiple sources (query params and body).
protected mergeRequestContext(options: {
paramsRequestContext?: Record<string, any>;
bodyRequestContext?: Record<string, any>;
}): RequestContext
TypesTypes的直接链接
BodyLimitOptionsbodylimitoptions的直接链接
interface BodyLimitOptions {
maxSize: number
onError: (error: unknown) => unknown
}
StreamOptionsstreamoptions的直接链接
interface StreamOptions {
redact?: boolean
}
MCPOptionsMCPOptions的直接链接
interface MCPOptions {
serverless?: boolean
sessionIdGenerator?: () => string
}
| Property | Description |
|---|---|
serverless | When true, runs MCP in stateless mode without session management. Use for serverless environments like Cloudflare Workers or Vercel Edge. |
sessionIdGenerator | Custom function to generate session IDs. |
ExampleExample的直接链接
import { MastraServer, ServerRoute } from '@mastra/server/server-adapter'
import type { Mastra } from '@mastra/core'
export class MyServer extends MastraServer<MyApp, MyRequest, MyResponse> {
registerContextMiddleware(): void {
this.app.use('*', (req, res, next) => {
res.locals.mastra = this.mastra
next()
})
}
registerAuthMiddleware(): void {
const auth = this.mastra.getServer()?.auth
if (!auth) return
// Register global auth middleware, or leave this empty and
// enforce auth when routes are registered.
}
async registerRoute(app, route, { prefix }) {
// Implement route registration
}
async getParams(route, request) {
return {
urlParams: request.params,
queryParams: request.query,
body: request.body,
}
}
async sendResponse(route, response, result) {
return response.json(result)
}
async stream(route, response, result) {
// Implement streaming
}
}
RelatedRelated的直接链接
- Server Adapters: Using adapters
- Custom Adapters: Creating custom adapters
- createRoute(): Creating custom routes