Skip to main content
Glama

query_conversation_history

Search and retrieve conversation sessions from architectural decision analysis using filters like date range, tools used, keywords, and project paths.

Instructions

Phase 3: Search and retrieve conversation sessions based on filters

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
projectPathNoFilter by project path
dateRangeNoFilter by date range
toolsUsedNoFilter by tools used in the session
keywordNoSearch keyword in conversation turns
limitNoMaximum number of sessions to return

Implementation Reference

  • The core handler function that implements the query_conversation_history tool. It constructs a SessionQuery from input args, calls memoryManager.querySessions(), formats the results into a markdown summary of matching conversation sessions, and returns an MCP CallToolResult.
    export async function queryConversationHistory(
      args: {
        projectPath?: string;
        dateRange?: { start: string; end: string };
        toolsUsed?: string[];
        keyword?: string;
        limit?: number;
      },
      memoryManager: ConversationMemoryManager
    ): Promise<CallToolResult> {
      try {
        const query: SessionQuery = {
          ...(args.projectPath ? { projectPath: args.projectPath } : {}),
          ...(args.dateRange ? { dateRange: args.dateRange } : {}),
          ...(args.toolsUsed ? { toolsUsed: args.toolsUsed } : {}),
          ...(args.keyword ? { keyword: args.keyword } : {}),
          limit: args.limit ?? 10,
        };
    
        const sessions = await memoryManager.querySessions(query);
    
        if (sessions.length === 0) {
          return {
            content: [
              {
                type: 'text',
                text: 'No conversation sessions found matching the query.',
              },
            ],
          };
        }
    
        let output = `# Conversation History (${sessions.length} sessions found)\n\n`;
    
        sessions.forEach((session, index) => {
          output += `## ${index + 1}. Session ${session.sessionId}\n\n`;
          output += `- **Project**: ${session.projectPath}\n`;
          output += `- **Started**: ${session.startedAt}\n`;
          output += `- **Last Activity**: ${session.lastActivityAt}\n`;
          output += `- **Turns**: ${session.turns.length}\n`;
          output += `- **Total Tokens**: ${session.metadata.totalTokensUsed}\n`;
          output += `- **Tools Used**: ${session.metadata.toolsUsed.join(', ')}\n`;
    
          // Show recent turns
          if (session.turns.length > 0) {
            output += `\n### Recent Turns:\n`;
            const recentTurns = session.turns.slice(-3);
            recentTurns.forEach(turn => {
              output += `- **Turn ${turn.turnNumber}**: ${turn.request.toolName || 'message'} `;
              output += `(${turn.metadata.duration}ms)\n`;
            });
          }
    
          output += `\n`;
        });
    
        return {
          content: [
            {
              type: 'text',
              text: output,
            },
          ],
        };
      } catch (error) {
        return {
          content: [
            {
              type: 'text',
              text: `❌ Failed to query conversation history: ${error instanceof Error ? error.message : String(error)}`,
            },
          ],
          isError: true,
        };
      }
    }
  • Type definition for SessionQuery interface, which defines the input parameters used by the tool handler (maps directly to tool args). This serves as the input schema validation for the tool.
    export interface SessionQuery {
      /** Filter by project path */
      projectPath?: string;
    
      /** Filter by date range */
      dateRange?: {
        start: string;
        end: string;
      };
    
      /** Filter by tools used */
      toolsUsed?: string[];
    
      /** Filter by keyword in turns */
      keyword?: string;
    
      /** Limit results */
      limit?: number;
    }
  • The underlying querySessions method in ConversationMemoryManager that performs the actual database/file query for conversation sessions based on the SessionQuery parameters. Called directly by the tool handler.
    async querySessions(query: SessionQuery): Promise<ConversationSession[]> {
      try {
        const sessionFiles = await fs.readdir(this.sessionsDir);
        const sessions: ConversationSession[] = [];
    
        for (const file of sessionFiles) {
          if (!file.endsWith('.json')) continue;
    
          const filePath = path.join(this.sessionsDir, file);
          const data = await fs.readFile(filePath, 'utf-8');
          const session = JSON.parse(data) as ConversationSession;
    
          // Apply filters
          if (query.projectPath && session.projectPath !== query.projectPath) continue;
          if (
            query.toolsUsed &&
            !query.toolsUsed.some(tool => session.metadata.toolsUsed.includes(tool))
          )
            continue;
          if (query.dateRange) {
            const sessionDate = new Date(session.startedAt);
            const start = new Date(query.dateRange.start);
            const end = new Date(query.dateRange.end);
            if (sessionDate < start || sessionDate > end) continue;
  • Metadata and approximate input schema registration in the central TOOL_CATALOG used for dynamic tool discovery and ListTools responses.
    TOOL_CATALOG.set('query_conversation_history', {
      name: 'query_conversation_history',
      shortDescription: 'Query conversation history',
      fullDescription: 'Queries the conversation history for relevant context.',
      category: 'memory',
      complexity: 'simple',
      tokenCost: { min: 500, max: 1500 },
      hasCEMCPDirective: true, // Phase 4.3: Simple tool - history query
      relatedTools: ['get_conversation_snapshot', 'memory_loading'],
      keywords: ['conversation', 'history', 'query', 'search'],
      requiresAI: false,
      inputSchema: {
        type: 'object',
        properties: {
          query: { type: 'string' },
          limit: { type: 'number', default: 20 },
        },
      },
    });
Behavior2/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. While it mentions 'search and retrieve', it doesn't describe what 'retrieve' entails - whether it returns full conversations, summaries, metadata, or paginated results. There's no mention of permissions needed, rate limits, or what happens when no matches are found. For a search tool with 5 parameters, this leaves significant behavioral questions unanswered.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is brief and to the point, consisting of a single clear sentence. The 'Phase 3:' prefix is unnecessary but doesn't significantly detract from conciseness. The description efficiently communicates the core function without wasted words, though it could be more front-loaded by placing the most critical information first.

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

Completeness2/5

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

For a search tool with 5 parameters, no annotations, and no output schema, the description is insufficient. It doesn't explain what constitutes a 'conversation session', what fields are searchable beyond the listed parameters, what format results return, or how to interpret empty results. With many sibling tools available, the lack of differentiation and behavioral context makes this description incomplete for effective tool selection.

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?

The schema description coverage is 100%, so all parameters are documented in the schema itself. The description adds minimal value beyond what the schema provides - it mentions 'filters' generally but doesn't explain how filters combine (AND/OR logic), what 'conversation sessions' include, or how the keyword search works across conversation turns. The baseline of 3 is appropriate given the comprehensive schema documentation.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose3/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description states the tool's purpose as 'Search and retrieve conversation sessions based on filters', which is clear but somewhat vague. It specifies the action (search/retrieve) and resource (conversation sessions), but doesn't differentiate from sibling tools like 'get_conversation_snapshot' or 'search_codebase'. The 'Phase 3' prefix adds unnecessary context but doesn't clarify the tool's unique role.

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?

The description provides no guidance on when to use this tool versus alternatives. With many sibling tools available (including 'get_conversation_snapshot' and 'search_codebase'), there's no indication of when this specific conversation history search tool is appropriate versus other search or retrieval tools. The description lacks any context about prerequisites, alternatives, or typical use cases.

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/tosin2013/mcp-adr-analysis-server'

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