Search IOCombats

Search challenges, guides, questions and articles

AI SDK vs Mastra vs LangGraph.js: Choosing a TypeScript Agent Framework
aiai agentsvercel ai sdkmastralanggraphtypescript

AI SDK vs Mastra vs LangGraph.js: Choosing a TypeScript Agent Framework

By Ghazi Khan | Nov 30, 2026 - 9 min read

Last week we wrote an agent loop with the AI SDK and it worked. Then product asks for three more things: remember the user between sessions, pause before a risky action until the user clicks "Approve", and survive a server restart halfway through a run. Now you are reading three framework landing pages that all say "build agents in TypeScript", and it is hard to tell which TypeScript agent framework solves your problem and which one just adds a layer.

This post builds the same small agent in the Vercel AI SDK, Mastra and LangGraph.js, side by side, so you can see the real differences in code instead of in marketing copy.

The concept: three levels of abstraction over one loop

Every agent framework runs the loop from last week: call the model, run the tools it asks for, append the results, repeat until a stop condition. The frameworks differ in what they build around that loop.

The closest analogy for a React developer is state management:

React worldAgent worldWhat you get
useState + fetchAI SDK (ToolLoopAgent)A thin, provider-agnostic loop. You own storage, memory and orchestration.
Redux Toolkit / TanStack QueryMastraAn opinionated toolkit: agents, workflows, memory, storage and a local dev UI, all in TypeScript.
XStateLangGraph.jsExplicit state machine: nodes, edges and a checkpointed state you can pause, inspect and resume.

None of these is "better". useState is the right call for most components, and XState is the right call when you have a payment flow with ten states. The same logic applies here.

Diagram
100%
flowchart TD A["Model call + tools<br/>(the agent loop)"] --> B["AI SDK<br/>ToolLoopAgent: loop, stop conditions,<br/>tool approval, React hooks"] B --> C["Mastra<br/>adds memory, storage, workflows,<br/>dev UI on top of an agent class"] A --> D["LangGraph.js<br/>you draw the loop as a graph;<br/>checkpointer saves state each step"]
visualized byIOCombats

Build it: one agent, three TypeScript agent frameworks

The agent searches a small job list. To make the comparison fair (and keep the code DRY), the data, the Zod schema and the instructions live in one framework-free file. Each framework file only wires them up. This is also the pattern you want in production: your business logic should not import a framework.

npm i ai @mastra/core @langchain/langgraph @langchain/core @langchain/anthropic zod
npm i -D tsx typescript

Set "type": "module" in package.json so top-level await works.

// jobs.ts: framework-free data and logic, shared by all three agents
import { z } from 'zod';

export type Job = { id: string; title: string; city: string; skills: string[] };

const jobs: Job[] = [
  {
    id: 'j1',
    title: 'Frontend Engineer, Acme Pay',
    city: 'Bengaluru',
    skills: ['react', 'typescript'],
  },
  {
    id: 'j2',
    title: 'React Developer, Shiplog',
    city: 'Pune',
    skills: ['react', 'redux'],
  },
  {
    id: 'j3',
    title: 'UI Engineer, Notewise',
    city: 'Remote',
    skills: ['react', 'typescript', 'css'],
  },
];

export const searchInput = z.object({
  skill: z.string().describe('One lowercase skill, for example "react"'),
  city: z.string().nullable().describe('City name, or null for any city'),
});

export const searchDescription =
  'Search open frontend jobs by one skill. Returns id, title and city for each match.';

export function searchJobs({ skill, city }: z.infer<typeof searchInput>) {
  const matches = jobs.filter(
    (j) => j.skills.includes(skill.toLowerCase()) && (!city || j.city === city),
  );
  return matches.length
    ? matches
    : 'No matches. Try a related skill or city: null.';
}

export const instructions =
  'You help frontend developers in India find jobs. Search before answering and only mention jobs the tool returned.';

1. Vercel AI SDK

// ai-sdk.ts
import { ToolLoopAgent, tool, isStepCount } from 'ai';
import {
  instructions,
  searchDescription,
  searchInput,
  searchJobs,
} from './jobs';

export const jobAgent = new ToolLoopAgent({
  model: 'anthropic/claude-sonnet-5.5', // routed through the AI Gateway
  instructions,
  tools: {
    searchJobs: tool({
      description: searchDescription,
      inputSchema: searchInput,
      execute: async (input) => searchJobs(input),
    }),
  },
  stopWhen: isStepCount(5),
});

const result = await jobAgent.generate({
  prompt: 'React roles in Bengaluru or remote',
});
console.log(result.text, `(${result.steps.length} steps)`);

This needs AI_GATEWAY_API_KEY, or swap the string for a provider package such as @ai-sdk/anthropic. You have seen this shape before: it is the agent from the tool calling post. Memory is your job: the AI SDK docs offer provider memory tools, third-party memory providers, or a custom tool. Durable runs move to a separate WorkflowAgent in @ai-sdk/workflow.

2. Mastra

// mastra.ts
import { Agent } from '@mastra/core/agent';
import { createTool } from '@mastra/core/tools';
import {
  instructions,
  searchDescription,
  searchInput,
  searchJobs,
} from './jobs';

const searchJobsTool = createTool({
  id: 'search-jobs',
  description: searchDescription,
  inputSchema: searchInput,
  execute: async (input) => searchJobs(input),
});

export const jobAgent = new Agent({
  id: 'job-agent',
  name: 'Job Agent',
  instructions,
  model: 'anthropic/claude-sonnet-5.5', // Mastra model router string
  tools: { searchJobsTool },
});

const result = await jobAgent.generate('React roles in Bengaluru or remote', {
  maxSteps: 5,
});
console.log(result.text);

Mastra reads ANTHROPIC_API_KEY for an anthropic/... model string. The code looks almost the same as the AI SDK version, and that is the point: Mastra's value is what you add next. Pass memory: new Memory({ options: { lastMessages: 20 } }) from @mastra/memory, register a storage provider on a Mastra instance, and every call with memory: { resource: userId, thread: chatId } gets its history back. Add requireApproval: true to a tool and the stream emits a tool-call-approval chunk; you continue with agent.approveToolCall({ runId }). Mastra also has workflows (fixed steps with suspend and resume) for the parts that should not be left to the model.

3. LangGraph.js

// langgraph.ts
import {
  StateGraph,
  MessagesAnnotation,
  MemorySaver,
  START,
} from '@langchain/langgraph';
import { ToolNode, toolsCondition } from '@langchain/langgraph/prebuilt';
import { tool } from '@langchain/core/tools';
import { SystemMessage } from '@langchain/core/messages';
import { ChatAnthropic } from '@langchain/anthropic';
import {
  instructions,
  searchDescription,
  searchInput,
  searchJobs,
} from './jobs';

const searchJobsTool = tool(
  async (input) => JSON.stringify(searchJobs(input)),
  {
    name: 'searchJobs',
    description: searchDescription,
    schema: searchInput,
  },
);

const tools = [searchJobsTool];
const model = new ChatAnthropic({ model: 'claude-sonnet-5-5' }).bindTools(
  tools,
);

async function callModel(state: typeof MessagesAnnotation.State) {
  const reply = await model.invoke([
    new SystemMessage(instructions),
    ...state.messages,
  ]);
  return { messages: [reply] };
}

export const graph = new StateGraph(MessagesAnnotation)
  .addNode('agent', callModel)
  .addNode('tools', new ToolNode(tools))
  .addEdge(START, 'agent')
  .addConditionalEdges('agent', toolsCondition) // tool calls? go to "tools", else end
  .addEdge('tools', 'agent')
  .compile({ checkpointer: new MemorySaver() });

const result = await graph.invoke(
  {
    messages: [{ role: 'user', content: 'React roles in Bengaluru or remote' }],
  },
  { configurable: { thread_id: 'user-42' }, recursionLimit: 10 },
);
console.log(result.messages.at(-1)?.content);

This is the most code, because you are drawing the loop yourself. In return, nothing is hidden. Each node is a plain async function that returns a partial state update, like a reducer. Because a checkpointer is attached, state is saved after every step under thread_id: call invoke again with the same id and the conversation continues. Swap MemorySaver for a Postgres or Redis checkpointer and a run can resume after a crash. Call interrupt() inside a node to pause for a human, then resume with a Command.

Diagram
100%
flowchart LR S(["START"]) --> A["agent node<br/>callModel()"] A -- "toolsCondition:<br/>has tool calls" --> T["tools node<br/>ToolNode runs searchJobs"] T --> A A -- "no tool calls" --> E(["END"]) A -. "state saved per step<br/>(checkpointer, thread_id)" .-> C[("MemorySaver")]
visualized byIOCombats

Run any of the three with node --env-file=.env.local --import tsx <file>.ts. All three type-check against the current major versions (AI SDK 7, @mastra/core 1.x, @langchain/langgraph 1.x), but these libraries ship fast, so pin versions and read the changelog before upgrading.

Side by side

NeedAI SDKMastraLangGraph.js
Tool loop with stop conditionsToolLoopAgent, stopWhenAgent, maxSteps (default 5) or stopWhenGraph edges, recursionLimit (default 25)
Conversation memoryBring your ownBuilt-in Memory with storage adaptersCheckpointer per thread_id
Human approvalTool approval in the looprequireApproval + approveToolCallinterrupt() + resume with Command
Durable, resumable runsWorkflowAgent (separate package)Workflows with suspend and resumeCheckpointers, core design
React streaminguseChat (native)Adapters to AI SDK UI (@mastra/ai-sdk)LangChain's useStream hook
Mental modelFunctionBatteries-included toolkitState machine

How to choose

  • Start with the AI SDK if the agent is one feature inside a Next.js app, and streaming UI is most of the work. You can always add a framework later.
  • Pick Mastra when you need memory, workflows and a dev UI in a TypeScript-only team, and you would rather configure than build them.
  • Pick LangGraph.js when runs are long, branch a lot, need to pause for humans for hours, or must resume after failures, and you want every transition explicit.

Common mistakes

  1. Choosing by GitHub stars. Popularity tells you nothing about whether a library fits your streaming or hosting needs. Fix: write your requirements first (memory, approval, durability, UI), then build this same tiny agent in your top two options as a one-day spike.
  2. Letting framework types leak into components. If AIMessage or a Mastra chunk type appears in your JSX, switching later means touching every file. Fix: keep logic in framework-free modules like jobs.ts, and expose one small runAssistant() function to the rest of the app.
  3. Confusing LangGraph's recursionLimit with model calls. It counts graph steps, and each pass through agent and tools is a step. A limit of 10 allows only about four tool rounds. Fix: size it from your graph shape and handle GraphRecursionError.
  4. Using MemorySaver in production. It keeps state in process memory, so a serverless cold start or deploy loses every thread. The same applies to Mastra's :memory: storage URL. Fix: use a persistent checkpointer or storage adapter (Postgres, LibSQL, Redis) before launch.
  5. Adopting a heavy framework for a single tool call. If the feature is "summarise this ticket with one lookup", a framework adds concepts without adding value. Fix: use generateText or ToolLoopAgent, and revisit when a real requirement (durability, long memory) appears.

Interview angle

"Which agent framework would you choose?" is a common scenario question for AI-leaning frontend roles. Interviewers want to hear requirements before names, a case for using no framework at all, and a plan to keep the choice reversible. Practise with the agent frameworks interview questions, starting with how to choose one for a TypeScript team.

What's next

On Thursday, the case study How a Multi-Agent Research System Works takes this one step further: a lead agent plans, fans out parallel subagents, and merges their findings with citations. Keep the three mental models from this post in mind while reading it, because that system needs orchestration, state and durability all at once.

Conclusion

The AI SDK, Mastra and LangGraph.js all run the same loop. The AI SDK gives you the loop and great UI hooks, Mastra wraps it in memory, storage and workflows, and LangGraph.js makes you draw it as a checkpointed graph. Keep your tools and data framework-free, pick the lightest option that meets today's requirements, and you can move up a level when the product actually needs it.

Advertisement

Ready to practice?

Test your skills with our interactive UI challenges and build your portfolio.

Start Coding Challenge