For AI agents: a documentation index is available at https://www.mongodb.com/docs/llms.txt — markdown versions of all pages are available by appending .md to any URL path.

Get Started with the MongoDB Vercel AI SDK Integration

You can integrate MongoDB with the Vercel AI SDK to configure memory for your agents that persists across sessions. This tutorial creates a MongoDB memory provider, builds an agent that saves and recalls memories, and runs the agent twice to show that it retrieves information from a previous run.

In this tutorial, you perform the following tasks:

  1. Set up your environment.

  2. Build an agent that has persistent memory.

  3. Run the agent and review the output.

The Vercel AI SDK is a TypeScript framework for building AI applications and agents. The @mongodb-developer/vercel-ai-memory package provides MongoDB-backed persistent memory for agents built with the SDK. The package stores memories in five tiers. To learn more about the memory tiers, see Integrate MongoDB with the Vercel AI SDK.

This tutorial uses the memory tool commands that the package exposes to the agent. The model calls the session_recent command to restore the conversation history at the start of each run, and calls the session_append and semantic_save commands to store new information.

To complete this tutorial, you must have the following resources:

  • One of the following MongoDB cluster types:

    • An Atlas cluster running MongoDB version 6.0.11, 7.0.2, or later. Ensure that your IP address is included in your Atlas project's access list.

    • A local Atlas deployment created using Python and Docker. Install atlas-local-lib-py (pip install atlas-local-lib-py) to programmatically create and manage local deployments. To learn more, see the atlas-local-lib-py repository.

    • A MongoDB Community cluster with Search and Vector Search installed.

  • An OpenAI API Key. You must have an OpenAI account with credits available for API requests. To learn more about registering an OpenAI account, see the OpenAI API website.

  • A Voyage AI API key. To create an API key, see Manage Voyage AI Model API Keys.

    This tutorial configures a base URL that routes embedding requests to MongoDB's Voyage AI endpoint. If you generated your API key directly from Voyage AI, remove the baseURL option specified in the memory provider step.

  • Node.js and npm.

In this section, you prepare your environment by installing the required dependencies, setting your environment variables, and creating a project file.

1

Run the following commands in your terminal to create a new directory named vercel-ai-mongodb-project and install the required dependencies:

mkdir vercel-ai-mongodb-projectcd vercel-ai-mongodb-projectnpm init -ynpm install @mongodb-developer/vercel-ai-memory ai mongodb zod @ai-sdk/openai voyage-ai-provider dotenvnpm install --save-dev tsx @types/node
2

In your vercel-ai-mongodb-project directory, create a .env file and add the following code:

OPENAI_API_KEY="<openai-api-key>"VOYAGE_API_KEY="<voyage-api-key>"MONGODB_URI="<connection-string>"

Replace <connection-string> with the connection string for your Atlas cluster or local Atlas deployment.

Your connection string should use the following format:

mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net

IMPORTANT: Ensure that your connection string includes your database user's credentials. To learn more about finding your connection string, see Connect to a Cluster via Client Libraries.

3

In your vercel-ai-mongodb-project directory, create a file named main.ts. Add the following code to this file to load your environment variables and import the required modules:

import 'dotenv/config'import { createMongoDBMemory } from '@mongodb-developer/vercel-ai-memory'import { createVoyage } from 'voyage-ai-provider'import { openai } from '@ai-sdk/openai'import { ToolLoopAgent } from 'ai'

In future steps, you add code to this file to create the memory provider and build your agent.

In this section, you create a MongoDB memory provider, build an agent that uses the provider to store and retrieve memories, and add the code that runs the agent.

1

Add the following code to your main.ts file to create a Voyage AI client and a memory provider that uses a Voyage AI embedding model:

const voyage = createVoyage({ apiKey: process.env.VOYAGE_API_KEY, baseURL: 'https://ai.mongodb.com/v1',}) const mongodbMemory = createMongoDBMemory({ uri: process.env.MONGODB_URI!, embedder: voyage.embeddingModel('voyage-4'),})

Important

Voyage AI API keys that you create in Atlas require the MongoDB Voyage AI endpoint, which the baseURL option specifies. If you generated your API key directly from Voyage AI, remove the baseURL option.

The provider connects to MongoDB on first use and creates the agent_memory database. Then, it adds one collection for each memory tier to the database. The provider also creates the MongoDB Vector Search indexes that semantic recall requires. To learn more about the collections and indexes that the provider creates, see Collections and Indexes in the Vercel AI SDK reference.

2

Add the following code to your main.ts file to create an agent whose memory tools are scoped to one user and session:

const agent = new ToolLoopAgent({ model: openai('gpt-4.1'), tools: mongodbMemory({ userId: 'alice', sessionId: 'sess-001' }), instructions: `You are an assistant with persistent memory. At the start of every conversation, call session_recent to restore context and semantic_search to recall facts about the user. Save each conversation turn with session_append. Save important facts about the user with semantic_save.`,})

The instructions tell the model which memory commands to call. The userId and sessionId values scope the memories that the agent stores and retrieves.

3

Add the following code to your main.ts file to pass a prompt to the agent from the command line, print the response, and close the MongoDB connection:

async function main() { const prompt = process.argv[2] if (!prompt) { console.error('Usage: npx tsx main.ts "<your message>"') process.exit(1) } const result = await agent.generate({ prompt }) console.log('[agent]:', result.text) await mongodbMemory.close()} main().catch((error) => { console.error(error) process.exit(1)})

In this section, you run the main.ts file and provide information to your agent. Then, you run the agent again and prompt it to recall this information.

1

From your vercel-ai-mongodb-project directory, run the following command:

npx tsx main.ts "I'm a marine biologist who studies emperor penguins in Antarctica. Remember that."

If the command runs successfully, the output resembles the following:

[agent]: I've noted that you are a marine biologist studying emperorpenguins in Antarctica.
2

Run the agent again and pass the following prompt that asks the agent to recall previous information:

npx tsx main.ts "What do I study, and where?"

The output resembles the following:

[agent]: You are a marine biologist who studies emperor penguins inAntarctica.

The agent uses memory to answer the prompt. Both runs pass the same userId and sessionId values, so the model calls the session_recent and semantic_search commands at the start of the second run. These commands restore the conversation and the memories that the first run stored in MongoDB.

Note

The MongoDB Vector Search indexes build asynchronously after the first run. If the agent doesn't recall the information, wait a few seconds and run the command again.

To learn more about the memory provider, including the full parameter reference, the retention and topology options, and all memory tool commands, see Integrate MongoDB with the Vercel AI SDK.

To learn more about the Vercel AI SDK, see the Vercel AI SDK documentation.