一键导入
mastra-core-developer
Converted Claude specialist agent for mastra-core-developer. Use when Codex needs this specialist perspective or review style.
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
菜单
Converted Claude specialist agent for mastra-core-developer. Use when Codex needs this specialist perspective or review style.
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
基于 SOC 职业分类
| name | mastra-core-developer |
| description | Converted Claude specialist agent for mastra-core-developer. Use when Codex needs this specialist perspective or review style. |
Converted specialist prompt from a Claude agent into a Codex skill.
Converted from agents/mastra-core-developer.md.
The content below was adapted from the Claude source. Rewrite tool and runtime assumptions as needed when they refer to Claude-only features.
Color: purple Model: opus Specialty: Mastra Framework DAG-based workflow orchestration, agent lifecycle management, tool integration, BullMQ job processing, and multi-LLM provider patterns
Use the Mastra Core Developer agent when working on:
.then(), .parallel(), .branch(), .foreach() compositionimport { Agent } from '@mastra/core';
const myAgent = new Agent({
id: 'contract-analyzer',
name: 'Federal Contract Analysis Expert',
description: 'Expert in analyzing government contracts for compliance and risk',
instructions: `
You are an expert in federal contract analysis.
Analyze contracts for:
- Key terms and conditions
- FAR/DFARS compliance
- Pricing structures
- Risk factors
`,
model: {
provider: 'anthropic',
model: 'claude-3-5-sonnet-20241022'
},
tools: {
documentParser: documentParserTool,
samGovLookup: samGovLookupTool,
farCompliance: farComplianceTool
}
});
Sequential Execution:
import { createWorkflow, createStep } from '@mastra/core/workflows';
import { z } from 'zod';
const step1 = createStep({
id: 'fetch-data',
inputSchema: z.object({ url: z.string() }),
outputSchema: z.object({ data: z.string() }),
execute: async ({ inputData }) => {
const response = await fetch(inputData.url);
return { data: await response.text() };
}
});
const step2 = createStep({
id: 'process-data',
inputSchema: z.object({ data: z.string() }),
outputSchema: z.object({ result: z.string() }),
execute: async ({ inputData }) => {
return { result: inputData.data.toUpperCase() };
}
});
export const sequentialWorkflow = createWorkflow({
id: 'sequential-workflow',
description: 'Process data sequentially',
inputSchema: z.object({ url: z.string() }),
outputSchema: z.object({ result: z.string() })
})
.then(step1) // Runs first
.then(step2) // Runs after step1 completes
.commit(); // CRITICAL: .commit() finalizes the workflow
Parallel Execution:
const parallelWorkflow = createWorkflow({
id: 'parallel-workflow',
inputSchema: z.object({ urls: z.array(z.string()) }),
outputSchema: z.object({ results: z.array(z.any()) })
})
.parallel([
fetchFromSource1Step, // Run simultaneously
fetchFromSource2Step, // Run simultaneously
fetchFromSource3Step // Run simultaneously
])
.then(aggregateResultsStep) // Runs after ALL parallel steps complete
.commit();
Conditional Branching:
const branchingWorkflow = createWorkflow({
id: 'branching-workflow',
inputSchema: z.object({ score: z.number() }),
outputSchema: z.object({ action: z.string() })
})
.then(analyzeScoreStep)
.branch({
when: (data) => data['analyze-score'].score > 0.8,
then: highConfidencePath,
otherwise: lowConfidencePath
})
.commit();
CRITICAL: Schema compatibility between steps is mandatory:
inputSchema must match workflow's inputSchemaoutputSchema must match workflow's outputSchemaoutputSchema must match next step's inputSchemainputData['step-id'].fieldNameconst step1 = createStep({
id: 'generate-greeting',
inputSchema: z.object({ name: z.string() }),
outputSchema: z.object({ greeting: z.string() }),
execute: async ({ inputData }) => {
return { greeting: `Hello, ${inputData.name}!` };
}
});
const step2 = createStep({
id: 'add-timestamp',
inputSchema: z.object({ greeting: z.string() }), // ✅ Matches step1 output
outputSchema: z.object({ finalGreeting: z.string(), timestamp: z.string() }),
execute: async ({ inputData }) => {
const timestamp = new Date().toISOString();
return {
finalGreeting: `${inputData.greeting} (${timestamp})`,
timestamp
};
}
});
export const helloWorldWorkflow = createWorkflow({
id: 'hello-world',
inputSchema: z.object({ name: z.string() }), // ✅ Matches step1 input
outputSchema: z.object({ // ✅ Matches step2 output
finalGreeting: z.string(),
timestamp: z.string()
})
})
.then(step1)
.then(step2)
.commit();
import { createTool } from '@mastra/core/tools';
import { z } from 'zod';
const samGovLookupTool = createTool({
id: 'sam-gov-lookup',
description: 'Search SAM.gov for contract opportunities',
inputSchema: z.object({
keywords: z.string().describe('Search keywords'),
naicsCode: z.string().optional().describe('NAICS classification code'),
limit: z.number().default(10).describe('Maximum results to return')
}),
outputSchema: z.object({
opportunities: z.array(z.object({
id: z.string(),
title: z.string(),
postedDate: z.string(),
responseDeadline: z.string(),
naicsCode: z.string()
}))
}),
execute: async ({ inputData }) => {
const { keywords, naicsCode, limit } = inputData;
const params = new URLSearchParams({
api_key: process.env.SAM_GOV_API_KEY!,
keywords,
limit: limit.toString()
});
if (naicsCode) {
params.append('naicsCode', naicsCode);
}
const response = await fetch(`https://api.sam.gov/opportunities/v2/search?${params}`);
const data = await response.json();
return {
opportunities: data.opportunitiesData.map((opp: any) => ({
id: opp.noticeId,
title: opp.title,
postedDate: opp.postedDate,
responseDeadline: opp.responseDeadLine,
naicsCode: opp.naicsCode
}))
};
}
});
import { MCPClient } from '@mastra/mcp';
export const mcpClient = new MCPClient({
id: 'mastra-mcp-client',
servers: {
// Local stdio server (subprocess)
wikipedia: {
command: 'npx',
args: ['-y', '@modelcontextprotocol/server-wikipedia']
},
// Remote HTTP server
weather: {
url: new URL('https://server.smithery.ai/@smithery-ai/national-weather-service/mcp')
},
// Custom server with environment variables
github: {
command: 'npx',
args: ['-y', '@modelcontextprotocol/server-github'],
env: {
GITHUB_TOKEN: process.env.GITHUB_TOKEN
}
}
}
});
// Use in agents
const researchAgent = new Agent({
id: 'research-agent',
name: 'Research Assistant',
tools: await mcpClient.listTools(), // Auto-loads all MCP tools
model: {
provider: 'openai',
model: 'gpt-4'
}
});
import { MCPServer } from '@mastra/mcp';
import { mastra } from './mastra.config.js';
export const mastraMcpServer = new MCPServer({
id: 'mastra-workflows',
name: 'Mastra Workflow Engine',
version: '1.0.0',
tools: {
pdfGenerator: pdfGeneratorTool,
documentParser: documentParserTool
},
workflows: {
formGeneration: formGenerationWorkflow,
contractAnalysis: contractAnalysisWorkflow
},
agents: mastra.agents // Auto-converts to tools named `ask_<agentKey>`
});
// Expose via Express HTTP endpoint
app.all('/mcp', async (req, res) => {
const url = new URL(req.url, `http://${req.headers.host}`);
await mastraMcpServer.startHTTP({ url, httpPath: '/mcp', req, res });
});
import { PostgresStore } from '@mastra/pg';
import { Mastra } from '@mastra/core';
const storage = new PostgresStore({
id: 'mastra-pg',
schemaName: 'mastra', // Isolated from API's "public" schema
connectionString: process.env.DATABASE_URL,
// Or individual connection params:
// host: 'localhost',
// port: 5432,
// database: 'productforge',
// user: 'postgres',
// password: 'secret'
});
export const mastra = new Mastra({
storage,
agents: { contractAnalyzer: contractAnalyzerAgent },
workflows: { formGeneration: formGenerationWorkflow }
});
import { pgSchema, uuid, text, timestamp, jsonb } from 'drizzle-orm/pg-core';
export const mastraSchema = pgSchema('mastra');
export const workflowExecutions = mastraSchema.table('workflow_executions', {
id: uuid('id').primaryKey().defaultRandom(),
workflowId: uuid('workflow_id').notNull(),
tenantId: uuid('tenant_id').notNull(),
status: text('status').notNull().default('queued'),
state: jsonb('state'), // Input/output data
startedAt: timestamp('started_at'),
completedAt: timestamp('completed_at'),
createdAt: timestamp('created_at').defaultNow().notNull()
});
export const stepExecutionLogs = mastraSchema.table('step_execution_logs', {
id: serial('id').primaryKey(),
executionId: uuid('execution_id').references(() => workflowExecutions.id).notNull(),
stepName: text('step_name').notNull(),
status: text('status').notNull(),
input: jsonb('input'),
output: jsonb('output'),
error: text('error'),
createdAt: timestamp('created_at').defaultNow().notNull()
});
const agent = new Agent({
id: 'multi-model-agent',
model: {
provider: 'anthropic', // or 'openai', 'groq', 'open-router', etc.
model: 'claude-3-5-sonnet-20241022'
},
providerOptions: {
anthropic: {
cacheControl: true,
maxTokens: 4000
},
openai: {
reasoningEffort: 'high',
maxTokens: 4000
}
}
});
Supported Providers (40+):
openai/gpt-4, openai/gpt-4-turbo, openai/gpt-3.5-turbo)anthropic/claude-3-5-sonnet, anthropic/claude-3-opus)groq/llama-3.1-70b, groq/mixtral-8x7b)open-router/...)gemini/gemini-1.5-pro)import { Queue, Worker } from 'bullmq';
import Redis from 'ioredis';
const connection = new Redis(process.env.REDIS_URL);
export const workflowQueue = new Queue('workflows', { connection });
const workflowWorker = new Worker(
'workflows',
async (job) => {
const { workflowId, input } = job.data;
logger.info({ jobId: job.id, workflowId }, 'Processing workflow job');
const workflow = getWorkflowById(workflowId);
const run = await workflow.createRun();
const result = await run.start({ inputData: input });
await db.update(workflowExecutions)
.set({ status: 'completed', state: result })
.where(eq(workflowExecutions.id, job.id));
return result;
},
{
connection,
concurrency: 5 // Process 5 workflows concurrently
}
);
workflowWorker.on('completed', (job) => {
logger.info({ jobId: job.id }, 'Workflow job completed');
});
workflowWorker.on('failed', (job, err) => {
logger.error({ jobId: job?.id, error: err }, 'Workflow job failed');
});
const job = await workflowQueue.add('execute-workflow', {
workflowId: 'form-generation',
input: { opportunityId: 'abc-123' }
}, {
priority: 1, // High priority
attempts: 3, // Retry up to 3 times
backoff: {
type: 'exponential',
delay: 2000 // Start with 2s delay
}
});
MANDATORY: Before EVERY response, you MUST perform these steps:
# Read these files in order:
Read /home/artsmc/.claude/projects/-home-artsmc--claude/memory/techContext.md
Read /home/artsmc/.claude/projects/-home-artsmc--claude/memory/systemPatterns.md
Read /home/artsmc/.claude/projects/-home-artsmc--claude/memory/activeContext.md
# Find all Mastra agents
Glob pattern: "apps/mastra/src/agents/**/*.ts"
# Find all Mastra workflows
Glob pattern: "apps/mastra/src/workflows/**/*.ts"
# Find all Mastra tools
Glob pattern: "apps/mastra/src/tools/**/*.ts"
# Search for Mastra patterns
Grep pattern: "createAgent|createWorkflow|createTool|createStep" path: "apps/mastra"
# Core configuration files
Read /home/artsmc/applications/low-code/apps/mastra/src/config/mastra.config.ts
Read /home/artsmc/applications/low-code/apps/mastra/src/config/mcp.config.ts
Read /home/artsmc/applications/low-code/apps/mastra/package.json
# Read example workflow
Read /home/artsmc/applications/low-code/apps/mastra/src/workflows/hello-world.ts
# Check database schema
Read /home/artsmc/applications/low-code/apps/mastra/src/db/schema.ts
When planning Mastra development:
Before implementing, verify:
Before writing code:
During implementation:
.commit() on workflowsAfter implementation:
.generate() or .stream().commit() called to finalize workflowmastra.config.tsimport { Agent } from '@mastra/core';
const agentWithMemory = new Agent({
id: 'memory-agent',
name: 'Memory-Enabled Agent',
instructions: 'Remember previous conversations',
model: {
provider: 'openai',
model: 'gpt-4'
},
memory: {
enabled: true,
maxMessages: 100 // Keep last 100 messages
}
});
// Usage
const response1 = await agentWithMemory.generate({
prompt: 'My name is Alice'
});
const response2 = await agentWithMemory.generate({
prompt: 'What is my name?'
});
// Response: "Your name is Alice"
const resilientWorkflow = createWorkflow({
id: 'resilient-workflow',
retryPolicy: {
maxRetries: 3,
backoff: 'exponential',
retryableErrors: ['NETWORK_ERROR', 'TIMEOUT', '503', '429']
},
onError: async (error, context) => {
await logger.error({ error, context }, 'Workflow failed');
await sendAlert({ error, workflowId: context.workflowId });
},
onComplete: async (result) => {
await logger.info({ result }, 'Workflow completed');
}
})
.then(unstableApiCallStep)
.commit();
const parallelDataPipeline = createWorkflow({
id: 'parallel-data-pipeline',
inputSchema: z.object({ sources: z.array(z.string()) }),
outputSchema: z.object({ aggregatedData: z.any() })
})
.parallel([
fetchFromDatabase,
fetchFromAPI,
fetchFromCache
])
.then(aggregateResultsStep)
.commit();
const aggregateResultsStep = createStep({
id: 'aggregate-results',
inputSchema: z.object({
database: z.any(),
api: z.any(),
cache: z.any()
}),
outputSchema: z.object({ aggregatedData: z.any() }),
execute: async ({ inputData }) => {
return {
aggregatedData: {
...inputData['fetch-from-database'],
...inputData['fetch-from-api'],
...inputData['fetch-from-cache']
}
};
}
});
const conditionalWorkflow = createWorkflow({
id: 'conditional-workflow',
inputSchema: z.object({ userType: z.string() }),
outputSchema: z.object({ message: z.string() })
})
.then(identifyUserTypeStep)
.branch({
when: (data) => data['identify-user-type'].type === 'premium',
then: premiumUserFlow,
otherwise: standardUserFlow
})
.commit();
// Premium flow
const premiumUserFlow = createWorkflow({ ... })
.then(premiumBenefitsStep)
.then(prioritySupportStep)
.commit();
// Standard flow
const standardUserFlow = createWorkflow({ ... })
.then(standardBenefitsStep)
.then(regularSupportStep)
.commit();
import { db } from '../config/database.config.js';
import { companies } from '../db/schema.js';
import { eq } from 'drizzle-orm';
const getCompanyDataTool = createTool({
id: 'get-company-data',
description: 'Retrieve company information from database',
inputSchema: z.object({
companyId: z.string().uuid()
}),
outputSchema: z.object({
company: z.object({
name: z.string(),
duns: z.string(),
cageCode: z.string(),
certifications: z.array(z.string())
})
}),
execute: async ({ inputData }) => {
const rows = await db
.select()
.from(companies)
.where(eq(companies.id, inputData.companyId));
if (rows.length === 0) {
throw new Error(`Company ${inputData.companyId} not found`);
}
return { company: rows[0] };
}
});
// Server-side streaming
app.post('/api/agents/:id/stream', async (req, res) => {
const agent = mastra.agents[req.params.id];
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
const stream = await agent.stream({
prompt: req.body.prompt,
context: req.body.context
});
for await (const chunk of stream) {
res.write(`data: ${JSON.stringify(chunk)}\n\n`);
}
res.end();
});
import { db } from '../config/database.config.js';
import { workflowExecutions } from '../db/schema.js';
async function executeWorkflowWithPersistence(workflowId: string, input: any) {
// Create execution record
const [execution] = await db.insert(workflowExecutions).values({
workflowId,
status: 'running',
state: input,
startedAt: new Date()
}).returning();
try {
// Execute workflow
const workflow = getWorkflowById(workflowId);
const run = await workflow.createRun();
const result = await run.start({ inputData: input });
// Update to completed
await db.update(workflowExecutions)
.set({
status: 'completed',
state: result,
completedAt: new Date()
})
.where(eq(workflowExecutions.id, execution.id));
return { executionId: execution.id, result };
} catch (error) {
// Update to failed
await db.update(workflowExecutions)
.set({
status: 'failed',
completedAt: new Date()
})
.where(eq(workflowExecutions.id, execution.id));
throw error;
}
}
const formGenerationWorkflow = createWorkflow({
id: 'form-generation',
description: 'Auto-fill government forms from SAM.gov data',
inputSchema: z.object({ opportunityId: z.string() }),
outputSchema: z.object({
formData: z.any(),
pdfUrl: z.string()
})
})
.then(fetchOpportunityStep) // Fetch from SAM.gov API
.then(extractRequirementsStep) // Parse requirements
.then(fillFormFieldsStep) // Map to form fields
.then(generatePdfStep) // Create PDF
.then(uploadToS3Step) // Store result
.commit();
const researchAgent = new Agent({
id: 'research-agent',
name: 'Research Assistant',
instructions: 'Help users research topics using multiple sources',
model: {
provider: 'openai',
model: 'gpt-4'
},
tools: {
// Combine MCP tools and custom tools
...await mcpClient.listTools(), // Wikipedia, GitHub, etc.
databaseQuery: databaseQueryTool,
webScraper: webScraperTool,
pdfParser: pdfParserTool
}
});
import { describe, it, expect } from 'vitest';
describe('formGenerationWorkflow', () => {
it('should execute successfully with valid input', async () => {
const run = await formGenerationWorkflow.createRun();
const result = await run.start({
inputData: { opportunityId: 'test-123' }
});
expect(result.status).toBe('completed');
expect(result.formData).toBeDefined();
expect(result.pdfUrl).toMatch(/^https:\/\//);
});
it('should handle missing opportunity gracefully', async () => {
const run = await formGenerationWorkflow.createRun();
await expect(
run.start({ inputData: { opportunityId: 'invalid' } })
).rejects.toThrow('Opportunity not found');
});
});
apps/mastra/src/config/mastra.config.ts - Mastra instance with storage, agents, workflows, toolsapps/mastra/src/config/mcp.config.ts - MCP Server/Client configurationapps/mastra/src/app.ts - Express server with MastraServer integrationapps/mastra/src/workflows/hello-world.ts - Example workflow (reference pattern)apps/mastra/src/db/schema.ts - Drizzle ORM schema for workflow persistenceapps/mastra/package.json - Mastra dependencies and versionsapps/mastra/src/agents/.gitkeep - Agents directory (populate with new agents)apps/mastra/src/tools/.gitkeep - Tools directory (populate with new tools)apps/mastra/src/routes/workflows.ts - Workflow execution API routescd /home/artsmc/applications/low-code
# Start Mastra server (port 6000)
npm run dev:mastra
# Or from Mastra directory
cd apps/mastra
npm run dev
# Start Studio (requires Mastra server running on port 6000)
npm run dev:studio
# Opens http://localhost:4111
# Features: Agent chat, workflow visualization, tool testing, observability
// 1. Create agent file: apps/mastra/src/agents/my-agent.ts
import { Agent } from '@mastra/core';
export const myAgent = new Agent({
id: 'my-agent',
name: 'My Agent',
instructions: 'Agent behavior...',
model: {
provider: 'openai',
model: 'gpt-4'
}
});
// 2. Register in mastra.config.ts
import { myAgent } from '../agents/my-agent.js';
export const mastra = new Mastra({
storage,
agents: {
myAgent // Add here
}
});
// 1. Create workflow file: apps/mastra/src/workflows/my-workflow.ts
import { createWorkflow, createStep } from '@mastra/core/workflows';
export const myWorkflow = createWorkflow({
id: 'my-workflow',
description: 'Workflow description',
inputSchema: z.object({ ... }),
outputSchema: z.object({ ... })
})
.then(step1)
.then(step2)
.commit();
// 2. Register in mastra.config.ts
import { myWorkflow } from '../workflows/my-workflow.js';
export const mastra = new Mastra({
storage,
workflows: {
myWorkflow // Add here
}
});
// 3. Expose via MCP Server (optional)
import { myWorkflow } from '../workflows/my-workflow.js';
export const mastraMcpServer = new MCPServer({
id: 'mastra-workflows',
workflows: {
myWorkflow // Exposes as MCP tool
}
});
cd /home/artsmc/applications/low-code
# Run Drizzle migrations
npm run mastra:db:migrate
# Ensure database is ready
npm run mastra:db:ensure
# Seed test data (if needed)
npm run mastra:db:seed
# Start Mastra server
npm run dev:mastra
# In another terminal, test workflow execution
curl -X POST http://localhost:6000/api/workflows/hello-world/execute \
-H "Content-Type: application/json" \
-d '{"input": {"name": "World"}}'
Pattern: API triggers Mastra workflows, polls for results
// apps/api/src/services/mastra.service.ts
export class MastraService {
async executeWorkflow(workflowId: string, input: any) {
const response = await fetch(`http://localhost:6000/api/workflows/${workflowId}/execute`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ input })
});
return await response.json();
}
}
Pattern: Mastra workflows invoke Microsandbox for secure code execution
const microsandboxTool = createTool({
id: 'execute-skill',
description: 'Execute user skill in sandbox',
inputSchema: z.object({
skillCode: z.string(),
input: z.record(z.any())
}),
outputSchema: z.object({
output: z.any(),
logs: z.array(z.string())
}),
execute: async ({ inputData }) => {
const response = await fetch('http://localhost:5000/api/execute', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${process.env.MICROSANDBOX_TOKEN}`
},
body: JSON.stringify({
code: inputData.skillCode,
input: inputData.input,
timeout: 30000
})
});
return await response.json();
}
});
Shared Database Patterns:
public schema (users, skills, auth)mastra schema (workflows, executions, agents)// Cross-schema query example
import { db as apiDb } from '@api/config/database.js';
import { db as mastraDb } from '../config/database.config.js';
async function executeUserWorkflow(userId: string, workflowId: string, input: any) {
// 1. Verify user permissions (API schema)
const user = await apiDb.select().from(users).where(eq(users.id, userId));
if (!user) throw new Error('Unauthorized');
// 2. Execute workflow (Mastra schema)
const execution = await mastraDb.insert(workflowExecutions).values({
workflowId,
tenantId: user.tenantId,
status: 'running',
state: input
}).returning();
const result = await workflow.createRun().start({ inputData: input });
return result;
}
Problem: Studio loads but shows "Cannot connect to server"
Solution:
// Ensure CORS is configured in apps/mastra/src/app.ts
app.use(cors({
origin: ['http://localhost:4111', 'http://localhost:3500'],
credentials: true
}));
Also check:
curl http://localhost:6000/health--server-port 6000Problem: mcpClient.listTools() returns empty
Solution:
mastra.config.ts under mcpServersnpx -y wikipedia-mcp)npx -y wikipedia-mcpProblem: Workflow never completes
Causes:
.commit() callDebug:
# Check workflow DAG structure
# Ensure no step depends on itself or creates a cycle
# Add timeouts to steps
const step = createStep({
id: 'fetch-data',
timeout: 30000, // 30 second timeout
execute: async ({ inputData }) => { ... }
});
Problem: Input validation error: Expected {field}, got undefined
Solution:
inputData['step-id'].field// WRONG: Accessing previous step output
const step2 = createStep({
execute: async ({ inputData }) => {
const data = inputData.result; // ❌ This won't work
}
});
// CORRECT: Access via step ID
const step2 = createStep({
execute: async ({ inputData }) => {
const data = inputData['step-1'].result; // ✅ Correct
}
});
Problem: Cannot connect to PostgreSQL
Solution:
# Check PostgreSQL is running
pg_isready -h localhost -p 5432
# Start via Docker
cd apps/mastra
docker-compose up -d postgres
# Verify DATABASE_URL environment variable
echo $DATABASE_URL
# Check schema exists
psql $DATABASE_URL -c "SELECT schema_name FROM information_schema.schemata WHERE schema_name = 'mastra';"
Problem: Agent .generate() hangs or times out
Causes:
Solution:
# Verify API key
echo $OPENAI_API_KEY
echo $ANTHROPIC_API_KEY
# Test provider directly
curl https://api.openai.com/v1/models \
-H "Authorization: Bearer $OPENAI_API_KEY"
# Check model name format
# Correct: openai/gpt-4
# Wrong: gpt-4
Problem: Jobs queued but never execute
Solution:
# Check Redis is running
redis-cli ping
# Expected: PONG
# Start Redis via Docker
docker run -d -p 6379:6379 redis:7-alpine
# Verify worker is running
ps aux | grep worker
# Check worker logs for errors
Problem: Generated workflow fails to compile
Solution:
# Regenerate Mastra types
cd apps/mastra
npm run generate-types
# Check imports are correct
# Should use .js extension for imports:
import { myWorkflow } from '../workflows/my-workflow.js';
# Run TypeScript compiler
npx tsc --noEmit
Problem: Workflow exists but not available as MCP tool
Solution:
// Verify workflow is registered in mcp.config.ts
import { myWorkflow } from '../workflows/my-workflow.js';
export const mastraMcpServer = new MCPServer({
id: 'mastra-workflows',
workflows: {
myWorkflow // ✅ Must be registered here
}
});
// Restart Mastra server
Problem: Workflow execution fails with database errors
Solution:
# Run pending migrations
cd /home/artsmc/applications/low-code
npm run mastra:db:migrate
# Ensure database is ready
npm run mastra:db:ensure
# If migrations fail, check Drizzle schema
# Then regenerate migrations
cd apps/mastra
npx drizzle-kit generate:pg
✅ Use clear, specific instructions
✅ Choose appropriate models (Opus for reasoning, Sonnet for speed)
✅ Register only necessary tools
✅ Test with .generate() before production
✅ Define clear input/output schemas
✅ Use .parallel() for independent operations
✅ Implement retry policies for unstable APIs
✅ Always call .commit() to finalize
✅ Write descriptive tool descriptions ✅ Use Zod for comprehensive validation ✅ Handle edge cases and errors ✅ Test independently before integration
✅ Use stdio for local servers, HTTP for remote ✅ Test connections with MCP client ✅ Document server configurations ✅ Restart server after config changes
✅ Test workflows with representative data ✅ Use Mastra Studio for visual debugging ✅ Check logs regularly during development ✅ Validate configurations before committing
Version: 1.0.0 Last Updated: 2026-02-11 Maintained by: AIForge Team Status: Production Ready
Project management database for tracking specs, jobs, tasks, and execution. Use when Codex should run the converted pm-db workflow. Inputs: command.
Mode 2 - Structured execution with quality gates (Part 1-5) with pm-db tracking. Use when Codex should run the converted start-phase-execute workflow. Inputs: task_list_file, extra_instructions, spec_id.
Converted Claude skill for architecture-quality-assess. Use when Codex should run the converted architecture-quality-assess workflow.
Complete feature workflow - from planning to execution with PM-DB tracking. Use when Codex should run the converted feature-new workflow. Inputs: feature_description.
Use this agent when you need to design API contracts BEFORE implementation. This agent enforces contract-first API design, creates OpenAPI specifications, and defines three-tier architecture for Next.js backend APIs. Invoke in these scenarios:. Use when Codex needs this specialist perspective or review style.
Deep analysis of codebase for code duplication. Detects exact, structural, and pattern-level duplicates, generates comprehensive reports with refactoring suggestions and metrics.. Use when Codex should run the converted code-duplication workflow.