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

Schema Changelog

Changes observed during successful MCP inspections.

  1. First observedv1.0.0

TDQS

C2.9/5.0
Behavior2/5

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

With no annotations, the description must disclose side effects but only says 'Initialize a Memory Bank'. It does not mention what happens if the bank already exists, permissions needed, or any destructive potential.

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 a single, front-loaded sentence with no wasted words. It is concise, though very brief; it could expand slightly without losing conciseness.

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

Completeness3/5

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

For a simple tool with one parameter and no output schema, the description is minimally adequate. However, it lacks context about prerequisites or post-conditions, leaving some gaps for an agent.

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?

Schema coverage is 100% with a clear description for the 'path' parameter. The tool description adds no extra semantic value beyond what the schema already provides, resulting in a baseline score of 3.

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

Purpose4/5

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

The description clearly states the verb 'Initialize' and resource 'Memory Bank', with the specific directory. It is specific enough to distinguish from sibling tools like 'set_memory_bank_path' which implies an existing bank, but does not explicitly state this distinction.

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?

No guidance is provided on when to use this tool versus alternatives like 'set_memory_bank_path' or what prerequisites exist. The description gives no context about appropriate scenarios.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.