Skip to main content
Glama
arjunkmrm

Mem0 MCP Server

add_memory

Store user preferences, conversation history, or contextual facts to enable persistent memory across sessions. Requires a text summary and optional identifiers.

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 main handler function that executes the 'add_memory' tool logic. It processes inputs, constructs the payload using AddMemoryArgs, handles defaults, and calls the Mem0 MemoryClient's add method.
    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)
  • Registers the add_memory function as an MCP tool using FastMCP's @server.tool decorator, with the tool name derived from the function name.
    @server.tool(description="Store a new preference, fact, or conversation snippet. Requires at least one: user_id, agent_id, or run_id.")
  • Pydantic BaseModel defining the input schema and validation for the add_memory tool arguments.
    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."
        )
Behavior3/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It mentions the storage action and a key requirement (needing at least one identifier), but doesn't address important behavioral aspects like whether this operation is idempotent, what happens on duplicate entries, permission requirements, rate limits, or error conditions. The description adds some value but leaves significant gaps.

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 perfectly concise - two sentences that each earn their place. The first sentence states the core purpose, and the second provides a critical constraint. There's zero wasted language, and the most important information (the requirement) is appropriately placed.

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 complexity (8 parameters, write operation) and the presence of an output schema, the description provides adequate context. It covers the core purpose and a critical constraint. The output schema means the description doesn't need to explain return values. However, for a write operation with no annotations, it could benefit from more behavioral context about side effects or error handling.

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?

With 100% schema description coverage, the schema already documents all 8 parameters thoroughly. The description doesn't add any parameter-specific information beyond what's in the schema - it mentions the identifier requirement but doesn't explain parameter interactions or provide usage examples. This meets the baseline for high schema coverage.

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 the resource 'new preference, fact, or conversation snippet', making the purpose specific and actionable. It distinguishes from siblings like delete_memory or get_memories by focusing on creation rather than retrieval 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 ('store a new...') and includes a critical requirement ('requires at least one: user_id, agent_id, or run_id'), which helps guide proper invocation. However, it doesn't explicitly mention when to use alternatives like update_memory or how this differs from other storage operations.

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/arjunkmrm/mem0-mcp'

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