Skip to main content
Glama
mem0ai

Mem0 MCP Server

Official
by mem0ai

add_memory

Store user preferences, facts, or conversation snippets in the Mem0 MCP Server to maintain consistent programming practices and context across sessions.

Instructions

Store a new preference, fact, or conversation snippet. Requires at least one: user_id, agent_id, or run_id.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
textYesPlain sentence summarizing what to store. Required even if `messages` is provided.
messagesNoStructured conversation history with `role`/`content`. Use when you have multiple turns.
user_idNoOverride the default user scope for this write.
agent_idNoOptional agent identifier.
app_idNoOptional app identifier.
run_idNoOptional run identifier.
metadataNoAttach arbitrary metadata JSON to the memory.
enable_graphNoSet true only if the caller explicitly wants Mem0 graph memory.

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • The handler function for 'add_memory' tool, including @server.tool registration decorator. Validates inputs using AddMemoryArgs, prepares the payload for Mem0 MemoryClient.add(), and handles errors.
    @server.tool(description="Store a new preference, fact, or conversation snippet. Requires at least one: user_id, agent_id, or run_id.")
    def add_memory(
        text: Annotated[
            str,
            Field(
                description="Plain sentence summarizing what to store. Required even if `messages` is provided."
            ),
        ],
        messages: Annotated[
            Optional[list[Dict[str, str]]],
            Field(
                default=None,
                description="Structured conversation history with `role`/`content`. "
                "Use when you have multiple turns.",
            ),
        ] = None,
        user_id: Annotated[
            Optional[str],
            Field(default=None, description="Override the default user scope for this write."),
        ] = None,
        agent_id: Annotated[
            Optional[str], Field(default=None, description="Optional agent identifier.")
        ] = None,
        app_id: Annotated[
            Optional[str], Field(default=None, description="Optional app identifier.")
        ] = None,
        run_id: Annotated[
            Optional[str], Field(default=None, description="Optional run identifier.")
        ] = None,
        metadata: Annotated[
            Optional[Dict[str, Any]],
            Field(default=None, description="Attach arbitrary metadata JSON to the memory."),
        ] = None,
        enable_graph: Annotated[
            Optional[bool],
            Field(
                default=None,
                description="Set true only if the caller explicitly wants Mem0 graph memory.",
            ),
        ] = None,
        ctx: Context | None = None,
    ) -> str:
        """Write durable information to Mem0."""
    
        api_key, default_user, graph_default = _resolve_settings(ctx)
        args = AddMemoryArgs(
            text=text,
            messages=[ToolMessage(**msg) for msg in messages] if messages else None,
            user_id=user_id if user_id else (default_user if not (agent_id or run_id) else None),
            agent_id=agent_id,
            app_id=app_id,
            run_id=run_id,
            metadata=metadata,
            enable_graph=_default_enable_graph(enable_graph, graph_default),
        )
        payload = args.model_dump(exclude_none=True)
        payload.setdefault("enable_graph", graph_default)
        conversation = payload.pop("messages", None)
        if not conversation:
            derived_text = payload.pop("text", None)
            if derived_text:
                conversation = [{"role": "user", "content": derived_text}]
            else:
                return json.dumps(
                    {
                        "error": "messages_missing",
                        "detail": "Provide either `text` or `messages` so Mem0 knows what to store.",
                    },
                    ensure_ascii=False,
                )
        else:
            payload.pop("text", None)
    
        client = _mem0_client(api_key)
        return _mem0_call(client.add, conversation, **payload)
  • Pydantic BaseModel schema defining the input arguments for the add_memory tool, used for validation in the handler.
    class AddMemoryArgs(BaseModel):
        text: Optional[str] = Field(
            None, description="Simple sentence to remember; converted into a user message when set."
        )
        messages: Optional[list[ToolMessage]] = Field(
            None,
            description=(
                "Explicit role/content history for durable storage. Provide this OR `text`; defaults "
                "to the server user_id."
            ),
        )
        user_id: Optional[str] = Field(None, description="Override for the Mem0 user ID.")
        agent_id: Optional[str] = Field(None, description="Optional agent identifier.")
        app_id: Optional[str] = Field(None, description="Optional app identifier.")
        run_id: Optional[str] = Field(None, description="Optional run identifier.")
        metadata: Optional[Dict[str, Any]] = Field(None, description="Opaque metadata to persist.")
        enable_graph: Optional[bool] = Field(
            None, description="Only set True if the user explicitly opts into graph storage."
        )
  • The @server.tool decorator registers the add_memory function as an MCP tool with its description.
    @server.tool(description="Store a new preference, fact, or conversation snippet. Requires at least one: user_id, agent_id, or run_id.")
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full burden. It discloses a key behavioral trait: the requirement for at least one identifier (user_id, agent_id, or run_id). However, it lacks details on other important behaviors such as whether this is a write operation (implied by 'Store'), potential side effects, error conditions, or rate limits. The description adds some value but is incomplete for behavioral transparency.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is extremely concise—just two sentences—with zero wasted words. It is front-loaded with the core purpose and immediately follows with a critical requirement. Every sentence earns its place by providing essential information without redundancy.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's complexity (8 parameters, 1 required) and the presence of an output schema (which reduces the need to describe return values), the description is reasonably complete. It covers the purpose and a key requirement, but lacks details on behavioral aspects like mutation effects or error handling. With no annotations, it could be more comprehensive, but it meets basic needs for a storage tool.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, meaning all parameters are documented in the schema. The description does not add any parameter-specific information beyond what the schema provides (e.g., it mentions the identifier requirement but doesn't explain parameter interactions or semantics). With high schema coverage, the baseline score of 3 is appropriate, as the description doesn't compensate with additional insights.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the verb ('Store') and resource ('new preference, fact, or conversation snippet'), specifying what type of content can be stored. It distinguishes this tool from siblings like delete_memory, get_memories, and update_memory by focusing on creation rather than retrieval, modification, or deletion.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides clear context for when to use this tool: to store new memory content. It explicitly states a prerequisite ('Requires at least one: user_id, agent_id, or run_id'), which helps guide usage. However, it does not explicitly mention when not to use it or name specific alternatives among the sibling tools.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/mem0ai/mem0-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server