Skip to main content
Glama

add_memory

Store preferences, facts, or conversation snippets in long-term memory for semantic search and retrieval across users and agents.

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 the 'add_memory' tool. It is registered via @server.tool decorator, validates and maps arguments using AddMemoryArgs schema, prepares the payload for Mem0, and calls the Mem0 client's add method to store the memory.
    @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 model defining the input schema (AddMemoryArgs) used by the add_memory tool handler for validation and serialization.
    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 on the FastMCP server.
    @server.tool(description="Store a new preference, fact, or conversation snippet. Requires at least one: user_id, agent_id, or run_id.")
Behavior2/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 of behavioral disclosure. It mentions the requirement for identifiers but lacks details on permissions, rate limits, whether the operation is idempotent, or what happens on success/failure. For a write operation with no annotation coverage, this leaves significant gaps in understanding the tool's behavior.

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 with just two sentences that directly convey the core purpose and a key requirement. Every word serves a purpose, and it's front-loaded with the main action, making it efficient and easy to parse.

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

Completeness3/5

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

Given the complexity of 8 parameters, no annotations, but with a rich input schema (100% coverage) and an output schema present, the description is minimally adequate. It covers the basic purpose and a critical requirement but doesn't address behavioral aspects like error handling or performance, leaving room for improvement despite the structured support.

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%, so the schema already documents all parameters thoroughly. The description adds minimal value by hinting at the identifier requirement but doesn't provide additional semantic context beyond what's in the schema, such as examples or edge cases. 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.

Purpose4/5

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

The description clearly states the action ('Store') and resource type ('preference, fact, or conversation snippet'), making the purpose evident. It doesn't explicitly differentiate from sibling tools like 'update_memory' or 'get_memories', but the verb 'Store a new' implies creation rather than modification or retrieval.

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

Usage Guidelines3/5

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

The description provides some context by specifying that at least one identifier (user_id, agent_id, or run_id) is required, which implies usage when scoping a memory. However, it doesn't explicitly state when to use this tool versus alternatives like 'update_memory' for modifications or 'get_memories' for retrieval, leaving the guidelines somewhat implied rather than explicit.

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/parthshr370/mem0_mcp_private'

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