Labsco
mkreyman logo

MCP Memory Keeper

β˜… 128

from mkreyman

A server for persistent context management in Claude AI coding assistants, using a local SQLite database for storage.

πŸ”₯πŸ”₯πŸ”₯βœ“ VerifiedFreeAdvanced setup

MCP Memory Keeper - Claude Code Context Management

npm version npm downloads CI codecov License: MIT

A Model Context Protocol (MCP) server that provides persistent context management for Claude AI coding assistants. Never lose context during compaction again! This MCP server helps Claude Code maintain context across sessions, preserving your work history, decisions, and progress.

πŸš€ Practical Memory Keeper Workflow Example

Custom Command + CLAUDE.md = Automatic Context Management

CLAUDE.md (condensed example)

# Project Configuration

## Development Rules

- Always use memory-keeper to track progress
- Save architectural decisions and test results
- Create checkpoints before context limits

## Quality Standards

- All tests must pass before marking complete
- Document actual vs claimed results

Custom Command Example: /my-dev-workflow

# My Development Workflow

When working on the provided project:

- Use memory-keeper with channel: <project_name>
- Save progress at every major milestone
- Document all decisions with category: "decision"
- Track implementation status with category: "progress"
- Before claiming anything is complete, save test results

## Workflow Steps

1. Initialize session with project name as channel
2. Save findings during investigation
3. Create checkpoint before major changes
4. Document what actually works vs what should work

Usage Example

User: /my-dev-workflow authentication-service

AI: Setting up workflow for authentication-service.
[Uses memory-keeper with channel "authentication-service"]

[... AI works, automatically saving context ...]

User: "Getting close to context limit. Create checkpoint and give me a key"

AI: "Checkpoint created: authentication-service-checkpoint-20250126-143026"

[Continue working until context reset or compact manually]

User: "Restore from key: authentication-service-checkpoint-20250126-143026"

AI: "Restored! Continuing OAuth implementation. We completed the token validation, working on refresh logic..."

The Pattern:

  1. Custom command includes instructions to use memory-keeper
  2. AI follows those instructions automatically
  3. When you notice the conversation getting long, YOU ask Claude to save a checkpoint (like saving your game before a boss fight!)
  4. When Claude runs out of space and starts fresh, YOU tell it to restore using the checkpoint key

🎯 Key Feature: Memory Keeper is a shared board! You can:

  • Continue in the same session after reset
  • Start a completely new session and restore
  • Have multiple Claude sessions running in parallel, all sharing the same memory
  • One session can save context that another session retrieves

This enables powerful workflows like having one Claude session doing research while another implements code, both sharing discoveries through Memory Keeper!

Why MCP Memory Keeper?

Claude Code users often face context loss when the conversation window fills up. This MCP server solves that problem by providing a persistent memory layer for Claude AI. Whether you're working on complex refactoring, multi-file changes, or long debugging sessions, Memory Keeper ensures your Claude assistant remembers important context, decisions, and progress.

Perfect for:

  • Long coding sessions with Claude Code
  • Complex projects requiring context preservation
  • Teams using Claude AI for collaborative development
  • Developers who want persistent context across Claude sessions

Features

  • πŸ”„ Save and restore context between Claude Code sessions
  • πŸ“ File content caching with change detection
  • 🏷️ Organize context with categories and priorities
  • πŸ“Ί Channels - Persistent topic-based organization (auto-derived from git branch)
  • πŸ“Έ Checkpoint system for complete context snapshots
  • πŸ€– Smart compaction helper that never loses critical info
  • πŸ” Full-text search across all saved context
  • πŸ• Enhanced filtering - Time-based queries, regex patterns, pagination
  • πŸ“Š Change tracking - See what's been added, modified, or deleted since any point
  • πŸ’Ύ Export/import for backup and sharing
  • 🌿 Git integration with automatic context correlation
  • πŸ“Š AI-friendly summarization with priority awareness
  • πŸš€ Fast SQLite-based storage optimized for Claude
  • πŸ” Batch operations - Save, update, or delete multiple items atomically
  • πŸ”„ Channel reassignment - Move items between channels based on patterns
  • πŸ”— Context relationships - Link related items with typed relationships
  • πŸ‘οΈ Real-time monitoring - Watch for context changes with filters

High Priority Items

  • main_task: Refactor Settings.Context to use behaviors
  • critical_bug: Fix memory leak in subscription handler

Task

  • implement_auth: Add OAuth2 authentication flow
  • update_tests: Update test suite for new API

Decision

  • architecture_decision: Split settings into read/write modules
  • db_choice: Use PostgreSQL for better JSON support

### Batch Operations

Perform multiple operations atomically:

```javascript
// Save multiple items at once
mcp_context_batch_save({
  items: [
    { key: 'config_api_url', value: 'https://api.example.com', category: 'note' },
    { key: 'config_timeout', value: '30000', category: 'note' },
    { key: 'config_retries', value: '3', category: 'note' },
  ],
});

// Update multiple items
mcp_context_batch_update({
  updates: [
    { key: 'task_1', priority: 'high' },
    { key: 'task_2', priority: 'high' },
    { key: 'task_3', value: 'Updated task description' },
  ],
});

// Delete by pattern
mcp_context_batch_delete({
  keyPattern: 'temp_*',
  dryRun: true, // Preview first
});

Channel Management

Reorganize context items between channels:

// Move items to a new channel
mcp_context_reassign_channel({
  keyPattern: 'auth_*',
  toChannel: 'feature-authentication',
});

// Move from one channel to another
mcp_context_reassign_channel({
  fromChannel: 'sprint-14',
  toChannel: 'sprint-15',
  category: 'task',
  priorities: ['high'],
});

Context Relationships

Build a graph of related items:

// Link related items
mcp_context_link({
  sourceKey: 'epic_user_management',
  targetKey: 'task_create_user_api',
  relationship: 'contains',
});

// Find related items
mcp_context_get_related({
  key: 'epic_user_management',
  relationship: 'contains',
  depth: 2,
});

Real-time Monitoring

Watch for context changes:

// Create a watcher
const watcher = await mcp_context_watch({
  action: 'create',
  filters: {
    categories: ['task'],
    priorities: ['high'],
  },
});

// Poll for changes
const changes = await mcp_context_watch({
  action: 'poll',
  watcherId: watcher.watcherId,
});

Smart Compaction (Phase 3)

Never lose critical context when Claude's window fills up:

// Before context window fills
mcp_context_prepare_compaction();

// This automatically:
// - Creates a checkpoint
// - Identifies high-priority items
// - Captures unfinished tasks
// - Saves all decisions
// - Generates a summary
// - Prepares restoration instructions

Git Integration (Phase 3)

Track git changes in your project directory and save context with commits:

// First, set your project directory (if not done during session start)
mcp_context_set_project_dir({
  projectDir: '/path/to/your/project',
});

// Commit with auto-save
mcp_context_git_commit({
  message: 'feat: Add user authentication',
  autoSave: true, // Creates checkpoint with commit
});

// Context is automatically linked to the commit
// Note: If no project directory is set, you'll see a helpful message
// explaining how to enable git tracking for your project

Context Search (Phase 3)

Find anything in your saved context:

// Search in keys and values
mcp_context_search({ query: 'authentication' });

// Search only in keys
mcp_context_search({
  query: 'config',
  searchIn: ['key'],
});

// Search in specific session
mcp_context_search({
  query: 'bug',
  sessionId: 'session-id',
});

Export/Import (Phase 3)

Share context or backup your work:

// Export current session β€” writes into the exports directory
// (<DATA_DIR>/exports/, overridable via MEMORY_KEEPER_EXPORT_DIR)
mcp_context_export(); // Creates memory-keeper-export-xxx.json

// Export specific session
mcp_context_export({
  sessionId: 'session-id',
  format: 'json',
});

// Import from a file inside the exports directory.
// A bare filename resolves against that directory; the absolute path
// returned by context_export also works.
mcp_context_import({
  filePath: 'memory-keeper-export-xxx.json',
});

// Merge into current session
mcp_context_import({
  filePath: 'backup.json',
  merge: true,
});

Security note: For safety, context_import only reads files inside the server-owned exports directory (<DATA_DIR>/exports/, or MEMORY_KEEPER_EXPORT_DIR if set). Absolute paths outside that directory and ../ traversal are rejected, so the tool cannot be steered at arbitrary files on disk. Drop any file you want to import into that directory first. Point MEMORY_KEEPER_EXPORT_DIR at a dedicated directory β€” not at a home folder or a tree containing secrets β€” since any JSON file inside it becomes importable. (Prior to this change, exports were written to the OS temp directory; existing exports there must be moved into the exports directory to be re-imported.)

Knowledge Graph (Phase 4)

Automatically extract entities and relationships from your context:

// Analyze context to build knowledge graph
mcp_context_analyze();

// Or analyze specific categories
mcp_context_analyze({
  categories: ['task', 'decision'],
});

// Find related entities
mcp_context_find_related({
  key: 'AuthService',
  maxDepth: 2,
});

// Generate visualization data
mcp_context_visualize({
  type: 'graph',
});

// Timeline view
mcp_context_visualize({
  type: 'timeline',
});

// Category/priority heatmap
mcp_context_visualize({
  type: 'heatmap',
});

Semantic Search (Phase 4.2)

Find context using natural language queries:

// Search with natural language
mcp_context_semantic_search({
  query: 'how are we handling user authentication?',
  topK: 5,
});

// Find the most relevant security decisions
mcp_context_semantic_search({
  query: 'security concerns and decisions',
  minSimilarity: 0.5,
});

// Search with specific similarity threshold
mcp_context_semantic_search({
  query: 'database performance optimization',
  topK: 10,
  minSimilarity: 0.3,
});

Multi-Agent System (Phase 4.3)

Delegate complex analysis tasks to specialized agents:

// Analyze patterns in your context
mcp_context_delegate({
  taskType: 'analyze',
  input: {
    analysisType: 'patterns',
    categories: ['task', 'decision'],
  },
});

// Get comprehensive analysis
mcp_context_delegate({
  taskType: 'analyze',
  input: {
    analysisType: 'comprehensive',
  },
});

// Analyze relationships between entities
mcp_context_delegate({
  taskType: 'analyze',
  input: {
    analysisType: 'relationships',
    maxDepth: 3,
  },
});

// Create intelligent summaries
mcp_context_delegate({
  taskType: 'synthesize',
  input: {
    synthesisType: 'summary',
    maxLength: 1000,
  },
});

// Get actionable recommendations
mcp_context_delegate({
  taskType: 'synthesize',
  input: {
    synthesisType: 'recommendations',
    analysisResults: {}, // Can pass previous analysis results
  },
});

// Chain multiple agent tasks
mcp_context_delegate({
  chain: true,
  taskType: ['analyze', 'synthesize'],
  input: [{ analysisType: 'comprehensive' }, { synthesisType: 'recommendations' }],
});

Agent Types:

  • Analyzer Agent: Detects patterns, analyzes relationships, tracks trends
  • Synthesizer Agent: Creates summaries, merges insights, generates recommendations

Session Branching & Merging (Phase 4.4)

Explore alternatives without losing your original work:

// Create a branch to try something new
mcp_context_branch_session({
  branchName: 'experimental-refactor',
  copyDepth: 'shallow', // Only copy high-priority items
});

// Or create a full copy
mcp_context_branch_session({
  branchName: 'feature-complete-copy',
  copyDepth: 'deep', // Copy everything
});

// Later, merge changes back
mcp_context_merge_sessions({
  sourceSessionId: 'branch-session-id',
  conflictResolution: 'keep_newest', // or "keep_current", "keep_source"
});

Journal Entries (Phase 4.4)

Track your thoughts and progress with timestamped journal entries:

// Add a journal entry
mcp_context_journal_entry({
  entry: 'Completed the authentication module. Tests are passing!',
  tags: ['milestone', 'authentication'],
  mood: 'accomplished',
});

// Entries are included in timeline views
mcp_context_timeline({
  groupBy: 'day',
});

Timeline & Activity Tracking (Phase 4.4)

Visualize your work patterns over time:

// Get activity timeline
mcp_context_timeline({
  startDate: '2024-01-01',
  endDate: '2024-01-31',
  groupBy: 'day', // or "hour", "week"
});

// Enhanced timeline (NEW in v0.10.0)
mcp_context_timeline({
  groupBy: 'hour',
  includeItems: true, // Show actual items, not just counts
  categories: ['task', 'progress'], // Filter by categories
  relativeTime: true, // Show "2 hours ago" format
  itemsPerPeriod: 10, // Limit items shown per time period
});

// Shows:
// - Context items created per day/hour
// - Category distribution over time
// - Journal entries with moods and tags
// - Actual item details when includeItems: true

Progressive Compression (Phase 4.4)

Save space by intelligently compressing old context:

// Compress items older than 30 days
mcp_context_compress({
  olderThan: '2024-01-01',
  preserveCategories: ['decision', 'critical'], // Keep these
  targetSize: 1000, // Target size in KB (optional)
});

// Compression summary shows:
// - Items compressed
// - Space saved
// - Compression ratio
// - Categories affected

Cross-Tool Integration (Phase 4.4)

Track events from other MCP tools:

// Record events from other tools
mcp_context_integrate_tool({
  toolName: 'code-analyzer',
  eventType: 'security-scan-complete',
  data: {
    vulnerabilities: 0,
    filesScanned: 150,
    important: true, // Creates high-priority context item
  },
});

Documentation

Development

Running in Development Mode

# Install dependencies
npm install

# Run tests
npm test

# Run tests with coverage
npm run test:coverage

# Run with auto-reload
npm run dev

# Build for production
npm run build

# Start production server
npm start

Project Structure

mcp-memory-keeper/
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ index.ts           # Main MCP server implementation
β”‚   β”œβ”€β”€ utils/             # Utility modules
β”‚   β”‚   β”œβ”€β”€ database.ts    # Database management
β”‚   β”‚   β”œβ”€β”€ validation.ts  # Input validation
β”‚   β”‚   β”œβ”€β”€ git.ts         # Git operations
β”‚   β”‚   β”œβ”€β”€ knowledge-graph.ts # Knowledge graph management
β”‚   β”‚   β”œβ”€β”€ vector-store.ts    # Vector embeddings
β”‚   β”‚   └── agents.ts      # Multi-agent system
β”‚   └── __tests__/         # Test files
β”œβ”€β”€ dist/                  # Compiled JavaScript (generated)
β”œβ”€β”€ context.db             # SQLite database (auto-created)
β”œβ”€β”€ EXAMPLES.md            # Quick start examples
β”œβ”€β”€ TROUBLESHOOTING.md     # Common issues and solutions
β”œβ”€β”€ package.json           # Project configuration
β”œβ”€β”€ tsconfig.json          # TypeScript configuration
β”œβ”€β”€ jest.config.js         # Test configuration
└── README.md              # This file

Testing

The project includes comprehensive test coverage:

# Run all tests
npm test

# Run tests in watch mode
npm run test:watch

# Generate coverage report
npm run test:coverage

# Run specific test file
npm test -- summarization.test.ts

Test categories:

  • Unit Tests: Input validation, database operations, git integration
  • Integration Tests: Full tool workflows, error scenarios, edge cases
  • Coverage: 97%+ coverage on critical modules

Feature Status

FeatureMaturityVersionUse Case
Basic Save/Getβœ… Stablev0.1+Daily context management
Sessionsβœ… Stablev0.2+Multi-project work
File Cachingβœ… Stablev0.2+Track file changes
Checkpointsβœ… Stablev0.3+Context preservation
Smart Compactionβœ… Stablev0.3+Pre-compaction prep
Git Integrationβœ… Stablev0.3+Commit context tracking
Searchβœ… Stablev0.3+Find saved items
Export/Importβœ… Stablev0.3+Backup & sharing
Knowledge Graphβœ… Stablev0.5+Code relationship analysis
Visualizationβœ… Stablev0.5+Context exploration
Semantic Searchβœ… Stablev0.6+Natural language queries
Multi-Agentβœ… Stablev0.7+Intelligent processing

Current Features (v0.10.0)

  • βœ… Session Management: Create, list, and continue sessions with branching support
  • βœ… Channels: Persistent topic-based organization (auto-derived from git branch)
  • βœ… Context Storage: Save/retrieve context with categories (task, decision, progress, note) and priorities
  • βœ… Enhanced Filtering: Time-based queries, regex patterns, sorting, pagination
  • βœ… File Caching: Track file changes with SHA-256 hashing
  • βœ… Checkpoints: Create and restore complete context snapshots
  • βœ… Smart Compaction: Never lose critical context when hitting limits
  • βœ… Git Integration: Auto-save context on commits with branch tracking
  • βœ… Search: Full-text search across all saved context
  • βœ… Export/Import: Backup and share context as JSON
  • βœ… SQLite Storage: Persistent, reliable data storage with WAL mode
  • βœ… Knowledge Graph: Automatic entity and relationship extraction from context
  • βœ… Visualization: Generate graph, timeline, and heatmap data for context exploration
  • βœ… Semantic Search: Natural language search using lightweight vector embeddings
  • βœ… Multi-Agent System: Intelligent analysis with specialized analyzer and synthesizer agents
  • βœ… Session Branching: Create branches to explore alternatives without losing original context
  • βœ… Session Merging: Merge branches back with conflict resolution options
  • βœ… Journal Entries: Time-stamped entries with tags and mood tracking
  • βœ… Enhanced Timeline: Activity patterns with item details and relative time
  • βœ… Progressive Compression: Intelligently compress old context to save space
  • βœ… Cross-Tool Integration: Track events from other MCP tools

Roadmap

Phase 4: Advanced Features (In Development)

  • 🚧 Knowledge Graph: Entity-relation tracking for code understanding
  • 🚧 Vector Search: Semantic search using natural language
  • πŸ“‹ Multi-Agent Processing: Intelligent analysis and synthesis
  • πŸ“‹ Time-Aware Context: Timeline views and journal entries

Phase 5: Documentation & Polish

  • βœ… Examples: Comprehensive quick-start scenarios
  • βœ… Troubleshooting: Common issues and solutions
  • 🚧 Recipes: Common patterns and workflows
  • πŸ“‹ Video Tutorials: Visual guides for key features

Future Enhancements

  • Web UI for browsing context history
  • Multi-user/team collaboration features
  • Cloud sync and sharing
  • Integration with other AI assistants
  • Advanced analytics and insights
  • Custom context templates
  • Automatic retention policies

Upgrading

Database path change (v0.12.x+)

Prior to this release, the server resolved context.db relative to the process's current working directory. The database now lives at an absolute path:

  • Default: ~/mcp-data/memory-keeper/context.db
  • Custom: set DATA_DIR=/your/path β€” the server will use $DATA_DIR/context.db

If you have existing data in a context.db in your old working directory, move it to the new location before restarting the server:

mkdir -p ~/mcp-data/memory-keeper
cp /path/to/old/context.db ~/mcp-data/memory-keeper/context.db

If DATA_DIR is set, use that path as the destination instead of ~/mcp-data/memory-keeper/.

The server will print a warning to stderr if it detects a context.db in the current directory that differs from the configured data directory, including the exact cp command to run.

From-source install command change

If you registered memory-keeper using node dist/index.js directly, update your MCP config to use the bin wrapper instead:

# remove the old entry
claude mcp remove memory-keeper

# add the updated entry
claude mcp add memory-keeper /absolute/path/to/mcp-memory-keeper/bin/mcp-memory-keeper

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/AmazingFeature)
  3. Commit your changes (git commit -m 'Add some AmazingFeature')
  4. Push to the branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

License

This project is licensed under the MIT License - see the LICENSE file for details.

Author

Mark Kreyman

Acknowledgments

  • Built for the Claude Code community
  • Inspired by the need for better context management in AI coding sessions
  • Thanks to Anthropic for the MCP protocol

Support

If you encounter any issues or have questions:

Keywords

Claude Code context management, MCP server, Claude AI memory, persistent context, Model Context Protocol, Claude assistant memory, AI coding context, Claude Code MCP, context preservation, Claude AI tools