#! /usr/bin/env node import { coreFeatures } from '@mastra/core/features'; import { Command } from 'commander'; import pc from 'picocolors'; import type { PackageJson } from 'type-fest'; import pkgJson from '../package.json'; import type { CLI_ORIGIN } from './analytics/index'; import { PosthogAnalytics, setAnalytics } from './analytics/index'; import { addScorer } from './commands/actions/add-scorer'; import { buildProject } from './commands/actions/build-project'; import { createProject } from './commands/actions/create-project'; import { initProject } from './commands/actions/init-project'; import { lintProject } from './commands/actions/lint-project'; import { listScorers } from './commands/actions/list-scorers'; import { migrate } from './commands/actions/migrate'; import { startDevServer } from './commands/actions/start-dev-server'; import { startProject } from './commands/actions/start-project'; import { startStudio } from './commands/actions/start-studio'; import { collect, registerApiCommand } from './commands/api/index'; import { loginAction, logoutAction } from './commands/auth/login'; import { listOrgsAction, switchOrgAction } from './commands/auth/orgs'; import { createTokenAction, listTokensAction, revokeTokenAction } from './commands/auth/tokens'; import { whoamiAction } from './commands/auth/whoami'; import { connectProviderAction, listProvidersAction, removeConnectionAction } from './commands/connect/connect.js'; import { configureCreateCommand } from './commands/create/create'; import { registerEnvDbCommands } from './commands/db/index.js'; import { unifiedDeployAction } from './commands/deploy/index.js'; import { envSuggestionsAction } from './commands/env/deploy-suggestions.js'; import { registerEnvCommands } from './commands/env/index.js'; import { buildExperimentWorker } from './commands/experiment/build'; import { COMPONENTS, LLMProvider } from './commands/init/utils'; import { serverDeployAction } from './commands/server/deploy'; import { serverSuggestionsAction } from './commands/server/deploy-suggestions'; import { envListAction, envSetAction, envUnsetAction, envImportAction, envPullAction } from './commands/server/env'; import { serverPauseAction, serverRestartAction } from './commands/server/lifecycle'; import { deployAction } from './commands/studio/deploy'; import { deploysAction } from './commands/studio/deploy-list'; import { logsAction } from './commands/studio/deploy-logs'; import { statusAction } from './commands/studio/deploy-status'; import { suggestionsAction } from './commands/studio/deploy-suggestions'; import { listProjectsAction, createProjectAction } from './commands/studio/projects'; import { traceImportAction } from './commands/traces/import/action.js'; import { configureTraceImportCommand } from './commands/traces/import/command.js'; import { parseComponents, parseLlmProvider, parseMcp, wrapAction } from './commands/utils'; import { buildWorker } from './commands/worker/build'; import { devWorker } from './commands/worker/dev'; import { startWorker } from './commands/worker/start'; const mastraPkg = pkgJson as PackageJson; export const version = mastraPkg.version; export const analytics = new PosthogAnalytics({ apiKey: 'phc_SBLpZVAB6jmHOct9CABq3PF0Yn5FU3G2FgT4xUr2XrT', host: 'https://us.posthog.com', version: version!, }); setAnalytics(analytics); const program = new Command(); export const origin = process.env.MASTRA_ANALYTICS_ORIGIN as CLI_ORIGIN; program .name('mastra') .version(`${version}`, '-v, --version') .addHelpText( 'before', ` ${pc.bold(pc.cyan('Mastra'))} is a typescript framework for building AI applications, agents, and workflows. `, ) .action(() => { program.help(); }); configureCreateCommand(program.command('create')).action(wrapAction(createProject)); program .command('init') .description('Initialize Mastra in your project') .option('--default', 'Quick start with defaults (src, OpenAI, examples)') .option('-d, --dir ', 'Directory for Mastra files to (defaults to src/)') .option( '-c, --components ', `Comma-separated list of components (${COMPONENTS.join(', ')})`, parseComponents, ) .option('-l, --llm ', `Default model provider (${LLMProvider.join(', ')})`, parseLlmProvider) .option('-k, --llm-api-key ', 'API key for the model provider') .option('-e, --example', 'Include example code') .option('-n, --no-example', 'Do not include example code') .option( '-m, --mcp ', 'MCP Server for code editor (cursor, cursor-global, windsurf, vscode, antigravity)', parseMcp, ) .option('--observability', 'Enable Mastra Observability (writes MASTRA_PLATFORM_ACCESS_TOKEN placeholder to .env)') .option('--no-observability', 'Do not enable Mastra Observability') .option( '--observability-project ', 'Existing platform project name/slug to attach Observability to, or a name to create. Skips the interactive picker.', ) .action(initProject); registerApiCommand(program); const tracesCommand = program.command('traces').description('Manage observability traces'); const traceImportCommand = tracesCommand.command('import'); configureTraceImportCommand(traceImportCommand); traceImportCommand.action(wrapAction(traceImportAction)); program .command('lint') .description('Lint your Mastra project') .option('-d, --dir ', 'Path to your Mastra folder') .option('-r, --root ', 'Path to your root folder') .option('-t, --tools ', 'Comma-separated list of paths to tool files to include') .option('--preflight', 'Also run bundle preflight checks (builds if needed)') .option('--skip-build', 'Skip build, reuse existing .mastra/output (requires --preflight)') .option('--env-file ', 'Env file for preflight validation (requires --preflight)') .option('--strict', 'Treat warnings as errors') .option('--json', 'Emit machine-readable JSON output') .option('--debug', 'Enable debug logs', false) .action(lintProject); program .command('dev') .description('Start mastra server') .option('-d, --dir ', 'Path to your mastra folder') .option('-r, --root ', 'Path to your root folder') .option('-t, --tools ', 'Comma-separated list of paths to tool files to include') .option('-e, --env ', 'Custom env file to include in the dev server') .option( '-i, --inspect [host:port]', 'Start the dev server in inspect mode (optional: [host:]port, e.g., 0.0.0.0:9229)', ) .option( '-b, --inspect-brk [host:port]', 'Start the dev server in inspect mode and break at the beginning of the script (optional: [host:]port)', ) .option( '-c, --custom-args ', 'Comma-separated list of custom arguments to pass to the dev server. IE: --experimental-transform-types', ) .option('-s, --https', 'Enable local HTTPS') .option('--request-context-presets ', 'Path to request context presets JSON file') .option('--debug', 'Enable debug logs', false) .action(startDevServer); const factoryCommand = program.command('factory').description('Manage Mastra Factory'); factoryCommand .command('dev') .description('Start mastra server') .option('-d, --dir ', 'Path to your mastra folder') .option('-r, --root ', 'Path to your root folder') .option('-t, --tools ', 'Comma-separated list of paths to tool files to include') .option('-e, --env ', 'Custom env file to include in the dev server') .option( '-i, --inspect [host:port]', 'Start the dev server in inspect mode (optional: [host:]port, e.g., 0.0.0.0:9229)', ) .option( '-b, --inspect-brk [host:port]', 'Start the dev server in inspect mode and break at the beginning of the script (optional: [host:]port)', ) .option( '-c, --custom-args ', 'Comma-separated list of custom arguments to pass to the dev server. IE: --experimental-transform-types', ) .option('-s, --https', 'Enable local HTTPS') .option('--request-context-presets ', 'Path to request context presets JSON file') .option('--debug', 'Enable debug logs', false) .action(args => startDevServer({ ...args, factory: true })); program .command('build') .description('Build your Mastra project') .option('-d, --dir ', 'Path to your Mastra Folder') .option('-r, --root ', 'Path to your root folder') .option('-t, --tools ', 'Comma-separated list of paths to tool files to include') .option('-s, --studio', 'Bundle the studio UI with the build') .option('-f, --force', 'Build even if a `mastra dev` server is running in this directory') .option('--debug', 'Enable debug logs', false) .action(buildProject); const experimentCommand = program.command('experiment').description('Build Mastra experiment artifacts'); experimentCommand .command('build') .description('Build a standalone experiment worker artifact') .option('-d, --dir ', 'Path to your Mastra folder') .option('-r, --root ', 'Path to your root folder') .option('-o, --output-dir ', 'Output directory for the experiment worker (default: .mastra/experiment-worker)') .option('--debug', 'Enable debug logs', false) .action((opts: { dir?: string; root?: string; outputDir?: string; debug: boolean }) => buildExperimentWorker(opts)); const workerCommand = program.command('worker').description('Build and run standalone Mastra worker bundles'); workerCommand .command('build') .description('Bundle a worker artifact (defaults to .mastra/output/index.mjs)') .option('-d, --dir ', 'Path to your Mastra folder') .option('-r, --root ', 'Path to your root folder') .option('-t, --tools ', 'Comma-separated list of paths to tool files to include') .option( '-o, --output-dir ', 'Output directory for the worker bundle. Defaults to .mastra/output (overwrites the server bundle if both are built in the same project — fine for split deploys). Pass a different path (relative or absolute) to redirect the worker bundle and leave the server bundle alone.', ) .option('--debug', 'Enable debug logs', false) .action((opts: { dir?: string; root?: string; tools?: string; outputDir?: string; debug: boolean }) => { return buildWorker(opts); }); workerCommand .command('start [name]') .description( 'Start the built worker (defaults to .mastra/output/index.mjs). [name] sets MASTRA_WORKERS for the spawned process.', ) .option('-d, --dir ', 'Path to your built worker output directory (default: .mastra/output)') .option('-e, --env ', 'Custom env file to load') .action((name: string | undefined, opts: { dir?: string; env?: string }) => { return startWorker({ name, ...opts }); }); workerCommand .command('dev [name]') .description('Build and start a worker in one step. [name] sets MASTRA_WORKERS for the spawned process.') .option('-d, --dir ', 'Path to your Mastra folder') .option('-r, --root ', 'Path to your root folder') .option('-t, --tools ', 'Comma-separated list of paths to tool files to include') .option( '-o, --output-dir ', 'Output directory for the worker bundle. Defaults to .mastra/output. Pass a different path to keep server and worker bundles side by side.', ) .option('-e, --env ', 'Custom env file to load') .option('--debug', 'Enable debug logs', false) .action( ( name: string | undefined, opts: { dir?: string; root?: string; tools?: string; outputDir?: string; env?: string; debug: boolean }, ) => { return devWorker({ name, ...opts }); }, ); program .command('start') .description('Start your built Mastra application') .option('-d, --dir ', 'Path to your built Mastra output directory (default: .mastra/output)') .option('-e, --env ', 'Custom env file to include in the start') .option( '-c, --custom-args ', 'Comma-separated list of custom arguments to pass to the Node.js process. IE: --require=newrelic', ) .action(startProject); // ---- Unified deploy command (new entry point) ---- program .command('deploy [dir]') .description('Deploy your Mastra application to an environment') .option('--env ', 'Target environment (default: production)', 'production') .option('--org ', 'Organization ID') .option('--project ', 'Project ID, slug, or name (creates new project if not found)') .option('-y, --yes', 'Auto-accept defaults without confirmation') .option('-c, --config ', 'Project config file path (default: .mastra-project.json)') .option('--env-file ', 'Env file to deploy (for example: .env.production)') .option('--skip-build', 'Skip the build step and use existing .mastra/output') .option('--skip-preflight', 'Skip the pre-deploy build/env validation') .option('--region ', 'Region for new environments (e.g., us, eu)') .option( '--workers ', 'Background worker deployment mode: "dedicated" (dedicated workers service, recommended; requires Redis) or "in-process" (run background tasks inside the API server container; spins down an existing workers service). Prompts on new environments when omitted.', ) .option('--debug', 'Enable debug logs', false) .action(wrapAction(unifiedDeployAction)); // ---- Studio commands ---- const studioCommand = program .command('studio') .description('Manage Mastra Studio') .option('-p, --port ', 'Port to run the studio on (default: 3000)') .option('-e, --env ', 'Custom env file to include in the studio') .option('-h, --server-host ', 'Host of the Mastra API server (default: localhost)') .option('-s, --server-port ', 'Port of the Mastra API server (default: 4111)') .option('-x, --server-protocol ', 'Protocol of the Mastra API server (default: http)') .option('--server-api-prefix ', 'API route prefix of the Mastra server (default: /api)') .option('--request-context-presets ', 'Path to request context presets JSON file') .action(startStudio); const deployCommand = studioCommand .command('deploy [dir]') .description('Deploy studio') .option('--org ', 'Organization ID') .option('--project ', 'Project ID, slug, or name (creates new project if not found)') .option('-y, --yes', 'Auto-accept defaults without confirmation') .option('-c, --config ', 'Project config file path (default: .mastra-project.json)') .option('--env-file ', 'Env file to deploy (for example: .env.production)') .option('--skip-build', 'Skip the build step and use existing .mastra/output') .option('--skip-preflight', 'Skip the pre-deploy build/env validation') .option('--debug', 'Enable debug logs', false) .action(wrapAction(deployAction)); deployCommand.command('list').description('List deployed studios').action(wrapAction(deploysAction)); deployCommand .command('status ') .description('Show deploy status') .option('-w, --watch', 'Watch for status changes') .action(wrapAction(statusAction)); deployCommand .command('logs ') .description('Show deploy logs') .option('-f, --follow', 'Stream logs in real time') .option('--tail ', 'Number of recent log lines') .action(wrapAction(logsAction)); if (coreFeatures.has('deploy-diagnosis')) { deployCommand .command('diagnosis [deploy-id]') .alias('suggestions') .description('Diagnose a failed deploy and show fix suggestions') .action(wrapAction(suggestionsAction)); } const studioProjects = studioCommand .command('projects') .description('Manage studio projects') .action(wrapAction(listProjectsAction)); studioProjects.command('create').description('Create a new project').action(wrapAction(createProjectAction)); program .command('migrate') .description('Run database migrations to update storage schema') .option('-d, --dir ', 'Path to your Mastra folder') .option('-r, --root ', 'Path to your root folder') .option('-e, --env ', 'Custom env file to include') .option('--debug', 'Enable debug logs', false) .option('-y, --yes', 'Skip confirmation prompt (for CI/automation)') .action(migrate); const scorersCommand = program.command('scorers').description('Manage scorers for evaluating AI outputs'); scorersCommand .command('add [scorer-name]') .description('Add a new scorer to your project') .option('-d, --dir ', 'Path to your Mastra directory (default: auto-detect)') .action(addScorer); scorersCommand.command('list').description('List available scorer templates').action(listScorers); // ---- Connect commands ---- const PROJECT_OPTION_ARGS = ['--project ', 'Project name, slug, or ID (default: linked project)'] as const; const connectCommand = program.command('connect').description('Manage provider integrations for your Mastra project'); connectCommand .command('list') .description('List available providers and their connection status') .option(...PROJECT_OPTION_ARGS) .action(wrapAction(listProvidersAction)); connectCommand .command('add ') .description('Connect a provider to the project') .option(...PROJECT_OPTION_ARGS) .option('-y, --yes', 'Skip confirmation prompts') .action(wrapAction(connectProviderAction)); connectCommand .command('remove ') .description('Unlink a provider connection from the project') .option(...PROJECT_OPTION_ARGS) .option('--connection ', 'Remove only the connection with this id') .option('--all', "Remove all of the provider's connections") .option('-y, --yes', 'Skip confirmation prompts') .action(wrapAction(removeConnectionAction)); // ---- Auth commands ---- const authCommand = program.command('auth').description('Manage authentication'); authCommand.command('login').description('Log in to Mastra').action(wrapAction(loginAction)); authCommand.command('logout').description('Log out and clear credentials').action(wrapAction(logoutAction)); authCommand.command('whoami').description('Show current user and organization').action(wrapAction(whoamiAction)); const authOrgs = authCommand.command('orgs').description('Manage organizations').action(wrapAction(listOrgsAction)); authOrgs.command('switch').description('Switch current organization').action(wrapAction(switchOrgAction)); const authTokens = authCommand.command('tokens').description('Manage API tokens').action(wrapAction(listTokensAction)); authTokens .command('create ') .description('Create a new API token') .option('--permission ', 'grant a permission, e.g. databases:write (repeatable)', collect, []) .action(wrapAction(createTokenAction)); authTokens.command('revoke ').description('Revoke an API token').action(wrapAction(revokeTokenAction)); // ---- Environment commands ---- const envCommand = registerEnvCommands(program); // Databases: mastra env db ... registerEnvDbCommands(envCommand); if (coreFeatures.has('deploy-diagnosis')) { envCommand .command('diagnosis [deploy-id]') .alias('suggestions') .description('Diagnose a failed environment deploy and show fix suggestions') .option('--project ', 'Project name, slug, or ID (default: linked project)') .option('--environment ', 'Environment name, slug, or ID (default: only env, or required when >1)') .action(wrapAction(envSuggestionsAction)); } // ---- Server commands ---- const serverCommand = program.command('server').description('Manage Mastra Server deployments'); const serverDeployCommand = serverCommand .command('deploy [dir]') .description('Deploy to Mastra Server') .option('--org ', 'Organization ID') .option('--project ', 'Project ID, slug, or name (creates new project if not found)') .option('-y, --yes', 'Auto-accept defaults without confirmation') .option('-c, --config ', 'Project config file path (default: .mastra-project.json)') .option('--env-file ', 'Env file to deploy (for example: .env.production)') .option('--skip-build', 'Skip the build step and deploy the existing .mastra/output directory') .option('--skip-preflight', 'Skip the pre-deploy build/env validation') .option('--debug', 'Enable debug logs', false) .action(wrapAction(serverDeployAction)); if (coreFeatures.has('deploy-diagnosis')) { serverDeployCommand .command('diagnosis [deploy-id]') .alias('suggestions') .description('Diagnose a failed deploy and show fix suggestions') .option('--org ', 'Organization ID') .action(wrapAction(serverSuggestionsAction)); } serverCommand .command('pause') .description('Pause the linked Mastra Server project instance') .option('--org ', 'Organization ID') .option('--project ', 'Project ID or slug (takes precedence over MASTRA_PROJECT_ID and the linked project)') .option('-c, --config ', 'Project config file path (default: .mastra-project.json)') .action(wrapAction(serverPauseAction)); serverCommand .command('restart') .description('Restart the linked Mastra Server project instance') .option('--org ', 'Organization ID') .option('--project ', 'Project ID or slug (takes precedence over MASTRA_PROJECT_ID and the linked project)') .option('-c, --config ', 'Project config file path (default: .mastra-project.json)') .action(wrapAction(serverRestartAction)); const serverEnvCommand = serverCommand.command('env').description('Manage server environment variables'); serverEnvCommand .command('list') .description('List environment variables for the linked project') .option('-c, --config ', 'Project config file path (default: .mastra-project.json)') .action(wrapAction(envListAction)); serverEnvCommand .command('set ') .description('Set an environment variable') .option('-c, --config ', 'Project config file path (default: .mastra-project.json)') .action(wrapAction(envSetAction)); serverEnvCommand .command('unset ') .description('Remove an environment variable') .option('-c, --config ', 'Project config file path (default: .mastra-project.json)') .action(wrapAction(envUnsetAction)); serverEnvCommand .command('import ') .description('Import environment variables from a .env file') .option('-c, --config ', 'Project config file path (default: .mastra-project.json)') .action(wrapAction(envImportAction)); serverEnvCommand .command('pull [file]') .description( 'Pull project-level environment variables into a local .env file (default: .env) — use `mastra env vars pull` to include environment-scoped vars', ) .option('-c, --config ', 'Project config file path (default: .mastra-project.json)') .option('--project ', 'Project ID or slug (takes precedence over MASTRA_PROJECT_ID and the linked project)') .action(wrapAction(envPullAction)); await program.parseAsync(process.argv); export { PosthogAnalytics } from './analytics/index'; export { create } from './commands/create/create';