Skip to main content
Glama

query_memory_bank

Query structured project documentation to retrieve relevant information efficiently. Supports precise searches for project knowledge using AI-powered access to stored data.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYes

Implementation Reference

  • Main handler function for the 'query_memory_bank' tool. Validates memory bank initialization, reads all documents using readAllDocuments, performs advanced search, formats relevant snippets from top matching documents, and returns structured text response.
    async ({ query }) => {
      try {
        // Check if Memory Bank has been initialized
        if (!MEMORY_BANK_DIR) {
          return {
            content: [{ type: 'text', text: `ℹ️ Memory Bank not initialized. Please use 'initialize_memory_bank' tool first.` }]
          };
        }
    
        // Check if Memory Bank directory exists on disk
        if (!await fs.pathExists(MEMORY_BANK_DIR)) {
          return {
            content: [{ type: 'text', text: `ℹ️ Memory Bank directory (${MEMORY_BANK_DIR}) not found on disk. Please use 'initialize_memory_bank' tool first.` }]
          };
        }
    
        // Read all documents
        const documents = await readAllDocuments(MEMORY_BANK_DIR);
        
        // Advanced search function
        const searchResults = performAdvancedSearch(query, documents);
        
        if (searchResults.length === 0) {
          return {
            content: [{ type: 'text', text: `ℹ️ No results found for query "${query}".` }]
          };
        }
        
        // Format results
        const formattedResults = searchResults.map(result => {
          return `📄 **${result.documentType}**:\n${result.snippet}\n`;
        }).join('\n');
        
        return {
          content: [{ 
            type: 'text', 
            text: `🔍 Results for query "${query}":\n\n${formattedResults}` 
          }]
        };
      } catch (error) {
        console.error('Error querying Memory Bank:', error);
        return {
          content: [{ type: 'text', text: `❌ Error: ${error instanceof Error ? error.message : String(error)}` }],
          isError: true
        };
      }
  • Zod input schema for the query_memory_bank tool, requiring a 'query' string parameter with minimum length of 5 characters.
    {
      query: z.string().min(5, 'Query must be at least 5 characters')
    },
  • MCP server.tool registration for 'query_memory_bank', specifying tool name, input schema, and handler function reference.
    server.tool(
      'query_memory_bank',
      {
        query: z.string().min(5, 'Query must be at least 5 characters')
      },
      async ({ query }) => {
        try {
          // Check if Memory Bank has been initialized
          if (!MEMORY_BANK_DIR) {
            return {
              content: [{ type: 'text', text: `ℹ️ Memory Bank not initialized. Please use 'initialize_memory_bank' tool first.` }]
            };
          }
    
          // Check if Memory Bank directory exists on disk
          if (!await fs.pathExists(MEMORY_BANK_DIR)) {
            return {
              content: [{ type: 'text', text: `ℹ️ Memory Bank directory (${MEMORY_BANK_DIR}) not found on disk. Please use 'initialize_memory_bank' tool first.` }]
            };
          }
    
          // Read all documents
          const documents = await readAllDocuments(MEMORY_BANK_DIR);
          
          // Advanced search function
          const searchResults = performAdvancedSearch(query, documents);
          
          if (searchResults.length === 0) {
            return {
              content: [{ type: 'text', text: `ℹ️ No results found for query "${query}".` }]
            };
          }
          
          // Format results
          const formattedResults = searchResults.map(result => {
            return `📄 **${result.documentType}**:\n${result.snippet}\n`;
          }).join('\n');
          
          return {
            content: [{ 
              type: 'text', 
              text: `🔍 Results for query "${query}":\n\n${formattedResults}` 
            }]
          };
        } catch (error) {
          console.error('Error querying Memory Bank:', error);
          return {
            content: [{ type: 'text', text: `❌ Error: ${error instanceof Error ? error.message : String(error)}` }],
            isError: true
          };
        }
      }
    );
  • performAdvancedSearch helper: implements semantic search by splitting documents into sections and paragraphs, computing relevance scores for query terms, extracting snippets, sorting by score, and limiting to top 5 results.
    function performAdvancedSearch(query: string, documents: Record<string, string>): SearchResult[] {
      const results: SearchResult[] = [];
      const queryTerms = query.toLowerCase().split(/\s+/).filter(term => term.length > 2);
      
      // Search in each document
      for (const [docType, content] of Object.entries(documents)) {
        // Split document into sections and paragraphs
        const sections = content.split(/\n#{2,3}\s+/).filter(Boolean);
        
        for (const section of sections) {
          // Extract title and content
          const titleMatch = section.match(/^([^\n]+)/);
          const title = titleMatch ? titleMatch[1].trim() : '';
          
          // Evaluate each paragraph
          const paragraphs = section.split(/\n\n+/);
          
          for (const paragraph of paragraphs) {
            // Calculate relevance score
            const relevanceScore = calculateRelevanceScore(query, queryTerms, paragraph);
            
            // Add results above threshold
            if (relevanceScore > 0.3) {
              // Extract relevant snippet
              const snippet = extractRelevantSnippet(paragraph, queryTerms, title);
              
              results.push({
                documentType: docType,
                relevanceScore,
                snippet
              });
            }
          }
        }
      }
      
      // Sort results by relevance and return top 5
      return results
        .sort((a, b) => b.relevanceScore - a.relevanceScore)
        .slice(0, 5);
    }
  • readAllDocuments utility function called by the handler to load all .md documents from the memory bank directory into a Record<string, string> for search processing.
    export async function readAllDocuments(directoryPath: string): Promise<Record<string, string>> {
      try {
        // Check if directory exists
        if (!await fs.pathExists(directoryPath)) {
          throw new Error(`Directory not found: ${directoryPath}`);
        }
        
        // List all files
        const files = await fs.readdir(directoryPath);
        
        // Filter only markdown files
        const markdownFiles = files.filter(file => file.endsWith('.md'));
        
        // Read each file
        const results: Record<string, string> = {};
        
        for (const file of markdownFiles) {
          const filePath = path.join(directoryPath, file);
          const content = await fs.readFile(filePath, 'utf-8');
          
          // Use filename as key (without extension)
          const fileName = path.basename(file, path.extname(file));
          results[fileName] = content;
        }
        
        return results;
      } catch (error) {
        console.error('Error reading documents:', error);
        throw new Error(`Failed to read documents: ${error}`);
      }
    }
Behavior1/5

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

Tool has no description.

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

Conciseness1/5

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

Tool has no description.

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

Completeness1/5

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

Tool has no description.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters1/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Tool has no description.

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

Purpose1/5

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

Tool has no description.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines1/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Tool has no description.

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

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/tuncer-byte/memory-bank-MCP'

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