How to integrate Neon MCP with Vercel AI SDK v6

Trusted by
AWS
Glean
Zoom
Airtable

30 min · no commitment · see it on your stack

Neon logo
Vercel AI SDK logo
divider

Introduction

This guide walks you through connecting Neon to Vercel AI SDK v6 using the Composio tool router. By the end, you'll have a working Neon agent that can create a new neon project with autoscaling, add a developer's email permission to a project, spin up a new branch database for testing through natural language commands.

This guide will help you understand how to give your Vercel AI SDK agent real control over a Neon account through Composio's Neon MCP server.

Before we dive in, let's take a quick look at the key ideas and tools involved.

Also integrate Neon with

TL;DR

Here's what you'll learn:
  • How to set up and configure a Vercel AI SDK agent with Neon integration
  • Using Composio's Tool Router to dynamically load and access Neon tools
  • Creating an MCP client connection using HTTP transport
  • Building an interactive CLI chat interface with conversation history management
  • Handling tool calls and results within the Vercel AI SDK framework

What is Vercel AI SDK?

The Vercel AI SDK is a TypeScript library for building AI-powered applications. It provides tools for creating agents that can use external services and maintain conversation state.

Key features include:

  • streamText: Core function for streaming responses with real-time tool support
  • MCP Client: Built-in support for Model Context Protocol via @ai-sdk/mcp
  • Step Counting: Control multi-step tool execution with stopWhen: stepCountIs()
  • OpenAI Provider: Native integration with OpenAI models

What is the Neon MCP server, and what's possible with it?

The Neon MCP server is an implementation of the Model Context Protocol that connects your AI agent and assistants like Claude, Cursor, etc directly to your Neon account. It provides structured and secure access to your serverless Postgres databases and project infrastructure, so your agent can perform actions like managing projects, configuring authentication, creating branches, and automating database operations on your behalf.

  • Project management and insights: Retrieve detailed information about specific Neon projects, including configurations, workflows, and current status for monitoring or troubleshooting.
  • Automated role and permission setup: Grant email-based permissions, add new roles to branches, and streamline access control across your projects with granular, automated adjustments.
  • Seamless API key and authentication management: Create new API keys for organizations or projects, manage authentication flows, and securely handle access credentials for integrations.
  • Database and branch orchestration: Spin up new Postgres databases within branches, create and configure compute endpoints, and automate the creation of development, testing, or isolated environments as needed.
  • Custom project provisioning: Launch new Neon projects with advanced quota, resource, and networking settings—tailored to your application's requirements and operational best practices.

Supported Tools & Triggers

Tools
Accept project transfer requestTool to accept a transfer request for a Neon project.
Access project details by idRetrieves detailed information about a specific Neon serverless Postgres project.
Add new jwks to project endpointAdds a new JSON Web Key Set (JWKS) URL to a Neon project for JWT-based authentication.
Add project email permissionAdds permissions for a specified email address to a particular project within the Neon B2B SaaS integration platform.
Add role to branchCreates a new PostgreSQL role within a specific branch of a Neon project.
Count project branchesTool to get the total number of branches in a Neon project.
Create API Key for OrganizationCreates a new API key for the specified organization in Neon.
Create Auth Provider SDK KeysTool to generate SDK or API keys for authentication providers.
Create auth userTool to create a new user in Neon Auth for a specific project branch.
Create branch databaseCreates a new database within a specified project and branch in the Neon platform.
Enable Neon Auth for branchTool to enable Neon Auth integration for a branch.
Create Neon Data APICreates a new instance of Neon Data API in the specified branch.
Create branch snapshotCreates a snapshot from the specified branch at a specific point in time.
Create compute endpointCreates a new compute endpoint for a specified branch within a Neon project.
Create New API KeyCreates a new personal API key for the authenticated Neon user account.
Create new project branchCreates a new branch in a Neon project.
Create anonymized branchCreates a new branch with anonymized data using PostgreSQL Anonymizer for static masking.
Create project transfer requestTool to create a transfer request for a Neon project.
Create project with quota and settingsCreates a new Neon project with specified configuration settings.
Set VPC endpoint restrictionSets or updates a VPC endpoint restriction for a Neon project.
Assign or Update VPC EndpointAssigns an AWS VPC endpoint to a Neon organization for Private Networking, or updates the label of an existing VPC endpoint assignment.
Delete api key by idDeletes a specific API key from the Neon platform.
Delete auth domainsDeletes domains from the redirect_uri whitelist for a specific branch's authentication configuration.
Delete OAuth providerDeletes an OAuth provider configuration from a specific branch in a Neon project.
Delete auth userDeletes an authentication user from a specified branch within a Neon project.
Delete branch data APIDeletes the Neon Data API for a specified branch and database.
Delete database from branchDeletes a specific database from a designated branch within a project in the Neon platform.
Delete organization api keyDeletes a specific API key associated with an organization in the Neon platform.
Delete organization memberRemoves a specific member from a Neon organization.
Delete project branch by idDeletes a specific branch within a project in the Neon B2B SaaS integration platform.
Delete project branch roleDeletes a PostgreSQL role from a specific branch within a Neon project.
Delete project by idPermanently deletes a Neon PostgreSQL project and all its associated resources.
Delete project endpointDeletes a specific endpoint within a Neon project.
Delete project jwks by idDeletes a specific JSON Web Key Set (JWKS) associated with a given project in the Neon B2B SaaS integration platform.
Delete project permissionDeletes a specific permission associated with a project in the Neon B2B SaaS integration platform.
Delete project snapshotDeletes a specific snapshot for a project in Neon.
Delete vpc endpoint by idsPermanently deletes a VPC endpoint from a Neon organization in a specified AWS region.
Delete vpc endpoint by project idDeletes a specific VPC endpoint within a designated project in the Neon platform.
Disable branches authTool to disable Neon Auth for a specific branch in a Neon project.
Fetch database for branchRetrieves a list of databases associated with a specific project and branch in the Neon platform.
Fetch organization members by idRetrieves a list of all members associated with a specific organization in the Neon B2B SaaS integration platform.
Fetch vpcendpoint details by idRetrieves the current state and configuration details of a specific VPC endpoint assigned to a Neon organization.
Finalize branch restoreFinalizes the restore operation for a branch created from a snapshot.
Get authRetrieves authentication information about the current API request credentials.
Get auth allow localhostRetrieves the allow localhost configuration for a specific branch in a Neon project.
Get auth email providerRetrieves the email provider configuration for Neon Auth on a specific branch.
Get available preload librariesRetrieves the list of available shared preload libraries for a Neon project.
Get branches anonymized statusRetrieves the current status of an anonymized branch, including its state and progress information.
Get branches backup scheduleRetrieves the backup schedule configuration for a specified branch within a Neon project.
Get Neon Data API for branchRetrieves the Neon Data API information for a specific branch and database.
Get branches for projectRetrieves a list of branches associated with a specific project in the Neon B2B SaaS integration platform.
Get branches masking rulesRetrieves the masking rules for the specified anonymized branch.
Get branch roles for projectRetrieves the roles associated with a specific branch within a project in the Neon B2B SaaS integration platform.
Get consumption history projectsRetrieves consumption history for projects within a Neon organization.
Get current user informationRetrieves the profile information for the currently authenticated user.
Get organization api keysRetrieves a list of all API keys associated with a specific organization in the Neon B2B SaaS integration platform.
Get project branchesRetrieves detailed information about a specific branch within a Neon project.
Get project branch roleRetrieves detailed information about a specific role within a particular branch of a Neon project.
Get project branch schema comparisonCompares the database schema of a branch with another branch's schema in a Neon project.
Get project connection uriRetrieves the connection URI for a specified project within the Neon B2B SaaS integration platform.
Get project endpoint informationRetrieves a list of all compute endpoints associated with a specific Neon project.
Get project operation by idRetrieves detailed information about a specific operation within a Neon serverless PostgreSQL project.
Get schema for project branchRetrieves the PostgreSQL database schema (DDL) for a specific database on a branch within a Neon project.
Get user organizationsRetrieves a list of organizations associated with the currently authenticated user in the Neon platform.
Get vpc region endpointsRetrieves a list of VPC endpoints for a specified organization within a particular AWS region.
List api keysRetrieves a list of API keys associated with the authenticated user's Neon account.
List auth domainsLists the domains in the redirect_uri whitelist for the specified project and branch.
List Auth OAuth ProvidersRetrieves the OAuth providers configured for Neon Auth on a specific branch.
List project snapshotsTool to list all snapshots for a specified Neon project.
List shared projectsRetrieves a list of Neon Postgres projects shared with your account.
List VPC endpoints for organizationTool to retrieve the list of VPC endpoints for a specified Neon organization across all regions.
Modify branch details in projectUpdates the details of a specific branch within a project in the Neon platform.
Patch branch database informationUpdates the properties of a specific database within a project branch in the Neon platform.
Reset role password for branchResets the password for a PostgreSQL role on a specific Neon branch and generates a new password.
Restart project endpointRestarts a Neon compute endpoint (Postgres instance) within a project.
Restore project branchThis endpoint restores a branch to a specific state or point in time.
Restore snapshot to new branchTool to restore a Neon snapshot to a new branch.
Retrieve account consumption historyRetrieves the consumption history for a specified account within the Neon platform.
Retrieve all regionsRetrieves a list of available geographic regions supported by the Neon B2B SaaS integration platform.
Retrieve branch database detailsRetrieves detailed information about a specific database within a Neon project and branch.
Retrieve branch endpointsRetrieves all compute endpoints associated with a specific branch in a Neon project.
Retrieve jwks for projectRetrieves the JSON Web Key Set (JWKS) for a specified project.
Retrieve organization by idRetrieves detailed information about a specific organization within the Neon platform.
Retrieve organization invitationsRetrieves a list of all pending invitations for a specified organization.
Retrieve organization member infoRetrieves detailed information about a specific member within an organization in the Neon B2B SaaS integration platform.
Retrieve project endpoint detailsRetrieves detailed information about a specific compute endpoint within a Neon serverless PostgreSQL project.
Retrieve project operationsRetrieves a list of operations associated with a specific project in the Neon B2B SaaS integration platform.
Retrieve project permissionsRetrieves the current permissions settings for a specific project within the Neon B2B SaaS integration platform.
Retrieve projects listRetrieves a list of all Neon projects associated with the authenticated user's account.
Retrieve vpc endpoints for projectRetrieves a list of VPC (Virtual Private Cloud) endpoints associated with a specific project in the Neon B2B SaaS integration platform.
Reveal role password in branchReveals the password for a specific role within a branch of a Neon project.
Send auth test emailTool to send a test email using specified SMTP configuration for Neon Auth.
Send organization invitationsCreates and sends invitations to join an organization in the Neon B2B SaaS integration platform.
Set branch as defaultSets a specified branch as the default branch for a given project in Neon.
Start branch anonymizationStarts the anonymization process for an anonymized branch that is in the initialized, error, or anonymized state.
Start endpoint for projectStarts a suspended or idle compute endpoint for a Neon PostgreSQL project.
Suspend project endpoint by idSuspends a specific endpoint within a project in the Neon B2B SaaS integration platform.
Transfer projects between organizationsTransfers selected projects from one organization to another organization.
Transfer user projects to organizationTransfers multiple projects from the authenticated user's personal account to a specified organization within the Neon B2B SaaS integration platform.
Update auth allow localhostUpdates the allow localhost configuration for a specific branch in a Neon project.
Update branch auth email providerUpdates the email provider configuration for a specific branch's authentication system.
Update branches data APIUpdates the Neon Data API configuration for the specified branch.
Update branches masking rulesUpdates the masking rules for the specified anonymized branch.
Update organization member roleUpdates the role of a specific member within an organization in the Neon B2B SaaS integration platform.
Update project compute endpoint settingsUpdates the configuration of a specific compute endpoint within a Neon project.
Update project settings by idUpdates the configuration and settings of a specific Neon project.
Update project snapshotTool to update the name of a specific snapshot in a Neon project.

What is the Composio tool router, and how does it fit here?

What is Composio SDK?

Composio's Composio SDK helps agents find the right tools for a task at runtime. You can plug in multiple toolkits (like Gmail, HubSpot, and GitHub), and the agent will identify the relevant app and action to complete multi-step workflows. This can reduce token usage and improve the reliability of tool calls. Read more here: Getting started with Composio SDK

The tool router generates a secure MCP URL that your agents can access to perform actions.

How the Composio SDK works

The Composio SDK follows a three-phase workflow:

  1. Discovery: Searches for tools matching your task and returns relevant toolkits with their details.
  2. Authentication: Checks for active connections. If missing, creates an auth config and returns a connection URL via Auth Link.
  3. Execution: Executes the action using the authenticated connection.

Step-by-step Guide

Prerequisites

Before you begin, make sure you have:
  • Node.js and npm installed
  • A Composio account with API key
  • An OpenAI API key

Getting API Keys for OpenAI and Composio

OpenAI API Key
  • Go to the OpenAI dashboard and create an API key. You'll need credits to use the models, or you can connect to another model provider.
  • Keep the API key safe.
Composio API Key
  • Log in to the Composio dashboard.
  • Navigate to your API settings and generate a new API key.
  • Store this key securely as you'll need it for authentication.

Install required dependencies

bash
npm install @ai-sdk/openai @ai-sdk/mcp @composio/core ai dotenv

First, install the necessary packages for your project.

What you're installing:

  • @ai-sdk/openai: Vercel AI SDK's OpenAI provider
  • @ai-sdk/mcp: MCP client for Vercel AI SDK
  • @composio/core: Composio SDK for tool integration
  • ai: Core Vercel AI SDK
  • dotenv: Environment variable management

Set up environment variables

bash
OPENAI_API_KEY=your_openai_api_key_here
COMPOSIO_API_KEY=your_composio_api_key_here
COMPOSIO_USER_ID=your_user_id_here

Create a .env file in your project root.

What's needed:

  • OPENAI_API_KEY: Your OpenAI API key for GPT model access
  • COMPOSIO_API_KEY: Your Composio API key for tool access
  • COMPOSIO_USER_ID: A unique identifier for the user session

Import required modules and validate environment

typescript
import "dotenv/config";
import { openai } from "@ai-sdk/openai";
import { Composio } from "@composio/core";
import * as readline from "readline";
import { streamText, type ModelMessage, stepCountIs } from "ai";
import { createMCPClient } from "@ai-sdk/mcp";

const composioAPIKey = process.env.COMPOSIO_API_KEY;
const composioUserID = process.env.COMPOSIO_USER_ID;

if (!process.env.OPENAI_API_KEY) throw new Error("OPENAI_API_KEY is not set");
if (!composioAPIKey) throw new Error("COMPOSIO_API_KEY is not set");
if (!composioUserID) throw new Error("COMPOSIO_USER_ID is not set");

const composio = new Composio({
  apiKey: composioAPIKey,
});
What's happening:
  • We're importing all necessary libraries including Vercel AI SDK's OpenAI provider and Composio
  • The dotenv/config import automatically loads environment variables
  • The MCP client import enables connection to Composio's tool server

Create Tool Router session and initialize MCP client

typescript
async function main() {
  // Create a tool router session for the user
  const session = await composio.create(composioUserID!, {
    toolkits: ["neon"],
  });

  const mcpUrl = session.mcp.url;
What's happening:
  • We're creating a Tool Router session that gives your agent access to Neon tools
  • The create method takes the user ID and specifies which toolkits should be available
  • The returned mcp object contains the URL and authentication headers needed to connect to the MCP server
  • This session provides access to all Neon-related tools through the MCP protocol

Connect to MCP server and retrieve tools

typescript
const mcpClient = await createMCPClient({
  transport: {
    type: "http",
    url: mcpUrl,
    headers: session.mcp.headers, // Authentication headers for the Composio MCP server
  },
});

const tools = await mcpClient.tools();
What's happening:
  • We're creating an MCP client that connects to our Composio Tool Router session via HTTP
  • The mcp.url provides the endpoint, and mcp.headers contains authentication credentials
  • The type: "http" is important - Composio requires HTTP transport
  • tools() retrieves all available Neon tools that the agent can use

Initialize conversation and CLI interface

typescript
let messages: ModelMessage[] = [];

console.log("Chat started! Type 'exit' or 'quit' to end the conversation.\n");
console.log(
  "Ask any questions related to neon, like summarize my last 5 emails, send an email, etc... :)))\n",
);

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  prompt: "> ",
});

rl.prompt();
What's happening:
  • We initialize an empty messages array to maintain conversation history
  • A readline interface is created to accept user input from the command line
  • Instructions are displayed to guide the user on how to interact with the agent

Handle user input and stream responses with real-time tool feedback

typescript
rl.on("line", async (userInput: string) => {
  const trimmedInput = userInput.trim();

  if (["exit", "quit", "bye"].includes(trimmedInput.toLowerCase())) {
    console.log("\nGoodbye!");
    rl.close();
    process.exit(0);
  }

  if (!trimmedInput) {
    rl.prompt();
    return;
  }

  messages.push({ role: "user", content: trimmedInput });
  console.log("\nAgent is thinking...\n");

  try {
    const stream = streamText({
      model: openai("gpt-5"),
      messages,
      tools,
      toolChoice: "auto",
      stopWhen: stepCountIs(10),
      onStepFinish: (step) => {
        for (const toolCall of step.toolCalls) {
          console.log(`[Using tool: ${toolCall.toolName}]`);
          }
          if (step.toolCalls.length > 0) {
            console.log(""); // Add space after tool calls
          }
        },
      });

      for await (const chunk of stream.textStream) {
        process.stdout.write(chunk);
      }

      console.log("\n\n---\n");

      // Get final result for message history
      const response = await stream.response;
      if (response?.messages?.length) {
        messages.push(...response.messages);
      }
    } catch (error) {
      console.error("\nAn error occurred while talking to the agent:");
      console.error(error);
      console.log(
        "\nYou can try again or restart the app if it keeps happening.\n",
      );
    } finally {
      rl.prompt();
    }
  });

  rl.on("close", async () => {
    await mcpClient.close();
    console.log("\n👋 Session ended.");
    process.exit(0);
  });
}

main().catch((err) => {
  console.error("Fatal error:", err);
  process.exit(1);
});
What's happening:
  • We use streamText instead of generateText to stream responses in real-time
  • toolChoice: "auto" allows the model to decide when to use Neon tools
  • stopWhen: stepCountIs(10) allows up to 10 steps for complex multi-tool operations
  • onStepFinish callback displays which tools are being used in real-time
  • We iterate through the text stream to create a typewriter effect as the agent responds
  • The complete response is added to conversation history to maintain context
  • Errors are caught and displayed with helpful retry suggestions

Complete Code

Here's the complete code to get you started with Neon and Vercel AI SDK:

typescript
import "dotenv/config";
import { openai } from "@ai-sdk/openai";
import { Composio } from "@composio/core";
import * as readline from "readline";
import { streamText, type ModelMessage, stepCountIs } from "ai";
import { createMCPClient } from "@ai-sdk/mcp";

const composioAPIKey = process.env.COMPOSIO_API_KEY;
const composioUserID = process.env.COMPOSIO_USER_ID;

if (!process.env.OPENAI_API_KEY) throw new Error("OPENAI_API_KEY is not set");
if (!composioAPIKey) throw new Error("COMPOSIO_API_KEY is not set");
if (!composioUserID) throw new Error("COMPOSIO_USER_ID is not set");

const composio = new Composio({
  apiKey: composioAPIKey,
});

async function main() {
  // Create a tool router session for the user
  const session = await composio.create(composioUserID!, {
    toolkits: ["neon"],
  });

  const mcpUrl = session.mcp.url;

  const mcpClient = await createMCPClient({
    transport: {
      type: "http",
      url: mcpUrl,
      headers: session.mcp.headers, // Authentication headers for the Composio MCP server
    },
  });

  const tools = await mcpClient.tools();

  let messages: ModelMessage[] = [];

  console.log("Chat started! Type 'exit' or 'quit' to end the conversation.\n");
  console.log(
    "Ask any questions related to neon, like summarize my last 5 emails, send an email, etc... :)))\n",
  );

  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
    prompt: "> ",
  });

  rl.prompt();

  rl.on("line", async (userInput: string) => {
    const trimmedInput = userInput.trim();

    if (["exit", "quit", "bye"].includes(trimmedInput.toLowerCase())) {
      console.log("\nGoodbye!");
      rl.close();
      process.exit(0);
    }

    if (!trimmedInput) {
      rl.prompt();
      return;
    }

    messages.push({ role: "user", content: trimmedInput });
    console.log("\nAgent is thinking...\n");

    try {
      const stream = streamText({
        model: openai("gpt-5"),
        messages,
        tools,
        toolChoice: "auto",
        stopWhen: stepCountIs(10),
        onStepFinish: (step) => {
          for (const toolCall of step.toolCalls) {
            console.log(`[Using tool: ${toolCall.toolName}]`);
          }
          if (step.toolCalls.length > 0) {
            console.log(""); // Add space after tool calls
          }
        },
      });

      for await (const chunk of stream.textStream) {
        process.stdout.write(chunk);
      }

      console.log("\n\n---\n");

      // Get final result for message history
      const response = await stream.response;
      if (response?.messages?.length) {
        messages.push(...response.messages);
      }
    } catch (error) {
      console.error("\nAn error occurred while talking to the agent:");
      console.error(error);
      console.log(
        "\nYou can try again or restart the app if it keeps happening.\n",
      );
    } finally {
      rl.prompt();
    }
  });

  rl.on("close", async () => {
    await mcpClient.close();
    console.log("\n👋 Session ended.");
    process.exit(0);
  });
}

main().catch((err) => {
  console.error("Fatal error:", err);
  process.exit(1);
});

Conclusion

You've successfully built a Neon agent using the Vercel AI SDK with streaming capabilities! This implementation provides a powerful foundation for building AI applications with natural language interfaces and real-time feedback.

Key features of this implementation:

  • Real-time streaming responses for a better user experience with typewriter effect
  • Live tool execution feedback showing which tools are being used as the agent works
  • Dynamic tool loading through Composio's Tool Router with secure authentication
  • Multi-step tool execution with configurable step limits (up to 10 steps)
  • Comprehensive error handling for robust agent execution
  • Conversation history maintenance for context-aware responses

You can extend this further by adding custom error handling, implementing specific business logic, or integrating additional Composio toolkits to create multi-app workflows.

How to build Neon MCP Agent with another framework

FAQ

What are the differences in Tool Router MCP and Neon MCP?

With a standalone Neon MCP server, the agents and LLMs can only access a fixed set of Neon tools tied to that server. However, with the Composio Tool Router, agents can dynamically load tools from Neon and many other apps based on the task at hand, all through a single MCP endpoint.

Can I use Tool Router MCP with Vercel AI SDK v6?

Yes, you can. Vercel AI SDK v6 fully supports MCP integration. You get structured tool calling, message history handling, and model orchestration while Tool Router takes care of discovering and serving the right Neon tools.

Can I manage the permissions and scopes for Neon while using Tool Router?

Yes, absolutely. You can configure which Neon scopes and actions are allowed when connecting your account to Composio. You can also bring your own OAuth credentials or API configuration so you keep full control over what the agent can do.

How safe is my data with Composio Tool Router?

All sensitive data such as tokens, keys, and configuration is fully encrypted at rest and in transit. Composio is SOC 2 Type 2 compliant and follows strict security practices so your Neon data and credentials are handled as safely as possible.

Used by agents from

Context
Letta
glean
HubSpot
Agent.ai
Altera
DataStax
Entelligence
Rolai
Context
Letta
glean
HubSpot
Agent.ai
Altera
DataStax
Entelligence
Rolai
Context
Letta
glean
HubSpot
Agent.ai
Altera
DataStax
Entelligence
Rolai

Never worry about agent reliability

We handle tool reliability, observability, and security so you never have to second-guess an agent action.