find_similar_elements
Identify semantically similar elements in DollhouseMCP using NLP scoring to discover related personas, skills, templates, agents, memories, or ensembles based on Jaccard similarity and Shannon entropy analysis.
Instructions
Find elements that are semantically similar to a given element using NLP scoring (Jaccard similarity and Shannon entropy). Returns elements with similarity scores and relationships.
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| element_name | Yes | Name of the element to find similar items for | |
| element_type | No | Type of the element. If not specified, searches all types. | |
| limit | No | Maximum number of similar elements to return. Defaults to 10. | |
| threshold | No | Minimum similarity score (0-1) to include. Defaults to 0.5. |
Implementation Reference
- Core handler function executing the tool: input validation, security (Unicode normalization, audit logging), similarity search via EnhancedIndexManager.getConnectedElements (maxDepth=1, minStrength=threshold), processes results into scored list with relationships, formats Markdown response.async findSimilarElements(options: { elementName: string; elementType?: string; limit: number; threshold: number; }) { try { // Validate inputs if (!options.elementName || typeof options.elementName !== 'string') { throw new Error('Element name is required and must be a string'); } // FIX: DMCP-SEC-004 - Normalize Unicode in user input to prevent homograph attacks const normalized = UnicodeValidator.normalize(options.elementName); if (!normalized.isValid) { throw new Error(`Invalid element name: ${normalized.detectedIssues?.join(', ')}`); } options.elementName = normalized.normalizedContent; // Also normalize element type if provided if (options.elementType) { const normalizedType = UnicodeValidator.normalize(options.elementType); if (!normalizedType.isValid) { throw new Error(`Invalid element type: ${normalizedType.detectedIssues?.join(', ')}`); } options.elementType = normalizedType.normalizedContent; } if (options.limit <= 0 || options.limit > 100) { options.limit = 5; // Default to reasonable limit } if (options.threshold < 0 || options.threshold > 1) { options.threshold = 0.3; // Default to reasonable threshold } // Ensure the enhanced index is available with error handling try { await this.enhancedIndexManager.getIndex(); } catch (indexError) { logger.error('Failed to get Enhanced Index', indexError); // Try to recover by forcing rebuild try { await this.enhancedIndexManager.getIndex({ forceRebuild: true }); } catch (rebuildError) { throw new Error('Enhanced Index is unavailable. Please try again later.'); } } // FIX: DMCP-SEC-006 - Add security audit logging for index operations SecurityMonitor.logSecurityEvent({ type: 'ELEMENT_CREATED', severity: 'LOW', source: 'EnhancedIndexHandler.findSimilarElements', details: `Similarity search performed for element: ${options.elementName}`, additionalData: { elementType: options.elementType, limit: options.limit, threshold: options.threshold } }); // Find the element const elementId = options.elementType ? `${options.elementType}/${options.elementName}` : options.elementName; // Get connected elements (similar/related) const connectedMap = await this.enhancedIndexManager.getConnectedElements( elementId, { maxDepth: 1, // Direct relationships only minStrength: options.threshold } ); // Convert to array and sort by relationship strength const similarElements = Array.from(connectedMap.entries()) .map(([id, path]) => { const [type, name] = id.split('/'); return { type, name, score: path.totalStrength || 0, relationships: path.relationships || [] // relationships is already an array of strings }; }) .sort((a, b) => b.score - a.score) .slice(0, options.limit); // Format results let text = `${this.personaIndicator}🔍 **Similar Elements**\n\n`; text += `**Reference**: ${options.elementName}\n`; if (options.elementType) { text += `**Type**: ${options.elementType}\n`; } text += `**Found**: ${similarElements.length} similar elements\n\n`; if (similarElements.length === 0) { text += `No similar elements found with similarity score >= ${options.threshold}\n`; } else { for (const element of similarElements) { const icon = this.getElementIcon(element.type); text += `${icon} **${element.name}** (${element.type})\n`; text += ` 📊 Similarity: ${(element.score * 100).toFixed(1)}%\n`; if (element.relationships && element.relationships.length > 0) { text += ` 🔗 Relationships: ${element.relationships.join(', ')}\n`; } text += '\n'; } } return { content: [{ type: "text", text }] }; } catch (error: any) { ErrorHandler.logError('EnhancedIndexHandler.findSimilarElements', error, options); return { content: [{ type: "text", text: `${this.personaIndicator}❌ Failed to find similar elements: ${SecureErrorHandler.sanitizeError(error).message}` }] }; } }
- src/server/tools/EnhancedIndexTools.ts:41-75 (registration)Tool registration in getEnhancedIndexTools(): defines name, description, inputSchema, and delegates handler to server.findSimilarElements with config-applied defaults.{ tool: { name: "find_similar_elements", description: "Find elements that are semantically similar to a given element using NLP scoring (Jaccard similarity and Shannon entropy). Returns elements with similarity scores and relationships.", inputSchema: { type: "object", properties: { element_name: { type: "string", description: "Name of the element to find similar items for", }, element_type: { type: "string", enum: ["personas", "skills", "templates", "agents", "memories", "ensembles"], description: "Type of the element. If not specified, searches all types.", }, limit: { type: "number", description: `Maximum number of similar elements to return. Defaults to ${config.performance.defaultSimilarLimit}.`, }, threshold: { type: "number", description: `Minimum similarity score (0-1) to include. Defaults to ${config.performance.defaultSimilarityThreshold}.`, }, }, required: ["element_name"], }, }, handler: (args: FindSimilarElementsArgs) => server.findSimilarElements({ elementName: args.element_name, elementType: args.element_type, limit: args.limit || config.performance.defaultSimilarLimit, threshold: args.threshold || config.performance.defaultSimilarityThreshold }) },
- TypeScript interface defining the argument shape for the tool handler.interface FindSimilarElementsArgs { element_name: string; element_type?: string; limit?: number; threshold?: number; }
- src/server/types.ts:79-82 (schema)IToolHandler interface defining the server method signature for findSimilarElements.findSimilarElements(options: {elementName: string; elementType?: string; limit: number; threshold: number}): Promise<any>; getElementRelationships(options: {elementName: string; elementType?: string; relationshipTypes?: string[]}): Promise<any>; searchByVerb(options: {verb: string; limit: number}): Promise<any>; getRelationshipStats(): Promise<any>;