Skip to main content
Glama

find_similar_queries

Search Claude Historian conversation history to find similar past queries and solutions, helping users avoid redundant work and build on previous insights.

Instructions

Find previous similar questions or queries with enhanced matching

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYesQuery to find similar previous questions
limitNoMaximum number of results (default: 8)
detail_levelNoResponse detail: summary (default), detailed, rawsummary

Implementation Reference

  • MCP tool handler for 'find_similar_queries': extracts parameters, calls UniversalHistorySearchEngine.findSimilarQueries, formats result with BeautifulFormatter.formatSimilarQueries based on detail_level, and returns formatted text content.
    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
      );
    
      return {
        content: [{ type: 'text', text: formattedResult }],
      };
    }
  • Input schema definition for the 'find_similar_queries' tool, including required 'query' string, optional 'limit' number (default 8), and 'detail_level' enum (summary/detailed/raw, default summary). Returned in tools/list response.
    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'],
    },
  • Core implementation of findSimilarQueries in HistorySearchEngine: scans conversation JSONL files across projects for user queries similar to targetQuery (using SearchHelpers.calculateQuerySimilarity >0.4 threshold), attaches following assistant response as claudeInsights, filters low-value content, sorts by relevance, limits to requested number.
    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 (let i = 0; i < userQueries.length; i++) {
              const query = userQueries[i];
              const similarity = SearchHelpers.calculateQuerySimilarity(targetQuery, query.content);
              // Raised threshold to 0.4 and REMOVED partial keyword fallback (causes false positives)
              if (similarity > 0.4) {
                query.relevanceScore = similarity;
    
                // Find the answer - look for next assistant message in original array
                const queryIndex = messages.findIndex((m) => m.uuid === query.uuid);
                if (queryIndex >= 0) {
                  // Look ahead for assistant response (may not be immediately next)
                  for (let j = queryIndex + 1; j < Math.min(queryIndex + 5, messages.length); j++) {
                    const nextMsg = messages[j];
                    if (nextMsg.type === 'assistant' && nextMsg.content.length > 50) {
                      query.context = query.context || {};
                      query.context.claudeInsights = [nextMsg.content.substring(0, 400)];
                      break;
                    }
                  }
                }
    
                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 [];
      }
    }
  • UniversalHistorySearchEngine.findSimilarQueries: delegates to HistorySearchEngine.findSimilarQueries (claudeCodeEngine), optionally combines with Claude Desktop search results (disabled), returns source, results, enhanced flag.
    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,
      };
    }
  • src/index.ts:41-256 (registration)
    Tool registration in MCP ListToolsRequestSchema handler: includes 'find_similar_queries' in the tools array with name, description, inputSchema.
    this.server.setRequestHandler(ListToolsRequestSchema, async () => {
      return {
        tools: [
          {
            name: 'search_conversations',
            description: 'Search through Claude Code conversation history with smart insights',
            inputSchema: {
              type: 'object',
              properties: {
                query: {
                  type: 'string',
                  description: 'Search query to find relevant conversations',
                },
                project: {
                  type: 'string',
                  description: 'Optional project name to filter results',
                },
                timeframe: {
                  type: 'string',
                  description: 'Time range filter (today, week, month)',
                },
                limit: {
                  type: 'number',
                  description: 'Maximum number of results (default: 10)',
                  default: 10,
                },
                detail_level: {
                  type: 'string',
                  description: 'Response detail: summary (default), detailed, raw',
                  enum: ['summary', 'detailed', 'raw'],
                  default: 'summary',
                },
              },
              required: ['query'],
            },
          },
          {
            name: 'find_file_context',
            description: 'Find all conversations and changes related to a specific file',
            inputSchema: {
              type: 'object',
              properties: {
                filepath: {
                  type: 'string',
                  description: 'File path to search for in conversation history',
                },
                operation_type: {
                  type: 'string',
                  description: 'Filter by operation: read, edit, create, or all',
                  enum: ['read', 'edit', 'create', 'all'],
                  default: 'all',
                },
                limit: {
                  type: 'number',
                  description: 'Maximum number of results (default: 15)',
                  default: 15,
                },
                detail_level: {
                  type: 'string',
                  description: 'Response detail: summary (default), detailed, raw',
                  enum: ['summary', 'detailed', 'raw'],
                  default: 'summary',
                },
              },
              required: ['filepath'],
            },
          },
          {
            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'],
            },
          },
          {
            name: 'get_error_solutions',
            description: 'Find solutions for specific errors with enhanced matching',
            inputSchema: {
              type: 'object',
              properties: {
                error_pattern: {
                  type: 'string',
                  description: 'Error message or pattern to search for solutions',
                },
                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: ['error_pattern'],
            },
          },
          {
            name: 'list_recent_sessions',
            description: 'Browse recent sessions with smart activity detection and summaries',
            inputSchema: {
              type: 'object',
              properties: {
                limit: {
                  type: 'number',
                  description: 'Maximum number of sessions (default: 10)',
                  default: 10,
                },
                project: {
                  type: 'string',
                  description: 'Optional project name to filter sessions',
                },
                include_summary: {
                  type: 'boolean',
                  description: 'Include intelligent session summaries (default: true)',
                  default: true,
                },
              },
            },
          },
          {
            name: 'extract_compact_summary',
            description: 'Get intelligent summary of a conversation session with key insights',
            inputSchema: {
              type: 'object',
              properties: {
                session_id: {
                  type: 'string',
                  description: 'Session ID to summarize',
                },
                max_messages: {
                  type: 'number',
                  description: 'Maximum messages to analyze (default: 10)',
                  default: 10,
                },
                focus: {
                  type: 'string',
                  description: 'Focus area: solutions, tools, files, or all',
                  enum: ['solutions', 'tools', 'files', 'all'],
                  default: 'all',
                },
              },
              required: ['session_id'],
            },
          },
          {
            name: 'find_tool_patterns',
            description: 'Analyze tool usage patterns, workflows, and successful practices',
            inputSchema: {
              type: 'object',
              properties: {
                tool_name: {
                  type: 'string',
                  description: 'Optional specific tool name to analyze',
                },
                pattern_type: {
                  type: 'string',
                  description: 'Type of patterns: tools, workflows, or solutions',
                  enum: ['tools', 'workflows', 'solutions'],
                  default: 'tools',
                },
                limit: {
                  type: 'number',
                  description: 'Maximum number of patterns (default: 12)',
                  default: 12,
                },
              },
            },
          },
          {
            name: 'search_plans',
            description:
              'Search Claude Code plan files for past implementation approaches, decisions, and patterns',
            inputSchema: {
              type: 'object',
              properties: {
                query: {
                  type: 'string',
                  description: 'Search query for plan content',
                },
                limit: {
                  type: 'number',
                  description: 'Maximum number of results (default: 10)',
                  default: 10,
                },
                detail_level: {
                  type: 'string',
                  description: 'Response detail level',
                  enum: ['summary', 'detailed', 'raw'],
                  default: 'summary',
                },
              },
              required: ['query'],
            },
          },
        ],
Behavior2/5

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

With no annotations provided, the description carries full burden for behavioral disclosure. It mentions 'enhanced matching' but doesn't explain what this means operationally—how similarity is determined, what data sources are searched, whether results are ranked, or what the output format looks like. This leaves significant gaps for a search tool.

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 with zero wasted words. It's appropriately sized and front-loaded with the core purpose.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's moderate complexity (search with similarity matching), no annotations, and no output schema, the description is minimally adequate but incomplete. It covers the basic purpose but lacks details on behavior, output format, and usage context that would help an agent invoke it correctly.

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 100%, so the schema already documents all three parameters thoroughly. The description adds no additional meaning about parameters beyond what's in the schema, meeting the baseline for high coverage.

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: 'Find previous similar questions or queries with enhanced matching'. It specifies the verb ('Find') and resource ('previous similar questions or queries'), but doesn't differentiate from siblings like 'search_conversations' or 'get_error_solutions' which might have overlapping functionality.

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?

No guidance is provided about when to use this tool versus alternatives. The description doesn't mention sibling tools like 'search_conversations' or 'get_error_solutions', nor does it specify context or prerequisites for using this tool.

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

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