Overview
MastraServer provides an HTTP server that exposes your Mastra agents, workflows, and custom APIs. It includes built-in support for Mastra Studio, authentication, CORS, and OpenAPI documentation.
ServerConfig
Configuration interface for the Mastra server.
interface ServerConfig {
port ?: number ;
host ?: string ;
studioBase ?: string ;
apiPrefix ?: string ;
timeout ?: number ;
apiRoutes ?: ApiRoute [];
middleware ?: Middleware | Middleware [];
cors ?: CorsOptions | false ;
build ?: BuildConfig ;
bodySizeLimit ?: number ;
auth ?: MastraAuthConfig | MastraAuthProvider ;
https ?: { key : Buffer ; cert : Buffer };
onError ?: ( err : Error , c : Context ) => Response | Promise < Response >;
}
Configuration Properties
host
string
default: "'localhost'"
Host for the server
Base path for Mastra Studio UI server : {
studioBase : '/my-mastra-studio'
}
Prefix for API routes server : {
apiPrefix : '/mastra'
}
Request timeout in milliseconds
middleware
Middleware | Middleware[]
Middleware for the server. Can be a single middleware or an array.
CORS configuration. Set to false to disable CORS. Default configuration: {
origin : '*' ,
allowMethods : [ 'GET' , 'POST' , 'PUT' , 'PATCH' , 'DELETE' , 'OPTIONS' ],
allowHeaders : [ 'Content-Type' , 'Authorization' , 'x-mastra-client-type' ],
exposeHeaders : [ 'Content-Length' , 'X-Requested-With' ],
credentials : false
}
Build configuration for the server Enable API request logging
Enable OpenAPI documentation
Body size limit in bytes (default: 4.5 MB)
auth
MastraAuthConfig | MastraAuthProvider
Authentication configuration for the server
https
{ key: Buffer; cert: Buffer }
HTTPS configuration. Provide key and cert files for running with HTTPS.
onError
(err: Error, c: Context) => Response | Promise<Response>
Custom error handler for unhandled errors. Use this to customize error responses or log errors to external services. server : {
onError : ( err , c ) => {
// Log to Sentry
Sentry . captureException ( err );
// Return custom response
return c . json ({
error: err . message ,
timestamp: new Date (). toISOString ()
}, 500 );
}
}
registerApiRoute
Function for creating custom API routes.
function registerApiRoute < P extends string >(
path : P ,
options : RegisterApiRouteOptions < P >
) : ApiRoute
URL path for the route. Must not start with /api (reserved for internal routes).
options
RegisterApiRouteOptions
required
Route configuration method
'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'ALL'
required
HTTP method for the route
Route handler function (mutually exclusive with createHandler)
createHandler
(c: Context) => Promise<Handler>
Factory function for creating the handler (mutually exclusive with handler)
OpenAPI documentation for the route
middleware
MiddlewareHandler | MiddlewareHandler[]
Middleware for this specific route
Whether this route requires authentication
Example Usage
Basic Server
import { Mastra } from '@mastra/core' ;
const mastra = new Mastra ({
agents: { /* ... */ },
server: {
port: 4111 ,
host: 'localhost'
}
});
Custom API Routes
import { Mastra , registerApiRoute } from '@mastra/core' ;
const mastra = new Mastra ({
agents: { assistant: myAgent },
server: {
port: 4111 ,
apiRoutes: [
registerApiRoute ( '/hello' , {
method: 'GET' ,
handler : async ( c ) => {
return c . json ({ message: 'Hello, World!' });
}
}),
registerApiRoute ( '/users/:id' , {
method: 'GET' ,
handler : async ( c ) => {
const id = c . req . param ( 'id' );
const mastra = c . get ( 'mastra' );
const requestContext = c . get ( 'requestContext' );
// Use Mastra resources
const storage = mastra . getStorage ();
// ... fetch user
return c . json ({ id , name: 'John Doe' });
}
}),
registerApiRoute ( '/data' , {
method: 'POST' ,
handler : async ( c ) => {
const body = await c . req . json ();
return c . json ({ received: body });
},
openapi: {
summary: 'Submit data' ,
description: 'Accepts JSON data' ,
requestBody: {
content: {
'application/json' : {
schema: {
type: 'object' ,
properties: {
name: { type: 'string' },
value: { type: 'number' }
}
}
}
}
}
}
})
]
}
});
Authentication
import { Mastra , defineAuth } from '@mastra/core' ;
const mastra = new Mastra ({
agents: { /* ... */ },
server: {
port: 4111 ,
auth: defineAuth ({
protected: [ / ^ \/ api \/ . * / ], // Protect all /api routes
public: [ '/api/health' , '/api/status' ],
authenticateToken : async ( token , request ) => {
// Verify JWT token
const user = await verifyToken ( token );
return user ;
},
authorize : async ( path , method , user , context ) => {
// Check if user has permission
if ( user . role === 'admin' ) return true ;
if ( path . startsWith ( '/api/public' )) return true ;
return false ;
}
})
}
});
CORS Configuration
const mastra = new Mastra ({
server: {
cors: {
origin: [ 'https://example.com' , 'https://app.example.com' ],
allowMethods: [ 'GET' , 'POST' , 'PUT' , 'DELETE' ],
allowHeaders: [ 'Content-Type' , 'Authorization' , 'X-Custom-Header' ],
credentials: true ,
maxAge: 86400
}
}
});
// Or disable CORS
const mastra2 = new Mastra ({
server: {
cors: false
}
});
Middleware
import { Mastra } from '@mastra/core' ;
const mastra = new Mastra ({
server: {
middleware: [
// Global logging middleware
async ( c , next ) => {
console . log ( ` ${ c . req . method } ${ c . req . path } ` );
await next ();
},
// Rate limiting middleware
async ( c , next ) => {
const ip = c . req . header ( 'x-forwarded-for' ) || 'unknown' ;
// Check rate limit...
await next ();
},
// Path-specific middleware
{
path: '/api/admin/*' ,
handler : async ( c , next ) => {
// Admin-only check
await next ();
}
}
]
}
});
OpenAPI Documentation
const mastra = new Mastra ({
server: {
build: {
openAPIDocs: true ,
swaggerUI: true ,
apiReqLogs: true
},
apiRoutes: [
registerApiRoute ( '/users' , {
method: 'GET' ,
handler : async ( c ) => {
return c . json ({ users: [] });
},
openapi: {
summary: 'List users' ,
description: 'Returns a list of all users' ,
responses: {
200 : {
description: 'Success' ,
content: {
'application/json' : {
schema: {
type: 'object' ,
properties: {
users: {
type: 'array' ,
items: { type: 'object' }
}
}
}
}
}
}
}
}
})
]
}
});
// Access Swagger UI at: http://localhost:4111/swagger
// Access OpenAPI spec at: http://localhost:4111/openapi.json
Error Handling
import { Mastra } from '@mastra/core' ;
import * as Sentry from '@sentry/node' ;
const mastra = new Mastra ({
server: {
onError : async ( err , c ) => {
// Log to Sentry
Sentry . captureException ( err , {
extra: {
path: c . req . path ,
method: c . req . method ,
headers: c . req . header ()
}
});
// Return user-friendly error
const isDev = process . env . NODE_ENV === 'development' ;
return c . json ({
error: isDev ? err . message : 'Internal server error' ,
timestamp: new Date (). toISOString (),
requestId: c . req . header ( 'x-request-id' )
}, 500 );
}
}
});
HTTPS Server
import { readFileSync } from 'fs' ;
import { Mastra } from '@mastra/core' ;
const mastra = new Mastra ({
server: {
port: 443 ,
https: {
key: readFileSync ( './key.pem' ),
cert: readFileSync ( './cert.pem' )
}
}
});