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
| Name | Required | Description | Default |
|---|---|---|---|
| includeEmbeddings | No | Whether to include embeddings in the returned entities (default: false) | |
| query | Yes |
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', ], }, },
- src/index.ts:333-354 (handler)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), }, ], }; }
- src/services/graph-service.ts:59-201 (handler)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)}` ); } }
- src/db/core.ts:288-293 (helper)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); }
- src/index.ts:281-284 (schema)TypeScript interface defining input for search_nodes tool handler.interface SearchNodesInput { query: string | number[]; includeEmbeddings?: boolean; }