docs/src/content/en/reference/server/mastra-server.mdx
import PropertiesTable from "@site/src/components/PropertiesTable";
The MastraServer abstract class is the base for all server adapters. Extend this class to create adapters for frameworks other than Hono or Express.
import { MastraServer } from '@mastra/server/server-adapter'
MastraServer<TApp, TRequest, TResponse>
| Parameter | Description |
|---|---|
TApp | Framework app type (e.g., Hono, Application) |
TRequest | Framework request type |
TResponse | Framework response/context type |
constructor(options: MastraServerOptions<TApp>)
<PropertiesTable
content={[
{
name: 'app',
type: 'TApp',
description: 'Framework app instance',
isOptional: false,
},
{
name: 'mastra',
type: 'Mastra',
description: 'Mastra instance',
isOptional: false,
},
{
name: 'prefix',
type: 'string',
description: 'Route path prefix (e.g., /api/v2)',
isOptional: true,
defaultValue: "''",
},
{
name: 'openapiPath',
type: 'string',
description: 'Path to serve OpenAPI spec',
isOptional: true,
defaultValue: "''",
},
{
name: 'bodyLimitOptions',
type: 'BodyLimitOptions',
description: 'Request body size limits',
isOptional: true,
},
{
name: 'streamOptions',
type: 'StreamOptions',
description: 'Stream redaction config',
isOptional: true,
defaultValue: '{ redact: true }',
},
{
name: 'customRouteAuthConfig',
type: 'Map<string, boolean>',
description: 'Per-route auth overrides',
isOptional: true,
},
{
name: 'tools',
type: 'Record<string, Tool>',
description: 'Available tools for the server',
isOptional: true,
},
{
name: 'taskStore',
type: 'InMemoryTaskStore',
description: 'Task store for A2A (Agent-to-Agent) operations',
isOptional: true,
},
{
name: 'mcpOptions',
type: 'MCPOptions',
description: 'MCP transport options for serverless environments',
isOptional: true,
},
]}
/>
These methods must be implemented by adapters:
registerContextMiddleware()Attach Mastra context to every request.
abstract registerContextMiddleware(): void
Context to attach:
mastra - Mastra instancerequestContext - Request-scoped contexttools - Available toolsabortSignal - Request cancellation signalregisterAuthMiddleware()Register authentication and authorization middleware.
abstract registerAuthMiddleware(): void
registerRoute()Register a single route with the framework.
abstract registerRoute(
app: TApp,
route: ServerRoute,
options: { prefix?: string }
): Promise<void>
getParams()Extract parameters from the request.
abstract getParams(
route: ServerRoute,
request: TRequest
): Promise<{
urlParams: Record<string, string>;
queryParams: Record<string, string>;
body: unknown;
}>
sendResponse()Send response based on route type.
abstract sendResponse(
route: ServerRoute,
response: TResponse,
result: unknown
): Promise<unknown>
stream()Handle streaming responses.
abstract stream(
route: ServerRoute,
response: TResponse,
result: unknown
): Promise<unknown>
init()Initialize the server by registering all middleware and routes.
async init(): Promise<void>
Calls in order:
registerContextMiddleware()registerAuthMiddleware()registerRoutes()registerRoutes()Register all Mastra routes.
async registerRoutes(): Promise<void>
getApp()Get the framework app instance.
getApp<T = TApp>(): T
parsePathParams()Validate path parameters with the route's Zod schema.
async parsePathParams(
route: ServerRoute,
params: Record<string, string>
): Promise<Record<string, unknown>>
parseQueryParams()Validate query parameters with the route's Zod schema.
async parseQueryParams(
route: ServerRoute,
params: Record<string, string>
): Promise<Record<string, unknown>>
parseBody()Validate request body with the route's Zod schema.
async parseBody(
route: ServerRoute,
body: unknown
): Promise<unknown>
registerOpenAPIRoute()Register an endpoint that serves the OpenAPI specification.
async registerOpenAPIRoute(
app: TApp,
config: OpenAPIConfig,
options: { prefix?: string }
): Promise<void>
mergeRequestContext()Merge request context from multiple sources (query params and body).
protected mergeRequestContext(options: {
paramsRequestContext?: Record<string, any>;
bodyRequestContext?: Record<string, any>;
}): RequestContext
BodyLimitOptionsinterface BodyLimitOptions {
maxSize: number
onError: (error: unknown) => unknown
}
StreamOptionsinterface StreamOptions {
redact?: boolean
}
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. |
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
// Implement auth
}
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
}
}