Subchapter 2.1
references/common-errors.mdMarkdown10 KBView on GitHub
Comprehensive guide to common Mastra errors and their solutions.
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.
Symptoms:
Error: Cannot find module '@mastra/core'
SyntaxError: Cannot use import statement outside a moduleCauses:
tsconfig.json"type": "module" in package.jsonSolutions:
Update tsconfig.json:
{
"compilerOptions": {
"target": "ES2022",
"module": "ES2022",
"moduleResolution": "bundler"
}
}Add to package.json:
{
"type": "module"
}Ensure imports use .js extensions for local files (if needed by your bundler)
Symptoms:
Property 'tools' does not exist on type 'Agent'
Property 'memory' does not exist on type 'AgentConfig'Causes:
Solutions:
embedded-docs.md) to check current APInode_modules/@mastra/core/dist/docs/assets/SOURCE_MAP.json for current exportsnpm list @mastra/corenpm update @mastra/coreSymptoms:
Causes:
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" /* ... */ }),
},
});Symptoms:
Causes:
threadIdSolutions:
// 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",
});Symptoms:
TypeError: Cannot read property 'then' of undefined
Workflow execution fails immediatelyCauses:
.commit() on workflowSolutions:
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" } });Symptoms:
getStepResult() returns undefinedCauses:
setState to update stateSolutions:
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" };
},
});Symptoms:
Error: Storage is required for Memory
Memory instantiation failsCauses:
Solutions:
// Always provide storage when creating Memory
const memory = new Memory({
id: "my-memory",
storage: postgresStore, // REQUIRED
options: {
lastMessages: 10,
},
});Symptoms:
Causes:
semanticRecall not enabledSolutions:
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
},
});Symptoms:
Error: Input validation failed for tool 'my-tool'
ZodError: Expected string, received numberCauses:
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 requiredSymptoms:
Causes:
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 },
});Symptoms:
Error: connect ECONNREFUSED 127.0.0.1:5432
Error: database "mastra" does not existCauses:
Solutions:
docker run -d \
--name mastra-postgres \
-e POSTGRES_PASSWORD=password \
-e POSTGRES_DB=mastra \
-p 5432:5432 \
postgres:16DATABASE_URL=postgresql://postgres:password@localhost:5432/mastraconst storage = new PostgresStore({
connectionString: process.env.DATABASE_URL,
});
await storage.init(); // Creates tables if neededSymptoms:
Error: OPENAI_API_KEY environment variable is not set
401 UnauthorizedCauses:
Solutions:
OPENAI_API_KEY=sk-...
ANTHROPIC_API_KEY=sk-ant-...
GOOGLE_GENERATIVE_AI_API_KEY=...import "dotenv/config"; // At top of entry fileif (!process.env.OPENAI_API_KEY) {
throw new Error("OPENAI_API_KEY is required");
}Symptoms:
Error: Model 'gpt-4' not found
Error: Invalid model formatCauses:
provider/model)Solutions:
Correct model format:
const agent = new Agent({
model: "openai/gpt-5.4", // ✅ Correct
// NOT: model: 'gpt-5.4' // ❌ Missing provider
});Common models:
openai/gpt-5.4, openai/gpt-5-minianthropic/claude-sonnet-4-5, anthropic/claude-haiku-4-5, anthropic/claude-opus-4-6google/gemini-2.5-pro, google/gemini-2.5-flashUse embedded docs to verify:
# Check supported models
ls node_modules/@mastra/core/dist/docs/
# See embedded-docs.md for lookup instructionsconst mastra = new Mastra({
logger: new PinoLogger({
name: "mastra",
level: "debug", // or 'trace' for even more detail
}),
});npm list @mastra/core
npm list @mastra/memory
npm list @mastra/ragnpx tsc --showConfig
# Verify target: ES2022, module: ES2022embedded-docs.md)Source