Index of every page on this site: llms.txt
All skills
mastra-ai avatar

/mastra

@0457401 official
by Mastramastra-ai/skills105 stars
13
Run it yourself

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.

Use this Skill: https://skilld.dev/gh/mastra-ai/skills/mastra

Nothing lands on disk. Nothing to clean up.

Fork this Skill

Edit a local copy. It keeps the author and licence.

referencescommon-errors.md

≈2.6k tokens on demand. Your agent reads this file only when SKILL.md points to it.

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 dev

Open 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 module

Causes:

  • CommonJS configuration in tsconfig.json
  • Missing "type": "module" in package.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 immediately

Causes:

  • 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 setState to 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 fails

Causes:

  • 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
  • semanticRecall not 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 number

Causes:

  • 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 required

Tool 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 exist

Causes:

  • 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:16
  1. Verify connection string:
DATABASE_URL=postgresql://postgres:password@localhost:5432/mastra
  1. Initialize storage:
const storage = new PostgresStore({
  connectionString: process.env.DATABASE_URL,
});
await storage.init(); // Creates tables if needed

Environment variable errors

"API key not found"

Symptoms:

Error: OPENAI_API_KEY environment variable is not set
401 Unauthorized

Causes:

  • 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=...
  1. Load environment variables (for Node.js):
import "dotenv/config"; // At top of entry file
  1. 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 format

Causes:

  • 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 instructions

Debugging 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/rag

Validate TypeScript config

npx tsc --showConfig
# Verify target: ES2022, module: ES2022

Getting 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

Source: SKILL.md on GitHub

skilld matched fixed text patterns in SKILL.md and file names. Patterns miss obfuscated code.

skilld run checks every file with the same patterns. It asks for approval before it loads a Skill with a behavior marked Needs approval.

2 warnings17d5 checks · Risk SAFE
  • Gen Agent Trust Hub18d

    The skill provides a comprehensive guide for the Mastra framework, including documentation lookup, project scaffolding, and CLI interaction. All external resources, including documentation URLs, GitHub repositories, and API endpoints, belong to the official vendor infrastructure. No malicious patterns, obfuscation, or unsafe data handling were detected.

  • Socket17d

    No alerts

  • Snyk18d

    Risk: MEDIUM · 1 issue

  • Runlayer9mo

    3/6 files flagged

  • ZeroLeaks7mo

    Score: 93/100 · 2 sections analyzed

Signed by skilld at 0457401. This ties the file your Agent reads to that commit on GitHub. It does not review the instructions.

Last checked against GitHub 2 weeks ago.

Activeupdated 3 weeks ago
Other metadata
metadata
{
  "author": "Mastra",
  "version": "2.5.0",
  "repository": "https://github.com/mastra-ai/skills"
}

README badge

README badge for mastra-ai/skills/mastra

Provides documentation lookup, API verification, and CLI reference for the Mastra framework—a TypeScript library for building AI agents, workflows, tools, and storage integrations. Use this skill to verify current Mastra APIs, resolve type errors from outdated knowledge, inspect resources via the `mastra api` CLI, and troubleshoot common setup issues like ES2022 module configuration.

Generated from the current SKILL.md.

Does this skill work without Mastra packages installed?
Yes. The skill includes references to remote documentation at mastra.ai/llms.txt for cases where packages aren't installed. If packages are installed, the skill prioritizes embedded docs in node_modules for accuracy.
What should I do if I get a TypeScript error when using Mastra?
Check references/common-errors.md first, then verify the current API in embedded docs or remote docs. Type errors often signal outdated knowledge rather than user mistakes, since Mastra APIs change between versions.
How do I verify a model name or provider is valid?
Run scripts/provider-registry.mjs to look up current providers and models in the model router before using any model. Model names change frequently and should never be guessed from memory.
What does the `mastra api` CLI do?
It inspects or calls resources on local dev servers, Mastra platform deployments, or remote endpoints. Use it to access agent state, execution traces, logs, threads, and workflow operations.
Does Mastra support CommonJS?
No. Mastra requires ES2022 modules and will fail with CommonJS. Verify your tsconfig.json is set up correctly.

Generated from the current SKILL.md. These answers refresh after source changes.