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:
- A JavaScript or TypeScript project with Node.js 22 or later. This example uses AI SDK 7 and ECMAScript modules (ESM).
- An AI Gateway API key.
- The
roll_diceMCP server from Deploy MCP servers to Vercel, deployed at a URL your client can reach.
Install the AI SDK and its MCP client:
pnpm i ai @ai-sdk/mcpyarn add ai @ai-sdk/mcpnpm i ai @ai-sdk/mcpbun add ai @ai-sdk/mcpSave your AI Gateway API key and deployed MCP endpoint in a .env file. Replace your-project with your deployment's domain:
AI_GATEWAY_API_KEY=your_api_key_here
MCP_SERVER_URL=https://your-project.vercel.app/api/mcpIf 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:
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:
pnpm dlx tsx --env-file=.env index.mtsFor JavaScript, run node --env-file=.env index.mjs. Your terminal displays the model's response with a dice result between one and six.
- Follow Vercel Connect with AI SDK and MCP for a streaming route with user consent and OAuth authentication.
- Configure model requests with AI SDK and AI Gateway.
- Explore MCP integrations for TanStack AI and eve examples.
Was this helpful?