Mastra

Open-source TypeScript framework for AI agents and applications: agents with a provider/model router, typed suspendable workflows, layered memory, processors as guardrails, scorers for evals, and a local Studio, deployable into existing Node servers.

Contents

Mastra is an open-source TypeScript framework for building AI agents and agent-powered applications. One package gives you agents with tools, graph-style workflows, memory, RAG, evals (called “scorers”), observability and a local developer UI (Studio) (docs). Version 1.0 went stable on 2026-01-20. At that point it reported over 300k weekly npm downloads and production users including Replit, PayPal and Sanity (1.0 announcement). By 2026-11-12 @mastra/core had reached 1.83.0 (repo). Most code is Apache 2.0; anything under an ee/ directory is under a separate enterprise licence (repo). Mastra is to TypeScript roughly what LangChain plus LangGraph is to Python: an opinionated, batteries-included layer above a model SDK. It is compatible with Vercel AI SDK v6 models (1.0 announcement).

Architecture

flowchart TD
  M["Mastra instance (registry: agents, workflows, scorers, storage, logger)"] --> A["Agent: instructions + model router + tools + memory"]
  M --> W["Workflow: createStep -> createWorkflow -> commit"]
  M --> S["Storage (LibSQL, Postgres, ...; composite per domain)"]
  A --> P["Input / output / error processors"]
  A --> MEM["Memory: history, working memory, semantic recall, observational"]
  A --> SUB["Subagents (called as tools)"]
  W --> A
  M --> SRV["Server: mastra build, or Express/Hono/Fastify/Koa adapters"]
  M --> ST["Studio + observability + scorers"]

Synthesis: assembled from the agents, workflows, memory, processors and 1.0 pages listed in Sources.

Everything registers on a central new Mastra({ agents, workflows, scorers, storage }). The docs tell you to fetch agents and workflows from the instance (mastra.getAgentById, mastra.getWorkflow) rather than importing them directly. Only registered primitives get shared storage, logging, full type inference, and persisted scores (docs, workflows, evals).

Agents

An Agent has id, name, instructions, a model and a tools map (docs):

  • Model router. Models are provider/model strings, and each provider reads its own API-key environment variable, so you need no provider import. model, instructions and tools can also be functions of the per-request RequestContext. That lets you pick the model by tenant, or inject instructions per user.
  • Tools. Built with createTool({ id, description, inputSchema, outputSchema?, execute }) using Zod or another Standard Schema library. Plain objects won’t execute. In 1.0, execute takes (inputData, context) (1.0 announcement). Agent-level hooks.beforeToolCall / afterToolCall intercept calls.
  • Loop. generate() waits for the whole tool loop and returns text, toolCalls, toolResults, steps and usage. stream() exposes textStream, with the same fields as promises (docs). See agent loop and streaming.
  • Supervisor / subagents. Put agents in the agents map (from 1.8.0). The supervisor calls them as tools, choosing among them by their description. Each delegation gets a fresh thread. messageFilter controls how much of the parent’s context the subagent sees. onDelegationStart / onDelegationComplete hooks can approve, rewrite or replace a delegation. A subagent’s step budget is capped at its own maxSteps default, so the supervisor can’t raise it (supervisor docs). See subagents.

Processors (middleware and guardrails)

Processors are Mastra’s hook system around the loop (processors):

HookRunsTypical use
processInputonce, before the first model callPII redaction, prompt-injection check
processInputStepbefore every loop stepswap model or tools mid-loop, trim context
processLLMRequest / processLLMResponsearound each provider calltransient prompt rewrites, cache writes
processOutputStreamper streamed chunkdrop or redact chunks
processOutputStep / processOutputResultafter each step / at the endvalidate and request a retry, transform final output
processAPIErroron provider errorrepair and retry

Built-ins include ModerationProcessor (content moderation), PromptInjectionDetector, PIIDetector, TokenLimiter, ToolCallFilter, ToolSearchProcessor and TokenCostControl. abort() raises a tripwire, which reaches clients as a tripwire stream chunk or result.tripwire. Step retries only happen if maxProcessorRetries is set (processors). See agent guardrails and guardrail tooling.

Workflows

Workflows are typed graphs. You define steps with createStep({ id, inputSchema, outputSchema, execute }), compose them with createWorkflow(...).then(...) and other control-flow methods, and finalise with .commit(). Steps can call agents or tools, nested workflows can be used as steps, and a stateSchema gives shared state that survives suspend and resume (workflows).

  • Runs. createRun() then start() or stream(). The result status is success, failed, suspended, tripwire or paused. A suspended run exposes a suspendPayload, and resumeStream({ resumeData }) continues it. This is the hook for human-in-the-loop steps.
  • Crash recovery. Runs are persisted and hold a storage lease. On boot, restartAllActiveWorkflowRuns() restarts unfinished runs from their last active step. A restarted step may run twice, so side-effecting steps need idempotency keys built from runId, workflowId and the step id. Recovery concurrency defaults to 5 (workflows). See durable agent execution.

Memory

Memory combines four mechanisms, scoped by resource (a user or entity) and thread (a conversation) (memory):

MechanismWhat it injectsDefault scope
Message historylast N messages (lastMessages, 10 by default since 1.0)thread
Working memorypersistent structured facts as a system messageresource
Semantic recallvector-retrieved past messages (off by default since 1.0)resource
Observational Memorybackground-agent “observations” and “reflections” replacing old messagesthread

Sources: memory, 1.0 defaults. Memory needs a storage adapter. Semantic recall also needs a vector store and an embedder. Since 1.0, MastraCompositeStore can put memory, workflows and scores on different backends (1.0 announcement). Observational Memory is a form of continuous context engineering compaction. See agent memory.

Evals and observability

Scorers (@mastra/evals) attach to agents or workflow steps. Each is configured as { scorer, sampling: { type: 'ratio', rate } } and samples live traffic deterministically by trace ID. Offline, runEvals() and dataset experiments run an agent or workflow over versioned test cases. Studio lists scores along with judge reasons (evals). Scores persist only if storage is configured and the scorer is registered on Mastra. The 1.0 observability schema exports to Langfuse, Braintrust, Arize and LangSmith (1.0 announcement). See agent evaluation and LLM observability.

Comparison

MastraVercel AI SDKLangGraphOpenAI Agents SDK / Claude Agent SDK
LanguageTypeScriptTypeScriptPython, JSPython, TS
LayerFull app framework (agents, workflows, memory, evals, server, UI)Model/agent toolkit (ToolLoopAgent, WorkflowAgent)Low-level state graph + checkpointerVendor-centred agent loop
Durable statePersisted workflow runs, suspend/resume, restart on bootWorkflowAgent persistenceCheckpointers, interruptsSessions
MemoryBuilt-in 4-tier memoryBring your ownStore + checkpointerSessions
EvalsBuilt-in scorers, datasetsExternalLangSmithVendor tracing

Sources: Mastra pages above, AI SDK docs, LangGraph persistence, OpenAI Agents SDK docs, Claude Agent SDK overview. Synthesis: pick the AI SDK when you want primitives and will assemble memory, evals and workflows yourself. Pick Mastra when you want them integrated, with one registry and one Studio, and accept its abstractions and release cadence.

Limitations and failure modes

  • Very fast release cadence. There were 83 minor versions in about ten months after 1.0 (repo), and 1.0 itself renamed core APIs (RuntimeContext became RequestContext, .get* became .list*) (1.0 announcement). Pin versions and read changelogs.
  • Silent degradations. Observational Memory silently turns off on unsupported storage adapters. Its lock only works within one process, so multi-instance deployments need a shared PubSub. Background buffering loses work unless you await memory.settled() (memory). Unregistered scorers drop their scores with only a warning (evals).
  • Memory scoping bugs. Resource-scoped working memory and recall are shared across a user’s threads by default. Reusing a thread ID across resources causes errors (memory). Get resource/thread from authenticated identity, never from client input. See PII and data privacy.
  • Replayed side effects. Workflow recovery can re-run steps, so you need idempotency (workflows).
  • Subagent limits. Subagents can’t run client-side tools, and their tool results are hidden from the parent unless you opt in (supervisor docs).
  • Licensing nuance. Enterprise modules under ee/ (auth, the editor) are not Apache 2.0 (repo). Check them before embedding Mastra in a product.

When to use it, and when not

  • Use it for TypeScript/Node teams that want an integrated stack: agents in a Next.js or Express app, persisted human-approval workflows, built-in memory and evals, and a local Studio for debugging. It fits FDE-style prototypes that must grow into production services without changing language.
  • Don’t use it for Python or .NET estates (use LangGraph, Pydantic AI or Microsoft Agent Framework), for thin single-vendor loops (use the vendor SDK), or when you only need streaming chat plus a few tools (use the Vercel AI SDK alone).

Sources

Suggest changes →