Skip to content

Mastra - TypeScript AI Agent Framework Cheatsheet

Mastra - TypeScript AI Agent Framework Cheatsheet

Mastra is an open-source TypeScript framework for AI agents and workflows, built by the team behind Gatsby. Where most agent frameworks are Python-first, Mastra targets the JavaScript/TypeScript ecosystem with full type safety: typed agents with tools and memory, durable workflows expressed as graphs with branching and suspend/resume, RAG primitives, built-in evals, and a local dev playground for iterating on agents in the browser.

Installation

MethodCommand
Create a projectnpm create mastra@latest
Add to existingnpm install @mastra/core
Dev servernpm run dev (playground at localhost:4111)
Model providernpm install @ai-sdk/openai (uses Vercel AI SDK)
Verifyopen the playground

Defining an Agent

import { Agent } from "@mastra/core/agent";
import { openai } from "@ai-sdk/openai";

export const supportAgent = new Agent({
  name: "support",
  instructions: "You are a concise support agent. Cite docs when possible.",
  model: openai("gpt-4o"),
  tools: { searchDocs },
});

const result = await supportAgent.generate("How do I rotate my API key?");
console.log(result.text);
MethodDoes
.generate(input)Run once and return the result
.stream(input)Stream tokens/steps
toolsTyped tools the agent may call
memoryPersistent conversation memory

Tools

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

export const searchDocs = createTool({
  id: "search-docs",
  description: "Search the product documentation",
  inputSchema: z.object({ query: z.string() }),
  outputSchema: z.object({ results: z.array(z.string()) }),
  execute: async ({ context }) => {
    return { results: await search(context.query) };
  },
});

Zod schemas give end-to-end type safety — the agent’s tool calls are validated and typed on both sides.

Workflows (Durable Graphs)

import { createWorkflow, createStep } from "@mastra/core/workflows";

const fetchData = createStep({ id: "fetch", execute: async () => ({ ... }) });
const analyze   = createStep({ id: "analyze", execute: async ({ inputData }) => ({ ... }) });

export const pipeline = createWorkflow({ id: "pipeline" })
  .then(fetchData)
  .then(analyze)
  .commit();
FeaturePurpose
.then()Sequential steps
.branch()Conditional paths
.parallel()Concurrent steps
.dowhile() / .foreach()Loops over data
Suspend/resumePause for human input, resume later
Durable executionSurvives restarts

Memory

TypeUse
Conversation historyRecent turns in context
Semantic recallVector search over past messages
Working memoryPersistent facts about the user
Storage adaptersLibSQL, Postgres, Upstash

RAG Primitives

PieceProvides
Document chunkingSplit docs with configurable strategies
EmbeddingsVia the AI SDK providers
Vector storespgvector, Pinecone, Qdrant, Chroma
Retrieval toolWire retrieval into an agent as a tool

Evals & Observability

CapabilityNote
Built-in evalsAnswer relevancy, faithfulness, toxicity, bias
Custom scorersDefine your own metrics
TracingOpenTelemetry-compatible traces
PlaygroundInspect agent runs, tools, and memory locally

Deployment

TargetNote
Node servermastra build produces a deployable server
Vercel / Cloudflare / NetlifyOfficial deployers
ServerlessWorkflows designed for stateless hosts

Mastra vs Other Agent Frameworks

AspectMastraLangGraphCrewAI
LanguageTypeScriptPythonPython
WorkflowsDurable graph + suspend/resumeStateful graphRole-based crews
Type safetyStrong (Zod end-to-end)Python typingPython typing
Best forTS/JS teams, web appsComplex stateful agentsMulti-agent role play

The TypeScript counterpart to LangGraph; compare with CrewAI and AutoGen for Python.

Resources