TypeScript: Mastra and Vercel AI SDK

One toolkit centers on model calls and agent loops in your web app. The other adds a fuller application framework.

BeginnerIntermediateExpert · 13 min read · Last updated:

In short

The Vercel AI SDK gives TypeScript programs one interface to many model providers, typed tools, streaming for user interfaces and a ToolLoopAgent class. Mastra is a framework with agents, tools, graph-style workflows, memory and a server, registered on a central instance. Use the SDK when you want a focused library inside your own application; consider Mastra when you want workflows, suspend and resume and conventions supplied.

What you will learn: an agent with typed tools and approval, a workflow that suspends and resumes, testing without a provider, upgrade traps and how the TypeScript options compare.
Prerequisites: The Agent Loop: Observe, Reason, Plan, Act, Reflect, comfort with TypeScript or JavaScript and promises.

Versions used

Checked in November 2026. The listings are JavaScript modules run on Node.js 22 with ai 7.0.184, @mastra/core 1.86.0 and zod 4.6.7. A mock model replaces a provider, so no key is needed. They were run as JavaScript and were not type-checked as TypeScript.

Beginner The landscape and a first agent

Why build agents in TypeScript

Many web teams already run TypeScript from browser to server. Keeping agents there means one language, shared types between interface and tools, and familiar deployment. The same agent principles apply as in any language: bounded loops, validated tool input, permissions enforced on the server and tests that do not depend on a live model.

Keys and tools stay on the server

Model keys, tool code with privileges and approval decisions belong in server code. Anything shipped to a browser can be read and changed by its user. Never accept a tool result or an approval from the client without verifying who sent it and whether it matches a pending request.

Vercel AI SDK

The core functions generate text or structured data and stream results. A tool has a description, an input schema, often written with Zod, and an execute function. ToolLoopAgent wraps the loop: call the model, run requested tools, repeat until the model stops asking, an approval is needed or a stop condition is met. Its documentation in this version gives 20 steps as the default stop condition.

import { ToolLoopAgent, isStepCount, tool } from 'ai';
import { MockLanguageModelV4 } from 'ai/test';
import { z } from 'zod';

const usage = { inputTokens: { total: 1 }, outputTokens: { total: 1 } };
const step = (content, reason) => ({
  content, finishReason: { unified: reason }, usage, warnings: [],
});
const call = (toolName, input) => step([{
  type: 'tool-call', toolCallId: `id-${toolName}`, toolName,
  input: JSON.stringify(input),
}], 'tool-calls');

// Offline stand-in: replays one prepared response per model call.
const model = new MockLanguageModelV4({
  doGenerate: [
    call('lookupOrder', { orderId: 'A-17' }),
    call('refund', { orderId: 'A-17', amount: 25 }),
    step([{ type: 'text', text: 'Refund of 25 issued.' }], 'stop'),
  ],
});

const refunds = [];
const agent = new ToolLoopAgent({
  model,
  instructions: 'Help with orders. Use tools for facts.',
  tools: {
    lookupOrder: tool({
      description: 'Look up one order',
      inputSchema: z.object({ orderId: z.string() }),
      execute: async ({ orderId }) => ({ orderId, total: 40 }),
    }),
    refund: tool({
      description: 'Refund money on an order',
      inputSchema: z.object({
        orderId: z.string(), amount: z.number().positive().max(100),
      }),
      execute: async (input) => { refunds.push(input); return 'done'; },
    }),
  },
  toolApproval: { refund: 'user-approval' },
  stopWhen: isStepCount(5),
});

const messages = [{ role: 'user', content: 'Refund 25 on A-17' }];
const first = await agent.generate({ messages });
const request = first.content.find(p => p.type === 'tool-approval-request');
console.log('approval needed:', request.toolCall.toolName,
  JSON.stringify(request.toolCall.input));
console.log('refunds so far:', refunds.length);

messages.push(...first.responseMessages, {
  role: 'tool',
  content: [{ type: 'tool-approval-response',
    approvalId: request.approvalId, approved: true }],
});
const second = await agent.generate({ messages });
console.log('answer:', second.text);
console.log('refunds:', JSON.stringify(refunds));

Output:

approval needed: refund {"orderId":"A-17","amount":25}
refunds so far: 0
answer: Refund of 25 issued.
refunds: [{"orderId":"A-17","amount":25}]

The order lookup ran immediately. The refund did not: toolApproval marked it as needing a person, so the first call returned a request and the refund list stayed empty. The second call adds an approval response to the message history and the tool then runs once. The schema also limits the amount to a positive number up to 100.

Approval travels in messages

In this pattern the pending request and the decision are part of the conversation you pass back. If a browser holds that history, it could be altered. Keep the authoritative history and pending approvals on the server, check the approver's rights, and let each approval be used once. The SDK has an experimental option for signing approval requests; treat experimental features with care.

Intermediate Streaming, structure and workflows

When a tool fails

This script asks for a charge that breaks the schema, then asks twice for a valid one while the tool itself fails. It never produces an answer.

import { ToolLoopAgent, isStepCount, tool } from 'ai';
import { MockLanguageModelV4 } from 'ai/test';
import { z } from 'zod';

const usage = { inputTokens: { total: 1 }, outputTokens: { total: 1 } };
const ask = (id, amount) => ({
  content: [{ type: 'tool-call', toolCallId: id, toolName: 'charge',
    input: JSON.stringify({ amount }) }],
  finishReason: { unified: 'tool-calls' }, usage, warnings: [],
});

// This script never gives a final answer, so a limit has to stop it.
const model = new MockLanguageModelV4({
  doGenerate: [ask('c1', 500), ask('c2', 40), ask('c3', 40)],
});

const agent = new ToolLoopAgent({
  model,
  tools: {
    charge: tool({
      inputSchema: z.object({ amount: z.number().max(100) }),
      execute: async () => { throw new Error('gateway timeout'); },
    }),
  },
  stopWhen: isStepCount(3),
});

const result = await agent.generate({ prompt: 'Charge the customer' });
for (const [index, step] of result.steps.entries()) {
  const failed = step.content.find(part => part.type === 'tool-error');
  const reason = String(failed.error?.message ?? failed.error);
  console.log(index + 1, step.finishReason, '|',
    reason.split(':')[0].slice(0, 60));
}
console.log('final text:', JSON.stringify(result.text));

Output:

1 tool-calls | AI_InvalidToolInputError
2 tool-calls | gateway timeout
3 tool-calls | gateway timeout
final text: ""

Three lessons follow. The invalid amount never reached execute. The thrown error did not crash the run; it was recorded as a tool error that the next model call could see. And the step limit ended the run with empty text, so code that shows result.text without checking would show nothing. The model also asked for the same charge again after a timeout. A timeout does not say whether the money moved, so a charging tool needs an operation key and a status check, as set out in Reliable Tool Execution and Error Recovery. Error messages are sent to the model, so keep secrets and internal detail out of them.

Streaming and structured results

Streaming improves perceived speed: show text and tool progress as they arrive. Plan for a stream that breaks halfway, a user who closes the page and a tool that finishes after nobody is listening. Pass an abort signal so that canceled requests stop costing money, and decide which actions must complete even if the connection drops.

For data that code will consume, request structured output against a schema. Validation confirms shape and types. It cannot confirm that a value matches your records, so check that separately.

ControlWhere to look in the SDK
Stop after a number of stepsstopWhen with isStepCount
Stop on a particular toolstopWhen with hasToolCall
Change model or tools between stepsprepareStep
Limit which tools are offeredactiveTools
Require a persontoolApproval
Test without a providerMock models in ai/test

Shared types, separate trust

Schemas let one definition describe tool input for the model, validate it at run time and give TypeScript types to your editor. That is a real advantage, but types disappear when code runs. Only the run-time check protects you from a model, a client or an upstream service that sends something else.

BoundaryCheck at run time
Browser to serverIdentity, message shape, size limits
Model to toolSchema, ranges, ownership of identifiers
Tool to external serviceResponse schema, status and timeouts
Storage to programVersion of saved state

Moving to AI SDK 7

Version 7, released in June 2026, is a major release aimed at production agents. It ships as ECMAScript modules only and needs Node.js 22 or later. It also introduces further agent classes for durable workflows and for running existing coding harnesses. A codemod, run with npx @ai-sdk/codemod v7, handles mechanical changes.

  1. Check Node.js versions in every environment, including build and serverless platforms.
  2. Convert or confirm that your packages can import ES modules.
  3. Upgrade the core package and provider packages together.
  4. Run the codemod, then read its changes and the migration guide.
  5. Run tests and your evaluation set; compare requests sent before and after.

Mastra

Mastra announced 1.0 in January 2026. You create agents, tools and workflows and register them on a Mastra instance, which connects them to storage, logging and a server. Workflows are built from typed steps and combined with methods such as .then(), .branch() and .parallel().

startvalidated input
check
approvesuspend if large
resumewith decision
outcome
The suspended state is kept by the configured storage.
import { Mastra } from '@mastra/core/mastra';
import { InMemoryStore } from '@mastra/core/storage';
import { createStep, createWorkflow } from '@mastra/core/workflows';
import { z } from 'zod';

const claim = z.object({ amount: z.number() });
const outcome = z.object({ amount: z.number(), status: z.string() });

const check = createStep({
  id: 'check', inputSchema: claim, outputSchema: claim,
  execute: async ({ inputData }) => inputData,
});

const approve = createStep({
  id: 'approve', inputSchema: claim, outputSchema: outcome,
  resumeSchema: z.object({ approved: z.boolean() }),
  suspendSchema: z.object({ question: z.string() }),
  execute: async ({ inputData, resumeData, suspend }) => {
    const { amount } = inputData;
    if (amount > 500 && !resumeData) {
      return suspend({ question: `Approve ${amount}?` });
    }
    const ok = resumeData ? resumeData.approved : true;
    return { amount, status: ok ? 'paid' : 'refused' };
  },
});

const claims = createWorkflow({
  id: 'claims', inputSchema: claim, outputSchema: outcome,
}).then(check).then(approve).commit();

const mastra = new Mastra({
  workflows: { claims },
  storage: new InMemoryStore({ id: 'demo' }), // use a database in real use
  logger: false,
});

for (const amount of [120, 900]) {
  const run = await mastra.getWorkflow('claims').createRun();
  let result = await run.start({ inputData: { amount } });
  console.log(amount, result.status);
  if (result.status === 'suspended') {
    console.log('  asked:', result.steps.approve.suspendPayload.question);
    result = await run.resume({
      step: 'approve', resumeData: { approved: true },
    });
    console.log(amount, result.status);
  }
  console.log('  outcome:', result.result.status);
}
process.exit(0);

Output:

120 success
  outcome: paid
900 suspended
  asked: Approve 900?
900 success
  outcome: paid

The small claim completes at once. The large one returns the status suspended with the question the step supplied. Resuming with data that matches resumeSchema runs the step again, and this time the decision is present. Note that the step's code starts again from the top, so keep effects after the suspension check.

Storage and license

The in-memory store loses everything on restart; configure a database for real use. Mastra's core is under Apache 2.0, while code in its ee directories falls under a separate enterprise license. Check which parts you use.

Choosing where long work lives

A web request is a poor home for work that takes an hour or waits for a person. Return an identifier quickly, run the work in a worker or workflow engine, store progress, and let the interface poll or subscribe. Mastra's suspend and resume, the AI SDK's workflow agent and general durable execution systems each address this in their own way. Whichever you pick, kill the process mid-task in a test and see what happens. Event-Driven and Background Agents describes the surrounding design.

Expert Testing, comparison and operations

Testing

Mock the model, not your own tools' logic. Script a tool call and a final answer, then assert on what ran. Include invalid arguments, a refused approval and a model that never stops.

  • Schemas reject out-of-range and missing values
  • Refusal leaves no side effect
  • Step limits stop a looping script and the result is handled
  • Suspended workflows resume after a process restart with real storage
  • Canceled requests stop model calls
  • Type checking runs in your build, since these listings did not check types

Deployment concerns

ConcernWhat to check
Serverless time limitsLong runs need background work or durable execution
ConcurrencyNo shared mutable state between requests, unlike the list in the demo
DependenciesLock versions; review packages that handle keys
TelemetryWhere traces go and whether prompts are included
Rate limitsPer-user budgets, not only provider limits

TypeScript agent frameworks compared

OptionFocusGood fitConsider
Vercel AI SDKModel interface, UI streaming, agent loopChat and tool features in web appsMajor version changes; you add storage
MastraApplication framework with workflows and memorySuspend and resume, conventionsLarger surface; license of add-ons
LangGraph for JavaScriptExplicit graphs and checkpointsTeams sharing designs with PythonFeature timing differs by language
OpenAI Agents SDK for TypeScriptAgents, handoffs, guardrailsRouting between specialistsPre-1.0 versioning
Claude Agent SDK for TypeScriptCoding-style tools and loopAgents working on filesPermissions and isolation
Plain provider clientDirect callsSmall, well understood agentsYou build the rest

Combinations are common: for example, a framework for workflows using the AI SDK's model interface underneath. When you combine them, upgrade them together and decide which layer owns state and retries.

Recommendations

A practical path

Begin with the AI SDK or a provider client for one agent with two tools and a mock-model test. Add a workflow framework only when you need to pause, resume or coordinate steps. Keep tool functions in plain modules so that either choice can use them.

Illustrative design, not a real product

A booking site streams answers with the AI SDK. Refunds go to a server workflow that suspends for staff approval and stores state in the company database. The browser receives only status text and a request identifier, never the means to approve.

Common mistakes

MistakeBetter practice
Calling models from the browser with a keyCall from the server
Trusting client message historyKeep the authoritative copy on the server
Relying on default step limitsSet a limit for the task
In-memory storage for suspended workUse durable storage
Upgrading only some related packagesUpgrade the family together
Assuming running code means correct typesRun the type checker

Checklist

  • Node.js and module format requirements are met everywhere
  • Tool inputs are validated with bounds
  • Approvals are verified on the server and used once
  • Runs have step, time and spending limits
  • Tests use mock models and include refusal and failure
  • Licenses and telemetry are reviewed

Frequently asked questions

Do I need Vercel hosting to use the AI SDK?

No. It is a library that runs wherever a supported JavaScript runtime does, subject to its Node.js and module requirements.

Is zod required?

It is a common choice for schemas. Libraries may accept other schema formats; check the documentation for your version.

Can TypeScript agents use MCP servers?

Both projects document ways to connect to MCP tools. Review each server and require approval for actions that change data.

Is Python needed for serious agent work?

No. Python has a wide data and evaluation ecosystem, but production agents can be built and tested entirely in TypeScript.

References and further reading

Next steps