Skip to main content
Glama

search_nodes

Find entities and their relationships using text or vector similarity queries in the MCP Memory LibSQL server, with optional embedding inclusion for enhanced data retrieval.

Instructions

Search for entities and their relations using text or vector similarity

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
includeEmbeddingsNoWhether to include embeddings in the returned entities (default: false)
queryYes

Implementation Reference

  • src/index.ts:140-169 (registration)
    Registration of the 'search_nodes' tool in the MCP server's ListTools handler, including name, description, and JSON input schema.
      name: 'search_nodes',
      description: 'Search for entities and their relations using text or vector similarity',
      inputSchema: {
        type: 'object',
        properties: {
          query: {
            oneOf: [
              {
                type: 'string',
                description: 'Text search query',
              },
              {
                type: 'array',
                items: {
                  type: 'number',
                },
                description: 'Vector for similarity search',
              },
            ],
          },
          includeEmbeddings: {
            type: 'boolean',
            description: 'Whether to include embeddings in the returned entities (default: false)',
          },
        },
        required: [
          'query',
        ],
      },
    },
  • MCP tool call handler for 'search_nodes': validates input, calls the searchNodes service function, and returns JSON-formatted results.
    case 'search_nodes': {
      // Safely access properties with type assertions for each property
      if (!args.query) {
        throw new McpError(
          ErrorCode.InvalidParams,
          'Missing required parameter: query'
        );
      }
      
      const query = args.query as string | number[];
      const includeEmbeddings = args.includeEmbeddings as boolean || false;
      
      const result = await searchNodes(query, includeEmbeddings);
      return {
        content: [
          {
            type: 'text',
            text: JSON.stringify(result, null, 2),
          },
        ],
      };
    }
  • Core implementation of searchNodes: performs vector similarity search or text search (with embedding fallback), retrieves relations, returns graph result.
    public static async searchNodes(
      query: string | number[],
      includeEmbeddings = false,
    ): Promise<GraphResult> {
      try {
        let entities: Entity[] = [];
    
        if (Array.isArray(query)) {
          // Validate vector query
          if (!query.every((n) => typeof n === 'number')) {
            throw new ValidationError('Vector query must contain only numbers');
          }
          
          // Vector similarity search
          const client = databaseService.getClient();
          const results = await client.execute({
            sql: `
              SELECT e.name
              FROM entities e
              WHERE e.embedding IS NOT NULL
              ORDER BY vector_distance_cos(e.embedding, vector32(?)) ASC
              LIMIT 5
            `,
            args: [JSON.stringify(query)],
          });
          
          // Get full entities with observations
          entities = await Promise.all(
            results.rows.map(async (row: { name: string }) => 
              getEntity(row.name as string, includeEmbeddings)
            )
          );
        } else {
          // Validate text query
          if (typeof query !== 'string') {
            throw new ValidationError('Text query must be a string');
          }
          if (query.trim() === '') {
            throw new ValidationError('Text query cannot be empty');
          }
          
          try {
            // Try semantic search first by generating an embedding for the text query
            logger.info(`Generating embedding for text query: "${query}"`);
            const embedding = await embeddingService.generateEmbedding(query);
            
            // Vector similarity search using the generated embedding
            logger.info(`Performing semantic search with generated embedding`);
            const client = databaseService.getClient();
            const results = await client.execute({
              sql: `
                SELECT e.name
                FROM entities e
                WHERE e.embedding IS NOT NULL
                ORDER BY vector_distance_cos(e.embedding, vector32(?)) ASC
                LIMIT 5
              `,
              args: [JSON.stringify(embedding)],
            });
            
            // Get full entities with observations
            entities = await Promise.all(
              results.rows.map(async (row: { name: string }) => 
                getEntity(row.name as string, includeEmbeddings)
              )
            );
            
            // If we got results, return them
            if (entities.length > 0) {
              logger.info(`Found ${entities.length} entities via semantic search`);
            } else {
              // Fall back to text search if no results from semantic search
              logger.info(`No results from semantic search, falling back to text search`);
              
              // Text-based search
              const client = databaseService.getClient();
              const results = await client.execute({
                sql: `
                  SELECT DISTINCT e.name
                  FROM entities e
                  LEFT JOIN observations o ON e.name = o.entity_name
                  WHERE e.name LIKE ? OR e.entity_type LIKE ? OR o.content LIKE ?
                  LIMIT 5
                `,
                args: [`%${query}%`, `%${query}%`, `%${query}%`],
              });
              
              // Get full entities with observations
              entities = await Promise.all(
                results.rows.map(async (row: { name: string }) => 
                  getEntity(row.name as string, includeEmbeddings)
                )
              );
            }
          } catch (embeddingError) {
            // If embedding generation fails, fall back to text search
            logger.error(`Failed to generate embedding for query, falling back to text search:`, embeddingError);
            
            // Text-based search
            const client = databaseService.getClient();
            const results = await client.execute({
              sql: `
                SELECT DISTINCT e.name
                FROM entities e
                LEFT JOIN observations o ON e.name = o.entity_name
                WHERE e.name LIKE ? OR e.entity_type LIKE ? OR o.content LIKE ?
                LIMIT 5
              `,
              args: [`%${query}%`, `%${query}%`, `%${query}%`],
            });
            
            // Get full entities with observations
            entities = await Promise.all(
              results.rows.map(async (row: { name: string }) => 
                getEntity(row.name as string, includeEmbeddings)
              )
            );
          }
        }
    
        // If no entities found, return empty graph
        if (entities.length === 0) {
          return { entities: [], relations: [] };
        }
    
        // Get entity names
        const entityNames = entities.map((entity: Entity) => entity.name);
        
        // Get relations for these entities
        const relations = await getRelationsForEntities(entityNames);
        
        // Return graph result
        return { entities, relations };
      } catch (error) {
        if (error instanceof ValidationError) {
          throw error;
        }
        
        throw new DatabaseError(
          `Node search failed: ${error instanceof Error ? error.message : String(error)}`
        );
      }
    }
  • Wrapper method in DatabaseManager that delegates to the searchNodes service function.
    async search_nodes(
    	query: string | number[],
    	includeEmbeddings: boolean = false,
    ): Promise<{ entities: Entity[]; relations: Relation[] }> {
    	return searchNodes(query, includeEmbeddings);
    }
  • TypeScript interface defining input for search_nodes tool handler.
    interface SearchNodesInput {
      query: string | number[];
      includeEmbeddings?: boolean;
    }
Behavior2/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It mentions the search functionality but lacks details on permissions, rate limits, response format, or potential side effects (e.g., whether it's read-only or has other impacts). This is inadequate for a search tool with no structured safety hints.

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 that front-loads the core purpose without unnecessary words. It directly communicates the tool's function and method, making it easy to parse and understand 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 complexity of a search tool with no annotations, no output schema, and incomplete parameter coverage, the description is insufficient. It lacks details on return values, error handling, or behavioral traits, leaving significant gaps for an AI agent to operate effectively.

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 50% (one of two parameters has a description). The description adds value by explaining the query parameter supports 'text or vector similarity,' which clarifies the oneOf schema, but it doesn't address the includeEmbeddings parameter or provide additional semantic context beyond the schema's basic descriptions.

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 as 'Search for entities and their relations using text or vector similarity,' which specifies the verb (search), resource (entities and their relations), and method (text or vector similarity). However, it doesn't explicitly differentiate from sibling tools like 'read_graph,' which might also involve reading/searching operations, leaving room for ambiguity.

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 provides no guidance on when to use this tool versus alternatives. It mentions the search methods (text or vector similarity) but doesn't specify scenarios, prerequisites, or exclusions compared to siblings like 'read_graph,' leaving the agent without clear usage context.

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

Related 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/joleyline/mcp-memory-libsql'

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