Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Build Mastra AI agents and workflows with guidance on current API lookup, tools, memory, and RAG patterns.
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
references/common-errors.md
1# Common errors and troubleshooting23Comprehensive guide to common Mastra errors and their solutions.45## Quickstart67In 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.89```bash10npm run dev11```1213Open `http://localhost:4111` in your browser to access Mastra Studio.1415## Build and configuration errors1617### "Cannot find module" or import errors1819**Symptoms**:2021```bash22Error: Cannot find module '@mastra/core'23SyntaxError: Cannot use import statement outside a module24```2526**Causes**:2728- CommonJS configuration in `tsconfig.json`29- Missing `"type": "module"` in `package.json`30- Incorrect module resolution3132**Solutions**:33341. Update `tsconfig.json`:3536```json37{38"compilerOptions": {39"target": "ES2022",40"module": "ES2022",41"moduleResolution": "bundler"42}43}44```45462. Add to `package.json`:4748```json49{50"type": "module"51}52```53543. Ensure imports use `.js` extensions for local files (if needed by your bundler)5556### "Property X does not exist on type Y"5758**Symptoms**:5960```bash61Property 'tools' does not exist on type 'Agent'62Property 'memory' does not exist on type 'AgentConfig'63```6465**Causes**:6667- Outdated API usage (Mastra is actively developed)68- Incorrect import or type69- Version mismatch between docs and installed package7071**Solutions**:72731. Check embedded docs (see `embedded-docs.md`) to check current API742. Check `node_modules/@mastra/core/dist/docs/assets/SOURCE_MAP.json` for current exports753. Verify package versions: `npm list @mastra/core`764. Update dependencies: `npm update @mastra/core`7778## Agent errors7980### Agent not using assigned tools8182**Symptoms**:8384- Agent responds "I don't have access to that tool"85- Tools never get called despite being relevant8687**Causes**:8889- Tools not registered in Mastra instance90- Tools not passed to Agent constructor91- Tool IDs don't match9293**Solutions**:9495**Correct pattern**:9697```typescript98// 1. Create tool99const weatherTool = createTool({100id: "get-weather",101// ... tool config102});103104// 2. Register in Mastra instance105const mastra = new Mastra({106tools: {107weatherTool, // or 'weatherTool': weatherTool108},109});110111// 3. Assign to agent112const agent = new Agent({113id: "weather-agent",114tools: { weatherTool }, // Reference the tool115// ... other config116});117```118119**Alternative pattern (direct assignment)**:120121```typescript122const agent = new Agent({123id: "weather-agent",124tools: {125weatherTool: createTool({ id: "get-weather" /* ... */ }),126},127});128```129130### Agent memory not persisting131132**Symptoms**:133134- Agent doesn't remember previous messages135- Conversation history is lost between calls136137**Causes**:138139- No storage backend configured140- Missing or inconsistent `threadId`141- Memory not assigned to agent142143**Solutions**:144145```typescript146// 1. Configure storage147const storage = new PostgresStore({148connectionString: process.env.DATABASE_URL,149});150151// 2. Create memory with storage152const memory = new Memory({153id: "chat-memory",154storage,155options: {156lastMessages: 10, // How many messages to retrieve157},158});159160// 3. Assign memory to agent161const agent = new Agent({162id: "chat-agent",163memory,164});165166// 4. Use consistent threadId167await agent.generate("Hello", {168threadId: "user-123-conversation", // Same threadId for entire conversation169resourceId: "user-123",170});171```172173## Workflow errors174175### "Cannot read property 'then' of undefined"176177**Symptoms**:178179```bash180TypeError: Cannot read property 'then' of undefined181Workflow execution fails immediately182```183184**Causes**:185186- Forgot to call `.commit()` on workflow187- Step returns undefined188189**Solutions**:190191**Correct pattern**:192193```typescript194const workflow = createWorkflow({195id: "my-workflow",196inputSchema: z.object({ data: z.string() }),197outputSchema: z.object({ result: z.string() }),198})199.then(step1)200.then(step2)201.commit(); // REQUIRED!202203// Then execute204const run = await workflow.createRun();205const result = await run.start({ inputData: { data: "test" } });206```207208### Workflow state not updating209210**Symptoms**:211212- State changes don't persist across steps213- `getStepResult()` returns undefined214215**Causes**:216217- Not using `setState` to update state218- Accessing state before step completes219220**Solutions**:221222```typescript223const step1 = createStep({224id: "step1",225execute: async ({ state, setState }) => {226// Update state227await setState({ ...state, counter: (state.counter || 0) + 1 });228return { result: "done" };229},230});231232// Access state in subsequent steps233const step2 = createStep({234id: "step2",235execute: async ({ state }) => {236console.log(state.counter); // Access updated state237return { result: "complete" };238},239});240```241242## Memory errors243244### "Storage is required for Memory"245246**Symptoms**:247248```bash249Error: Storage is required for Memory250Memory instantiation fails251```252253**Causes**:254255- Memory created without storage backend256257**Solutions**:258259```typescript260// Always provide storage when creating Memory261const memory = new Memory({262id: "my-memory",263storage: postgresStore, // REQUIRED264options: {265lastMessages: 10,266},267});268```269270### Semantic recall not working271272**Symptoms**:273274- Memory doesn't retrieve semantically similar messages275- Only recent messages are returned276277**Causes**:278279- No vector store configured280- No embedder configured281- `semanticRecall` not enabled282283**Solutions**:284285```typescript286const memory = new Memory({287id: "semantic-memory",288storage: postgresStore,289vector: chromaVectorStore, // REQUIRED for semantic recall290embedder: openaiEmbedder, // REQUIRED for semantic recall291options: {292lastMessages: 10,293semanticRecall: true, // REQUIRED294},295});296```297298## Tool errors299300### "Tool validation failed"301302**Symptoms**:303304```bash305Error: Input validation failed for tool 'my-tool'306ZodError: Expected string, received number307```308309**Causes**:310311- Input doesn't match inputSchema312- Missing required fields313- Type mismatch314315**Solutions**:316317```typescript318const tool = createTool({319id: "my-tool",320inputSchema: z.object({321name: z.string(),322age: z.number().optional(), // Make optional fields explicit323}),324execute: async (input) => {325// input is validated and typed326return { result: `Hello ${input.name}` };327},328});329330// Correct usage331await tool.execute({ name: "Alice" }); // Works332await tool.execute({ name: "Bob", age: 30 }); // Works333await tool.execute({ age: 30 }); // ERROR: name is required334```335336### Tool suspension not resuming337338**Symptoms**:339340- Tool suspends but never resumes341- resumeData is undefined342343**Causes**:344345- Not calling workflow.resume() or agent.generate() with resumeData346- Incorrect resumeSchema347348**Solutions**:349350```typescript351const approvalTool = createTool({352id: "approval",353inputSchema: z.object({ request: z.string() }),354outputSchema: z.object({ approved: z.boolean() }),355suspendSchema: z.object({ requestId: z.string() }),356resumeSchema: z.object({ approved: z.boolean() }),357execute: async (input, context) => {358if (!context.resumeData) {359// First call - suspend360const requestId = generateId();361context.suspend({ requestId });362return; // Execution pauses here363}364365// Resumed - use resumeData366return { approved: context.resumeData.approved };367},368});369370// Resume the workflow/agent371await run.resume({372resumeData: { approved: true },373});374```375376## Storage errors377378### "Connection refused" or "Database does not exist"379380**Symptoms**:381382```bash383Error: connect ECONNREFUSED 127.0.0.1:5432384Error: database "mastra" does not exist385```386387**Causes**:388389- Database not running390- Incorrect connection string391- Database not created392393**Solutions**:3943951. Start database (Postgres example):396397```bash398docker run -d \399--name mastra-postgres \400-e POSTGRES_PASSWORD=password \401-e POSTGRES_DB=mastra \402-p 5432:5432 \403postgres:16404```4054062. Verify connection string:407408```env409DATABASE_URL=postgresql://postgres:password@localhost:5432/mastra410```4114123. Initialize storage:413414```typescript415const storage = new PostgresStore({416connectionString: process.env.DATABASE_URL,417});418await storage.init(); // Creates tables if needed419```420421## Environment variable errors422423### "API key not found"424425**Symptoms**:426427```bash428Error: OPENAI_API_KEY environment variable is not set429401 Unauthorized430```431432**Causes**:433434- Missing .env file435- Environment variables not loaded436- Incorrect variable name437438**Solutions**:4394401. Create .env file:441442```env443OPENAI_API_KEY=sk-...444ANTHROPIC_API_KEY=sk-ant-...445GOOGLE_GENERATIVE_AI_API_KEY=...446```4474482. Load environment variables (for Node.js):449450```typescript451import "dotenv/config"; // At top of entry file452```4534543. Verify variable is loaded:455456```typescript457if (!process.env.OPENAI_API_KEY) {458throw new Error("OPENAI_API_KEY is required");459}460```461462## Model errors463464### "Model not found" or "Invalid model"465466**Symptoms**:467468```bash469Error: Model 'gpt-4' not found470Error: Invalid model format471```472473**Causes**:474475- Incorrect model format (should be `provider/model`)476- Unsupported model477- Missing provider API key478479**Solutions**:480481**Correct model format**:482483```typescript484const agent = new Agent({485model: "openai/gpt-5.4", // ✅ Correct486// NOT: model: 'gpt-5.4' // ❌ Missing provider487});488```489490**Common models**:491492- OpenAI: `openai/gpt-5.4`, `openai/gpt-5-mini`493- Anthropic: `anthropic/claude-sonnet-4-5`, `anthropic/claude-haiku-4-5`, `anthropic/claude-opus-4-6`494- Google: `google/gemini-2.5-pro`, `google/gemini-2.5-flash`495496**Use embedded docs to verify**:497498```bash499# Check supported models500ls node_modules/@mastra/core/dist/docs/501# See embedded-docs.md for lookup instructions502```503504## Debugging tips505506### Enable verbose logging507508```typescript509const mastra = new Mastra({510logger: new PinoLogger({511name: "mastra",512level: "debug", // or 'trace' for even more detail513}),514});515```516517### Check package versions518519```bash520npm list @mastra/core521npm list @mastra/memory522npm list @mastra/rag523```524525### Validate TypeScript config526527```bash528npx tsc --showConfig529# Verify target: ES2022, module: ES2022530```531532## Getting help5335341. **Check embedded docs**: Check embedded docs (see `embedded-docs.md`)5352. **Search documentation**: [mastra.ai/docs](https://mastra.ai/docs)5363. **Check version compatibility**: Ensure all @mastra packages are same version5374. **File an issue**: [github.com/mastra-ai/mastra](https://github.com/mastra-ai/mastra)538