> Discover all available pages from the documentation index: https://mastra.ai/llms.txt

# CLI commands

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

## `mastra dev`

Starts a server which exposes [Studio](https://mastra.ai/docs/studio/overview) 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](https://mastra.ai/reference/configuration).

### Flags

The command accepts [common flags](#common-flags) and the following additional flags:

#### `--https`

Enable local HTTPS support. [Learn more](https://mastra.ai/reference/configuration).

#### `--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`

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`

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

#### `--request-context-presets`

Path to a JSON file containing [request context](https://mastra.ai/docs/server/request-context) presets. When provided, a dropdown displays in Studio's request context editor, letting you quickly switch between preset configurations.

```bash
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:

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

### Configs

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

#### Skip peer dependency check

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

```bash
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

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

```bash
MASTRA_DEV_NO_CACHE=1 mastra dev
```

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

#### Limit parallelism

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

```bash
MASTRA_CONCURRENCY=4 mastra dev
```

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

#### 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:

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

For Anthropic:

```bash
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`

Starts a development server for [Agent Builder](https://agent-builder.mastra.ai/) development. It uses the same dev runtime and flags as [`mastra dev`](#mastra-dev) and writes to the same `.mastra/output` directory.

```bash
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`](#mastra-dev), including `--https`, `--inspect`, `--inspect-brk`, `--custom-args`, and `--request-context-presets`.

## `mastra build`

The `mastra build` command bundles your Mastra project into a production-ready Hono server. [Hono](https://hono.dev/) 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`](#mastra-start).

If you're deploying to a [serverless platform](https://mastra.ai/docs/deployment/cloud-providers) you need to install the correct deployer to receive the correct output in `.mastra`.

It accepts [common flags](#common-flags).

### Flags

#### `--studio`

Bundle the Studio UI with the build.

### Configs

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

#### Skip peer dependency check

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

```bash
MASTRA_SKIP_PEERDEP_CHECK=1 mastra build
```

#### 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`.

```bash
MASTRA_CONCURRENCY=2 mastra build
```

## `mastra start`

> **Note:** 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](https://mastra.ai/docs/observability/tracing/overview) is enabled.

### Flags

The command accepts [common flags](#common-flags) and the following additional flags:

#### `--dir`

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

#### `--custom-args`

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

## `mastra worker build`

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

```bash
mastra worker build [options]
```

### Flags

#### `--dir`

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

#### `--root`

Project root directory. Defaults to the current directory.

#### `--tools`

Comma-separated tool paths to include in the bundle.

#### `--output-dir`

Custom output directory. Defaults to `.mastra/output`.

#### `--debug`

Enable debug logging during the 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.

```bash
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

`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

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:

| Code | Meaning                    |
| ---- | -------------------------- |
| `0`  | Completed                  |
| `10` | Completed with item errors |
| `20` | Fatal failure              |
| `21` | Retryable failure          |
| `30` | Cancelled                  |
| `31` | Timed out                  |
| `70` | Protocol failure           |

### 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

#### `--dir`

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

#### `--root`

Project root directory. Defaults to the current directory.

#### `--output-dir`

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

#### `--debug`

Enable debug logging during the build.

## `mastra worker start`

> **Note:** 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.

```bash
mastra worker start [name] [options]
```

### Flags

#### `--dir`

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

#### `--env`

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

### Examples

```bash
# 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](https://mastra.ai/docs/deployment/workers) for deployment topologies and configuration.

## `mastra studio`

Starts [Studio](https://mastra.ai/docs/studio/overview) 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

The command accepts [common flags](#common-flags) and the following additional flags:

#### `--port`

The port to run Studio on. Defaults to `3000`.

#### `--server-host`

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

#### `--server-port`

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

#### `--server-protocol`

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

#### `--server-api-prefix`

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

#### `--request-context-presets`

Path to a JSON file containing [request context](https://mastra.ai/docs/server/request-context) presets. Works the same as the [`mastra dev` flag](#--request-context-presets).

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

## `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`](#mastra-studio-deploy) and [`mastra server deploy`](#mastra-server-deploy), which continue to work but should no longer be used for new setups.

Requires authentication via [`mastra auth login`](#mastra-auth-login) or a `MASTRA_API_TOKEN` environment variable.

```bash
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.

If the project doesn't exist yet, the CLI creates it from the `package.json` `name` field after confirmation. If the target environment doesn't exist, the CLI creates it (defaulting to `type: staging` for anything other than `production`) after confirmation. Combined with `--yes`, this creates and deploys everything in one non-interactive command:

```bash
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

#### `[dir]`

Project directory. Defaults to the current directory.

### Flags

#### `--env`

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`

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

#### `--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`

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

#### `-c, --config`

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

#### `--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`.

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

#### `--region`

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

#### `--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 the pre-upload validation of the built output.

#### `--debug`

Enable debug logs during the build step.

### 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.

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

## `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 `MASTRA_PROJECT_ID` environment variable and the `--project <name|slug|id>` flag. It then reads the `.mastra-project.json` file written by [`mastra deploy`](#mastra-deploy) in the current directory. Run from your project directory and you never need to name the project.

### `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.

```bash
mastra env list
```

#### `--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`

Creates a new environment for a project.

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

#### `-t, --type`

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

#### `-r, --region`

Region for the environment (for example `eu`).

#### `--json`

Emit machine-readable JSON. Sensitive fields are omitted, as with [`mastra env list`](#mastra-env-list).

### `mastra env delete`

Deletes an environment.

```bash
mastra env delete <env>
```

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

#### `-y, --yes`

Skip the confirmation prompt.

### `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.

```bash
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`

Pulls an environment's env vars into a local env file (default: `.env`). The file contains the merged set used by a deploy. It combines vars stored on the environment (for example, added in the dashboard's environment editor) with project-level vars. Project values win on conflict. Managed vars injected by attached databases are listed as comments (names only) since their values are platform-managed secrets.

```bash
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`

File to write. Defaults to `.env`.

#### `-f, --force`

Replace an existing output file.

### `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`

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).

```bash
mastra env db list
mastra env db list <env>
```

#### `--json`

Emit machine-readable JSON.

### `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`.

```bash
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
```

#### `--kind`

Database provider (required). One of `turso`, `neon`, or `redis`.

#### `--name`

Database name. Defaults to a name derived from the project slug and provider (for example `my-app-turso` or `my-app-redis`).

#### `--region`

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

#### `--shared`

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

#### `--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`

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`

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

```bash
mastra env db show <database>
```

`<database>` can be a database ID or name.

#### `--show-secrets`

Print secret connection values instead of masking them.

#### `--json`

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

### `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.

```bash
mastra env db delete <database>
```

#### `-y, --yes`

Skip the confirmation prompt.

### `mastra env deploys`

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

```bash
mastra env deploys [environment]
```

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

#### `--json`

Emit machine-readable JSON.

## `mastra studio deploy`

> **Note:** `mastra studio deploy` continues to work but is superseded by [`mastra deploy`](#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`](#mastra-auth-login) or a `MASTRA_API_TOKEN` environment variable.

```bash
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:

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

### Arguments

#### `[dir]`

Project directory. Defaults to the current directory.

### Flags

#### `--org`

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

#### `--project`

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`

Auto-accept defaults without confirmation prompts.

#### `-c, --config`

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

#### `--env-file`

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`).

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

#### `--skip-build`

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

#### `--debug`

Enable debug logs during the build step.

### 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`

Lists all projects with their latest deploy status and URL.

### `mastra studio deploy status`

Shows the status of a specific deploy.

```bash
mastra studio deploy status <deploy-id>
```

#### `--watch, -w`

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

### `mastra studio deploy logs`

Shows logs for a specific deploy.

```bash
mastra studio deploy logs <deploy-id>
```

#### `--follow, -f`

Stream logs in real time.

#### `--tail`

Number of recent log lines to show.

### `mastra studio deploy suggestions`

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

```bash
mastra studio deploy suggestions [deploy-id]
```

If you omit `deploy-id`, the command uses the latest deploy for the linked project. If a diagnosis doesn't exist yet, the command starts one and polls until results are ready. Suggestions appear only when the diagnosis finds a problem.

### `mastra studio projects`

Lists all projects in the current organization.

### `mastra studio projects create`

Creates a new project through an interactive prompt. This command doesn't accept a `--name` flag; for non-interactive project creation, use [`mastra studio deploy --project <name> --yes`](#mastra-studio-deploy) instead, which creates the project and deploys to it in one step.

## `mastra server deploy`

> **Note:** `mastra server deploy` continues to work but is superseded by [`mastra deploy`](#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`](#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.

```bash
mastra server deploy [dir]
```

### `mastra server deploy suggestions`

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

```bash
mastra server deploy suggestions [deploy-id]
```

If you omit `deploy-id`, the command uses the latest deploy for the linked project. If a diagnosis doesn't exist yet, the command starts one and polls until results are ready. Suggestions appear only when the diagnosis finds a problem.

## `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-deploy).

```bash
mastra server pause
```

### Flags

#### `--org`

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

#### `--project`

Project ID or slug when `MASTRA_PROJECT_ID` isn't set. Slugs are resolved against projects in the current organization.

#### `-c, --config`

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

Fails if the instance isn't running.

## `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`](#mastra-server-deploy) until the deploy reaches a terminal state.

### Flags

Same flags as [`mastra server pause`](#mastra-server-pause): **`--org`**, **`--project`**, and **`-c` / `--config`**, with the same defaults and behavior.

```bash
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`

Manages environment variables for the linked server deployment. Organization and project resolution work the same as [`mastra server deploy`](#mastra-server-deploy).

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

### `mastra server env list`

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

### `mastra server env set`

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

```bash
mastra server env set <key> <value>
```

### `mastra server env unset`

Removes an environment variable.

```bash
mastra server env unset <key>
```

### `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.

```bash
mastra server env import <file>
```

### `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-import).

```bash
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 ID or slug. Overrides the linked project when `MASTRA_PROJECT_ID` isn't set.

#### CI usage

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

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

## `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`

Opens a browser for login and stores the credentials locally.

### `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`

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

### `mastra auth orgs`

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

#### `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`

Lists all API tokens with their last-used date.

#### `mastra auth tokens create`

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

```bash
mastra auth tokens create <name>
```

#### `mastra auth tokens revoke`

Revokes an API token.

```bash
mastra auth tokens revoke <token-id>
```

## `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.

```bash
mastra lint --preflight
```

It accepts [common flags](#common-flags).

### Flags

#### `--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`

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

#### `--env-file <file>`

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

#### `--strict`

Treats warnings as errors.

#### `--json`

Emits machine-readable JSON output.

#### `--debug`

Enables debug logs.

## `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](https://mastra.ai/docs/evals/overview) to learn more.

### `add`

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

```bash
mastra scorers add
```

Or provide a scorer name directly:

```bash
mastra scorers add answer-relevancy
```

Use the [`list`](#list) command to get the correct ID.

### `list`

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

## `mastra create`

Create a standalone Mastra project with the same project-creation flow as [`create-mastra`](https://mastra.ai/reference/cli/create-mastra).

**npm**:

```bash
npx mastra@latest create
```

**pnpm**:

```bash
pnpm dlx mastra@latest create
```

**Yarn**:

```bash
yarn dlx mastra@latest create
```

**Bun**:

```bash
bun x 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](https://mastra.ai/reference/cli/create-mastra) for mode behavior, conflicts, validation, and complete flag descriptions.

## `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

The command accepts the following additional flags:

#### `--default`

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

#### `--dir`

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

#### `--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`

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

#### `--llm-api-key`

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

#### `--example`

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

#### `--no-example`

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

#### `--mcp`

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

#### `--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`

Skip the Mastra Observability prompt.

#### `--observability-project`

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

## `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](https://mastra.ai/integrations/databases/clickhouse) for details.

```bash
mastra migrate
```

See the [Storage migration guide](https://mastra.ai/reference/migrations/upgrade-to-v1/storage) for details on when migrations are needed.

It accepts [common flags](#common-flags).

## `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.

```bash
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

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

```json
{ "data": {} }
```

List commands return a `data` array and pagination metadata:

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

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

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

### 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 auth is only used when the CLI resolves a Mastra platform target from `.mastra-project.json`. Localhost targets and 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 `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`. Both resolve 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.

Use `--url` and `--header` when you need to override the default hosted observability target or credentials.

### Flags

#### `--url <url>`

Target a specific Mastra server URL.

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

#### `--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.

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

#### `--header <"Key: Value">`

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

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

#### `--timeout <ms>`

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

#### `--pretty`

Pretty-print JSON output. Defaults to `false`.

#### `--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.

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

### Input model

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

```bash
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.

```bash
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:

```bash
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:

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

### 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:

```bash
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:

```bash
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

#### `mastra api agent list`

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

```bash
mastra api agent list [input]
```

#### `mastra api agent get`

Gets metadata for one registered agent.

```bash
mastra api agent get <agentId>
```

#### `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.

```bash
mastra api agent run <agentId> <input>
```

#### `mastra api workflow list`

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

```bash
mastra api workflow list [input]
```

#### `mastra api workflow get`

Gets metadata for one registered workflow.

```bash
mastra api workflow get <workflowId>
```

#### `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.

```bash
mastra api workflow run start <workflowId> <input>
```

#### `mastra api workflow run list`

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

```bash
mastra api workflow run list <workflowId> [input]
```

#### `mastra api workflow run get`

Gets one workflow run by ID.

```bash
mastra api workflow run get <workflowId> <runId>
```

#### `mastra api workflow run resume`

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

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

#### `mastra api workflow run cancel`

Cancels a workflow run.

```bash
mastra api workflow run cancel <workflowId> <runId>
```

#### `mastra api tool list`

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

```bash
mastra api tool list [input]
```

#### `mastra api tool get`

Gets metadata and schemas for one tool.

```bash
mastra api tool get <toolId>
```

#### `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.

```bash
mastra api tool execute <toolId> <input>
```

#### `mastra api mcp list`

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

```bash
mastra api mcp list [input]
```

#### `mastra api mcp get`

Gets metadata for one MCP server.

```bash
mastra api mcp get <id>
```

#### `mastra api mcp tool list`

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

```bash
mastra api mcp tool list <serverId> [input]
```

#### `mastra api mcp tool get`

Gets metadata and schemas for one MCP tool.

```bash
mastra api mcp tool get <serverId> <toolId>
```

#### `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.

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

#### `mastra api thread list`

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

```bash
mastra api thread list [input]
```

#### `mastra api thread get`

Gets one memory thread by ID.

```bash
mastra api thread get <threadId>
```

#### `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.

```bash
mastra api thread create <input>
```

#### `mastra api thread update`

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

```bash
mastra api thread update <threadId> <input>
```

#### `mastra api thread delete`

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

```bash
mastra api thread delete <threadId> <input>
```

#### `mastra api thread messages`

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

```bash
mastra api thread messages <threadId> [input]
```

#### `mastra api memory search`

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

```bash
mastra api memory search <input>
```

#### `mastra api memory current get`

Reads current working memory for a thread.

```bash
mastra api memory current get <input>
```

#### `mastra api memory current update`

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

```bash
mastra api memory current update <input>
```

#### `mastra api memory status`

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

```bash
mastra api memory status <input>
```

#### `mastra api trace list`

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

```bash
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 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.

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

#### `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.

```bash
mastra api trace span <traceId> <spanId>
```

#### `mastra api log list`

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

```bash
mastra api log list [input]
```

#### `mastra api metric aggregate`

Gets a single aggregate metric value.

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

#### `mastra api metric breakdown`

Gets metric values grouped by a label or field.

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

#### `mastra api metric timeseries`

Gets metric values over time.

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

#### `mastra api metric percentiles`

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

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

#### `mastra api metric names`

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

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

#### `mastra api metric label-keys`

Lists label keys for a metric.

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

#### `mastra api metric label-values`

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

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

#### Observability with `curl`

You can call the hosted observability API directly with your platform access token and project ID:

```bash
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:

```bash
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:

```bash
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`

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

```bash
mastra api score create <input>
```

#### `mastra api score list`

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

```bash
mastra api score list [input]
```

#### `mastra api score get`

Gets one observability score by ID.

```bash
mastra api score get <scoreId>
```

#### `mastra api dataset list`

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

```bash
mastra api dataset list [input]
```

#### `mastra api dataset get`

Gets one dataset by ID.

```bash
mastra api dataset get <datasetId>
```

#### `mastra api dataset create`

Creates a dataset with JSON input.

```bash
mastra api dataset create <input>
```

#### `mastra api dataset items`

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

```bash
mastra api dataset items <datasetId> [input]
```

#### `mastra api experiment list`

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

```bash
mastra api experiment list <datasetId> [input]
```

#### `mastra api experiment get`

Gets one experiment by ID.

```bash
mastra api experiment get <datasetId> <experimentId>
```

#### `mastra api experiment run`

Starts an experiment for a dataset with JSON input.

```bash
mastra api experiment run <datasetId> <input>
```

#### `mastra api experiment results`

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

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

#### `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.

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

#### `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.

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

#### `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.

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

#### `mastra api learning paths`

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

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

#### `mastra api learning theme list`

Lists themes for one trace signal in one snapshot.

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

#### `mastra api learning theme get`

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

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

#### `mastra api learning theme examples`

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

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

#### `mastra api learning theme history`

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

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

#### `mastra api learning noise get`

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

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

#### `mastra api learning noise examples`

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

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

## Common flags

### `--dir`

**Available in:** `dev`, `build`, `lint`, `migrate`

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

### `--debug`

**Available in:** `dev`, `build`, `migrate`

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

### `--env`

**Available in:** `dev`, `start`, `studio`, `migrate`

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

### `--root`

**Available in:** `dev`, `build`, `lint`, `migrate`

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

### `--tools`

**Available in:** `dev`, `build`, `lint`

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

## Global flags

Use these flags to get information about the `mastra` CLI.

### `--version`

Prints the Mastra CLI version and exits.

### `--help`

Prints help message and exits.

## Telemetry

By default, Mastra collects anonymous information about your project like your OS, Mastra version or Node.js version. You can read the [source code](https://github.com/mastra-ai/mastra/blob/main/packages/cli/src/analytics/index.ts) to check what's collected.

When a server started with `mastra dev` or `mastra start` has observability metrics enabled, Mastra also sends anonymous, aggregated model usage at startup: input and output token counts per provider and model, plus the command (`dev` or `start`) and `NODE_ENV`. No prompts, responses, or other message content is ever sent. You can read the [source code](https://github.com/mastra-ai/mastra/blob/main/packages/core/src/telemetry/usage-telemetry.ts) to check what's collected.

At server startup, Mastra also sends an anonymous project-surface snapshot: counts of registered agents, agent controllers, workflows, tools, processors, vector stores, scorers, workspaces, MCP servers, gateways, and channels, plus booleans for memory, voice, editor, and observability usage and the coarse storage backend category. It doesn't send names or identifiers. You can read the [source code](https://github.com/mastra-ai/mastra/blob/main/packages/core/src/telemetry/feature-telemetry.ts) to check what's collected.

The Studio UI also collects anonymous browser-side usage analytics, such as page views and UI interactions. You can read the [source code](https://github.com/mastra-ai/mastra/blob/main/packages/playground/src/lib/analytics.tsx) 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 all CLI and usage analytics by setting an environment variable:

```bash
MASTRA_TELEMETRY_DISABLED=1
```

You can also set this while using other `mastra` commands:

```bash
MASTRA_TELEMETRY_DISABLED=1 mastra dev
```