Mastra Tutorial: TypeScript Framework for Building AI Agents and Workflows

# Tutorial Mastra: Framework TypeScript untuk Membangun AI Agent dan Workflow Mastra adalah framework open-source berbasis TypeScript yang dirancang untuk memudahkan developer membangun AI agent, wor...

By Ruby Abdullah · · tutorial
MastraTypeScriptAI AgentsWorkflowRAG

Mastra Tutorial: TypeScript Framework for Building AI Agents and Workflows

Mastra is an open-source TypeScript framework designed to simplify building AI agents, workflows, and RAG pipelines. With Mastra, you can create complex AI applications with well-structured, maintainable code. The framework supports multiple LLM providers, features a flexible tool system, and provides a powerful workflow engine for orchestrating AI tasks.

In this tutorial, we will cover how to use Mastra from installation, creating simple agents, building multi-step workflows, to integrating RAG pipelines. All code examples can be directly executed in your TypeScript project.

Why Mastra?

Before diving into implementation, here are several reasons why Mastra is worth considering:

  • TypeScript-first: Built from the ground up for TypeScript with strong type safety
  • Multi-provider LLM: Supports OpenAI, Anthropic, Google Gemini, and other providers through the Vercel AI SDK
  • Agent Framework: Agent system with tool calling, memory, and structured output
  • Workflow Engine: Step-based workflow with branching, parallel execution, and error handling
  • Built-in RAG: Integrated RAG pipeline with support for various vector databases
  • Observability: Integrated tracing and logging for agent monitoring
  • Self-hostable: Can be deployed on your own server or using Mastra Cloud

Installation and Setup

Prerequisites

Make sure you have installed:

  • Node.js version 18 or later
  • npm or pnpm as package manager
  • API key from an LLM provider (OpenAI, Anthropic, etc.)

Creating a New Project

The fastest way to get started is using the Mastra CLI:

npx create-mastra@latest my-ai-app

The CLI will ask for several configuration options:

? Select components to install:

✔ Agents

✔ Tools

✔ Workflows

? Select default LLM provider:

✔ OpenAI

? Select example to include:

✔ Weather Agent

After completion, navigate to the project directory:

cd my-ai-app

npm install

Manual Setup

If you want to add Mastra to an existing project:

npm install mastra @mastra/core @mastra/memory

Create the environment configuration file:

# .env

OPENAIAPIKEY=sk-your-openai-key

ANTHROPICAPIKEY=sk-ant-your-anthropic-key

Project Structure

Here is the recommended Mastra project structure:

my-ai-app/

├── src/

│ ├── mastra/

│ │ ├── agents/

│ │ │ └── index.ts

│ │ ├── tools/

│ │ │ └── index.ts

│ │ ├── workflows/

│ │ │ └── index.ts

│ │ └── index.ts

│ └── index.ts

├── .env

├── package.json

└── tsconfig.json

Core Concepts

Initializing Mastra

The main file for Mastra initialization:

// src/mastra/index.ts

import { Mastra } from "@mastra/core";

import { createLogger } from "@mastra/core/logger";

import { weatherAgent } from "./agents";

export const mastra = new Mastra({

agents: { weatherAgent },

logger: createLogger({

name: "MyApp",

level: "info",

}),

});

Creating Your First Agent

An agent is the core component in Mastra. Each agent has instructions, an LLM model, and tools it can use:

// src/mastra/agents/index.ts

import { Agent } from "@mastra/core/agent";

import { openai } from "@ai-sdk/openai";

export const assistantAgent = new Agent({

name: "Assistant",

instructions: You are an AI assistant that helps users answer

questions accurately and informatively. Provide clear,

well-structured responses.,

model: openai("gpt-4o"),

});

Using the agent:

import { mastra } from "./mastra";

async function main() {

const agent = mastra.getAgent("assistantAgent");

const response = await agent.generate(

"Explain what machine learning is in 3 sentences"

);

console.log(response.text);

}

main();

Creating Custom Tools

Tools allow agents to interact with the outside world, such as calling APIs, reading databases, or performing calculations.

Tool Definition

// src/mastra/tools/index.ts

import { createTool } from "@mastra/core/tools";

import { z } from "zod";

export const weatherTool = createTool({

id: "get-weather",

description: "Fetches weather data for a specific city",

inputSchema: z.object({

city: z.string().describe("City name"),

unit: z.enum(["celsius", "fahrenheit"]).default("celsius"),

}),

outputSchema: z.object({

temperature: z.number(),

condition: z.string(),

humidity: z.number(),

}),

execute: async ({ context }) => {

const { city, unit } = context;

const response = await fetch(

https://api.weatherapi.com/v1/current.json?key=${process.env.WEATHERAPIKEY}&q=${city}

);

const data = await response.json();

return {

temperature: unit === "celsius"

? data.current.tempc

: data.current.tempf,

condition: data.current.condition.text,

humidity: data.current.humidity,

};

},

});

Database Query Tool

import { createTool } from "@mastra/core/tools";

import { z } from "zod";

export const searchProductsTool = createTool({

id: "search-products",

description: "Searches products by keyword and category",

inputSchema: z.object({

query: z.string().describe("Search keyword"),

category: z.string().optional().describe("Product category"),

maxResults: z.number().default(10),

}),

execute: async ({ context }) => {

const { query, category, maxResults } = context;

const products = await db.products.findMany({

where: {

name: { contains: query },

...(category && { category }),

},

take: maxResults,

});

return { products, total: products.length };

},

});

Connecting Tools to an Agent

import { Agent } from "@mastra/core/agent";

import { openai } from "@ai-sdk/openai";

import { weatherTool, searchProductsTool } from "../tools";

export const smartAssistant = new Agent({

name: "SmartAssistant",

instructions: You are a smart assistant that can:

  • Check weather in various cities
  • Search products in the database
  • Use the available tools to answer user questions.,

    model: openai("gpt-4o"),

    tools: {

    getWeather: weatherTool,

    searchProducts: searchProductsTool,

    },

    });

    Workflow Engine

    Workflows in Mastra allow you to orchestrate a series of complex steps with clear flow control.

    Simple Workflow

    // src/mastra/workflows/index.ts
    

    import { Workflow, Step } from "@mastra/core/workflows";

    import { z } from "zod";

    const analyzeText = new Step({

    id: "analyze-text",

    inputSchema: z.object({

    text: z.string(),

    }),

    outputSchema: z.object({

    wordCount: z.number(),

    sentiment: z.string(),

    language: z.string(),

    }),

    execute: async ({ context }) => {

    const text = context.inputData.text;

    const words = text.split(/\s+/).length;

    const agent = mastra.getAgent("assistantAgent");

    const result = await agent.generate(

    Analyze the sentiment of the following text and respond with

    one word (positive/negative/neutral): "${text}"

    );

    return {

    wordCount: words,

    sentiment: result.text.trim().toLowerCase(),

    language: "en",

    };

    },

    });

    const generateReport = new Step({

    id: "generate-report",

    inputSchema: z.object({

    wordCount: z.number(),

    sentiment: z.string(),

    language: z.string(),

    }),

    outputSchema: z.object({

    report: z.string(),

    }),

    execute: async ({ context }) => {

    const { wordCount, sentiment, language } = context.inputData;

    return {

    report: Text Analysis Report:

    • Word count: ${wordCount}
    • Sentiment: ${sentiment}
    • Language: ${language},
    };

    },

    });

    export const textAnalysisWorkflow = new Workflow({

    name: "text-analysis",

    triggerSchema: z.object({

    text: z.string(),

    }),

    });

    textAnalysisWorkflow

    .step(analyzeText)

    .then(generateReport)

    .commit();

    Running a Workflow

    import { mastra } from "./mastra";
    
    

    async function runWorkflow() {

    const workflow = mastra.getWorkflow("text-analysis");

    const result = await workflow.execute({

    triggerData: {

    text: "Mastra is an amazing framework for building AI applications!",

    },

    });

    console.log(result.results);

    }

    Workflow with Branching

    import { Workflow, Step } from "@mastra/core/workflows";
    

    import { z } from "zod";

    const classifyIntent = new Step({

    id: "classify-intent",

    inputSchema: z.object({

    message: z.string(),

    }),

    outputSchema: z.object({

    intent: z.enum(["question", "complaint", "feedback"]),

    confidence: z.number(),

    }),

    execute: async ({ context }) => {

    const agent = mastra.getAgent("assistantAgent");

    const result = await agent.generate({

    messages: [

    {

    role: "user",

    content: Classify the intent of the following message into one of:

    question, complaint, feedback.

    Message: "${context.inputData.message}"

    Respond in JSON format: {"intent": "...", "confidence": 0.0-1.0},

    },

    ],

    });

    return JSON.parse(result.text);

    },

    });

    const handleQuestion = new Step({

    id: "handle-question",

    execute: async ({ context }) => {

    return { response: "Thank you for your question. Our team will respond shortly." };

    },

    });

    const handleComplaint = new Step({

    id: "handle-complaint",

    execute: async ({ context }) => {

    return { response: "We apologize for the inconvenience. Your complaint has been recorded." };

    },

    });

    const handleFeedback = new Step({

    id: "handle-feedback",

    execute: async ({ context }) => {

    return { response: "Thank you for your feedback. Your input is very valuable to us." };

    },

    });

    export const customerServiceWorkflow = new Workflow({

    name: "customer-service",

    triggerSchema: z.object({

    message: z.string(),

    }),

    });

    customerServiceWorkflow

    .step(classifyIntent)

    .then(handleQuestion, {

    when: async ({ context }) => {

    const result = context.getStepResult("classify-intent");

    return result.intent === "question";

    },

    })

    .after(classifyIntent)

    .step(handleComplaint, {

    when: async ({ context }) => {

    const result = context.getStepResult("classify-intent");

    return result.intent === "complaint";

    },

    })

    .after(classifyIntent)

    .step(handleFeedback, {

    when: async ({ context }) => {

    const result = context.getStepResult("classify-intent");

    return result.intent === "feedback";

    },

    })

    .commit();

    RAG Pipeline with Mastra

    Mastra provides built-in support for RAG (Retrieval-Augmented Generation).

    Setting Up the Vector Store

    // src/mastra/rag/index.ts
    

    import { PgVector } from "@mastra/pg";

    import { MDocument } from "@mastra/rag";

    import { openai } from "@ai-sdk/openai";

    import { embed } from "ai";

    const pgVector = new PgVector({

    connectionString: process.env.DATABASEURL!,

    });

    await pgVector.createIndex({

    indexName: "knowledge-base",

    dimension: 1536,

    metric: "cosine",

    });

    Ingesting Documents

    import { MDocument } from "@mastra/rag";
    

    import { embed, embedMany } from "ai";

    import { openai } from "@ai-sdk/openai";

    async function ingestDocuments(texts: string[]) {

    const docs = texts.map(

    (text) => MDocument.fromText(text)

    );

    const chunks = [];

    for (const doc of docs) {

    const docChunks = await doc.chunk({

    strategy: "recursive",

    size: 512,

    overlap: 50,

    });

    chunks.push(...docChunks);

    }

    const { embeddings } = await embedMany({

    model: openai.embedding("text-embedding-3-small"),

    values: chunks.map((chunk) => chunk.text),

    });

    await pgVector.upsert({

    indexName: "knowledge-base",

    vectors: embeddings.map((embedding, i) => ({

    id: chunk-${i},

    values: embedding,

    metadata: {

    text: chunks[i].text,

    source: chunks[i].metadata?.source,

    },

    })),

    });

    console.log(Successfully ingested ${chunks.length} chunks);

    }

    RAG Agent

    import { Agent } from "@mastra/core/agent";
    

    import { openai } from "@ai-sdk/openai";

    import { createTool } from "@mastra/core/tools";

    import { z } from "zod";

    import { embed } from "ai";

    const searchKnowledgeBase = createTool({

    id: "search-knowledge-base",

    description: "Searches for information from the company knowledge base",

    inputSchema: z.object({

    query: z.string().describe("Search query"),

    topK: z.number().default(5),

    }),

    execute: async ({ context }) => {

    const { query, topK } = context;

    const { embedding } = await embed({

    model: openai.embedding("text-embedding-3-small"),

    value: query,

    });

    const results = await pgVector.query({

    indexName: "knowledge-base",

    queryVector: embedding,

    topK,

    includeMetadata: true,

    });

    return {

    results: results.map((r) => ({

    text: r.metadata?.text,

    score: r.score,

    })),

    };

    },

    });

    export const ragAgent = new Agent({

    name: "RAGAssistant",

    instructions: You are an assistant that answers questions based on

    the company knowledge base. Always search the knowledge base first

    before answering. If information is not found, communicate that

    you don't have the relevant data.,

    model: openai("gpt-4o"),

    tools: {

    searchKnowledgeBase,

    },

    });

    Structured Output

    Mastra supports structured output to get responses in a consistent format:

    import { Agent } from "@mastra/core/agent";
    

    import { openai } from "@ai-sdk/openai";

    import { z } from "zod";

    const dataExtractor = new Agent({

    name: "DataExtractor",

    instructions: "Extract structured information from the given text.",

    model: openai("gpt-4o"),

    });

    async function extractInvoiceData(text: string) {

    const result = await dataExtractor.generate(

    Extract invoice data from the following text: ${text},

    {

    output: z.object({

    invoiceNumber: z.string(),

    date: z.string(),

    items: z.array(

    z.object({

    name: z.string(),

    quantity: z.number(),

    price: z.number(),

    })

    ),

    total: z.number(),

    currency: z.string(),

    }),

    }

    );

    console.log(result.object);

    // {

    // invoiceNumber: "INV-2026-001",

    // date: "2026-09-01",

    // items: [{ name: "AI Consultation", quantity: 1, price: 15000000 }],

    // total: 15000000,

    // currency: "IDR"

    // }

    }

    Memory and Conversation History

    Mastra provides a memory system for storing conversation context:

    import { Agent } from "@mastra/core/agent";
    

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

    import { openai } from "@ai-sdk/openai";

    import { PgMemory } from "@mastra/pg";

    const memory = new Memory({

    storage: new PgMemory({

    connectionString: process.env.DATABASEURL!,

    }),

    options: {

    lastMessages: 20,

    semanticRecall: {

    topK: 3,

    messageRange: { before: 2, after: 1 },

    },

    },

    });

    export const chatAgent = new Agent({

    name: "ChatAssistant",

    instructions: You are a friendly chat assistant.

    Remember previous conversation context to provide

    relevant and personalized responses.,

    model: openai("gpt-4o"),

    memory,

    });

    async function chat(threadId: string, message: string) {

    const agent = mastra.getAgent("chatAgent");

    const response = await agent.generate(message, {

    threadId,

    resourceId: "user-123",

    });

    return response.text;

    }

    // Multi-turn conversation

    await chat("thread-1", "Hello, my name is Ruby");

    await chat("thread-1", "What is my name?"); // Agent will remember "Ruby"

    Streaming Responses

    For real-time applications, use streaming:

    import { Agent } from "@mastra/core/agent";
    

    import { openai } from "@ai-sdk/openai";

    const streamAgent = new Agent({

    name: "StreamAgent",

    instructions: "Provide detailed and well-structured explanations.",

    model: openai("gpt-4o"),

    });

    async function streamResponse(prompt: string) {

    const stream = await streamAgent.stream(prompt);

    for await (const chunk of stream.textStream) {

    process.stdout.write(chunk);

    }

    }

    async function streamWithTools(prompt: string) {

    const stream = await streamAgent.stream(prompt);

    for await (const part of stream.fullStream) {

    switch (part.type) {

    case "text-delta":

    process.stdout.write(part.textDelta);

    break;

    case "tool-call":

    console.log(\nCalling tool: ${part.toolName});

    break;

    case "tool-result":

    console.log(Tool result: ${JSON.stringify(part.result)});

    break;

    }

    }

    }

    Multi-Agent Collaboration

    Mastra enables multiple agents to work together:

    import { Agent } from "@mastra/core/agent";
    

    import { openai } from "@ai-sdk/openai";

    import { createTool } from "@mastra/core/tools";

    import { z } from "zod";

    const researchAgent = new Agent({

    name: "Researcher",

    instructions: "You are a researcher skilled at gathering and analyzing information.",

    model: openai("gpt-4o"),

    });

    const writerAgent = new Agent({

    name: "Writer",

    instructions: "You are a professional content writer producing high-quality articles.",

    model: openai("gpt-4o"),

    });

    const reviewerAgent = new Agent({

    name: "Reviewer",

    instructions: "You are an editor who reviews and improves writing quality.",

    model: openai("gpt-4o"),

    });

    async function createArticle(topic: string) {

    // Step 1: Research

    const research = await researchAgent.generate(

    Conduct in-depth research about: ${topic}.

    Provide key points and supporting data.

    );

    // Step 2: Writing

    const draft = await writerAgent.generate(

    Based on the following research, write a complete article:

    ${research.text}

    );

    // Step 3: Review

    const finalArticle = await reviewerAgent.generate(

    Review and improve the following article. Ensure it is accurate,

    clear, and engaging:

    ${draft.text}

    );

    return finalArticle.text;

    }

    Deployment and Production

    Running as an HTTP Server

    // src/index.ts
    

    import { mastra } from "./mastra";

    const app = mastra.serve();

    // Server runs on port 4111 (default)

    // Available endpoints:

    // POST /api/agents/:agentId/generate

    // POST /api/agents/:agentId/stream

    // POST /api/workflows/:workflowId/execute

    Docker Deployment

    FROM node:20-slim
    
    

    WORKDIR /app

    COPY package.json ./

    RUN npm ci --only=production

    COPY . .

    RUN npm run build

    EXPOSE 4111

    CMD ["node", "dist/index.js"]

    Environment Variables for Production

    # .env.production
    

    NODEENV=production

    OPENAIAPIKEY=sk-prod-key

    DATABASEURL=postgresql://user:pass@host:5432/mastra

    MASTRALOGLEVEL=warn

    Best Practices

    1. Design Clear Agent Instructions

    // Good - specific and structured instructions
    

    const agent = new Agent({

    name: "SupportAgent",

    instructions: You are a customer support agent for an online store.

    Guidelines:

    • Answer questions about products, shipping, and returns
    • If the question is out of scope, redirect to the relevant team
    • Always ask for the order number for order-related queries
    • Use polite and professional language

    Limitations:

    • Do not offer discounts without supervisor approval
    • Do not share internal company information,
    model: openai("gpt-4o"),

    });

    2. Proper Error Handling

    const robustTool = createTool({
    

    id: "api-call",

    description: "Calls an external API",

    inputSchema: z.object({ endpoint: z.string() }),

    execute: async ({ context }) => {

    try {

    const response = await fetch(context.endpoint, {

    signal: AbortSignal.timeout(5000),

    });

    if (!response.ok) {

    return { error: API returned ${response.status}, data: null };

    }

    return { error: null, data: await response.json() };

    } catch (error) {

    return {

    error: error instanceof Error ? error.message : "Unknown error",

    data: null,

    };

    }

    },

    });

    3. Use Zod Schemas for Validation

    Always define input and output schemas using Zod. This ensures type safety and provides clear descriptions to the LLM about expected parameters.

    4. Monitoring and Logging

    import { Mastra } from "@mastra/core";
    

    import { createLogger } from "@mastra/core/logger";

    const mastra = new Mastra({

    agents: { / ... */ },

    logger: createLogger({

    name: "Production",

    level: process.env.NODE_ENV === "production" ? "warn" : "debug",

    }),

    });

    5. Rate Limiting and Caching

    Implement rate limiting on tools that call external APIs, and use caching for frequently repeated queries. This saves API costs and improves application performance.

    Conclusion

    Mastra provides a solid foundation for building AI applications with TypeScript. With features like the agent framework, workflow engine, RAG pipeline, and memory management, you can build complex AI applications with clean, well-structured code.

    The key advantage of Mastra is its TypeScript-first approach with strong type safety, seamless integration with various LLM providers through the Vercel AI SDK, and flexible deployment options both as an HTTP server and in containers.

    For next steps, you can:

    • Explore the official Mastra documentation for advanced features
    • Try integrating with various vector databases for RAG
    • Build more complex multi-agent systems
    • Implement evaluation and testing for your agents
    • Join the Mastra community to share experiences and best practices

    Related Articles

    Complete Dify Tutorial: Open-Source Platform for Building AI Applications

    Tutorial Lengkap Dify: Platform Open-Source untuk Membangun Aplikasi AI Dify adalah platform open-source yang memungkink...

    Complete Griptape Tutorial: Python Framework for Building AI Agents and Pipelines

    Tutorial Lengkap Griptape: Framework Python untuk Membangun AI Agent dan Pipeline Griptape adalah framework open-source ...

    Complete Tavily Tutorial: AI Search API for RAG and AI Agents

    Tutorial Lengkap Tavily: AI Search API untuk RAG dan AI Agents Tavily adalah search API yang dirancang khusus untuk apli...

    LangChain Tutorial: The Most Popular Framework for Building LLM Applications

    Tutorial LangChain: Framework Paling Populer untuk Membangun Aplikasi LLM LangChain adalah framework open-source yang di...