MCP (Model Context Protocol) server for semantic code indexing. Enables AI agents like Claude, Copilot, Cursor, and others to maintain a "persistent memory" of entire codebases through vector embeddings and semantic search.
Memory Bank is an external memory system for code agents that solves the fundamental problem of context loss in AIs. It works as the project's "external brain":
- Indexes all your code using OpenAI embeddings
- Chunks intelligently using AST parsing (functions, classes, methods)
- Stores vectors in LanceDB for ultra-fast searches
- Searches semantically: ask in natural language, get relevant code
- Updates incrementally: only reindexes modified files
- Multi-project: query code from any indexed project from any workspace
Without Memory Bank, AIs:
- β Forget everything between sessions
- β Only see small code snippets
- β Hallucinate non-existent implementations
- β Give generic answers without context
With Memory Bank, AIs:
- β Remember the entire codebase
- β Understand architecture and patterns
- β Respond with real project code
- β Generate code consistent with your style
- β Query multiple indexed projects simultaneously
- π Semantic Search: Ask "how does authentication work?" and get relevant code
- π§© Intelligent Chunking: AST parsing for TS/JS/Python with token limits (8192 max)
- β‘ Incremental Updates: Only reindexes modified files (hash-based detection)
- πΎ Embedding Cache: Avoids regenerating embeddings unnecessarily
- π― Advanced Filters: By file, language, chunk type
- π Detailed Statistics: Know the state of your index at all times
- π Privacy: Local vector store, respects .gitignore and .memoryignore
- π Multi-Project: Query any indexed project using its
projectId
- π Automatic Documentation: Generates 6 structured markdown documents about the project
- π§ AI with Reasoning: Uses OpenAI Responses API with reasoning models (gpt-5-mini)
- π Smart Updates: Only regenerates documents affected by changes
- π Global Context: Complements precise search with high-level vision
- π Quick Initialization: Creates Memory Bank structure with initial templates (no AI)
- π Session Tracking: Records active context, recent changes, and next steps
- π Decision Log: Documents technical decisions with rationale and alternatives
- π Progress Tracking: Manages tasks, milestones, and blockers
- π‘ MCP Resources: Direct read-only access to documents via URIs
- Node.js >= 18.0.0
- OpenAI API Key: Get one here
- Disk space: ~10MB per 10,000 files (embeddings + metadata)
The easiest way to use Memory Bank MCP without local installation:
npx @grec0/memory-bank-mcp@latestFor development or contribution:
# Clone repository
git clone https://github.com/gcorroto/memory-bank-mcp.git
cd memory-bank-mcp
# Install dependencies
npm install
# Build
npm run build
# Run
npm run startMemory Bank is configured through environment variables. You can set them in your MCP client or in a .env file:
| Variable | Description |
|---|---|
OPENAI_API_KEY |
REQUIRED. Your OpenAI API key |
| Variable | Default | Description |
|---|---|---|
MEMORYBANK_STORAGE_PATH |
.memorybank |
Directory where the vector index is stored |
MEMORYBANK_WORKSPACE_ROOT |
process.cwd() |
Workspace root (usually auto-detected) |
MEMORYBANK_EMBEDDING_MODEL |
text-embedding-3-small |
OpenAI embedding model |
MEMORYBANK_EMBEDDING_DIMENSIONS |
1536 |
Vector dimensions (1536 or 512) |
MEMORYBANK_MAX_TOKENS |
7500 |
Maximum tokens per chunk (limit: 8192) |
MEMORYBANK_CHUNK_OVERLAP_TOKENS |
200 |
Overlap between chunks to maintain context |
| Variable | Default | Description |
|---|---|---|
MEMORYBANK_REASONING_MODEL |
gpt-5-mini |
Model for generating documentation (supports reasoning) |
MEMORYBANK_REASONING_EFFORT |
medium |
Reasoning level: low, medium, high |
MEMORYBANK_AUTO_UPDATE_DOCS |
false |
Auto-regenerate docs when indexing code |
Edit your MCP configuration file:
Windows: %APPDATA%\Cursor\User\globalStorage\saoudrizwan.claude-dev\settings\cline_mcp_settings.json
{
"mcpServers": {
"memory-bank-mcp": {
"type": "stdio",
"command": "npx",
"args": ["@grec0/memory-bank-mcp@latest"],
"env": {
"OPENAI_API_KEY": "sk-your-api-key-here"
}
}
}
}{
"mcpServers": {
"memory-bank-mcp": {
"type": "stdio",
"command": "npx",
"args": ["@grec0/memory-bank-mcp@latest"],
"env": {
"OPENAI_API_KEY": "sk-your-api-key-here",
"MEMORYBANK_REASONING_MODEL": "gpt-5-mini",
"MEMORYBANK_REASONING_EFFORT": "medium",
"MEMORYBANK_AUTO_UPDATE_DOCS": "false",
"MEMORYBANK_MAX_TOKENS": "7500",
"MEMORYBANK_CHUNK_OVERLAP_TOKENS": "200",
"MEMORYBANK_EMBEDDING_MODEL": "text-embedding-3-small",
"MEMORYBANK_EMBEDDING_DIMENSIONS": "1536"
}
}
}
}Windows: %APPDATA%\Claude\claude_desktop_config.json
macOS: ~/Library/Application Support/Claude/claude_desktop_config.json
Linux: ~/.config/claude/claude_desktop_config.json
{
"mcpServers": {
"memory-bank": {
"command": "npx",
"args": ["@grec0/memory-bank-mcp@latest"],
"env": {
"OPENAI_API_KEY": "sk-your-api-key-here",
"MEMORYBANK_REASONING_MODEL": "gpt-5-mini",
"MEMORYBANK_REASONING_EFFORT": "medium"
}
}
}
}{
"mcpServers": {
"memory-bank": {
"command": "node",
"args": ["/absolute/path/memory-bank-mcp/dist/index.js"],
"cwd": "/absolute/path/memory-bank-mcp",
"env": {
"OPENAI_API_KEY": "sk-your-api-key-here"
}
}
}
}Memory Bank includes an intelligent documentation system that generates and maintains structured knowledge about your project using AI with reasoning capabilities.
- Code Analysis: The system analyzes indexed code using semantic search
- AI Generation: Uses reasoning models (gpt-5-mini) to generate structured documentation
- Incremental Updates: Only regenerates documents affected by significant changes
- Persistent Storage: Documents are saved in
.memorybank/projects/{projectId}/docs/
The system generates 6 markdown documents that provide different perspectives of the project:
| Document | Purpose | Content |
|---|---|---|
projectBrief.md |
General Description | What the project is, its main purpose, key features |
productContext.md |
Business Perspective | Why it exists, problems it solves, target users, UX |
systemPatterns.md |
Architecture and Patterns | Code structure, design patterns, technical decisions |
techContext.md |
Tech Stack | Technologies, dependencies, configurations, integrations |
activeContext.md |
Current State | What's being worked on, recent changes, next steps |
progress.md |
Tracking | Change history, what works, what's missing, known issues |
Generates or regenerates project documentation.
{
"projectId": "my-project",
"force": false
}projectId(REQUIRED): Project IDforce(optional):trueto regenerate everything,falsefor incremental updates
Reads generated documentation.
// Get summary of all documents
{
"projectId": "my-project",
"document": "summary"
}
// Get specific document
{
"projectId": "my-project",
"document": "systemPatterns"
}
// Get all complete documents
{
"projectId": "my-project",
"document": "all",
"format": "full"
}1. Index code
memorybank_index_code({ projectId: "my-project" })
2. Generate documentation
memorybank_generate_project_docs({ projectId: "my-project" })
3. Query documentation at the start of each session
memorybank_get_project_docs({ projectId: "my-project", document: "activeContext" })
4. Search specific code
memorybank_search({ projectId: "my-project", query: "..." })
If you configure MEMORYBANK_AUTO_UPDATE_DOCS=true, documents will be automatically regenerated after each indexing. This is useful for keeping documentation always up to date but consumes more API tokens.
A powerful feature of Memory Bank is the ability to query any indexed project from any workspace.
All indexed projects are stored in a shared vector store, identified by their projectId. This means:
- You can work on Project A and query code from Project B
- Agents can learn from similar already-indexed projects
- Reuse patterns from other projects in your organization
# You're working on "frontend-app" but need to see how something was done in "backend-api"
User: How was authentication implemented in the backend-api project?
Agent: [executes memorybank_search({
projectId: "backend-api", // Another project
query: "JWT middleware authentication"
})]
Found the implementation in backend-api:
- The auth middleware is in src/middleware/auth.ts
- Uses JWT with refresh tokens
- Validation is done with jsonwebtoken...
- The project must be previously indexed with its
projectId - Use the correct projectId when making queries
- Documentation is independent per project
// Project 1: a2a_gateway (already indexed)
memorybank_search({
"projectId": "a2a_gateway",
"query": "how agents are registered"
})
// Project 2: GREC0AI (current workspace)
memorybank_search({
"projectId": "GREC0AI",
"query": "AgentEntity implementation"
})
// You can query both in the same session!
β οΈ IMPORTANT: All tools require mandatoryprojectId. This ID must match the one defined in yourAGENTS.mdfile.
Indexes code semantically to enable searches.
Parameters:
projectId(REQUIRED): Unique project identifierpath(optional): Relative or absolute path (default: workspace root)recursive(optional): Index subdirectories (default: true)forceReindex(optional): Force complete reindexing (default: false)
Example:
{
"projectId": "my-project",
"path": "src/auth",
"recursive": true
}Searches code by semantic similarity.
Parameters:
projectId(REQUIRED): Project identifier to search inquery(required): Natural language querytopK(optional): Number of results (default: 10)minScore(optional): Minimum score 0-1 (default: 0.4)filterByFile(optional): Filter by file patternfilterByLanguage(optional): Filter by language
Example:
{
"projectId": "my-project",
"query": "function that authenticates users with JWT",
"topK": 5,
"minScore": 0.8
}Reads file contents.
Parameters:
path(required): File pathstartLine(optional): Start lineendLine(optional): End line
Writes a file and automatically reindexes it.
Parameters:
projectId(REQUIRED): Project identifier for reindexingpath(required): File pathcontent(required): File contentautoReindex(optional): Auto-reindex (default: true)
Gets Memory Bank statistics.
Analyzes project indexing coverage.
Parameters:
projectId(REQUIRED): Project identifier to analyzepath(REQUIRED): Absolute workspace path to analyze
Example:
{
"projectId": "my-project",
"path": "C:/workspaces/my-project"
}Generates structured project documentation using AI with reasoning.
Parameters:
projectId(REQUIRED): Project identifierforce(optional): Force regeneration (default: false)
Reads AI-generated project documentation.
Parameters:
projectId(REQUIRED): Project identifierdocument(optional):"summary","all", or specific name (projectBrief,systemPatterns, etc.)format(optional):"full"or"summary"(default: "full")
These tools allow managing project context manually, complementing automatic AI generation.
Initializes Memory Bank for a new project. Creates directory structure and 7 markdown documents with initial templates. Does not use AI.
Parameters:
projectId(REQUIRED): Unique project identifierprojectPath(REQUIRED): Absolute project pathprojectName(optional): Human-readable project namedescription(optional): Initial project description
Example:
{
"projectId": "my-project",
"projectPath": "C:/workspaces/my-project",
"projectName": "My Awesome Project",
"description": "A web application for..."
}Created documents:
projectBrief.md- General descriptionproductContext.md- Product contextsystemPatterns.md- Architecture patternstechContext.md- Tech stackactiveContext.md- Session contextprogress.md- Progress trackingdecisionLog.md- Decision log
Updates active context with current session information. Maintains history of the last 10 sessions. Does not use AI.
Parameters:
projectId(REQUIRED): Project identifiercurrentSession(optional): Session information (date, mode, task)recentChanges(optional): List of recent changesopenQuestions(optional): Pending questionsnextSteps(optional): Planned next stepsnotes(optional): Additional notes
Example:
{
"projectId": "my-project",
"currentSession": {
"mode": "development",
"task": "Implementing authentication"
},
"recentChanges": ["Added JWT middleware", "Created user model"],
"nextSteps": ["Add refresh token", "Create login endpoint"]
}Records technical decisions with rationale in the decision log. Does not use AI.
Parameters:
projectId(REQUIRED): Project identifierdecision(REQUIRED): Object with decision informationtitle(REQUIRED): Decision titledescription(REQUIRED): What was decidedrationale(REQUIRED): Why this decision was madealternatives(optional): Considered alternativesimpact(optional): Expected impactcategory(optional): architecture, technology, dependencies, etc.
Example:
{
"projectId": "my-project",
"decision": {
"title": "JWT Authentication",
"description": "Use JWT tokens for API authentication",
"rationale": "Stateless, scalable, works well with microservices",
"alternatives": ["Session-based auth", "OAuth only"],
"category": "architecture"
}
}Updates progress tracking with tasks, milestones, and blockers. Does not use AI.
Parameters:
projectId(REQUIRED): Project identifierprogress(optional): Tasks to updatecompleted: Completed tasksinProgress: Tasks in progressblocked: Blocked tasksupcoming: Upcoming tasks
milestone(optional): Milestone to add/update (name, status, targetDate, notes)blockers(optional): List of blockers with severity (low/medium/high)phase(optional): Current project phasephaseStatus(optional): Phase status
Example:
{
"projectId": "my-project",
"progress": {
"completed": ["Setup project structure", "Configure ESLint"],
"inProgress": ["Implement user authentication"],
"upcoming": ["Add unit tests"]
},
"milestone": {
"name": "MVP",
"status": "in_progress",
"targetDate": "2026-02-01"
}
}Memory Bank exposes MCP resources for direct read-only access to project documents.
| Resource URI | Content |
|---|---|
memory://{projectId}/active |
Active session context |
memory://{projectId}/progress |
Progress tracking |
memory://{projectId}/decisions |
Technical decision log |
memory://{projectId}/context |
Project context (brief + tech) |
memory://{projectId}/patterns |
System patterns |
memory://{projectId}/brief |
Project description |
Usage example:
// Access active context for "my-project"
memory://my-project/active
// Access decision log
memory://my-project/decisions
Resources are read-only. To modify documents, use the corresponding tools (memorybank_update_context, memorybank_record_decision, etc.).
Memory Bank includes instruction templates in two formats to configure agent behavior:
- AGENTS.md - Standard agents.md (compatible with Claude, Cursor, multiple agents)
- VSCode/Copilot -
.github/copilot-instructions.mdformat for GitHub Copilot in VS Code
| Mode | File | Ideal Use |
|---|---|---|
| Basic | AGENTS.basic.md |
Total control, manual indexing |
| Auto-Index | AGENTS.auto-index.md |
Active development, automatic sync |
| Sandboxed | AGENTS.sandboxed.md |
Environments without direct file access |
For projects where you want total control.
- β Agent ALWAYS consults Memory Bank before acting
- β Only indexes when user explicitly requests
- β Asks permission before modifying code
- β Suggests reindexing after changes
Ideal for: Critical projects, code review, onboarding.
For active development with automatic synchronization.
- β Agent consults Memory Bank automatically
- β Reindexes EVERY file after modifying it
- β Keeps Memory Bank always up to date
- β Can read/write files directly
Ideal for: Active development, rapid iteration, teams.
For environments without direct file system access.
- β Does NOT have direct file access
- β
MUST use
memorybank_read_fileto read - β
MUST use
memorybank_write_fileto write - β Auto-reindexes automatically on each write
Ideal for: Restricted environments, remote development, security.
All templates are available in the GitHub repository:
| Mode | URL |
|---|---|
| Basic | AGENTS.basic.md |
| Auto-Index | AGENTS.auto-index.md |
| Sandboxed | AGENTS.sandboxed.md |
Installation:
# Download template (choose one)
curl -o AGENTS.md https://raw.githubusercontent.com/gcorroto/memory-bank-mcp/main/templates/AGENTS.basic.md
# Or
curl -o AGENTS.md https://raw.githubusercontent.com/gcorroto/memory-bank-mcp/main/templates/AGENTS.auto-index.md
# Or
curl -o AGENTS.md https://raw.githubusercontent.com/gcorroto/memory-bank-mcp/main/templates/AGENTS.sandboxed.md
# Edit placeholders:
# - Replace {{PROJECT_ID}} with your unique project ID
# - Replace {{WORKSPACE_PATH}} with the absolute workspace path| Mode | URL |
|---|---|
| Basic | copilot-instructions.basic.md |
| Auto-Index | copilot-instructions.auto-index.md |
| Sandboxed | copilot-instructions.sandboxed.md |
| Instructions | memory-bank.instructions.md |
Installation:
# Create .github folder if it doesn't exist
mkdir -p .github
# Download template (choose one)
curl -o .github/copilot-instructions.md https://raw.githubusercontent.com/gcorroto/memory-bank-mcp/main/templates/vscode/copilot-instructions.basic.md
# Or
curl -o .github/copilot-instructions.md https://raw.githubusercontent.com/gcorroto/memory-bank-mcp/main/templates/vscode/copilot-instructions.auto-index.md
# Or
curl -o .github/copilot-instructions.md https://raw.githubusercontent.com/gcorroto/memory-bank-mcp/main/templates/vscode/copilot-instructions.sandboxed.md
# Enable in VS Code settings.json:
# "github.copilot.chat.codeGeneration.useInstructionFiles": trueTo use the .instructions.md file that applies only to certain files:
# Create instructions folder
mkdir -p .github/instructions
# Download base instructions
curl -o .github/instructions/memory-bank.instructions.md https://raw.githubusercontent.com/gcorroto/memory-bank-mcp/main/templates/vscode/memory-bank.instructions.mdThis file includes applyTo: "**/*" which applies to all files, but you can modify it.
# AGENTS.md
## Project Configuration
- **Project ID**: `my-awesome-app`
- **Workspace**: `C:/workspaces/my-awesome-app`
## Memory Bank Instructions
### CRITICAL: Always Consult Before Acting
Before any action, call `memorybank_search` with projectId="my-awesome-app"
### Auto-Indexing Policy
AFTER every file modification:
memorybank_index_code({ projectId: "my-awesome-app", path: "<modified_file>" })
### Session Start
At the beginning of each session, get context:
memorybank_get_project_docs({ projectId: "my-awesome-app", document: "activeContext" })User: Hi, I want you to help me with my project. The projectId is "my-app"
Claude: [executes memorybank_get_stats]
I see there's no code indexed yet.
Would you like me to index the project so I can help you better?
User: Yes
Claude: [executes memorybank_index_code({ projectId: "my-app" })]
I've indexed 145 files (1,234 chunks) in 45 seconds.
How can I help you?
User: How does authentication work in this project?
Claude: [executes memorybank_search({ projectId: "my-app", query: "authentication login users" })]
Authentication is implemented in src/auth/authService.ts (lines 23-87):
[Found code]
The system uses JWT tokens with refresh token rotation.
Validation is done in the middleware src/middleware/auth.ts.
User: I'm working on "frontend-v2" but I want to see how pagination was done
in the "admin-dashboard" project
Claude: [executes memorybank_search({
projectId: "admin-dashboard",
query: "pagination table listing"
})]
In admin-dashboard, pagination was implemented like this...
[Shows code from the other project]
Would you like me to implement something similar in frontend-v2?
User: Generate project documentation for new developers
Claude: [executes memorybank_generate_project_docs({ projectId: "my-app" })]
I've generated 6 project knowledge documents:
- projectBrief.md: General description
- systemPatterns.md: Architecture and patterns
- techContext.md: Tech stack
...
You can query them anytime with memorybank_get_project_docs
Similar to .gitignore, specifies patterns to exclude from indexing:
# Dependencies
node_modules/
vendor/
# Build outputs
dist/
build/
*.min.js
# Memory Bank storage
.memorybank/
# Large data files
*.csv
*.log
*.db
# Binary and media
*.exe
*.pdf
*.jpg
*.png
*.mp4Memory Bank automatically respects .gitignore patterns in your project, in addition to .memoryignore patterns.
Memory Bank uses text-embedding-3-small which is very economical:
- Embedding price: ~$0.00002 per 1K tokens
- Example: 10,000 files Γ 1,000 average tokens = ~$0.20
- Cache: Embeddings are cached, only regenerated if code changes
- Incremental: Only modified files are reindexed
Searches are extremely cheap (only 1 embedding per query).
AI Documentation uses reasoning models which are more expensive but only run when explicitly requested.
# Run tests
npm test
# Tests with coverage
npm test -- --coverage- β Local vector store: LanceDB runs on your machine
- β No telemetry: We don't send data to external servers
- β Embeddings only: OpenAI only sees code text, not sensitive metadata
- β Respects .gitignore: Ignored files are not indexed
- β Secure API key: Read from environment variables, never hardcoded
- Don't push
.memorybank/to git (already in .gitignore) - Use
.memoryignoreto exclude sensitive files - API keys in environment variables, never in code
- Verify
.envis in .gitignore
Solution: Configure your API key in the MCP environment variables.
Possible causes:
- Directory is empty
- All files are in .gitignore/.memoryignore
- No recognized code files
Solutions:
- Increase
minScore: Use 0.8 or 0.9 for more precise results - Use filters:
filterByFileorfilterByLanguage - Rephrase query: Be more specific and descriptive
- Reindex:
memorybank_index_code({ path: "..." })(automatically detects changes by hash)
Solution: All tools require projectId. Define projectId in your AGENTS.md file so the agent uses it consistently.
memorybank_get_stats({})If pendingFiles shows pending files, reindex the directory:
{
"projectId": "my-project",
"path": "C:/workspaces/my-project/src"
}The system automatically detects changes by hash. Only use forceReindex: true if you need to regenerate embeddings even without changes.
AGENTS.md Format (multi-agent standard):
- AGENTS.basic.md - Basic mode (manual indexing)
- AGENTS.auto-index.md - Auto-index mode
- AGENTS.sandboxed.md - Sandboxed mode (no direct file access)
VS Code / Copilot Format:
- copilot-instructions.basic.md - Basic mode
- copilot-instructions.auto-index.md - Auto-index mode
- copilot-instructions.sandboxed.md - Sandboxed mode
- memory-bank.instructions.md - Conditional instructions
Contributions are welcome!
- Fork the project
- Create your feature branch (
git checkout -b feature/AmazingFeature) - Commit changes (
git commit -m 'Add some AmazingFeature') - Push to branch (
git push origin feature/AmazingFeature) - Open a Pull Request
This project combines the best concepts from two complementary approaches:
The vector indexing and semantic search system is inspired by how Cursor IDE handles code memory:
- Advanced Cursor: Use the Memory Bank - Eliminate hallucinations with persistent memory
- How Cursor Indexes Codebases Fast - Efficient indexing techniques
The Project Knowledge Layer system (structured markdown documents) is inspired by the Cline Memory Bank approach:
- Cline MCP Memory Bank - Reference Memory Bank implementation for Cline
- Cline Memory Bank Custom Instructions - Custom instructions for using Memory Bank
Documents from the Cline approach we adopted:
| Document | Purpose |
|---|---|
projectBrief.md |
Project requirements and scope |
productContext.md |
Purpose, target users, problems solved |
activeContext.md |
Current tasks, recent changes, next steps |
systemPatterns.md |
Architectural decisions, patterns, relationships |
techContext.md |
Tech stack, dependencies, configurations |
progress.md |
Milestones, overall status, known issues |
Memory Bank MCP merges both approaches:
- Semantic Search (Cursor-style): Vector embeddings + LanceDB to find relevant code instantly
- Structured Documentation (Cline-style): 6 AI-generated markdown documents providing global context
- Multi-Project: Unique capability to query multiple indexed projects from any workspace
This combination allows agents to have both precision (semantic search) and global understanding (structured documentation).
This project is licensed under the MIT License - see the LICENSE file for details.
- Issues: GitHub Issues
- Documentation: Project Wiki
- OpenAI API: Official Documentation
- LanceDB: Documentation
β If you find this project useful, consider giving it a star!
Made with β€οΈ for the AI coding assistants community