Skip to content
Docs

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.

  1. First, create a new Mastra project using the CLI:

    terminal
    pnpm dlx create-mastra@latest

    During 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.

  2. To use the AI Gateway provider, install the @ai-sdk/gateway package along with Mastra:

    Terminal
    pnpm i @ai-sdk/gateway mastra @mastra/core @mastra/memory
    Terminal
    yarn add @ai-sdk/gateway mastra @mastra/core @mastra/memory
    Terminal
    npm i @ai-sdk/gateway mastra @mastra/core @mastra/memory
    Terminal
    bun add @ai-sdk/gateway mastra @mastra/core @mastra/memory
  3. Create or update your .env file with your Vercel AI Gateway API key:

    .env
    AI_GATEWAY_API_KEY=your-api-key-here
  4. Now, swap out the @ai-sdk/openai package (or your existing model provider) for the @ai-sdk/gateway package.

    Update your agent configuration file, typically src/mastra/agents/weather-agent.ts to the following code:

    src/mastra/agents/weather-agent.ts
    import '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);
      }
    })();
  5. Since your agent is now configured to use AI Gateway, run the Mastra development server:

    Terminal
    pnpm dev 
    Terminal
    yarn dev 
    Terminal
    npm run dev 
    Terminal
    bun run dev 

    Open 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:

Last updated September 8, 2026

Was this helpful?

supported.