Skip to main content
Glama

initialize_memory_bank

Initializes a structured project documentation folder at a specified location, enabling teams to manage and generate comprehensive project knowledge using Memory Bank MCP.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
geminiApiKeyNoGemini API key (optional)
goalYes
locationYesAbsolute path where memory-bank folder will be created

Implementation Reference

  • Registration of the initialize_memory_bank tool on the MCP server, including Zod input schema (goal required, geminiApiKey and location optional) and the complete handler function that orchestrates memory bank initialization.
      'initialize_memory_bank',
      {
        goal: z.string().min(10, 'Project goal must be at least 10 characters'),
        geminiApiKey: z.string().optional().describe('Gemini API key (optional)'),
        location: z.string().describe('Absolute path where memory-bank folder will be created')
      },
      async ({ goal, geminiApiKey, location }) => {
        try {
          // Diagnostics: Log environment info
          console.log(`Current working directory: ${process.cwd()}`);
          console.log(`Node version: ${process.version}`);
          console.log(`Platform: ${process.platform}`);
          
          // Determine where to create the memory-bank directory
          let baseDir;
          let memoryBankDir;
          
          if (location) {
            // Use user-specified location as the base directory
            if (path.isAbsolute(location)) {
              // If absolute path is provided, use it directly as base directory
              baseDir = location;
            } else {
              // If relative path is provided, resolve against current working directory
              baseDir = path.resolve(process.cwd(), location);
            }
            console.log(`Using user specified base location: ${baseDir}`);
          } else {
            // If no location provided, use current working directory as base
            baseDir = process.cwd();
            console.log(`No location specified, using current directory as base: ${baseDir}`);
          }
          
          // Create memory-bank directory inside the base directory
          memoryBankDir = path.join(baseDir, 'memory-bank');
          console.log(`Will create Memory Bank structure at: ${memoryBankDir}`);
          
          // Ensure parent directory exists if needed
          const parentDir = path.dirname(memoryBankDir);
          try {
            await fs.ensureDir(parentDir);
            console.log(`Ensured parent directory exists: ${parentDir}`);
          } catch (error) {
            console.error(`Error ensuring parent directory: ${error}`);
            throw new Error(`Cannot create or access parent directory: ${error}`);
          }
          
          // Set global memory bank directory
          MEMORY_BANK_DIR = memoryBankDir;
          
          console.log(`Will create Memory Bank at: ${MEMORY_BANK_DIR}`);
          
          // Ensure memory-bank directory exists before passing to createMemoryBankStructure
          try {
            await fs.ensureDir(MEMORY_BANK_DIR);
            console.log(`Created Memory Bank root directory: ${MEMORY_BANK_DIR}`);
          } catch (error) {
            console.error(`Error creating Memory Bank directory: ${error}`);
            throw new Error(`Cannot create Memory Bank directory: ${error}`);
          }
    
          // Temporarily set the API key if provided
          if (geminiApiKey) {
            process.env.GEMINI_API_KEY = geminiApiKey;
          }
    
          // First, set up the .byterules file before creating other files
          // This ensures the byterules file is in place before other operations
          const byterulesDest = path.join(MEMORY_BANK_DIR, '.byterules');
          
          try {
            // Debug: List all search paths we're going to try
            console.log('Searching for .byterules template file...');
            
            // Get the ESM compatible dirname
            const __filename = fileURLToPath(import.meta.url);
            const __dirname = dirname(__filename);
            console.log(`Current file directory: ${__dirname}`);
            
            // Try multiple possible locations for the .byterules file
            const possiblePaths = [
              path.join(process.cwd(), 'src', 'templates', '.byterules'),          // From current working dir
              path.join(__dirname, '..', 'templates', '.byterules'),               // From mcp dir to templates
              path.join(__dirname, '..', '..', 'src', 'templates', '.byterules'),  // From mcp dir up two levels
              path.join(process.cwd(), 'templates', '.byterules'),                 // Direct templates folder
              path.join(process.cwd(), '.byterules')                               // Root of project
            ];
            
            // Manually create .byterules content as fallback
            const defaultByterules = `# Memory Bank Document Orchestration Standard
    
    ## Directory Validation
    
    Before any operation (create/update/reference/review), ensure you are in the correct project root directory. Specifically:
    
    - A valid Memory Bank system **must contain** this \`.byterules\` file at its root.
    - If this file is missing, halt operations and **navigate to the correct directory** using:
    
    \`\`\`bash
    cd /your/project/root
    \`\`\`
    
    Failing to validate the directory can lead to misplaced or inconsistent documentation.
    
    ---
    
    ## System Overview
    
    Memory Bank is a structured documentation system designed to maintain project knowledge in an organized, accessible format. This \`.byterules\` file serves as the standard guide for how the system works across all projects.
    
    ## Standard Document Types
    
    ### 1. Project Brief (projectbrief.md)
    - **Purpose**: Core document that defines project objectives, scope, and vision
    - **When to Use**: Reference when making any major project decisions
    - **Workflow Step**: Start here; all other documents derive from this foundation
    - **Critical For**: Maintaining alignment with business goals throughout development
    
    ### 2. Product Context (productContext.md)
    - **Purpose**: Documents product functionality from a user perspective
    - **When to Use**: When designing features and establishing requirements
    - **Workflow Step**: Second document in sequence, expands on project brief goals
    - **Critical For**: Ensuring user needs drive technical decisions
    
    ### 3. System Patterns (systemPatterns.md)
    - **Purpose**: Establishes system architecture and component relationships
    - **When to Use**: During system design and when making integration decisions
    - **Workflow Step**: Third document, translates product needs to technical design
    - **Critical For**: Maintaining a coherent and scalable technical architecture
    
    ### 4. Tech Context (techContext.md)
    - **Purpose**: Specifies technology stack and implementation details
    - **When to Use**: During development and when onboarding technical team members
    - **Workflow Step**: Fourth document, makes concrete technology choices
    - **Critical For**: Technical consistency and efficient development
    
    ### 5. Active Context (activeContext.md)
    - **Purpose**: Tracks current tasks, open issues, and development focus
    - **When to Use**: Daily, during planning sessions, and when switching tasks
    - **Workflow Step**: Fifth document, operationalizes the technical approach
    - **Critical For**: Day-to-day execution and short-term planning
    
    ### 6. Progress (progress.md)
    - **Purpose**: Documents completed work, milestones, and project history
    - **When to Use**: After completing significant work or during reviews
    - **Workflow Step**: Ongoing document that records the project journey
    - **Critical For**: Tracking accomplishments and learning from experience
    
    ## Standard Workflows
    
    ### Documentation Sequence
    Always follow this sequence for document creation and reference:
    1. **Project Brief** → Foundation of all project decisions
    2. **Product Context** → User-focused requirements and features
    3. **System Patterns** → Architecture and component design
    4. **Tech Context** → Technology choices and implementation guidelines
    5. **Active Context** → Current work and immediate focus
    6. **Progress** → Historical record and milestone tracking
    
    ### Document Lifecycle Management
    Each document follows a standard lifecycle:
    1. **Creation**: Establish initial content based on project needs
    2. **Reference**: Use document for planning and decision-making
    3. **Update**: Revise when relevant factors change
    4. **Review**: Periodically validate for accuracy and completeness
    5. **Archive**: Maintain as historical reference when superseded
    
    ## Best Practices
    
    ### Document Quality Standards
    - **Clarity**: Write in clear, concise language
    - **Completeness**: Include all relevant information
    - **Consistency**: Use consistent terminology across documents
    - **Structure**: Follow standardized document formats
    - **Granularity**: Balance detail with readability
    - **Traceability**: Link related concepts across documents
    
    ### Document Integration Principles
    - **Vertical Traceability**: Ensure business goals trace to technical implementation
    - **Horizontal Consistency**: Maintain alignment across documents at the same level
    - **Change Impact Analysis**: Update related documents when one changes
    - **Decision Recording**: Document the reasoning behind significant decisions
    
    
    `;
            
            // Try each path and use the first one that exists
            let bytesRulesFound = false;
            
            for (const testPath of possiblePaths) {
              console.log(`Checking path: ${testPath}`);
              
              if (await fs.pathExists(testPath)) {
                console.log(`✓ Found .byterules at: ${testPath}`);
                await fs.copy(testPath, byterulesDest);
                console.log(`Standard .byterules file copied to: ${byterulesDest}`);
                bytesRulesFound = true;
                break;
              } else {
                console.log(`✗ Not found at: ${testPath}`);
              }
            }
            
            // If no .byterules file found, create one with the default content
            if (!bytesRulesFound) {
              console.log('No .byterules template found, creating default');
              await fs.writeFile(byterulesDest, defaultByterules, 'utf-8');
              console.log(`Default .byterules file created at: ${byterulesDest}`);
            }
            
          } catch (error) {
            console.error(`Error setting up .byterules file: ${error}`);
            throw new Error(`Failed to set up .byterules file: ${error}`);
          }
          
          // Now create the full structure
          await createMemoryBankStructure(MEMORY_BANK_DIR);
    
          // Generate document contents
          const documentContents = await generateAllDocuments(goal);
    
          // Save each document
          for (const [docType, content] of Object.entries(documentContents)) {
            const filePath = path.join(MEMORY_BANK_DIR, `${docType}.md`);
            await saveDocument(content, filePath);
          }
    
          return {
            content: [
              { 
                type: 'text', 
                text: `✅ Memory Bank successfully created!\n\nLocation: ${MEMORY_BANK_DIR}\n\nGenerated Documents:\n- projectbrief.md\n- productContext.md\n- systemPatterns.md\n- techContext.md\n- activeContext.md\n- progress.md\n- .byterules` 
              }
            ]
          };
        } catch (error) {
          console.error('Error creating Memory Bank:', error);
          return {
            content: [{ type: 'text', text: `❌ Error: ${error instanceof Error ? error.message : String(error)}` }],
            isError: true
          };
        }
      }
    );
  • The core handler function for executing the tool logic: sets up the memory-bank directory, handles .byterules, imports helpers for structure creation, document generation via Gemini, and saving files.
      async ({ goal, geminiApiKey, location }) => {
        try {
          // Diagnostics: Log environment info
          console.log(`Current working directory: ${process.cwd()}`);
          console.log(`Node version: ${process.version}`);
          console.log(`Platform: ${process.platform}`);
          
          // Determine where to create the memory-bank directory
          let baseDir;
          let memoryBankDir;
          
          if (location) {
            // Use user-specified location as the base directory
            if (path.isAbsolute(location)) {
              // If absolute path is provided, use it directly as base directory
              baseDir = location;
            } else {
              // If relative path is provided, resolve against current working directory
              baseDir = path.resolve(process.cwd(), location);
            }
            console.log(`Using user specified base location: ${baseDir}`);
          } else {
            // If no location provided, use current working directory as base
            baseDir = process.cwd();
            console.log(`No location specified, using current directory as base: ${baseDir}`);
          }
          
          // Create memory-bank directory inside the base directory
          memoryBankDir = path.join(baseDir, 'memory-bank');
          console.log(`Will create Memory Bank structure at: ${memoryBankDir}`);
          
          // Ensure parent directory exists if needed
          const parentDir = path.dirname(memoryBankDir);
          try {
            await fs.ensureDir(parentDir);
            console.log(`Ensured parent directory exists: ${parentDir}`);
          } catch (error) {
            console.error(`Error ensuring parent directory: ${error}`);
            throw new Error(`Cannot create or access parent directory: ${error}`);
          }
          
          // Set global memory bank directory
          MEMORY_BANK_DIR = memoryBankDir;
          
          console.log(`Will create Memory Bank at: ${MEMORY_BANK_DIR}`);
          
          // Ensure memory-bank directory exists before passing to createMemoryBankStructure
          try {
            await fs.ensureDir(MEMORY_BANK_DIR);
            console.log(`Created Memory Bank root directory: ${MEMORY_BANK_DIR}`);
          } catch (error) {
            console.error(`Error creating Memory Bank directory: ${error}`);
            throw new Error(`Cannot create Memory Bank directory: ${error}`);
          }
    
          // Temporarily set the API key if provided
          if (geminiApiKey) {
            process.env.GEMINI_API_KEY = geminiApiKey;
          }
    
          // First, set up the .byterules file before creating other files
          // This ensures the byterules file is in place before other operations
          const byterulesDest = path.join(MEMORY_BANK_DIR, '.byterules');
          
          try {
            // Debug: List all search paths we're going to try
            console.log('Searching for .byterules template file...');
            
            // Get the ESM compatible dirname
            const __filename = fileURLToPath(import.meta.url);
            const __dirname = dirname(__filename);
            console.log(`Current file directory: ${__dirname}`);
            
            // Try multiple possible locations for the .byterules file
            const possiblePaths = [
              path.join(process.cwd(), 'src', 'templates', '.byterules'),          // From current working dir
              path.join(__dirname, '..', 'templates', '.byterules'),               // From mcp dir to templates
              path.join(__dirname, '..', '..', 'src', 'templates', '.byterules'),  // From mcp dir up two levels
              path.join(process.cwd(), 'templates', '.byterules'),                 // Direct templates folder
              path.join(process.cwd(), '.byterules')                               // Root of project
            ];
            
            // Manually create .byterules content as fallback
            const defaultByterules = `# Memory Bank Document Orchestration Standard
    
    ## Directory Validation
    
    Before any operation (create/update/reference/review), ensure you are in the correct project root directory. Specifically:
    
    - A valid Memory Bank system **must contain** this \`.byterules\` file at its root.
    - If this file is missing, halt operations and **navigate to the correct directory** using:
    
    \`\`\`bash
    cd /your/project/root
    \`\`\`
    
    Failing to validate the directory can lead to misplaced or inconsistent documentation.
    
    ---
    
    ## System Overview
    
    Memory Bank is a structured documentation system designed to maintain project knowledge in an organized, accessible format. This \`.byterules\` file serves as the standard guide for how the system works across all projects.
    
    ## Standard Document Types
    
    ### 1. Project Brief (projectbrief.md)
    - **Purpose**: Core document that defines project objectives, scope, and vision
    - **When to Use**: Reference when making any major project decisions
    - **Workflow Step**: Start here; all other documents derive from this foundation
    - **Critical For**: Maintaining alignment with business goals throughout development
    
    ### 2. Product Context (productContext.md)
    - **Purpose**: Documents product functionality from a user perspective
    - **When to Use**: When designing features and establishing requirements
    - **Workflow Step**: Second document in sequence, expands on project brief goals
    - **Critical For**: Ensuring user needs drive technical decisions
    
    ### 3. System Patterns (systemPatterns.md)
    - **Purpose**: Establishes system architecture and component relationships
    - **When to Use**: During system design and when making integration decisions
    - **Workflow Step**: Third document, translates product needs to technical design
    - **Critical For**: Maintaining a coherent and scalable technical architecture
    
    ### 4. Tech Context (techContext.md)
    - **Purpose**: Specifies technology stack and implementation details
    - **When to Use**: During development and when onboarding technical team members
    - **Workflow Step**: Fourth document, makes concrete technology choices
    - **Critical For**: Technical consistency and efficient development
    
    ### 5. Active Context (activeContext.md)
    - **Purpose**: Tracks current tasks, open issues, and development focus
    - **When to Use**: Daily, during planning sessions, and when switching tasks
    - **Workflow Step**: Fifth document, operationalizes the technical approach
    - **Critical For**: Day-to-day execution and short-term planning
    
    ### 6. Progress (progress.md)
    - **Purpose**: Documents completed work, milestones, and project history
    - **When to Use**: After completing significant work or during reviews
    - **Workflow Step**: Ongoing document that records the project journey
    - **Critical For**: Tracking accomplishments and learning from experience
    
    ## Standard Workflows
    
    ### Documentation Sequence
    Always follow this sequence for document creation and reference:
    1. **Project Brief** → Foundation of all project decisions
    2. **Product Context** → User-focused requirements and features
    3. **System Patterns** → Architecture and component design
    4. **Tech Context** → Technology choices and implementation guidelines
    5. **Active Context** → Current work and immediate focus
    6. **Progress** → Historical record and milestone tracking
    
    ### Document Lifecycle Management
    Each document follows a standard lifecycle:
    1. **Creation**: Establish initial content based on project needs
    2. **Reference**: Use document for planning and decision-making
    3. **Update**: Revise when relevant factors change
    4. **Review**: Periodically validate for accuracy and completeness
    5. **Archive**: Maintain as historical reference when superseded
    
    ## Best Practices
    
    ### Document Quality Standards
    - **Clarity**: Write in clear, concise language
    - **Completeness**: Include all relevant information
    - **Consistency**: Use consistent terminology across documents
    - **Structure**: Follow standardized document formats
    - **Granularity**: Balance detail with readability
    - **Traceability**: Link related concepts across documents
    
    ### Document Integration Principles
    - **Vertical Traceability**: Ensure business goals trace to technical implementation
    - **Horizontal Consistency**: Maintain alignment across documents at the same level
    - **Change Impact Analysis**: Update related documents when one changes
    - **Decision Recording**: Document the reasoning behind significant decisions
    
    
    `;
            
            // Try each path and use the first one that exists
            let bytesRulesFound = false;
            
            for (const testPath of possiblePaths) {
              console.log(`Checking path: ${testPath}`);
              
              if (await fs.pathExists(testPath)) {
                console.log(`✓ Found .byterules at: ${testPath}`);
                await fs.copy(testPath, byterulesDest);
                console.log(`Standard .byterules file copied to: ${byterulesDest}`);
                bytesRulesFound = true;
                break;
              } else {
                console.log(`✗ Not found at: ${testPath}`);
              }
            }
            
            // If no .byterules file found, create one with the default content
            if (!bytesRulesFound) {
              console.log('No .byterules template found, creating default');
              await fs.writeFile(byterulesDest, defaultByterules, 'utf-8');
              console.log(`Default .byterules file created at: ${byterulesDest}`);
            }
            
          } catch (error) {
            console.error(`Error setting up .byterules file: ${error}`);
            throw new Error(`Failed to set up .byterules file: ${error}`);
          }
          
          // Now create the full structure
          await createMemoryBankStructure(MEMORY_BANK_DIR);
    
          // Generate document contents
          const documentContents = await generateAllDocuments(goal);
    
          // Save each document
          for (const [docType, content] of Object.entries(documentContents)) {
            const filePath = path.join(MEMORY_BANK_DIR, `${docType}.md`);
            await saveDocument(content, filePath);
          }
    
          return {
            content: [
              { 
                type: 'text', 
                text: `✅ Memory Bank successfully created!\n\nLocation: ${MEMORY_BANK_DIR}\n\nGenerated Documents:\n- projectbrief.md\n- productContext.md\n- systemPatterns.md\n- techContext.md\n- activeContext.md\n- progress.md\n- .byterules` 
              }
            ]
          };
        } catch (error) {
          console.error('Error creating Memory Bank:', error);
          return {
            content: [{ type: 'text', text: `❌ Error: ${error instanceof Error ? error.message : String(error)}` }],
            isError: true
          };
        }
      }
  • Supporting utility that generates initial content for all memory bank documents using the Gemini API based on the project goal.
    export async function generateAllDocuments(goal: string): Promise<Record<string, string>> {
      const currentDate = new Date().toLocaleDateString('tr-TR');
      
      const basePrompt = `
    You are a project documentation expert. You will create comprehensive documentation for the following project:
    
    PROJECT PURPOSE: ${goal}
    
    Create the following documents for this project:
    `;
    
      const documentTypes = {
        projectbrief: `
    1. Project Brief (projectbrief.md):
       - Explain the general purpose and vision of the project
       - List the main objectives
       - Define the target audience
       - Specify key features
       - Determine success criteria
       - Present a realistic timeline`,
        
        productContext: `
    2. Product Context (productContext.md):
       - Conduct market analysis
       - Evaluate competitive landscape
       - Write user stories
       - List requirements
       - Explain workflows
       - Define product roadmap`,
        
        systemPatterns: `
    3. System Patterns (systemPatterns.md):
       - Explain architectural design
       - Define data models
       - Specify API definitions
       - Show component structure
       - List integration points
       - Explain scalability strategy`,
        
        techContext: `
    4. Technology Context (techContext.md):
       - List technologies used
       - Specify software development tools
       - Define development environment
       - Explain testing strategy
       - Define deployment process
       - Explain continuous integration approach`,
        
        activeContext: `
    5. Active Context (activeContext.md):
       - Explain current sprint goals
       - List ongoing tasks
       - Specify known issues
       - Define priorities
       - Explain next steps
       - Add meeting notes`,
        
        progress: `
    6. Progress Report (progress.md):
       - List completed tasks
       - Specify milestones
       - Report test results
       - Show performance metrics
       - Summarize feedback
       - Maintain a changelog`
      };
      
    
      const results: Record<string, string> = {};
    
      for (const [docType, docPrompt] of Object.entries(documentTypes)) {
        console.log(`Creating ${docType} document...`);
        
        const fullPrompt = `${basePrompt}${docPrompt}\n\nPlease create content only for the "${docType}" document. Use Markdown format with section headers marked by ##. At the end of the document, add the note "Created on ${currentDate}".`;
        
        const content = await generateContent(fullPrompt);
        results[docType] = content;
      }
    
      return results;
    }
  • Helper function called by handler to create the memory bank directory structure and README.md file.
    export async function createMemoryBankStructure(outputDir: string): Promise<void> {
      try {
        console.log(`Creating Memory Bank structure in existing directory: ${outputDir}`);
        
        // Verify directory exists
        if (!await fs.pathExists(outputDir)) {
          console.warn(`Directory does not exist: ${outputDir}, will create it`);
          await fs.ensureDir(outputDir);
        }
        
        // No subdirectories needed - using a flat structure for simplicity
        console.log(`Using flat structure for Memory Bank in "${outputDir}"`);
        
        // Create a README.md file with component descriptions
        const readmePath = path.join(outputDir, 'README.md');
        const readmeContent = `# Memory Bank
    
    This directory serves as a structured repository for your project information and notes.
    
    ## Directory Structure
    - **resources**: Images, diagrams, and other resources
    - **temp**: Temporary files and drafts
    - **archive**: Archived documents
    - **references**: Reference materials and documentation
    
    ## Core Documents
    - **projectbrief.md**: Project goals, scope, and vision
    - **productContext.md**: Product features, user stories, and market context
    - **systemPatterns.md**: System architecture, design patterns, and component structure
    - **techContext.md**: Technology stack, frameworks, and technical specifications
    - **activeContext.md**: Active tasks, current sprint, and in-progress work
    - **progress.md**: Progress tracking, milestones, and project history
    
    ## Document Management
    This Memory Bank uses a structured approach to organize project knowledge. Each document serves a specific purpose in the project lifecycle and should be maintained according to the rules specified in the \`.byterules\` file.
    
    See the \`.byterules\` file for detailed guidelines on how to maintain and update these documents.
    `;
        try {
          await fs.writeFile(readmePath, readmeContent, 'utf-8');
          console.log(`README file created at: ${readmePath}`);
        } catch (error) {
          const err = error as any;
          console.error(`Error creating README file: ${err.code} - ${err.message}`);
          // Continue without README
        }
        
        console.log(`Memory Bank structure successfully created in "${outputDir}".`);
      } catch (error) {
        console.error(`Error creating directory structure at ${outputDir}:`, error);
        if (error instanceof Error) {
          throw new Error(`Failed to create Memory Bank structure: ${error.message} (Code: ${(error as any).code || 'UNKNOWN'})`);
        } else {
          throw new Error(`Failed to create Memory Bank structure: Unknown error`);
        }
      }
    }
  • Helper function used in loop to save each generated document to its .md file.
    export async function saveDocument(content: string, filePath: string): Promise<void> {
      try {
        // Ensure directory exists
        await fs.ensureDir(path.dirname(filePath));
        
        // Write file
        await fs.writeFile(filePath, content, 'utf-8');
        
        console.log(`Document saved: ${filePath}`);
      } catch (error) {
        console.error('Error saving document:', error);
        throw new Error(`Failed to save document: ${error}`);
      }
    }
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