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;
    }
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