Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/mastra-ai/mastra/llms.txt

Use this file to discover all available pages before exploring further.

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

port
number
default:"4111"
Port for the server
host
string
default:"'localhost'"
Host for the server
studioBase
string
default:"'/'"
Base path for Mastra Studio UI
server: {
  studioBase: '/my-mastra-studio'
}
apiPrefix
string
default:"'/api'"
Prefix for API routes
server: {
  apiPrefix: '/mastra'
}
timeout
number
Request timeout in milliseconds
apiRoutes
ApiRoute[]
Custom API routes for the server. See registerApiRoute for creating routes.
middleware
Middleware | Middleware[]
Middleware for the server. Can be a single middleware or an array.
cors
CorsOptions | false
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
object
Build configuration for the server
bodySizeLimit
number
default:"4718592"
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
path
string
required
URL path for the route. Must not start with /api (reserved for internal routes).
options
RegisterApiRouteOptions
required
Route configuration

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')
    }
  }
});

Build docs developers (and LLMs) love