Skip to main content
Glama

search_memories_advanced

Search stored AI memories using text queries, vector similarity, memory types, importance levels, and date ranges to retrieve relevant information.

Instructions

Advanced memory search with multiple criteria

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
criteriaYes

Implementation Reference

  • The main handler implementation for search_memories_advanced. This method accepts a criteria object with textQuery, embedding, memoryTypes, importanceRange, dateRange, and limit parameters. It builds a complex SQL query using Drizzle ORM with full-text search (ts_rank), vector similarity search (embedding <=>), and multiple filters (memory type, importance, date range). Results are ordered by relevance based on the combination of text and vector search, with importance as a fallback.
    async searchMemoriesAdvanced(criteria) {
      try {
        const {
          textQuery,
          embedding,
          memoryTypes = [],
          importanceRange = [0, 1],
          dateRange = {},
          limit = 10
        } = criteria;
    
        let query = this.db
          .select({
            id: schema.memories.id,
            type: schema.memories.type,
            content: schema.memories.content,
            importance: schema.memories.importance,
            accessCount: schema.memories.accessCount,
            createdAt: schema.memories.createdAt,
            relevanceScore: schema.memories.relevanceScore,
            textRank: textQuery 
              ? sql`ts_rank(to_tsvector('english', ${schema.memories.content}), plainto_tsquery('english', ${textQuery}))`.as('text_rank')
              : sql`0`.as('text_rank'),
            similarityScore: embedding
              ? sql`1 - (${schema.memories.embedding} <=> ${`[${embedding.join(',')}]`}::vector)`.as('similarity_score')
              : sql`0`.as('similarity_score')
          })
          .from(schema.memories);
    
        // Build where conditions
        const conditions = [eq(schema.memories.status, 'active')];
    
        if (textQuery) {
          conditions.push(
            sql`to_tsvector('english', ${schema.memories.content}) @@ plainto_tsquery('english', ${textQuery})`
          );
        }
    
        if (memoryTypes.length > 0) {
          conditions.push(inArray(schema.memories.type, memoryTypes));
        }
    
        conditions.push(
          and(
            gte(schema.memories.importance, importanceRange[0]),
            lte(schema.memories.importance, importanceRange[1])
          )
        );
    
        if (dateRange.start) {
          conditions.push(gte(schema.memories.createdAt, dateRange.start));
        }
    
        if (dateRange.end) {
          conditions.push(lte(schema.memories.createdAt, dateRange.end));
        }
    
        query = query.where(and(...conditions));
    
        // Order by relevance
        if (textQuery && embedding) {
          query = query.orderBy(
            sql`ts_rank(to_tsvector('english', ${schema.memories.content}), plainto_tsquery('english', ${textQuery})) DESC`,
            sql`1 - (${schema.memories.embedding} <=> ${`[${embedding.join(',')}]`}::vector) DESC`,
            desc(schema.memories.importance)
          );
        } else if (textQuery) {
          query = query.orderBy(
            sql`ts_rank(to_tsvector('english', ${schema.memories.content}), plainto_tsquery('english', ${textQuery})) DESC`,
            desc(schema.memories.importance)
          );
        } else if (embedding) {
          query = query.orderBy(
            sql`1 - (${schema.memories.embedding} <=> ${`[${embedding.join(',')}]`}::vector) DESC`,
            desc(schema.memories.importance)
          );
        } else {
          query = query.orderBy(desc(schema.memories.importance));
        }
    
        const results = await query.limit(limit);
        return results;
      } catch (error) {
        const truncatedEmbedding = embedding && embedding.length > 10 
          ? `[${embedding.slice(0, 5).join(',')}...${embedding.slice(-5).join(',')}] (${embedding.length} values)`
          : embedding ? `[${embedding.join(',')}]` : 'none';
        console.error('Error in advanced search with embedding:', truncatedEmbedding, 'textQuery:', textQuery, error.message);
        throw error;
      }
    }
  • mcp.js:678-680 (registration)
    Registration/case handler in CallToolRequestSchema that routes the search_memories_advanced tool call to the memoryManager.searchMemoriesAdvanced method with the criteria argument.
    case "search_memories_advanced":
      const advancedResults = await memoryManager.searchMemoriesAdvanced(args.criteria);
      return { content: [{ type: "text", text: JSON.stringify(advancedResults, null, 2) }] };
  • Tool schema definition for search_memories_advanced in the ListToolsRequestSchema. Defines the input parameters including text_query, embedding, memory_types, importance_range, date_range, and limit, all nested under a 'criteria' object.
      name: "search_memories_advanced",
      description: "Advanced memory search with multiple criteria",
      inputSchema: {
        type: "object",
        properties: {
          criteria: {
            type: "object",
            properties: {
              text_query: {
                type: "string",
                description: "Text search query"
              },
              embedding: {
                type: "array",
                items: { type: "number" },
                description: "Vector embedding for similarity search"
              },
              memory_types: {
                type: "array",
                items: { type: "string" },
                description: "Filter by memory types",
                default: []
              },
              importance_range: {
                type: "array",
                items: { type: "number" },
                minItems: 2,
                maxItems: 2,
                description: "Importance range [min, max]",
                default: [0, 1]
              },
              date_range: {
                type: "object",
                properties: {
                  start: { type: "string", format: "date-time" },
                  end: { type: "string", format: "date-time" }
                },
                default: {}
              },
              limit: {
                type: "integer",
                description: "Maximum number of results",
                default: 10
              }
            }
          }
        },
        required: ["criteria"]
      }
    }
  • Alternative schema definition for search_memories_advanced exported as part of the memoryTools array. Contains the same structure as the mcp.js schema with text_query, embedding, memory_types, importance_range, date_range, and limit parameters.
      name: "search_memories_advanced",
      description: "Advanced memory search with multiple criteria",
      inputSchema: {
        type: "object",
        properties: {
          criteria: {
            type: "object",
            properties: {
              text_query: {
                type: "string",
                description: "Text search query"
              },
              embedding: {
                type: "array",
                items: { type: "number" },
                description: "Vector embedding for similarity search"
              },
              memory_types: {
                type: "array",
                items: { type: "string" },
                description: "Filter by memory types",
                default: []
              },
              importance_range: {
                type: "array",
                items: { type: "number" },
                minItems: 2,
                maxItems: 2,
                description: "Importance range [min, max]",
                default: [0, 1]
              },
              date_range: {
                type: "object",
                properties: {
                  start: { type: "string", format: "date-time" },
                  end: { type: "string", format: "date-time" }
                },
                default: {}
              },
              limit: {
                type: "integer",
                description: "Maximum number of results",
                default: 10
              }
            }
          }
        },
        required: ["criteria"]
      }
    }

Schema Changelog

Changes observed during successful MCP inspections.

  1. First observedv1.0.0

TDQS

C2.6/5.0
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 'advanced' and 'multiple criteria' but fails to describe key traits: whether this is a read-only operation, what permissions are needed, how results are returned (e.g., pagination, sorting), or any rate limits. For a search tool with complex nested parameters, this leaves significant gaps in understanding its 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 a single sentence that efficiently conveys the core idea. It's front-loaded with the main purpose ('Advanced memory search') and adds a qualifier ('with multiple criteria') without unnecessary elaboration. Every word earns its place, making it structurally sound for quick comprehension.

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?

Given the complexity (1 nested parameter with 6 sub-properties), no annotations, and no output schema, the description is incomplete. It doesn't explain the tool's behavior, parameter usage, or return values, which are critical for an 'advanced' search operation. The lack of output schema means the description should ideally hint at result format, but it doesn't, leaving the agent under-informed.

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%, meaning all parameter details are undocumented in the schema. The description only vaguely references 'multiple criteria', without explaining what those criteria are, how they interact, or their semantics. It doesn't compensate for the schema gap by detailing parameters like 'criteria' object, 'embedding', 'memory_types', etc., leaving the agent with insufficient guidance.

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 'Advanced memory search with multiple criteria' states the general purpose (searching memories) and hints at capability ('advanced', 'multiple criteria'), but it's vague about what makes it 'advanced' and doesn't clearly differentiate from sibling tools like 'search_memories_similarity' or 'search_memories_text'. It provides a basic verb+resource but lacks specificity about scope or unique features.

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?

The description offers no guidance on when to use this tool versus alternatives. It doesn't mention sibling tools like 'search_memories_similarity' or 'search_memories_text', nor does it provide context about when 'advanced' search is appropriate versus simpler methods. There's no explicit when/when-not advice or prerequisites stated.

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