跳到主要内容
非官方简体中文翻译,内容版权归 Mastra 所有,遵循 Apache-2.0 许可。

CLI commands

You can use the Command-Line Interface (CLI) provided by Mastra to develop, build, and start your Mastra project.

mastra dev
mastra-dev的直接链接

Starts a server which exposes Studio and REST endpoints for your agents, tools, and workflows. You can visit http://localhost:4111/swagger-ui for an overview of all available endpoints once mastra dev is running.

You can also configure the server.

Flags
Flags的直接链接

The command accepts common flags and the following additional flags:

--https
--https的直接链接

Enable local HTTPS support. Learn more.

--inspect
--inspect的直接链接

Start the development server in inspect mode, helpful for debugging. Optionally specify a custom host and port (e.g., --inspect=0.0.0.0:9229 for Docker). This can't be used together with --inspect-brk.

--inspect-brk
--inspect-brk的直接链接

Start the development server in inspect mode and break at the beginning of the script. Optionally specify a custom host and port (e.g., --inspect-brk=0.0.0.0:9229). This can't be used together with --inspect.

--custom-args
--custom-args的直接链接

Comma-separated list of custom arguments to pass to the Node.js process, e.g. --require=newrelic or --experimental-transform-types.

--request-context-presets
--request-context-presets的直接链接

Path to a JSON file containing request context presets. When provided, a dropdown displays in Studio's request context editor, letting you quickly switch between preset configurations.

mastra dev --request-context-presets ./presets.json

The file must be a JSON object where each key is a preset name and each value is an object:

{
"development": { "userId": "dev-user", "env": "development" },
"production": { "userId": "prod-user", "env": "production" }
}

Configs
Configs的直接链接

You can set environment variables to modify the behavior of mastra dev.

Skip peer dependency check
Skip peer dependency check的直接链接

Set MASTRA_SKIP_PEERDEP_CHECK=1 to skip the peer dependency version mismatch check at startup:

MASTRA_SKIP_PEERDEP_CHECK=1 mastra dev

This is useful during monorepo development when peer dependencies may be bumped but packages aren't yet published.

Disable build caching
Disable build caching的直接链接

Set MASTRA_DEV_NO_CACHE=1 to force a full rebuild rather than using the cached assets under .mastra/:

MASTRA_DEV_NO_CACHE=1 mastra dev

This helps when you are debugging bundler plugins or suspect stale output.

Limit parallelism
Limit parallelism的直接链接

MASTRA_CONCURRENCY caps how many expensive operations run in parallel (primarily build and evaluation steps). For example:

MASTRA_CONCURRENCY=4 mastra dev

Leave it unset to let the CLI pick a sensible default for the machine.

Custom provider endpoints
Custom provider endpoints的直接链接

When using providers supported by the Vercel AI SDK you can redirect requests through proxies or internal gateways by setting a base URL. For OpenAI:

OPENAI_API_KEY=<your-api-key> \
OPENAI_BASE_URL=https://openrouter.example/v1 \
mastra dev

For Anthropic:

ANTHROPIC_API_KEY=<your-api-key> \
ANTHROPIC_BASE_URL=https://anthropic.internal \
mastra dev

These are forwarded to the Mastra model router and will work with any "openai/..." or "anthropic/..." model selections.

mastra factory dev
mastra-factory-dev的直接链接

Starts a development server for Agent Builder development. It uses the same dev runtime and flags as mastra dev and writes to the same .mastra/output directory.

npx mastra factory dev

Both commands share the same dev lock, so mastra dev and mastra factory dev can't run simultaneously in the same project. If one is already running, the other exits with a duplicate development server error.

Use mastra factory dev when developing Agent Builder features. It accepts the same flags as mastra dev, including --https, --inspect, --inspect-brk, --custom-args, and --request-context-presets.

mastra build
mastra-build的直接链接

The mastra build command bundles your Mastra project into a production-ready Hono server. Hono is a lightweight, type-safe web framework that makes it straightforward to deploy Mastra agents as HTTP endpoints with middleware support.

Under the hood Mastra's Rollup server locates your Mastra entry file and bundles it to a production-ready Hono server. During that bundling it tree-shakes your code and generates source maps for debugging.

The output in .mastra can be deployed to any cloud server using mastra start.

If you're deploying to a serverless platform you need to install the correct deployer to receive the correct output in .mastra.

It accepts common flags.

Flags
Flags的直接链接

--studio
--studio的直接链接

Bundle the Studio UI with the build.

Configs
Configs的直接链接

You can set environment variables to modify the behavior of mastra build.

Skip peer dependency check
Skip peer dependency check的直接链接

Set MASTRA_SKIP_PEERDEP_CHECK=1 to skip the peer dependency version mismatch check:

MASTRA_SKIP_PEERDEP_CHECK=1 mastra build

Limit parallelism
Limit parallelism的直接链接

For CI or when running in resource constrained environments you can cap how many expensive tasks run at once by setting MASTRA_CONCURRENCY.

MASTRA_CONCURRENCY=2 mastra build

mastra start
mastra-start的直接链接

备注

You need to run mastra build before using mastra start.

Starts a local server to serve your built Mastra application in production mode. By default, OTEL Tracing is enabled.

Flags
Flags的直接链接

The command accepts common flags and the following additional flags:

--dir
--dir的直接链接

The path to your built Mastra output directory. Defaults to .mastra/output.

--custom-args
--custom-args-1的直接链接

Comma-separated list of custom arguments to pass to the Node.js process, e.g. --require=newrelic or --experimental-transform-types.

mastra worker build
mastra-worker-build的直接链接

Bundles your Mastra application for worker deployment. Produces the same output as mastra build: a self-contained .mastra/output/ directory.

mastra worker build [options]

Flags
Flags的直接链接

--dir
--dir-1的直接链接

Path to your Mastra source directory. Defaults to src/mastra.

--root
--root的直接链接

Project root directory. Defaults to the current directory.

--tools
--tools的直接链接

Comma-separated tool paths to include in the bundle.

--output-dir
--output-dir的直接链接

Custom output directory. Defaults to .mastra/output.

--debug
--debug的直接链接

Enable debug logging during the build.

mastra experiment build
mastra-experiment-build的直接链接

Builds a standalone companion worker that runs experiments without exposing an HTTP server. The worker loads your exported Mastra instance and accepts versioned newline-delimited JSON (NDJSON) protocol messages on standard input. It writes protocol events to standard output.

mastra experiment build [options]

The command writes the worker to .mastra/experiment-worker by default. The directory contains the executable entry point, production dependencies, and experiment-worker-manifest.json. Treat standard output as protocol-only output. Worker diagnostics are written to standard error.

Artifact contract
Artifact contract的直接链接

experiment-worker-manifest.json identifies the artifact as mastra-experiment-worker version 1 and provides:

  • The CLI version, creation time, and unique build ID embedded in the executable.
  • Supported protocol and dataset canonicalization versions.
  • The executable, arguments, and working directory required to launch the worker.
  • The dependency manifest and generated lockfile paths.
  • A sorted SHA-256 digest for each artifact file.
  • A SHA-256 content digest derived from those file paths and digests.

The content digest excludes experiment-worker-manifest.json to avoid a self-referential digest. Package the manifest with the rest of the directory. Use an outer package digest when the manifest itself must be attested.

Protocol contract
Protocol contract的直接链接

The worker implements the pinned experiment companion-worker protocol version 1. It reads strict UTF-8 NDJSON frames from standard input and requires every frame, including the last one, to end with a newline. Frames larger than 1 MiB, malformed or truncated frames, unsupported protocol or canonicalization versions, and messages that don't match the active experiment correlation are rejected as protocol failures.

A run request must match the artifact's embedded build ID and include the ordered dataset item count and SHA-256 attestation. The worker emits contiguous sequence numbers starting at 0, timer-driven heartbeats, awaited experiment lifecycle events, and exactly one terminal event. Cancellation must match the active protocol version and experiment ID, plus the job ID, attempt, and idempotency key.

Protocol exit codes are:

CodeMeaning
0Completed
10Completed with item errors
20Fatal failure
21Retryable failure
30Cancelled
31Timed out
70Protocol failure

Packet field handling
Packet field handling的直接链接

The worker passes target identity, ordered inline dataset items, scorer IDs, concurrency, timeout, experiment metadata, request context, tool mocks, and cancellation to runExperiment. Scorer versions and artifact provenance are retained as experiment metadata. Scorer code provenance is enforced by artifact admission rather than runtime scorer lookup.

Version 1 uses deterministic undeclared-tool denial. Non-empty network allowlists and secret references are rejected with a policy failure because network enforcement and secret materialization belong to the process sandbox. Dataset item source and expected-trajectory fields are preserved as item metadata when passed to runExperiment.

Flags
Flags的直接链接

--dir
--dir-2的直接链接

Path to your Mastra source directory. Defaults to src/mastra.

--root
--root-1的直接链接

Project root directory. Defaults to the current directory.

--output-dir
--output-dir-1的直接链接

Custom artifact directory. Relative paths are resolved from the project root. Defaults to .mastra/experiment-worker.

--debug
--debug-1的直接链接

Enable debug logging during the build.

mastra worker start
mastra-worker-start的直接链接

备注

You need to run mastra worker build or mastra build before using mastra worker start.

Starts a worker process from a previously built bundle. The optional name argument sets MASTRA_WORKERS in the spawned process, controlling which worker starts.

mastra worker start [name] [options]

Flags
Flags的直接链接

--dir
--dir-3的直接链接

Path to the build output directory. Defaults to .mastra/output.

--env
--env的直接链接

Path to the environment file. Defaults to .env.production, falling back to .env.

Examples
Examples的直接链接

# Start only the orchestration worker
mastra worker start orchestration

# Start only the scheduler
mastra worker start scheduler

# Start from a custom build directory
mastra worker start orchestration --dir ./dist

See Workers for deployment topologies and configuration.

mastra studio
mastra-studio的直接链接

Starts Studio as a static server. After starting, you can enter your Mastra instance URL (e.g. http://localhost:4111) to connect Studio to your Mastra backend. Looks for .env and .env.production files in the current working directory for configuration.

Flags
Flags的直接链接

The command accepts common flags and the following additional flags:

--port
--port的直接链接

The port to run Studio on. Defaults to 3000.

--server-host
--server-host的直接链接

The host of the Mastra API server to connect to. Defaults to localhost.

--server-port
--server-port的直接链接

The port of the Mastra API server to connect to. Defaults to 4111.

--server-protocol
--server-protocol的直接链接

The protocol of the Mastra API server to connect to. Defaults to http.

--server-api-prefix
--server-api-prefix的直接链接

The API route prefix of the Mastra API server. Defaults to /api.

--request-context-presets
--request-context-presets-1的直接链接

Path to a JSON file containing request context presets. Works the same as the mastra dev flag.

mastra studio --request-context-presets ./presets.json

mastra deploy
mastra-deploy的直接链接

Builds and deploys your project to the Mastra platform environment selected by --env. This is the recommended command for all new deploys and replaces both mastra studio deploy and mastra server deploy, which continue to work but should no longer be used for new setups.

Requires authentication via mastra auth login or a MASTRA_API_TOKEN environment variable.

mastra deploy
mastra deploy --env staging
mastra deploy --env production --region eu

The command runs mastra build and zips the output before uploading it to the selected environment. It then polls the deploy status while streaming build logs until the deploy reaches a terminal state.

Organization, project, and environment are resolved in order from: environment variable (MASTRA_ORG_ID, MASTRA_PROJECT_ID), CLI flag (--org, --project, --env), .mastra-project.json config file, current org from credentials, and lastly interactive prompt. On first deploy, the CLI saves the resolved org and project IDs to .mastra-project.json so subsequent deploys skip the prompts.

After confirmation, the CLI creates a missing project from the package.json name field and creates a missing target environment, defaulting to type: staging for anything other than production. Combined with --yes, this creates and deploys everything in one non-interactive command:

mastra deploy --env staging --yes

When --env <name> is set and --env-file isn't, the CLI auto-selects .env.<name> from the project directory if present (for example .env.staging). The <name> value is validated against a strict allowlist before being interpolated into a file path.

Arguments
Arguments的直接链接

[dir]
dir的直接链接

Project directory. Defaults to the current directory.

Flags
Flags的直接链接

--env
--env-1的直接链接

Target environment name. Defaults to production. Auto-selects .env.<name> from the project directory when --env-file isn't set. If the environment doesn't exist, the CLI creates it after confirmation.

--org
--org的直接链接

Organization ID. Can also be set via the MASTRA_ORG_ID environment variable.

--project
--project的直接链接

Project ID, slug, or name. Can also be set via the MASTRA_PROJECT_ID environment variable. If no project matches, the value is used as the name of a new project to create on deploy.

-y, --yes
-y---yes的直接链接

Auto-accept defaults without confirmation prompts, including creating projects and environments.

-c, --config
-c---config的直接链接

Path to the project config file. Defaults to .mastra-project.json.

--env-file
--env-file的直接链接

Path to the env file to bundle with the deploy (relative to the project directory). When set, disables the .env.<name> auto-selection based on --env.

mastra deploy --env staging --env-file .env.staging.local

--region
--region的直接链接

Region for a newly created environment (for example eu). Applied only when the CLI creates the environment.

--skip-build
--skip-build的直接链接

Skip the build step and deploy the existing .mastra/output directory. The CLI warns if the existing build is stale relative to the current source.

--skip-preflight
--skip-preflight的直接链接

Skip the pre-upload validation of the built output.

--debug
--debug-2的直接链接

Enable debug logs during the build step.

CI/CD usage
CI/CD usage的直接链接

Set MASTRA_API_TOKEN, MASTRA_ORG_ID, and MASTRA_PROJECT_ID as environment variables for headless deploys. Interactive prompts are skipped automatically when MASTRA_API_TOKEN is set. Combine with --yes to auto-accept environment creation.

export MASTRA_API_TOKEN="..."
export MASTRA_ORG_ID="..."
export MASTRA_PROJECT_ID="..."
mastra deploy --env staging --yes

mastra env
mastra-env的直接链接

Manages environments on Mastra platform. Environments are deploy targets (for example production, staging, preview-42) that belong to a project. The current organization is resolved from stored credentials.

Every subcommand resolves its project in a fixed order. It first checks the --project <name|slug|id> flag, then the MASTRA_PROJECT_ID environment variable. It then reads the .mastra-project.json file written by mastra deploy in the current directory. Run from your project directory and you never need to name the project.

mastra env list
mastra-env-list的直接链接

Lists environments for a project. Each environment shows its latest deploy (with an (active) marker when it's serving traffic) and the env var names injected by managed resources such as attached databases.

mastra env list

--json
--json的直接链接

Emit machine-readable JSON. Only non-sensitive metadata (id, name, slug, type, region, branch, URLs, managed env var names, and latest deploy status) is included so the output is safe to log in CI.

mastra env create
mastra-env-create的直接链接

Creates a new environment for a project.

mastra env create staging --type staging --region eu

-t, --type
-t---type的直接链接

Environment type. One of production, staging, or preview. Defaults to staging.

-r, --region
-r---region的直接链接

Region for the environment (for example eu).

--json
--json-1的直接链接

Emit machine-readable JSON. Sensitive fields are omitted, as with mastra env list.

mastra env delete
mastra-env-delete的直接链接

Deletes an environment.

mastra env delete <env>

<env> can be an environment name, slug, or ID. The CLI prompts for confirmation unless --yes is passed.

-y, --yes
-y---yes-1的直接链接

Skip the confirmation prompt.

mastra env restart
mastra-env-restart的直接链接

Restarts an environment's running service so saved env vars (including managed vars from attached databases) take effect immediately, without a new deploy.

mastra env restart <env>

<env> can be an environment name, slug, or ID. Fails with a conflict error if the environment has never been deployed.

mastra env vars pull
mastra-env-vars-pull的直接链接

Pulls an environment's env vars into a local env file (default: .env). The file contains the set a deploy of that environment runs with: the vars stored on the environment itself (for example, added in the dashboard's environment editor). Each environment is pulled on its own, and values stored on another environment are never merged in. Projects still on the legacy pipeline run from project-level vars instead, so pulling any of their environments returns those shared project-level values. Managed vars injected by attached databases are listed as comments (names only) since their values are platform-managed secrets.

mastra env vars pull
mastra env vars pull <env> --output .env.staging

<env> can be an environment name, slug, or ID, and can be omitted when the project has exactly one environment. The file is written with 0600 permissions. The command stops if the output file already exists. Pass --force to replace it.

-o, --output
-o---output的直接链接

File to write. Defaults to .env.

-f, --force
-f---force的直接链接

Replace an existing output file.

mastra env db
mastra-env-db的直接链接

Manages databases attached to a project on Mastra platform. Databases are provisioned from a managed provider (for example Turso or Neon) and inject their connection env vars into deploys automatically.

A database is either environment-scoped (its env vars only go to one environment) or shared (project-scoped: its env vars go to all environments). Environment-scoped is the default for mastra env db create: pass an environment argument, or let the CLI pick or prompt for one. Pass --shared on create to attach a shared database instead. For other subcommands (list, delete, keys), pass the environment argument to work with environment-scoped databases and omit it for shared databases.

Creating and deleting databases requires the admin role in the organization.

mastra env db list
mastra-env-db-list的直接链接

Lists databases attached to a project, including provider, provisioning status, scope (which environment each database feeds), and the env var names each database injects. Pass an environment to only show databases feeding that environment (environment-scoped plus shared).

mastra env db list
mastra env db list <env>

--json
--json-2的直接链接

Emit machine-readable JSON.

mastra env db create
mastra-env-db-create的直接链接

Provisions and attaches a managed database, then polls until it's ready. Provisioning errors are printed with the provider's error detail.

By default, the database is scoped to a single environment. Pass an environment argument to select it. If you omit the argument, the CLI uses the project's only environment or prompts you when several are available. In non-interactive contexts (CI, --json) an environment argument is required. Pass --shared to attach a project-scoped database that's shared by every environment instead.

Environment-scoped databases inherit their provider region from the environment. Shared databases accept --region.

mastra env db create --kind turso # picks or prompts for an environment
mastra env db create staging --kind turso # scoped to the "staging" environment
mastra env db create --kind turso --shared # shared by all environments
mastra env db create --kind neon --name my-app-db --region aws-us-east-1 --shared
mastra env db create production --kind postgres # VPC-isolated Postgres, private to the environment

--kind
--kind的直接链接

Database provider (required). One of turso, neon (public serverless Postgres), or postgres (VPC-isolated Postgres that runs on the same private network as the deployed environment).

--name
--name的直接链接

Database name. Defaults to a name derived from the project slug and provider (for example my-app-turso, my-app-pg for Neon, or my-app-postgres for VPC Postgres).

--region
--region-1的直接链接

Provider region ID for shared databases. Ignored for environment-scoped databases.

--shared
--shared的直接链接

Attach as a project-scoped database that's shared by every environment. Can't be combined with an environment argument.

--no-wait
--no-wait的直接链接

Return immediately after the attach is queued instead of polling until the database is ready. Check progress later with mastra env db show.

--json
--json-3的直接链接

Emit machine-readable JSON. In this mode, an environment argument or --shared is required when the project has more than one environment (no interactive prompt).

mastra env db show
mastra-env-db-show的直接链接

Shows database details and, once the database is ready, its connection env vars. Secret values are masked by default.

mastra env db show <database>

<database> can be a database ID or name.

--show-secrets
--show-secrets的直接链接

Print secret connection values instead of masking them.

--json
--json-4的直接链接

Emit machine-readable JSON. Secret values are masked unless --show-secrets is passed.

mastra env db delete
mastra-env-db-delete的直接链接

Permanently deletes a database with the provider, including all of its data. This can't be undone. The CLI prompts for confirmation unless --yes is passed. After deletion, deploys no longer receive the database's env vars.

mastra env db delete <database>

-y, --yes
-y---yes-2的直接链接

Skip the confirmation prompt.

mastra env deploys
mastra-env-deploys的直接链接

Lists deploys for a project, newest first. Deploys that are serving traffic are marked (active).

mastra env deploys [environment]

Omit [environment] to show deploys across all environments; pass an environment name, slug, or ID to filter to one.

--json
--json-5的直接链接

Emit machine-readable JSON.

mastra env diagnosis
mastra-env-diagnosis的直接链接

Diagnoses a failed deploy and prints suggestions for fixing it. Each suggestion includes a description, a recommended action, and a documentation link when one applies, followed by a link to the deploy logs in the dashboard.

mastra env diagnosis
mastra env diagnosis <deploy-id>
mastra env diagnosis --environment staging

Omit <deploy-id> to diagnose the environment's latest deploy. The environment comes from --environment, or from the project when it has exactly one environment. Projects with several environments require --environment or a deploy ID. A deploy ID passed on its own works without a linked project.

If the deploy is running successfully, the command reports that no suggestions are required and exits. Otherwise it starts a diagnosis when one doesn't already exist and polls until the result is ready, for up to five minutes. Rerunning the command reuses an in-progress diagnosis instead of restarting it. The command exits with a non-zero code when the diagnosis itself fails.

After a failed mastra deploy, the CLI prints the exact mastra env diagnosis <deploy-id> command to run.

--project
--project-1的直接链接

Project name, slug, or ID. Defaults to the linked project, as described in mastra env.

--environment
--environment的直接链接

Environment name, slug, or ID. Defaults to the project's only environment. Required when the project has more than one and no deploy ID is passed.

mastra studio deploy
mastra-studio-deploy的直接链接

备注

mastra studio deploy continues to work but is superseded by mastra deploy, which supports environments (--env staging, --env production) on a single project. New setups should use mastra deploy.

Builds and deploys your project to Mastra platform. Requires authentication via mastra auth login or a MASTRA_API_TOKEN environment variable.

mastra studio deploy

The command runs mastra build and zips the output. It reads an env file from the project directory before uploading everything to the platform. After uploading, it polls the deploy status and streams build logs until the deploy reaches a terminal state.

The deploy command auto-loads the project's .env file. If MASTRA_PROJECT_ID points to a project that was provisioned for Observability, the deploy links to that project instead of creating a new one. Deploying Studio to an observability-only project converts it into a Studio project on the platform side.

The CLI requires at least one .env or .env.* file (excluding .env.example) in the project directory and fails with Error: No env file found for deploy. if none exists. When multiple env files are present, the CLI prompts you to pick one (defaulting to .env.production). Pass --env-file to choose explicitly. With --yes and multiple env files, you must pass --env-file or the deploy errors.

Organization and project are resolved in order from: Environment variable flag, .mastra-project.json config file, current org from credentials, and lastly interactive prompt. On first deploy, the CLI saves the resolved IDs to .mastra-project.json so subsequent deploys skip the prompts.

If --project <value> doesn't match an existing project (by ID or slug), the CLI treats <value> as a new project name and creates it after confirmation. Combined with --yes, this creates and deploys a new project in one non-interactive command:

mastra studio deploy --project "my-new-project" --yes

Arguments
Arguments的直接链接

[dir]
dir-1的直接链接

Project directory. Defaults to the current directory.

Flags
Flags的直接链接

--org
--org-1的直接链接

Organization ID. Can also be set via the MASTRA_ORG_ID environment variable.

--project
--project-2的直接链接

Project ID or slug. Can also be set via the MASTRA_PROJECT_ID environment variable. If no project matches, the value is used as the name of a new project to create on deploy.

-y, --yes
-y---yes-3的直接链接

Auto-accept defaults without confirmation prompts.

-c, --config
-c---config-1的直接链接

Path to the project config file. Defaults to .mastra-project.json.

--env-file
--env-file-1的直接链接

Path to the env file to bundle with the deploy (relative to the project directory). Use this to deploy the same project to multiple environments by pointing at different env files (for example .env.staging, .env.production).

mastra studio deploy --env-file .env.staging --yes

--skip-build
--skip-build-1的直接链接

Skip the build step and deploy the existing .mastra/output directory.

--debug
--debug-3的直接链接

Enable debug logs during the build step.

CI/CD usage
CI/CD usage的直接链接

Set MASTRA_API_TOKEN, MASTRA_ORG_ID, and MASTRA_PROJECT_ID as environment variables for headless deploys. Interactive prompts are skipped automatically when MASTRA_API_TOKEN is set.

mastra studio deploy list
mastra-studio-deploy-list的直接链接

Lists all projects with their latest deploy status and URL.

mastra studio deploy status
mastra-studio-deploy-status的直接链接

Shows the status of a specific deploy.

mastra studio deploy status <deploy-id>

--watch, -w
--watch--w的直接链接

Poll for status changes until the deploy reaches a terminal state.

mastra studio deploy logs
mastra-studio-deploy-logs的直接链接

Shows logs for a specific deploy.

mastra studio deploy logs <deploy-id>

--follow, -f
--follow--f的直接链接

Stream logs in real time.

--tail
--tail的直接链接

Number of recent log lines to show.

mastra studio deploy suggestions
mastra-studio-deploy-suggestions的直接链接

Shows diagnosis results and suggested fixes for a failed Studio deploy.

mastra studio deploy suggestions [deploy-id]

When you omit deploy-id, the command uses the latest deploy for the linked project and starts a diagnosis if needed, polling until the results are ready. Suggestions appear only when the diagnosis finds a problem.

mastra studio projects
mastra-studio-projects的直接链接

Lists all projects in the current organization.

mastra studio projects create
mastra-studio-projects-create的直接链接

Creates a new project through an interactive prompt, but doesn't accept a --name flag. For non-interactive project creation, use mastra studio deploy --project <name> --yes instead. That command creates the project and deploys to it in one step.

mastra server deploy
mastra-server-deploy的直接链接

备注

mastra server deploy continues to work but is superseded by mastra deploy, which deploys a single project to multiple environments instead of separate Studio and Server commands. New setups should use mastra deploy.

Builds and deploys your project to Server on Mastra platform. Works the same as mastra studio deploy with the same flags, arguments, and resolution logic.

The deploy command auto-loads the project's .env file. If MASTRA_PROJECT_ID points to a project that was provisioned for Observability, the deploy links to that project instead of creating a new one. Deploying Server to an observability-only project converts it into a Server project on the platform side.

mastra server deploy [dir]

mastra server deploy suggestions
mastra-server-deploy-suggestions的直接链接

Shows diagnosis results and suggested fixes for a failed Server deploy.

mastra server deploy suggestions [deploy-id]

When you omit deploy-id, the command uses the latest deploy for the linked project and starts a diagnosis if needed, polling until the results are ready. Suggestions appear only when the diagnosis finds a problem.

mastra server pause
mastra-server-pause的直接链接

Pauses the running server instance for the linked project. Organization and project resolution work the same as mastra server deploy.

mastra server pause

Flags
Flags的直接链接

--org
--org-2的直接链接

Organization ID. Can also be set via the MASTRA_ORG_ID environment variable.

--project
--project-3的直接链接

Project ID or slug. Takes precedence over MASTRA_PROJECT_ID. Slugs are resolved against projects in the current organization.

-c, --config
-c---config-2的直接链接

Path to the project config file. Defaults to .mastra-project.json.

Fails if the instance isn't running.

mastra server restart
mastra-server-restart的直接链接

Restarts a paused or stopped server instance for the linked project. After the platform accepts the restart, the CLI resolves the deploy id (from the API response or by polling project and deploy metadata when the response omits an id), then streams build and deploy logs the same way as mastra server deploy until the deploy reaches a terminal state.

Flags
Flags的直接链接

Same flags as mastra server pause: --org, --project, and -c / --config, with the same defaults and behavior.

mastra server restart

Fails if a deployment is still active for this project (running, building, deploying, etc.). That's a platform restriction so you can't restart while another deploy is in progress.

mastra server env
mastra-server-env的直接链接

Manages environment variables for the linked server deployment. Organization and project resolution work the same as mastra server deploy.

Every subcommand accepts -c / --config for the project config file path (defaults to .mastra-project.json).

mastra server env list
mastra-server-env-list的直接链接

Lists all environment variables for the linked project. Values are partially masked in the output.

mastra server env set
mastra-server-env-set的直接链接

Sets an environment variable. The CLI reads the current map and applies the change before uploading the result.

mastra server env set <key> <value>

mastra server env unset
mastra-server-env-unset的直接链接

Removes an environment variable.

mastra server env unset <key>

mastra server env import
mastra-server-env-import的直接链接

Imports variables from a file (for example a .env file) and merges them into the existing map. New values override keys that already exist on the server.

mastra server env import <file>

mastra server env pull
mastra-server-env-pull的直接链接

Downloads environment variables from the linked project and writes them to a local file. This is the inverse of mastra server env import.

mastra server env pull [file]

The file defaults to .env when no argument is given. All values are double-quoted and escaped for safe shell sourcing. Keys that aren't valid shell identifiers are skipped. The output file is created with restrictive permissions (0600) since it contains secrets.

--project
--project-4的直接链接

Project ID or slug. Takes precedence over MASTRA_PROJECT_ID and the linked project.

CI usage
CI usage的直接链接

In a continuous-integration pipeline, authenticate with MASTRA_API_TOKEN and pull the environment before running your app:

export MASTRA_API_TOKEN="..."
mastra server env pull .env.production --project my-project

mastra auth
mastra-auth的直接链接

Manages authentication for Mastra platform. Credentials are stored in ~/.mastra/credentials.json. You can also set the MASTRA_API_TOKEN environment variable as an alternative to interactive login.

mastra auth login
mastra-auth-login的直接链接

Opens a browser for login and stores the credentials locally.

mastra auth logout
mastra-auth-logout的直接链接

Removes stored credentials. If MASTRA_API_TOKEN is still set in the environment, the CLI warns that it will continue to be used.

mastra auth whoami
mastra-auth-whoami的直接链接

Shows the current user email, user ID, and active organization.

mastra auth orgs
mastra-auth-orgs的直接链接

Lists all organizations with your role in each. The current organization is marked.

mastra auth orgs switch
mastra-auth-orgs-switch的直接链接

Switches the active organization through an interactive prompt. Can't be used when MASTRA_API_TOKEN or MASTRA_ORG_ID environment variables are set.

mastra auth tokens
mastra-auth-tokens的直接链接

Lists all API tokens with their last-used date.

mastra auth tokens create
mastra-auth-tokens-create的直接链接

Creates a new API token. The secret is displayed once and can't be retrieved again.

mastra auth tokens create <name>

mastra auth tokens revoke
mastra-auth-tokens-revoke的直接链接

Revokes an API token.

mastra auth tokens revoke <token-id>

mastra connect
mastra-connect的直接链接

Manages provider connections for the linked platform project, so agents using @mastra/connect pick up provider toolsets without leaving the terminal.

Commands use the organization you're signed in to with mastra auth login. Switch organizations with mastra auth orgs switch.

The target project resolves from the --project flag, the MASTRA_PROJECT_ID environment variable, or the .mastra-project.json written by mastra deploy, in that order. All subcommands accept --project <name|slug|id>.

mastra connect list
mastra-connect-list的直接链接

Lists providers with connected providers first. Active connections are shown in green, connections needing reauthorization in yellow, and unconnected providers in grey. Providers that aren't available yet are marked as coming soon.

mastra connect list

mastra connect add
mastra-connect-add的直接链接

Connects a provider to the project. When the organization already has connections for the provider that aren't attached to the project, the command lists them and lets you attach an existing connection or create a new one. With no existing connections it goes straight to the provider's auth flow.

OAuth providers open the provider's consent screen in your browser and print its URL if you need to open it manually. API key and Basic auth providers prompt for credentials in the terminal and verify them before completing the connection. Providers with other auth types open a hosted connect page. The command waits until the connection becomes active before exiting.

Credential prompts require an interactive terminal, even with --yes. Run the command outside CI or connect through the platform UI. See provider setup for API keys and required permissions.

Once a new connection is active, the command offers to set a display name so you can tell connections to the same provider apart. It lists the provider's existing connections, suggests a name that doesn't collide with them, and asks for confirmation if the chosen name duplicates another connection's name. Leave the field blank to skip naming. Setting a display name requires the organization admin role; if naming fails, the connection remains active.

mastra connect add <provider>

Pass --yes to skip all prompts. This always creates a new connection without a display name, even when existing connections could be reused.

mastra connect remove
mastra-connect-remove的直接链接

Unlinks a provider's connection from the project. The organization-level connection is kept and can be re-attached later.

mastra connect remove <provider>

When a provider has multiple connections, the command prompts for which one to remove. Pass --yes to skip confirmation. Without a terminal, or with --yes, removing several connections at once requires --all, and --connection <id> removes a single one.

Replace a connection that needs reauthorization
Replace a connection that needs reauthorization的直接链接

mastra connect list marks connections that need reauthorization, for example after a provider API key is revoked. Connect tool resolution skips these connections with a warning.

Unlink the affected connection, then add a new one:

mastra connect remove posthog
mastra connect add posthog

If the project has multiple connections, select the affected one when removing it. When add offers to reuse an organization connection, choose Create a new connection and authorize it with valid credentials.

mastra lint
mastra-lint的直接链接

The mastra lint command validates the structure and code of your Mastra project.

By default, mastra lint runs project checks against your source files and configuration. Use --preflight to also run bundle checks against .mastra/output before deployment.

mastra lint --preflight

It accepts common flags.

Flags
Flags的直接链接

--preflight
--preflight的直接链接

Runs deployment preflight checks against the built Mastra output. This builds the project before checking it unless you also pass --skip-build.

--skip-build
--skip-build-2的直接链接

Skips the build step and reuses the existing .mastra/output directory. This flag only applies when --preflight is set.

--env-file <file>
--env-file-file的直接链接

Uses the specified environment file for preflight validation. This flag only applies when --preflight is set.

--strict
--strict的直接链接

Treats warnings as errors.

--json
--json-6的直接链接

Emits machine-readable JSON output.

--debug
--debug-4的直接链接

Enables debug logs.

mastra scorers
mastra-scorers的直接链接

The mastra scorers command provides management capabilities for evaluation scorers that measure the quality, accuracy, and performance of AI-generated outputs.

Read the Scorers overview to learn more.

add
add的直接链接

Add a new scorer to your project. You can use an interactive prompt:

mastra scorers add

Or provide a scorer name directly:

mastra scorers add answer-relevancy

Use the list command to get the correct ID.

list
list的直接链接

List all available scorer templates. Use the ID for the add command.

mastra create
mastra-create的直接链接

Create a standalone Mastra project with the same project-creation flow as create-mastra.

npx mastra@latest create

Providing both the project name and --llm skips the interactive setup prompts. Use --template [template] for an arbitrary template or --empty for a minimal provider-free scaffold.

The command installs Mastra skills for detected coding assistants and initializes Git when appropriate. Use --no-skills or --no-git to opt out.

See the create-mastra reference for mode behavior, conflicts, validation, and complete flag descriptions.

mastra init
mastra-init的直接链接

The mastra init command initializes Mastra in an existing project. Use this command to scaffold the necessary folders and configuration without generating a new project from scratch.

Flags
Flags的直接链接

The command accepts the following additional flags:

--default
--default的直接链接

Creates files inside src using OpenAI. It also populates the src/mastra folders with example code.

--dir
--dir-4的直接链接

The directory where Mastra files should be saved to. Defaults to src.

--components
--components的直接链接

Comma-separated list of components to add. For each component a new folder will be created. Choose from: "agents" | "tools" | "workflows" | "scorers". Defaults to ['agents', 'tools', 'workflows'].

--llm
--llm的直接链接

Default model provider. Choose from: "openai" | "anthropic" | "groq" | "google" | "cerebras" | "mistral".

--llm-api-key
--llm-api-key的直接链接

The API key for your chosen model provider. Will be written to an environment variables file (.env).

--example
--example的直接链接

If enabled, example code is written to the list of components (e.g. example agent code).

--no-example
--no-example的直接链接

Don't include example code. Useful when using the --default flag.

--mcp
--mcp的直接链接

Configure your code editor with Mastra's MCP server. Choose from: "cursor" | "cursor-global" | "windsurf" | "vscode".

--observability
--observability的直接链接

Enable Observability on the Mastra platform. The CLI prompts you to select an existing platform project or create a new one. It then writes the required environment variables and configures the observability exporters.

--no-observability
--no-observability的直接链接

Skip the Mastra Observability prompt.

--observability-project
--observability-project的直接链接

Set the platform project name to use when Mastra Observability is enabled.

mastra migrate
mastra-migrate的直接链接

Runs database migrations to update your storage schema. This command is useful when upgrading Mastra versions that include storage schema changes.

The command bundles your project and connects to your configured storage backend. It then executes any pending migrations. Currently supports:

  • Duplicate spans migration: Removes duplicate (traceId, spanId) entries and adds a unique constraint to ensure data integrity.
  • ClickHouse legacy-to-vNext span migration: Copies historical spans from the legacy mastra_ai_spans table to the vNext mastra_span_events schema. Runs in batches to stay within memory limits. See the ClickHouse storage reference for details.
mastra migrate

See the Storage migration guide for details on when migrations are needed.

It accepts common flags.

mastra traces import
mastra-traces-import的直接链接

Imports historical traces from a supported observability provider into an existing Mastra Platform project. The command prepares complete traces locally, uploads whole-trace batches, supports resume, and verifies a sample through Mastra Platform.

mastra traces import <provider> [options]

The following provider is currently supported:

ProviderArgumentRequirements
LangfuselangfuseLangfuse Cloud or self-hosted Langfuse v4 or later

See Import existing traces for the complete workflow, data mapping, local-file lifecycle, and limits.

Options
Options的直接链接

--target-project <name|slug|id>
--target-project-nameslugid的直接链接

Selects the destination Mastra Platform project that receives the traces. Takes precedence over MASTRA_PROJECT_ID. Without either value, the command uses the project linked in .mastra-project.json. The source project comes from the provider credentials, such as LANGFUSE_PUBLIC_KEY and LANGFUSE_SECRET_KEY.

--since <date>
--since-date的直接链接

Sets the inclusive start of the import window as an ISO 8601 date or timestamp. It defaults to 30 days before --until, clamped to the current 30-day Platform retention boundary. --from is accepted as an alias.

--until <date>
--until-date的直接链接

Sets the exclusive end of the import window as an ISO 8601 date or timestamp. It defaults to the time when the import starts and can't be in the future. --to is accepted as an alias.

The complete window must fall within the current 30-day Platform retention period, --since must be earlier than --until, and the window can't exceed 30 days.

--dry-run
--dry-run的直接链接

Reads the source and prepares valid traces locally without uploading them. The command writes a report and prints a command that resumes the prepared import.

--resume <import-id>
--resume-import-id的直接链接

Resumes a prepared import using its saved provider, destination project, date window, and acknowledged progress. Use the same destination project shown in the generated resume command. This option can't be combined with --since, --until, or --dry-run.

-y, --yes
-y---yes-4的直接链接

Uploads without asking for confirmation.

Environment variables
Environment variables的直接链接

The command loads .env and .env.local from the current directory.

VariableRequiredDescription
LANGFUSE_PUBLIC_KEYFor new Langfuse importsPublic project API key. Together with the secret key, it selects the source Langfuse project.
LANGFUSE_SECRET_KEYFor new Langfuse importsSecret project API key.
LANGFUSE_BASE_URLNoLangfuse host. Defaults to https://cloud.langfuse.com.
MASTRA_API_TOKENFor headless authenticationMastra Platform API token. Without it, the command uses credentials from mastra auth login.
MASTRA_ORG_IDWith MASTRA_API_TOKENOrganization that owns the destination project.
MASTRA_PLATFORM_ACCESS_TOKENFor upload and read-back with interactive loginMastra Platform access token for the destination. Not required for --dry-run or when MASTRA_API_TOKEN is set.
MASTRA_PROJECT_IDWhen no project is otherwise linkedDestination project ID. The --target-project flag takes precedence over it.

Examples
Examples的直接链接

Preview the default 30-day window without uploading:

mastra traces import langfuse --target-project my-mastra-project --dry-run

Import a smaller date window without a confirmation prompt:

mastra traces import langfuse \
--target-project my-mastra-project \
--since "$SINCE" \
--until "$UNTIL" \
--yes

Resume an existing import:

mastra traces import langfuse \
--resume 00000000-0000-0000-0000-000000000000 \
--target-project my-mastra-project

mastra api
mastra-api的直接链接

Calls a Mastra runtime server with JSON input and JSON output. Use it for local development servers, deployed Mastra platform projects, self-hosted Mastra servers, or hosted Mastra Platform Observability APIs.

mastra api agent list
mastra api agent run weather-agent '{"messages":"What is the weather in London?"}'
mastra api tool execute get-weather '{"location":"San Francisco"}'
mastra api trace list '{"page":0,"perPage":20}'

Use mastra api <resource> <action> --help to see examples for a command.

Output
Output的直接链接

Success responses are written to stdout as JSON. Single-resource commands return:

{ "data": {} }

List commands return a data array and pagination metadata:

{ "data": [], "page": { "total": 0, "page": 0, "perPage": 0, "hasMore": false } }

Errors are written to stderr as JSON and return a non-zero exit code:

{
"error": {
"code": "SERVER_UNREACHABLE",
"message": "Could not connect to target server",
"details": {}
}
}

Target resolution
Target resolution的直接链接

For runtime commands, the command resolves the target server in this order:

  1. --url <url> for an explicit remote or self-hosted server.
  2. http://localhost:4111 for a local mastra dev server.
  3. .mastra-project.json for a Mastra platform project.

Automatic Platform authentication is used when the CLI resolves a project from .mastra-project.json or recognizes an explicit Mastra-hosted Studio, Factory, or observability URL. Localhost and arbitrary explicit --url targets don't receive automatic credentials. Headers passed with --header are sent to any target, including localhost.

For observability commands (trace, log, score, and metric), the CLI targets the United States endpoint at https://observability.mastra.ai by default instead of a project deployment URL. Trace Intelligence commands (learning) work the same way but target https://output.signals.mastra.ai. When the CLI selects either hosted target automatically, it resolves credentials in this order:

  1. Explicit Authorization and X-Mastra-Project-Id headers passed with --header.
  2. MASTRA_PLATFORM_ACCESS_TOKEN and MASTRA_PROJECT_ID from your environment.
  3. Project metadata from .mastra-project.json for the project ID.
  4. Your Mastra CLI login token as an auth fallback.

Learning commands also send X-Mastra-Organization-Id, resolved from an explicit --header, MASTRA_ORGANIZATION_ID in your environment, or .mastra-project.json, in that order.

European Union observability data is stored at https://observability.eu.mastra.ai. Pass that trusted host with --url; it uses the same Platform credential resolution as the default United States endpoint:

mastra api --url https://observability.eu.mastra.ai trace list

Use --url and --header when you need to override another target or its credentials.

Factory commands
Factory commands的直接链接

Use mastra api factory to manage Factory projects, work items, decisions, attention items, and queue health. These commands use the same JSON input, output, authentication, headers, timeout, and target resolution as other mastra api commands.

List the Factory projects available to the current organization:

mastra api factory project list

Inspect the generated request schema before sending a governed work-item transition:

mastra api factory work-item transition --schema

Move a work item using its current revision:

mastra api factory work-item transition <project-id> <work-item-id> '{"board":"work","stage":"planning","requestId":"00000000-0000-4000-8000-000000000000","cause":"manual","expectedRevision":1}'

After you deploy the project with mastra deploy, the resulting non-secret .mastra-project.json lets the CLI find the hosted Factory instance, apply your Mastra CLI credentials, and select the deployed project's organization automatically. For an explicit hosted Factory --url, the CLI uses MASTRA_ORG_ID when set, then the organization selected by mastra auth orgs switch. An explicit X-Mastra-Organization-Id header takes precedence over both. Before deployment, or to target a specific local, remote, or self-hosted Factory server, pass --url instead:

mastra api --url http://localhost:4111 factory project list

Factory endpoints use their root-level /web/factory/... paths. --server-api-prefix still controls local target probing, but it isn't prepended to Factory requests.

Flags
Flags的直接链接

--url <url>
--url-url的直接链接

Target a specific Mastra server URL.

mastra api --url https://example.com agent list

--server-api-prefix <prefix>
--server-api-prefix-prefix的直接链接

Set the API route prefix of the target server. Defaults to /api. Use this when the server is mounted under a custom prefix (for example a @mastra/fastify MastraServer with prefix: "/api/mastra-studio"), the same way mastra studio accepts --server-api-prefix. You can also set the MASTRA_API_PREFIX environment variable instead of passing the flag.

mastra api --url https://example.com --server-api-prefix /api/mastra-studio agent list

--header <"Key: Value">
--header-key-value的直接链接

Send a custom HTTP header. Repeat the flag to send multiple headers.

mastra api --url https://example.com --header "Authorization: Bearer $TOKEN" agent list

--timeout <ms>
--timeout-ms的直接链接

Set the request timeout in milliseconds. Defaults to 30000. Workflow run start and resume commands default to 120000.

--pretty
--pretty的直接链接

Pretty-print JSON output. Defaults to false.

--schema
--schema的直接链接

Print the CLI-oriented request schema for a command that accepts JSON input. The schema comes from the target server's route contracts and includes the command shape, positionals, examples, request schemas, and response shape.

--schema is available on leaf commands that accept JSON input. It isn't available as a top-level mastra api flag.

mastra api agent run --schema
mastra api tool execute --schema

Input model
Input model的直接链接

Commands that accept input take one inline JSON argument. Don't pass file paths or stdin.

mastra api workflow run start data-pipeline '{"inputData":{"source":"s3://bucket/data.csv"}}'

Use positional arguments for stable IDs and JSON for filters or payloads. For routes that require both query parameters and a request body, pass one JSON object. The CLI splits the input according to the server route schema.

mastra api thread create '{"agentId":"weather-agent","resourceId":"user_123","threadId":"thread_abc123","title":"Support conversation"}'

List commands accept page and perPage in the JSON input when the target route supports pagination:

mastra api score list '{"page":0,"perPage":50}'
mastra api trace list '{"page":0,"perPage":20}'

Routes that support filters accept them in the same JSON input. For example, observability trace listing supports pagination and route-supported filters:

mastra api trace list '{"page":0,"perPage":20,"filters":{"spanType":"agent"}}'

Get command-specific help
Get command-specific help的直接链接

Each mastra api leaf command includes command-specific examples in its help output. Use --help on the exact command you want to call:

mastra api agent run --help
mastra api tool execute --help
mastra api memory current update --help
mastra api workflow run resume --help

Use --schema on commands that accept JSON input to inspect the request shape returned by the target server:

mastra api agent run --schema
mastra api thread create --schema
mastra api score create --schema

Some commands have important runtime requirements. For example, mastra api memory current update requires working memory to be enabled for the memory instance, and mastra api workflow run resume only works for suspended workflow runs.

Commands
Commands的直接链接

mastra api agent list
mastra-api-agent-list的直接链接

Lists the agents registered on the target server. Pass optional JSON input for route-supported filters.

mastra api agent list [input]

mastra api agent get
mastra-api-agent-get的直接链接

Gets metadata for one registered agent.

mastra api agent get <agentId>

mastra api agent run
mastra-api-agent-run的直接链接

Runs an agent with JSON input. Use command help to see examples for text prompts and chat messages, including memory thread options.

mastra api agent run <agentId> <input>

mastra api workflow list
mastra-api-workflow-list的直接链接

Lists workflows registered on the target server. Pass optional JSON input for route-supported filters.

mastra api workflow list [input]

mastra api workflow get
mastra-api-workflow-get的直接链接

Gets metadata for one registered workflow.

mastra api workflow get <workflowId>

mastra api workflow run start
mastra-api-workflow-run-start的直接链接

Starts a workflow run with JSON input. Workflow start commands use a longer default timeout than most commands because runs can take longer to complete.

mastra api workflow run start <workflowId> <input>

mastra api workflow run list
mastra-api-workflow-run-list的直接链接

Lists runs for a workflow. Pass optional JSON input for route-supported filters or pagination.

mastra api workflow run list <workflowId> [input]

mastra api workflow run get
mastra-api-workflow-run-get的直接链接

Gets one workflow run by ID.

mastra api workflow run get <workflowId> <runId>

mastra api workflow run resume
mastra-api-workflow-run-resume的直接链接

Resumes a suspended workflow run with JSON input. The run must be in a suspended state.

mastra api workflow run resume <workflowId> <runId> <input>

mastra api workflow run cancel
mastra-api-workflow-run-cancel的直接链接

Cancels a workflow run.

mastra api workflow run cancel <workflowId> <runId>

mastra api tool list
mastra-api-tool-list的直接链接

Lists tools registered on the target server. Pass optional JSON input for route-supported filters.

mastra api tool list [input]

mastra api tool get
mastra-api-tool-get的直接链接

Gets metadata and schemas for one tool.

mastra api tool get <toolId>

mastra api tool execute
mastra-api-tool-execute的直接链接

Executes a tool with JSON input. Raw tool input is wrapped as the route data field unless you pass an explicit data object.

mastra api tool execute <toolId> <input>

mastra api mcp list
mastra-api-mcp-list的直接链接

Lists Model Context Protocol (MCP) servers registered on the target server. Pass optional JSON input for route-supported filters.

mastra api mcp list [input]

mastra api mcp get
mastra-api-mcp-get的直接链接

Gets metadata for one MCP server.

mastra api mcp get <id>

mastra api mcp tool list
mastra-api-mcp-tool-list的直接链接

Lists tools exposed by an MCP server. Pass optional JSON input for route-supported filters.

mastra api mcp tool list <serverId> [input]

mastra api mcp tool get
mastra-api-mcp-tool-get的直接链接

Gets metadata and schemas for one MCP tool.

mastra api mcp tool get <serverId> <toolId>

mastra api mcp tool execute
mastra-api-mcp-tool-execute的直接链接

Executes an MCP tool with JSON input. Raw tool input is wrapped as the route data field unless you pass an explicit data object.

mastra api mcp tool execute <serverId> <toolId> <input>

mastra api thread list
mastra-api-thread-list的直接链接

Lists memory threads. Pass optional JSON input for route-supported filters.

mastra api thread list [input]

mastra api thread get
mastra-api-thread-get的直接链接

Gets one memory thread by ID.

mastra api thread get <threadId>

mastra api thread create
mastra-api-thread-create的直接链接

Creates a memory thread. Pass one JSON input object. The CLI splits fields such as agentId into query parameters when required by the server route.

mastra api thread create <input>

mastra api thread update
mastra-api-thread-update的直接链接

Updates a memory thread. Pass one JSON input object for fields such as agentId, resourceId, title, or metadata.

mastra api thread update <threadId> <input>

mastra api thread delete
mastra-api-thread-delete的直接链接

Deletes a memory thread. Pass JSON input for route-required query parameters such as agentId and resourceId.

mastra api thread delete <threadId> <input>

mastra api thread messages
mastra-api-thread-messages的直接链接

Lists messages for a memory thread. Pass optional JSON input for route-supported filters or pagination.

mastra api thread messages <threadId> [input]

Searches long-term memory. Use --help or --schema to inspect required fields such as agentId, resourceId, and searchQuery.

mastra api memory search <input>

mastra api memory current get
mastra-api-memory-current-get的直接链接

Reads current working memory for a thread.

mastra api memory current get <input>

mastra api memory current update
mastra-api-memory-current-update的直接链接

Updates current working memory for a thread. Working memory must be enabled for the memory instance.

mastra api memory current update <input>

mastra api memory status
mastra-api-memory-status的直接链接

Gets memory status for an agent and optional thread or resource context.

mastra api memory status <input>

mastra api trace list
mastra-api-trace-list的直接链接

Lists observability traces. Pass optional JSON input for route-supported filters or pagination.

mastra api trace list [input]
mastra api trace list '{"page":0,"perPage":20}'
mastra api trace list '{"page":0,"perPage":20}' --verbose

trace list returns lightweight root span records by default so you can page through traces without fetching large input, output, attributes, or metadata payloads. Pass --verbose to fetch the full root span records.

mastra api trace query
mastra-api-trace-query的直接链接

Queries completed observability traces with recursive predicates over trace fields and related spans. The inline JSON input is required and uses the same query structure as the SDK and HTTP API. Like other observability commands, it targets https://observability.mastra.ai by default. Pass --url http://localhost:4111 to query a local server.

mastra api trace query <input>
mastra api trace query '{"timeRange":{"from":"2026-08-01T00:00:00.000Z","to":"2026-08-08T00:00:00.000Z"}}'

Inspect the command with:

mastra api trace query --help

For supported fields, operators, and request options, see Query traces. For a local Mastra server, you can also inspect its request and response schemas:

mastra api --url http://localhost:4111 trace query --schema

Mastra Platform doesn't currently expose the schema endpoint used by --schema. To find fields and values recorded in your project, use field and value discovery.

The response remains nested under data to preserve cursor pagination:

{
"data": {
"traces": [],
"page": { "next": "opaque-cursor" }
}
}

Each invocation makes one query. Pass a non-null data.page.next value back as page.after in the next query. See Pagination and errors for pagination modes, cursor handling, and errors.

To load a numbered page and then poll, keep the same time range and predicate in both requests:

mastra api trace query '{"timeRange":{"from":"2026-08-01T00:00:00.000Z","to":"2026-08-08T00:00:00.000Z"},"pagination":{"page":0,"perPage":100}}'
mastra api trace query '{"timeRange":{"from":"2026-08-01T00:00:00.000Z","to":"2026-08-08T00:00:00.000Z"},"mode":"delta","after":"CURSOR_FROM_NUMBERED_RESPONSE","limit":100}'

Replace CURSOR_FROM_NUMBERED_RESPONSE with data.deltaCursor from the first response. Delta results remain under data, with traces, delta: { limit, hasMore }, and deltaCursor. Merge traces by traceId, retain each returned cursor, and continue immediately while data.delta.hasMore is true. Don't combine delta mode with page, pagination, or orderBy.

Omitting after establishes a cursor and returns no historical traces. Changing the time range or predicate requires a fresh numbered request. See Delta polling limitations before using this workflow to maintain a local trace list.

mastra api trace aggregate
mastra-api-trace-aggregate的直接链接

Groups the traces selected by a time range and optional where predicate, and returns one row of measures per group. The inline JSON input is required and accepts the same predicates as trace query. Like other observability commands, it targets https://observability.mastra.ai by default.

mastra api trace aggregate <input>
mastra api trace aggregate '{"timeRange":{"from":"2026-08-01T00:00:00.000Z","to":"2026-08-08T00:00:00.000Z"},"groupBy":["entityName"],"measures":["count","errorRate"]}'

Set interval to 1m, 5m, 15m, 1h, or 1d to split each group into time buckets:

mastra api trace aggregate '{"timeRange":{"from":"2026-08-01T00:00:00.000Z","to":"2026-08-08T00:00:00.000Z"},"where":{"op":"eq","left":{"path":"entityName"},"right":{"literal":"weather-agent"}},"interval":"1d","measures":["count","duration.p95"]}'

For dimensions, measures, and request options, see Aggregate traces. Run mastra api trace aggregate --help for more examples.

The response stays nested under data so truncated is preserved. truncated is true when more groups matched than limit:

{
"data": {
"rows": [
{
"dimensions": { "entityName": "weather-agent" },
"measures": { "count": 42, "errorRate": 0.05 }
}
],
"truncated": false
}
}

Servers whose observability store doesn't support trace aggregation return 501. The CLI prints it like other request failures, as an HTTP_ERROR with the server response in error.details.body.

mastra api trace get
mastra-api-trace-get的直接链接

Gets a lightweight timeline for one observability trace without fetching full span input, output, attributes, or metadata payloads. Pass --verbose to fetch the full trace payload.

mastra api trace get <traceId>
mastra api trace get <traceId> --verbose

mastra api trace span
mastra-api-trace-span的直接链接

Gets one full span from an observability trace. Use this after trace get when you know which span you need to inspect.

mastra api trace span <traceId> <spanId>

mastra api log list
mastra-api-log-list的直接链接

Lists observability logs. Pass optional JSON input for route-supported filters or pagination.

mastra api log list [input]

mastra api metric aggregate
mastra-api-metric-aggregate的直接链接

Gets a single aggregate metric value.

mastra api metric aggregate '{"name":["latency_ms"],"aggregation":"avg"}'

mastra api metric breakdown
mastra-api-metric-breakdown的直接链接

Gets metric values grouped by a label or field.

mastra api metric breakdown '{"name":["latency_ms"],"aggregation":"avg","groupBy":["model"],"limit":10}'

mastra api metric timeseries
mastra-api-metric-timeseries的直接链接

Gets metric values over time.

mastra api metric timeseries '{"name":["latency_ms"],"aggregation":"avg","interval":"1h"}'

mastra api metric percentiles
mastra-api-metric-percentiles的直接链接

Gets metric percentile values over time. Percentile values use decimals from 0 to 1.

mastra api metric percentiles '{"name":"latency_ms","percentiles":[0.5,0.95,0.99],"interval":"1h"}'

mastra api metric names
mastra-api-metric-names的直接链接

Lists discovered metric names. Pass optional JSON input for prefix search and limit.

mastra api metric names '{"prefix":"lat","limit":10}'

mastra api metric label-keys
mastra-api-metric-label-keys的直接链接

Lists label keys for a metric.

mastra api metric label-keys '{"metricName":"latency_ms"}'

mastra api metric label-values
mastra-api-metric-label-values的直接链接

Lists label values for a metric label key. Pass optional prefix and limit values to narrow the result.

mastra api metric label-values '{"metricName":"latency_ms","labelKey":"model","prefix":"g","limit":10}'

Observability with curl
observability-with-curl的直接链接

You can call the hosted observability API directly with your platform access token and project ID. The examples below use the United States host. Substitute https://observability.eu.mastra.ai for a European Union environment. The Feedback API documents feedback endpoints that don't have CLI commands:

curl -sS "https://observability.mastra.ai/api/observability/traces?page=0&perPage=20" \
-H "Authorization: Bearer $MASTRA_PLATFORM_ACCESS_TOKEN" \
-H "X-Mastra-Project-Id: $MASTRA_PROJECT_ID" | jq

Get a lightweight trace timeline:

curl -sS "https://observability.mastra.ai/api/observability/traces/<trace-id>/light" \
-H "Authorization: Bearer $MASTRA_PLATFORM_ACCESS_TOKEN" \
-H "X-Mastra-Project-Id: $MASTRA_PROJECT_ID" | jq

Get a specific span:

curl -sS "https://observability.mastra.ai/api/observability/traces/<trace-id>/spans/<span-id>" \
-H "Authorization: Bearer $MASTRA_PLATFORM_ACCESS_TOKEN" \
-H "X-Mastra-Project-Id: $MASTRA_PROJECT_ID" | jq

mastra api score create
mastra-api-score-create的直接链接

Creates an observability score. The input uses the server score body shape. Inspect it with --schema.

mastra api score create <input>

mastra api score list
mastra-api-score-list的直接链接

Lists observability scores. Pass optional JSON input for filters such as run ID or pagination.

mastra api score list [input]

mastra api score get
mastra-api-score-get的直接链接

Gets one observability score by ID.

mastra api score get <scoreId>

mastra api dataset list
mastra-api-dataset-list的直接链接

Lists datasets. Pass optional JSON input for route-supported filters or pagination.

mastra api dataset list [input]

mastra api dataset get
mastra-api-dataset-get的直接链接

Gets one dataset by ID.

mastra api dataset get <datasetId>

mastra api dataset create
mastra-api-dataset-create的直接链接

Creates a dataset with JSON input.

mastra api dataset create <input>

mastra api dataset items
mastra-api-dataset-items的直接链接

Lists items in a dataset. Pass optional JSON input for route-supported filters or pagination.

mastra api dataset items <datasetId> [input]

mastra api experiment list
mastra-api-experiment-list的直接链接

Lists experiments for a dataset. Pass optional JSON input for route-supported filters or pagination.

mastra api experiment list <datasetId> [input]

mastra api experiment get
mastra-api-experiment-get的直接链接

Gets one experiment by ID.

mastra api experiment get <datasetId> <experimentId>

mastra api experiment run
mastra-api-experiment-run的直接链接

Starts an experiment for a dataset with JSON input.

mastra api experiment run <datasetId> <input>

mastra api experiment results
mastra-api-experiment-results的直接链接

Lists results for an experiment. Pass optional JSON input for route-supported filters or pagination.

mastra api experiment results <datasetId> <experimentId> [input]

mastra api learning entities
mastra-api-learning-entities的直接链接

Lists entities (agents) with Trace Intelligence output, including which trace signals are available per entity. Requires enrollment in the Trace Intelligence private beta.

mastra api learning entities '{"entityType":"agent"}'

mastra api learning snapshots
mastra-api-learning-snapshots的直接链接

Lists analysis snapshots for an entity and an ordered, comma-separated list of trace signals. Later commands need a snapshotId from this list.

mastra api learning snapshots <entityId> '{"entityType":"agent","signalNames":"goal,outcome,behavior,sentiment","limit":10}'

mastra api learning flow
mastra-api-learning-flow的直接链接

Gets the cross-signal theme flow for one snapshot: stages and links for a Sankey-style view where counts are distinct traces.

mastra api learning flow <entityId> '{"entityType":"agent","signalNames":"goal,outcome","snapshotId":"<snapshotId>"}'

mastra api learning paths
mastra-api-learning-paths的直接链接

Gets per-trace theme assignments across the ordered trace signals in one snapshot. Paginate with limit and offset.

mastra api learning paths <entityId> '{"entityType":"agent","signalNames":"goal,outcome","snapshotId":"<snapshotId>","limit":100}'

mastra api learning theme list
mastra-api-learning-theme-list的直接链接

Lists themes for one trace signal in one snapshot.

mastra api learning theme list <entityId> '{"entityType":"agent","signalName":"goal","snapshotId":"<snapshotId>"}'

mastra api learning theme get
mastra-api-learning-theme-get的直接链接

Gets one theme in one snapshot by its numeric theme ID.

mastra api learning theme get <entityId> <themeId> '{"entityType":"agent","signalName":"goal","snapshotId":"<snapshotId>"}'

mastra api learning theme examples
mastra-api-learning-theme-examples的直接链接

Lists trace examples for one theme in one snapshot. Paginate with limit and offset.

mastra api learning theme examples <entityId> <themeId> '{"entityType":"agent","signalName":"goal","snapshotId":"<snapshotId>","limit":10}'

mastra api learning theme history
mastra-api-learning-theme-history的直接链接

Gets the lifecycle history for one durable theme across snapshots, including split and merge relationships. Takes no snapshotId.

mastra api learning theme history <entityId> <themeId> '{"entityType":"agent","signalName":"goal"}'

mastra api learning noise get
mastra-api-learning-noise-get的直接链接

Gets the unclustered (noise) bucket for one trace signal in one snapshot.

mastra api learning noise get <entityId> '{"entityType":"agent","signalName":"goal","snapshotId":"<snapshotId>"}'

mastra api learning noise examples
mastra-api-learning-noise-examples的直接链接

Lists trace examples for the noise bucket in one snapshot. Paginate with limit and offset.

mastra api learning noise examples <entityId> '{"entityType":"agent","signalName":"goal","snapshotId":"<snapshotId>","limit":10}'

Common flags
Common flags的直接链接

--dir
--dir-5的直接链接

Available in: dev, build, lint, migrate

The path to your Mastra folder. Defaults to src/mastra.

--debug
--debug-5的直接链接

Available in: dev, build, migrate

Enable verbose logging for Mastra's internals. Defaults to false.

--env
--env-2的直接链接

Available in: dev, start, studio, migrate

Custom environment variables file to include. By default, includes .env.development, .env.local, and .env.

--root
--root-2的直接链接

Available in: dev, build, lint, migrate

Path to your root folder. Defaults to process.cwd().

--tools
--tools-1的直接链接

Available in: dev, build, lint

Comma-separated list of tool paths to include. Defaults to src/mastra/tools.

Global flags
Global flags的直接链接

Use these flags to get information about the mastra CLI.

--version
--version的直接链接

Prints the Mastra CLI version and exits.

--help
--help的直接链接

Prints help message and exits.

Telemetry
Telemetry的直接链接

By default, Mastra collects telemetry about your project, including your OS, Mastra version, and Node.js version. Server events also include the project identifiers described below. You can read the CLI telemetry source code to check what's collected by the CLI.

When a server started with mastra dev, mastra start, or a mastra build output has observability configured, Mastra counts the input and output tokens each model call uses in that server process. Every 15 minutes, and once more when the server shuts down, it sends a mastra_model_token_usage_v2 event per provider and model used since the previous report. If no model calls finished since then, nothing is sent. Each event contains the tokens used since the previous report, the report window's start and end times, the reason for the report (interval or shutdown), the command (dev, start, or server when the build output runs directly), and NODE_ENV. No prompts, responses, or other message content is sent. You can read the model usage telemetry source code to check what's collected.

For compatibility with older analysis, servers also send the earlier mastra_model_token_usage event at startup. It reads token totals from observability storage and sends the usage added since a cursor saved in ~/.mastra/usage-telemetry.json. You can read the startup usage telemetry source code to check what's collected.

At server startup, Mastra sends a project-surface snapshot with component counts, feature flags, and the coarse storage backend category, but no component names or component identifiers. You can read the feature telemetry source code to check what's collected.

The server events mastra_feature_usage, mastra_model_token_usage, and mastra_model_token_usage_v2 include:

  • project_id: The first 16 hexadecimal characters of the SHA-256 hash of MASTRA_PROJECT_ROOT, or the current working directory when unset. This identifier also keys the local model-usage cursor.
  • project_id2: An optional identifier for correlation across machines and deployments. If the trimmed MASTRA_PROJECT_ID value has UUID format, the value is sent unhashed, prefixed with mp_. Search for mp_<platform-project-id> to find that project's telemetry. Names, slugs, and other non-UUID values aren't sent as Platform identifiers.

When no UUID-shaped Platform ID is available, project_id2 uses the first 16 hexadecimal characters of the SHA-256 hash of the normalized Git origin remote. Normalization keeps the lowercase host and repository path, excluding the scheme, credentials, port, query, fragment, trailing slashes, and .git suffix. Equivalent SSH and HTTPS remotes produce the same identifier. Remotes with the same host and path share an identifier even if different ports or SSH users refer to different repositories. Local filesystem remotes aren't used. Git discovery runs asynchronously and is cached for the process, including when unavailable. If neither source is available, project_id2 is omitted.

These server events aren't anonymous: a Platform ID links them to that project, and a known repository URL can be normalized and hashed to match Git-derived events. Hashing the Git identity avoids sending the raw repository URL or credentials, but doesn't prevent correlation with public or otherwise known repositories.

The Studio UI also collects anonymous browser-side usage analytics, such as page views and UI interactions. You can read the source code to check what's collected. Setting MASTRA_TELEMETRY_DISABLED disables this too: the value is injected into the served page, so it applies to mastra dev and self-hosted builds alike.

You can opt out of CLI, server, and Studio usage analytics by setting this environment variable before starting Mastra. When disabled, server telemetry doesn't look up the Git remote or send either project identifier:

MASTRA_TELEMETRY_DISABLED=1

You can also set this while using other mastra commands:

MASTRA_TELEMETRY_DISABLED=1 mastra dev
On this page