Class: MastraServer
@mastra/express subclass that stamps RequestContext with the
AppKit user, resource id, and a thread id backed by an HTTP-only
session cookie (appkit_<plugin-name>_session_id).
Extends
Section titled “Extends”MastraServer
Constructors
Section titled “Constructors”Constructor
Section titled “Constructor”new MastraServer(
config, …args):MastraServer
Parameters
Section titled “Parameters”config
Section titled “config”…[{ app: Application; bodyLimitOptions?: BodyLimitOptions; customApiRoutes?: ApiRoute[]; customRouteAuthConfig?: Map<string, boolean>; mastra: Mastra; mcpOptions?: MCPOptions; openapiPath?: string; prefix?: string; streamOptions?: StreamOptions; taskStore?: InMemoryTaskStore; tools?: ToolsInput; }]
Returns
Section titled “Returns”MastraServer
Overrides
Section titled “Overrides”ExpressMastraServer.constructor
Properties
Section titled “Properties”bodyLimitOptions?
Section titled “bodyLimitOptions?”
protectedoptionalbodyLimitOptions?:BodyLimitOptions
Inherited from
Section titled “Inherited from”ExpressMastraServer.bodyLimitOptions
component
Section titled “component”component:
RegisteredLogger
Inherited from
Section titled “Inherited from”ExpressMastraServer.component
customApiRoutes?
Section titled “customApiRoutes?”
protectedoptionalcustomApiRoutes?:ApiRoute[]
Inherited from
Section titled “Inherited from”ExpressMastraServer.customApiRoutes
customRouteAuthConfig?
Section titled “customRouteAuthConfig?”
protectedoptionalcustomRouteAuthConfig?:Map<string,boolean>
Inherited from
Section titled “Inherited from”ExpressMastraServer.customRouteAuthConfig
httpLoggingConfig?
Section titled “httpLoggingConfig?”
protectedoptionalhttpLoggingConfig?:HttpLoggingConfig
Inherited from
Section titled “Inherited from”ExpressMastraServer.httpLoggingConfig
logger
Section titled “logger”
protectedlogger:IMastraLogger
Inherited from
Section titled “Inherited from”ExpressMastraServer.logger
mastra
Section titled “mastra”
protectedmastra:Mastra
Inherited from
Section titled “Inherited from”ExpressMastraServer.mastra
mcpOptions?
Section titled “mcpOptions?”
protectedoptionalmcpOptions?:MCPOptions
Inherited from
Section titled “Inherited from”ExpressMastraServer.mcpOptions
optionalname?:string
Inherited from
Section titled “Inherited from”ExpressMastraServer.name
openapiPath?
Section titled “openapiPath?”
protectedoptionalopenapiPath?:string
Inherited from
Section titled “Inherited from”ExpressMastraServer.openapiPath
prefix?
Section titled “prefix?”
protectedoptionalprefix?:string
Inherited from
Section titled “Inherited from”ExpressMastraServer.prefix
streamOptions
Section titled “streamOptions”
protectedstreamOptions:StreamOptions
Inherited from
Section titled “Inherited from”ExpressMastraServer.streamOptions
taskStore?
Section titled “taskStore?”
protectedoptionaltaskStore?:InMemoryTaskStore
Inherited from
Section titled “Inherited from”ExpressMastraServer.taskStore
tools?
Section titled “tools?”
protectedoptionaltools?:ToolsInput
Inherited from
Section titled “Inherited from”ExpressMastraServer.tools
Accessors
Section titled “Accessors”Get Signature
Section titled “Get Signature”get
protectedapp():TApp
Protected getter for subclasses to access the app.
This allows subclasses to use this.app naturally.
Returns
Section titled “Returns”TApp
Inherited from
Section titled “Inherited from”ExpressMastraServer.app
Methods
Section titled “Methods”__setLogger()
Section titled “__setLogger()”__setLogger(
logger):void
Set the logger for the agent
Parameters
Section titled “Parameters”logger
Section titled “logger”IMastraLogger
Returns
Section titled “Returns”void
Inherited from
Section titled “Inherited from”ExpressMastraServer.__setLogger
__setRawConfig()
Section titled “__setRawConfig()”__setRawConfig(
rawConfig):void
Internal
Sets the raw storage configuration for this primitive.
Parameters
Section titled “Parameters”rawConfig
Section titled “rawConfig”Record<string, unknown>
Returns
Section titled “Returns”void
Inherited from
Section titled “Inherited from”ExpressMastraServer.__setRawConfig
applyRequestMetadataToContext()
Section titled “applyRequestMetadataToContext()”
protectedapplyRequestMetadataToContext(__namedParameters):void
Parameters
Section titled “Parameters”__namedParameters
Section titled “__namedParameters”getHeader
Section titled “getHeader”(name) => string | undefined
requestContext
Section titled “requestContext”RequestContext
Returns
Section titled “Returns”void
Inherited from
Section titled “Inherited from”ExpressMastraServer.applyRequestMetadataToContext
buildCustomRouteHandler()
Section titled “buildCustomRouteHandler()”
protectedbuildCustomRouteHandler():Promise<boolean>
Creates an internal Hono sub-app with all custom API routes registered. Stores the handler on this instance for use by handleCustomRouteRequest(). Returns true if custom routes were found and registered.
Returns
Section titled “Returns”Promise<boolean>
Inherited from
Section titled “Inherited from”ExpressMastraServer.buildCustomRouteHandler
checkRouteAuth()
Section titled “checkRouteAuth()”
protectedcheckRouteAuth(route,context):Promise<{error:string;headers?:Record<string,string>;status:number; } |null>
Check if the current request should be authenticated/authorized. Returns null if auth passes, or an error response if it fails.
This is a thin wrapper around coreAuthMiddleware that:
- Routes to the correct auth provider (studio vs server) based on request headers
- Handles route-level requiresAuth opt-out (not available in global middleware)
- Delegates all other auth logic to coreAuthMiddleware
- Translates the AuthResult into the {status, error} format adapters expect
Security: When x-mastra-client-type: studio header is present and studio auth
is configured, we ONLY use studio auth. If authentication fails, we return 401
and redirect to login - we do NOT fall back to server auth. This prevents
external users from spoofing the studio header to access Studio UI.
Parameters
Section titled “Parameters”ServerRoute
context
Section titled “context”buildAuthorizeContext?
Section titled “buildAuthorizeContext?”() => unknown
Build framework-specific context for authorize() callback
getHeader
Section titled “getHeader”(name) => string | undefined
getQuery
Section titled “getQuery”(name) => string | undefined
method
Section titled “method”string
string
request?
Section titled “request?”Request
Raw Request object for cookie-based auth providers
requestContext
Section titled “requestContext”RequestContext
Returns
Section titled “Returns”Promise<{ error: string; headers?: Record<string, string>; status: number; } | null>
Inherited from
Section titled “Inherited from”ExpressMastraServer.checkRouteAuth
checkRoutePermission()
Section titled “checkRoutePermission()”
protectedcheckRoutePermission(route,userPermissions,hasPermissionFn,requestContext?): {error:string;message:string;status:number; } |null
Check if the user has the required permission for a route.
Uses convention-based permission derivation:
- If route has explicit
requiresPermission, use that - Otherwise, derive permission from path/method (e.g., GET /agents → agents:read)
- Routes with
requiresAuth: falseskip permission checks
Permission checks use the RBAC provider that corresponds to the auth mode (studio vs server) that was used for authentication.
Parameters
Section titled “Parameters”ServerRoute
The route being accessed
userPermissions
Section titled “userPermissions”string[] | undefined
The user’s permissions from the request context
hasPermissionFn
Section titled “hasPermissionFn”(userPerms, required) => boolean
Function to check if user permissions match required permission
requestContext?
Section titled “requestContext?”RequestContext<unknown>
Request context to determine which RBAC provider to use
Returns
Section titled “Returns”{ error: string; message: string; status: number; } | null
Error response if permission denied, null if allowed
Inherited from
Section titled “Inherited from”ExpressMastraServer.checkRoutePermission
configureMlflowTraceId()
Section titled “configureMlflowTraceId()”configureMlflowTraceId(
res):void
Stamp the turn’s MLflow trace id on the response so the chat client
can attach thumbs / comment feedback to it later. MLflow derives
its trace id from the OpenTelemetry trace id (tr-<hex>), and every
Mastra span for this request inherits the ambient OTel context (see
observability.ts), so the active span’s trace id here is the id
MLflow will record for the turn.
No-op unless feedback is enabled, and when no live OTel span is active (e.g. the OTLP SDK isn’t registered): in that case the header is simply absent and the client hides feedback for that message, degrading gracefully rather than emitting a bogus trace id.
Parameters
Section titled “Parameters”Response
Returns
Section titled “Returns”void
configureRequestContextModelOverride()
Section titled “configureRequestContextModelOverride()”configureRequestContextModelOverride(
req,requestContext):void
Parameters
Section titled “Parameters”Request
requestContext
Section titled “requestContext”RequestContext
Returns
Section titled “Returns”void
configureRequestContextRequestId()
Section titled “configureRequestContextRequestId()”configureRequestContextRequestId(
req,res,requestContext):void
Stamp a per-request id and echo it on the response so an upstream
proxy / curl client / browser-side log line can pair its view of
the request with the matching trace span. Reuses X-Request-Id
when the upstream already supplies one so multi-hop traces stay
joined; otherwise mints a UUIDv4.
The id is surfaced as mastra__requestId span metadata via
TRACE_REQUEST_CONTEXT_KEYS and as the X-Request-Id
response header so dev tools can copy it from either side.
Parameters
Section titled “Parameters”Request
Response
requestContext
Section titled “requestContext”RequestContext
Returns
Section titled “Returns”void
configureRequestContextScopes()
Section titled “configureRequestContextScopes()”configureRequestContextScopes(
req,requestContext):void
Stamp OAuth scopes from the forwarded access token on MASTRA_SCOPES_KEY for workspace mount gating.
Parameters
Section titled “Parameters”Request
requestContext
Section titled “requestContext”RequestContext
Returns
Section titled “Returns”void
configureRequestContextThreadId()
Section titled “configureRequestContextThreadId()”configureRequestContextThreadId(
req,res,requestContext):void
Resolve the thread id this request targets and pin it on
RequestContext (consumed by the agent stream for persistence and
by the history / threads routes). Resolution order:
- A client-supplied thread id (the thread-selection header /
?threadId=query). This is how the chat UI references a specific conversation among the many a user owns - it picks a thread id from the/threadslisting (or mints one for a new conversation) and stamps it here. The id is scoped to the caller’s resource by the recall / list routes, so a client can only ever read or write its own threads. - The per-session cookie (
appkit_<plugin-name>_session_id), minted on first contact. This is the default single-thread fallback for clients that don’t manage threads explicitly, so existing embeds keep one stable conversation per session with no client changes.
Parameters
Section titled “Parameters”Request
Response
requestContext
Section titled “requestContext”RequestContext
Returns
Section titled “Returns”void
configureRequestContextUser()
Section titled “configureRequestContextUser()”configureRequestContextUser(
req,requestContext):Promise<void>
Parameters
Section titled “Parameters”Request
requestContext
Section titled “requestContext”RequestContext
Returns
Section titled “Returns”Promise<void>
createContextMiddleware()
Section titled “createContextMiddleware()”createContextMiddleware(): (
req,res,next) =>Promise<void>
Returns
Section titled “Returns”(req, res, next) => Promise<void>
Inherited from
Section titled “Inherited from”ExpressMastraServer.createContextMiddleware
getApp()
Section titled “getApp()”getApp<
T>():T
Get the app instance.
Returns the server app that was passed to the constructor. This allows users to access the underlying server framework’s app for direct operations like calling routes via app.fetch() (Hono) or using the app for testing.
Type Parameters
Section titled “Type Parameters”T = Application
The expected type of the app (defaults to TApp)
Returns
Section titled “Returns”T
The app instance cast to T. Callers are responsible for ensuring T matches the actual app type.
Example
Section titled “Example”const app = adapter.getApp<Hono>();const response = await app.fetch(new Request('http://localhost/api/agents'));Inherited from
Section titled “Inherited from”ExpressMastraServer.getApp
getEffectiveAuthConfig()
Section titled “getEffectiveAuthConfig()”
protectedgetEffectiveAuthConfig(getHeader): {authConfig:unknown;authMode:MastraAuthMode; } |null
Determines which auth configuration to use for the current request.
Request routing logic:
- If
x-mastra-client-type: studioheader is present ANDstudio.authis configured: → Use studio auth (for internal team members accessing Studio UI) - If studio header is present but
studio.authis NOT configured: → No auth required (Studio development mode) - Otherwise: → Use server auth (for external customers calling API)
Security note: The header is only for routing - auth validation happens via session cookies/tokens. If someone spoofs the studio header but doesn’t have a valid studio session, they’ll get a 401 (not fall back to server auth).
Parameters
Section titled “Parameters”getHeader
Section titled “getHeader”(name) => string | undefined
Returns
Section titled “Returns”{ authConfig: unknown; authMode: MastraAuthMode; } | null
Inherited from
Section titled “Inherited from”ExpressMastraServer.getEffectiveAuthConfig
getEffectiveFGAProvider()
Section titled “getEffectiveFGAProvider()”
protectedgetEffectiveFGAProvider(requestContext):IFGAProvider<any> |undefined
Gets the effective FGA provider for the current request based on auth mode.
Parameters
Section titled “Parameters”requestContext
Section titled “requestContext”RequestContext
Returns
Section titled “Returns”IFGAProvider<any> | undefined
Inherited from
Section titled “Inherited from”ExpressMastraServer.getEffectiveFGAProvider
getEffectiveRBACProvider()
Section titled “getEffectiveRBACProvider()”
protectedgetEffectiveRBACProvider(requestContext):IRBACProvider<any> |undefined
Gets the effective RBAC provider for the current request based on auth mode.
Parameters
Section titled “Parameters”requestContext
Section titled “requestContext”RequestContext
Returns
Section titled “Returns”IRBACProvider<any> | undefined
Inherited from
Section titled “Inherited from”ExpressMastraServer.getEffectiveRBACProvider
getParams()
Section titled “getParams()”getParams(
route,request):Promise<ParsedRequestParams>
Parameters
Section titled “Parameters”ServerRoute
request
Section titled “request”Request
Returns
Section titled “Returns”Promise<ParsedRequestParams>
Inherited from
Section titled “Inherited from”ExpressMastraServer.getParams
handleCustomRouteRequest()
Section titled “handleCustomRouteRequest()”
protectedhandleCustomRouteRequest(url,method,headers,body,requestContext?,signal?):Promise<Response|null>
Forwards a request to the internal custom route handler. Returns the Response if a custom route matched, or null to fall through.
Parameters
Section titled “Parameters”string
method
Section titled “method”string
headers
Section titled “headers”Record<string, string | string[] | undefined>
unknown
requestContext?
Section titled “requestContext?”RequestContext<unknown>
signal?
Section titled “signal?”AbortSignal
Returns
Section titled “Returns”Promise<Response | null>
Inherited from
Section titled “Inherited from”ExpressMastraServer.handleCustomRouteRequest
init()
Section titled “init()”init():
Promise<void>
Returns
Section titled “Returns”Promise<void>
Inherited from
Section titled “Inherited from”ExpressMastraServer.init
mergeRequestContext()
Section titled “mergeRequestContext()”
protectedmergeRequestContext(__namedParameters):RequestContext
Parameters
Section titled “Parameters”__namedParameters
Section titled “__namedParameters”bodyRequestContext?
Section titled “bodyRequestContext?”Record<string, any>
paramsRequestContext?
Section titled “paramsRequestContext?”Record<string, any>
Returns
Section titled “Returns”RequestContext
Inherited from
Section titled “Inherited from”ExpressMastraServer.mergeRequestContext
parseBody()
Section titled “parseBody()”parseBody(
route,body):Promise<unknown>
Parameters
Section titled “Parameters”ServerRoute
unknown
Returns
Section titled “Returns”Promise<unknown>
Inherited from
Section titled “Inherited from”ExpressMastraServer.parseBody
parsePathParams()
Section titled “parsePathParams()”parsePathParams(
route,params):Promise<Record<string,any>>
Parameters
Section titled “Parameters”ServerRoute
params
Section titled “params”Record<string, string>
Returns
Section titled “Returns”Promise<Record<string, any>>
Inherited from
Section titled “Inherited from”ExpressMastraServer.parsePathParams
parseQueryParams()
Section titled “parseQueryParams()”parseQueryParams(
route,params):Promise<Record<string,any>>
Parameters
Section titled “Parameters”ServerRoute
params
Section titled “params”Record<string, QueryParamValue>
Returns
Section titled “Returns”Promise<Record<string, any>>
Inherited from
Section titled “Inherited from”ExpressMastraServer.parseQueryParams
registerAuthMiddleware()
Section titled “registerAuthMiddleware()”registerAuthMiddleware():
void
Returns
Section titled “Returns”void
Overrides
Section titled “Overrides”ExpressMastraServer.registerAuthMiddleware
registerContextMiddleware()
Section titled “registerContextMiddleware()”registerContextMiddleware():
void
Returns
Section titled “Returns”void
Inherited from
Section titled “Inherited from”ExpressMastraServer.registerContextMiddleware
registerCustomApiRoutes()
Section titled “registerCustomApiRoutes()”registerCustomApiRoutes():
Promise<void>
Override in adapters to register custom API routes defined via registerApiRoute(). Called by init() between registerAuthMiddleware() and registerRoutes().
Returns
Section titled “Returns”Promise<void>
Inherited from
Section titled “Inherited from”ExpressMastraServer.registerCustomApiRoutes
registerHttpLoggingMiddleware()
Section titled “registerHttpLoggingMiddleware()”registerHttpLoggingMiddleware():
void
Returns
Section titled “Returns”void
Inherited from
Section titled “Inherited from”ExpressMastraServer.registerHttpLoggingMiddleware
registerOpenAPIRoute()
Section titled “registerOpenAPIRoute()”registerOpenAPIRoute(
app,config,__namedParameters):Promise<void>
Parameters
Section titled “Parameters”Application
config
Section titled “config”OpenAPIConfig | undefined
__namedParameters
Section titled “__namedParameters”prefix?
Section titled “prefix?”string
Returns
Section titled “Returns”Promise<void>
Inherited from
Section titled “Inherited from”ExpressMastraServer.registerOpenAPIRoute
registerRoute()
Section titled “registerRoute()”registerRoute(
app,route,__namedParameters?):Promise<void>
Parameters
Section titled “Parameters”Application
ServerRoute
__namedParameters?
Section titled “__namedParameters?”prefix?
Section titled “prefix?”string
Returns
Section titled “Returns”Promise<void>
Inherited from
Section titled “Inherited from”ExpressMastraServer.registerRoute
registerRoutes()
Section titled “registerRoutes()”registerRoutes():
Promise<void>
Returns
Section titled “Returns”Promise<void>
Inherited from
Section titled “Inherited from”ExpressMastraServer.registerRoutes
resolveValidationError()
Section titled “resolveValidationError()”
protectedresolveValidationError(route,error,context):ValidationErrorResponse
Parameters
Section titled “Parameters”ServerRoute
ZodError
context
Section titled “context”ValidationErrorContext
Returns
Section titled “Returns”ValidationErrorResponse
Inherited from
Section titled “Inherited from”ExpressMastraServer.resolveValidationError
sendResponse()
Section titled “sendResponse()”sendResponse(
route,response,result,request?,prefix?):Promise<void>
Parameters
Section titled “Parameters”ServerRoute
response
Section titled “response”Response
result
Section titled “result”unknown
request?
Section titled “request?”Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>
prefix?
Section titled “prefix?”string
Returns
Section titled “Returns”Promise<void>
Inherited from
Section titled “Inherited from”ExpressMastraServer.sendResponse
shouldLogRequest()
Section titled “shouldLogRequest()”
protectedshouldLogRequest(path):boolean
Determines if a request to the given path should be logged.
Parameters
Section titled “Parameters”string
The request path to check
Returns
Section titled “Returns”boolean
true if the request should be logged, false otherwise
Inherited from
Section titled “Inherited from”ExpressMastraServer.shouldLogRequest
stream()
Section titled “stream()”stream(
route,res,result):Promise<void>
Parameters
Section titled “Parameters”ServerRoute
Response
result
Section titled “result”fullStream
Section titled “fullStream”ReadableStream
Returns
Section titled “Returns”Promise<void>
Inherited from
Section titled “Inherited from”ExpressMastraServer.stream
toRawConfig()
Section titled “toRawConfig()”toRawConfig():
Record<string,unknown> |undefined
Returns the raw storage configuration this primitive was created from, or undefined if it was created from code.
Returns
Section titled “Returns”Record<string, unknown> | undefined
Inherited from
Section titled “Inherited from”ExpressMastraServer.toRawConfig
validateAgentBuilderLicense()
Section titled “validateAgentBuilderLicense()”validateAgentBuilderLicense():
Promise<void>
Validate that an Agent Builder configuration has a valid EE license. Throws if the editor is configured with builder support but no valid EE license is available.
Returns
Section titled “Returns”Promise<void>
Inherited from
Section titled “Inherited from”ExpressMastraServer.validateAgentBuilderLicense
validateCustomRoutePaths()
Section titled “validateCustomRoutePaths()”
protectedvalidateCustomRoutePaths(routes):void
Validates that no custom route path collides with the built-in route prefix.
Throws if any route path starts with the server’s apiPrefix.
Parameters
Section titled “Parameters”routes
Section titled “routes”ApiRoute[]
Returns
Section titled “Returns”void
Inherited from
Section titled “Inherited from”ExpressMastraServer.validateCustomRoutePaths
validateEELicense()
Section titled “validateEELicense()”validateEELicense():
Promise<void>
Validate that EE features have a valid license in production. Throws if RBAC or FGA is configured without a valid license outside dev/test environments.
Returns
Section titled “Returns”Promise<void>
Inherited from
Section titled “Inherited from”ExpressMastraServer.validateEELicense
validateFGAPolicyCoverage()
Section titled “validateFGAPolicyCoverage()”validateFGAPolicyCoverage():
Promise<void>
Validate route-level FGA policy coverage when an FGA provider opts into startup checks.
Returns
Section titled “Returns”Promise<void>
Inherited from
Section titled “Inherited from”ExpressMastraServer.validateFGAPolicyCoverage
writeCustomRouteResponse()
Section titled “writeCustomRouteResponse()”
protectedwriteCustomRouteResponse(response,nodeRes,signal?):Promise<void>
Pipes a custom route Response to a Node.js ServerResponse (http.ServerResponse). Works with Koa (ctx.res), Express (res), and Fastify (reply.raw).
Parameters
Section titled “Parameters”response
Section titled “response”Response
nodeRes
Section titled “nodeRes”object & WritableStream
signal?
Section titled “signal?”AbortSignal
Returns
Section titled “Returns”Promise<void>
Inherited from
Section titled “Inherited from”ExpressMastraServer.writeCustomRouteResponse