Skip to main content
Glama

initialize_memory_bank

Set up a Memory Bank in a specified directory to create a central knowledge base with SSH support for efficient data storage and retrieval.

Instructions

Initialize a Memory Bank in the specified directory

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
pathYesPath where the Memory Bank will be initialized

Implementation Reference

  • The primary handler function for the 'initialize_memory_bank' MCP tool. It sets the custom path, calls MemoryBankManager.initialize(true), and returns success/error messages.
    export async function handleInitializeMemoryBank(
      memoryBankManager: MemoryBankManager,
      dirPath: string
    ) {
      try {
        // If dirPath is not provided, use the project path
        const basePath = dirPath || memoryBankManager.getProjectPath();
        
        // Ensure the path is absolute
        const absolutePath = path.isAbsolute(basePath) ? basePath : path.resolve(process.cwd(), basePath);
        console.error('Using absolute path:', absolutePath);
        
        try {
          // Set the custom path first
          await memoryBankManager.setCustomPath(absolutePath);
          
          // Initialize the Memory Bank with createIfNotExists = true
          await memoryBankManager.initialize(true);
          
          // Get the Memory Bank directory
          const memoryBankDir = memoryBankManager.getMemoryBankDir();
          
          return {
            content: [
              {
                type: 'text',
                text: `Memory Bank initialized at ${memoryBankDir}`,
              },
            ],
          };
        } catch (initError) {
          // Check if the error is related to .clinerules files
          const errorMessage = String(initError);
          if (errorMessage.includes('.clinerules')) {
            console.warn('Warning: Error related to .clinerules files:', initError);
            console.warn('Continuing with Memory Bank initialization despite .clinerules issues.');
            
            // Use the provided path directly as the memory bank directory
            const memoryBankDir = absolutePath;
            try {
              await FileUtils.ensureDirectory(memoryBankDir);
              memoryBankManager.setMemoryBankDir(memoryBankDir);
              
              return {
                content: [
                  {
                    type: 'text',
                    text: `Memory Bank initialized at ${memoryBankDir} (with warnings about .clinerules files)`,
                  },
                ],
              };
            } catch (dirError) {
              console.error('Failed to create memory-bank directory:', dirError);
              
              // Try to use an existing memory-bank directory if it exists
              if (await FileUtils.fileExists(memoryBankDir) && await FileUtils.isDirectory(memoryBankDir)) {
                memoryBankManager.setMemoryBankDir(memoryBankDir);
                
                return {
                  content: [
                    {
                      type: 'text',
                      text: `Memory Bank initialized at ${memoryBankDir} (with warnings)`,
                    },
                  ],
                };
              }
              
              // If we can't create or find a memory-bank directory, return an error
              return {
                content: [
                  {
                    type: 'text',
                    text: `Failed to initialize Memory Bank: ${dirError}`,
                  },
                ],
              };
            }
          }
          
          // For other errors, return the error message
          return {
            content: [
              {
                type: 'text',
                text: `Failed to initialize Memory Bank: ${initError}`,
              },
            ],
          };
        }
      } catch (error) {
        return {
          content: [
            {
              type: 'text',
              text: `Error initializing Memory Bank: ${error}`,
            },
          ],
        };
      }
    }
  • The tool schema definition including name, description, and input schema for 'path' parameter.
    {
      name: 'initialize_memory_bank',
      description: 'Initialize a Memory Bank in the specified directory',
      inputSchema: {
        type: 'object',
        properties: {
          path: {
            type: 'string',
            description: 'Path where the Memory Bank will be initialized',
          },
        },
        required: ['path'],
      },
    },
  • Registration of the tool handler in the MCP server's CallToolRequestSchema switch statement, dispatching to handleInitializeMemoryBank.
    case 'initialize_memory_bank': {
      const { path: dirPath } = request.params.arguments as { path: string };
      if (!dirPath) {
        throw new McpError(ErrorCode.InvalidParams, 'Path not specified');
      }
      console.error('Initializing Memory Bank at path:', dirPath);
      return handleInitializeMemoryBank(memoryBankManager, dirPath);
    }
  • Includes the coreTools (containing initialize_memory_bank schema) in the list of available tools for ListToolsRequest.
    server.setRequestHandler(ListToolsRequestSchema, async () => ({
      tools: [
        ...coreTools,
        ...progressTools,
        ...contextTools,
        ...decisionTools,
        ...modeTools,
      ],
    }));
  • Core helper method in MemoryBankManager called by the handler to perform the actual Memory Bank initialization (create directory if needed, populate core template files).
    async initialize(createIfNotExists: boolean = true): Promise<string> {
      try {
        // Determine the Memory Bank path
        let memoryBankPath: string;
        
        if (this.isRemote) {
          // For remote: use folderName directly under remote path (don't need to append to remotePath)
          memoryBankPath = this.folderName;
          logger.debug('MemoryBankManager', `Initializing remote Memory Bank with path: ${memoryBankPath}`);
        } else if (this.customPath) {
          // Use the custom path if set (for local filesystem)
          memoryBankPath = path.join(this.customPath, this.folderName);
        } else if (this.projectPath) {
          // Use the project path if set (for local filesystem)
          memoryBankPath = path.join(this.projectPath, this.folderName);
        } else {
          // Use the current directory as a fallback (for local filesystem)
          const currentDir = process?.cwd() || '.';
          memoryBankPath = path.join(currentDir, this.folderName);
        }
        
        // Create the Memory Bank directory if it doesn't exist
        if (createIfNotExists) {
          if (!this.fileSystem) {
            if (this.isRemote && this.remoteConfig) {
              // Create remote file system
              this.fileSystem = FileSystemFactory.createRemoteFileSystem(
                this.remoteConfig.remotePath,
                this.remoteConfig.sshKeyPath,
                this.remoteConfig.remoteUser,
                this.remoteConfig.remoteHost
              );
            } else if (this.projectPath) {
              // Create local file system
              this.fileSystem = FileSystemFactory.createLocalFileSystem(this.projectPath);
            } else {
              throw new Error('File system cannot be initialized');
            }
          }
          
          // Create the Memory Bank directory if it doesn't exist
          const exists = await this.fileSystem.fileExists(memoryBankPath);
          const isDir = exists ? await this.fileSystem.isDirectory(memoryBankPath) : false;
          
          if (!exists || !isDir) {
            logger.info('MemoryBankManager', `Creating Memory Bank directory at ${memoryBankPath}`);
            await this.fileSystem.ensureDirectory(memoryBankPath);
          }
          
          // Create core template files if they don't exist
          for (const template of coreTemplates) {
            const filePath = this.isRemote 
              ? `${memoryBankPath}/${template.name}` 
              : path.join(memoryBankPath, template.name);
            
            const fileExists = await this.fileSystem.fileExists(filePath);
            if (!fileExists) {
              logger.info('MemoryBankManager', `Creating ${template.name}`);
              await this.fileSystem.writeFile(filePath, template.content);
            }
          }
        } else {
          // Check if the Memory Bank directory exists
          if (!this.fileSystem) {
            throw new Error('File system not initialized');
          }
          
          const exists = await this.fileSystem.fileExists(memoryBankPath);
          const isDir = exists ? await this.fileSystem.isDirectory(memoryBankPath) : false;
          
          if (!exists || !isDir) {
            throw new Error(`Memory Bank directory not found at ${memoryBankPath}`);
          }
        }
        
        // Set the memory bank directory
        this.setMemoryBankDir(memoryBankPath);
        
        // Initialize the progress tracker - ensure memoryBankPath is not null
        if (memoryBankPath) {
          this.progressTracker = new ProgressTracker(memoryBankPath, this.userId || undefined);
        }
        
        // Welcome message
        logger.info('MemoryBankManager', `Memory Bank initialized at ${memoryBankPath}`);
        
        return memoryBankPath;
      } catch (error) {
        logger.error('MemoryBankManager', `Failed to initialize Memory Bank: ${error}`);
        throw new Error(`Failed to initialize Memory Bank: ${error instanceof Error ? error.message : String(error)}`);
      }
    }
  • Convenience helper method in MemoryBankManager that matches the tool name, wrapping setCustomPath and initialize.
    async initializeMemoryBank(dirPath: string): Promise<string> {
      try {
        // Set the custom path
        await this.setCustomPath(dirPath);
        
        // Initialize the Memory Bank
        return await this.initialize(true);
      } catch (error) {
        logger.error('MemoryBankManager', `Failed to initialize Memory Bank: ${error}`);
        throw new Error(`Failed to initialize Memory Bank: ${error instanceof Error ? error.message : String(error)}`);
      }
    }

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/aakarsh-sasi/memory-bank-mcp'

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