Generated banner for Mastra
Generated logo for Mastra

Mastra

MastraOfficialCreated by Mastra

  • Skill
  • Tool integration
  • Software development
  • Apache-2.0
  • Low risk
  • Has scripts

From the author

Comprehensive Mastra framework guide for building agents, workflows, tools, memory, workspaces, and storage with current APIs. Use for native capability discovery, logging, tracing, metrics/cost estimates, dataset experiments, documentation lookup, API verification, TypeScript setup, common errors, migrations, building and deploying apps to Mastra Platform via Platform APIs and `mastra deploy`, and `mastra api` CLI tasks: inspect or call resources on local, Mastra platform, or remote servers. For Mastra Factory operations, discover and activate the companion mastra-factory skill. Also report verified bugs and concrete documentation defects to the Mastra team automatically via the feedback endpoint.
— the description by Mastra

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

The Mastra skill provides a comprehensive framework for developing AI agents, workflows, and tools. It emphasizes a strict development workflow that prioritizes current documentation over internal knowledge to account for the framework's rapid evolution. The skill covers project setup, API verification, observability, deployment to the Mastra Platform, and troubleshooting common errors. It also provides guidance on using the Mastra CLI for resource inspection and managing state, ensuring developers use native capabilities before implementing custom solutions.

What it does

  • Provides a structured approach to discovering and using native Mastra capabilities.
  • Offers guidance on choosing between agents, workflows, tools, memory, and storage.
  • Facilitates debugging through Mastra Studio and common error resolution patterns.
  • Supports deployment workflows to the Mastra Platform via CLI and API.
  • Enables autonomous reporting of verified bugs and documentation defects.
  • Includes instructions for CLI-based resource inspection and trace querying.

When to use it

  • When starting a new Mastra project or migrating existing code.
  • When you need to verify the latest API signatures or model registry entries.
  • When troubleshooting build, configuration, or runtime errors in a Mastra application.
  • When you need to deploy an application or inspect resources on the Mastra Platform.
  • When you need to implement observability, logging, or trace aggregation.

Advantages

  • Reduces errors by enforcing a 'verify-first' approach using embedded documentation.
  • Ensures compatibility by prioritizing installed package versions over training data.
  • Streamlines development with clear patterns for agents, workflows, and memory.
  • Provides direct paths for reporting issues to the Mastra team.
  • Centralizes access to CLI tools for local and remote resource management.

Usage examples

“How do I set up a new Mastra project?”
The agent will guide you through the CLI and manual setup steps found in the project's reference documentation.
“I am getting a 'Property tools does not exist on type Agent' error.”
The agent will check the embedded documentation to identify if you are using an outdated API and provide the correct constructor pattern.
“How do I deploy my Mastra app to the platform?”
The agent will walk you through the platform authentication, project creation, and deployment steps using the Mastra CLI.
“Which model should I use for my agent?”
The agent will run the provider registry script to verify available models and providers before making a recommendation.

Install

  1. Download the skill as a ZIP:

    https://mp-staging.autogineer.com/agent-skills/mastra-ai/mastra/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip mastra.zip -d .agents/skills

Documentation by Mastra

Mastra Framework Guide

Build AI applications with Mastra. This skill teaches you how to find current documentation and build agents and workflows.

Critical: Do not trust internal knowledge

Everything you know about Mastra is likely outdated or wrong. Never rely on memory. Always verify against current documentation.

Your training data contains obsolete APIs, deprecated patterns, and incorrect usage. Mastra evolves rapidly - APIs change between versions, constructor signatures shift, and patterns get refactored.

Prerequisites

Before writing any Mastra code, check if packages are installed:

ls node_modules/@mastra/
  • If packages exist: Use embedded docs first (most reliable)

  • If no packages: Install first or use remote docs

Resources

References
User QuestionFirst CheckHow To
Create/install Mastra projectreferences/create-mastra.mdSetup guide with CLI and manual steps
Choose Agent/Workflow/Tool/Memory/Storagereferences/core-concepts.mdCore concepts and when to use each primitive
Add logging or set up tracingreferences/embedded-docs.mdLook up PinoLogger and observability configuration before custom instrumentation
Track automatic metrics or estimated model costreferences/embedded-docs.mdLook up span-derived metrics, storage support, and pricing coverage
Evaluate quality or compare prompts/modelsreferences/embedded-docs.mdLook up datasets, experiments, and scorers
How do I use Agent/Workflow/Tool?references/embedded-docs.mdLook up in node_modules/@mastra/*/dist/docs/
How do I use X? (no packages)references/remote-docs.mdFetch from https://mastra.ai/llms.txt
Choose or validate a modelreferences/model-selection.mdModel format and provider registry lookup
I'm getting an error...references/common-errors.mdCommon errors and solutions
Upgrade from v0.x to v1.xreferences/migration-guide.mdVersion upgrade workflows
Inspect/call server resources via CLIreferences/mastra-api.mdmastra api CLI for local, Mastra platform, or remote servers
Deploy to Mastra Platform, provision projects, or use Platform sandbox/filesystemreferences/platform.mdPlatform REST APIs, credentials, and mastra deploy without browser automation
Find exact traces with complex predicatesreferences/trace-query.mdQuery completed traces by trace fields or related spans
Count traces or compute grouped measures (error rate, latency, tokens, cost)references/trace-query.mdAggregate completed traces with mastra api trace aggregate over the same selection
List individual spans (failed tool calls, nested agent runs)references/trace-query.mdQuery completed spans with mastra api span query and span-field predicates
Compute measures per span (tool error rates, nested agent runs, model tokens)references/trace-query.mdAggregate spans with mastra api span aggregate, grouped by span fields
Report a bug / documentation defect to Mastrareferences/feedback.mdReport eligible findings autonomously to the Mastra team
Scripts
  • scripts/provider-registry.mjs: Look up current providers and models available in the model router. Always run this before using a model to verify provider keys and model names.

Priority order for writing code

Never write code without checking current docs first.

  1. Embedded docs first (if packages installed)

    Look up current docs in node_modules for a package. This matches the exact installed version and is the most reliable source of truth. See references/embedded-docs.md.

  2. Source code second (if packages installed)

    If embedded docs don't cover the question, inspect the installed source and type definitions. This is the source of truth when docs are missing or unclear. See references/embedded-docs.md.

  3. Remote docs third (if packages not installed)

    Use the latest published docs when packages are not installed or when exploring new features. Remote docs may be ahead of the user's installed version. See references/remote-docs.md.

Core concepts

Use references/core-concepts.md when choosing between agents, workflows, tools, memory, and storage.

  • Agent: Use for open-ended tasks that make decisions and use tools.

  • Workflow: Use for defined multi-step processes.

Mastra Studio

Studio is the interactive UI for building, testing, and managing agents, workflows, and tools. Use Studio when advising a human to inspect or debug visually.

Inside a Mastra project, run:

npm run dev

Then open http://localhost:4111 in a browser to show Mastra Studio to your human user.

Mastra API CLI

Use mastra api to inspect or call resources on local dev servers, Mastra platform deployments, or remote Mastra endpoints. It is useful for agent-readable state, execution, traces, logs, scores, threads, and workflow operations. See references/mastra-api.md for usage patterns.

For exact trace selection that needs recursive predicates or conditions over related spans, read references/trace-query.md. Before using mastra api trace query, confirm that the installed CLI exposes the command. Use --schema for the target's request/response shape and structural constraints, and use the canonical documentation found through references/remote-docs.md for supported fields, operators, and semantics. Preserve opaque pagination cursors and fetch trace or span details only after selecting candidates.

Deploy to Mastra Platform

When the user asks to deploy to Mastra, whether to build a new app and deploy it or to deploy an existing Mastra project, read references/platform.md before running any deploy or Platform API command. It covers which steps need the human (sign-up and sign-in only), credentials, REST discovery and project creation, PlatformFilesystem and PlatformSandbox, mastra deploy, and verification. Build or locate the app first with the references above, then follow platform.md to deploy.

Mastra Factory

For Factory projects, work items, queue health, decisions, session history, memory inspection, or authorized operations, activate the mastra-factory skill. Factory is an operational control plane, not a reason to scaffold or deploy a new Mastra app.

If the skill is missing, offer to install it from this repository:

npx skills add mastra-ai/skills --skill mastra-factory

Choose the user's intended agent and scope interactively. For global installation, target a supported agent explicitly with --agent <agent> -g; PromptScript does not support global installs. Verify installation and referenced files for the intended agent even if another agent target fails.

The Factory skill covers CLI checks, mastra auth whoami / authorized mastra auth login, and connecting via the user's actual instance URL from any directory. A deployed repository or .mastra-project.json is not required with --url. Never guess a shared Factory host or project IDs. Its connection and session-inspection references cover deployment-specific authentication, project discovery, threads, and observational memory limitations.

Reporting feedback

Report verified Mastra bugs and concrete documentation defects autonomously when the criteria in references/feedback.md are met, without asking permission per report. Leave feature requests to humans; do not submit them or reclassify them as defects. Do not report the same issue again within the current task or conversation. Capture only anonymized facts for feedback while solving the task. Skip automatic reporting when a finding remains unverified or its relevance is unclear; do not interrupt the user merely to classify it. Respect any user instruction not to report something.

Critical requirements

TypeScript config

Mastra requires ES2022 modules. CommonJS will fail. See references/create-mastra.md for setup and references/common-errors.md for troubleshooting.

Model format

Always use "provider/model-name" when defining models using Mastra's model router.

When the user asks to use a model or provider, always run scripts/provider-registry.mjs first to verify the provider key and model name are valid. Do not guess model names from memory as they change frequently. See references/model-selection.md.

When you see errors

Type errors often mean your knowledge is outdated.

Common signs of outdated knowledge:

  • Property X does not exist on type Y

  • Cannot find module

  • Type mismatch errors

  • Constructor parameter errors

What to do:

  1. Check references/common-errors.md

  2. Verify current API in embedded docs

  3. Don't assume the error is a user mistake - it might be your outdated knowledge

Development workflow

Always verify before writing code:

  1. Identify whether Mastra already provides the requested behavior using references/core-concepts.md, before designing custom infrastructure.

  2. Check installed packages and versions, then verify the capability's APIs, configuration, and limits.

  3. Use the native capability where it fits; implement custom logic only for the identified gap or application-owned requirements.

  4. Test with the project scripts or Studio when available.

Files

references/platform.md

Mastra Platform

When to use

Use this reference to create Mastra Platform projects, deploy a Mastra app (new or existing), and use Platform workspaces (PlatformFilesystem, PlatformSandbox) in generated code. For calls to a running Mastra server (agents, workflows, traces), use mastra-api.md; it does not cover the Platform control plane.

The Platform API changes often. Treat the live spec https://platform.mastra.ai/openapi.json and mastra <command> --help as the source of truth, and check them before using anything not listed here.

Human steps vs agent steps

The browser is only for the human: signing up, creating an organization, and mastra auth login. Never automate the browser or scrape the dashboard.

Everything else is agent work: scaffolding, REST discovery and provisioning, mastra deploy, and verification. When credentials are missing, stop and ask the user to do one of:

  • Run mastra auth login in their own terminal (browser sign-in). The CLI saves the session, and later CLI commands reuse it without a TTY.

  • Create an API token themselves (mastra auth tokens create <name> in their own terminal, or the dashboard) and put it, with MASTRA_ORG_ID, in the environment or an ignored env file.

Do not run mastra auth tokens create yourself: it prints the secret to stdout. Never ask for secret values in chat, never print or log them, and never commit them.

If you need anything you were not given — a credential, a model-provider key, which org or project to use — stop and ask the user. Do not take secrets from your own shell environment, other projects, or files the user did not point you to.

Credentials

Two credential models exist. Do not mix them.

VariableUsed byNotes
MASTRA_API_TOKENCLI and control-plane RESTWins over saved mastra auth login credentials. Setting it puts mastra deploy in headless mode.
MASTRA_ORG_IDCLI and control-plane RESTSent as x-organization-id. Required with MASTRA_API_TOKEN.
MASTRA_PROJECT_IDCLI headless deployMust be a project ID (not a slug or name) in headless mode.
MASTRA_PLATFORM_API_URLCLIOptional override. Default https://platform.mastra.ai.
MASTRA_PLATFORM_ACCESS_TOKENApp runtime (workspaces, observability)Not a deploy credential. Injected on deploy; locally, an org API token the user creates.
MASTRA_ENVIRONMENT_ID, MASTRA_PLATFORM_BUCKET_NAMEApp runtime (workspaces)Injected on deploy; set manually only for local runs.

Check for a saved session with mastra auth whoami before asking for credentials. With a saved session, CLI commands (including mastra deploy) work without a TTY and use the current org (mastra auth orgs; override with --org <id>). Only signing in, or signing in again after the session expires, needs a TTY. Do not read the saved credentials file; in session mode use CLI commands instead of the REST calls below, which need MASTRA_API_TOKEN.

Keep control-plane credentials (MASTRA_API_TOKEN, MASTRA_ORG_ID) in the shell environment, not in the app's .env: deploy uploads app env files as-is and does not filter them.

Discover and provision over REST

mastra deploy and mastra auth have no JSON output, so use REST when you need machine-readable state. Every control-plane call uses the same headers:

curl -fsS https://platform.mastra.ai/v1/auth/orgs \
  -H "Authorization: Bearer $MASTRA_API_TOKEN" \
  -H "x-organization-id: $MASTRA_ORG_ID"
RoutePurpose
GET /v1/auth/orgs{ organizations: [{ id, slug, name, role, isCurrent }] }. Pick MASTRA_ORG_ID here (or mastra auth whoami). Org API keys (sk_...) get an empty list; ask the user for the org ID.
GET /v1/projectsList projects in the org.
POST /v1/studio/projectsCreate a project. Body {"name": "..."} (1–64 chars); response { project: { id, slug, workspacesEnabled, ... } }. Viewer/read-only roles get 403.
GET /v1/projects/{id}Project details, including workspacesEnabled.
GET /v1/projects/{projectId}/environments{ environments: [{ id, name, slug, type, region, instanceUrl, customServerUrl, ... }] }. Not in the public spec; called by the CLI.
POST /v1/projects/{projectId}/environmentsCreate an environment. Body {"name": "production", "type": "production", "region": "us"} (region optional). Not in the public spec; called by the CLI.
GET /v1/projects/{projectId}/environment-deploys{ deploys: [{ id, environmentName, status, error, errorCode, createdAt, ... }] }. Not in the public spec; called by the CLI.

/v1/projects itself is list-only; project creation is under /v1/studio/projects. The spec also lists POST /v1/auth/orgs (create organization), but creating or choosing an organization is the user's decision: ask the user, do not create one.

Before calling a route not listed here, check it exists with the method you need:

curl -fsS https://platform.mastra.ai/openapi.json | jq '.paths["/v1/studio/projects"] | keys'

Build with Platform workspaces

Use @mastra/platform-workspace when the app needs durable file storage or remote command execution on the Platform. New projects have workspaces enabled and get one bucket per environment when the environment is created.

npm install @mastra/platform-workspace
import { Workspace } from '@mastra/core/workspace';
import { PlatformFilesystem, PlatformSandbox } from '@mastra/platform-workspace';

// Reads MASTRA_PLATFORM_ACCESS_TOKEN, MASTRA_PROJECT_ID, MASTRA_ENVIRONMENT_ID,
// and MASTRA_PLATFORM_BUCKET_NAME from the environment. The Platform injects them on deploy.
export const workspace = new Workspace({
  filesystem: new PlatformFilesystem(),
  sandbox: new PlatformSandbox(),
});
import { Mastra } from '@mastra/core';
import { workspace } from './workspace';

export const mastra = new Mastra({
  // TODO: register your agents, workflows, and storage
  workspace,
});

The bucket is shared by every request in the environment. A statically configured PlatformSandbox is one shared sandbox; construct a new PlatformSandbox() (call start(), then destroy()) for per-task isolation. The sandbox does not mount the bucket. Check the installed package's types or embedded docs for sandbox options before using them.

Local runs need all four runtime variables in the app's .env. Get MASTRA_ENVIRONMENT_ID from the environments route and the bucket name from GET /v1/server/projects/{id}/environments/{envId}/bucket (envId is the environment ID; response includes status: provisioning, ready, failed, or destroyed). The user creates the local MASTRA_PLATFORM_ACCESS_TOKEN (an org API token from the dashboard). For an offline loop, swap in LocalFilesystem and LocalSandbox.

Projects created before workspaces were on by default may have workspacesEnabled: false. Enable with POST /v1/server/projects/{id}/workspaces/enable: it requires an admin role (an org API key may not qualify), returns 409 when the project has no environment yet, is idempotent, and cannot be undone. Ask the user before calling it.

Deploy

mastra deploy builds the app, runs preflight checks, uploads .mastra/output, and follows the deploy until it is running or fails. The first deploy creates the environment (--env, default production) and writes .mastra-project.json (projectId, projectName, projectSlug, organizationId, optional disablePlatformObservability). It holds no secrets and links the directory to the project for later deploys.

SituationCommand
Saved mastra auth login session (no MASTRA_API_TOKEN set)mastra deploy --project <name> --yes (creates the project in the current org if not found)
Headless, token in envExport MASTRA_API_TOKEN, MASTRA_ORG_ID, MASTRA_PROJECT_ID, then mastra deploy --yes
Directory already linkedmastra deploy --yes (reads .mastra-project.json)

--project <value> deploys into an existing project whose ID, slug, or name matches, replacing whatever is running there; it creates a project only when nothing matches. When the directory is not linked yet, check for an existing project with that name first (GET /v1/projects with a token; otherwise ask the user). If one exists and you did not create it in this session, ask the user whether to deploy into it or pick a different name.

In headless mode the project must already exist and MASTRA_PROJECT_ID must be its ID. For a new app, create it first with POST /v1/studio/projects, read project.id, and export it. Headless mode auto-accepts prompts.

Other useful flags: --env <name>, --region us|eu (new environments only), --env-file <file>, --workers dedicated|in-process, --skip-build. Avoid --skip-preflight; it skips the checks that prevent broken deploys.

App environment variables. Variables stored on the Platform environment are used at deploy time. --env-file <file> layers a local file on top (overriding stored keys); with several .env* files present, headless mode requires an explicit --env-file. A missing model-provider key fails at runtime, not at deploy. Before deploying, check which keys the app needs (for example OPENAI_API_KEY); if they are not already stored on the environment, ask the user to put them in a gitignored env file in the project (for example .env.production) and deploy with --env-file <file> (path relative to the project). Deploy saves those variables on the environment, so later deploys reuse them. Never fill that file from your own shell (for example printf 'KEY=%s' "$KEY" > .env.production): the value persists on the Platform environment. If a key was deployed that the user did not provide, tell the user so they can remove or rotate it; do not change stored environment credentials yourself.

Storage. Preflight blocks file-backed storage (file:./mastra.db) because the Platform filesystem is ephemeral. Guard the path with an environment variable:

import { LibSQLStore } from '@mastra/libsql';

export const storage = new LibSQLStore({
  id: 'mastra-storage',
  // Hosted database when deployed, local file during development
  url: process.env.TURSO_DATABASE_URL ?? 'file:./mastra.db',
  authToken: process.env.TURSO_AUTH_TOKEN,
});

The deploy-time offer to create a managed database is interactive only; in headless or --yes runs the CLI prints the command instead. Provision it explicitly once the environment exists (create the environment first with mastra env create production --type production --project "$MASTRA_PROJECT_ID" or the REST route above):

mastra env db create production --kind turso --project "$MASTRA_PROJECT_ID"

The database's connection variables are injected into deploys automatically.

Verify

  1. mastra deploy exits non-zero on failure and prints the Server URL on success. The CLI waits until the deploy status is running (success), failed, or stopped; any other status is still in progress.

  2. For machine-readable status, read the newest entry from GET /v1/projects/{projectId}/environment-deploys, or poll GET /v1/projects/{projectId}/environments/{environmentId}/deploys/{deployId}.

  3. On failure, run mastra env diagnosis <deploy-id> for fix suggestions.

  4. Call the deployed server with mastra api --url <server-url> agent list (see mastra-api.md), then exercise one agent, including a workspace tool if the app uses one.

Clean up

Only delete resources you created in this session, and only with the user's consent. DELETE /v1/projects/{id} is a soft delete: GET /v1/projects/recently-deleted lists deleted projects and POST /v1/projects/{id}/undelete restores one. mastra env delete <environment> removes an environment.

Failures

SymptomCause and fix
401Missing, expired, or wrong credential type. MASTRA_PLATFORM_ACCESS_TOKEN cannot replace MASTRA_API_TOKEN. Ask the user for a new token.
403Role lacks permission (viewer on project create, non-admin on workspace enable). Ask the user for a token with a sufficient role.
Headless deploy asks for MASTRA_ORG_ID / MASTRA_PROJECT_IDBoth are required with MASTRA_API_TOKEN; create the project over REST first.
No organizations found from mastra env ... with MASTRA_API_TOKENKnown CLI issue: org resolution can fail before MASTRA_ORG_ID is read. Use the REST route with x-organization-id instead.
409 on workspace enableThe project has no environment; deploy or create one first.
Generic 500 from PlatformFilesystem / PlatformSandboxUpstream storage or sandbox error, not auth. Capture the request ID and report it; do not retry in a loop.
Preflight blocks a local storage pathGuard the path with an env var and attach a managed database (see Storage).
Deploy succeeds but agent calls failModel-provider key missing from the environment. Ask the user to add it to a gitignored env file, then redeploy with --env-file <file>.

Requirements and compatibility

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Needs: Needs Node.js

Security

What our scanner noticed· Low risk

  • Instructions that use the network
  • Scripts that your agent may run

This skill includes scripts that your agent may run. Read them before you use it.

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Created by
Mastra
Publisher
Mastra (Official)
Source
mastra-ai/skills · skills/mastra · commit 3020257
Licence
Apache License 2.0 (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by Mastra.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download mastra.zip