Mastra with AI Gateway
Mastra is a framework for building and deploying AI-powered features using a modern JavaScript stack powered by the Vercel AI SDK. Integrating with AI Gateway provides unified model management and routing capabilities.
For project setup, deployment, and storage options, see Mastra on Vercel.
First, create a new Mastra project using the CLI:
terminalpnpm dlx create-mastra@latestDuring the setup, the system prompts you to name your project, choose a default provider, and more. and more. Feel free to use the default settings.
To use the AI Gateway provider, install the
@ai-sdk/gatewaypackage along with Mastra:Terminalpnpm i @ai-sdk/gateway mastra @mastra/core @mastra/memoryTerminalyarn add @ai-sdk/gateway mastra @mastra/core @mastra/memoryTerminalnpm i @ai-sdk/gateway mastra @mastra/core @mastra/memoryTerminalbun add @ai-sdk/gateway mastra @mastra/core @mastra/memoryCreate or update your
.envfile with your Vercel AI Gateway API key:.envAI_GATEWAY_API_KEY=your-api-key-hereNow, swap out the
@ai-sdk/openaipackage (or your existing model provider) for the@ai-sdk/gatewaypackage.Update your agent configuration file, typically
src/mastra/agents/weather-agent.tsto the following code:src/mastra/agents/weather-agent.tsimport 'dotenv/config'; import { gateway } from '@ai-sdk/gateway'; import { Agent } from '@mastra/core/agent'; import { Memory } from '@mastra/memory'; import { LibSQLStore } from '@mastra/libsql'; import { weatherTool } from '../tools/weather-tool'; export const weatherAgent = new Agent({ name: 'Weather Agent', instructions: ` You are a helpful weather assistant that provides accurate weather information and can help planning activities based on the weather. Your primary function is to help users get weather details for specific locations. When responding: - Always ask for a location if none is provided - If the location name isn't in English, please translate it - If giving a location with multiple parts (e.g. "New York, NY"), use the most relevant part (e.g. "New York") - Include relevant details like humidity, wind conditions, and precipitation - Keep responses concise but informative - If the user asks for activities and provides the weather forecast, suggest activities based on the weather forecast. - If the user asks for activities, respond in the format they request. Use the weatherTool to fetch current weather data. `, model: gateway('google/gemini-3.1-pro-preview'), tools: { weatherTool }, memory: new Memory({ storage: new LibSQLStore({ url: 'file:../mastra.db', // path is relative to the .mastra/output directory }), }), }); (async () => { try { const response = await weatherAgent.generate( "What's the weather in San Francisco today?", ); console.log('Weather Agent Response:', response.text); } catch (error) { console.error('Error invoking weather agent:', error); } })();Since your agent is now configured to use AI Gateway, run the Mastra development server:
Terminalpnpm devTerminalyarn devTerminalnpm run devTerminalbun run devOpen the Mastra API to test your agents, workflows, and tools.
To give your Mastra agent isolated command execution, add a workspace with the VercelSandbox adapter. Follow Mastra with Vercel Sandbox to configure authentication, run an agent, and clean up its sandbox.
Connect the Mastra agent you deploy on Vercel to Slack, Discord, or Microsoft Teams with Chat SDK. Users can send prompts in chat while AI Gateway routes the agent's model requests. Inspect those requests in AI Gateway observability.
Mastra's channels integration accepts Chat SDK adapters through channels.adapters and registers their webhook routes. Point the platform's webhook URL to your deployed Mastra server. See Mastra's channels guide for adapter credentials, webhook configuration, and persistent storage.
Before you launch your Mastra agent, work through the agent checklist. It lists the AI Gateway settings to check, such as budgets, spend alerts, and model fallbacks. Its Mastra items include server authentication and storage.
Set the agent's model to a model from the gateway provider in @ai-sdk/gateway, such as gateway('google/gemini-3.1-pro-preview'). You can also pass a Mastra model router string that starts with vercel/, such as 'vercel/google/gemini-3.1-pro-preview'. Both options send the agent's requests through AI Gateway and read AI_GATEWAY_API_KEY. Mastra's model router uses an OpenAI-compatible endpoint, so some provider-specific features may not be available through it. Use the gateway provider when you need those features.
No. When your Mastra agent runs on Vercel, the gateway provider can authenticate with the deployment's OIDC token, and an API key takes precedence when you set one. For local development, either add AI_GATEWAY_API_KEY to your .env file or run vercel env pull to write a VERCEL_OIDC_TOKEN. Pulled OIDC tokens are valid for 12 hours, so pull again when yours expires.
Change the model ID in the agent's model setting, for example from gateway('google/gemini-3.1-pro-preview') to gateway('anthropic/claude-sonnet-5'). You don't need a different provider package or a separate provider API key. Browse available IDs in models and providers. To use your own provider credentials instead of AI Gateway's, add them at the team level with Bring Your Own Key (BYOK).
Open AI Gateway observability in your Vercel dashboard. Every model request your agent sends through AI Gateway appears there, with usage, spend, and a detailed request log at team and project level. You don't need to add instrumentation to your Mastra code to see these requests.
AI Gateway handles model requests. You can add these Vercel products to the same agent:
- Vercel Functions run your Mastra server when you deploy with
VercelDeployer. See Mastra on Vercel. - Vercel Sandbox runs agent commands in an isolated microVM, and Vercel Drives keep workspace files across sandbox runs.
- Vercel Blob stores reports and other files the agent creates.
- Vercel Workflows coordinate multi-step tasks that call the agent.
- Vercel Daemons run Mastra's background workers.
- Vercel Passport signs visitors in so you can scope agent memory to each user.
- Chat SDK connects the agent to Slack, Discord, or Microsoft Teams.
Was this helpful?