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"]
      }
    }
Behavior2/5

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

With no annotations provided, the description carries full burden but only states it's an 'advanced' search without detailing behavioral traits like permissions, rate limits, pagination, or what 'advanced' entails (e.g., combining text and vector searches). It lacks critical information for a mutation-free but complex search operation.

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 a single, efficient sentence with no wasted words. It's front-loaded and appropriately sized for the tool's complexity, making it easy to parse quickly.

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 tool's complexity (multiple search criteria, nested objects) and lack of annotations and output schema, the description is insufficient. It doesn't explain return values, error handling, or how criteria interact, leaving significant gaps for an AI agent to use it correctly.

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

Parameters4/5

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

The description mentions 'multiple criteria', which aligns with the input schema's single 'criteria' parameter containing nested properties for text, embedding, types, importance, date range, and limit. Since there's only 1 parameter and schema description coverage is 0%, the description adds meaningful context by hinting at the parameter's purpose, though it doesn't detail specific criteria.

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 tool's purpose (searching memories) and hints at advanced functionality, but it's vague about what makes it 'advanced' compared to siblings like 'search_memories_similarity' and 'search_memories_text'. It doesn't specify the verb beyond 'search' or distinguish clearly from alternatives.

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 guidance is provided on when to use this tool versus sibling tools like 'search_memories_similarity' or 'search_memories_text'. The description implies it supports multiple criteria but doesn't specify contexts, prerequisites, or exclusions for its use.

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/randyandrade/agi-mcp-server'

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