AgDex
Framework Comparison TypeScript July 2026 · 18 min read

Mastra vs Vercel AI SDK vs LangGraph.js: Best TypeScript AI Agent Frameworks in 2026

For years, building production AI agents meant writing Python—even if your entire stack ran on Node.js. In 2026, the TypeScript AI ecosystem has finally grown up. Three frameworks now dominate the landscape, each solving a fundamentally different problem. This guide breaks down Mastra, Vercel AI SDK, and LangGraph.js so you can pick the right one without wasting a sprint.

1. TL;DR — The Decision Matrix

💡 Quick Answer

Building a chatbot or streaming UI?Vercel AI SDK.
Building a full-stack agent product?Mastra.
Building mission-critical, stateful workflows?LangGraph.js.

These three frameworks are not interchangeable. They operate at different layers of the agentic stack. The diagram below shows exactly where each one sits:

2. The 2026 TypeScript AI Landscape

Two years ago, if you wanted to build an AI agent, Python was the only serious option. LangChain, AutoGen, CrewAI — the entire tooling ecosystem was built for pip install. TypeScript developers were stuck with thin wrappers, incomplete ports, or writing raw OpenAI API calls by hand.

That era is over. Three forces converged to create a first-class TypeScript AI ecosystem:

  • The MCP standard — the Model Context Protocol gave TypeScript servers a standardized way to expose tools — think of it as a "USB-C port for AI agents." Before MCP, every framework had its own proprietary adapter format. Now, a tool written once can be consumed by any MCP-compatible agent, eliminating the cross-framework integration tax entirely.
  • Zod + structured outputs — Zod schemas became the universal contract for type-safe tool definitions, enabling compile-time validation of agent behavior.
  • Production demand — enterprise teams shipping Next.js and Node.js backends needed agent orchestration that lived in the same runtime, same monorepo, same CI/CD pipeline.

The result? Three distinct frameworks, each purpose-built for a different slice of the AI agent problem space. Let's examine each one.

3. Vercel AI SDK — The UI-First Standard

The Vercel AI SDK (now at v7.x) is the most widely installed TypeScript AI package. It is not an agent framework in the traditional sense — it's a model-agnostic interface layer that excels at connecting LLMs to user interfaces with minimal friction.

Core Strengths

  • Streaming-first: Native SSE transport with real-time token streaming. The useChat and useCompletion hooks work across React, Vue, Svelte, and Angular.
  • Model-agnostic: Swap between OpenAI, Anthropic, Google Gemini, Mistral, or local Ollama models with a single import change — zero refactoring.
  • Type-safe tool calling: Tools are defined with inputSchema / outputSchema via Zod. Tool input parameters stream automatically, allowing live UI updates as the model "thinks."
  • Agentic loops: The maxSteps and stopWhen controls let you run multi-turn tool-calling loops without building your own orchestration layer.

Where It Falls Short

  • No built-in persistent memory or RAG pipeline.
  • No workflow engine for multi-step, branching logic.
  • No observability dashboard — you need to wire your own tracing (e.g., OpenTelemetry).

⚠️ When NOT to Use

If your agent needs durable state, complex branching, or cross-session memory, the Vercel AI SDK alone won't cut it. It's a transport layer, not an orchestrator. Pair it with Mastra or LangGraph.js for those use cases.

4. Mastra — The Batteries-Included Contender

Mastra, built by the team behind Gatsby, is the 2026 breakout star. It's an opinionated, "batteries-included" TypeScript framework that bundles agents, workflows, RAG, memory, evals, and an observability studio into a single cohesive package.

Critically, Mastra doesn't reinvent the LLM layer. It uses the Vercel AI SDK internally for all model interactions, which means you get the same model-agnostic, streaming-first interface — plus everything else on top.

Core Strengths

  • Agents + Workflows in one place: Agents handle autonomous LLM reasoning loops; Workflows provide deterministic, graph-based pipelines for multi-step business logic. Both coexist in the same project.
  • Native MCP support: Mastra can act as both an MCP client (consuming external tools) and an MCP server (exposing your agents as standardized endpoints).
  • Memory gateway: Persistent context across sessions — from simple message history to vector-based semantic recall — built in.
  • Mastra Studio: A local debugging environment where you can chat with agents, visualize workflow execution traces, and tune settings in real-time.
  • Mastra Server: Exposes agents and workflows as production API endpoints with authentication, middleware, and streaming out of the box.

Where It Falls Short

  • Younger ecosystem — fewer community integrations compared to LangChain/LangGraph.
  • Opinionated design may feel constraining for teams with existing orchestration patterns.
  • Durable execution (surviving server crashes mid-workflow) is not as battle-tested as LangGraph's checkpointing.

💡 Key Insight

Think of Mastra as "Next.js for AI agents." It gives you sensible defaults, a dev server, and a clear path from prototype to production — at the cost of some flexibility.

5. LangGraph.js — The State Machine Powerhouse

LangGraph.js is the TypeScript implementation of LangGraph, LangChain's low-level orchestration framework. It models agent workflows as directed state graphs — nodes represent logic, edges represent transitions, and a strongly typed state object flows through the entire graph.

In 2026, LangGraph.js has reached full feature parity with its Python counterpart, making it the go-to choice for teams that need surgical control over every decision point in their agent's execution.

Core Strengths

  • Durable execution: Every state transition is automatically checkpointed to storage (PostgresSaver for production). Agents survive server restarts and resume exactly where they left off.
  • Human-in-the-loop (HITL): First-class interrupt() support allows agents to pause for human approval, then resume seamlessly.
  • Time-travel debugging: Load any historical checkpoint to replay executions, diagnose failures, or branch off to test alternative inputs.
  • Cycles and subgraphs: Natively supports loops (self-reflection, retry patterns) and modular subgraphs for decomposing complex agents.
  • LangSmith integration: Deep observability with trace visualization, step-by-step debugging, and token usage analytics.

Where It Falls Short

  • Steeper learning curve — modeling everything as a graph requires upfront architectural thinking.
  • No built-in UI components or streaming hooks. You need to pair it with the Vercel AI SDK or another UI layer.
  • Tighter coupling to the LangChain ecosystem (LangSmith, LangServe) may concern teams worried about vendor lock-in.

6. Code Comparison: Build a Tool-Calling Agent

Let's build the same simple agent in all three frameworks: an agent that has access to a getWeather tool and can answer questions about the weather.

Vercel AI SDK

typescript — agent.ts
import { openai } from "@ai-sdk/openai";
import { generateText, tool } from "ai";
import { z } from "zod";

const result = await generateText({
 model: openai("gpt-4o"),
 prompt: "What's the weather in Tokyo?",
 tools: {
  getWeather: tool({
   description: "Get weather for a city",
   parameters: z.object({
    city: z.string().describe("City name"),
   }),
   execute: async ({ city }) => {
    // Call your weather API here
    return { city, temp: "22°C", condition: "Sunny" };
   },
  }),
 },
 maxSteps: 5, // Allow multi-turn tool-calling loop
});

Mastra

typescript — agent.ts
import { Agent, createTool } from "@mastra/core";
import { openai } from "@ai-sdk/openai";
import { z } from "zod";

const getWeather = createTool({
 id: "getWeather",
 description: "Get weather for a city",
 inputSchema: z.object({
  city: z.string().describe("City name"),
 }),
 outputSchema: z.object({
  city: z.string(),
  temp: z.string(),
  condition: z.string(),
 }),
 execute: async ({ context }) => {
  return { city: context.city, temp: "22°C", condition: "Sunny" };
 },
});

const weatherAgent = new Agent({
 name: "Weather Agent",
 instructions: "You answer weather questions accurately.",
 model: openai("gpt-4o"),
 tools: { getWeather },
});

const response = await weatherAgent.generate(
 "What's the weather in Tokyo?"
);

LangGraph.js

typescript — agent.ts
import { StateGraph, Annotation, END } from "@langchain/langgraph";
import { ChatOpenAI } from "@langchain/openai";
import { ToolNode } from "@langchain/langgraph/prebuilt";
import { tool } from "@langchain/core/tools";
import { z } from "zod";
import { MemorySaver } from "@langchain/langgraph";

// 1. Define your tool
const getWeather = tool(
 async ({ city }) => {
  return JSON.stringify({ city, temp: "22°C", condition: "Sunny" });
 },
 { name: "getWeather", description: "Get weather for a city",
  schema: z.object({ city: z.string() }) }
);

// 2. Define state schema
const AgentState = Annotation.Root({
 messages: Annotation({ reducer: (a, b) => a.concat(b) }),
});

// 3. Define nodes
const model = new ChatOpenAI({ model: "gpt-4o" }).bindTools([getWeather]);
const callModel = async (state) => {
 const response = await model.invoke(state.messages);
 return { messages: [response] };
};

// 4. Build the graph: nodes → edges → compile
const graph = new StateGraph(AgentState)
 .addNode("agent", callModel)
 .addNode("tools", new ToolNode([getWeather]))
 .addEdge("__start__", "agent")
 .addConditionalEdges("agent", (state) => {
  const last = state.messages[state.messages.length - 1];
  return last.tool_calls?.length ? "tools" : END;
 })
 .addEdge("tools", "agent")
 .compile({ checkpointer: new MemorySaver() });

const result = await graph.invoke(
 { messages: [{ role: "user", content: "What's the weather in Tokyo?" }] },
 { configurable: { thread_id: "session-1" } }
);

💡 Notice the Difference

Vercel AI SDK is the leanest — one function call, no classes, no ceremony.
Mastra introduces an Agent class with typed tools and output schemas.
LangGraph.js reveals its power: you explicitly define nodes, edges, and conditionalEdges — giving you surgical control over every state transition, with automatic checkpointing baked in.

7. Deep Feature Comparison

Feature Vercel AI SDK Mastra LangGraph.js
Primary Use Case Chat UIs & streaming Full-stack agent apps Stateful orchestration
Model Support 20+ providers 20+ (via AI SDK) 10+ (via LangChain)
Tool Calling
Zod schemas
Zod schemas Zod schemas
MCP Support Client Client + Server ⚠️Via adapters
Persistent Memory Built-in Checkpointing
RAG Pipeline Built-in ⚠️Via LangChain
Workflow Engine ⚠️Basic Graph-based State graphs
Human-in-the-Loop ⚠️Manual interrupt()
Observability ⚠️DIY (OTel) Mastra Studio LangSmith
Durable Execution ⚠️Early stage Battle-tested
Best Runtime Serverless / Edge Node.js Server Containerized Node.js
License Apache 2.0 Elastic License v2 MIT

💡 Pro Tip: They're Not Mutually Exclusive

Many production teams use Vercel AI SDK for the frontend (streaming, hooks) and LangGraph.js or Mastra on the backend (orchestration, memory). The frameworks are designed to complement each other, not compete.

9. The Verdict

The TypeScript AI agent ecosystem in 2026 is no longer playing catch-up with Python. It's offering something Python can't: end-to-end type safety from your model calls to your React components, in a single runtime, a single monorepo, and a single deployment pipeline.

The right choice depends entirely on your architecture:

  • Vercel AI SDK is the transport layer. If you're building a chat product and need streaming, model-switching, and UI hooks — start here. You'll likely use it regardless of which orchestration framework you choose.
  • Mastra is the application framework. If you're building a full agent product and want agents, workflows, memory, and an observability studio out of the box — Mastra is the fastest path from zero to production.
  • LangGraph.js is the orchestration engine. If your workflows are complex, long-running, and must survive failures — LangGraph's durable state graphs and battle-tested checkpointing are unmatched.

Whatever you choose, avoid tightly coupling your business logic to framework-specific APIs. Build your tools as pure functions with Zod schemas, and you'll be able to migrate between any of these frameworks with minimal friction.

Comparación de frameworks TypeScript Julio 2026 · 18 min de lectura

Mastra vs Vercel AI SDK vs LangGraph.js: Los mejores frameworks de agentes de IA de TypeScript en 2026

Durante años, construir agentes de IA en producción significaba escribir en Python, incluso si todo tu stack corría en Node.js. En 2026, el ecosistema de IA en TypeScript finalmente ha madurado. Tres frameworks dominan ahora el panorama, cada uno resolviendo un problema fundamentalmente diferente. Esta guía desglosa Mastra, Vercel AI SDK y LangGraph.js para que puedas elegir el adecuado sin desperdiciar un sprint.

1. TL;DR — La matriz de decisión

💡 Respuesta rápida

¿Construyendo un chatbot o una interfaz con streaming?Vercel AI SDK.
¿Construyendo un producto de agentes full-stack?Mastra.
¿Construyendo flujos de trabajo con estado de misión crítica?LangGraph.js.

2. El panorama de la IA en TypeScript en 2026

  • El estándar MCP — el Model Context Protocol dio a los servidores de TypeScript una forma estandarizada de exponer herramientas — piénsalo como un "puerto USB-C para agentes de IA". Antes de MCP, cada framework tenía su propio formato de adaptador propietario. Ahora, una herramienta escrita una vez puede ser consumida por cualquier agente compatible con MCP, eliminando por completo el coste de integración entre frameworks.
  • Zod + salidas estructuradas — Los esquemas de Zod se convirtieron en el contrato universal para definiciones de herramientas seguras en tipos, permitiendo la validación en tiempo de compilación del comportamiento del agente.
  • Demanda de producción — Los equipos empresariales que lanzaban backends en Next.js y Node.js necesitaban orquestación de agentes que viviera en el mismo entorno de ejecución (runtime), el mismo monorepo y el mismo pipeline de CI/CD.

3. Vercel AI SDK — El estándar centrado en la UI

Fortalezas principales

  • Streaming como prioridad (Streaming-first): Transporte SSE nativo con streaming de tokens en tiempo real. Los hooks useChat y useCompletion funcionan en React, Vue, Svelte y Angular.
  • Independiente del modelo: Cambia entre OpenAI, Anthropic, Google Gemini, Mistral o modelos locales de Ollama con un solo cambio de importación — cero refactorización.
  • Llamado de herramientas con seguridad de tipos (Type-safe tool calling): Las herramientas se definen con inputSchema / outputSchema a través de Zod. Los parámetros de entrada de la herramienta se transmiten automáticamente, permitiendo actualizaciones de la UI en vivo mientras el modelo "piensa".
  • Bucles agénticos (Agentic loops): Los controles maxSteps y stopWhen te permiten ejecutar bucles de llamadas a herramientas de múltiples turnos sin construir tu propia capa de orquestación.

Dónde se queda corto

  • Sin memoria persistente incorporada ni pipeline RAG.
  • Sin motor de flujos de trabajo (workflow engine) para lógica ramificada de múltiples pasos.
  • Sin panel de observabilidad — necesitas configurar tu propio rastreo (ej., OpenTelemetry).

⚠️ Cuándo NO usarlo

Si tu agente necesita estado duradero, ramificaciones complejas o memoria entre sesiones, el Vercel AI SDK por sí solo no será suficiente. Es una capa de transporte, no un orquestador. Combínalo con Mastra o LangGraph.js para esos casos de uso.

4. Mastra — El competidor con todo incluido

Fortalezas principales

  • Agentes + Flujos de trabajo (Workflows) en un solo lugar: Los agentes manejan bucles de razonamiento autónomos de los LLM; los flujos de trabajo proporcionan pipelines deterministas basados en grafos para la lógica de negocio de múltiples pasos. Ambos coexisten en el mismo proyecto.
  • Soporte nativo MCP: Mastra puede actuar tanto como un cliente MCP (consumiendo herramientas externas) como un servidor MCP (exponiendo tus agentes como endpoints estandarizados).
  • Gateway de memoria: Contexto persistente entre sesiones — desde un simple historial de mensajes hasta recuperación semántica basada en vectores — integrado.
  • Mastra Studio: Un entorno de depuración local donde puedes chatear con los agentes, visualizar las trazas de ejecución del flujo de trabajo y ajustar la configuración en tiempo real.
  • Mastra Server: Expone agentes y flujos de trabajo como endpoints de API en producción con autenticación, middleware y streaming listos para usar (out of the box).

Dónde se queda corto

  • Ecosistema más joven — menos integraciones de la comunidad en comparación con LangChain/LangGraph.
  • Su diseño estricto (opinionated) puede sentirse restrictivo para equipos con patrones de orquestación ya existentes.
  • La ejecución duradera (sobrevivir a caídas del servidor a mitad de un flujo de trabajo) no está tan probada en batalla como el sistema de checkpoints de LangGraph.

💡 Conclusión clave

Piensa en Mastra como "Next.js para agentes de IA". Te da configuraciones predeterminadas sensatas, un servidor de desarrollo y un camino claro desde el prototipo a producción — a costa de cierta flexibilidad.

5. LangGraph.js — La potencia de las máquinas de estado

Fortalezas principales

  • Ejecución duradera: Cada transición de estado se guarda automáticamente en un checkpoint en el almacenamiento (PostgresSaver para producción). Los agentes sobreviven a reinicios del servidor y se reanudan exactamente donde se quedaron.
  • Humano en el bucle (Human-in-the-loop o HITL): Soporte de primera clase para interrupt() que permite a los agentes pausar para obtener aprobación humana y luego reanudarse sin problemas.
  • Depuración con viaje en el tiempo (Time-travel debugging): Carga cualquier checkpoint histórico para reproducir ejecuciones, diagnosticar fallos o crear ramas para probar entradas alternativas.
  • Ciclos y subgrafos: Soporta de forma nativa bucles (auto-reflexión, patrones de reintento) y subgrafos modulares para descomponer agentes complejos.
  • Integración con LangSmith: Observabilidad profunda con visualización de trazas, depuración paso a paso y análisis de uso de tokens.

Dónde se queda corto

  • Curva de aprendizaje más pronunciada — modelar todo como un grafo requiere pensamiento arquitectónico por adelantado.
  • Sin componentes de UI ni hooks de streaming integrados. Necesitas combinarlo con Vercel AI SDK u otra capa de UI.
  • El fuerte acoplamiento al ecosistema de LangChain (LangSmith, LangServe) puede preocupar a los equipos respecto a la dependencia del proveedor (vendor lock-in).

6. Comparación de código: Construyendo un agente que llama a herramientas

Vercel AI SDK

typescript — agent.ts
import { openai } from "@ai-sdk/openai";
import { generateText, tool } from "ai";
import { z } from "zod";

const result = await generateText({
 model: openai("gpt-4o"),
 prompt: "What's the weather in Tokyo?",
 tools: {
  getWeather: tool({
   description: "Get weather for a city",
   parameters: z.object({
    city: z.string().describe("City name"),
   }),
   execute: async ({ city }) => {
    // Call your weather API here
    return { city, temp: "22°C", condition: "Sunny" };
   },
  }),
 },
 maxSteps: 5, // Allow multi-turn tool-calling loop
});

Mastra

typescript — agent.ts
import { Agent, createTool } from "@mastra/core";
import { openai } from "@ai-sdk/openai";
import { z } from "zod";

const getWeather = createTool({
 id: "getWeather",
 description: "Get weather for a city",
 inputSchema: z.object({
  city: z.string().describe("City name"),
 }),
 outputSchema: z.object({
  city: z.string(),
  temp: z.string(),
  condition: z.string(),
 }),
 execute: async ({ context }) => {
  return { city: context.city, temp: "22°C", condition: "Sunny" };
 },
});

const weatherAgent = new Agent({
 name: "Weather Agent",
 instructions: "You answer weather questions accurately.",
 model: openai("gpt-4o"),
 tools: { getWeather },
});

const response = await weatherAgent.generate(
 "What's the weather in Tokyo?"
);

LangGraph.js

typescript — agent.ts
import { StateGraph, Annotation, END } from "@langchain/langgraph";
import { ChatOpenAI } from "@langchain/openai";
import { ToolNode } from "@langchain/langgraph/prebuilt";
import { tool } from "@langchain/core/tools";
import { z } from "zod";
import { MemorySaver } from "@langchain/langgraph";

// 1. Define your tool
const getWeather = tool(
 async ({ city }) => {
  return JSON.stringify({ city, temp: "22°C", condition: "Sunny" });
 },
 { name: "getWeather", description: "Get weather for a city",
  schema: z.object({ city: z.string() }) }
);

// 2. Define state schema
const AgentState = Annotation.Root({
 messages: Annotation({ reducer: (a, b) => a.concat(b) }),
});

// 3. Define nodes
const model = new ChatOpenAI({ model: "gpt-4o" }).bindTools([getWeather]);
const callModel = async (state) => {
 const response = await model.invoke(state.messages);
 return { messages: [response] };
};

// 4. Build the graph: nodes → edges → compile
const graph = new StateGraph(AgentState)
 .addNode("agent", callModel)
 .addNode("tools", new ToolNode([getWeather]))
 .addEdge("__start__", "agent")
 .addConditionalEdges("agent", (state) => {
  const last = state.messages[state.messages.length - 1];
  return last.tool_calls?.length ? "tools" : END;
 })
 .addEdge("tools", "agent")
 .compile({ checkpointer: new MemorySaver() });

const result = await graph.invoke(
 { messages: [{ role: "user", content: "What's the weather in Tokyo?" }] },
 { configurable: { thread_id: "session-1" } }
);

💡 Nota la diferencia

Vercel AI SDK es el más ligero — una llamada a función, sin clases, sin ceremonia.
Mastra introduce una clase Agent con herramientas tipadas y esquemas de salida.
LangGraph.js revela su poder: defines explícitamente nodes, edges, y conditionalEdges — dándote control quirúrgico sobre cada transición de estado, con creación de checkpoints automáticos integrada.

7. Comparación detallada de características

Característica Vercel AI SDK Mastra LangGraph.js
Caso de uso principal UIs de chat y streaming Apps de agentes full-stack Orquestación con estado
Soporte de modelos 20+ proveedores 20+ (vía AI SDK) 10+ (vía LangChain)
Llamado a herramientas
Esquemas Zod
Esquemas Zod Esquemas Zod
Soporte MCP Cliente Cliente + Servidor ⚠️Vía adaptadores
Memoria persistente Integrada Checkpoints
Pipeline RAG Integrada ⚠️Vía LangChain
Motor de flujos de trabajo ⚠️Básico Basado en grafos Grafos de estado
Humano en el bucle ⚠️Manual interrupt()
Observabilidad ⚠️Hágalo usted mismo (OTel) Mastra Studio LangSmith
Ejecución duradera ⚠️Etapa temprana Probado en batalla
Mejor entorno de ejecución (Runtime) Serverless / Edge Servidor Node.js Node.js en contenedores
Licencia Apache 2.0 Elastic License v2 MIT

💡 Consejo profesional: No son mutuamente excluyentes

Muchos equipos en producción usan Vercel AI SDK para el frontend (streaming, hooks) y LangGraph.js o Mastra en el backend (orquestación, memoria). Los frameworks están diseñados para complementarse, no para competir.

9. El veredicto

  • Vercel AI SDK es la capa de transporte. Si estás construyendo un producto de chat y necesitas streaming, cambio de modelos y hooks de UI — empieza por aquí. Es probable que lo uses sin importar qué framework de orquestación elijas.
  • Mastra es el framework de aplicaciones. Si estás construyendo un producto de agentes completo y quieres agentes, flujos de trabajo, memoria y un estudio de observabilidad listo para usar — Mastra es el camino más rápido desde cero hasta producción.
  • LangGraph.js es el motor de orquestación. Si tus flujos de trabajo son complejos, de larga duración y deben sobrevivir a fallos — los grafos de estado duradero de LangGraph y su sistema de checkpoints probado en batalla no tienen rival.
Framework-Vergleich TypeScript Juli 2026 · 18 Min. Lesezeit

Mastra vs Vercel AI SDK vs LangGraph.js: Die besten TypeScript AI Agent Frameworks 2026

Jahrelang bedeutete die Entwicklung produktionsreifer KI-Agenten, dass man Python schreiben musste – selbst wenn der gesamte Stack auf Node.js lief. Im Jahr 2026 ist das TypeScript-KI-Ökosystem endlich erwachsen geworden. Drei Frameworks dominieren nun die Landschaft, wobei jedes ein grundlegend anderes Problem löst. Dieser Leitfaden analysiert Mastra, Vercel AI SDK und LangGraph.js, damit Sie das richtige auswählen können, ohne einen Sprint zu verschwenden.

1. TL;DR — Die Entscheidungsmatrix

💡 Schnelle Antwort

Einen Chatbot oder eine Streaming-UI bauen?Vercel AI SDK.
Ein Full-Stack-Agenten-Produkt entwickeln?Mastra.
Unternehmenskritische, zustandsbehaftete Workflows erstellen?LangGraph.js.

2. Die TypeScript-KI-Landschaft 2026

  • Der MCP-Standard — das Model Context Protocol gab TypeScript-Servern eine standardisierte Möglichkeit, Tools bereitzustellen — denken Sie an einen "USB-C-Anschluss für KI-Agenten". Vor MCP hatte jedes Framework sein eigenes proprietäres Adapterformat. Jetzt kann ein einmal geschriebenes Tool von jedem MCP-kompatiblen Agenten genutzt werden, was die Integrationskosten zwischen Frameworks vollständig eliminiert.
  • Zod + strukturierte Ausgaben (Structured Outputs) — Zod-Schemas wurden zum universellen Vertrag für typsichere Tool-Definitionen, was die Validierung des Agentenverhaltens zur Compile-Zeit ermöglicht.
  • Produktionsnachfrage — Enterprise-Teams, die Next.js- und Node.js-Backends auslieferten, benötigten eine Agenten-Orchestrierung, die in derselben Runtime, demselben Monorepo und derselben CI/CD-Pipeline angesiedelt ist.

3. Vercel AI SDK — Der UI-First-Standard

Kernstärken

  • Streaming-first: Nativer SSE-Transport mit Echtzeit-Token-Streaming. Die useChat- und useCompletion-Hooks funktionieren über React, Vue, Svelte und Angular hinweg.
  • Modellunabhängig: Wechseln Sie zwischen OpenAI, Anthropic, Google Gemini, Mistral oder lokalen Ollama-Modellen mit einer einzigen Import-Änderung — null Refactoring.
  • Typsicheres Tool-Calling: Tools werden mit inputSchema / outputSchema via Zod definiert. Tool-Eingabeparameter werden automatisch gestreamt, was Live-UI-Updates ermöglicht, während das Modell "denkt".
  • Agenten-Schleifen: Die Steuerelemente maxSteps und stopWhen ermöglichen es Ihnen, Multi-Turn-Tool-Calling-Schleifen auszuführen, ohne Ihre eigene Orchestrierungsschicht aufbauen zu müssen.

Wo es Schwächen hat

  • Kein integriertes persistentes Memory oder RAG-Pipeline.
  • Keine Workflow-Engine für mehrstufige, verzweigte Logik.
  • Kein Observability-Dashboard — Sie müssen Ihr eigenes Tracing einrichten (z. B. OpenTelemetry).

⚠️ Wann man es NICHT nutzen sollte

Wenn Ihr Agent einen dauerhaften Zustand (Durable State), komplexe Verzweigungen oder sitzungsübergreifendes Memory benötigt, reicht das Vercel AI SDK allein nicht aus. Es ist eine Transportschicht, kein Orchestrator. Kombinieren Sie es für diese Anwendungsfälle mit Mastra oder LangGraph.js.

4. Mastra — Der All-Inclusive-Kandidat

Kernstärken

  • Agenten + Workflows an einem Ort: Agenten handhaben autonome LLM-Reasoning-Schleifen; Workflows bieten deterministische, graphenbasierte Pipelines für mehrstufige Geschäftslogik. Beides koexistiert im selben Projekt.
  • Nativer MCP-Support: Mastra kann sowohl als MCP-Client (Nutzung externer Tools) als auch als MCP-Server (Bereitstellung Ihrer Agenten als standardisierte Endpunkte) fungieren.
  • Memory-Gateway: Persistenter Kontext über Sitzungen hinweg — von einfachem Nachrichtenverlauf bis hin zu vektorbasierter semantischer Erinnerung — ist integriert.
  • Mastra Studio: Eine lokale Debugging-Umgebung, in der Sie mit Agenten chatten, Workflow-Ausführungs-Traces visualisieren und Einstellungen in Echtzeit optimieren können.
  • Mastra Server: Stellt Agenten und Workflows out-of-the-box als produktionsreife API-Endpunkte mit Authentifizierung, Middleware und Streaming bereit.

Wo es Schwächen hat

  • Jüngeres Ökosystem — weniger Community-Integrationen im Vergleich zu LangChain/LangGraph.
  • Das meinungsstarke Design könnte sich für Teams mit bestehenden Orchestrierungsmustern einschränkend anfühlen.
  • Dauerhafte Ausführung (Überstehen von Serverabstürzen mitten im Workflow) ist nicht so praxiserprobt wie das Checkpointing von LangGraph.

💡 Wichtige Erkenntnis

Stellen Sie sich Mastra als "Next.js für KI-Agenten" vor. Es bietet Ihnen sinnvolle Standardeinstellungen, einen Dev-Server und einen klaren Weg vom Prototyp in die Produktion — auf Kosten von etwas Flexibilität.

5. LangGraph.js — Das Zustandsautomaten-Kraftpaket

Kernstärken

  • Dauerhafte Ausführung (Durable Execution): Jeder Zustandsübergang wird automatisch in den Speicher geschrieben (Checkpointing via PostgresSaver in der Produktion). Agenten überleben Serverneustarts und setzen genau dort an, wo sie aufgehört haben.
  • Human-in-the-loop (HITL): Erstklassiger interrupt()-Support ermöglicht es Agenten, auf menschliche Freigabe zu warten und dann nahtlos fortzufahren.
  • Time-Travel-Debugging: Laden Sie einen beliebigen historischen Checkpoint, um Ausführungen erneut abzuspielen, Fehler zu diagnostizieren oder abzuzweigen, um alternative Eingaben zu testen.
  • Zyklen und Teilgraphen: Unterstützt nativ Schleifen (Self-Reflection, Retry-Muster) und modulare Teilgraphen (Subgraphs) zur Zerlegung komplexer Agenten.
  • LangSmith-Integration: Tiefe Observability mit Trace-Visualisierung, schrittweisem Debugging und Analytics zur Token-Nutzung.

Wo es Schwächen hat

  • Steilere Lernkurve — alles als Graphen zu modellieren, erfordert architektonisches Vorausdenken.
  • Keine integrierten UI-Komponenten oder Streaming-Hooks. Sie müssen es mit dem Vercel AI SDK oder einer anderen UI-Schicht kombinieren.
  • Eine engere Kopplung an das LangChain-Ökosystem (LangSmith, LangServe) könnte Teams beunruhigen, die Angst vor Vendor-Lock-in haben.

6. Code-Vergleich: Einen Tool-Calling-Agenten bauen

Vercel AI SDK

typescript — agent.ts
import { openai } from "@ai-sdk/openai";
import { generateText, tool } from "ai";
import { z } from "zod";

const result = await generateText({
 model: openai("gpt-4o"),
 prompt: "What's the weather in Tokyo?",
 tools: {
  getWeather: tool({
   description: "Get weather for a city",
   parameters: z.object({
    city: z.string().describe("City name"),
   }),
   execute: async ({ city }) => {
    // Call your weather API here
    return { city, temp: "22°C", condition: "Sunny" };
   },
  }),
 },
 maxSteps: 5, // Allow multi-turn tool-calling loop
});

Mastra

typescript — agent.ts
import { Agent, createTool } from "@mastra/core";
import { openai } from "@ai-sdk/openai";
import { z } from "zod";

const getWeather = createTool({
 id: "getWeather",
 description: "Get weather for a city",
 inputSchema: z.object({
  city: z.string().describe("City name"),
 }),
 outputSchema: z.object({
  city: z.string(),
  temp: z.string(),
  condition: z.string(),
 }),
 execute: async ({ context }) => {
  return { city: context.city, temp: "22°C", condition: "Sunny" };
 },
});

const weatherAgent = new Agent({
 name: "Weather Agent",
 instructions: "You answer weather questions accurately.",
 model: openai("gpt-4o"),
 tools: { getWeather },
});

const response = await weatherAgent.generate(
 "What's the weather in Tokyo?"
);

LangGraph.js

typescript — agent.ts
import { StateGraph, Annotation, END } from "@langchain/langgraph";
import { ChatOpenAI } from "@langchain/openai";
import { ToolNode } from "@langchain/langgraph/prebuilt";
import { tool } from "@langchain/core/tools";
import { z } from "zod";
import { MemorySaver } from "@langchain/langgraph";

// 1. Define your tool
const getWeather = tool(
 async ({ city }) => {
  return JSON.stringify({ city, temp: "22°C", condition: "Sunny" });
 },
 { name: "getWeather", description: "Get weather for a city",
  schema: z.object({ city: z.string() }) }
);

// 2. Define state schema
const AgentState = Annotation.Root({
 messages: Annotation({ reducer: (a, b) => a.concat(b) }),
});

// 3. Define nodes
const model = new ChatOpenAI({ model: "gpt-4o" }).bindTools([getWeather]);
const callModel = async (state) => {
 const response = await model.invoke(state.messages);
 return { messages: [response] };
};

// 4. Build the graph: nodes → edges → compile
const graph = new StateGraph(AgentState)
 .addNode("agent", callModel)
 .addNode("tools", new ToolNode([getWeather]))
 .addEdge("__start__", "agent")
 .addConditionalEdges("agent", (state) => {
  const last = state.messages[state.messages.length - 1];
  return last.tool_calls?.length ? "tools" : END;
 })
 .addEdge("tools", "agent")
 .compile({ checkpointer: new MemorySaver() });

const result = await graph.invoke(
 { messages: [{ role: "user", content: "What's the weather in Tokyo?" }] },
 { configurable: { thread_id: "session-1" } }
);

💡 Beachten Sie den Unterschied

Das Vercel AI SDK ist am schlanksten — ein Funktionsaufruf, keine Klassen, kein formeller Aufwand.
Mastra führt eine Agent-Klasse mit typisierten Tools und Output-Schemas ein.
LangGraph.js zeigt seine wahre Kraft: Sie definieren explizit nodes, edges und conditionalEdges — was Ihnen chirurgische Kontrolle über jeden Zustandsübergang gibt, inklusive automatischem Checkpointing.

7. Detaillierter Feature-Vergleich

Feature Vercel AI SDK Mastra LangGraph.js
Primärer Anwendungsfall Chat-UIs & Streaming Full-Stack-Agenten-Apps Zustandsbehaftete Orchestrierung
Modell-Support 20+ Anbieter 20+ (via AI SDK) 10+ (via LangChain)
Tool-Calling
Zod-Schemas
Zod-Schemas Zod-Schemas
MCP-Support Client Client + Server ⚠️Via Adapter
Persistentes Memory Integriert Checkpointing
RAG-Pipeline Integriert ⚠️Via LangChain
Workflow-Engine ⚠️Basis Graphenbasiert Zustandsgraphen
Human-in-the-Loop ⚠️Manuell interrupt()
Observability ⚠️DIY (OTel) Mastra Studio LangSmith
Dauerhafte Ausführung ⚠️Frühe Phase Praxiserprobt
Beste Runtime Serverless / Edge Node.js Server Containerisiertes Node.js
Lizenz Apache 2.0 Elastic License v2 MIT

💡 Profi-Tipp: Sie schließen sich nicht gegenseitig aus

Viele Produktionsteams nutzen das Vercel AI SDK für das Frontend (Streaming, Hooks) und LangGraph.js oder Mastra im Backend (Orchestrierung, Memory). Die Frameworks sind darauf ausgelegt, sich zu ergänzen, nicht zu konkurrieren.

9. Das Fazit

  • Das Vercel AI SDK ist die Transportschicht. Wenn Sie ein Chat-Produkt entwickeln und Streaming, Modellwechsel und UI-Hooks benötigen — beginnen Sie hier. Sie werden es wahrscheinlich ohnehin nutzen, unabhängig davon, für welches Orchestrierungs-Framework Sie sich entscheiden.
  • Mastra ist das Anwendungs-Framework. Wenn Sie ein vollständiges Agenten-Produkt bauen und Agenten, Workflows, Memory und ein Observability-Studio out-of-the-box haben möchten — Mastra ist der schnellste Weg von null in die Produktion.
  • LangGraph.js ist die Orchestrierungs-Engine. Wenn Ihre Workflows komplex und langlebig sind sowie Ausfälle überstehen müssen — LangGraphs robuste Zustandsgraphen und praxiserprobtes Checkpointing sind unübertroffen.
フレームワーク比較 TypeScript 2026年7月 · 読了18分

Mastra vs Vercel AI SDK vs LangGraph.js: 2026年のベストTypeScript AIエージェントフレームワーク

長年、本番用のAIエージェントを構築するとなると、スタック全体がNode.jsで動いていてもPythonを書く必要がありました。2026年、TypeScriptのAIエコシステムはようやく成熟しました。現在、3つのフレームワークが主流となっており、それぞれが根本的に異なる課題を解決しています。このガイドでは、無駄なスプリントを費やすことなく適切なものを選択できるように、MastraVercel AI SDK、そしてLangGraph.jsについて詳しく解説します。

1. TL;DR — 意思決定マトリクス

💡 簡単な回答

チャットボットやストリーミングUIを構築するなら?Vercel AI SDK。
フルスタックのエージェントプロダクトを構築するなら?Mastra。
ミッションクリティカルでステートフルなワークフローを構築するなら?LangGraph.js。

2. 2026年のTypeScript AIの状況

  • MCP標準Model Context Protocolにより、TypeScriptサーバーがツールを公開するための標準化された方法がもたらされました。これは「AIエージェント向けのUSB-Cポート」と考えることができます。MCP以前は、すべてのフレームワークが独自のプロプライエタリアダプタ形式を持っていました。現在では、一度書かれたツールはMCP互換のどのエージェントでも利用でき、フレームワーク間の統合にかかる負担が完全に解消されました。
  • Zod + 構造化出力 — Zodスキーマが型安全なツール定義の普遍的な契約となり、エージェントの動作のコンパイル時検証が可能になりました。
  • 本番環境での需要 — Next.jsやNode.jsバックエンドを出荷するエンタープライズチームは、同じランタイム、同じモノレポ、同じCI/CDパイプライン内に存在するエージェントのオーケストレーションを必要としていました。

3. Vercel AI SDK — UIファーストの標準

コアの強み

  • ストリーミングファースト: リアルタイムのトークンストリーミングを備えたネイティブSSEトランスポート。useChatuseCompletionフックは、React、Vue、Svelte、Angularで機能します。
  • モデル非依存: インポートを1つ変更するだけで、OpenAI、Anthropic、Google Gemini、Mistral、またはローカルのOllamaモデルを切り替えることができます。リファクタリングは不要です。
  • 型安全なツール呼び出し: ツールはZodを使ってinputSchema / outputSchemaで定義されます。ツールの入力パラメータは自動的にストリーミングされ、モデルが「思考」している間にライブでUIを更新できます。
  • エージェントループ: maxStepsstopWhenコントロールを使用すると、独自のオーケストレーションレイヤーを構築することなく、複数ターンのツール呼び出しループを実行できます。

不足している点

  • 組み込みの永続的なメモリやRAGパイプラインがない。
  • マルチステップや分岐ロジックのためのワークフローエンジンがない。
  • オブザーバビリティダッシュボードがない — 独自のトレーシング(例:OpenTelemetry)を接続する必要がある。

⚠️ 使わないほうがいい場合

エージェントに永続的なステート、複雑な分岐、またはセッション間のメモリが必要な場合、Vercel AI SDKだけでは不十分です。これはトランスポートレイヤーであり、オーケストレータではありません。それらのユースケースには、MastraまたはLangGraph.jsと組み合わせて使用してください。

4. Mastra — バッテリー同梱の対抗馬

コアの強み

  • エージェントとワークフローが1か所に: エージェントは自律的なLLM推論ループを処理し、ワークフローはマルチステップのビジネスロジックのための決定的でグラフベースのパイプラインを提供します。両方が同じプロジェクト内に共存できます。
  • ネイティブMCPサポート: MastraはMCPクライアント(外部ツールを利用する)としても、MCPサーバー(エージェントを標準化されたエンドポイントとして公開する)としても機能します。
  • メモリゲートウェイ: シンプルなメッセージ履歴からベクトルベースのセマンティック検索まで、セッション間の永続的なコンテキスト機能が組み込まれています。
  • Mastra Studio: エージェントとのチャット、ワークフロー実行トレースの視覚化、設定のリアルタイム調整ができるローカルデバッグ環境。
  • Mastra Server: 認証、ミドルウェア、およびストリーミング機能を備え、エージェントやワークフローを本番APIエンドポイントとして標準で公開できます。

不足している点

  • 若いエコシステム — LangChain/LangGraphと比較してコミュニティの連携が少ない。
  • オピニオンを持った設計は、既存のオーケストレーションパターンを持つチームにとって制約に感じるかもしれない。
  • 永続的な実行(ワークフローの途中でサーバーがクラッシュしても生き残る機能)は、LangGraphのチェックポイント機能ほど実戦テストを経ていない。

💡 重要な洞察

Mastraを「AIエージェント向けのNext.js」と考えてください。いくつかの柔軟性を犠牲にする代わりに、理にかなったデフォルト設定、開発サーバー、プロトタイプから本番環境への明確な道筋を提供します。

5. LangGraph.js — ステートマシンの実力派

コアの強み

  • 永続的な実行: すべてのステート遷移は自動的にストレージ(本番環境用にはPostgresSaver)にチェックポイントとして保存されます。エージェントはサーバーの再起動を生き延び、中断した場所から正確に再開します。
  • ヒューマン・イン・ザ・ループ (HITL): ファーストクラスのinterrupt()サポートにより、エージェントは人間の承認を待って一時停止し、その後シームレスに再開できます。
  • タイムトラベルデバッグ: 過去のチェックポイントを読み込んで実行をリプレイし、失敗の診断や分岐して別の入力をテストすることができます。
  • サイクルとサブグラフ: ループ(自己反省、リトライパターン)と、複雑なエージェントを分解するためのモジュール化されたサブグラフをネイティブにサポート。
  • LangSmithの統合: トレースの視覚化、ステップバイステップのデバッグ、トークン使用状況の分析を備えた深いオブザーバビリティ。

不足している点

  • 学習曲線が急 — すべてをグラフとしてモデル化するには、事前のアーキテクチャ設計が必要です。
  • 組み込みのUIコンポーネントやストリーミングフックがない。Vercel AI SDKやその他のUIレイヤーと組み合わせる必要があります。
  • LangChainエコシステム(LangSmith、LangServe)との密結合により、ベンダーロックインを懸念するチームには向かない可能性があります。

6. コード比較: ツール呼び出しエージェントの構築

Vercel AI SDK

typescript — agent.ts
import { openai } from "@ai-sdk/openai";
import { generateText, tool } from "ai";
import { z } from "zod";

const result = await generateText({
 model: openai("gpt-4o"),
 prompt: "What's the weather in Tokyo?",
 tools: {
  getWeather: tool({
   description: "Get weather for a city",
   parameters: z.object({
    city: z.string().describe("City name"),
   }),
   execute: async ({ city }) => {
    // Call your weather API here
    return { city, temp: "22°C", condition: "Sunny" };
   },
  }),
 },
 maxSteps: 5, // Allow multi-turn tool-calling loop
});

Mastra

typescript — agent.ts
import { Agent, createTool } from "@mastra/core";
import { openai } from "@ai-sdk/openai";
import { z } from "zod";

const getWeather = createTool({
 id: "getWeather",
 description: "Get weather for a city",
 inputSchema: z.object({
  city: z.string().describe("City name"),
 }),
 outputSchema: z.object({
  city: z.string(),
  temp: z.string(),
  condition: z.string(),
 }),
 execute: async ({ context }) => {
  return { city: context.city, temp: "22°C", condition: "Sunny" };
 },
});

const weatherAgent = new Agent({
 name: "Weather Agent",
 instructions: "You answer weather questions accurately.",
 model: openai("gpt-4o"),
 tools: { getWeather },
});

const response = await weatherAgent.generate(
 "What's the weather in Tokyo?"
);

LangGraph.js

typescript — agent.ts
import { StateGraph, Annotation, END } from "@langchain/langgraph";
import { ChatOpenAI } from "@langchain/openai";
import { ToolNode } from "@langchain/langgraph/prebuilt";
import { tool } from "@langchain/core/tools";
import { z } from "zod";
import { MemorySaver } from "@langchain/langgraph";

// 1. Define your tool
const getWeather = tool(
 async ({ city }) => {
  return JSON.stringify({ city, temp: "22°C", condition: "Sunny" });
 },
 { name: "getWeather", description: "Get weather for a city",
  schema: z.object({ city: z.string() }) }
);

// 2. Define state schema
const AgentState = Annotation.Root({
 messages: Annotation({ reducer: (a, b) => a.concat(b) }),
});

// 3. Define nodes
const model = new ChatOpenAI({ model: "gpt-4o" }).bindTools([getWeather]);
const callModel = async (state) => {
 const response = await model.invoke(state.messages);
 return { messages: [response] };
};

// 4. Build the graph: nodes → edges → compile
const graph = new StateGraph(AgentState)
 .addNode("agent", callModel)
 .addNode("tools", new ToolNode([getWeather]))
 .addEdge("__start__", "agent")
 .addConditionalEdges("agent", (state) => {
  const last = state.messages[state.messages.length - 1];
  return last.tool_calls?.length ? "tools" : END;
 })
 .addEdge("tools", "agent")
 .compile({ checkpointer: new MemorySaver() });

const result = await graph.invoke(
 { messages: [{ role: "user", content: "What's the weather in Tokyo?" }] },
 { configurable: { thread_id: "session-1" } }
);

💡 違いに注目

Vercel AI SDKは最もシンプルです。単一の関数呼び出しで、クラスや面倒な手続きはありません。
Mastraは、型付けされたツールと出力スキーマを持つAgentクラスを導入しています。
LangGraph.jsはその威力を発揮します。nodesedges、そしてconditionalEdgesを明示的に定義することで、すべてのステート遷移を外科手術のように制御でき、自動チェックポイント機能も組み込まれています。

7. 機能の詳細比較

機能 Vercel AI SDK Mastra LangGraph.js
主なユースケース チャットUI & ストリーミング フルスタックのエージェントアプリ ステートフルなオーケストレーション
モデルサポート 20以上のプロバイダー 20以上 (AI SDK経由) 10以上 (LangChain経由)
ツール呼び出し
Zodスキーマ
Zodスキーマ Zodスキーマ
MCPサポート クライアント クライアント + サーバー ⚠️アダプタ経由
永続的メモリ 組み込み チェックポイント
RAGパイプライン 組み込み ⚠️LangChain経由
ワークフローエンジン ⚠️基本的 グラフベース ステートグラフ
ヒューマン・イン・ザ・ループ ⚠️手動 interrupt()
オブザーバビリティ ⚠️DIY (OTel) Mastra Studio LangSmith
永続的な実行 ⚠️初期段階 実戦テスト済み
最適なランタイム サーバーレス / エッジ Node.js サーバー コンテナ化されたNode.js
ライセンス Apache 2.0 Elastic License v2 MIT

💡 プロのヒント:これらは排他的ではありません

多くのプロダクションチームは、フロントエンドにはVercel AI SDK(ストリーミング、フック)を、バックエンドにはLangGraph.jsまたはMastra(オーケストレーション、メモリ)を使用しています。これらのフレームワークは互いに競合するのではなく、補完し合うように設計されています。

9. 結論

  • Vercel AI SDKトランスポートレイヤーです。チャット製品を構築していて、ストリーミング、モデルの切り替え、UIフックが必要な場合は、ここから始めましょう。どのオーケストレーションフレームワークを選ぶかに関わらず、おそらくこれを使用することになります。
  • Mastraアプリケーションフレームワークです。フル機能のエージェント製品を構築し、エージェント、ワークフロー、メモリ、およびオブザーバビリティスタジオをすぐに使える状態で求めているなら、Mastraはゼロから本番環境への最短経路となります。
  • LangGraph.jsオーケストレーションエンジンです。ワークフローが複雑で、実行時間が長く、障害を生き延びる必要があるなら、LangGraphの永続的なステートグラフと実戦テスト済みのチェックポイント機能に匹敵するものはありません。