
Mastra
- 27.1k installs
- 71 repo stars
- Updated July 30, 2026
- mastra-ai/skills
Mastra skills are official guides for building AI-powered agents and applications using the Mastra TypeScript framework.
About
Official Mastra skills teach developers how to build AI-powered applications and agents using the Mastra framework. A single comprehensive skill uses progressive disclosure to route between setup guides, embedded docs lookup from node_modules, remote API docs, common errors, and migration guides. Mastra itself is a modern TypeScript framework for agents with state, scheduling, RPC, and more.
- Single comprehensive skill for all Mastra framework development with progressive disclosure across setup, embedded docs,
- Embedded docs lookup reads live from node_modules/@mastra/*/dist/docs/ and remote llms.txt at https://mastra.ai/llms.txt
- Covers setup, troubleshooting, and migrations for building AI-powered applications and agents with modern TypeScript
Mastra by the numbers
- 27,112 all-time installs (skills.sh)
- +914 installs in the week ending Aug 5, 2026 (Skillselion tracking)
- Ranked #47 of 16,546 AI & Agent Building skills by installs in the Skillselion catalog
- Security screen: MEDIUM risk (skills.sh audit)
- Data as of Aug 5, 2026 (Skillselion catalog sync)
mastra capabilities & compatibility
- Works with
- anthropic
- Use cases
- api development
npx skills add https://github.com/mastra-ai/skills --skill mastraAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 27.1k |
|---|---|
| repo stars | ★ 71 |
| Security audit | 2 / 3 scanners passed |
| Last updated | July 30, 2026 |
| Repository | mastra-ai/skills ↗ |
How do you fix common Mastra agent build errors?
Building AI agents and LLM-powered applications with the Mastra framework's TypeScript stack.
Who is it for?
Developers building Mastra agents or workflows who encounter module resolution, import syntax, or Studio configuration errors during development.
Skip if: Developers not using the Mastra framework or teams seeking general TypeScript linting unrelated to Mastra agent architecture.
When should I use this skill?
The user hits Mastra build errors, import failures, or runtime agent issues and needs troubleshooting steps or Mastra Studio debugging guidance.
What you get
Resolved module imports, corrected tsconfig settings, and verified agent behavior in Mastra Studio logs.
- resolved import errors
- corrected tsconfig
- verified Studio agent logs
By the numbers
- Mastra Studio runs at http://localhost:4111 after npm run dev
Files
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 Question | First Check | How To |
|---|---|---|
| Create/install Mastra project | `references/create-mastra.md` | Setup guide with CLI and manual steps |
| Choose Agent/Workflow/Tool/Memory/Storage | `references/core-concepts.md` | Core concepts and when to use each primitive |
| How do I use Agent/Workflow/Tool? | `references/embedded-docs.md` | Look up in node_modules/@mastra/*/dist/docs/ |
| How do I use X? (no packages) | `references/remote-docs.md` | Fetch from https://mastra.ai/llms.txt |
| Choose or validate a model | `references/model-selection.md` | Model format and provider registry lookup |
| I'm getting an error... | `references/common-errors.md` | Common errors and solutions |
| Upgrade from v0.x to v1.x | `references/migration-guide.md` | Version upgrade workflows |
| Inspect/call server resources via CLI | `references/mastra-api.md` | mastra api CLI for local, Mastra platform, or remote servers |
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 devThen 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.
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 YCannot find moduleType mismatcherrors- 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. Check whether Mastra packages are installed 2. Look up current API
- If installed: Use embedded docs `references/embedded-docs.md`
- If not: Use remote docs `references/remote-docs.md`
3. Write code based on current docs 4. Test with the project scripts or Studio when available
Common errors and troubleshooting
Comprehensive guide to common Mastra errors and their solutions.
Quickstart
In a lot of cases, debugging errors can be greatly simplified by first checking the behavior in Mastra Studio. This allows you to interactively test agents and workflows, inspect logs, and see real-time error messages.
npm run devOpen http://localhost:4111 in your browser to access Mastra Studio.
Build and configuration errors
"Cannot find module" or import errors
Symptoms:
Error: Cannot find module '@mastra/core'
SyntaxError: Cannot use import statement outside a moduleCauses:
- CommonJS configuration in
tsconfig.json - Missing
"type": "module"inpackage.json - Incorrect module resolution
Solutions:
1. Update tsconfig.json:
{
"compilerOptions": {
"target": "ES2022",
"module": "ES2022",
"moduleResolution": "bundler"
}
}2. Add to package.json:
{
"type": "module"
}3. Ensure imports use .js extensions for local files (if needed by your bundler)
"Property X does not exist on type Y"
Symptoms:
Property 'tools' does not exist on type 'Agent'
Property 'memory' does not exist on type 'AgentConfig'Causes:
- Outdated API usage (Mastra is actively developed)
- Incorrect import or type
- Version mismatch between docs and installed package
Solutions:
1. Check embedded docs (see embedded-docs.md) to check current API 2. Check node_modules/@mastra/core/dist/docs/assets/SOURCE_MAP.json for current exports 3. Verify package versions: npm list @mastra/core 4. Update dependencies: npm update @mastra/core
Agent errors
Agent not using assigned tools
Symptoms:
- Agent responds "I don't have access to that tool"
- Tools never get called despite being relevant
Causes:
- Tools not registered in Mastra instance
- Tools not passed to Agent constructor
- Tool IDs don't match
Solutions:
Correct pattern:
// 1. Create tool
const weatherTool = createTool({
id: "get-weather",
// ... tool config
});
// 2. Register in Mastra instance
const mastra = new Mastra({
tools: {
weatherTool, // or 'weatherTool': weatherTool
},
});
// 3. Assign to agent
const agent = new Agent({
id: "weather-agent",
tools: { weatherTool }, // Reference the tool
// ... other config
});Alternative pattern (direct assignment):
const agent = new Agent({
id: "weather-agent",
tools: {
weatherTool: createTool({ id: "get-weather" /* ... */ }),
},
});Agent memory not persisting
Symptoms:
- Agent doesn't remember previous messages
- Conversation history is lost between calls
Causes:
- No storage backend configured
- Missing or inconsistent
threadId - Memory not assigned to agent
Solutions:
// 1. Configure storage
const storage = new PostgresStore({
connectionString: process.env.DATABASE_URL,
});
// 2. Create memory with storage
const memory = new Memory({
id: "chat-memory",
storage,
options: {
lastMessages: 10, // How many messages to retrieve
},
});
// 3. Assign memory to agent
const agent = new Agent({
id: "chat-agent",
memory,
});
// 4. Use consistent threadId
await agent.generate("Hello", {
threadId: "user-123-conversation", // Same threadId for entire conversation
resourceId: "user-123",
});Workflow errors
"Cannot read property 'then' of undefined"
Symptoms:
TypeError: Cannot read property 'then' of undefined
Workflow execution fails immediatelyCauses:
- Forgot to call
.commit()on workflow - Step returns undefined
Solutions:
Correct pattern:
const workflow = createWorkflow({
id: "my-workflow",
inputSchema: z.object({ data: z.string() }),
outputSchema: z.object({ result: z.string() }),
})
.then(step1)
.then(step2)
.commit(); // REQUIRED!
// Then execute
const run = await workflow.createRun();
const result = await run.start({ inputData: { data: "test" } });Workflow state not updating
Symptoms:
- State changes don't persist across steps
getStepResult()returns undefined
Causes:
- Not using
setStateto update state - Accessing state before step completes
Solutions:
const step1 = createStep({
id: "step1",
execute: async ({ state, setState }) => {
// Update state
await setState({ ...state, counter: (state.counter || 0) + 1 });
return { result: "done" };
},
});
// Access state in subsequent steps
const step2 = createStep({
id: "step2",
execute: async ({ state }) => {
console.log(state.counter); // Access updated state
return { result: "complete" };
},
});Memory errors
"Storage is required for Memory"
Symptoms:
Error: Storage is required for Memory
Memory instantiation failsCauses:
- Memory created without storage backend
Solutions:
// Always provide storage when creating Memory
const memory = new Memory({
id: "my-memory",
storage: postgresStore, // REQUIRED
options: {
lastMessages: 10,
},
});Semantic recall not working
Symptoms:
- Memory doesn't retrieve semantically similar messages
- Only recent messages are returned
Causes:
- No vector store configured
- No embedder configured
semanticRecallnot enabled
Solutions:
const memory = new Memory({
id: "semantic-memory",
storage: postgresStore,
vector: chromaVectorStore, // REQUIRED for semantic recall
embedder: openaiEmbedder, // REQUIRED for semantic recall
options: {
lastMessages: 10,
semanticRecall: true, // REQUIRED
},
});Tool errors
"Tool validation failed"
Symptoms:
Error: Input validation failed for tool 'my-tool'
ZodError: Expected string, received numberCauses:
- Input doesn't match inputSchema
- Missing required fields
- Type mismatch
Solutions:
const tool = createTool({
id: "my-tool",
inputSchema: z.object({
name: z.string(),
age: z.number().optional(), // Make optional fields explicit
}),
execute: async (input) => {
// input is validated and typed
return { result: `Hello ${input.name}` };
},
});
// Correct usage
await tool.execute({ name: "Alice" }); // Works
await tool.execute({ name: "Bob", age: 30 }); // Works
await tool.execute({ age: 30 }); // ERROR: name is requiredTool suspension not resuming
Symptoms:
- Tool suspends but never resumes
- resumeData is undefined
Causes:
- Not calling workflow.resume() or agent.generate() with resumeData
- Incorrect resumeSchema
Solutions:
const approvalTool = createTool({
id: "approval",
inputSchema: z.object({ request: z.string() }),
outputSchema: z.object({ approved: z.boolean() }),
suspendSchema: z.object({ requestId: z.string() }),
resumeSchema: z.object({ approved: z.boolean() }),
execute: async (input, context) => {
if (!context.resumeData) {
// First call - suspend
const requestId = generateId();
context.suspend({ requestId });
return; // Execution pauses here
}
// Resumed - use resumeData
return { approved: context.resumeData.approved };
},
});
// Resume the workflow/agent
await run.resume({
resumeData: { approved: true },
});Storage errors
"Connection refused" or "Database does not exist"
Symptoms:
Error: connect ECONNREFUSED 127.0.0.1:5432
Error: database "mastra" does not existCauses:
- Database not running
- Incorrect connection string
- Database not created
Solutions:
1. Start database (Postgres example):
docker run -d \
--name mastra-postgres \
-e POSTGRES_PASSWORD=password \
-e POSTGRES_DB=mastra \
-p 5432:5432 \
postgres:162. Verify connection string:
DATABASE_URL=postgresql://postgres:password@localhost:5432/mastra3. Initialize storage:
const storage = new PostgresStore({
connectionString: process.env.DATABASE_URL,
});
await storage.init(); // Creates tables if neededEnvironment variable errors
"API key not found"
Symptoms:
Error: OPENAI_API_KEY environment variable is not set
401 UnauthorizedCauses:
- Missing .env file
- Environment variables not loaded
- Incorrect variable name
Solutions:
1. Create .env file:
OPENAI_API_KEY=sk-...
ANTHROPIC_API_KEY=sk-ant-...
GOOGLE_GENERATIVE_AI_API_KEY=...2. Load environment variables (for Node.js):
import "dotenv/config"; // At top of entry file3. Verify variable is loaded:
if (!process.env.OPENAI_API_KEY) {
throw new Error("OPENAI_API_KEY is required");
}Model errors
"Model not found" or "Invalid model"
Symptoms:
Error: Model 'gpt-4' not found
Error: Invalid model formatCauses:
- Incorrect model format (should be
provider/model) - Unsupported model
- Missing provider API key
Solutions:
Correct model format:
const agent = new Agent({
model: "openai/gpt-5.4", // ✅ Correct
// NOT: model: 'gpt-5.4' // ❌ Missing provider
});Common models:
- OpenAI:
openai/gpt-5.4,openai/gpt-5-mini - Anthropic:
anthropic/claude-sonnet-4-5,anthropic/claude-haiku-4-5,anthropic/claude-opus-4-6 - Google:
google/gemini-2.5-pro,google/gemini-2.5-flash
Use embedded docs to verify:
# Check supported models
ls node_modules/@mastra/core/dist/docs/
# See embedded-docs.md for lookup instructionsDebugging tips
Enable verbose logging
const mastra = new Mastra({
logger: new PinoLogger({
name: "mastra",
level: "debug", // or 'trace' for even more detail
}),
});Check package versions
npm list @mastra/core
npm list @mastra/memory
npm list @mastra/ragValidate TypeScript config
npx tsc --showConfig
# Verify target: ES2022, module: ES2022Getting help
1. Check embedded docs: Check embedded docs (see embedded-docs.md) 2. Search documentation: mastra.ai/docs 3. Check version compatibility: Ensure all @mastra packages are same version 4. File an issue: github.com/mastra-ai/mastra
Core Concepts Reference
Use this reference when deciding which Mastra primitive to use or when explaining the high-level shape of a Mastra application.
Agents vs workflows
Agent: Autonomous, makes decisions, uses tools. Use for open-ended tasks such as support, research, analysis, and tool-using assistants.
Workflow: Structured sequence of steps. Use for defined processes such as pipelines, approvals, ETL, multi-step business logic, and resumable processes.
Key components
- Tools: Extend agent capabilities through APIs, databases, external services, and deterministic functions.
- Memory: Maintain context through message history, working memory, semantic recall, and observational memory.
- Storage: Persist data with providers such as Postgres, LibSQL, and MongoDB.
Create Mastra Reference
Complete guide for creating new Mastra projects. Includes both quickstart CLI method and detailed manual installation.
Official documentation: [mastra.ai/docs](https://mastra.ai/docs)
Get started
Ask: "How would you like to create your Mastra project?"
1. Quick Setup: Copy and run: npm create mastra@latest 2. Guided Setup: I walk you through each step, you approve commands 3. Automatic Setup: I create everything, just give me your API key
For AI agents: The CLI is interactive. Use Automatic Setup to create files using the steps in "Automatic Setup / Manual Installation" below.
Prerequisites
- An API key from a supported model provider (OpenAI, Anthropic, Google, etc.)
Quick Setup (user runs CLI)
Create a new Mastra project with one command:
npm create mastra@latestOther package managers:
pnpm create mastra@latest
yarn create mastra@latest
bun create mastra@latestCLI flags
Skip the example agent:
npm create mastra@latest --no-exampleUse a specific template:
npm create mastra@latest --template <template-name>Automatic setup / manual installation
Use this for automatic setup (AI creates all files) or when you prefer manual control.
Follow these steps to create a complete Mastra project:
Step 1: Create project directory
mkdir my-first-agent && cd my-first-agent
npm init -yStep 2: Install dependencies
npm install -D typescript @types/node mastra@latest
npm install @mastra/core@latest zod@^4Step 3: Configure package scripts
Add to package.json:
{
"scripts": {
"dev": "mastra dev",
"build": "mastra build"
}
}Step 4: Configure TypeScript
Create tsconfig.json:
{
"compilerOptions": {
"target": "ES2022",
"module": "ES2022",
"moduleResolution": "bundler",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true,
"noEmit": true,
"outDir": "dist"
},
"include": ["src/**/*"]
}Important: Mastra requires "module": "ES2022" and "moduleResolution": "bundler". CommonJS will cause errors.
Step 5: Create environment file
Create .env with your API key:
GOOGLE_GENERATIVE_AI_API_KEY=<your-api-key>Or use OPENAI_API_KEY, ANTHROPIC_API_KEY, etc.
Step 6: Create weather tool
Create src/mastra/tools/weather-tool.ts:
import { createTool } from "@mastra/core/tools";
import { z } from "zod";
export const weatherTool = createTool({
id: "get-weather",
description: "Get current weather for a location",
inputSchema: z.object({
location: z.string().describe("City name"),
}),
outputSchema: z.object({
output: z.string(),
}),
execute: async () => {
return { output: "The weather is sunny" };
},
});Step 7: Create weather agent
Create src/mastra/agents/weather-agent.ts:
import { Agent } from "@mastra/core/agent";
import { weatherTool } from "../tools/weather-tool";
export const weatherAgent = new Agent({
id: "weather-agent",
name: "Weather Agent",
instructions: `
You are a helpful weather assistant that provides accurate weather information.
Your primary function is to help users get weather details for specific locations. When responding:
- Always ask for a location if none is provided
- If the location name isn't in English, please translate it
- If giving a location with multiple parts (e.g. "New York, NY"), use the most relevant part (e.g. "New York")
- Include relevant details like humidity, wind conditions, and precipitation
- Keep responses concise but informative
Use the weatherTool to fetch current weather data.
`,
model: "google/gemini-2.5-pro",
tools: { weatherTool },
});Note: Model format is "provider/model-name". Examples:
"google/gemini-2.5-pro""openai/gpt-5.4""anthropic/claude-sonnet-4-5"
Step 8: Create mastra entry point
Create src/mastra/index.ts:
import { Mastra } from "@mastra/core";
import { weatherAgent } from "./agents/weather-agent";
export const mastra = new Mastra({
agents: { weatherAgent },
});Step 9: Launch Mastra Studio
Launch the development server:
npm run devAccess Studio at http://localhost:4111 to test your agent.
Next steps
After creating your project with create mastra:
- Customize the example agent in
src/mastra/agents/weather-agent.ts - Add new agents - see Agents documentation
- Create workflows - see Workflows documentation
- Add more tools to extend agent capabilities
- Integrate into your app - see framework guides at mastra.ai/docs
Troubleshooting
| Issue | Solution |
|---|---|
| API key not found | Make sure your .env file has the correct key |
| Studio won't start | Check that port 4111 is available |
| CommonJS errors | Ensure tsconfig.json uses "module": "ES2022" and "moduleResolution": "bundler" |
| Command not found | Ensure you're using Node.js 20+ |
Resources
Embedded Docs Reference
Look up API signatures from embedded docs in node_modules/@mastra/*/dist/docs/ - these match the installed version.
Use this FIRST when Mastra packages are installed locally. Embedded docs are always accurate for the installed version.
Why use embedded docs
- Version accuracy: Embedded docs match the exact installed version
- No network required: All docs are local in
node_modules/ - Mastra evolves quickly: APIs change rapidly, embedded docs stay in sync
- TypeScript definitions: Includes JSDoc, type signatures, and examples
- Training data may be outdated: Claude's knowledge cutoff may not reflect latest APIs
Documentation structure
node_modules/@mastra/core/dist/docs/
├── SKILL.md # Package overview, exports
├── assets/
│ └── SOURCE_MAP.json # Export -> file mappings
└── references/ # Individual topic docsLookup process
1. Check if packages are installed
ls node_modules/@mastra/If you see packages like core, memory, rag, etc., proceed with embedded docs lookup.
2. Look through topic docs
Use grep to find relevant docs in references/:
grep -r "Agent" node_modules/@mastra/core/dist/docs/referencesNaming convention
Documents are typically formatted as <category>-<topic>.md where category is one of: "docs", "reference", "guides", "models".
Optional: Check source code for type definitions / additional details
Look at the SOURCE_MAP.json to find the file path for the export:
cat node_modules/@mastra/core/dist/docs/assets/SOURCE_MAP.json | grep '"Agent"'Returns: { "Agent": { "types": "dist/agent/agent.d.ts", ... } }
Read the type definition for exact constructor parameters, types, and JSDoc:
cat node_modules/@mastra/core/dist/agent/agent.d.tsCommon packages
| Package | Path | Contains |
|---|---|---|
@mastra/core | node_modules/@mastra/core/dist/docs/ | Agents, Workflows, Tools, Mastra instance |
@mastra/memory | node_modules/@mastra/memory/dist/docs/ | Memory systems, conversation history |
@mastra/rag | node_modules/@mastra/rag/dist/docs/ | RAG features, vector stores |
@mastra/pg | node_modules/@mastra/pg/dist/docs/ | PostgreSQL storage |
@mastra/libsql | node_modules/@mastra/libsql/dist/docs/ | LibSQL/SQLite storage |
Quick commands reference
# List installed @mastra packages
ls node_modules/@mastra/
# List available topic documentation
ls node_modules/@mastra/core/dist/docs/references/
# Find specific export in SOURCE_MAP
cat node_modules/@mastra/core/dist/docs/assets/SOURCE_MAP.json | grep '"ExportName"'
# Read type definition from path
cat node_modules/@mastra/core/dist/[path-from-source-map]
# View package overview
cat node_modules/@mastra/core/dist/docs/SKILL.mdWhen embedded docs are not available
If packages aren't installed or dist/docs/ doesn't exist:
1. Recommend installation: Suggest installing packages to access embedded docs 2. Fall back to remote docs: See references/remote-docs.md
Best Practices
1. Check topic docs for conceptual understanding and patterns 2. Search source code if docs don't answer the question 3. Verify imports match what's exported in the type definitions
Mastra API CLI Reference
How to use the mastra api CLI to interact with Mastra servers. Prefer fast, focused commands and compact JSON projections. Treat the installed CLI and server schema as the source of truth when discovery is needed.
Use this reference when the user asks to inspect or call agents, workflows, tools, MCP servers, memory threads, traces, logs, metrics, scores, datasets, experiments, or to debug/test mastra api commands.
Setup
The CLI can interact with any reachable Mastra server:
- Local dev server:
http://localhost:4111fromnpm run dev - Mastra platform deployment: Use the deployment URL
- Remote/self-hosted server: Use the server URL
- Hosted Mastra Platform Observability:
https://observability.mastra.ai(auto-targeted bytrace,log,score, andmetriccommands)
For local servers, mastra api defaults to http://localhost:4111:
npx mastra api agent listFor Mastra platform or remote servers, pass --url. For the sake of brevity in examples, $MASTRA_URL is used as a placeholder for the actual server URL which you need to set yourself:
npx mastra api --url $MASTRA_URL agent listVerify the server once with a cheap check before resource calls:
MASTRA_URL="${MASTRA_URL:-http://localhost:4111}"
curl -fsS "$MASTRA_URL/api/system/api-schema" >/dev/nullIf $MASTRA_URL is not reachable, the user may be using a Mastra platform deployment or remote URL. Ask for the correct server URL and set --url accordingly. If authentication is required, ask the user for the necessary token or credentials and set them in the environment for subsequent commands.
For authenticated servers, pass repeatable headers:
npx mastra api --url "$MASTRA_URL" --header "Authorization: Bearer $TOKEN" agent listTarget resolution
Runtime commands (agent, workflow, tool, mcp, thread, memory, dataset, experiment) resolve the target 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.
Observability commands (trace, log, score, metric) target https://observability.mastra.ai by default instead of a project deployment URL. The CLI 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 the environment. 3. Project metadata from .mastra-project.json for the project ID. 4. The Mastra CLI login token as an auth fallback.
For observability calls, no --url or --header is required if MASTRA_PLATFORM_ACCESS_TOKEN and MASTRA_PROJECT_ID are set, or if .mastra-project.json is present:
npx mastra api trace list '{"page":0,"perPage":10}'
npx mastra api metric namesPass --url and --header only when overriding the hosted observability target or credentials.
Decision flow
1. Clear read-only request (list X, latest X, get X, summarize recent X): infer the resource and use the fast path first. 2. Mutating request (create, update, delete, run, resume, execute), unclear resource/action, failed fast path, or exact syntax requested: use narrow CLI discovery. 3. JSON input uncertain: use command-specific --schema. 4. Route behavior confusing: inspect /api/system/api-schema.
Start with these command groups when present; verify with mastra api --help if the group fails.
agent workflow tool mcp thread memory trace log metric score dataset experimentFast path for read-only requests
Use conventional list/get commands first. Keep pages small and pipe through jq immediately.
Latest item:
npx mastra api <resource> list '{"page":0,"perPage":1}' \
| jq '.data[0]'Recent items:
npx mastra api <resource> list '{"page":0,"perPage":10}' \
| jq '.data[]'When the shape is known, project only the fields needed for the task:
npx mastra api <resource> list '{"page":0,"perPage":10}' \
| jq '.data[] | {id, name, createdAt, status}'Get details:
npx mastra api <resource> get <id> \
| jq '.data'When the shape is known, project only the fields needed for the task:
npx mastra api <resource> get <id> \
| jq '.data | {id, name, createdAt, status}'If a resource does not support the conventional shape, fall back to narrow --help for that resource/action.
Output control
- Do not use unfiltered
--prettyduring exploration. - Always project list/get output with
jqbefore reading details. - Use
perPage:1for latest andperPage:10or less for recent lists. - If output is truncated or noisy, rerun with a narrower
jqprojection. Do not increase terminal output just to see more raw JSON. - Fetch full JSON only when the user asks for raw output or compact projections are insufficient.
Fallback discovery
Use the narrowest discovery command that can answer the question. Example for traces:
npx mastra api trace --help
npx mastra api trace list --help
npx mastra api trace list --schemaUse top-level help only when the resource is unknown:
npx mastra api --helpRead --schema output as the contract:
command: usage stringexamples: known-good examplespositionals: required path/identity argumentsinput.required: whether JSON input is requiredinput.schema: accepted CLI JSON input, including query/body fieldsschemas: raw server route schemas for deeper debugging
JSON and output contract
mastra api accepts at most one inline JSON object as input. Do not use stdin or files unless the user explicitly asks.
For non-GET routes, the CLI splits the one JSON object into query parameters and request body according to the server route schema.
Output envelopes:
{ "data": {} }
{ "data": [], "page": { "total": 0, "page": 0, "perPage": 0, "hasMore": false } }
{ "error": { "code": "...", "message": "...", "details": {} } }Error handling
INVALID_JSON: fix shell quoting; input must be one JSON object.MISSING_INPUT: run the same command with--schemaand supply required JSON.MISSING_ARGUMENT: provide the positional shown by--help/--schema.HTTP_ERROR: inspecterror.details, then compare against--schemaor route schema.REQUEST_TIMEOUT: retry with larger--timeout, especially for workflow execution.SERVER_UNREACHABLE: verify the URL and the server check. If localhost is not running, ask whether the user wants to use a Mastra platform deployment or another remote server URL.
Route-level debugging
If CLI behavior seems wrong, inspect the route-derived schema manifest instead of guessing.
Find routes by path:
curl -fsS "$MASTRA_URL/api/system/api-schema" \
| jq '.routes[] | select(.path | contains("/memory"))'Inspect one route:
curl -fsS "$MASTRA_URL/api/system/api-schema" \
| jq '.routes[] | select(.method == "POST" and .path == "/tools/:toolId/execute") | {pathParamSchema, queryParamSchema, bodySchema, responseShape}'Known notes
- Tool and MCP tool execution accept raw tool input; explicit
{ "data": ... }also works. - Workflow resume only works for suspended workflow runs.
- Working memory update requires the agent's memory to have working memory enabled.
- Empty lists may simply mean the server has no matching stored data yet.
trace listandtrace getreturn lightweight payloads by default (no span input, output, attributes, or metadata). Pass--verboseto fetch full span records, or usetrace span <traceId> <spanId>to fetch one specific span in full.
Migration Guide
Guide for upgrading Mastra versions using official documentation and current API verification.
Migration strategy
For version upgrades, follow this process:
1. Check official migration docs
Always start with the official migration documentation: https://mastra.ai/llms.txt
Look for the Migrations or Guides section, which will have:
- Breaking changes for each version
- Automated migration tools
- Step-by-step upgrade instructions
Example sections to look for:
/guides/migrations/upgrade-to-v1//guides/migrations/upgrade-to-v2/- Breaking changes lists
2. Use embedded docs for current APIs
After identifying breaking changes, verify the new APIs:
Check your installed version:
cat node_modules/@mastra/core/dist/docs/assets/SOURCE_MAP.json | grep '"ApiName"'
cat node_modules/@mastra/core/dist/[path-from-source-map]See `embedded-docs.md` for detailed lookup instructions.
3. Use remote docs for latest info
If packages aren't updated yet, check what APIs will look like: https://mastra.ai/reference/[topic]
See `remote-docs.md` for detailed lookup instructions.
Quick migration workflow
# 1. Check current version
npm list @mastra/core
# 2. Fetch migration guide from official docs
# Use WebFetch: https://mastra.ai/llms.txt
# Find relevant migration section
# 3. Update dependencies
npm install @mastra/core@latest @mastra/memory@latest @mastra/rag@latest mastra@latest
# 4. Run automated migration (if available)
npx @mastra/codemod@latest v1 # or whatever version
# 5. Check embedded docs for new APIs
cat node_modules/@mastra/core/dist/docs/assets/SOURCE_MAP.json
# 6. Fix breaking changes using embedded docs lookup
# See embedded-docs.md for how to look up each API
# 7. Test
npm run dev
npm testCommon migration patterns
Finding what changed
Check official migration docs: https://mastra.ai/guides/migrations/upgrade-to-v1/overview.md
This will list:
- Breaking changes
- Deprecated APIs
- New features
- Migration tools
Updating API usage
For each breaking change:
1. Find the old API in your code 2. Look up the new API using embedded docs:
cat node_modules/@mastra/core/dist/docs/assets/SOURCE_MAP.json | grep '"NewApi"'
cat node_modules/@mastra/core/dist/[path]3. Update your code based on the type signatures 4. Test the change
Example: Tool execute signature change
Official docs say: "Tool execute signature changed"
Look up current signature:
cat node_modules/@mastra/core/dist/docs/assets/SOURCE_MAP.json | grep '"createTool"'
cat node_modules/@mastra/core/dist/tools/tool.d.tsUpdate based on type definition:
// Old (from docs)
execute: async (input) => { ... }
// New (from embedded docs)
execute: async (inputData, context) => { ... }Pre-migration checklist
- [ ] Backup code (git commit)
- [ ] Check official migration docs:
https://mastra.ai/llms.txt - [ ] Note current version:
npm list @mastra/core - [ ] Read breaking changes list
- [ ] Tests are passing
Post-migration checklist
- [ ] All dependencies updated together
- [ ] TypeScript compiles:
npx tsc --noEmit - [ ] Tests pass:
npm test - [ ] Studio works:
npm run dev - [ ] No console warnings
- [ ] APIs verified against embedded docs
Migration resources
| Resource | Use For |
|---|---|
https://mastra.ai/llms.txt | Finding migration guides and breaking changes |
| `embedded-docs.md` | Looking up new API signatures after updating |
| `remote-docs.md` | Checking latest docs before updating |
| `common-errors.md` | Fixing migration errors |
Version-specific notes
General principles
1. Always update all @mastra packages together
npm install @mastra/core@latest @mastra/memory@latest @mastra/rag@latest mastra@latest2. Check for automated migration tools
npx @mastra/codemod@latest [version]3. Verify Node.js version requirements
- Check official migration docs for minimum Node version
4. Run database migrations if using storage
- Follow storage migration guide in official docs
Getting help
1. Check official migration docs: https://mastra.ai/llms.txt → Migrations section 2. Look up new APIs: See `embedded-docs.md` 3. Check for errors: See `common-errors.md` 4. Ask in Discord: https://discord.gg/BTYqqHKUrf 5. File issues: https://github.com/mastra-ai/mastra/issues
Key principles
1. Official docs are source of truth - Start with https://mastra.ai/llms.txt 2. Verify with embedded docs - Check installed version APIs 3. Update incrementally - Don't skip major versions 4. Test thoroughly - Run tests after each change 5. Use automation - Use codemods when available
Model Selection Reference
Use this reference when choosing or validating Mastra model strings.
Model format
Always use "provider/model-name" when defining models with Mastra's model router.
Verify provider keys and model names
Use the provider registry script to look up available providers and models:
# List all available providers
node scripts/provider-registry.mjs --list
# List all models for a specific provider, sorted newest first
node scripts/provider-registry.mjs --provider openai
node scripts/provider-registry.mjs --provider anthropicWhen the user asks to use a model or provider, run the script first to verify the provider key and model name are valid. Do not guess model names from memory because they change frequently.
If you need examples in a new-project scaffold, see `create-mastra.md`, then verify the chosen model with the provider registry script.
Remote Docs Reference
How to look up current documentation from https://mastra.ai when local packages aren't available or you need conceptual guidance.
Use this when:
- Mastra packages aren't installed locally
- You need conceptual explanations or guides
- You want the latest documentation (may be ahead of installed version)
Documentation site structure
Mastra docs are organized at https://mastra.ai:
- Docs: Core documentation covering concepts, features, and implementation details
- Models: Mastra provides a unified interface for working with LLMs across multiple providers
- Guides: Step-by-step tutorials for building specific applications
- Reference: API reference documentation
Finding relevant documentation
Method 1: Use llms.txt (Recommended)
The main llms.txt file provides an agent-friendly overview of all documentation: https://mastra.ai/llms.txt
This returns a structured markdown document with:
- Documentation organization and hierarchy
- All available topics and sections
- Direct links to relevant documentation
- Agent-optimized content structure
Use this first to understand what documentation is available and where to find specific topics.
Method 2: Direct URL patterns
Documentation follows predictable URL patterns:
- Overview pages:
https://mastra.ai/docs/{topic}/overview - API reference:
https://mastra.ai/reference/{topic}/ - Guides:
https://mastra.ai/guides/{topic}/
Examples:
https://mastra.ai/docs/agents/overviewhttps://mastra.ai/docs/workflows/overviewhttps://mastra.ai/reference/workflows/workflow-methods/
Agent-friendly documentation
Critical feature: Send the text-markdown request header or add .md to any documentation URL to get clean, agent-friendly markdown.
Standard URL:
https://mastra.ai/reference/workflows/workflow-methods/thenAgent-friendly URL (Markdown):
https://mastra.ai/reference/workflows/workflow-methods/then.mdThe .md version:
- Removes navigation, headers, footers
- Returns pure markdown content
- Optimized for LLM consumption
- Includes all code examples and explanations
Lookup Workflow
1. Check the main documentation index
Start here to understand what's available:
https://mastra.ai/llms.txtThis provides:
- Complete documentation structure
- Available topics and sections
- Links to relevant documentation pages
2. Find relevant documentation
Option A: Use information from llms.txt The main llms.txt will guide you to the right section.
Option B: Construct URL directly
https://mastra.ai/docs/{topic}/overview
https://mastra.ai/reference/{topic}/3. Fetch agent-friendly version
Add .md to the end of any documentation URL:
https://mastra.ai/reference/workflows/workflow-methods/then.md4. Extract relevant information
The markdown will include:
- Function signatures
- Parameter descriptions
- Return types
- Usage examples
- Best practices
Common documentation paths
Agents
- Overview:
https://mastra.ai/docs/agents/overview - Creating agents:
https://mastra.ai/docs/agents/creating-agents - Agent tools:
https://mastra.ai/docs/agents/tools - Memory:
https://mastra.ai/docs/agents/memory
Workflows
- Overview:
https://mastra.ai/docs/workflows/overview - Creating workflows:
https://mastra.ai/docs/workflows/creating-workflows - Workflow methods:
https://mastra.ai/reference/workflows/workflow-methods/
Tools
- Overview:
https://mastra.ai/docs/tools/overview - Creating tools:
https://mastra.ai/docs/tools/creating-tools
Memory
- Overview:
https://mastra.ai/docs/memory/overview - Configuration:
https://mastra.ai/docs/memory/configuration
RAG
- Overview:
https://mastra.ai/docs/rag/overview - Vector stores:
https://mastra.ai/docs/rag/vector-stores
Example: Looking up workflow .then() method
1. Check main documentation index
WebFetch({
url: "https://mastra.ai/llms.txt",
prompt: "Where can I find documentation about workflow methods like .then()?"
})This will point you to the workflows reference section.
2. Fetch specific method documentation
https://mastra.ai/reference/workflows/workflow-methods/then.md3. Use WebFetch tool
WebFetch({
url: "https://mastra.ai/reference/workflows/workflow-methods/then.md",
prompt: "What are the parameters for the .then() method and how do I use it?"
})When to use remote vs embedded docs
| Situation | Use |
|---|---|
| Packages installed locally | Embedded docs (guaranteed version match) |
| Packages not installed | Remote docs |
| Need conceptual guides | Remote docs |
| Need exact API signatures | Embedded docs (if available) |
| Exploring new features | Remote docs (may be ahead of installed version) |
| Need working examples | Both (embedded for types, remote for guides) |
Best practices
1. Always use .md for fetching documentation 2. Check sitemap.xml when unsure about URL structure 3. Prefer embedded docs when packages are installed (version accuracy) 4. Use remote docs for conceptual understanding and guides 5. Combine both for comprehensive understanding
#!/usr/bin/env node
import { readFileSync } from "node:fs";
import { join, dirname } from "node:path";
import { fileURLToPath } from "node:url";
const __dirname = dirname(fileURLToPath(import.meta.url));
function findRegistryPath() {
const rel = join('node_modules', '@mastra', 'core', 'dist', 'provider-registry.json');
// Walk up from script location to find project root with node_modules
let dir = __dirname;
for (let i = 0; i < 10; i++) {
try {
const p = join(dir, rel);
readFileSync(p, "utf-8");
return p;
} catch {
dir = dirname(dir);
}
}
// Fall back to cwd
return join(process.cwd(), rel);
}
function loadRegistry() {
const path = findRegistryPath();
try {
return JSON.parse(readFileSync(path, "utf-8"));
} catch (e) {
console.error(`Error: Could not load provider registry at ${path}`);
console.error(e.message);
process.exit(1);
}
}
/**
* Extract version numbers from a model name for sorting.
* Returns an array of numeric segments, e.g. "gpt-5.4" → [5, 4].
* Handles dot-separated (3.5), hyphen-separated (3-7), and mixed formats.
* Models without detectable version numbers return null.
*/
function extractVersion(name) {
// Use named capture to grab version-like sequences along with their context.
// We capture digits separated by dots/hyphens, plus any trailing letter for filtering.
const regex = /(\d+(?:[.\-]\d+)*)([a-zA-Z])?/g;
const candidates = [];
let match;
while ((match = regex.exec(name)) !== null) {
const numStr = match[1];
const suffix = match[2] || "";
candidates.push({ numStr, suffix, index: match.index });
}
if (candidates.length === 0) return null;
// Process candidates: filter and clean up non-version parts
const processed = [];
for (const c of candidates) {
let parts = c.numStr.split(/[.\-]/).map(Number);
// If followed by a size suffix (b/B/k/K/m/M/t/T) — e.g. "8b", "70B", "1t" —
// strip the last numeric part (param count) but keep earlier parts as the version
if (/^[bBkKmMtT]$/.test(c.suffix)) {
parts = parts.slice(0, -1);
if (parts.length === 0) continue;
}
// Strip date-like segments (>= 2020 or YYYYMMDD-style 8-digit numbers)
parts = parts.filter((p) => p < 2020);
if (parts.length === 0) continue;
// Skip very large standalone numbers (parameter counts, IDs)
if (parts.length === 1 && parts[0] >= 100 && candidates.length > 1) continue;
// Skip trailing date-like patterns (MM-DD) in the latter half of the name
if (
parts.length === 2 &&
parts[0] >= 1 && parts[0] <= 12 &&
parts[1] >= 1 && parts[1] <= 31 &&
c.index > name.length / 2 &&
candidates.length > 1
) continue;
processed.push(parts);
}
if (processed.length === 0) return null;
// Return the first valid version candidate (versions appear early in model names)
return processed[0];
}
function compareVersionsDesc(a, b) {
const va = extractVersion(a);
const vb = extractVersion(b);
// Models without versions go to the end
if (!va && !vb) return a.localeCompare(b);
if (!va) return 1;
if (!vb) return -1;
// Compare version tuples numerically, descending
const len = Math.max(va.length, vb.length);
for (let i = 0; i < len; i++) {
const ai = va[i] ?? 0;
const bi = vb[i] ?? 0;
if (bi !== ai) return bi - ai;
}
// Same version — secondary sort by full name descending
return b.localeCompare(a);
}
function printUsage() {
console.log(`Usage: provider-registry.mjs [options]
Options:
--list List all available model providers
--provider <name> List all models for a provider (sorted newest first)
--help Show this help message
Examples:
node provider-registry.mjs --list
node provider-registry.mjs --provider openai
node provider-registry.mjs --provider anthropic`);
}
function listProviders(registry) {
const entries = Object.entries(registry.providers)
.map(([key, val]) => ({ key, name: val.name || key }))
.sort((a, b) => a.key.localeCompare(b.key));
const maxKey = Math.max(...entries.map((e) => e.key.length));
const maxName = Math.max(...entries.map((e) => e.name.length));
console.log(`${"PROVIDER".padEnd(maxKey)} ${"NAME".padEnd(maxName)} MODELS`);
console.log(`${"─".repeat(maxKey)} ${"─".repeat(maxName)} ${"─".repeat(6)}`);
for (const entry of entries) {
const modelCount = registry.providers[entry.key].models.length;
console.log(`${entry.key.padEnd(maxKey)} ${entry.name.padEnd(maxName)} ${modelCount}`);
}
console.log(`\n${entries.length} providers`);
}
function listModels(registry, providerName) {
const provider = registry.providers[providerName];
if (!provider) {
console.error(`Error: Provider "${providerName}" not found.`);
console.error(`Run with --list to see available providers.`);
process.exit(1);
}
const models = [...provider.models].sort(compareVersionsDesc);
console.log(`${provider.name || providerName} — ${models.length} models\n`);
for (const model of models) {
console.log(` ${model}`);
}
}
const args = process.argv.slice(2);
if (args.includes("--help") || args.length === 0) {
printUsage();
process.exit(0);
}
if (args.includes("--list")) {
listProviders(loadRegistry());
process.exit(0);
}
const providerIdx = args.indexOf("--provider");
if (providerIdx !== -1) {
const name = args[providerIdx + 1];
if (!name) {
console.error("Error: --provider requires a provider name.");
process.exit(1);
}
listModels(loadRegistry(), name);
process.exit(0);
}
console.error("Error: Unknown arguments:", args.join(" "));
printUsage();
process.exit(1);
Related skills
How it compares
Use the mastra skill for framework-specific agent errors; use general TypeScript docs for language features unrelated to Mastra Studio or @mastra/core.
FAQ
How do you debug Mastra agents quickly?
The mastra skill recommends running npm run dev and opening Mastra Studio at http://localhost:4111 to interactively test agents, inspect logs, and view real-time error messages before editing configuration or imports.
What causes Mastra module import errors?
The mastra skill identifies CommonJS settings in tsconfig.json and mixed module systems as common causes of '@mastra/core' not-found and ESM import syntax errors. Fixes target build and configuration alignment for Mastra agents and workflows.
Is Mastra safe to install?
skills.sh reports 2 of 3 security scanners passed. Review the Security Audits panel on this page before installing in production.