Skip to content

Build TypeScript Agents with Mastra & Vercel AI SDK

Typed tools and Zod-validated output with Mastra 1.86 and AI SDK 7. Every snippet type-checked on 2026-11-25; none was run against a live model.

· · 10 min read

Updated: November 25, 2026

TypeScript code defining a Mastra search tool with a Zod input schema

Quick Take

Two TypeScript-native frameworks now cover the whole AI agent stack: Mastra handles orchestration and tool wiring, Vercel AI SDK handles the generation layer. Together they give you typed tools, Zod-validated outputs, and streaming: the compiler checks your own code, and Zod rejects bad model output at runtime.

A note on evidence first. On November 25, 2026 I installed @mastra/core 1.86.0, ai 7.0.181, @ai-sdk/openai 4.0.123 and zod 4.6.7, and type-checked every snippet below with TypeScript 7.0.2 under strict. I didn't call a model: no API key, no agent run, no output to show. So the types and signatures are checked, and anything about what happens at runtime is attributed to the Mastra and AI SDK docs.

Most TypeScript AI agent tutorials skip two questions: what type is that tool's output? What does the agent return when it's done? "It returns a string" is not an answer a production TypeScript codebase accepts.

Mastra is a TypeScript-native agent orchestration framework that handles tool wiring, memory, and multi-step reasoning, and pairing it with the Vercel AI SDK's model-generation layer gives you a typed stack from tool call to final output. The idea to take from this page is to define types before writing agent logic, the same pattern that works for TypeScript contracts in LLM prompting.

Why use the two SDKs together

Mastra and Vercel AI SDK solve different problems. Mastra is the agent architecture layer: you define tools, register them with agents, and describe what the agent should do. It handles multi-step reasoning, the agent deciding which tool to call, in what order, with what arguments.

Vercel AI SDK is the model communication layer. It abstracts over OpenAI, Anthropic, Google Gemini, and a dozen other providers. Its generateText and streamText functions have consistent TypeScript signatures regardless of which model you're talking to.

Neither replaces the other. Combined, you get Mastra's agent patterns on top of the AI SDK's provider integrations. Both move fast. @mastra/core 1.0.0 went to npm on January 20, 2026 and the newest release on November 25 is 1.86.0; its v1 migration guide lists a new createTool execute signature among the breaking changes. The ai package is on major version 7, and its structured-data page now leads with generateText plus Output.object(), where older tutorials (this one included, until today) used generateObject. Code copied from a post that's six months old may simply not compile, which is the reason this page names its versions. The install:

npm install @mastra/core ai @ai-sdk/openai zod

That's four packages: Mastra core, the Vercel AI SDK, the OpenAI provider and Zod.

Typed tools come first

Tools are where TypeScript earns its place. A tool with any types is no safer than a raw API call, while a tool with Zod schemas is something the compiler can reason about. Typed tools are functions an AI agent can call whose inputs and outputs are declared with a runtime-validated schema, typically Zod, rather than left as loosely-typed JavaScript objects the model happens to produce correctly most of the time. According to the Vercel AI SDK's documentation on structured outputs, a Zod schema does double duty: it shapes the prompt sent to the model so the model knows what format to return, and it validates the response before your application code ever touches it. Every snippet in this guide is wired this way, so by the docs' description malformed model output fails at the schema boundary, which is exactly where you want to find it.

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

const searchFiles = createTool({
  id: 'search-files',
  description: 'Search TypeScript files for a pattern or function name',
  inputSchema: z.object({
    pattern: z.string().describe('Search pattern or function name'),
    fileExtension: z.enum(['.ts', '.tsx']).optional().default('.ts'),
    maxResults: z.number().int().positive().max(20).default(10),
  }),
  outputSchema: z.object({
    matches: z.array(z.object({
      file: z.string(),
      line: z.number(),
      snippet: z.string(),
    })),
    totalCount: z.number(),
  }),
  execute: async (inputData) => {
    // inputData is fully typed: { pattern: string, fileExtension: '.ts' | '.tsx', maxResults: number }
    const results = await runSearch(inputData.pattern, inputData.fileExtension);
    return { matches: results, totalCount: results.length };
  },
});

The inputSchema tells the model exactly what arguments to pass. The outputSchema validates what your handler returns and types the result throughout the rest of your code. Model sends the wrong argument type? The compiler can't see that, because the arguments only arrive at runtime, so Zod rejects them before execute runs and the error names the field. Handler returns the wrong shape? Compiler error. I checked that one: renaming totalCount to total in the return fails with TS2322, "Property 'totalCount' is missing". So does the pre-1.0 handler shape. Write execute: async ({ context }) => as Mastra 0.x tutorials do, and 1.86.0 answers with TS2339, "Property 'context' does not exist" on the input type.

In practice, that's the split between typed TypeScript agents and loosely typed ones. Mistakes in your own code fail at compile time. Mistakes the model makes fail at the schema boundary, at runtime, with a message that names the field, instead of as an attribute error three calls later.

Typed agents fail in two honest places: your own mistakes at compile time, the model's mistakes at the Zod boundary at runtime, with a message that names the field.

Share this Post on X Bluesky

Structured outputs with Zod schemas

Some agents return free text. Many need structured data. The AI SDK handles this with generateText and an Output.object() setting that takes a Zod schema:

import { generateText, Output } from 'ai';
import { openai } from '@ai-sdk/openai';
import { z } from 'zod';

const ReviewResult = z.object({
  issues: z.array(z.object({
    severity: z.enum(['error', 'warning', 'suggestion']),
    file: z.string(),
    description: z.string(),
    suggestedFix: z.string().optional(),
  })),
  overallAssessment: z.enum(['approve', 'request-changes', 'needs-discussion']),
  confidence: z.number().min(0).max(1),
});

type ReviewResult = z.infer<typeof ReviewResult>;

const { output } = await generateText({
  model: openai('gpt-4o'),
  output: Output.object({ schema: ReviewResult }),
  prompt: `Review this TypeScript PR diff for issues:\n\n${diff}`,
});

// output is typed as ReviewResult, no type assertions, no casting
output.issues.forEach(issue => {
  console.log(`[${issue.severity}] ${issue.file}: ${issue.description}`);
});

The schema does two jobs. It generates the structured output prompt that tells the model what format to return, and it validates and types the response so your downstream code has full TypeScript inference. If the model returns something that doesn't match the schema, the AI SDK docs say generateText rejects with a NoObjectGeneratedError: loud failure close to the source, not a silent type mismatch three function calls deep. Free-text parsing pushes the failure into whatever code eventually reads the wrong field, often several layers away from the model call, and by then the stack trace tells you nothing useful about what the model actually said. A schema violation names the offending field immediately. Don't expect the SDK to retry a malformed response for you: maxRetries covers failed API calls, and a schema mismatch is an error you have to handle yourself. The model id is a placeholder, by the way. Use one your account can call.

The complete agent pattern

A Mastra agent combines tools and instructions into a unit that reasons across multiple steps:

import { Agent } from '@mastra/core/agent';

const codeReviewAgent = new Agent({
  id: 'code-reviewer',
  name: 'Code reviewer',
  instructions: `You review TypeScript code for correctness, type safety, and style.
Use the searchFiles tool to find relevant context before making judgments.
Return structured findings with severity levels and suggested fixes.`,
  model: 'openai/gpt-4o',
  tools: { searchFiles },
});

const result = await codeReviewAgent.generate(
  'Review the authentication module for type safety issues',
  { structuredOutput: { schema: ReviewResult }, maxSteps: 5 }
);

// result.object is ReviewResult
console.log(`Decision: ${result.object.overallAssessment}`);
console.log(`Issues: ${result.object.issues.length}`);

Two details in that snippet come from the current packages, not from older tutorials. id is required: leave it out and 1.86.0 fails to compile with "Property 'id' is missing". And the model is a provider/model string, the form Mastra's structured output docs use; they read the key from OPENAI_API_KEY.

The agent can call searchFiles multiple times across reasoning steps, searching for the auth module, then for usage sites, then for related types, before returning the final ReviewResult. The TypeScript types flow through the entire chain. Notice what you didn't have to write: no loop deciding when to stop, no branching on which tool to invoke next, no manual assembly of tool results back into the conversation. That control flow is what Mastra sells, and it's the part that's tedious to get right by hand against a raw chat completions endpoint. That's also why the call passes maxSteps: 5. Would an agent with no ceiling stop on its own? Usually, but each extra round trip is a billed request, and a limit costs one option.

Streaming long-running agents

Multi-step agent runs on complex tasks aren't quick, so stream the reasoning instead of making users stare at a spinner:

const stream = await codeReviewAgent.stream(
  'Review all API route handlers for input validation gaps',
  { structuredOutput: { schema: ReviewResult } }
);

for await (const chunk of stream.textStream) {
  process.stdout.write(chunk); // or push to a UI
}

const finalResult = await stream.object; // typed as ReviewResult

stream.object carries the same type as generate's result; assigning it to a ReviewResult variable type-checks. Per Mastra's docs you read it after the stream completes, and validation failures follow errorStrategy: 'strict' (the default) throws, 'warn' logs and continues, 'fallback' returns a fallbackValue you supply. So you can show progress from the first token while still refusing to act on the structured result until it has passed the schema. An earlier version of this section warned about a deadlock when awaiting stream.object first. I couldn't confirm that without a live run, so it's gone.

Mastra vs Vercel AI SDK: Who Does What?

Mastra and the Vercel AI SDK get framed as competitors constantly, and they aren't. Vercel AI SDK is the layer that talks to models: one typed interface over OpenAI, Anthropic, Google, and roughly a dozen other providers, with Output.object() doing schema validation on the way out. Mastra sits above that and owns the agent loop, deciding which tool to call, feeding results back in, and stopping when the task is done. A project can use the AI SDK alone if all it needs is a typed model call. The moment you want multi-step reasoning over tools, you either adopt Mastra or write that orchestration yourself. Both accept Zod as the schema language, which is why they compose cleanly.

MastraVercel AI SDK
LayerAgent orchestration, tools, memoryModel generation, streaming, structured outputs
HandlesMulti-step reasoning, which tool to call and whengenerateText and streamText across providers
Type safety mechanismZod inputSchema/outputSchema on toolsZod schema passed to Output.object()
Version checked here@mastra/core 1.86.0 (1.0.0 published 2026-01-20)ai 7.0.181

Applying the pattern

The same principles that make TypeScript strict for AI apply to AI agents: define the shape first, let the tools enforce it. An agent with untyped tools and any return values gives you the same class of silent runtime failures that untyped AI code does.

Zod schemas as tool contracts, Output.object() for structured outputs, TypeScript inference throughout: together they decide whether you get an agent that fails loudly, at compile time for your code and at the schema boundary for the model's, or one that fails silently at 2am in production. The CI quality gates setup catches any any that slips through into your agent code.

Once your agent is running, the next question is how to connect it to external databases, filesystems, and APIs in a standardized way. That's what Model Context Protocol addresses, a JSON-RPC-based standard for wiring AI agents to developer tools without custom integrations for every service.

Frequently Asked Questions

What is Mastra and how does it differ from Vercel AI SDK?
Mastra is a TypeScript agent orchestration framework, it handles the agent architecture: defining tools, managing multi-step reasoning, wiring memory, and composing workflows. Vercel AI SDK is the generation layer, it talks to OpenAI, Anthropic, Google, and other models through a consistent interface and handles streaming, structured outputs, and React hooks. They're complementary: Mastra for 'how the agent thinks', Vercel AI SDK for 'how it talks to models'.
Do I need both Mastra and Vercel AI SDK together?
No, you can use either independently. Vercel AI SDK alone is great for adding AI to a Next.js app: streaming chat, structured outputs, simple tool use. Mastra alone can work with any provider. But using both gives you Mastra's opinionated agent patterns plus Vercel AI SDK's polished provider integrations and streaming primitives.
How does TypeScript improve AI agent reliability?
AI agent failures tend to cluster around two problems: tools called with wrong arguments, and outputs with unexpected shapes. TypeScript and Zod split that job. The model's arguments only exist at runtime, so the compiler can't see them: when you define a tool's inputSchema as a Zod object, the agent framework validates the arguments at runtime before calling the tool, and TypeScript infers the exact type of the input parameter inside your handler, so your own code is checked at compile time. Same for outputs: generateText with Output.object and a Zod schema validates the model's response before it reaches your code.
What version of Mastra and Vercel AI SDK does this tutorial use?
@mastra/core 1.86.0, ai 7.0.181, @ai-sdk/openai 4.0.123 and zod 4.6.7, the versions npm installed on November 25, 2026. Every snippet was type-checked against them with TypeScript 7.0.2 under strict. None was executed against a live model, so runtime behavior is described from the two projects' documentation. Mastra's v1 migration changed createTool's execute signature to (inputData, context), and the AI SDK docs now show generateText with Output.object() for structured data.