Skip to content
Docs

AI SDK with MCP

Use the AI SDK to call tools from a Model Context Protocol (MCP) server hosted on Vercel. The @ai-sdk/mcp client discovers the server's tools, and AI Gateway handles model requests.

Before you begin, you need:

Install the AI SDK and its MCP client:

Terminal
pnpm i ai @ai-sdk/mcp
Terminal
yarn add ai @ai-sdk/mcp
Terminal
npm i ai @ai-sdk/mcp
Terminal
bun add ai @ai-sdk/mcp

Save your AI Gateway API key and deployed MCP endpoint in a .env file. Replace your-project with your deployment's domain:

.env
AI_GATEWAY_API_KEY=your_api_key_here
MCP_SERVER_URL=https://your-project.vercel.app/api/mcp

If your MCP server requires a bearer token, also set MCP_SERVER_TOKEN to a token the server accepts. For OAuth consent and token refresh, follow Vercel Connect with AI SDK and MCP.

For a deployment with Deployment Protection, also configure automation access on the MCP client transport.

Create an entry file that connects over Streamable HTTP and passes the discovered tools to generateText. Run this code on the server or from your terminal to keep credentials private:

index.mts
import { createMCPClient } from '@ai-sdk/mcp';
import { generateText, isStepCount } from 'ai';
 
const url = process.env.MCP_SERVER_URL;
if (!url) {
  throw new Error('Set MCP_SERVER_URL in your .env file.');
}
 
const token = process.env.MCP_SERVER_TOKEN;
const client = await createMCPClient({
  transport: {
    type: 'http',
    url,
    ...(token ? { headers: { Authorization: `Bearer ${token}` } } : {}),
  },
});
 
try {
  const tools = await client.tools();
  const result = await generateText({
    model: 'anthropic/claude-opus-5',
    tools,
    prompt: 'Use roll_dice to roll a six-sided die once.',
    stopWhen: isStepCount(5),
  });
 
  console.log(result.text);
} finally {
  await client.close();
}

The stop condition allows up to five model steps so the model can call the tool and respond with its result. The finally block closes the MCP client after generation succeeds or fails.

Run the TypeScript example with tsx, loading credentials from .env:

terminal
pnpm dlx tsx --env-file=.env index.mts

For JavaScript, run node --env-file=.env index.mjs. Your terminal displays the model's response with a dice result between one and six.

Last updated September 18, 2026

Was this helpful?

supported.