Sari la conținutul principal

MongoDB Atlas Agent Engine: Build, Deploy, and Govern Your Agents

Learn how to build, deploy, and govern AI agents with long-term memory, identity, and tracing using MongoDB Atlas Agent Engine.
· 14 min. citește

Explorează cu ajutorul AI-ului

Adaugă DataCamp ca sursă preferată pe Google

Big Model vs. Big Harness has been an ongoing debate in AI engineering. An agent harness is everything besides the LLM that makes an agent work, including the runtime, tools, context, and guardrails surrounding the model. As models improve, the parts of the harness that coax better reasoning out of the model, such as prompts and loops, will likely get absorbed into the model, while the control layers won't. Persistent memory, identity and least-privilege access, isolated execution, governance policies, and audit trails exist to persist, constrain, and record the model's work, so they have to live outside it.

MongoDB recently announced the Atlas Agent Engine, now in public preview, which provides this control layer as a managed service. Agent Engine gives your agents an identity, a managed runtime, long-term memory, auditability, and guardrails. It's also neutral across models, frameworks, and data sources: you can bring a LangGraph agent over with a handful of code changes, and it can keep accessing data where it already lives, without moving it to MongoDB.

In this tutorial, you'll see how to migrate a LangGraph agent to Atlas Agent Engine. Specifically, we will cover the following:

  • Packaging an agent for deployment on Agent Engine
  • Configuring long-term memory for the agent via Agent Engine
  • Deploying the agent on Agent Engine
  • Adding governance policies and guardrails to the agent in Agent Engine

Migrating a LangGraph Agent to Atlas Agent Engine

In this tutorial, we'll walk through how we migrated a travel agent built with LangGraph to Agent Engine. This includes the changes we made to the agent's code and the configuration files we added to get it ready for Agent Engine. You'll make similar changes to migrate your own agents.

The migrated agent is available as a ready-to-deploy template in our Agent Engine examples repository on GitHub.

About the Agent

The travel agent we built helps users find flights and accommodations and books them on their behalf once they approve. The flight data and Airbnb listings are stored in MongoDB, and the agent uses a combination of custom tools and tools from the MongoDB Atlas Managed MCP Server to query the data and make bookings:

MCP tools:

  • remote-atlas-connect: Connect to an Atlas cluster.
  • list-collections: Return the list of collections in a MongoDB database.
  • collection-schema: Sample documents from a collection to infer their schema.
  • aggregate: Run MongoDB aggregation pipelines.

Custom tools:

  • list_bookings: List existing bookings for a given user.
  • create_booking: Validate a booking and save booking details to a MongoDB collection.

Architecture

On Agent Engine, the system looks like this:

Architecture diagram of an agent deployed on Atlas Agent Engine

In Agent Engine, the agent gets its own runtime environment, called a workspace, within a project. Its code runs in two sandboxes: the agent sandbox runs the agent's graph, and the tool sandbox runs the agent's tools and LLM calls, including calls to the MongoDB Atlas Managed MCP Server. Agent Engine also comes with a memory service, lets you set governance policies and guardrails, and traces and monitors every tool and LLM call. The agent's memory, state, and application data all live in MongoDB Atlas.

The project and workspace structure also applies to how you organize your code: a project directory with one workspace directory per agent you want to deploy to the project. We will use the following terminology throughout the tutorial:

  • Project directory: The top-level folder for an Agent Engine project.
  • Workspace directory: A folder inside the project directory for a single agent, which Agent Engine deploys as its own workspace.

We migrated a single agent, so the template's project directory in the GitHub repo has one workspace directory (agents/trip-planner), which holds the agent's code and configuration files. To run more agents in the same project, add a workspace directory for each one under agents/. Here's the template's layout:

travel-agent/                 # project directory
├── project-config.yaml
└── agents/
    └── trip-planner/         # workspace directory
        ├── agent.yaml
        ├── pyproject.toml
        ├── env.example
        ├── data/
        ├── scripts/
        └── src/trip_planner/

Note: If you're building a new agent from scratch, the agentengine create command scaffolds the above structure for you.

Step 1: Prerequisites

Whether you're deploying our template or your own agent to Agent Engine, complete the following tasks before you begin:

If you're deploying the template or an agent that accesses the MongoDB Atlas Managed MCP Server, you'll also need to create an Atlas Managed MCP configuration with the Project Data Access Read Only role, and copy its client ID and secret.

Step 2: Migrate the Agent Code

To migrate the travel agent to Agent Engine, we first made a few changes to its code. You'll make similar changes if you're migrating your own agent.

Step 2.1: Wrap the agent with the App class

To connect the agent to Agent Engine, we created an instance of the App class from agent_engine_sdk_langgraph, which is the LangGraph adapter for the Agent Engine SDK. This is used to register the agent's tools and graph, and to route LLM and tool calls through Agent Engine so they can be traced and governed.

# src/trip_planner/main.py

from agent_engine_sdk_langgraph import App

app = App(app_name="trip-planner")

Step 2.2: Wrap the LLM with app.llm()

Next, we wrapped the LLM instance in app.llm() to route all LLM calls through Agent Engine's audited execution path.

# src/trip_planner/main.py

def build_agent() -> CompiledStateGraph:
    """Build the LangGraph agent."""
    logger.info("Building trip-planner graph")
    llm = app.llm(build_llm())

Step 2.3: Register and load tools with app

In LangGraph, you use the @tool decorator to automatically generate tool definitions for any tools that you write for your agents. In the Agent Engine SDK, you use the @app.tool() decorator, which generates the same definitions and also registers the tools with Agent Engine, so tool calls run through it and can be traced and governed. For our travel agent, we did this for the two custom tools, list_bookings and create_booking.

# src/trip_planner/tools.py

def register(app: App) -> None:
    ...
    @app.tool()
    def create_booking(
        booking_type: Literal["flight", "accommodation"],
        item_name: str,
        destination: str,
        traveler_name: str,
        travelers: int = 1,
        nights: int = 1,
    ) -> str:
        """Book a flight or an accommodation at its catalog price.

        Args:
            booking_type: Either "flight" or "accommodation".
            item_name: Flight number for flights, or listing name for accommodation.
            destination: Destination city, e.g. "Barcelona".
            traveler_name: Full name of the traveler making the booking.
            travelers: Number of travelers. Defaults to 1.
            nights: Number of nights, for accommodation. Defaults to 1.
        """
        try:
            details = validate_booking(booking_type, item_name, destination, travelers, nights)
        ...
        return (
            f"Booked {booking_type} to {destination}: {item_name}. "
            f"Total price ${details['price_usd']:.2f} for {travelers} travelers."
        )

    @app.tool()
    def list_bookings() -> str:
        """List the current user's bookings, newest first."""
        bookings = (
            get_database()["bookings"]
            .find({"user_id": current_user_id()}, {"_id": 0, "user_id": 0})
            .sort("created_at", -1)
            .limit(MAX_RESULTS)
        )
        return json_util.dumps(list(bookings))

Then, instead of passing the list of tools to the LLM and the graph, we got them from app. app.get_tools() returns the tools for the graph, and app.get_tool_schemas() returns them for binding to the LLM:

# src/trip_planner/main.py

tools = app.get_tools()
tools_map = {t.name: t for t in tools}
prompt = ChatPromptTemplate.from_messages(
    [
        ("system", SYSTEM_PROMPT + MEMORY_PROMPT),
        MessagesPlaceholder(variable_name="messages"),
    ]
).partial(
    top_k=5,
    tool_names=", ".join(tools_map),
    database=database_name(),
    project_id=project_id,
    cluster_name=cluster_name,
)
llm_with_tools = prompt | llm.bind_tools(app.get_tool_schemas())

Both methods also return the tools from any remote MCP servers configured in the agent.yaml (see Step 4). That's how the travel agent gets the tools from the MongoDB Atlas Managed MCP Server without any tool code.

Step 2.4: Replace the LangGraph checkpointer with the Agent Engine's checkpointer

The original agent persisted its state and short-term memory in MongoDB using the MongoDBSaver checkpointer integration. To let Agent Engine manage this instead, we replaced the MongoDBSaver checkpointer with app.checkpointer().

# src/trip_planner/main.py

def build_agent() -> CompiledStateGraph:
    """Build the LangGraph agent."""
    logger.info("Building trip-planner graph")
    llm = app.llm(build_llm())
    .
    .
    .
    return builder.compile(checkpointer=app.checkpointer())

Step 2.5: Mark the app's entrypoint

We added the @app.entrypoint decorator to the function (build_agent()) that builds the agent's graph. Agent Engine calls this function to build the graph that handles each request.

# src/trip_planner/main.py

@app.entrypoint
def build_agent() -> CompiledStateGraph:
    """Build the LangGraph agent."""
    logger.info("Building trip-planner graph")
    llm = app.llm(build_llm())
    .
    .
    .
    return builder.compile(checkpointer=app.checkpointer())

Step 2.6: Start the agent's runtime with app.run()

The last change was to call app.run(), which starts the runtime server that handles requests to the agent:

# src/trip_planner/main.py

def main() -> None:
    """Run the travel agent."""
    app.run()

if __name__ == "__main__":
    main()

Note: Migrating the agent to Agent Engine did not change the core functionality of the agent. The agent's graph and the tool logic remained untouched. With Agent Engine, you can continue building agents using frameworks you're familiar with and let it handle scaling and running them in production.

Step 3: Update the pyproject.toml

With the code changes done, we have the agent ready to run on Agent Engine. Agent Engine installs agents as Python packages using uv. It reads the package's name, dependencies, and build settings from pyproject.toml in the agent's workspace directory.

Note: If your project doesn't have a pyproject.toml yet, create one by running uv init --package in your agent's workspace directory.

Here's the travel agent template's pyproject.toml, truncated to show what Agent Engine requires:

[project]
name = "trip-planner"
version = "0.1.0"
requires-python = ">=3.11"
dependencies = [
    "agent-engine-sdk-langgraph>=0.11.4,<1",
    "langchain>=1.3.17",
    "langchain-openai>=1.1.12",
    "langgraph>=1.2.11",
    "pymongo>=4.9",
    "python-dotenv>=1.0",
]

[build-system]                                 # how to build the package
requires = ["hatchling"]
build-backend = "hatchling.build"

[tool.hatch.build.targets.wheel]               # where the code lives
packages = ["src/trip_planner"]

In the above pyproject.toml snippet:

  • [project]: Specifies the package name, version, Python requirements (requires-python) and dependencies. Notice that we added agent-engine-sdk-langgraph as a dependency and dropped langgraph-checkpoint-mongodb, because we swapped out the MongoDBSaver checkpointer for the Agent Engine checkpointer.
  • [build-system]: Names the tool that builds your code into an installable package, in this case, hatchling.
  • [tool.hatch.build.targets.wheel]: Tells hatchling where the agent's source code is, in this case, src/trip_planner.

Step 4: Create an agent.yaml

Next, we created an agent.yaml file in the agent's workspace directory that configures how Agent Engine discovers and runs the agent. It specifies the agent's entry point, sandbox configurations, network policies, and so on. See our documentation for the full list of configuration options.

name: trip-planner
entrypoint: trip_planner.main:app     # required: module.path:attribute format
framework: langgraph

mcp:
  servers:
    mongodb:
      transport: streamable_http
      url: https://mcp.mongodb.com
      auth:
        type: client_credentials
        client_id_env: MDB_MCP_CLIENT_ID
        client_secret_env: MDB_MCP_CLIENT_SECRET
        token_url: https://cloud.mongodb.com/api/oauth/token
      allowed_tools:
        - remote-atlas-connect
        - list-collections
        - collection-schema
        - aggregate
      timeout_seconds: 30

sandboxes:                           # required
  agent:
    secrets: ["*"]
    tools: []
    network:
      egress_mode: allow_list
      egress:
        - fqdn: mcp.mongodb.com
          ports: [443]
        - fqdn: cloud.mongodb.com
          ports: [443]
  tool:
    secrets: ["*"]
    tools:
      - create_booking
      - list_bookings
    network:
      egress_mode: allow_list
      egress:
        - fqdn: api.openai.com
          ports: [443]
        - fqdn: mcp.mongodb.com
          ports: [443]
        - fqdn: cloud.mongodb.com
          ports: [443]

In our agent.yaml, we configured the following:

  • name: The app name. This should match the app_name specified when creating the App instance in Step 2.1.
  • entrypoint: The entry point for the agent. This should follow the format module.path:attribute, where module.path is the Python module that creates the App (trip_planner.main), and attribute is the variable that holds it (app).
  • framework: The agent orchestration framework that the agent is built with. Supported frameworks are langgraph, adk (Google's Agent Development Kit), and custom for anything else.
  • mcp: The remote MCP servers the agent can use, in this case the MongoDB Atlas Managed MCP Server. Agent Engine prefixes each tool with the server name (mongodb), so it sees the list-collections tool as mongodb__list_collections. It authenticates to the MCP server by exchanging the MCP client ID (MDB_MCP_CLIENT_ID) and secret (MDB_MCP_CLIENT_SECRET) for short-lived access tokens from the token_url. allowed_tools limits the agent to only the four tools it needs.
  • sandboxes: Configures where the agent and its tools run. The agent sandbox runs the agent's graph, and the tool sandbox handles the agent's tool and LLM calls. For each sandbox, tools lists the tools that run there, secrets lists the secrets it has access to, and network lists the hosts it can connect to. Here, we set secrets in both sandboxes to ["*"] to give each sandbox access to all secrets, and we configured both the agent and tool sandboxes to reach the MongoDB Atlas Managed MCP Server (mcp.mongodb.com) and its token endpoint (cloud.mongodb.com): the agent sandbox to discover the MCP tools at startup, and the tool sandbox to run them. The tool sandbox also needs to reach the LLM provider (OpenAI), since it makes the LLM calls.

Step 5: Enable Long-term Memory

In Step 2.4, app.checkpointer() enabled state persistence and short-term memory for the agent. Next, we added long-term memory, so the agent remembers facts about users and their preferences, such as a budget or a nonstop-only rule for flights, across conversations. This took three steps:

Step 5.1: Enable memory in agent.yaml

Agent Engine comes with a memory service, so we only had to enable and configure it. To enable long-term memory for the agent, we set features.memory to true in agent.yaml:

features:
  memory: true

Step 5.2: Configure memory extraction in project-config.yaml

Next, we created a project-config.yaml file in the project directory. It configures how Agent Engine extracts and stores long-term memories: which LLM to use for memory extraction, what memory types to extract, and which Voyage AI embedding model to use to embed memories for semantic retrieval. Here's the travel agent's project-config.yaml:

memory:
  log_level: info
  voyage:
    model: "voyage-4-large"
    dimension: 1024
  extraction_llm:
    provider: openai
    model: "gpt-5.4-mini"
    api_key_secret: LLM_API_KEY
  extraction:
    enabled:
      - semantic
      - episodic
      - preferences

We chose Voyage AI's voyage-4-large model to generate the embeddings for semantic search, and gpt-5.4-mini to extract memories from conversations, and turned on three types of memories for the agent:

  • Semantic: Facts about the user, such as their name.
  • Episodic: Summaries of past conversations, including key decisions and outcomes.
  • Preferences: The user's preferences, such as a budget or a preferred airline.

The api_key_secret is the name of the secret that contains the OpenAI API key (LLM_API_KEY). Memory also needs a Voyage API key stored in the VOYAGE_API_KEY secret. You'll set both secrets when you deploy the agent in Step 6.

To learn more about the Memory feature of Agent Engine, see our documentation.

Step 5.3: Add memory recall in the agent code

Finally, we added a memory retrieval step to the agent code, and passed the retrieved memories to the LLM as additional context.

# src/trip_planner/main.py

def recall(messages: list) -> str:
    """Return long-term memories relevant to the latest user message."""
    query = next((m.text for m in reversed(messages) if isinstance(m, HumanMessage)), "")
    memories = ""
    if query:
        try:
            memories = app.memory.build_context(query=query, max_tokens=2000).formatted_context
        except Exception:
            logger.warning("Memory recall failed; continuing without memories", exc_info=True)
    if isinstance(memories, list):
        memories = "\n".join(str(m.get("content", m)) for m in memories)
    logger.info("Recalled long-term memories" if memories else "No long-term memories found")
    return memories or "None yet."

The above code uses the build_context() method of app.memory, the app's memory client, to retrieve the current user's memories that are most relevant to their latest query. The max_tokens parameter caps how much memory text comes back.

# src/trip_planner/main.py

def agent_node(state: TravelAgentState) -> dict:
    messages = state["messages"]
    # Recall once per user turn
    memories = state.get("memories")
    if memories is None or isinstance(messages[-1], HumanMessage):
        memories = recall(messages)
    response = llm_with_tools.invoke({"messages": messages, "memories": memories})
    return {"messages": [response], "memories": memories}

# src/trip_planner/system_message.py

MEMORY_PROMPT = """
Use what you remember about the traveler from past conversations, such as their budget,
seat or accommodation preferences, to personalize your answers.
Relevant memories:
{memories}
"""

In the agent node, we call recall() to fetch memories, then pass them to the LLM along with the conversation history (messages). Specifically, the retrieved memories fill the {memories} placeholder in the system prompt.

Step 6: Deploy the Agent to Agent Engine

With the template ready, here's how to deploy it on Agent Engine. 🎉 We'll do this using the agentengine CLI.

Note: If you want to test the deployment locally before deploying to the cloud, follow the steps in the template's README.

Step 6.1: Load the sample data into Atlas

First, load the sample flights and Airbnb datasets into your Atlas cluster. If you already loaded them while testing locally, skip this step.

MONGODB_URI="<your Atlas connection string>" uv run scripts/seed_data.py

Step 6.2: Register the agent on Agent Engine

Next, run the following command from the agent's workspace directory and choose the organization and project for the agent when prompted. Choose the Atlas project that contains your cluster so Agent Engine can create a workspace for the agent in that project.

agentengine init

Then, run the command below to link your cluster to the agent. It asks you to choose the organization, project, and cluster for the agent, creates a database user and Voyage API key, saves the MONGODB_URI and VOYAGE_API_KEY as project-level secrets, and adds Agent Engine's data plane IP addresses to the cluster's access list:

agentengine atlas setup

Step 6.4: Set the remaining environment variables

Next, store the remaining environment variables the agent needs as secrets. In Agent Engine, you can set secrets at the project or workspace level. Project secrets are shared by all agents in the project, while workspace secrets are only available to the agent running in that workspace. For the travel agent, set the following secrets:

Project scope (default):

  • LLM_API_KEY: Your OpenAI API key

Workspace scope (set with --workspace-scope):

  • ATLAS_PROJECT_ID: Your Atlas project ID
  • ATLAS_CLUSTER_NAME: Your Atlas cluster name
  • MONGODB_DATABASE: The database containing the sample data, travel_agent in this case
  • MDB_MCP_CLIENT_ID: Your MCP client ID
  • MDB_MCP_CLIENT_SECRET: Your MCP client secret

Run the following commands. Each command prompts for a value.

agentengine secret set LLM_API_KEY
agentengine secret set ATLAS_PROJECT_ID --workspace-scope
agentengine secret set ATLAS_CLUSTER_NAME --workspace-scope
agentengine secret set MONGODB_DATABASE --workspace-scope
agentengine secret set MDB_MCP_CLIENT_ID --workspace-scope
agentengine secret set MDB_MCP_CLIENT_SECRET --workspace-scope

Step 6.5: Upload the memory configuration

In Step 5.2, we configured how Agent Engine should create and store memories for the agent. Now, upload that memory configuration to your Agent Engine project using the command below. Memory configuration in Agent Engine is project-scoped, meaning one configuration applies to all agents in your project.

agentengine memory configure

Step 6.6: Build and deploy

Finally, build the agent image and deploy it to Agent Engine using the following commands:

agentengine build
agentengine deploy

If the deployment is successful, you will see it show up with a "Succeeded" status in the Agent Engine UI:

A successful deployment on Atlas Agent Engine

Once the agent is deployed, you can interact with it in the Playground, monitor uptime, token usage, failures, etc., in the Monitoring tab, and investigate agent traces under Traces. To invoke the agent from an application or backend service, use the Invocation API.

Step 7: Add Governance Policies and Guardrails

Governance is one of the main pillars of Agent Engine. Agent Engine gives admins the ability to enforce governance policies and content guardrails to ensure that agents deployed in their environments work within the bounds of desired behavior.

Policies control what the agents can do by limiting the models and tools they can use, the number of LLM calls and tokens used per execution, etc. Content guardrails control what goes into and comes out of the LLM. They match inputs and outputs against regular expressions and can block, modify, or send them for review.

Here's an example of a policy that limits the travel agent we deployed to read-only tools: the four MongoDB MCP tools and the custom list_bookings tool. Policies match the tool names the agent sees, so the MCP tools are listed with their mongodb__ prefix (see Step 4):

An example of an Authorized tools policy in Atlas Agent Engine

This explicitly prevents the agent from creating bookings using the create_booking tool since it is not a part of the authorized tools list for the agent.

Unauthorized tool call blocked by a policy on Atlas Agent Engine

Here's an example of a content guardrail on the LLM input designed to detect and block inputs that contain credit card numbers:

An example of a content guardrail in Atlas Agent Engine

The guardrail blocks any input that contains a credit card number before it's sent to the LLM, so it never reaches the model.

Conclusion

In this tutorial, we walked through how we migrated a LangGraph agent to MongoDB Atlas Agent Engine with a handful of code changes. With Agent Engine, you can keep building agents with the frameworks you're already familiar with, and let MongoDB handle running them in production.

Agent Engine turns your agent into a managed, scalable service, with built-in state and memory, tracing, observability, and governance. Next, try bringing one of your own agents to Agent Engine, and explore our documentation to see what else you can do with it.

Atlas Agent Engine FAQs

What is MongoDB's Atlas Agent Engine?

MongoDB's Atlas Agent Engine is a managed service for running AI agents in production. It provides the control layer around the model: a managed runtime with isolated sandboxes, an identity for each agent, long-term memory, tracing and monitoring, and governance policies and guardrails.

Do I have to rewrite my agents to run them on Atlas Agent Engine?

No. Agent Engine works with the frameworks you already use, such as LangGraph, Google ADK, or your own custom code, so your agent's logic stays the same. You connect the agent to Agent Engine using the Agent Engine SDK.

Do I need to migrate my data to MongoDB Atlas to use Agent Engine?

No. Agent Engine needs an Atlas cluster for its own data, meaning the agent's memory and execution state. Your agents can keep accessing data where it already lives, such as Salesforce, Oracle, Snowflake, Amazon S3, SharePoint, or other internal systems, through custom tools or remote MCP servers.

How does Atlas Agent Engine handle long-term memory?

Agent Engine includes a built-in memory service. It extracts long-term memories from conversations in the background, such as user facts and conversation summaries, embeds them with Voyage AI, and stores them in MongoDB Atlas. You configure memory once per project and enable it per agent in the project.

How does Atlas Agent Engine handle security and governance for agents?

Agent Engine runs each agent in its own workspace, with its code and tools running in separate, isolated sandboxes. Each sandbox gets only the secrets and network access you allow. Governance policies control what the agent can do, and content guardrails check what goes into and comes out of the LLM. Every tool and LLM call is traced, so you can audit what your agents did.

Apoorva Joshi

Autor

Apoorva Joshi

Apoorva is a Data Scientist turned Developer Advocate, with over 7 years of experience applying machine learning to problems in domains such as cybersecurity and mental health. As an AI Developer Advocate at MongoDB, she now helps developers be successful at building AI applications through written content and hands-on workshops.

Subiecte

Conexe