How to integrate Mem0 MCP with Pydantic AI

Framework Integration Gradient
Mem0 Logo
Pydantic AI Logo
divider

Introduction

This guide walks you through connecting Mem0 to Pydantic AI using the Composio tool router. By the end, you'll have a working Mem0 agent that can store meeting notes from today's call, export all project memories as csv, add new user to our team space, search recent notes mentioning quarterly goals through natural language commands.

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

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

TL;DR

Here's what you'll learn:
  • How to set up your Composio API key and User ID
  • How to create a Composio Tool Router session for Mem0
  • How to attach an MCP Server to a Pydantic AI agent
  • How to stream responses and maintain chat history
  • How to build a simple REPL-style chat interface to test your Mem0 workflows

What is Pydantic AI?

Pydantic AI is a Python framework for building AI agents with strong typing and validation. It leverages Pydantic's data validation capabilities to create robust, type-safe AI applications.

Key features include:

  • Type Safety: Built on Pydantic for automatic data validation
  • MCP Support: Native support for Model Context Protocol servers
  • Streaming: Built-in support for streaming responses
  • Async First: Designed for async/await patterns

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

The Mem0 MCP server is an implementation of the Model Context Protocol that connects your AI agent and assistants like Claude, Cursor, etc directly to your Mem0 account. It provides structured and secure access to your notes, projects, and organizational knowledge, so your agent can perform actions like searching memories, managing users, adding content, and orchestrating agent runs on your behalf.

  • AI-powered memory search and recall: Let your agent search and retrieve existing memory entries using advanced filters and pagination to surface just the right note or piece of information.
  • Automated content and note creation: Have your agent store new memory records from conversations, meetings, or tasks—ensuring nothing slips through the cracks.
  • Collaboration and organization management: Direct your agent to add members to projects or organizations, assign roles, and keep team structures up to date.
  • Agent and application orchestration: Enable your agent to create new AI agents, initiate agent runs, and manage applications for custom workflows and automation.
  • Structured knowledge export and reporting: Ask your agent to initiate export jobs with specific schemas and filters, so you can back up or analyze your stored knowledge on demand.

Supported Tools & Triggers

Tools
Add member to projectAdds an existing user to a project (identified by `project id` within organization `org id`), assigning a valid system role.
Add new memory recordsStores new memory records from a list of messages, optionally inferring structured content; requires association via `agent id`, `user id`, `app id`, or `run id`.
Add organization memberAdds a new member, who must be a registered user, to an organization, assigning them a specific role.
Create a new agentCreates a new agent with a unique `agent id` and an optional `name`; additional metadata may be assigned by the system.
Create a new agent runCreates a new agent run in the mem0.
Create a new applicationCreates a new application, allowing metadata to be passed in the request body (not an explicit field in this action's request model); ensure `app id` is unique to avoid potential errors or unintended updates.
Create a new organization entryCreates a new organization entry using the provided name and returns its details.
Create a new userCreates a new user with the specified unique `user id` and supports associating `metadata` (not part of the request schema fields).
Create an export job with schemaInitiates an asynchronous job to export memories, structured by a schema provided in the request body and allowing optional filters.
Create memory entryLists/searches existing memory entries with filtering and pagination; critically, this action retrieves memories and does *not* create new ones, despite its name.
Create projectCreates a new project with a given name within an organization that must already exist.
Delete an organizationPermanently deletes an existing organization identified by its unique id.
Delete memory by idPermanently deletes a specific memory by its unique id; ensure the `memory id` exists as this operation is irreversible.
Delete entity by type and idCall to permanently and irreversibly hard-delete an existing entity (user, agent, app, or run) and all its associated data, using its type and id.
Delete memoriesDeletes memories matching specified filter criteria; omitting all filters may result in deleting all memories.
Delete memory batch with uuidsDeletes a batch of up to 1000 existing memories, identified by their uuids, in a single api call.
Delete projectPermanently deletes a specific project and all its associated data from an organization; this action cannot be undone and requires the project to exist within the specified organization.
Delete project memberRemoves an existing member, specified by username, from a project, immediately revoking their project-specific access; the user is not removed from the organization.
Export data based on filtersRetrieves memory export data, optionally filtered by various identifiers (e.
List organizationsRetrieves a summary list of organizations for administrative oversight; returns summary data (names, ids), not exhaustive details, despite 'detailed' in the name.
Fetch details of a specific organizationFetches comprehensive details for an organization using its `org id`; the `org id` must be valid and for an existing organization.
Get list of entity filtersRetrieves predefined filter definitions for entities (e.
Get entity by idFetches detailed information for an existing entity (user, agent, app, or run) identified by its type and unique id.
Get organization membersFetches a list of members for a specified, existing organization.
Get project detailsFetches comprehensive details for a specified project within an organization.
Get project membersRetrieves all members for a specified project within an organization.
Get projectsRetrieves all projects for a given organization `org id` to which the caller has access.
Get user memory statsRetrieves a summary of the authenticated user's memory activity, including total memories created, search events, and add events.
List entitiesRetrieves a list of entities, optionally filtered by organization or project (prefer `org id`/`project id` over deprecated `org name`/`project name`), noting results may be summaries and subject to limits.
Perform semantic search on memoriesSearches memories semantically using a natural language query (required if `only metadata based search` is false) and/or metadata filters.
Remove a member from the organizationRemoves a member, specified by their username, from an existing organization of which they are currently a member.
Retrieve all events for the currently logged in userRetrieves a paginated list of events for the authenticated user, filterable and paginable via url query parameters.
Retrieve entity-specific memoriesRetrieves all memories (e.
Retrieve list of memory eventsRetrieves a chronological list of all memory events (e.
Retrieve memory by idRetrieves a complete memory entry by its unique identifier; `memory id` must be valid and for an existing memory.
Retrieve memory history by idRetrieves the complete version history for an existing memory, using its unique `memory id`, to inspect its evolution or audit changes.
Retrieve memory listRetrieves a list of memories, supporting pagination and diverse filtering (e.
Search memories with filtersSemantically searches memories using a natural language query and mandatory structured filters, offering options to rerank results and select specific fields; any provided `org id` or `project id` must reference a valid existing entity.
Update memory batch with uuidUpdates text for up to 1000 memories in a single batch, using their uuids.
Update memory text contentUpdates the text content of an existing memory, identified by its `memory id`.
Update organization member roleUpdates the role of an existing member to a new valid role within an existing organization.
Update projectUpdates a project by `project id` within an `org id`, modifying only provided fields (name, description, custom instructions, custom categories); list fields are fully replaced (cleared by `[]`), other omitted/null fields remain unchanged.
Update project member roleUpdates the role of a specific member within a designated project, ensuring the new role is valid and recognized by the system.

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

What is Tool Router?

Composio's Tool Router 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 Tool Router

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

How the Tool Router works

The Tool Router 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 starting, make sure you have:
  • Python 3.9 or higher
  • A Composio account with an active API key
  • Basic familiarity with Python and async programming

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 dependencies

bash
pip install composio pydantic-ai python-dotenv

Install the required libraries.

What's happening:

  • composio connects your agent to external SaaS tools like Mem0
  • pydantic-ai lets you create structured AI agents with tool support
  • python-dotenv loads your environment variables securely from a .env file

Set up environment variables

bash
COMPOSIO_API_KEY=your_composio_api_key_here
USER_ID=your_user_id_here
OPENAI_API_KEY=your_openai_api_key

Create a .env file in your project root.

What's happening:

  • COMPOSIO_API_KEY authenticates your agent to Composio's API
  • USER_ID associates your session with your account for secure tool access
  • OPENAI_API_KEY to access OpenAI LLMs

Import dependencies

python
import asyncio
import os
from dotenv import load_dotenv
from composio import Composio
from pydantic_ai import Agent
from pydantic_ai.mcp import MCPServerStreamableHTTP

load_dotenv()
What's happening:
  • We load environment variables and import required modules
  • Composio manages connections to Mem0
  • MCPServerStreamableHTTP connects to the Mem0 MCP server endpoint
  • Agent from Pydantic AI lets you define and run the AI assistant

Create a Tool Router Session

python
async def main():
    api_key = os.getenv("COMPOSIO_API_KEY")
    user_id = os.getenv("USER_ID")
    if not api_key or not user_id:
        raise RuntimeError("Set COMPOSIO_API_KEY and USER_ID in your environment")

    # Create a Composio Tool Router session for Mem0
    composio = Composio(api_key=api_key)
    session = composio.create(
        user_id=user_id,
        toolkits=["mem0"],
    )
    url = session.mcp.url
    if not url:
        raise ValueError("Composio session did not return an MCP URL")
What's happening:
  • We're creating a Tool Router session that gives your agent access to Mem0 tools
  • The create method takes the user ID and specifies which toolkits should be available
  • The returned session.mcp.url is the MCP server URL that your agent will use

Initialize the Pydantic AI Agent

python
# Attach the MCP server to a Pydantic AI Agent
mem0_mcp = MCPServerStreamableHTTP(url, headers={"x-api-key": COMPOSIO_API_KEY})
agent = Agent(
    "openai:gpt-5",
    toolsets=[mem0_mcp],
    instructions=(
        "You are a Mem0 assistant. Use Mem0 tools to help users "
        "with their requests. Ask clarifying questions when needed."
    ),
)
What's happening:
  • The MCP client connects to the Mem0 endpoint
  • The agent uses GPT-5 to interpret user commands and perform Mem0 operations
  • The instructions field defines the agent's role and behavior

Build the chat interface

python
# Simple REPL with message history
history = []
print("Chat started! Type 'exit' or 'quit' to end.\n")
print("Try asking the agent to help you with Mem0.\n")

while True:
    user_input = input("You: ").strip()
    if user_input.lower() in {"exit", "quit", "bye"}:
        print("\nGoodbye!")
        break
    if not user_input:
        continue

    print("\nAgent is thinking...\n", flush=True)

    async with agent.run_stream(user_input, message_history=history) as stream_result:
        collected_text = ""
        async for chunk in stream_result.stream_output():
            text_piece = None
            if isinstance(chunk, str):
                text_piece = chunk
            elif hasattr(chunk, "delta") and isinstance(chunk.delta, str):
                text_piece = chunk.delta
            elif hasattr(chunk, "text"):
                text_piece = chunk.text
            if text_piece:
                collected_text += text_piece
        result = stream_result

    print(f"Agent: {collected_text}\n")
    history = result.all_messages()
What's happening:
  • The agent reads input from the terminal and streams its response
  • Mem0 API calls happen automatically under the hood
  • The model keeps conversation history to maintain context across turns

Run the application

python
if __name__ == "__main__":
    asyncio.run(main())
What's happening:
  • The asyncio loop launches the agent and keeps it running until you exit

Complete Code

Here's the complete code to get you started with Mem0 and Pydantic AI:

python
import asyncio
import os
from dotenv import load_dotenv
from composio import Composio
from pydantic_ai import Agent
from pydantic_ai.mcp import MCPServerStreamableHTTP

load_dotenv()

async def main():
    api_key = os.getenv("COMPOSIO_API_KEY")
    user_id = os.getenv("USER_ID")
    if not api_key or not user_id:
        raise RuntimeError("Set COMPOSIO_API_KEY and USER_ID in your environment")

    # Create a Composio Tool Router session for Mem0
    composio = Composio(api_key=api_key)
    session = composio.create(
        user_id=user_id,
        toolkits=["mem0"],
    )
    url = session.mcp.url
    if not url:
        raise ValueError("Composio session did not return an MCP URL")

    # Attach the MCP server to a Pydantic AI Agent
    mem0_mcp = MCPServerStreamableHTTP(url, headers={"x-api-key": COMPOSIO_API_KEY})
    agent = Agent(
        "openai:gpt-5",
        toolsets=[mem0_mcp],
        instructions=(
            "You are a Mem0 assistant. Use Mem0 tools to help users "
            "with their requests. Ask clarifying questions when needed."
        ),
    )

    # Simple REPL with message history
    history = []
    print("Chat started! Type 'exit' or 'quit' to end.\n")
    print("Try asking the agent to help you with Mem0.\n")

    while True:
        user_input = input("You: ").strip()
        if user_input.lower() in {"exit", "quit", "bye"}:
            print("\nGoodbye!")
            break
        if not user_input:
            continue

        print("\nAgent is thinking...\n", flush=True)

        async with agent.run_stream(user_input, message_history=history) as stream_result:
            collected_text = ""
            async for chunk in stream_result.stream_output():
                text_piece = None
                if isinstance(chunk, str):
                    text_piece = chunk
                elif hasattr(chunk, "delta") and isinstance(chunk.delta, str):
                    text_piece = chunk.delta
                elif hasattr(chunk, "text"):
                    text_piece = chunk.text
                if text_piece:
                    collected_text += text_piece
            result = stream_result

        print(f"Agent: {collected_text}\n")
        history = result.all_messages()

if __name__ == "__main__":
    asyncio.run(main())

Conclusion

You've built a Pydantic AI agent that can interact with Mem0 through Composio's Tool Router. With this setup, your agent can perform real Mem0 actions through natural language. You can extend this further by:
  • Adding other toolkits like Gmail, HubSpot, or Salesforce
  • Building a web-based chat interface around this agent
  • Using multiple MCP endpoints to enable cross-app workflows (for example, Gmail + Mem0 for workflow automation)
This architecture makes your AI agent "agent-native", able to securely use APIs in a unified, composable way without custom integrations.

How to build Mem0 MCP Agent with another framework

FAQ

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

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

Can I use Tool Router MCP with Pydantic AI?

Yes, you can. Pydantic AI 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 Mem0 tools.

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

Yes, absolutely. You can configure which Mem0 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 Mem0 data and credentials are handled as safely as possible.

Used by agents from

Context
ASU
Letta
glean
HubSpot
Agent.ai
Altera
DataStax
Entelligence
Rolai
Context
ASU
Letta
glean
HubSpot
Agent.ai
Altera
DataStax
Entelligence
Rolai
Context
ASU
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.