Skip to main content
Glama

add_memory

Store conversation data and user preferences to memory for future recall, enabling Claude to maintain context across sessions and learn from past interactions.

Instructions

Store important information to memory - AUTO-STORE user preferences and decisions

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
messagesYes
user_idNo
metadataNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • MCP tool handler for 'add_memory'. Registers the tool with @mcp.tool decorator, defines input schema via type hints (messages: list[dict], user_id, metadata), executes by calling memory_service.add_memory, handles errors, and includes comprehensive autonomous usage docstring.
    @mcp.tool(
        name="add_memory",
        description="Store important information to memory - AUTO-STORE user preferences and decisions",
    )
    async def add_memory(
        messages: list[dict[str, str]],
        user_id: str | None = None,
        metadata: dict[str, Any] | None = None,
    ) -> dict[str, Any]:
        """
        Store important information to memory for future reference.
    
        ## AUTONOMOUS STORAGE TRIGGERS
    
        ### HIGH Priority (Always Store Silently)
        - **User preferences**: "I prefer X", "I don't like Y", "I usually use Z"
        - **Project decisions**: "Let's use X for this project", "We decided on Y"
        - **Solution discoveries**: "That fixed it", "This approach worked", "The solution was X"
        - **Configuration details**: API keys, URLs, important file paths
        - **Error solutions**: Successfully resolved errors and their fixes
    
        ### MEDIUM Priority (Store with Brief Acknowledgment)
        - **Important context**: Project requirements, constraints, guidelines
        - **Learning insights**: "Now I understand X", "The key is Y"
        - **Workflow preferences**: How user likes to approach problems
    
        ### Autonomous Storage Examples
    
        ```python
        # User: "I prefer functional components over class components"
        # → AUTO: add_memory([{"role": "user", "content": "I prefer functional components..."}])
        # → SILENT: No announcement, just store
    
        # User: "Perfect! That fixed the CORS issue"
        # → AUTO: add_memory([{"role": "assistant", "content": "CORS fixed by adding proxy config..."}])
        # → METADATA: {"type": "solution", "issue": "CORS", "resolved": True}
    
        # User: "Let's use PostgreSQL for this project"
        # → AUTO: add_memory([{"role": "user", "content": "Let's use PostgreSQL..."}])
        # → METADATA: {"type": "decision", "category": "database"}
        ```
    
        ## Smart Metadata Generation
    
        Automatically generate metadata based on content patterns:
    
        - **"preference"**: Contains "prefer", "like", "don't like", "usually use"
        - **"solution"**: Contains "fixed", "solved", "worked", "solution was"
        - **"decision"**: Contains "let's use", "we'll go with", "decided on"
        - **"error"**: Contains "error", "issue", "problem", "bug"
        - **"configuration"**: Contains "config", "setup", "environment", "api key"
    
        ## Storage Best Practices
    
        - **Silent operation**: Don't announce routine storage unless explicitly requested
        - **Rich metadata**: Include type, category, project context automatically
        - **Concise content**: Store essential information, not full conversations
        - **Avoid duplicates**: Check if similar information already exists before storing
    
        Args:
            messages: List of message dictionaries, each with:
                - role: "user", "assistant", or "system"
                - content: The message text to store (keep concise but complete)
            user_id: User ID (optional, defaults to DEFAULT_USER_ID)
            metadata: Optional metadata dict for categorization
                - AUTO-GENERATED when not provided based on content analysis
                - SHOULD INCLUDE: type, category, project, resolved status
    
        Returns:
            Dictionary containing:
            - id: Unique identifier for the created memory
            - created_at: Timestamp of creation
            - status: "created" on success
            - message: Confirmation message
        """
        try:
            result = await memory_service.add_memory(
                messages=messages, user_id=user_id, metadata=metadata
            )
            logger.info("Memory added", memory_id=result.get("id"))
            return result
        except Exception as e:
            logger.error("Add failed", error=str(e))
            raise RuntimeError(f"Add failed: {str(e)}") from e
  • Core helper method in MemoryService class that implements the add_memory logic by constructing parameters and calling Mem0's AsyncMemoryClient.add() API, with detailed logging and error handling.
    async def add_memory(
        self,
        messages: list[dict[str, Any]],
        user_id: str | None = None,
        agent_id: str | None = None,
        run_id: str | None = None,
        categories: list[dict[str, str]] | None = None,
        metadata: dict[str, Any] | None = None,
    ) -> dict[str, Any]:
        """Add memory asynchronously.
    
        Args:
            messages: List of message dicts with 'role' and 'content'
            user_id: User identifier (defaults to settings.default_user_id)
            agent_id: Agent identifier (defaults to settings.default_agent_id)
            run_id: Session/run identifier for tracking conversations
            categories: List of custom categories with descriptions for organizing memories
            metadata: Optional metadata to attach to the memory
    
        Returns:
            Response from Mem0 API
        """
        user_id = user_id or settings.default_user_id
        agent_id = agent_id or settings.default_agent_id
        categories = categories or settings.memory_categories
    
        # Build the add parameters
        add_params = {
            "messages": messages,
            "user_id": user_id,
            "agent_id": agent_id,
            "version": "v2",
        }
    
        # Add optional parameters if provided
        if run_id:
            add_params["run_id"] = run_id
        if categories:
            add_params["custom_categories"] = categories
            add_params["output_format"] = "v1.1"  # Required for custom categories
        if metadata:
            add_params["metadata"] = metadata
    
        try:
            self._logger.info(
                "Adding memory",
                user_id=user_id,
                agent_id=agent_id,
                run_id=run_id,
                categories=categories,
                message_count=len(messages),
            )
    
            result = await self.async_client.add(**add_params)
    
            self._logger.info(
                "Memory added successfully",
                user_id=user_id,
                agent_id=agent_id,
                run_id=run_id,
                categories=categories,
                memory_id=result.get("id"),
            )
            return result
    
        except Exception as e:
            # Log the full error details for debugging
            error_details = str(e)
            if hasattr(e, "response") and hasattr(e.response, "text"):
                error_details = f"{str(e)} - Response: {e.response.text}"
    
            self._logger.error(
                "Failed to add memory",
                user_id=user_id,
                agent_id=agent_id,
                run_id=run_id,
                categories=categories,
                error=error_details,
                add_params=add_params,  # Log the actual parameters being sent
            )
            raise
Behavior2/5

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

With no annotations provided, the description carries full burden for behavioral disclosure. It mentions storage behavior but lacks critical details: what permissions are needed, whether storage is permanent or temporary, rate limits, or what happens on success/failure. The 'AUTO-STORE' hint suggests automated behavior but doesn't clarify how it differs from manual storage.

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

Conciseness4/5

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

The description is brief and front-loaded with the core purpose, though the second part about 'AUTO-STORE' could be integrated more smoothly. It avoids unnecessary elaboration but could benefit from clearer structure to separate purpose from behavioral hints.

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

Completeness2/5

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

For a tool with 3 parameters, 0% schema coverage, no annotations, and sibling tools, the description is insufficient. It doesn't explain the storage mechanism, return values (despite having an output schema), or how it differs from related tools. The mention of 'AUTO-STORE' adds some context but doesn't compensate for the overall gaps.

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

Parameters2/5

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

Schema description coverage is 0%, so the description must compensate but provides no parameter information. It doesn't explain what 'messages', 'user_id', or 'metadata' represent, their formats, or how they interact. The description adds no value beyond the bare schema, leaving all three parameters semantically undocumented.

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

Purpose3/5

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

The description states the tool 'Store important information to memory' which provides a basic verb+resource combination, but it's vague about what 'memory' refers to and doesn't distinguish it from sibling tools like list_memories or search_memories. The 'AUTO-STORE user preferences and decisions' adds some specificity but remains ambiguous about scope.

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

Usage Guidelines2/5

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

No explicit guidance on when to use this tool versus alternatives like list_memories or search_memories. The mention of 'AUTO-STORE user preferences and decisions' implies a context for automated storage but doesn't provide clear when/when-not criteria or prerequisites for usage.

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

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