Skip to main content

MastraFactory class

MastraFactory assembles the storage domains, integrations, rules, routes, agent controller, tools, and background workers used by a Mastra Factory server. Its prepare() method returns configuration for a Mastra instance, and finalize() starts the runtime after that instance exists.

Install the package:

npm install @mastra/factory

Quickstart

Create the Factory, pass the result of prepare() to a literal new Mastra() call, then call finalize():

import { Mastra } from '@mastra/core/mastra'
import { MastraFactory } from '@mastra/factory'
import { LibSQLFactoryStorage } from '@mastra/libsql'

const storage = new LibSQLFactoryStorage({
	id: 'factory-storage',
	url: 'file:./factory.db',
})

export const factory = new MastraFactory({
	storage,
	auth: null,
})

const prepared = await factory.prepare()

export const mastra = new Mastra({
	...prepared,
	bundler: {
		transpilePackages: ['@mastra/factory'],
	},
})

await factory.finalize()

Constructor parameters

storage:
FactoryStorage
Storage backend for agent data and Factory domains. Use `PgFactoryStorage` from `@mastra/pg` for deployments or `LibSQLFactoryStorage` from `@mastra/libsql` for local development.
auth?:
IMastraAuthProvider | null
= MastraAuthStudio
Authentication provider for the Factory server. Omit this property to use the Mastra Studio authentication provider, pass another provider to replace it, or pass `null` to disable authentication.
vector?:
MastraVector
Vector store used by the agent controller for features such as semantic recall. For PostgreSQL deployments, this is commonly a `PgVector` connected to the same database as Factory storage.
pubsub?:
PubSub
Cross-process pub/sub provider used for distributed runtime coordination. Omit it to use the in-process behavior suitable for a single server process.
publicUrl?:
string
= "http://localhost:5173"
Browser-facing Factory origin used for authentication and integration callback URLs. The default is the local Factory UI origin. When the UI is hosted separately, set this to the public API origin. Factory removes trailing slashes before using the value.
allowedOrigins?:
string[]
= []
Origins allowed to make credentialed cross-origin requests to the Factory server.
sandbox?:
MastraFactorySandboxConfig
Sandbox template and provisioning limits for project workspaces. When omitted, sandbox-backed operations are unavailable.
stateSecret?:
string
Secret used to sign OAuth state. When omitted, Factory generates a per-process value. `prepare()` throws if a configured integration declares `requiresStableStateSigner` and no stable secret is provided.
integrations?:
FactoryIntegration[]
Integration instances that contribute routes, capabilities, tools, observers, and workers. Integration `id` values must be unique. When `MASTRA_PLATFORM_SECRET_KEY` is set, Factory adds the Platform GitHub and Linear integrations for any missing `github` or `linear` IDs. Explicit integrations with those IDs take precedence.
rules?:
FactoryRules
= builtInFactoryRules()
Rules that respond to board transitions, tool results, GitHub events, and Linear events. Omit this property to use the current built-in rules. Use `defaultFactoryRules({ version, overrides })` to configure an explicit deployment version and overrides.

MastraFactorySandboxConfig

machine:
WorkspaceSandbox
Template sandbox cloned for each project workspace. The sandbox implementation must provide a `clone()` method.
workdir?:
string
Base path for repository checkouts inside cloned sandboxes. Defaults to the template sandbox's working directory or `/workspace`.
maxSandboxes?:
number
= 0
Maximum number of active sandboxes for this Factory process. `0` means unlimited.

Methods

prepare()

Prepares the Factory runtime and returns the configuration used to construct Mastra.

class MastraFactory {
	prepare(): Promise<MastraArgs>
}

prepare() performs the one-time setup required before constructing the host Mastra instance. It:

  • Registers the Factory storage domains and initializes the storage backend.
  • Initializes the authentication provider when it supports initialization.
  • Registers the tenant credential resolver when authentication is enabled.
  • Adds Platform GitHub and Linear integrations for missing provider IDs when MASTRA_PLATFORM_SECRET_KEY is set.
  • Initializes configured and defaulted integrations with scoped storage, project storage, and route authentication.
  • Creates the sandbox fleet when sandbox is configured.
  • Validates integration identifiers, rules, and OAuth state-signing requirements.
  • Builds the Mastra Code agent controller, integration tools, API routes, middleware, and workers.

Call prepare() once. A second or concurrent call throws an error.

Returns

Promise<MastraArgs> containing the constructor properties to spread directly into new Mastra(). The returned object includes the prepared agent controller, storage, server configuration, and integration workers when present.

finalize()

Starts the prepared controller, workers, thread reconciliation, and Factory decision dispatcher.

class MastraFactory {
	finalize(): Promise<void>
}

Call finalize() after constructing the Mastra instance. Calling it before prepare() throws an error.

shutdown()

Stops background dispatch owned by the Factory runtime.

class MastraFactory {
	shutdown(): Promise<void>
}

Call shutdown() during host process shutdown. It stops the Factory decision dispatcher. The host remains responsible for shutting down the Mastra instance and its workers.

Lifecycle

The required lifecycle order is:

  1. Create MastraFactory with explicit storage and optional capabilities.
  2. Call factory.prepare() once.
  3. Construct and export Mastra from the returned properties.
  4. Call factory.finalize() after the Mastra instance exists.
  5. Call factory.shutdown() before the host process exits.

Integrations

Pass integrations through the integrations constructor property. Each integration implements FactoryIntegration and can contribute HTTP routes, source capabilities, agent tools, session tools, tool observers, diagnostics, audit export, and background workers.

id:
string
Stable identifier for the integration. It must be unique within a Factory instance.
intake?:
Intake
Issue-oriented capability used by Factory intake flows.
versionControl?:
VersionControl
Repository, installation, branch, and pull request capability.
initialize?:
({ storage, projects, auth }) => void
Receives integration-scoped storage, Factory project storage, and route authentication before the integration's routes, tools, or workers are collected.
routes:
(context: IntegrationContext) => ApiRoute[]
Returns the integration's API routes during Factory preparation.
agentTools?:
({ requestContext }) => Promise<IntegrationTools>
Returns organization-scoped tools resolved for each agent request.
sessionTools?:
({ requestContext }) => IntegrationTools
Returns tools scoped to the current agent session.
postToolObserver?:
({ toolContext, requestContext? }) => Promise<void>
Observes completed or failed agent tool calls. `requestContext` is omitted when the tool execution context does not contain one.
workers?:
(context: IntegrationContext) => MastraWorker[]
Returns background workers that start with the host Mastra instance.
diagnostics:
() => Record<string, unknown>
Returns non-secret integration status for startup logs and diagnostics.
audit?:
({ event }) => Promise<void>
Receives locally persisted audit events for best-effort export.
requiresStableStateSigner?:
boolean
Indicates that the integration signs OAuth state and requires a configured `stateSecret`. `prepare()` throws when this is `true` and the Factory is using its generated per-process secret.

Included integrations

Import the included integrations from the @mastra/factory/integrations subpaths.

IntegrationConfiguration
/github/integrationGithubIntegration accepts GitHub App credentials and an optional webhook secret.
/linear/integrationLinearIntegration accepts a Linear OAuth client ID and client secret.
/workos/integrationWorkOSAuditIntegration accepts a WorkOS client and return URL.
/platform/github/integrationPlatformGithubIntegration reads its Mastra Platform API configuration from the environment.
/platform/linear/integrationPlatformLinearIntegration reads its Mastra Platform API configuration from the environment.

When MASTRA_PLATFORM_SECRET_KEY is set, prepare() automatically creates the Platform GitHub and Linear integrations unless the integrations array already contains an integration with the corresponding github or linear ID.

The package exposes integration contracts and included integrations through these subpaths. Other wildcard-importable files under @mastra/factory/*, such as route assembly and storage-domain implementations, are internal runtime wiring rather than supported extension points.

Rules

Import the default rules and rule types from @mastra/factory/rules:

import {
	DEFAULT_FACTORY_RULE_VERSION,
	defaultFactoryRules,
	type FactoryRules,
} from '@mastra/factory/rules'

const rules: FactoryRules = defaultFactoryRules({
	version: DEFAULT_FACTORY_RULE_VERSION,
	overrides: {},
})

Pass the returned rules object to the MastraFactory constructor. FactoryRules contains handlers for the work and review boards, tool results, GitHub events, and Linear events. defaultFactoryRules() merges the supplied overrides with the built-in rules and validates the result.