| name | mastra |
| description | Mastra AI: TypeScript agent framework — agents, workflows, tools, memory, RAG, evals — for building production-grade AI applications |
Mastra Skill
When to activate
- Building a production AI agent with memory, tools, and multi-step workflows
- Setting up RAG (Retrieval-Augmented Generation) pipelines
- Orchestrating multi-step AI workflows with branching logic and human-in-the-loop
- Adding evaluations to test AI output quality
- Building analytical CRMs or AI-powered business automation
When NOT to use
- Simple one-shot Claude API calls with no workflow — use the Claude API skill
- Chat UIs without agent logic — use the Vercel AI SDK skill
- When you need direct Claude Code integration — Claude's native agent loop is better
Instructions
Installation
npm install @mastra/core
npm install @mastra/core @mastra/memory @mastra/rag
Basic agent
import { Agent } from '@mastra/core/agent'
import { anthropic } from '@ai-sdk/anthropic'
export const analystAgent = new Agent({
name: 'Data Analyst',
instructions: `You are a data analyst. When given data, you:
1. Identify trends and anomalies
2. Provide actionable recommendations
3. Format output as structured JSON when asked`,
model: anthropic('claude-opus-4-7'),
})
const response = await analystAgent.generate('Analyze this sales data: ...')
console.log(response.text)
const stream = await analystAgent.stream('Summarize Q1 performance')
for await (const chunk of stream.textStream) {
process.stdout.write(chunk)
}
Tools — what the agent can do
import { createTool } from '@mastra/core/tools'
import { z } from 'zod'
export const queryCustomersTool = createTool({
id: 'query-customers',
description: 'Query the customer database with filters',
inputSchema: z.object({
status: z.enum(['active', 'churned', 'trial']).optional(),
minSpend: z.number().optional(),
limit: z.number().int().min(1).max(100).default(20),
}),
outputSchema: z.object({
customers: z.array(z.object({
id: z.string(),
name: z.string(),
email: z.string(),
spend: z.number(),
})),
total: z.number(),
}),
execute: ({ context }) => {
{ status, minSpend, limit } = context
customers = db..({
: {
...(status && { status }),
...(minSpend && { : { : minSpend } }),
},
: limit,
})
{ customers, : customers. }
},
})
sendEmailTool = ({
: ,
: ,
: z.({
: z.().(),
: z.(),
: z.(),
}),
: ({ context }) => {
emailService.(context)
{ : , : ().() }
},
})
crmAgent = ({
: ,
: ,
: (),
: {
: queryCustomersTool,
: sendEmailTool,
},
})
Workflows — multi-step orchestration
import { createWorkflow, createStep } from '@mastra/core/workflows'
import { z } from 'zod'
const analyzeUserStep = createStep({
id: 'analyze-user',
inputSchema: z.object({ userId: z.string() }),
outputSchema: z.object({
userId: z.string(),
segment: z.string(),
riskScore: z.number(),
}),
execute: async ({ inputData }) => {
const user = await db.users.findById(inputData.userId)
const analysis = await analystAgent.generate(
`Analyze this user for onboarding segmentation: ${JSON.stringify(user)}`
)
return {
userId: inputData.userId,
segment: extractSegment(analysis.text),
riskScore: extractRiskScore(analysis.text),
}
},
})
const sendWelcomeStep = createStep({
: ,
: z.({ : z.(), : z.() }),
: z.({ : z.() }),
: ({ inputData }) => {
template = [inputData.] ?? .
emailService.({ : inputData., template })
{ : }
},
})
onboardingWorkflow = ({
: ,
: z.({ : z.() }),
})
.(analyzeUserStep)
.([
{
: ({ inputData }) => inputData. > ,
: ({
: ,
: ({ inputData }) => {
(inputData.)
{ : }
},
}),
},
{
: ({ inputData }) => inputData. <= ,
: sendWelcomeStep,
},
])
.()
Memory — persist context across sessions
import { Agent } from '@mastra/core/agent'
import { Memory } from '@mastra/memory'
import { LibSQLStore } from '@mastra/memory/stores'
const memory = new Memory({
storage: new LibSQLStore({
url: 'file:./memory.db',
}),
options: {
lastMessages: 20,
semanticRecall: {
topK: 5,
messageRange: 2,
},
},
})
export const assistantWithMemory = new Agent({
name: 'Assistant',
instructions: 'You are a helpful assistant with memory of past conversations.',
model: anthropic('claude-opus-4-7'),
memory,
})
const response = await assistantWithMemory.generate(
'What did we discuss last week?',
{ : , : }
)
RAG — knowledge base integration
import { MastraVector } from '@mastra/core/vector'
import { PgVector } from '@mastra/pg'
const vectorStore = new PgVector({ connectionString: process.env.DATABASE_URL! })
async function indexDocuments(docs: Document[]) {
for (const doc of docs) {
const embedding = await embed(doc.content)
await vectorStore.upsert({
indexName: 'docs',
vectors: [{ id: doc.id, vector: embedding, metadata: { content: doc.content, title: doc.title } }],
})
}
}
export const searchKnowledgeBaseTool = createTool({
id: 'search-knowledge-base',
description: 'Search internal documentation and knowledge base',
inputSchema: z.({ : z.() }),
: ({ context }) => {
queryEmbedding = (context.)
results = vectorStore.({
: ,
: queryEmbedding,
: ,
})
{ : results.( r.) }
},
})
Evals — test output quality
import { evaluate } from '@mastra/evals'
import { ToxicityMetric, RelevancyMetric } from '@mastra/evals/metrics'
const results = await evaluate({
agent: crmAgent,
testCases: [
{
input: 'Find all churned customers from last month',
expectedOutput: 'Should list churned customers with their contact info',
},
],
metrics: [
new ToxicityMetric(),
new RelevancyMetric({ threshold: 0.8 }),
],
})
console.log(results.summary)
Mastra instance (wires everything together)
import { Mastra } from '@mastra/core'
export const mastra = new Mastra({
agents: { analystAgent, crmAgent, assistantWithMemory },
workflows: { onboardingWorkflow },
vectors: { docs: vectorStore },
})
export async function POST(req: Request) {
const { message, threadId } = await req.json()
const agent = mastra.getAgent('crmAgent')
const response = await agent.generate(message, { threadId })
return Response.json({ text: response.text })
}
Example
User: Build an AI-powered customer success agent that can query churned customers, analyze their usage patterns, and send personalized re-engagement emails — with memory so it remembers past campaigns.
Expected output:
src/mastra/tools/crm.ts — queryChurnedCustomers, getUsageMetrics, sendEmail tools
src/mastra/agents/customer-success.ts — agent with all 3 tools + memory
src/mastra/workflows/reengagement.ts — workflow: query → analyze → draft email → send
src/mastra/index.ts — new Mastra({ agents, workflows })
app/api/cs-agent/route.ts — POST endpoint using mastra.getAgent()