Skip to main content
Glama
hoppo-chan

Memory Bank MCP

by hoppo-chan

init-memory-bank

Set up a memory-bank directory and generate core files for structured project context tracking. Integrates existing project briefs and provides guidance for next steps. Uses a root directory path to initialize or overwrite files as needed.

Instructions

Initialize memory-bank directory and core files. This tool will:

  • Create memory-bank directory

  • Generate initial templates for 5 core files

  • Read and integrate projectBrief.md if it exists

  • Provide next steps guidance

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
forceNoForce re-initialization (will overwrite existing files)
rootPathYesProject root directory path Windows example: "C:/Users/name/project" macOS/Linux example: "/home/name/project"

Implementation Reference

  • The main execution logic of the init-memory-bank tool. Handles directory creation, template generation and file writing for the memory bank system.
      async ({ rootPath, force = false }) => {
        const normalizedPath = normalizePath(rootPath);
        const memoryBankPath = path.join(normalizedPath, "memory-bank");
    
        try {
          // Check if directory exists
          if (existsSync(memoryBankPath) && !force) {
            const files = await fs.readdir(memoryBankPath);
            if (files.length > 0) {
              return {
                content: [
                  {
                    type: "text",
                    text: `[MEMORY BANK: EXISTS]
    
    memory-bank directory already exists and contains files. To re-initialize, use force: true parameter.
    
    Existing files:
    ${files.map((f) => `- ${f}`).join("\n")}
    
    Suggestions:
    - Use get-memory-bank-info to read existing content
    - If you really need to re-initialize, set force: true`,
                  },
                ],
              };
            }
          }
    
          // Create directory
          await fs.mkdir(memoryBankPath, { recursive: true });
    
          // Check if projectBrief.md exists
          let projectBriefContent = "";
          const projectBriefPath = path.join(normalizedPath, "projectBrief.md");
          if (existsSync(projectBriefPath)) {
            try {
              projectBriefContent = await fs.readFile(projectBriefPath, "utf-8");
            } catch (err) {
              console.error("Failed to read projectBrief.md:", err);
            }
          }
    
          // Get templates
          const templates = getMemoryBankTemplates();
    
          // If projectBrief exists, update productContext.md template
          if (projectBriefContent) {
            templates["productContext.md"] = templates["productContext.md"].replace(
              "## Project Goal\n\n*   ",
              `## Project Goal\n\n*Based on projectBrief.md content:*\n\n${projectBriefContent}\n\n*Extract and define project goals from the above content:*\n\n*   `
            );
          }
    
          // Create all files
          const createdFiles: string[] = [];
          for (const [filename, content] of Object.entries(templates)) {
            const filePath = path.join(memoryBankPath, filename);
            await fs.writeFile(filePath, content, "utf-8");
            createdFiles.push(filename);
          }
    
          return {
            content: [
              {
                type: "text",
                text: `[MEMORY BANK: INITIALIZED]
    
    Memory Bank has been successfully initialized!
    
    Created files:
    ${createdFiles.map((f) => `- ${f}`).join("\n")}
    
    ${
      projectBriefContent
        ? "✓ Read projectBrief.md and integrated into productContext.md\n\n"
        : ""
    }
    
    [ATTENTION] Next steps to execute:
    1. Read and update each memory-bank/*.md file
    2. Fill in relevant content following the guidance in each file
    3. Do not use get-memory-bank-info before completing initial edits
    4. After completing edits, you can start using Memory Bank
    
    Important file descriptions:
    - productContext.md: Define project goals, features, and architecture
    - activeContext.md: Track current work status and focus
    - progress.md: Manage task progress
    - decisionLog.md: Record important decisions
    - systemPatterns.md: Document code patterns and standards
    
    Maintenance Tips:
    - Keep each file under 300 lines for optimal performance
    - Archive old content daily/weekly to memory-bank/archive/
    - Use update-memory-bank tool for detailed maintenance guidance
    - Check file sizes after each work session`,
              },
            ],
          };
        } catch (error) {
          return {
            content: [
              {
                type: "text",
                text: `Error initializing Memory Bank: ${
                  error instanceof Error ? error.message : String(error)
                }`,
              },
            ],
          };
        }
      }
  • Input schema validation using Zod for the tool parameters: rootPath (required string) and force (optional boolean).
    {
      rootPath: z.string().describe(
        `Project root directory path
        Windows example: "C:/Users/name/project" 
        macOS/Linux example: "/home/name/project"`
      ),
      force: z
        .boolean()
        .optional()
        .describe("Force re-initialization (will overwrite existing files)"),
    },
  • index.ts:556-688 (registration)
    The server.tool call that registers the 'init-memory-bank' tool with its name, description, input schema, and handler function.
    server.tool(
      "init-memory-bank",
      `Initialize memory-bank directory and core files.
      This tool will:
      - Create memory-bank directory
      - Generate initial templates for 5 core files
      - Read and integrate projectBrief.md if it exists
      - Provide next steps guidance`,
      {
        rootPath: z.string().describe(
          `Project root directory path
          Windows example: "C:/Users/name/project" 
          macOS/Linux example: "/home/name/project"`
        ),
        force: z
          .boolean()
          .optional()
          .describe("Force re-initialization (will overwrite existing files)"),
      },
      async ({ rootPath, force = false }) => {
        const normalizedPath = normalizePath(rootPath);
        const memoryBankPath = path.join(normalizedPath, "memory-bank");
    
        try {
          // Check if directory exists
          if (existsSync(memoryBankPath) && !force) {
            const files = await fs.readdir(memoryBankPath);
            if (files.length > 0) {
              return {
                content: [
                  {
                    type: "text",
                    text: `[MEMORY BANK: EXISTS]
    
    memory-bank directory already exists and contains files. To re-initialize, use force: true parameter.
    
    Existing files:
    ${files.map((f) => `- ${f}`).join("\n")}
    
    Suggestions:
    - Use get-memory-bank-info to read existing content
    - If you really need to re-initialize, set force: true`,
                  },
                ],
              };
            }
          }
    
          // Create directory
          await fs.mkdir(memoryBankPath, { recursive: true });
    
          // Check if projectBrief.md exists
          let projectBriefContent = "";
          const projectBriefPath = path.join(normalizedPath, "projectBrief.md");
          if (existsSync(projectBriefPath)) {
            try {
              projectBriefContent = await fs.readFile(projectBriefPath, "utf-8");
            } catch (err) {
              console.error("Failed to read projectBrief.md:", err);
            }
          }
    
          // Get templates
          const templates = getMemoryBankTemplates();
    
          // If projectBrief exists, update productContext.md template
          if (projectBriefContent) {
            templates["productContext.md"] = templates["productContext.md"].replace(
              "## Project Goal\n\n*   ",
              `## Project Goal\n\n*Based on projectBrief.md content:*\n\n${projectBriefContent}\n\n*Extract and define project goals from the above content:*\n\n*   `
            );
          }
    
          // Create all files
          const createdFiles: string[] = [];
          for (const [filename, content] of Object.entries(templates)) {
            const filePath = path.join(memoryBankPath, filename);
            await fs.writeFile(filePath, content, "utf-8");
            createdFiles.push(filename);
          }
    
          return {
            content: [
              {
                type: "text",
                text: `[MEMORY BANK: INITIALIZED]
    
    Memory Bank has been successfully initialized!
    
    Created files:
    ${createdFiles.map((f) => `- ${f}`).join("\n")}
    
    ${
      projectBriefContent
        ? "✓ Read projectBrief.md and integrated into productContext.md\n\n"
        : ""
    }
    
    [ATTENTION] Next steps to execute:
    1. Read and update each memory-bank/*.md file
    2. Fill in relevant content following the guidance in each file
    3. Do not use get-memory-bank-info before completing initial edits
    4. After completing edits, you can start using Memory Bank
    
    Important file descriptions:
    - productContext.md: Define project goals, features, and architecture
    - activeContext.md: Track current work status and focus
    - progress.md: Manage task progress
    - decisionLog.md: Record important decisions
    - systemPatterns.md: Document code patterns and standards
    
    Maintenance Tips:
    - Keep each file under 300 lines for optimal performance
    - Archive old content daily/weekly to memory-bank/archive/
    - Use update-memory-bank tool for detailed maintenance guidance
    - Check file sizes after each work session`,
              },
            ],
          };
        } catch (error) {
          return {
            content: [
              {
                type: "text",
                text: `Error initializing Memory Bank: ${
                  error instanceof Error ? error.message : String(error)
                }`,
              },
            ],
          };
        }
      }
    );
  • Supporting function that generates and returns the initial template strings for all five core memory-bank markdown files, including timestamps.
    // Memory Bank file template generation function
    function getMemoryBankTemplates(): Record<string, string> {
      const timestamp = formatTimestamp();
    
      return {
        "productContext.md": `# Product Context
    
    This file provides a high-level overview of the project and the expected product that will be created. Initially it is based upon projectBrief.md (if provided) and all other available project-related information in the working directory. This file is intended to be updated as the project evolves, and should be used to inform all other modes of the project's goals and context.
    ${timestamp} - Log of updates made will be appended as footnotes to the end of this file.
    
    *
    
    ## Project Goal
    
    *   
    
    ## Key Features
    
    *   
    
    ## Overall Architecture
    
    *   `,
    
        "activeContext.md": `# Active Context
    
    This file tracks the project's current status, including recent changes, current goals, and open questions.
    ${timestamp} - Log of updates made.
    
    *
    
    ## Current Focus
    
    *   
    
    ## Recent Changes
    
    *   
    
    ## Open Questions/Issues
    
    *   `,
    
        "progress.md": `# Progress
    
    This file tracks the project's progress using a task list format.
    ${timestamp} - Log of updates made.
    
    *
    
    ## Completed Tasks
    
    *   
    
    ## Current Tasks
    
    *   
    
    ## Next Steps
    
    *   `,
    
        "decisionLog.md": `# Decision Log
    
    This file records architectural and implementation decisions using a list format.
    ${timestamp} - Log of updates made.
    
    *
    
    ## Decision
    
    *
    
    ## Rationale 
    
    *
    
    ## Implementation Details
    
    *   `,
    
        "systemPatterns.md": `# System Patterns *Optional*
    
    This file documents recurring patterns and standards used in the project.
    It is optional, but recommended to be updated as the project evolves.
    ${timestamp} - Log of updates made.
    
    *
    
    ## Coding Patterns
    
    *   
    
    ## Architectural Patterns
    
    *   
    
    ## Testing Patterns
    
    *   `,
      };
    }
Behavior4/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It clearly describes what the tool does (creates directory, generates files, reads projectBrief.md, provides guidance) and hints at overwriting behavior via the 'force' parameter. However, it does not cover potential side effects like file permissions, error handling, or specific output formats, leaving some behavioral aspects unspecified.

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

Conciseness5/5

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

The description is appropriately sized and front-loaded, starting with a clear purpose statement followed by a bulleted list of specific actions. Each sentence earns its place by adding value (e.g., detailing core file creation and projectBrief.md integration) without redundancy or unnecessary elaboration.

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

Completeness4/5

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

Given the tool's complexity (initialization with file operations), no annotations, and no output schema, the description is mostly complete. It covers key actions and parameters but lacks details on output (e.g., what 'next steps guidance' entails) and error scenarios. For a tool with 2 parameters and moderate complexity, it provides sufficient context but could be more thorough about behavioral outcomes.

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 description coverage is 100%, so the schema already documents both parameters ('force' and 'rootPath') with descriptions. The description does not add any additional meaning or context beyond what the schema provides, such as explaining how 'rootPath' interacts with the initialization process or default behaviors. Baseline 3 is appropriate as the schema handles parameter documentation adequately.

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

Purpose5/5

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

The description clearly states the tool's purpose with specific verbs ('Initialize', 'Create', 'Generate', 'Read and integrate', 'Provide') and resources ('memory-bank directory', 'core files', 'projectBrief.md', 'next steps guidance'). It distinguishes from siblings like 'get-memory-bank-info' (which likely reads) and 'update-memory-bank' (which likely modifies) by focusing on initial setup.

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

Usage Guidelines4/5

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

The description implies usage context (e.g., for initial setup of a memory bank) and mentions reading 'projectBrief.md if it exists', suggesting it's for new or existing projects. However, it lacks explicit guidance on when to use this tool versus alternatives like 'update-memory-bank' or 'get-memory-bank-info', and does not specify prerequisites or exclusions.

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/hoppo-chan/memory-bank-mcp'

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