Skip to main content
Glama

find_similar_queries

Identify and retrieve previously saved queries or questions similar to your current search to leverage past insights and solutions efficiently.

Instructions

Find previous similar questions or queries

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
limitNoMaximum number of results (default: 10)
queryYesQuery to find similar previous questions

Implementation Reference

  • Core handler function in HistorySearchEngine that implements the logic for finding similar user queries in conversation history by parsing JSONL files, filtering quality user messages, computing similarity scores using SearchHelpers, and returning top matches.
    async findSimilarQueries(targetQuery: string, limit: number = 10): Promise<CompactMessage[]> { const allMessages: CompactMessage[] = []; try { const projectDirs = await findProjectDirectories(); // BALANCED: More projects for better coverage, early termination for speed const limitedDirs = projectDirs.slice(0, 8); for (const projectDir of limitedDirs) { const jsonlFiles = await findJsonlFiles(projectDir); // BALANCED: More files per project for better context const limitedFiles = jsonlFiles.slice(0, 5); for (const file of limitedFiles) { const messages = await this.parser.parseJsonlFile(projectDir, file); // Find user messages (queries) that are similar and valuable const userQueries = messages.filter( (msg) => msg.type === 'user' && msg.content.length > 15 && msg.content.length < 800 && !this.isLowValueContent(msg.content) // Only quality queries ); for (const query of userQueries) { const similarity = SearchHelpers.calculateQuerySimilarity(targetQuery, query.content); // Lowered threshold from 0.3 to 0.1 and added partial matching if (similarity > 0.2 || SearchHelpers.hasExactKeywords(targetQuery, query.content)) { query.relevanceScore = similarity; allMessages.push(query); } } // SPEED FIX: Early termination when we have enough candidates if (allMessages.length >= limit * 4) break; } if (allMessages.length >= limit * 4) break; } // Quality filter and return only if we have valuable results const qualityResults = allMessages .filter(msg => !this.isLowValueContent(msg.content)) .sort((a, b) => (b.relevanceScore || 0) - (a.relevanceScore || 0)) .slice(0, limit); return qualityResults; } catch (error) { console.error('Similar query search error:', error); return []; } }
  • Input schema and tool metadata definition for 'find_similar_queries' registered in the MCP tools list.
    { name: 'find_similar_queries', description: 'Find previous similar questions or queries with enhanced matching', inputSchema: { type: 'object', properties: { query: { type: 'string', description: 'Query to find similar previous questions', }, limit: { type: 'number', description: 'Maximum number of results (default: 8)', default: 8, }, detail_level: { type: 'string', description: 'Response detail: summary (default), detailed, raw', enum: ['summary', 'detailed', 'raw'], default: 'summary', }, }, required: ['query'], },
  • src/index.ts:304-331 (registration)
    MCP tool call handler dispatch for 'find_similar_queries' that invokes UniversalHistorySearchEngine.findSimilarQueries and formats the response.
    case 'find_similar_queries': { const universalResult = await this.universalEngine.findSimilarQueries( args?.query as string, (args?.limit as number) || 8 ); const detailLevel = (args?.detail_level as string) || 'summary'; const formattedResult = this.formatter.formatSimilarQueries(universalResult.results, args?.query as string, detailLevel); // Create enhanced 3-line header with similarity context const lines = formattedResult.split('\n'); const sourceInfo = universalResult.enhanced ? '[⌐◆_◆] Searching: Claude Code + Desktop' : '[⌐◆_◆] Searching: Claude Code'; const actionInfo = `Query: "${args?.query}" | Action: Similar queries & patterns`; lines[0] = sourceInfo; lines[1] = actionInfo; return { content: [ { type: 'text', text: lines.join('\n'), }, ], }; }
  • Wrapper handler in UniversalHistorySearchEngine that delegates to HistorySearchEngine.findSimilarQueries and optionally augments with Claude Desktop conversation data.
    async findSimilarQueries( query: string, limit?: number ): Promise<{ source: string; results: CompactMessage[]; enhanced: boolean }> { await this.initialize(); const claudeCodeResults = await this.claudeCodeEngine.findSimilarQueries(query, limit); if (!this.claudeDesktopAvailable) { return { source: 'claude-code', results: claudeCodeResults, enhanced: false }; } const desktopMessages = await this.searchClaudeDesktopConversations( query, undefined, limit ); const combinedResults = [...claudeCodeResults, ...desktopMessages]; const hasDesktopData = desktopMessages.length > 0; return { source: hasDesktopData ? 'claude-desktop' : 'claude-code', results: combinedResults, enhanced: hasDesktopData }; }
  • Supporting utility functions SearchHelpers.calculateQuerySimilarity and SearchHelpers.hasExactKeywords used in the core handler for similarity scoring and keyword matching.
    import { CompactMessage, FileContext } from './types.js'; export class SearchHelpers { // Enhanced semantic query expansion for better search results static expandQuery(query: string): string[] { const baseQuery = query.toLowerCase().trim(); const expansions = [baseQuery]; // Technical term expansions const technicalExpansions: Record<string, string[]> = { 'error': ['exception', 'fail', 'crash', 'bug', 'issue'], 'fix': ['resolve', 'solve', 'repair', 'correct'], 'implement': ['create', 'build', 'develop', 'add'], 'optimize': ['improve', 'enhance', 'speed up', 'performance'], 'debug': ['troubleshoot', 'diagnose', 'trace'], 'deploy': ['publish', 'release', 'launch'], 'test': ['verify', 'check', 'validate'], 'config': ['configuration', 'settings', 'setup'], 'auth': ['authentication', 'login', 'security'], 'api': ['endpoint', 'service', 'request'] }; for (const [term, synonyms] of Object.entries(technicalExpansions)) { if (baseQuery.includes(term)) { expansions.push(...synonyms); } } // Pattern-based expansions if (baseQuery.includes('.ts')) expansions.push('typescript', 'type'); if (baseQuery.includes('.js')) expansions.push('javascript'); if (baseQuery.includes('npm')) expansions.push('package', 'dependency'); if (baseQuery.includes('git')) expansions.push('version control', 'commit'); return [...new Set(expansions)]; } // Intelligent content deduplication static deduplicateByContent(messages: CompactMessage[]): CompactMessage[] { const seen = new Map<string, CompactMessage>(); for (const message of messages) { const signature = this.createContentSignature(message); if (!seen.has(signature)) { seen.set(signature, message); } else { // Keep the message with higher relevance score const existing = seen.get(signature)!;

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/Vvkmnn/claude-historian'

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