MCP Server - Vercel AI SDK
The Vercel AI SDK exposes MCP tools through its provider-independent tool interface. Install AI SDK Core, the Anthropic provider, and the MCP client:
pnpm add ai @ai-sdk/anthropic @ai-sdk/mcpCreate the MCP client, discover the Xweather tools, and pass them to generateText:
// app/api/weather/route.ts
import { anthropic } from "@ai-sdk/anthropic";
import { createMCPClient } from "@ai-sdk/mcp";
import { generateText, isStepCount } from "ai";
export async function POST(req: Request) {
const { location } = await req.json();
const mcpClient = await createMCPClient({
transport: {
type: "http",
url: "https://mcp.api.xweather.com/mcp?include_tools=xweather_get_current_weather,xweather_get_weather_conditions",
headers: {
Authorization: `Bearer ${process.env.XWEATHER_API_KEY}`,
},
},
});
try {
const tools = await mcpClient.tools();
const { text } = await generateText({
model: anthropic("claude-sonnet-4-6"),
tools,
stopWhen: isStepCount(5),
prompt: `Give me the next 6 hours of weather for ${location}`,
onToolExecutionStart({ toolCall }) {
console.info("Calling Xweather MCP tool", {
name: toolCall.toolName,
input: toolCall.input,
});
},
});
return Response.json({ answer: text });
} finally {
await mcpClient.close();
}
}Best practices
- Restrict the tools exposed to the model with Xweather’s
include_toolsorinclude_tagsquery parameters. - Close short-lived MCP clients in a
finallyblock. For streamed responses, close the client in theonEndcallback. - Store
XWEATHER_API_KEYin Vercel project environment variables; never expose it to the browser. - Use
onToolExecutionStartandonToolExecutionEndto capture tool arguments, results, timing, and errors for auditing.