Skip to main content

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.

Import
Direct link to Import

import { MastraServer } from '@mastra/server/server-adapter'

Type parameters
Direct link to Type parameters

MastraServer<TApp, TRequest, TResponse>
ParameterDescription
TAppFramework app type (e.g., Hono, Application)
TRequestFramework request type
TResponseFramework response/context type

Constructor
Direct link to Constructor

constructor(options: MastraServerOptions<TApp>)

Options
Direct link to Options

app:

TApp
Framework app instance

mastra:

Mastra
Mastra instance

prefix?:

string
= ''
Route path prefix (e.g., `/api/v2`)

openapiPath?:

string
= ''
Path to serve OpenAPI spec

bodyLimitOptions?:

BodyLimitOptions
Request body size limits

streamOptions?:

StreamOptions
= { redact: true }
Stream redaction config

customRouteAuthConfig?:

Map<string, boolean>
Per-route auth overrides

tools?:

Record<string, Tool>
Available tools for the server

taskStore?:

InMemoryTaskStore
Task store for A2A (Agent-to-Agent) operations

mcpOptions?:

MCPOptions
MCP transport options for serverless environments

Abstract methods
Direct link to Abstract methods

These methods must be implemented by adapters:

registerContextMiddleware()
Direct link to registercontextmiddleware

Attach Mastra context to every request.

abstract registerContextMiddleware(): void

Context to attach:

  • mastra - Mastra instance
  • requestContext - Request-scoped context
  • tools - Available tools
  • abortSignal - Request cancellation signal

registerAuthMiddleware()
Direct link to 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()
Direct link to registerroute

Register a single route with the framework.

abstract registerRoute(
app: TApp,
route: ServerRoute,
options: { prefix?: string }
): Promise<void>

getParams()
Direct link to getparams

Extract parameters from the request.

abstract getParams(
route: ServerRoute,
request: TRequest
): Promise<{
urlParams: Record<string, string>;
queryParams: Record<string, string>;
body: unknown;
}>

sendResponse()
Direct link to sendresponse

Send response based on route type.

abstract sendResponse(
route: ServerRoute,
response: TResponse,
result: unknown
): Promise<unknown>

stream()
Direct link to stream

Handle streaming responses.

abstract stream(
route: ServerRoute,
response: TResponse,
result: unknown
): Promise<unknown>

Instance methods
Direct link to Instance methods

init()
Direct link to init

Initialize the server by registering all middleware and routes.

async init(): Promise<void>

Calls in order:

  1. registerContextMiddleware()
  2. registerAuthMiddleware()
  3. registerRoutes()

registerRoutes()
Direct link to registerroutes

Register all Mastra routes.

async registerRoutes(): Promise<void>

getApp()
Direct link to getapp

Get the framework app instance.

getApp<T = TApp>(): T

parsePathParams()
Direct link to parsepathparams

Validate path parameters with the route's Zod schema.

async parsePathParams(
route: ServerRoute,
params: Record<string, string>
): Promise<Record<string, unknown>>

parseQueryParams()
Direct link to parsequeryparams

Validate query parameters with the route's Zod schema.

async parseQueryParams(
route: ServerRoute,
params: Record<string, string>
): Promise<Record<string, unknown>>

parseBody()
Direct link to parsebody

Validate request body with the route's Zod schema.

async parseBody(
route: ServerRoute,
body: unknown
): Promise<unknown>

registerOpenAPIRoute()
Direct link to registeropenapiroute

Register an endpoint that serves the OpenAPI specification.

async registerOpenAPIRoute(
app: TApp,
config: OpenAPIConfig,
options: { prefix?: string }
): Promise<void>

Protected methods
Direct link to Protected methods

mergeRequestContext()
Direct link to mergerequestcontext

Merge request context from multiple sources (query params and body).

protected mergeRequestContext(options: {
paramsRequestContext?: Record<string, any>;
bodyRequestContext?: Record<string, any>;
}): RequestContext

Types
Direct link to Types

BodyLimitOptions
Direct link to bodylimitoptions

interface BodyLimitOptions {
maxSize: number
onError: (error: unknown) => unknown
}

StreamOptions
Direct link to streamoptions

interface StreamOptions {
redact?: boolean
}

MCPOptions
Direct link to MCPOptions

interface MCPOptions {
serverless?: boolean
sessionIdGenerator?: () => string
}
PropertyDescription
serverlessWhen true, runs MCP in stateless mode without session management. Use for serverless environments like Cloudflare Workers or Vercel Edge.
sessionIdGeneratorCustom function to generate session IDs.

Example
Direct link to Example

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
}
}