Skip to content

Mastra Framework (2026): TypeScript Developer's Secret Weapon for AI Agents — Setup & Examples

Why Choose Mastra?

If you are a TypeScript/JavaScript developer looking to achieve the same productivity as Python developers in AI application development, Mastra is the framework built for you.

Mastra is an open-source TypeScript-native AI Agent framework backed by Y Combinator, designed specifically for web developers. It provides all the primitives needed to build, test, and deploy AI applications, enabling you to quickly go from idea to production.

Core Advantages

  • TypeScript Native: Full type support and IDE IntelliSense
  • Production Ready: Built-in workflows, memory, RAG, evaluation, and tracing
  • Developer Experience: Interactive Playground and real-time debugging
  • Open Source and Free: MIT License, community-driven

Quick Start

Installing Mastra

# Create a new project
npx create-mastra@latest my-ai-app

# Enter project directory
cd my-ai-app

# Install dependencies
npm install

Project Structure

my-ai-app/
├── src/
│   ├── mastra/
│   │   ├── agents/          # Agent definitions
│   │   ├── tools/           # Custom tools
│   │   ├── workflows/       # Workflows
│   │   └── index.ts         # Main entry
│   └── index.ts
├── package.json
└── mastra.config.ts

Core Concepts

1. Creating an Agent

Agents are Mastra's core building block. Each agent has a specific role, tools, and memory.

// src/mastra/agents/customer-support.ts
import { Agent } from '@mastra/core/agent';

export const customerSupportAgent = new Agent({
  name: 'Customer Support Agent',
  instructions: `
    You are a professional customer support assistant, responsible for answering user questions about products.
    - Maintain a friendly and professional tone
    - Provide accurate information
    - If you don't know the answer, honestly say so and suggest contacting human support
  `,
  model: {
    provider: 'ANTHROPIC',
    name: 'claude-sonnet-4-20250514',
  },
});

2. Creating Custom Tools

Tools enable agents to perform specific actions, such as querying databases or calling APIs.

// src/mastra/tools/order-lookup.ts
import { createTool } from '@mastra/core/tools';
import { z } from 'zod';

export const orderLookupTool = createTool({
  id: 'order-lookup',
  description: 'Query order status by order number',
  inputSchema: z.object({
    orderId: z.string().describe('Order ID'),
  }),
  execute: async ({ context }) => {
    const { orderId } = context;

    // Simulate database query
    const order = await db.orders.findUnique({
      where: { id: orderId },
    });

    return {
      status: order?.status || 'not_found',
      items: order?.items || [],
      total: order?.total || 0,
    };
  },
});

3. Binding Tools to an Agent

// src/mastra/agents/customer-support.ts
import { customerSupportAgent } from './customer-support';
import { orderLookupTool } from '../tools/order-lookup';

// Add tools
customerSupportAgent.addTools([orderLookupTool]);

4. Creating Workflows

Workflows enable you to orchestrate multiple agents and tools to implement complex business processes.

// src/mastra/workflows/order-processing.ts
import { Workflow } from '@mastra/core/workflows';
import { agentStep } from '@mastra/core/step';

export const orderProcessingWorkflow = new Workflow({
  name: 'order-processing',
  triggerSchema: z.object({
    orderId: z.string(),
    customerEmail: z.string().email(),
  }),
});

// Define steps
const checkOrder = agentStep({
  agent: customerSupportAgent,
  outputSchema: z.object({
    status: z.string(),
    canRefund: z.boolean(),
  }),
});

const sendEmail = agentStep({
  agent: emailAgent,
  outputSchema: z.object({
    sent: z.boolean(),
  }),
});

// Orchestrate the flow
orderProcessingWorkflow
  .step(checkOrder)
  .then(sendEmail, {
    when: { ref: checkOrder, path: 'canRefund', eq: true },
  });

Practical Example: Building a Customer Service Bot

Let's build a complete customer service bot capable of handling order inquiries, return requests, and product consultations.

Complete Code

// src/mastra/index.ts
import { Mastra } from '@mastra/core/mastra';
import { customerSupportAgent } from './agents/customer-support';
import { orderLookupTool } from './tools/order-lookup';
import { refundTool } from './tools/refund';
import { orderProcessingWorkflow } from './workflows/order-processing';

export const mastra = new Mastra({
  agents: {
    'customer-support': customerSupportAgent,
  },
  tools: {
    'order-lookup': orderLookupTool,
    'refund': refundTool,
  },
  workflows: {
    'order-processing': orderProcessingWorkflow,
  },
});

Starting the Development Server

# Start Mastra development server (includes Playground)
npx mastra dev

Visit http://localhost:4111 to open the interactive Playground, where you can test your agents in real time.

Calling an Agent

// src/index.ts
import { mastra } from './mastra';

async function main() {
  const agent = mastra.getAgent('customer-support');

  const response = await agent.generate(
    'My order number is ORD-12345, please check the status for me'
  );

  console.log(response.text);
}

main();

Advanced Features

Memory System

Mastra has built-in memory, enabling agents to remember conversation history.

import { Memory } from '@mastra/memory';

const memory = new Memory({
  storage: {
    type: 'postgres',
    connectionString: process.env.DATABASE_URL,
  },
});

const agent = new Agent({
  name: 'Support Agent',
  memory,
  // ...other configuration
});

RAG (Retrieval-Augmented Generation)

import { RAG } from '@mastra/rag';

const rag = new RAG({
  vectorStore: {
    type: 'pinecone',
    apiKey: process.env.PINECONE_API_KEY,
  },
});

// Index documents
await rag.index({
  documents: ['./docs/product-manual.pdf'],
  indexName: 'product-knowledge',
});

// Use in an agent
const agent = new Agent({
  name: 'Product Expert',
  rag: {
    indexes: ['product-knowledge'],
  },
});

Evaluation and Tracing

import { Eval } from '@mastra/evals';

const eval = new Eval({
  name: 'response-quality',
  criteria: [
    { name: 'accuracy', weight: 0.4 },
    { name: 'helpfulness', weight: 0.3 },
    { name: 'tone', weight: 0.3 },
  ],
});

// Run evaluation
const results = await eval.evaluate(agent, testCases);
console.log(results.summary);

Production Deployment

Deploying to Vercel

# Install Vercel CLI
npm i -g vercel

# Deploy
vercel deploy --prod

Deploying to Docker

# Dockerfile
FROM node:20-alpine

WORKDIR /app
COPY package*.json ./
RUN npm ci

COPY . .
RUN npm run build

EXPOSE 3000
CMD ["npm", "start"]
# Build and run
docker build -t my-mastra-app .
docker run -p 3000:3000 my-mastra-app

Performance Optimization Tips

  1. Use streaming responses: For long text generation, enable streaming to improve user experience
  2. Cache tool results: For frequently called tools, implement result caching
  3. Batch processing: For multiple similar requests, use batch API calls
  4. Monitor latency: Use Mastra's built-in tracing to monitor each step's duration

Comparison with Other Frameworks

Feature Mastra LangChain.js Vercel AI SDK
TypeScript Native ⚠️
Built-in Workflows
Interactive Playground
Memory System ⚠️
RAG Support
Evaluation Tools ⚠️
Learning Curve Medium Steep Gentle

Summary

Mastra is one of the best choices for TypeScript developers entering AI Agent development. It provides:

  • 🎯 Developer-friendly API: Type-safe, complete IntelliSense support
  • 🔧 Rich built-in features: Workflows, memory, RAG, evaluation all-in-one
  • 🚀 Production ready: Complete toolchain from development to deployment
  • 📚 Excellent documentation: Detailed tutorials and examples

If you are already working in the TypeScript ecosystem and want to quickly build AI applications, Mastra is worth trying.

Resources


Recommended Reading: