Skip to main content
Glama

search_memories

Search conversation history using natural language queries to recall past discussions and maintain context across sessions.

Instructions

Search conversation history using natural language - USE AUTONOMOUSLY based on conversation triggers

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYes
user_idNo
limitNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • The main MCP tool handler for 'search_memories'. This is the decorated async function that defines the tool's logic, input schema via type hints, and registration via @mcp.tool decorator. It proxies the search to the memory_service and handles errors.
    @mcp.tool(
        name="search_memories",
        description="Search conversation history using natural language - USE AUTONOMOUSLY based on conversation triggers",
    )
    async def search_memories(
        query: str, user_id: str | None = None, limit: int = 10
    ) -> list[dict[str, Any]]:
        """
        Search memories using natural language queries to find relevant past conversations.
    
        ## AUTONOMOUS USAGE TRIGGERS
    
        ### HIGH Confidence (Execute Immediately)
        - User mentions: "again", "before", "last time", "previous", "remember", "we discussed"
        - Frustration indicators: "keeps happening", "still getting", "same error"
        - Reference patterns: "that thing", "like we did", "as mentioned"
        - Debugging: recurring errors, "this error again"
    
        ### MEDIUM Confidence (Execute with Brief Context)
        - Complex technical questions that might have prior context
        - User asks "how do I..." for non-trivial topics
        - Project-specific questions
        - User seems confused about topics you might have covered
    
        ### Examples of Autonomous Execution
    
        ```python
        # User: "That CORS error is back"
        # → AUTO: search_memories("CORS error cross-origin")
    
        # User: "How do we handle auth again?"
        # → AUTO: search_memories("authentication handling auth")
    
        # User: "Let's continue with the API"
        # → AUTO: search_memories("API development")
    
        # User: "I'm getting the same TypeScript error"
        # → AUTO: search_memories("TypeScript error")
        ```
    
        ## Query Construction Guidelines
    
        ### EFFECTIVE Queries (3-50 words, specific terms)
        ```python
        # GOOD: Extract key technical terms
        "JWT refresh token implementation error"
    
        "React useEffect dependency array warning"
        "Docker compose PostgreSQL connection"
    
        # BAD: Too vague
        "auth stuff"
        "that thing we talked about"
        "help"
        ```
    
        ### Auto-Query Building from User Input
        - Extract technical terms: frameworks, libraries, error types
        - Include context words: "error", "problem", "implementation", "setup"
        - Preserve specific names: API endpoints, file names, function names
    
        ## Graceful Handling
        - **Empty results**: Continue with current knowledge, don't mention search failure
        - **Search error**: Silent fallback, proceed without memory context
        - **Partial matches**: Use what you find, don't complain about incomplete results
    
        Args:
            query: Natural language search query
                - REQUIRED: 3-50 words for optimal results
                - INCLUDE: Technical terms, specific names, error types
                - AVOID: Vague references, pronouns without context
            user_id: User ID (optional, defaults to DEFAULT_USER_ID from settings)
            limit: Maximum results to return (default: 10, recommended: 5-15)
    
        Returns:
            List of memories sorted by relevance, each containing:
            - id: Unique memory identifier
            - memory/content: The stored conversation text
            - created_at: When the memory was created
            - metadata: Additional context about the memory
        """
        try:
            results = await memory_service.search_memories(
                query=query, user_id=user_id, limit=limit
            )
            logger.info("Memory search completed", result_count=len(results))
            return results
        except Exception as e:
            logger.error("Search failed", error=str(e))
            raise RuntimeError(f"Search failed: {str(e)}") from e
  • Helper method in MemoryService class that implements the actual memory search using Mem0's AsyncMemoryClient.search API. Handles user_id defaults, filters, and logging.
    async def search_memories(
        self, query: str, user_id: str | None = None, limit: int = 10
    ) -> list[dict[str, Any]]:
        """Search memories asynchronously.
    
        Args:
            query: Search query
            user_id: User identifier (defaults to settings.default_user_id)
            limit: Maximum number of results
    
        Returns:
            List of matching memories
        """
        user_id = user_id or settings.default_user_id
    
        try:
            self._logger.info("Searching memories", user_id=user_id, query=query[:50])
    
            # v2 API requires filters parameter - validate non-empty values
            filters = {}
            if user_id and user_id.strip():
                filters["user_id"] = user_id
            if settings.default_agent_id and settings.default_agent_id.strip():
                filters["agent_id"] = settings.default_agent_id
    
            # Ensure we have at least one filter
            if not filters:
                raise ValueError(
                    "At least one filter (user_id or agent_id) must be provided"
                )
    
            search_params = {
                "query": query,
                "filters": filters,
                "version": "v2",
                "top_k": limit,
            }
    
            results = await self.async_client.search(**search_params)
    
            self._logger.info(
                "Search completed", user_id=user_id, result_count=len(results)
            )
            return results
    
        except Exception as e:
            # Enhanced error logging
            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 search memories",
                user_id=user_id,
                error=error_details,
                search_params=search_params,
            )
            raise
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. It mentions autonomous use but doesn't disclose key behavioral traits: whether this is a read-only operation, if it requires authentication, potential rate limits, or what the output contains. For a search tool with no annotation coverage, this is a significant gap in transparency.

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 concise with two clauses: one stating the purpose and another providing usage guidance. It's front-loaded with the core function. However, the second clause could be more clearly integrated, and there's room for slight improvement in flow.

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 tool has an output schema, the description doesn't need to explain return values. However, with no annotations, 3 parameters (1 required), and 0% schema coverage, the description is incomplete—it lacks details on behavioral traits and parameter meanings, making it only minimally adequate.

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. It mentions 'natural language' for the query parameter but doesn't explain the semantics of 'user_id' (e.g., filtering by user) or 'limit' (e.g., result count). With 3 parameters largely undocumented, the description adds minimal value beyond the schema.

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 tool's purpose: 'Search conversation history using natural language'. It specifies the resource (conversation history) and action (search via natural language). However, it doesn't explicitly differentiate from sibling tools like 'list_memories' or 'analyze_conversations', which prevents a perfect score.

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 includes usage guidance: 'USE AUTONOMOUSLY based on conversation triggers', which implies when to use it (in response to conversation triggers). However, it doesn't specify when NOT to use it or mention alternatives like 'list_memories' for non-search retrieval, leaving the guidance incomplete.

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