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

NameRequiredDescriptionDefault
queryYes

Input Schema (JSON Schema)

{ "$schema": "http://json-schema.org/draft-07/schema#", "additionalProperties": false, "properties": { "query": { "minLength": 5, "type": "string" } }, "required": [ "query" ], "type": "object" }

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}`); } }

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