Vercel AI SDK 7: TypeScript-First Agent Framework

The definitive guide to Vercel AI SDK 7 -- the TypeScript toolkit for building AI-powered applications and agents. From the Agent primitive and ToolLoopAgent to human-in-the-loop approval, native MCP client integration, DevTools debugging, streaming UI with useChat, provider switching across Claude/GPT/Gemini/Ollama, and deployment on Vercel Agentic Infrastructure.

What AI SDK 7 Brings

Vercel AI SDK 7 shipped stable on June 25, 2026 (npm [email protected]; 7.0.165 was the latest release in November 2026) and builds on the agent primitives introduced in AI SDK 6 (December 2025). With about 142 million npm downloads in the last month (npm downloads API, Oct 9 to Nov 7, 2026), the TypeScript toolkit provides a unified API for connecting to any AI provider -- OpenAI, Anthropic, Google, xAI, Ollama, and more -- through a single, model-agnostic interface. It requires Node.js 22+ and is ESM-only.

The headline feature is the Agent abstraction. Agent is an interface rather than a class, and ToolLoopAgent provides the production-ready default implementation. You define an agent once with its model, instructions, and tools, then reuse it across your entire application -- in API routes, Server Actions, background jobs, and streaming UIs. The agent handles the complete tool execution loop: call the LLM, execute any requested tool calls, add results back to the conversation, and repeat until a stop condition is reached.

Other major capabilities include human-in-the-loop tool approval (configured with toolApproval in v7; v6 used a per-tool needsApproval flag), structured outputs through the output option, a native MCP client in the @ai-sdk/mcp package for connecting to any MCP server, OpenTelemetry in the separate @ai-sdk/otel package, and AI SDK DevTools for inspecting token usage, execution flows, and raw provider requests. Chat UIs use useChat with a transport pointed at a route handler (React components can also call model functions through Server Actions).

Key Features

CORE

Agent Interface

Agent is an interface, not a class. ToolLoopAgent provides the default implementation. Define your agent once with model, instructions, and tools, then use it across API routes, Server Actions, and streaming UIs. Implement the Agent interface to build custom abstractions for specialized needs.

CORE

ToolLoopAgent

Production-ready agent that handles the complete reasoning-and-acting loop. Calls the LLM, executes tool calls, adds results to the conversation, and repeats for up to 20 steps by default (configurable via stopWhen: isStepCount(n)). Unlike single-step generateText(), ToolLoopAgent iterates until completion or approval is needed.

SAFETY

Human-in-the-Loop Approval

Configure toolApproval on the call or agent: toolApproval: { deleteFile: 'user-approval' } for static approval on every call, or a function that returns 'user-approval' or undefined for conditional approval (v6's needsApproval flag was replaced in v7). The frontend renders approve/deny buttons via useChat, and addToolApprovalResponse sends the decision back.

TOOLS

Native MCP Client

Connect to any MCP server via createMCPClient() from @ai-sdk/mcp. Tools from MCP servers become available through the same interface as native AI SDK tools. Supports stdio (local servers) and HTTP transports. Combine MCP tools with native tools in a single agent for maximum flexibility.

DEBUG

AI SDK DevTools

Install @ai-sdk/devtools, register it with registerTelemetry(DevToolsTelemetry()), launch the viewer with npx @ai-sdk/devtools@latest and open localhost:4983. Inspect every step of any LLM call: input, output, model configuration, token usage, timing, and raw provider requests/responses. For local development only.

UI

Streaming UI Hooks

useChat for real-time chat streaming (sendMessage, message.parts and status over a DefaultChatTransport) and useCompletion for text completions. Automatic message appending, streaming display, and full conversation history management -- all with end-to-end type safety.

FLEX

Provider Switching

Switch between Claude, GPT, Gemini, Ollama, and 20+ providers by changing two lines of code. All providers follow the same interface -- pass the model into generateText() or streamText() without changing anything else. Vercel AI Gateway adds model routing and cost controls.

INFRA

Route Handlers and Server Actions

The current useChat docs pair the hook with a /api/chat Route Handler (via DefaultChatTransport). You can also call model functions from Next.js Server Actions using "use server", for example in form-driven flows with progressive enhancement.

CORE

Structured Output + Tool Calling

Structured outputs with Zod schemas through the output option of generateText()/streamText() (graduated from experimental_output in v7). Tool inputs are defined with inputSchema (Zod) for full type inference. Combine structured outputs with tool calling for agents that return both actions and structured data.

INFRA

Agentic Infrastructure

Vercel platform support for agent workloads: AI Gateway for model routing, Fluid Compute for AI-optimized execution, Workflows and Queues for pause/resume orchestration, and Sandbox for isolated code execution. Over 30% of Vercel deployments are now initiated by coding agents.

v5 to v6 to v7 Migration Guide

Upgrading from AI SDK 5 to 6 is streamlined by the official codemod: run npx @ai-sdk/codemod v6. AI SDK 7 then shipped stable on June 25, 2026 (npm [email protected]); from v6 run npx @ai-sdk/codemod v7 to move up (all codemods at once; see the official AI SDK 7 migration guide at ai-sdk.dev/docs/migration-guides/migration-guide-7-0). v7 requires Node.js 22+ and is ESM-only (no require('ai')). Manual review is still recommended for custom agent implementations.

The most significant v5-to-v6 change was replacing Experimental_Agent with ToolLoopAgent: the system parameter became instructions, and the default stopWhen changed from one step to 20 steps. In v7 the stop helper is named isStepCount (formerly stepCountIs), so code that relied on single-step behavior should set stopWhen: isStepCount(1).

// v5 (deprecated)
import { Experimental_Agent, stepCountIs } from 'ai';

const agent = new Experimental_Agent({
  model: openai('gpt-5.5'),
  system: 'You are a helpful assistant.',
  tools: { myTool },
  stopWhen: stepCountIs(1)
});

// v6/v7 (current)
import { ToolLoopAgent } from 'ai';

const agent = new ToolLoopAgent({
  model: openai('gpt-5.5'),
  instructions: 'You are a helpful assistant.',
  tools: { myTool },
  // Default: stopWhen: isStepCount(20)  (stepCountIs in v6)
});

Other v7 renames to expect: needsApproval becomes toolApproval, onFinish/onStepFinish become onEnd/onStepEnd, experimental_telemetry becomes telemetry (OpenTelemetry now lives in @ai-sdk/otel and is enabled with registerTelemetry()), result.fullStream becomes result.stream, and tool definitions use inputSchema. Messages with role: 'system' are rejected in favor of instructions. The MCP client is imported from @ai-sdk/mcp as createMCPClient.

The Agent Abstraction and ToolLoopAgent

AI SDK 6 introduced, and 7 keeps, the idea of agents as reusable, composable primitives. The Agent interface defines the contract: a model, instructions, tools, and a stop condition. ToolLoopAgent implements this interface with a production-ready reasoning-and-acting loop that handles tool execution, result collection, and iterative reasoning.

Unlike single-shot generateText() calls, a ToolLoopAgent can invoke tools, collect results, reason over them, invoke more tools, and repeat until the stop condition is reached. This enables autonomous multi-step workflows: research agents that search, summarize, and synthesize; coding agents that plan, implement, and test; and data agents that query, analyze, and report.

import { ToolLoopAgent, isStepCount, tool } from 'ai';
import { anthropic } from '@ai-sdk/anthropic';
import { z } from 'zod';

const researchAgent = new ToolLoopAgent({
  model: anthropic('claude-sonnet-5-5'),
  instructions: 'You are a research assistant. Search for information, analyze results, and provide comprehensive answers.',
  tools: {
    search: tool({
      description: 'Search the web for information',
      inputSchema: z.object({
        query: z.string().describe('Search query'),
      }),
      execute: async ({ query }) => {
        // Your search implementation
        return await searchWeb(query);
      },
    }),
    analyze: tool({
      description: 'Analyze a text document',
      inputSchema: z.object({
        text: z.string(),
        focus: z.string().describe('Analysis focus area'),
      }),
      execute: async ({ text, focus }) => {
        return await analyzeText(text, focus);
      },
    }),
  },
  // Runs up to 10 reasoning steps (the default is 20)
  stopWhen: isStepCount(10),
});

// Use the agent for text generation
const result = await researchAgent.generate({ prompt: 'Compare React and Vue in 2026' });
console.log(result.text);

// Or for streaming
const stream = await researchAgent.stream({ prompt: 'Analyze the latest AI trends' });
for await (const chunk of stream.textStream) console.log(chunk);

You can also implement the Agent interface directly for custom abstractions. This is useful when you need non-standard loop behavior, such as agents that collaborate with other agents, agents that switch models mid-conversation based on task complexity, or agents with custom memory systems that persist across sessions.

Human-in-the-Loop Tool Approval

AI SDK 6 introduced human-in-the-loop approval as a per-tool needsApproval flag; in AI SDK 7 it is configured with toolApproval on generateText, streamText or ToolLoopAgent. This enables human-in-the-loop safety for sensitive operations without building custom approval infrastructure. When a tool requires approval, the call pauses and the tool call is surfaced to the user for review.

There are two modes: static approval (map the tool to 'user-approval') and dynamic approval (a function of the tool input that returns 'user-approval' or undefined). Dynamic approval is powerful for graduated safety: small payments execute automatically, large payments require human review.

import { convertToModelMessages, createUIMessageStreamResponse, streamText, tool, toUIMessageStream } from 'ai';
import { openai } from '@ai-sdk/openai';
import { z } from 'zod';

// app/api/chat/route.ts
export async function POST(req: Request) {
  const { messages } = await req.json();
  const result = streamText({
    model: openai('gpt-5.5'),
    messages: await convertToModelMessages(messages),
    tools: {
      deleteUser: tool({
        description: 'Delete a user account',
        inputSchema: z.object({ userId: z.string() }),
        execute: async ({ userId }) => deleteUserAccount(userId),
      }),
      processPayment: tool({
        description: 'Process a payment',
        inputSchema: z.object({ amount: z.number(), recipient: z.string() }),
        execute: async ({ amount, recipient }) => ({ status: 'processed', amount, recipient }),
      }),
    },
    toolApproval: {
      // Static: always requires approval
      deleteUser: 'user-approval',
      // Dynamic: approval only for amounts over 1000
      processPayment: async ({ amount }) => (amount > 1000 ? 'user-approval' : undefined),
    },
  });
  return createUIMessageStreamResponse({ stream: toUIMessageStream({ stream: result.stream }) });
}

On the frontend, the useChat hook surfaces the approval-requested state. You check for pending tool approvals and render approve/deny buttons. The addToolApprovalResponse function from useChat sends the user's decision back to the server, where the agent either executes the tool or skips it and continues reasoning.

Native MCP Client Integration

AI SDK ships MCP support in the @ai-sdk/mcp package through createMCPClient(). This function connects to any MCP server and makes its tools available through the same interface as native AI SDK tools. You can mix MCP tools with SDK-defined tools in a single agent, giving you the best of both worlds: the MCP ecosystem of community servers alongside your custom tool definitions.

The MCP client supports stdio transport (for local servers only) and HTTP transport (recommended for production, with optional headers and an OAuth client provider). Once connected, you access server tools via client.tools() and pass them to your agent or generateText()/streamText() calls. Close the client in onEnd when streaming, or in a finally block. In v7 HTTP redirects default to 'error'; set redirect: 'follow' if your server redirects.

import { createMCPClient } from '@ai-sdk/mcp';
import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
import { generateText, tool } from 'ai';
import { anthropic } from '@ai-sdk/anthropic';

// Connect to a local MCP server via stdio
const localClient = await createMCPClient({
  transport: new StdioClientTransport({
    command: 'node',
    args: ['src/stdio/dist/server.js'],
  }),
});

// Connect to a remote MCP server via HTTP
const dbClient = await createMCPClient({
  transport: {
    type: 'http',
    url: 'https://mcp.internal.company.com/db',
    headers: { Authorization: `Bearer ${process.env.MCP_TOKEN}` },
  },
});

try {
  // Combine MCP tools with native tools
  const result = await generateText({
    model: anthropic('claude-sonnet-5-5'),
    tools: {
      ...await localClient.tools(),
      ...await dbClient.tools(),
      myCustomTool: tool({ /* ... */ }),
    },
    prompt: 'Use the available tools to find open billing issues',
  });
  console.log(result.text);
} finally {
  // Clean up connections
  await localClient.close();
  await dbClient.close();
}

DevTools for Agent Debugging

AI SDK DevTools provides full visibility into LLM calls and agent execution. It requires AI SDK 7. Install it with pnpm add @ai-sdk/devtools, register it once at startup with registerTelemetry(DevToolsTelemetry()) (both from ai and @ai-sdk/devtools), launch the viewer with npx @ai-sdk/devtools@latest and open http://localhost:4983. Every step of every call is recorded: input messages, output text, model configuration, token usage, timing, tool calls, tool results, and raw provider HTTP requests and responses.

For multi-step agent loops, DevTools shows each iteration as a separate step within the run. You can see exactly which tools the agent called at each step, what results were returned, and how the agent reasoned about them before deciding on the next action. This is invaluable for debugging agents that take unexpected paths, consume too many tokens, or get stuck in loops.

DevTools is meant for local development only, not production. Captured data is saved in .devtools/generations.json, so make sure .devtools is listed in your .gitignore. Once the integration is registered, telemetry turns on automatically and no per-call configuration is needed, which makes it easy to follow a request from the React component rendering the streaming response down to the raw HTTP request sent to the model provider.

Streaming UI in Next.js with useChat and useCompletion

The useChat hook is the primary interface for building chat UIs with the AI SDK. It manages the full conversation lifecycle: appending user messages (sendMessage), streaming assistant responses token by token, maintaining conversation history, and tracking status (submitted, streaming, ready, error). The current docs pair it with a /api/chat route handler through DefaultChatTransport and render message.parts instead of the older content string.

The useCompletion hook handles single-prompt text completions for use cases like autocomplete, summarization, and inline suggestions. Both hooks support all AI SDK features including tool calls, structured output, and human-in-the-loop approval. The streaming is powered by the Node.js ReadableStream API, ensuring compatibility with edge runtimes and serverless functions.

// app/api/chat/route.ts - Route Handler
import { convertToModelMessages, createUIMessageStreamResponse, streamText, toUIMessageStream, type UIMessage } from 'ai';
import { anthropic } from '@ai-sdk/anthropic';

export async function POST(req: Request) {
  const { messages }: { messages: UIMessage[] } = await req.json();
  const result = streamText({
    model: anthropic('claude-sonnet-5-5'),
    instructions: 'You are a helpful assistant.',
    messages: await convertToModelMessages(messages),
  });
  return createUIMessageStreamResponse({
    stream: toUIMessageStream({ stream: result.stream }),
  });
}

// app/page.tsx - Client Component
'use client';
import { useChat } from '@ai-sdk/react';
import { DefaultChatTransport } from 'ai';
import { useState } from 'react';

export default function ChatPage() {
  const { messages, sendMessage, status } = useChat({
    transport: new DefaultChatTransport({ api: '/api/chat' }),
  });
  const [input, setInput] = useState('');

  return (
    <div>
      {messages.map(m => (
        <div key={m.id}>
          <strong>{m.role}:</strong>{' '}
          {m.parts.map((part, i) =>
            part.type === 'text' ? <span key={i}>{part.text}</span> : null
          )}
        </div>
      ))}
      <form onSubmit={e => {
        e.preventDefault();
        if (input.trim()) { sendMessage({ text: input }); setInput(''); }
      }}>
        <input value={input} onChange={e => setInput(e.target.value)}
               disabled={status !== 'ready'} placeholder="Ask something..." />
        <button type="submit" disabled={status !== 'ready'}>Send</button>
      </form>
    </div>
  );
}

Provider Switching: Claude, GPT, Gemini, Ollama

The AI SDK is model-agnostic by design. Every provider follows the same interface: you import the provider package, pass a model string, and the returned model object works with generateText(), streamText(), and ToolLoopAgent without any code changes. Switching from Claude to GPT to Gemini requires changing exactly two lines of code -- the import and the model string. You can also pass a plain gateway string such as 'anthropic/claude-sonnet-5.5' to route through the Vercel AI Gateway.

import { generateText } from 'ai';

// Anthropic Claude
import { anthropic } from '@ai-sdk/anthropic';
const result1 = await generateText({ model: anthropic('claude-sonnet-5-5'), prompt: 'Hello' });

// OpenAI GPT
import { openai } from '@ai-sdk/openai';
const result2 = await generateText({ model: openai('gpt-5.5'), prompt: 'Hello' });

// Google Gemini
import { google } from '@ai-sdk/google';
const result3 = await generateText({ model: google('gemini-3.1-pro-preview'), prompt: 'Hello' });

// Vercel AI Gateway: a plain provider/model string, no provider package
const result3b = await generateText({ model: 'anthropic/claude-sonnet-5.5', prompt: 'Hello' });

// Ollama (self-hosted)
import { ollama } from 'ollama-ai-provider';
const result4 = await generateText({ model: ollama('llama3.3'), prompt: 'Hello' });

// Any OpenAI-compatible endpoint
import { createOpenAICompatible } from '@ai-sdk/openai-compatible';
const custom = createOpenAICompatible({ baseURL: 'https://my-server.com/v1' });
const result5 = await generateText({ model: custom('my-model'), prompt: 'Hello' });

The Vercel AI Gateway adds model routing, cost controls, and fallback chains on top of the SDK's provider system. Route requests to different models based on task complexity, set spending limits per model, and configure automatic fallback to cheaper models when primary providers experience downtime. The gateway is optional -- the SDK works directly with providers without it.

As of November 2026, the AI Gateway lists about 435 models (vercel.com/ai-gateway/models), including Claude Fable 5.1, Opus 5.5, Sonnet 5.5 and Haiku 5.5, the OpenAI GPT-6 and GPT-5.6 families, Google Gemini 4 and 3.x models, DeepSeek V4 and V4.1, and Moonshot AI Kimi K3.1. The Voyage AI provider (@ai-sdk/voyage) adds embeddings and reranking capabilities from Voyage AI directly through the SDK interface, enabling semantic search and RAG pipelines without separate HTTP calls. Security note (April 2026): Vercel disclosed unauthorized access to internal systems via a compromised third-party AI tool (Context.ai OAuth breach). API keys should be rotated if used before April 19, 2026.

Deploying on Vercel Agentic Infrastructure

Agent workloads have fundamentally different requirements than traditional web applications. They need long-lived execution for multi-step reasoning, orchestration primitives for pause/resume workflows, model routing for cost optimization, sandboxed environments for code execution, and abuse resistance for public-facing agents. Vercel's Agentic Infrastructure addresses all of these.

The platform includes four key components: AI Gateway for model routing, rate limiting, and cost controls across all providers. Fluid Compute optimized for AI workloads with dynamic scaling based on token throughput rather than request count. Workflows and Queues that let agents pause execution (waiting for human approval, external API responses, or scheduled resumption) and resume without losing state. Sandbox for isolated code execution environments where agents can safely run generated code.

The shift is significant: over 30% of weekly deployments on Vercel are now initiated by coding agents, up 1,000% from six months prior. This has driven platform optimizations specifically for agent patterns -- longer function execution times, streaming-first infrastructure, and built-in token metering. You can deploy AI SDK agents on other platforms (AWS Lambda, Cloudflare Workers, self-hosted Node.js), but Vercel's infrastructure provides the tightest integration with the SDK.

Comparison: AI SDK 7 vs LangChain JS vs Mastra

The TypeScript AI framework landscape in 2026 has three major contenders. Vercel AI SDK 7 excels at streaming UI and React/Next.js integration. LangChain JS offers the broadest ecosystem for complex RAG pipelines and agent chains. Mastra, which uses AI SDK primitives internally, provides the cleanest agent abstraction with built-in workflow orchestration, vector search, and a local dev UI.

Dimension AI SDK 7 LangChain JS Mastra
Primary strength Streaming UI + Next.js RAG + complex chains Agent workflows + DX
Agent abstraction ToolLoopAgent AgentExecutor / LangGraph Built-in Agent class
TypeScript-native Yes (first-class) Partial (Python-first) Yes (TypeScript-only)
Bundle size (gzipped) ~15 kB ~101 kB ~25 kB
Edge runtime Full support Blocked Supported
MCP support Native client Community adapter Via AI SDK
Dev experience (NextBuild score) 8/10 5/10 9/10
Best for Next.js chat/streaming apps Complex RAG pipelines Agent-first backends

Mastra uses AI SDK primitives under the hood for LLM interactions, which means you get the best of both worlds: Mastra's clean agent abstraction and workflow orchestration with AI SDK's streaming and provider ecosystem. For pure Next.js streaming chat applications, AI SDK 7 alone provides the most direct path with minimal dependencies. For complex multi-agent systems with memory, RAG, and workflow orchestration, consider Mastra on top of AI SDK. For Python-first teams or projects requiring LangChain's mature retrieval ecosystem, LangChain JS is the pragmatic choice despite the larger bundle. For production AI agent architecture, see also the Claude Agent SDK guide and the Full-Stack AI guide.

Related Technologies