Doramagic Project Pack · Human Manual
memory-mcp
Memory MCP is a Model Context Protocol (MCP) server that provides persistent memory and knowledge graph capabilities for AI agents and applications. It exposes 213 tools across 58 categori...
Getting Started
Related topics: Architecture Overview, Development Guide
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Related Pages
Related topics: Architecture Overview, Development Guide
Getting Started
This guide provides everything you need to install, configure, and begin using the Enhanced Memory MCP server.
Overview
Memory MCP is a Model Context Protocol (MCP) server that provides persistent memory and knowledge graph capabilities for AI agents and applications. It exposes 213 tools across 58 categories for entity management, semantic search, hierarchy traversal, graph algorithms, and context compression. Sources: CLAUDE.md:1
The server acts as a bridge between AI applications and a knowledge graph storage layer, enabling:
- Persistent entity and relation storage
- Semantic and ranked search capabilities
- Time-based memory decay and importance scoring
- Context compression for large inputs
- Multi-format data import/export
Prerequisites
Before installing Memory MCP, ensure your environment meets these requirements:
| Requirement | Minimum Version | Notes |
|---|---|---|
| Node.js | 18.0+ | ES2022 features required |
| npm | 9.0+ | For package management |
| SQLite | 3.39+ | Only if using SQLite storage |
| TypeScript | 5.0+ | For development work |
Sources: CLAUDE.md:20
Installation
From npm (Recommended for Users)
npm install @danielsimonjr/memory-mcp
This installs the pre-built package with all dependencies. The core library @danielsimonjr/memoryjs is automatically included. Sources: CLAUDE.md:24
From Source (Recommended for Development)
# Clone the repository
git clone https://github.com/danielsimonjr/memory-mcp.git
cd memory-mcp
# Install dependencies
npm install
# Build the project
npm run build
The prepare script runs automatically on npm install, triggering the build process. Sources: CONTRIBUTING.md:1
Verify Installation
After installation, verify the CLI is available:
mcp-server-memory --help
Configuration
Environment Variables
Memory MCP supports several environment variables for configuration:
| Variable | Default | Description |
|---|---|---|
MEMORY_STORAGE_TYPE | jsonl | Storage backend: jsonl or sqlite |
MEMORY_DB_PATH | memory.db | Path to SQLite database (when using SQLite) |
MEMORY_JSONL_PATH | memory.jsonl | Path to JSONL file (when using JSONL) |
Sources: CLAUDE.md:14
Storage Options
Memory MCP supports two storage backends:
JSONL Storage (Default)
- Data stored in human-readable JSONL files
- Files:
memory.jsonl,memory-saved-searches.jsonl,memory-tag-aliases.jsonl - Location: Project root directory Sources: CLAUDE.md:14
SQLite Storage
- Set
MEMORY_STORAGE_TYPE=sqliteto enable - Uses
better-sqlite3for native performance - Single database file:
memory.dbSources: tools/migrate-from-jsonl-to-sqlite/migrate-from-jsonl-to-sqlite.ts:1
Architecture Overview
System Layers
graph TD
subgraph "memory-mcp (this repo)"
A["src/index.ts"] --> B["MCPServer.ts"]
B --> C["toolDefs.ts"]
C --> D["toolHandlers.ts"]
end
subgraph "@danielsimonjr/memoryjs (npm dependency)"
E["ManagerContext<br/>(lazy init)"] --> F["EntityManager"]
E --> G["RelationManager"]
E --> H["SearchManager"]
E --> I["IOManager"]
E --> J["GraphStorage / SQLiteStorage"]
end
D --> ESources: CLAUDE.md:4-13
Entry Points
| Entry Point | Purpose |
|---|---|
dist/index.js | Main build output |
mcp-server-memory | CLI binary (defined in package.json bin) |
src/index.ts | Source entry point |
Sources: CLAUDE.md:17
Manager Accessors
The ManagerContext provides access to all core managers:
| Accessor | Purpose |
|---|---|
ctx.entityManager | Core CRUD for graph nodes |
ctx.relationManager | Directed edges between entities |
ctx.observationManager | Facts attached to entities |
ctx.searchManager | Basic, ranked, boolean, fuzzy search |
ctx.semanticSearch | Embedding similarity via OpenAI or local models |
ctx.tagManager | Tag management with importance scores |
ctx.hierarchyManager | Parent-child trees, subtree traversal |
ctx.compressionManager | Duplicate detection, merge, archive |
ctx.graphTraversal | BFS/DFS path finding, centrality |
ctx.analyticsManager | Graph stats and integrity validation |
ctx.storage | Direct GraphStorage access |
Sources: CLAUDE.md:1
Tool Categories Overview
Memory MCP exposes tools organized into 58 categories with 213 total tools:
| Category | Count | Key Purpose |
|---|---|---|
| Entity | 4 | Core CRUD for graph nodes |
| Relation | 2 | Directed edges between entities |
| Observation | 3 | Facts attached to entities |
| Search | 7 | Basic, ranked, boolean, fuzzy |
| Semantic Search | 3 | Embedding similarity |
| Intelligent Search | 3 | Hybrid multi-layer, query analysis |
| Saved Searches | 5 | Store and re-execute queries |
| Tag Management | 6 | Tags, bulk ops, importance scores |
| Tag Aliases | 5 | Tag synonym/alias management |
| Hierarchy | 9 | Parent-child trees, subtree traversal |
| Graph Algorithms | 4 | BFS/DFS, centrality, connected components |
| Analytics | 2 | Graph stats and integrity validation |
| Compression | 4 | Dedup, merge, auto-compress, archive |
| Import/Export | 2 | 7 export formats |
| Decay & Salience | 3 | Time-based importance decay |
Sources: CLAUDE.md:3
Quick Start with MCP Client
Once Memory MCP is installed and configured, integrate it with your MCP-compatible client:
{
"mcpServers": {
"memory": {
"command": "mcp-server-memory",
"args": []
}
}
}
For SQLite storage:
{
"mcpServers": {
"memory": {
"command": "mcp-server-memory",
"env": {
"MEMORY_STORAGE_TYPE": "sqlite"
}
}
}
}
Basic Operations
Creating Entities
// Via tool handler (internal usage example)
await ctx.entityManager.createEntity({
name: "project_alpha",
entityType: "project",
observations: ["Initial setup complete"]
});
Searching
// Ranked search (TF-IDF)
const results = await ctx.searchManager.rankedSearch("query text");
// Semantic search
const semanticResults = await ctx.semanticSearch.query({
text: "query text",
limit: 10
});
Context Compression
const compressed = ctx.contextWindowManager.compressForContext(
largeText,
{ level: 'medium' }
);
Standalone Tools
The tools/ directory contains standalone utilities:
| Tool | Purpose |
|---|---|
chunking-for-files | Split/merge large files for context-limited editing |
compress-for-context | CTON compression for LLM context windows |
create-dependency-graph | Generate TypeScript project dependency graphs |
migrate-from-jsonl-to-sqlite | Convert between JSONL and SQLite formats |
Sources: CLAUDE.md:18
Each tool has its own package.json and can be built to Windows executables via pkg. Sources: CLAUDE.md:18
Development Setup
Cloning and Initial Setup
git clone https://github.com/danielsimonjr/memory-mcp.git
cd memory-mcp
npm install
Creating a Feature Branch
git checkout -b feature/your-feature-name
Development Workflow
# Make your changes
# Commit your changes
cd c:/mcp-servers/memory-mcp
git add .
git commit -m "Description of your changes"
# Push and create PR
git push origin feature/your-feature-name
Sources: CONTRIBUTING.md:1-7
Code Style Guidelines
- Follow TypeScript best practices
- Use meaningful variable names
- Add JSDoc comments for public methods
- Keep functions focused and small
- Maintain consistent indentation (2 spaces)
Sources: CONTRIBUTING.md:12-16
Testing
Test Requirements
When testing new features:
- Test new features thoroughly
- Include edge cases
- Test backward compatibility
- Verify export formats are valid
- Test with empty graphs and large graphs
Sources: CONTRIBUTING.md:18-22
Running Tests
npm test
Note: Test runs create/modify memory.jsonl, memory.db files in the project root. These are in .gitignore and won't appear in git status. Sources: CLAUDE.md:22
Building for Distribution
Package Structure
- Build output:
dist/index.js - CLI binary:
mcp-server-memory(defined in package.jsonbin) - Source entry:
src/index.ts - TypeScript target: ES2022 with Node16 module resolution
Sources: CLAUDE.md:17,23
Publishing to npm
# Set authentication token
npm config set //registry.npmjs.org/:_authToken=$(cat c:\mcp-servers\npm_key.txt)
# Publish with public access
npm publish --access public
The prepare script auto-builds, so separate npm run build is not needed before publish. Sources: CLAUDE.md:25
Verifying Package Contents
Before publishing:
npm pack --dry-run 2>&1 | grep -E "jsonl|\.db|total files|package size"
Sources: CLAUDE.md:25
Data Migration
JSONL to SQLite
npx tsx tools/migrate-from-jsonl-to-sqlite.ts \
--from memory.jsonl \
--to memory.db \
--verbose
Command Line Arguments
| Argument | Short | Description |
|---|---|---|
--from <path> | -f | Source file path (JSONL or SQLite) |
--to <path> | -t | Target file path (JSONL or SQLite) |
--verbose | -v | Show detailed progress |
--help | -h | Show help message |
Sources: tools/migrate-from-jsonl-to-sqlite/migrate-from-jsonl-to-sqlite.ts:1-30
Documentation
When adding features:
- Update README.md with new tools/functionality
- Add entries to CHANGELOG.md
- Update WORKFLOW.md if development process changes
- Include usage examples
Sources: CONTRIBUTING.md:28-32
Pull Request Process
- Title: Clear, descriptive summary
- Description: What changed, why it changed, how to test it
- Tests: Include test results
- Documentation: Update relevant docs
- Backward Compatibility: Confirm no breaking changes
Sources: CONTRIBUTING.md:37-44
Error Handling
Error handling in dispatch catches exceptions from handlers and returns them as MCP-formatted error responses. Check the MCP response isError field when debugging. Sources: CLAUDE.md:23
Next Steps
After setting up your environment:
- Explore the Tool Categories to understand available operations
- Review the Architecture Overview for system design
- Set up your preferred Storage Configuration
- Run the standalone Dependency Graph Tool to visualize project structure
- Consult the project's issues for feature requests or bug reports
Sources: CLAUDE.md:20
Project Structure
Related topics: Architecture Overview, Development Guide
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Related Pages
Related topics: Architecture Overview, Development Guide
Project Structure
Overview
The memory-mcp project implements a Model Context Protocol (MCP) server that provides a knowledge graph-based memory system for AI agents. The repository exposes over 200 tools across 58 categories, enabling persistent memory management with features including entity/relation CRUD, semantic search, bitemporal validity, and causal reasoning.
Repository Layout
memory-mcp/
├── src/ # Main TypeScript source code
│ ├── index.ts # Entry point and exports
│ └── server/
│ ├── MCPServer.ts # Core MCP server implementation
│ ├── toolDefinitions.ts # Tool schemas (input/output specifications)
│ └── toolHandlers.ts # Tool implementation handlers
├── tools/ # Standalone utility tools
│ ├── create-dependency-graph/ # TypeScript dependency analysis
│ ├── compress-for-context/ # LLM context window compression
│ ├── chunking-for-files/ # Large file splitting utilities
│ └── migrate-from-jsonl-to-sqlite/ # Storage format migration
├── dist/ # Build output (npm published)
├── docs/architecture/ # Generated documentation
├── memory.jsonl # JSONL storage (project root)
├── memory.db # SQLite storage (optional)
├── package.json # npm package configuration
└── CLAUDE.md # Developer documentation
Core Architecture
Layered Architecture
The project follows a layered architecture where memory-mcp acts as an MCP interface wrapper around the core @danielsimonjr/memoryjs library.
graph TD
subgraph "memory-mcp (this repo)"
A[src/index.ts] --> B[src/server/MCPServer.ts]
B --> C[src/server/toolDefs.ts]
B --> D[src/server/toolHandlers.ts]
end
subgraph "@danielsimonjr/memoryjs (npm dependency)"
E[ManagerContext] --> F[EntityManager]
E --> G[RelationManager]
E --> H[SearchManager]
E --> I[ObservationManager]
E --> J[TagManager]
E --> K[CompressionManager]
E --> L[GraphStorage]
E --> M[SQLiteStorage]
end
D --> E
C --> ESources: CLAUDE.md:layered-architecture
Accessor Hierarchy
The ManagerContext provides lazy-initialized accessors for all subsystems:
| Accessor | Purpose |
|---|---|
ctx.entityManager | Graph node CRUD operations |
ctx.relationManager | Directed edge management |
ctx.observationManager | Facts attached to entities |
ctx.searchManager | Basic, ranked, boolean, fuzzy search |
ctx.tagManager | Tag CRUD and bulk operations |
ctx.hierarchyManager | Parent-child tree structures |
ctx.analyticsManager | Graph statistics and validation |
ctx.compressionManager | Duplicate detection and merging |
ctx.archiveManager | Historical data archival |
ctx.ioManager | Import/export operations |
ctx.graphTraversal | BFS/DFS path finding |
ctx.semanticSearch | Embedding similarity search |
ctx.rankedSearch | TF-IDF ranking |
ctx.storage | Direct GraphStorage access |
Sources: CLAUDE.md:accessors
Source Code Organization
Entry Point (`src/index.ts`)
The main entry point handles:
- Package exports and re-exports
- Backward compatibility aliases (exports
ManagerContextasKnowledgeGraphManager) - Core type re-exports
MCP Server (`src/server/MCPServer.ts`)
The MCPServer class is responsible for:
- Initializing the ManagerContext with storage configuration
- Tool dispatch and request handling
- Error formatting and response generation
Key aspects:
- Error handling:
handleToolCallcatches exceptions from handlers and returns them as MCP-formatted error responses (checksisErrorfield in responses) - Storage initialization: Supports both JSONL and SQLite storage backends
- Tool registration: Dynamically registers tools from definitions
Sources: CLAUDE.md:entry-points, CLAUDE.md:error-handling
Tool Definitions (`src/server/toolDefinitions.ts`)
The tool definitions file contains JSON Schema specifications for all 213 tools. Tools are organized into categories:
| Category | Count | Description |
|---|---|---|
| Entity | 4 | Core CRUD for graph nodes |
| Relation | 2 | Directed edges between entities |
| Observation | 3 | Facts attached to entities |
| Search | 7 | Basic, ranked, boolean, fuzzy search |
| Intelligent Search | 3 | Hybrid multi-layer search |
| Semantic Search | 3 | Embedding-based similarity |
| Saved Searches | 5 | Stored query execution |
| Tag Management | 6 | Tag CRUD and bulk operations |
| Tag Aliases | 5 | Tag synonym management |
| Hierarchy | 9 | Tree structures and traversal |
| Graph Algorithms | 4 | Path finding, centrality |
| Analytics | 2 | Stats and validation |
| Compression | 4 | Duplicate detection, merge |
| Import/Export | 2+ | Multiple format support |
Sources: CLAUDE.md:tool-categories, src/server/toolDefinitions.ts
Tool Handlers (`src/server/toolHandlers.ts`)
Tool handlers implement the actual logic for each tool. Each handler:
- Validates input arguments using Zod schemas
- Accesses appropriate ManagerContext accessors
- Returns formatted responses
Example handler pattern:
tool_name: async (ctx, args) => {
// Input validation
const param = validateWithSchema(args.param, z.string(), 'Invalid param');
// Business logic via ManagerContext
const result = await getSomeManager(ctx).someOperation(param);
// Response formatting
return formatToolResponse(result);
}
Sources: src/server/toolHandlers.ts
Standalone Tools
The tools/ directory contains independent utilities, each with its own package.json and compilable to Windows executables via pkg:
create-dependency-graph
Analyzes TypeScript source files and generates dependency documentation.
| Output | Description |
|---|---|
docs/architecture/DEPENDENCY_GRAPH.md | Human-readable Markdown documentation |
docs/architecture/dependency-graph.json | Machine-readable JSON structure |
Features:
- Scans all TypeScript files in
src/ - Parses imports and exports
- Categorizes files into logical modules
- Detects circular dependencies
- Generates statistics
Usage:
npm run docs:deps
# or
npx tsx tools/create-dependency-graph.ts
Sources: tools/create-dependency-graph/README.md
compress-for-context
CTON (Context Token Optimization Notation) compression for reducing LLM context window usage.
| Option | Description |
|---|---|
-o, --output <file> | Output file path |
-f, --format <fmt> | Force format: json, yaml, markdown, csv, etc. |
-l, --level <lvl> | Compression level: light, medium, aggressive |
-b, --batch | Batch mode for multiple files |
-d, --decompress | Restore compressed file |
chunking-for-files
Splits large files into editable sections for context-limited editing.
Commands:
chunker split <file>- Split file into chunkschunker merge <manifest.json>- Merge chunks backchunker status <manifest.json>- Show chunk status
migrate-from-jsonl-to-sqlite
Converts between JSONL and SQLite storage formats using better-sqlite3.
migrate-from-jsonl-to-sqlite --from <source> --to <target> [--verbose]
Storage System
Data files reside in the project root (not dist/):
| Storage Type | File | Environment Variable |
|---|---|---|
| JSONL (default) | memory.jsonl, memory-saved-searches.jsonl, memory-tag-aliases.jsonl | MEMORY_STORAGE_TYPE=jsonl |
| SQLite | memory.db | MEMORY_STORAGE_TYPE=sqlite |
The memory.db and *.jsonl files are gitignored—they are created/modified at runtime but not tracked by version control.
Sources: CLAUDE.md:storage
Build and Publication
Build Output
| Artifact | Description |
|---|---|
dist/index.js | Main build output |
mcp-server-memory | CLI binary (package.json bin field) |
The TypeScript target is ES2022 with Node16 module resolution. The prepare script auto-runs npm run build on npm install, ensuring dist/ is always rebuilt.
Publishing to npm
# Token with "bypass 2FA" required
npm config set //registry.npmjs.org/:_authToken=$(cat ~/.npm_token)
npm publish --access public
The prepare script handles builds automatically, so separate npm run build is unnecessary before publishing.
Sources: CLAUDE.md:publishing-to-npm
Development Guidelines
Code Style
| Guideline | Standard |
|---|---|
| Language | TypeScript best practices |
| Indentation | 2 spaces |
| Documentation | JSDoc comments for public methods |
| Function design | Small, focused functions |
| Naming | Meaningful variable names |
Testing Requirements
When adding features:
- Test with empty graphs and large graphs
- Include edge cases
- Verify backward compatibility
- Ensure export formats are valid
Documentation Checklist
| File | When to Update |
|---|---|
README.md | New tools/functionality |
CHANGELOG.md | Version changes |
WORKFLOW.md | Development process changes |
File Naming Conventions
| Pattern | Example | Purpose |
|---|---|---|
*.ts | MCPServer.ts, toolHandlers.ts | TypeScript source files |
*.md | DEPENDENCY_GRAPH.md | Generated documentation |
*.json | dependency-graph.json | Machine-readable data |
*.compact | output.compact | Compressed files |
Summary
The memory-mcp project is structured as a thin MCP wrapper around the @danielsimonjr/memoryjs library. The core source in src/ contains only 5 TypeScript files, while the tools/ directory provides standalone utilities for dependency analysis, context compression, file chunking, and storage migration. The architecture prioritizes backward compatibility, lazy initialization of managers, and clean separation between tool definitions, handlers, and the underlying knowledge graph implementation.
Sources: CLAUDE.md:layered-architecture
Architecture Overview
Related topics: Storage Backends, Entity-Relation-Observation Model
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Related Pages
Related topics: Storage Backends, Entity-Relation-Observation Model
Architecture Overview
The memory-mcp project implements a Model Context Protocol (MCP) server that provides a persistent knowledge graph for AI agents. The system enables structured memory management with 213 tools across 58 categories, supporting entity management, relationships, observations, search, tagging, hierarchy traversal, analytics, and compression capabilities.
High-Level Architecture
The project follows a layered architecture that separates concerns between the MCP protocol interface, business logic, and storage implementation. The core knowledge graph functionality is delegated to the @danielsimonjr/memoryjs library (currently v2.1.0+), while memory-mcp serves as the protocol adapter and tool layer.
graph TD
subgraph "memory-mcp (This Repository)"
A["src/index.ts<br/>Entry Point"] --> B["MCPServer.ts<br/>Protocol Handler"]
B --> C["toolDefs.ts<br/>Tool Definitions"]
B --> D["toolHandlers.ts<br/>Tool Handlers"]
C --> D
end
subgraph "@danielsimonjr/memoryjs (npm Dependency)"
E["ManagerContext<br/>Lazy Initialization"]
E --> F["EntityManager"]
E --> G["RelationManager"]
E --> H["ObservationManager"]
E --> I["SearchManager"]
E --> J["TagManager"]
E --> K["HierarchyManager"]
E --> L["AnalyticsManager"]
E --> M["CompressionManager"]
E --> N["IOManager"]
end
D --> E
O["GraphStorage/SQLiteStorage"] --> E
style A fill:#e1f5fe
style E fill:#fff3e0Sources: CLAUDE.md:Layered Architecture
Core Components
Entry Point (src/index.ts)
The src/index.ts file serves as the primary entry point for the application. It exports the ManagerContext under an alias KnowledgeGraphManager for backward compatibility, along with all core types needed by consumers of the library.
The exports enable external consumers to:
- Import the main context manager class
- Access type definitions for entities, relations, observations, and search operations
- Use the manager without knowledge of internal implementation details
Sources: src/index.ts
MCPServer (src/server/MCPServer.ts)
The MCPServer class implements the Model Context Protocol server interface. It handles:
- Protocol message parsing and routing
- Tool registration and discovery
- Request/response lifecycle management
- Error handling and validation
The server initializes lazy-loaded managers through ManagerContext, ensuring resources are only allocated when actually needed.
Sources: src/server/MCPServer.ts
ManagerContext (memoryjs)
The ManagerContext provides access to all core managers through a unified interface. It implements lazy initialization to optimize startup time and resource usage.
| Manager | Purpose |
|---|---|
entityManager | Core CRUD operations for graph nodes |
relationManager | Directed edges between entities |
observationManager | Facts attached to entities with normalization |
searchManager | Basic, ranked, boolean, fuzzy, and auto-select search |
tagManager | Tag operations, bulk operations, importance scores |
hierarchyManager | Parent-child trees, subtree traversal |
analyticsManager | Graph statistics and integrity validation |
compressionManager | Duplicate detection, merge, auto-compress, archive |
archiveManager | Long-term storage management |
ioManager | Import/export operations |
graphTraversal | Graph algorithm utilities |
semanticSearch | Embedding-based similarity search |
rankedSearch | TF-IDF weighted search |
storage | Direct GraphStorage access for advanced use cases |
Sources: CLAUDE.md:Accessors
Tool System Architecture
Tool Definitions (src/server/toolDefs.ts)
Tool definitions describe the interface contract for each capability. Each definition includes:
- name: Unique identifier for the tool
- description: Human-readable explanation of functionality
- inputSchema: JSON Schema describing required and optional parameters
Tool Handlers (src/server/toolHandlers.ts)
Tool handlers implement the business logic for each tool. They receive the ManagerContext and validated arguments, then execute the appropriate manager operations.
Example handler pattern:
create_entity: async (ctx, args) => {
const name = validateWithSchema(args.name, z.string().min(1), 'Invalid name');
const entity = await ctx.entityManager.createEntity({ name, ... });
return formatToolResponse(entity);
}
Sources: src/server/toolHandlers.ts:tool pattern
Tool Categories
The system organizes its 213 tools into 58 categories:
| Category | Count | Key Purpose |
|---|---|---|
| Entity | 4 | Core CRUD for graph nodes |
| Relation | 2 | Directed edges between entities |
| Observation | 3 | Facts attached to entities, with normalization |
| Search | 7 | Basic, ranked, boolean, fuzzy, auto-select |
| Intelligent Search | 3 | Hybrid multi-layer, query analysis, reflection-based |
| Semantic Search | 3 | Embedding similarity via OpenAI or local models |
| Saved Searches | 5 | Store and re-execute frequent queries |
| Tag Management | 6 | Tags, bulk ops, importance scores |
| Tag Aliases | 5 | Tag synonym/alias management |
| Hierarchy | 9 | Parent-child trees, subtree traversal |
| Graph Algorithms | 4 | BFS/DFS path finding, centrality, connected components |
| Analytics | 2 | Graph stats and integrity validation |
| Compression | 4 | Duplicate detection, merge, auto-compress, archive |
| Import/Export | 2 | 7 export formats |
Sources: CLAUDE.md:Tool Categories
Storage Layer
The storage layer supports two backends controlled by the MEMORY_STORAGE_TYPE environment variable.
JSONL Storage (Default)
Data files are stored in the project root directory:
| File | Purpose |
|---|---|
memory.jsonl | Main knowledge graph data |
memory-saved-searches.jsonl | Saved search definitions |
memory-tag-aliases.jsonl | Tag synonym mappings |
SQLite Storage
When MEMORY_STORAGE_TYPE=sqlite, the system uses:
memory.db- Single-file relational database
The SQLite backend provides better performance for large datasets and supports advanced query capabilities through the storage layer.
Sources: CLAUDE.md:Storage
Entry Points
| Entry Point | Description |
|---|---|
dist/index.js | Built output for npm distribution |
mcp-server-memory | CLI binary defined in package.json bin field |
src/index.ts | Source entry point |
Sources: CLAUDE.md:Entry Points
Data Flow
sequenceDiagram
participant Client
participant MCPServer
participant ToolHandler
participant ManagerContext
participant Manager
participant Storage
Client->>MCPServer: MCP Request
MCPServer->>ToolHandler: Route to handler
ToolHandler->>ManagerContext: Access manager
ManagerContext->>Manager: Lazy initialization
Manager->>Storage: Read/Write operations
Storage-->>Manager: Data
Manager-->>ManagerContext: Result
ManagerContext-->>ToolHandler: Structured response
ToolHandler-->>MCPServer: Formatted response
MCPServer-->>Client: MCP ResponseStandalone Tools
The tools/ directory contains standalone utilities with their own package.json files, buildable to Windows executables via pkg:
| Tool | Purpose |
|---|---|
chunking-for-files | Split/merge large files for context-limited editing |
compress-for-context | CTON compression for LLM context windows |
create-dependency-graph | Generate TypeScript project dependency graphs |
migrate-from-jsonl-to-sqlite | Convert between JSONL and SQLite formats |
Sources: CLAUDE.md:Standalone Tools
Version History
The architecture has evolved through multiple phases:
| Phase | Version | Key Changes |
|---|---|---|
| Phase 13 | Initial | 5 TypeScript source files, memoryjs v2.1.0+ |
| Phase 15 | v12.2.0 | 23 tools for memoryjs v1.14+ features (bitemporal, OCC, RBAC) |
| Phase 16 | v12.3.0 | 53 tools for memoryjs v2.1.0 (exclusions, ADR, context, heuristics) |
Sources: CLAUDE.md:Phase History
npm Package Information
- Package:
@danielsimonjr/memory-mcp - Core Dependency:
@danielsimonjr/memoryjs(version specified in package.json)
Sources: CLAUDE.md:npm Information
Sources: CLAUDE.md:Layered Architecture
Storage Backends
Related topics: Architecture Overview, Entity-Relation-Observation Model
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Related Pages
Related topics: Architecture Overview, Entity-Relation-Observation Model
Storage Backends
The Memory MCP server implements a dual-storage backend architecture that supports both JSONL (JSON Lines) and SQLite formats for persisting knowledge graph data. This flexible design allows users to choose the most appropriate storage mechanism based on dataset size, performance requirements, and debugging preferences.
Architecture Overview
The storage layer handles all persistence operations for entities, relations, and associated metadata within the knowledge graph. The architecture separates the storage format from the core application logic, enabling seamless migration between formats without losing data integrity.
graph TD
A[Memory MCP Server] --> B[Storage Abstraction Layer]
B --> C[JSONL Backend]
B --> D[SQLite Backend]
C --> E[memory.jsonl]
D --> F[memory.db]
D --> G[FTS5 Index]
style A fill:#e1f5fe
style B fill:#fff3e0
style E fill:#f3e5f5
style F fill:#e8f5e9
style G fill:#e8f5e9Data Models
KnowledgeGraph Structure
The knowledge graph comprises two primary collections that together represent the complete state of the memory system.
| Collection | Type | Description |
|---|---|---|
entities | Entity[] | Individual memory items with observations and metadata |
relations | Relation[] | Connections between entities defining semantic relationships |
Entity Model
| Field | Type | Required | Description |
|---|---|---|---|
name | string | Yes | Unique identifier for the entity |
entityType | string | Yes | Classification category (e.g., "person", "concept", "task") |
observations | string[] | Yes | Array of recorded facts or data points |
createdAt | string | No | ISO timestamp of entity creation |
lastModified | string | No | ISO timestamp of last modification |
tags | string[] | No | Optional categorization labels |
importance | number | No | Priority score (null if unspecified) |
parentId | string | No | Hierarchical parent reference |
Sources: tools/migrate-from-jsonl-to-sqlite/migrate-from-jsonl-to-sqlite.ts:50-58
Relation Model
| Field | Type | Required | Description |
|---|---|---|---|
from | string | Yes | Source entity name or ID |
to | string | Yes | Target entity name or ID |
relationType | string | Yes | Semantic relationship type (e.g., "related_to", "part_of") |
createdAt | string | No | ISO timestamp of relation creation |
lastModified | string | No | ISO timestamp of last modification |
Sources: tools/migrate-from-jsonl-to-sqlite/migrate-from-jsonl-to-sqlite.ts:60-66
Supported Storage Formats
JSONL Format
The JSONL (JSON Lines) backend stores each entity and relation as a separate JSON object on its own line within plain text files. This format provides human-readable data and simple version control compatibility.
File Locations (Project Root):
| File | Purpose |
|---|---|
memory.jsonl | Primary knowledge graph storage |
memory-saved-searches.jsonl | Stored search configurations |
memory-tag-aliases.jsonl | Tag normalization mappings |
Sources: CLAUDE.md:2-9
Characteristics:
- Default storage format when no configuration is provided
- Each line contains a valid JSON object
- Easy to inspect, edit, and debug
- Direct compatibility with text editors and version control systems
- Recommended for datasets under 1,000 entities
Sources: tools/migrate-from-jsonl-to-sqlite/README.md:45-55
SQLite Format
The SQLite backend provides a relational database optimized for larger datasets and concurrent access patterns. It offers ACID transaction support and full-text search capabilities through FTS5.
File Location (Project Root):
| File | Purpose |
|---|---|
memory.db | Primary SQLite database |
Sources: CLAUDE.md:6
SQLite Backend Features:
| Feature | Description |
|---|---|
| FTS5 Index | Automatic full-text search indexing for fast entity lookups |
| WAL Mode | Write-Ahead Logging for improved concurrent read/write performance |
| Atomic Transactions | Ensures data integrity during write operations |
| Native Performance | Uses better-sqlite3 for 3-10x faster operations compared to WASM alternatives |
Sources: tools/migrate-from-jsonl-to-sqlite/migrate-from-jsonl-to-sqlite.ts:14-15
Environment Configuration
Storage behavior is controlled through environment variables that must be set before server initialization.
Configuration Variables
| Variable | Values | Default | Description |
|---|---|---|---|
MEMORY_STORAGE_TYPE | jsonl, sqlite | jsonl | Determines which storage backend to use |
MEMORY_FILE_PATH | Valid file path | memory.jsonl (cwd) | Absolute or relative path to primary storage file |
Sources: CLAUDE.md:24-28
Configuration Examples
JSONL (Default):
# No environment variables needed - defaults to JSONL
SQLite:
{
"mcpServers": {
"memory": {
"command": "node",
"args": ["/path/to/memory-mcp/src/memory/dist/index.js"],
"env": {
"MEMORY_STORAGE_TYPE": "sqlite",
"MEMORY_FILE_PATH": "/path/to/memory.db"
}
}
}
}
Sources: tools/migrate-from-jsonl-to-sqlite/README.md:70-79
Migration Between Formats
The migrate-from-jsonl-to-sqlite tool provides bidirectional conversion between JSONL and SQLite storage formats. This enables users to start with simple JSONL storage and migrate to SQLite as their dataset grows.
Supported File Extensions
| Format | Extensions | Detection Logic |
|---|---|---|
| JSONL | .jsonl, .json | Extension-based detection |
| SQLite | .db, .sqlite, .sqlite3 | Extension-based detection |
Sources: tools/migrate-from-jsonl-to-sqlite/migrate-from-jsonl-to-sqlite.ts:97-103
Migration Tool Usage
# JSONL to SQLite migration
migrate-from-jsonl-to-sqlite --from memory.jsonl --to memory.db
# SQLite to JSONL migration
migrate-from-jsonl-to-sqlite --from memory.db --to memory.jsonl
# Using positional arguments
migrate-from-jsonl-to-sqlite memory.jsonl memory.db
# Verbose output for troubleshooting
migrate-from-jsonl-to-sqlite -f memory.jsonl -t memory.db -v
Sources: tools/migrate-from-jsonl-to-sqlite/migrate-from-jsonl-to-sqlite.ts:1-30
Migration Options
| Argument | Short | Description |
|---|---|---|
--from | -f | Source file path (JSONL or SQLite) |
--to | -t | Target file path (JSONL or SQLite) |
--verbose | -v | Show detailed progress information |
--help | -h | Display help message |
Migration Workflow
graph TD
A[Start Migration] --> B{Detect Source Format}
B -->|JSONL| C[loadFromJsonl]
B -->|SQLite| D[loadFromSqlite]
C --> E[Parse Knowledge Graph]
D --> E
E --> F{Validate Timestamps}
F -->|Missing createdAt| G[Set to migration time + warn]
F -->|Missing lastModified| H[Set to migration time + warn]
G --> I
H --> I[Write to Target Format]
I -->|JSONL| J[writeToJsonl]
I -->|SQLite| K[Initialize FTS5 + WAL]
J --> L[Migration Complete]
K --> LMigration Notes and Limitations
| Aspect | Behavior |
|---|---|
| Target Creation | Target file is created if it doesn't exist |
| Existing Targets | Target file will be overwritten if it exists |
| Data Integrity | Atomic transactions ensure no data loss during migration |
| Timestamp Handling | Missing createdAt or lastModified fields are populated with migration timestamp and a warning is displayed |
| Saved Searches | NOT migrated (stored in separate memory-saved-searches.jsonl file) |
| Tag Aliases | NOT migrated (stored in separate memory-tag-aliases.jsonl file) |
| Large Datasets | Recommended for graphs with 10,000+ entities |
Sources: tools/migrate-from-jsonl-to-sqlite/README.md:20-25
Format Selection Guide
Choose the appropriate storage backend based on your specific use case and dataset characteristics.
| Criteria | JSONL | SQLite |
|---|---|---|
| Dataset Size | < 1,000 entities | 10,000+ entities |
| Transaction Needs | Simple append operations | ACID transactions required |
| Data Inspection | Human-readable preferred | Structured queries needed |
| Concurrent Access | Single process | Multiple readers/writers |
| Debugging | Direct file inspection | Requires SQLite tools |
| Performance | Sufficient for small datasets | Optimized for large graphs |
Sources: tools/migrate-from-jsonl-to-sqlite/README.md:45-55
Security Considerations
When configuring storage backends, consider the following security implications documented in the project's security guidelines.
File Permissions
The storage files contain all knowledge graph data and should be protected with appropriate file system permissions:
{
"mcpServers": {
"memory": {
"command": "node",
"args": ["/path/to/memory-mcp/src/memory/dist/index.js"],
"env": {
"MEMORY_FILE_PATH": "/secure/path/memory.jsonl"
}
}
}
}
Sources: SECURITY.md:8-18
Data Sensitivity
| Format | Export Considerations |
|---|---|
| JSONL/JSON | Full entity data visible in plain text |
| SQLite | Database contents require database tools to inspect |
| CSV/GraphML Exports | Full data included; filter parameters can limit exported data |
Sources: SECURITY.md:19-26
Tool Dependencies
The SQLite backend and migration tool rely on the better-sqlite3 package for native performance:
{
"name": "migrate-from-jsonl-to-sqlite",
"version": "1.1.0",
"dependencies": {
"better-sqlite3": "^11.7.0"
},
"devDependencies": {
"@types/better-sqlite3": "^7.6.12"
}
}
Sources: tools/migrate-from-jsonl-to-sqlite/package.json:1-12
The package is configured with yao-pkg/pkg for building standalone executables targeting node22-win-x64.
Related Documentation
| Document | Description |
|---|---|
| CLAUDE.md | Project architecture and development guidelines |
| tools/migrate-from-jsonl-to-sqlite/README.md | Detailed migration tool documentation |
| SECURITY.md | Security considerations for data storage |
Sources: tools/migrate-from-jsonl-to-sqlite/migrate-from-jsonl-to-sqlite.ts:50-58
Entity-Relation-Observation Model
Related topics: Search Capabilities, Temporal and Advanced Features
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Related Pages
Related topics: Search Capabilities, Temporal and Advanced Features
Entity-Relation-Observation Model
The Entity-Relation-Observation (ERO) Model is the core data architecture powering the Enhanced Memory MCP server. It implements a temporal knowledge graph where entities represent nodes in a graph, relations represent directed edges between entities, and observations attach factual metadata to entities.
Architecture Overview
The ERO Model is built on the layered architecture of memoryjs (v^2.1.0), where the ManagerContext provides lazy-initialized access to specialized managers:
graph TD
subgraph "memory-mcp (MCP Server Layer)"
MCPS[MCPServer]
TH[ToolHandlers]
TD[ToolDefinitions]
end
subgraph "memoryjs (Core Library Layer)"
MC[ManagerContext]
EM[EntityManager]
RM[RelationManager]
OM[ObservationManager]
SM[SearchManager]
end
MCPS --> TH
TH --> TD
TH --> MC
MC --> EM
MC --> RM
MC --> OM
MC --> SM
subgraph "Storage Layer"
GS[GraphStorage]
SS[SQLiteStorage]
JL[JSONLStorage]
end
MC --> GS
GS --> SS
GS --> JLSources: CLAUDE.md:layered-architecture
Core Components
Entity Manager
Entities are the primary nodes in the knowledge graph. The EntityManager provides core CRUD operations:
| Operation | Tool Name | Description |
|---|---|---|
| Create | create_entity | Add a new entity to the graph |
| Read | get_entity | Retrieve entity by name or ref |
| Update | update_entity | Modify entity properties |
| Delete | delete_entities | Remove entity from graph |
| List | list_entities | Get entities with optional filters |
Sources: toolDefinitions.ts:entity-tools
Entity Properties:
name(required): Unique identifiermemoryType: Classification type (default:semantic)confidence: Trust score (0.0 - 1.0, default: 0.8)tags: Array of associated tagsobservations: Attached factual metadatacreatedAt/updatedAt: Temporal timestampsaccessCount: Usage trackingconfirmationCount: Verification count
Relation Manager
Relations are directed edges connecting entities with typed relationships. The RelationManager handles:
graph LR
E1[Entity A] -->|"created_by"| R[Relation]
R -->|"part_of"| E2[Entity B]
E1 -->|"depends_on"| R2[Relation]
R2 -->|"implements"| E3[Entity C]| Operation | Tool Name | Description |
|---|---|---|
| Create | create_relations | Batch create directed edges |
| Delete | delete_relations | Remove relations by criteria |
| Invalidate | invalidate_relation | Bitemporal validity - end a relation |
| Chain | get_entity_chain | Traverse relation paths between entities |
Sources: toolHandlers.ts:relation-handlers
Relation Schema:
interface Relation {
from: string; // Source entity name/ref
relationType: string; // Relationship type (e.g., "depends_on", "part_of")
to: string; // Target entity name/ref
ended?: string; // Bitemporal end timestamp (undefined = active)
}
Observation Manager
Observations are factual statements attached to entities, providing evidence and context:
| Property | Description |
|---|---|
content | The factual statement |
normalized | Canonical form for comparison |
source | Origin of the observation |
confirmed | Verification status |
attachedAt | Timestamp when attached |
Sources: CLAUDE.md:observation
Key Features:
- Content normalization for deduplication
- Source tracking for provenance
- Confirmation counting for consensus-based truth
Tool Categories
The ERO Model exposes 213 tools across 58 categories:
| Category | Count | Purpose |
|---|---|---|
| Entity | 4 | Core CRUD for graph nodes |
| Relation | 2 | Directed edges between entities |
| Observation | 3 | Facts attached to entities |
| Search | 7 | Query graph data |
| Intelligent Search | 3 | Advanced query processing |
| Semantic Search | 3 | Embedding-based retrieval |
| Tag Management | 6 | Entity categorization |
| Hierarchy | 9 | Parent-child tree structures |
| Graph Algorithms | 4 | Path finding, centrality |
| Analytics | 2 | Graph statistics |
| Compression | 4 | Deduplication, archiving |
Sources: CLAUDE.md:tool-categories
Data Flow
sequenceDiagram
participant Client
participant MCPS as MCPServer
participant TH as ToolHandlers
participant MC as ManagerContext
participant Storage as GraphStorage
Client->>MCPS: create_entity({ name, tags, observations })
MCPS->>TH: Route to create_entity handler
TH->>MC: ctx.entityManager.createEntity()
MC->>Storage: saveGraph(graph)
Storage-->>MC: Success
MC-->>TH: Entity result
TH-->>MCPS: Formatted response
MCPS-->>Client: { content: [...] }Storage Layer
The ERO Model supports two storage backends:
JSONL Storage (Default)
- File:
memory.jsonl(project root) - Format: One JSON object per line
- Additional files:
memory-saved-searches.jsonl,memory-tag-aliases.jsonl
SQLite Storage
- File:
memory.db(project root) - Enable: Set
MEMORY_STORAGE_TYPE=sqlite - Benefits: Queryable, relational operations
Sources: CLAUDE.md:storage
Bitemporal Validity
Relations support bitemporal validity for tracking historical state:
graph TD
A[Entity A] -->|created: 2024-01-01| R1[Active Relation]
A -->|ended: 2024-02-15| R2[Historical Relation]
subgraph "Timeline"
T1[Jan 2024]
T2[Feb 2024]
T3[Current]
end
R1 --> T3
R2 --> T2The invalidate_relation tool terminates a relation at a specified timestamp:
invalidate_relation(from, relationType, to, ended?)
Sources: toolHandlers.ts:invalidate-relation
Hierarchy Integration
Entities can form hierarchical trees through the HierarchyManager:
| Tool | Purpose |
|---|---|
set_entity_parent | Assign parent entity |
get_children | Direct descendants |
get_parent | Direct ancestor |
get_ancestors | Full ancestry path |
get_descendants | All descendants (recursive) |
get_subtree | Subtree structure |
Sources: toolHandlers.ts:hierarchy-handlers
Search Capabilities
The ERO Model provides layered search:
graph TD
Q[Query] --> BS[Basic Search]
Q --> RS[Ranked Search]
Q --> FS[Fuzzy Search]
Q --> SS[Semantic Search]
BS -->|TF-IDF| R1[Results]
RS -->|Ranked| R2[Results]
FS -->|Edit Distance| R3[Results]
SS -->|Embeddings| R4[Results]
subgraph "Intelligent Search"
QA[Query Analysis]
QR[Query Reflection]
end
Q --> QA
QA --> QR
QR --> R5[Intelligent Results]Search Types:
- Basic: Exact and substring matching
- Ranked (TF-IDF): Term frequency-inverse document frequency
- Fuzzy: Edit distance tolerance
- Semantic: Embedding similarity (OpenAI or local models)
- Intelligent: Multi-layer hybrid with query analysis
Sources: CLAUDE.md:search
Environment Configuration
| Variable | Description | Default |
|---|---|---|
MEMORY_FILE_PATH | Storage file path | memory.jsonl |
MEMORY_STORAGE_TYPE | Backend type | jsonl |
MEMORY_EMBEDDING_PROVIDER | Embedding service | none |
MEMORY_OPENAI_API_KEY | API key for OpenAI | — |
MEMORY_EMBEDDING_MODEL | Model name | text-embedding-3-small |
MEMORY_AUTO_INDEX_EMBEDDINGS | Auto-index on create | false |
Sources: CLAUDE.md:env-vars
API Entry Points
| Endpoint | Description |
|---|---|
dist/index.js | Build output entry |
src/index.ts | Source entry (exports ManagerContext as KnowledgeGraphManager) |
mcp-server-memory | CLI binary |
Sources: package.json:exports
Adding Custom Tools
To extend the ERO Model with new functionality:
- Define Schema in
toolDefinitions.ts:
{
name: 'new_tool',
description: 'Tool description',
inputSchema: {
type: 'object',
properties: { /* parameters */ },
required: ['param1']
}
}
- Implement Handler in
toolHandlers.ts:
new_tool: async (ctx, args) => {
// Validate arguments
// Call manager methods
// Return formatted response
}
- Add Tests in
tests/e2e/tools/
Sources: CLAUDE.md:adding-tools
Sources: CLAUDE.md:layered-architecture
Tool Reference
Related topics: Search Capabilities, Temporal and Advanced Features, Collaboration and Security
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Related Pages
Related topics: Search Capabilities, Temporal and Advanced Features, Collaboration and Security
Tool Reference
Overview
The Tool Reference documents the 213 MCP tools exposed by memory-mcp, organized across 58 categories. These tools provide a comprehensive interface for managing a persistent knowledge graph that supports entity storage, relationship mapping, semantic search, and temporal reasoning capabilities.
The tool layer acts as a bridge between MCP clients and the underlying ManagerContext system, which provides access to specialized managers for entities, relations, observations, search, tags, hierarchies, analytics, compression, and I/O operations. Sources: CLAUDE.md:1-5
Architecture
Layered Design
graph TD
A[MCP Client] --> B[MCPServer]
B --> C[Tool Definitions]
B --> D[Tool Handlers]
C --> E[Schema Validation]
D --> F[ManagerContext]
F --> G[memoryjs Library]
F --> H[GraphStorage]
G --> I[SQLite/JSONL]
subgraph Managers
F --> J[EntityManager]
F --> K[RelationManager]
F --> L[SearchManager]
F --> M[ObservationManager]
F --> N[TagManager]
F --> O[HierarchyManager]
F --> P[AnalyticsManager]
endThe architecture follows a layered approach where tool definitions declare schemas using JSON Schema format, handlers implement business logic by calling manager methods, and the ManagerContext provides lazy-initialized access to specialized subsystems. Sources: CLAUDE.md:8-12
Tool Execution Flow
sequenceDiagram
participant Client
participant MCPServer
participant Handler
participant Manager
participant Storage
Client->>MCPServer: Tool Call Request
MCPServer->>Handler: Dispatch with args
Handler->>Handler: Validate with Zod schema
Handler->>Manager: Call manager method
Manager->>Storage: Read/Write data
Storage-->>Manager: Result
Manager-->>Handler: Response
Handler->>Handler: Format response
Handler-->>MCPServer: ToolResponse
MCPServer-->>Client: MCP-formatted resultError handling in dispatch catches exceptions from handlers and returns them as MCP-formatted error responses rather than throwing. The MCP response isError field indicates failures. Sources: CLAUDE.md:85-87
Tool Categories
The tools are organized into 58 categories spanning core graph operations to advanced features like bitemporal validity and causal reasoning.
| Category | Count | Key Purpose |
|---|---|---|
| Entity | 4 | Core CRUD for graph nodes |
| Relation | 2 | Directed edges between entities |
| Observation | 3 | Facts attached to entities, with normalization |
| Search | 7 | Basic, ranked (TF-IDF), boolean, fuzzy, auto-select |
| Intelligent Search | 3 | Hybrid multi-layer, query analysis, reflection-based |
| Semantic Search | 3 | Embedding similarity via OpenAI or local models |
| Saved Searches | 5 | Store and re-execute frequent queries |
| Tag Management | 6 | Tags, bulk ops, importance scores |
| Tag Aliases | 5 | Tag synonym/alias management |
| Hierarchy | 9 | Parent-child trees, subtree traversal |
| Graph Algorithms | 4 | BFS/DFS path finding, centrality, connected components |
| Analytics | 2 | Graph stats and integrity validation |
| Compression | 4 | Duplicate detection, merge, auto-compress, archive |
| Import/Export | 2 | 7 export formats |
Sources: CLAUDE.md:30-44
Tool Definition Schema
Each tool is defined with a JSON Schema that specifies input parameters. The schema follows a consistent pattern:
{
name: 'tool_name',
description: 'Human-readable description of tool purpose',
inputSchema: {
type: 'object',
properties: {
paramName: {
type: 'string',
description: 'Parameter description',
enum: ['option1', 'option2'] // optional for constrained values
},
},
required: ['paramName'], // mandatory parameters
additionalProperties: false,
},
}
Sources: src/server/toolDefinitions.ts:1-20
Example: Artifact Tool Definition
{
name: 'create_artifact',
description: 'Create an artifact entity (tool output, code snippet, API response, etc.) with a stable auto-generated ref',
inputSchema: {
type: 'object',
properties: {
content: { type: 'string', description: 'Artifact content stored as an entity observation' },
toolName: { type: 'string', description: 'Name of the tool or source that produced this artifact' },
artifactType: {
type: 'string',
enum: ['tool_output', 'code_snippet', 'api_response', 'search_result', 'file_content', 'user_input'],
description: 'Category of artifact for structured filtering',
},
description: { type: 'string', description: 'Optional human-readable description' },
sessionId: { type: 'string', description: 'Optional session context for grouping related artifacts' },
},
required: ['content', 'toolName', 'artifactType'],
additionalProperties: false,
},
}
Sources: src/server/toolDefinitions.ts:90-115
Handler Implementation Pattern
Tool handlers follow a consistent implementation pattern across all 213 tools:
tool_name: async (ctx, args) => {
// 1. Validate required arguments
const param = validateWithSchema(args.param, z.string().min(1), 'Invalid param');
// 2. Build filter/options objects
const filter: FilterType = {};
if (args.optionalParam !== undefined) {
filter.optionalParam = validateWithSchema(args.optionalParam, z.string(), 'Invalid optionalParam');
}
// 3. Call manager method
const result = await getManager(ctx).method(filter);
// 4. Format and return response
return formatToolResponse(result);
}
Sources: src/server/toolHandlers.ts:1-30
Validation with Zod
Handlers use Zod schemas for runtime validation:
| Zod Function | Usage |
|---|---|
z.string().min(1) | Non-empty string |
z.number().int().min(1).max(1000) | Bounded integer |
z.enum(['option1', 'option2']) | Constrained string |
z.boolean() | Boolean flag |
z.string().regex(/pattern/) | Pattern-matched string |
z.record(z.string(), z.unknown()) | Dictionary object |
const ref = validateWithSchema(args.ref, z.string().min(1), 'Invalid ref');
const limit = validateWithSchema(args.limit, z.number().int().min(1).max(1000), 'Invalid limit');
const artifactType = validateWithSchema(
args.artifactType,
z.enum(['tool_output', 'code_snippet', 'api_response', 'search_result', 'file_content', 'user_input']),
'Invalid artifactType'
);
Sources: src/server/toolHandlers.ts:5-25
Artifact Tools
Artifact tools manage tool outputs, code snippets, API responses, and other generated content with stable references.
create_artifact
Creates an artifact entity with a stable auto-generated reference.
| Parameter | Type | Required | Description |
|---|---|---|---|
content | string | Yes | Artifact content stored as an entity observation |
toolName | string | Yes | Name of the tool or source that produced this artifact |
artifactType | enum | Yes | Category: tool_output, code_snippet, api_response, search_result, file_content, user_input |
description | string | No | Human-readable description |
sessionId | string | No | Session context for grouping related artifacts |
create_artifact: async (ctx, args) => {
const content = validateWithSchema(args.content, z.string().min(1), 'Invalid content');
const toolName = validateWithSchema(args.toolName, z.string().min(1), 'Invalid toolName');
const artifactType = validateWithSchema(
args.artifactType,
z.enum(['tool_output', 'code_snippet', 'api_response', 'search_result', 'file_content', 'user_input']),
'Invalid artifactType'
);
const description = args.description !== undefined
? validateWithSchema(args.description, z.string(), 'Invalid description')
: undefined;
const sessionId = args.sessionId !== undefined
? validateWithSchema(args.sessionId, z.string(), 'Invalid sessionId')
: undefined;
const artifact = await getArtifactManager(ctx).createArtifact({
content, toolName, artifactType, description, sessionId,
});
return formatToolResponse(artifact);
}
Sources: src/server/toolHandlers.ts:290-315
get_artifact
Retrieves an artifact entity by its stable ref or entity name.
| Parameter | Type | Required | Description |
|---|---|---|---|
ref | string | Yes | Stable ref or entity name (e.g. "bash-2026-03-24-a3f2") |
get_artifact: async (ctx, args) => {
const ref = validateWithSchema(args.ref, z.string().min(1), 'Invalid ref');
const artifact = await getArtifactManager(ctx).getArtifact(ref);
if (!artifact) {
return formatTextResponse(`Artifact "${ref}" not found`);
}
return formatToolResponse(artifact);
}
Sources: src/server/toolHandlers.ts:318-328
list_artifacts
Lists artifacts with optional filtering by tool name, type, or time.
| Parameter | Type | Required | Description |
|---|---|---|---|
toolName | string | No | Filter by originating tool |
artifactType | enum | No | Filter by artifact category |
since | string | No | ISO 8601 timestamp for time-based filtering |
list_artifacts: async (ctx, args) => {
const filter: ArtifactFilter = {};
if (args.toolName !== undefined) {
filter.toolName = validateWithSchema(args.toolName, z.string(), 'Invalid toolName');
}
if (args.artifactType !== undefined) {
filter.artifactType = validateWithSchema(
args.artifactType,
z.enum(['tool_output', 'code_snippet', 'api_response', 'search_result', 'file_content', 'user_input']),
'Invalid artifactType'
);
}
if (args.since !== undefined) {
const sinceStr = validateWithSchema(args.since, z.string().regex(/^\d{4}-\d{2}-\d{2}(T[\d:.Z+-]+)?$/, 'since must be an ISO 8601 date string'), 'Invalid since');
const sinceDate = new Date(sinceStr);
if (isNaN(sinceDate.getTime())) {
throw new Error(`Invalid since date: "${sinceStr}" is not a valid date`);
}
filter.since = sinceDate;
}
const artifacts = await getArtifactManager(ctx).listArtifacts(Object.keys(filter).length > 0 ? filter : undefined);
return formatToolResponse({ artifacts, count: artifacts.length });
}
Sources: src/server/toolHandlers.ts:330-360
Decay and Salience Tools
These tools manage memory importance over time using time-based decay algorithms.
run_decay_cycle
Runs a single pass of time-based importance decay across all agent memories.
| Parameter | Type | Required | Description |
|---|---|---|---|
| (none) | - | - | No parameters required |
Returns the count of decayed and forgotten memories. Sources: src/server/toolDefinitions.ts:180-195
get_decayed_memories
Lists memories whose importance has fallen below a threshold due to time-based decay.
| Parameter | Type | Required | Description |
|---|---|---|---|
threshold | number | No | Importance threshold (default: 0.1) |
Unlike get_stale_entities which uses freshness timestamps, this tool uses decay engine importance calculations. Sources: src/server/toolDefinitions.ts:197-208
forget_weak_memories
Bulk-deletes memories that fell below a decay threshold.
| Parameter | Type | Required | Description |
|---|---|---|---|
threshold | number | No | Importance threshold below which to forget |
maxCount | number | No | Maximum number of memories to forget |
dryRun | boolean | No | If true, report what would be forgotten without deleting |
Unlike forget_memory (content match) or archive_entities (criteria-based move), this uses decay-based importance scoring. Sources: src/server/toolDefinitions.ts:210-222
Governance and Audit Tools
audit_query
Queries the audit log for operations matching specified criteria.
| Parameter | Type | Required | Description |
|---|---|---|---|
operation | enum | No | Filter by: create, update, delete, merge, archive |
agentId | string | No | Filter by agent identifier |
entityName | string | No | Filter by entity name |
since | string | No | Start time (ISO 8601) |
until | string | No | End time (ISO 8601) |
limit | number | No | Maximum entries to return (default: 50, max: 1000) |
audit_query: async (ctx, args) => {
const filter: AuditFilter = {};
if (args.operation !== undefined) {
filter.operation = validateWithSchema(
args.operation,
z.enum(['create', 'update', 'delete', 'merge', 'archive']),
'Invalid operation'
) as AuditFilter['operation'];
}
if (args.agentId !== undefined) {
filter.agentId = validateWithSchema(args.agentId, z.string(), 'Invalid agentId');
}
if (args.entityName !== undefined) {
filter.entityName = validateWithSchema(args.entityName, z.string(), 'Invalid entityName');
}
// AuditFilter uses fromTime/toTime (not since/until)
if (args.since !== undefined) {
filter.fromTime = validateWithSchema(args.since, z.string(), 'Invalid since');
}
if (args.until !== undefined) {
filter.toTime = validateWithSchema(args.until, z.string(), 'Invalid until');
}
const limit = args.limit !== undefined
? validateWithSchema(args.limit, z.number().int().min(1).max(1000), 'Invalid limit')
: 50;
const al = getAuditLog(ctx);
let entries = await al.query(filter);
entries = entries.slice(0, limit);
return formatToolResponse({ entries, count: entries.length });
}
Sources: src/server/toolHandlers.ts:400-440
Adding New Tools
The development workflow for adding a new tool follows a three-step process:
graph LR
A[1. Add schema to toolDefinitions.ts] --> B[2. Add handler to toolHandlers.ts]
B --> C[3. Add e2e test in tests/e2e/tools/]- Add schema to
toolDefinitions.ts— Define the tool name, description, and input schema in the appropriate category section - Add handler to
toolHandlers.ts— Register handler in theTOOL_HANDLERSregistry with the pattern: validate args → call manager method → return formatted response - Add e2e test — Create test coverage in
tests/e2e/tools/Sources: CONTRIBUTING.md:55-62
Handler Pattern Template
// ==================== CATEGORY_NAME ====================
tool_name: async (ctx, args) => {
// Validate required arguments
const required = validateWithSchema(args.required, z.string().min(1), 'Invalid required');
// Build options object with optional parameters
const options: OptionsType = {};
if (args.optional !== undefined) {
options.optional = validateWithSchema(args.optional, z.string(), 'Invalid optional');
}
// Call manager method
const result = await getManager(ctx).method(options);
// Return formatted response
return formatToolResponse(result);
},
If the response can be large, wrap the handler result with withCompression(). Sources: CONTRIBUTING.md:58-60
Environment Configuration
Tools honor the following environment variables:
| Variable | Description | Default |
|---|---|---|
MEMORY_FILE_PATH | Path to storage file | memory.jsonl (cwd) |
MEMORY_STORAGE_TYPE | jsonl or sqlite | jsonl |
MEMORY_EMBEDDING_PROVIDER | openai, local, or none | none |
MEMORY_OPENAI_API_KEY | Required if provider is openai | — |
MEMORY_EMBEDDING_MODEL | Embedding model name | text-embedding-3-small / Xenova/all-MiniLM-L6-v2 |
MEMORY_AUTO_INDEX_EMBEDDINGS | Auto-index on entity creation | false |
Sources: CLAUDE.md:66-73
ManagerContext Accessors
Handlers access underlying functionality through the ManagerContext:
| Accessor | Purpose |
|---|---|
ctx.entityManager | Core entity CRUD operations |
ctx.relationManager | Relationship management |
ctx.observationManager | Fact attachment to entities |
ctx.searchManager | Full-text and ranked search |
ctx.tagManager | Tag CRUD and bulk operations |
ctx.hierarchyManager | Tree structures and traversal |
ctx.analyticsManager | Graph statistics |
ctx.compressionManager | Deduplication and archiving |
ctx.archiveManager | Historical data management |
ctx.ioManager | Import/export operations |
ctx.graphTraversal | Path finding algorithms |
ctx.semanticSearch | Embedding-based similarity |
ctx.rankedSearch | TF-IDF ranking |
ctx.storage | Direct GraphStorage access |
Sources: CLAUDE.md:13-26
Storage Backend
Tools persist data to the project root (not dist/):
| Format | Files |
|---|---|
| JSONL | memory.jsonl, memory-saved-searches.jsonl, memory-tag-aliases.jsonl |
| SQLite | memory.db (set MEMORY_STORAGE_TYPE=sqlite) |
The prepare script runs npm run build on install, so dist/ is rebuilt automatically. Sources: CLAUDE.md:48-55
Response Formatting
Handlers return responses using two formatting functions:
| Function | Usage |
|---|---|
formatToolResponse(data) | Structured data response (objects, arrays) |
formatTextResponse(text) | Simple text response (errors, confirmations) |
// Success with data
return formatToolResponse(artifact);
// Not found / error message
return formatTextResponse(`Artifact "${ref}" not found`);
// List results
return formatToolResponse({ artifacts, count: artifacts.length });
Sources: src/server/toolHandlers.ts:318-328
TypeScript Configuration
Tools are built with the following TypeScript configuration:
- Target: ES2022
- Module resolution: Node16
- Build output:
dist/index.js - Source entry:
src/index.tsSources: CLAUDE.md:88-90
Backward compatibility is maintained by re-exporting ManagerContext as KnowledgeGraphManager alias, plus core types. Sources: CLAUDE.md:27-29
Sources: CLAUDE.md:30-44
Search Capabilities
Related topics: Entity-Relation-Observation Model, Temporal and Advanced Features
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Related Pages
Related topics: Entity-Relation-Observation Model, Temporal and Advanced Features
Search Capabilities
Overview
The memory-mcp repository provides a comprehensive multi-layered search system with 13 search tools across 6 categories. These capabilities enable users to query the knowledge graph using various matching strategies, from simple text matching to advanced semantic similarity using embeddings.
Sources: CLAUDE.md:18
Architecture
The search system is built on a layered architecture that provides progressive enhancement from basic keyword matching to intelligent semantic understanding.
graph TD
A[Search Query] --> B[Search Category]
A --> C[Intelligent Search]
A --> D[Semantic Search]
B --> B1[Basic Search]
B --> B2[Ranked Search TF-IDF]
B --> B3[Boolean Search]
B --> B4[Fuzzy Search]
B --> B5[Auto-Select]
C --> C1[Hybrid Multi-Layer]
C --> C2[Query Analysis]
C --> C3[Reflection-Based]
D --> D1[OpenAI Embeddings]
D --> D2[Local Model Embeddings]
style A fill:#e1f5fe
style B fill:#fff3e0
style C fill:#e8f5e9
style D fill:#f3e5f5Search Tool Categories
| Category | Tool Count | Primary Use Case |
|---|---|---|
| Search | 7 | Core text-based query operations |
| Intelligent Search | 3 | Advanced query analysis and multi-layer approaches |
| Semantic Search | 3 | Embedding-based similarity matching |
| Saved Searches | 5 | Store and reuse frequent queries |
Sources: CLAUDE.md:18-22
Basic Search Operations
Core Search Handler
The primary search functionality is implemented in toolHandlers.ts and supports multiple query types:
search: async (ctx, args) => {
const query = validateWithSchema(args.query, SearchQuerySchema, 'Invalid search query');
const limit = args.limit !== undefined
? validateWithSchema(args.limit, z.number().int().min(1).max(100), 'Invalid limit')
: undefined;
const graph = await ctx.storage.loadGraph();
const results = await ctx.searchManager.search(graph, query, limit);
return formatToolResponse({ query, results, count: results.length });
}
Sources: src/server/toolHandlers.ts
Search Tool Definition
The MCP tool definition specifies the input schema for the search interface:
{
name: 'semantic_search',
description: 'Search for entities using semantic similarity. Requires embedding provider to be configured via MEMORY_EMBEDDING_PROVIDER.',
inputSchema: {
type: 'object',
properties: {
query: { type: 'string', description: 'Natural language search query' },
limit: { type: 'number', description: 'Maximum number of results (default: 10, max: 100)' },
minSimilarity: {
type: 'number',
description: 'Minimum similarity score threshold (0.0-1.0, default: 0)',
},
},
required: ['query'],
additionalProperties: false,
},
}
Sources: src/server/toolDefinitions.ts:1-30
Semantic Search
Semantic search provides embedding-based similarity matching for natural language queries.
Configuration Requirements
Semantic search requires an embedding provider to be configured via the MEMORY_EMBEDDING_PROVIDER environment variable:
| Provider | Description |
|---|---|
openai | Use OpenAI embedding models |
local | Use locally deployed embedding models |
Handler Implementation
The semantic search handler validates configuration and executes embedding-based queries:
semantic_search: async (ctx, args) => {
const semanticSearch = ctx.semanticSearch;
if (!semanticSearch) {
return formatTextResponse(
'Semantic search is not available. Set MEMORY_EMBEDDING_PROVIDER environment variable to "openai" or "local".'
);
}
const query = validateWithSchema(args.query, SearchQuerySchema, 'Invalid search query');
const limit = args.limit !== undefined
? validateWithSchema(args.limit, z.number().int().min(1).max(100), 'Invalid limit (1-100)')
: undefined;
const minSimilarity = args.minSimilarity !== undefined
? validateWithSchema(args.minSimilarity, z.number().min(0).max(1), 'Invalid minSimilarity (0-1)')
: undefined;
const graph = await ctx.storage.loadGraph();
const results = await semanticSearch.search(graph, query, limit, minSimilarity);
return formatToolResponse({
query,
results: results.map(r => ({
entity: r.entity,
similarity: r.similarity,
})),
count: results.length,
});
}
Sources: src/server/toolHandlers.ts
Similar Entity Discovery
The find_similar_entities tool extends semantic search to discover entities similar to a given reference entity:
find_similar_entities: async (ctx, args) => {
const semanticSearch = ctx.semanticSearch;
if (!semanticSearch) {
return formatTextResponse(
'Semantic search is not available. Set MEMORY_EMBEDDING_PROVIDER environment variable...'
);
}
// Implementation continues...
}
Search Manager Architecture
The search functionality is provided through the ManagerContext which exposes the searchManager and semanticSearch accessors:
// Available accessors in ManagerContext
ctx.entityManager
ctx.relationManager
ctx.observationManager
ctx.searchManager // Basic search operations
ctx.tagManager
ctx.hierarchyManager
ctx.analyticsManager
ctx.compressionManager
ctx.archiveManager
ctx.ioManager
ctx.graphTraversal
ctx.semanticSearch // Embedding-based search
ctx.rankedSearch
ctx.storage // Direct GraphStorage access
Sources: CLAUDE.md:10-13
Search Parameters
Input Validation Schema
All search operations use Zod schemas for input validation to ensure type safety:
| Parameter | Type | Constraints | Default |
|---|---|---|---|
| query | string | min(1) | required |
| limit | number | int, min(1), max(100) | undefined |
| minSimilarity | number | min(0), max(1) | undefined |
Validation Pattern
The tool handlers use a consistent validation pattern:
const validateWithSchema = (value, schema, errorMessage) => {
const result = schema.safeParse(value);
if (!result.success) {
throw new Error(`${errorMessage}: ${result.error.message}`);
}
return result.data;
};
Search Result Format
Results are formatted consistently across all search operations:
return formatToolResponse({
query,
results: results.map(r => ({
entity: r.entity,
similarity: r.similarity, // Only for semantic search
})),
count: results.length,
});
Configuration
Environment Variables
| Variable | Required | Values | Purpose |
|---|---|---|---|
MEMORY_EMBEDDING_PROVIDER | For semantic search | openai, local | Select embedding backend |
MEMORY_STORAGE_TYPE | No | jsonl, sqlite | Storage format for graph data |
Storage Integration
Search operations load the graph from storage before executing queries:
const graph = await ctx.storage.loadGraph();
The storage layer supports both JSONL and SQLite backends for persistent graph storage.
Sources: CLAUDE.md:38-42
Workflow Diagram
sequenceDiagram
participant User
participant MCPServer
participant SearchManager
participant Storage
participant SemanticSearch
User->>MCPServer: search query
MCPServer->>MCPServer: Validate input schema
MCPServer->>Storage: loadGraph()
Storage-->>MCPServer: graph data
alt Basic Search
MCPServer->>SearchManager: search(graph, query, limit)
SearchManager-->>MCPServer: text match results
else Semantic Search
MCPServer->>SemanticSearch: search(graph, query, limit, minSimilarity)
SemanticSearch-->>MCPServer: similarity results
end
MCPServer-->>User: formatted responseRelated Documentation
- Query Language Guide - Syntax and operators for advanced queries
- Compression Guide - Search optimization through deduplication
Sources: CLAUDE.md:18
Temporal and Advanced Features
Related topics: Entity-Relation-Observation Model, Tool Reference
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Related Pages
Related topics: Entity-Relation-Observation Model, Tool Reference
Temporal and Advanced Features
This page documents the temporal, governance, and advanced cognitive features available in the memory-mcp system. These features extend beyond basic entity and relation management to provide sophisticated memory lifecycle management, access control, and intelligent decay mechanisms.
Overview
The memory-mcp system implements advanced features introduced in two major phases:
- Phase 15 (v12.2.0): Added 23 tools surfacing memoryjs v1.14+ features including bitemporal validity, OCC (Optimistic Concurrency Control), RBAC (Role-Based Access Control), procedural memory, active retrieval, causal reasoning, and world model capabilities.
- Phase 16 (v12.3.0): Added 53 tools surfacing memoryjs v2.1.0 features including decision rationale, ADR markdown dual-write, structured project context, heuristic guidelines, tool affordance observation pipeline, observation deduplication, and spell correction.
Sources: CLAUDE.md
Architecture
The advanced features are built upon the layered architecture where memory-mcp acts as the MCP server layer while the core graph logic resides in the @danielsimonjr/memoryjs package.
graph TD
subgraph "memory-mcp (MCP Server Layer)"
A[toolHandlers.ts] --> B[ManagerContext Accessors]
C[toolDefinitions.ts] --> B
end
subgraph "@danielsimonjr/memoryjs (Core Library)"
B --> D[EntityManager]
B --> E[RelationManager]
B --> F[ObservationManager]
B --> G[SearchManager]
B --> H[CompressionManager]
B --> I[ArchiveManager]
B --> J[GraphTraversal]
B --> K[SemanticSearch]
end
subgraph "Temporal Features"
L[Bitemporal Validity]
M[OCC - Optimistic Concurrency Control]
N[Decay Engine]
end
subgraph "Advanced Features"
O[RBAC Governance]
P[Audit Logging]
Q[Artifact Management]
R[Procedural Memory]
end
D --> L
E --> M
F --> N
G --> O
H --> P
I --> Q
J --> RSources: CLAUDE.md
Governance and Access Control
Role-Based Access Control (RBAC)
The system implements RBAC through governance policy settings that control what operations agents can perform on memory entities.
#### Governance Policy Tool
| Parameter | Type | Description |
|---|---|---|
allowCreate | boolean | Permission to create new entities |
allowUpdate | boolean | Permission to update existing entities |
allowDelete | boolean | Permission to delete entities |
Handler Implementation:
governance_policy_set: async (ctx, args) => {
const allowCreate = validateWithSchema(args.allowCreate, z.boolean(), 'Invalid allowCreate');
const allowUpdate = validateWithSchema(args.allowUpdate, z.boolean(), 'Invalid allowUpdate');
const allowDelete = validateWithSchema(args.allowDelete, z.boolean(), 'Invalid allowDelete');
const { setGovernancePolicy } = await import('@danielsimonjr/memoryjs');
await setGovernancePolicy(ctx.storage, {
canCreate: allowCreate ? undefined : () => false,
canUpdate: allowUpdate ? undefined : () => false,
canDelete: allowDelete ? undefined : () => false,
});
return formatTextResponse(`Governance policy set: canCreate=${allowCreate}, canUpdate=${allowUpdate}, canDelete=${allowDelete}`);
}
Sources: src/server/toolHandlers.ts:1-50
Audit Logging
The audit system tracks all operations performed on the knowledge graph for compliance and debugging purposes.
#### Audit Query Parameters
| Parameter | Type | Description | Default |
|---|---|---|---|
operation | enum | create, update, delete, merge, archive | — |
agentId | string | Filter by agent identifier | — |
entityName | string | Filter by entity name | — |
since | string | Start time (maps to fromTime) | — |
until | string | End time (maps to toTime) | — |
limit | number | Maximum entries to return | 50 |
Handler Implementation:
audit_query: async (ctx, args) => {
const filter: AuditFilter = {};
if (args.operation !== undefined) {
filter.operation = validateWithSchema(args.operation, z.enum(['create', 'update', 'delete', 'merge', 'archive']), 'Invalid operation');
}
if (args.agentId !== undefined) {
filter.agentId = validateWithSchema(args.agentId, z.string(), 'Invalid agentId');
}
if (args.entityName !== undefined) {
filter.entityName = validateWithSchema(args.entityName, z.string(), 'Invalid entityName');
}
if (args.since !== undefined) {
filter.fromTime = validateWithSchema(args.since, z.string(), 'Invalid since');
}
if (args.until !== undefined) {
filter.toTime = validateWithSchema(args.until, z.string(), 'Invalid until');
}
const limit = args.limit !== undefined
? validateWithSchema(args.limit, z.number().int().min(1).max(1000), 'Invalid limit')
: 50;
const al = getAuditLog(ctx);
let entries = await al.query(filter);
entries = entries.slice(0, limit);
// ...
}
Sources: src/server/toolHandlers.ts
Temporal Validity and Bitemporal Data
Bitemporal Validity
Bitemporal validity tracks two dimensions of time:
- Valid Time: When facts were true in the real world
- Transaction Time: When facts were recorded in the system
This enables accurate historical queries and audit trails that reflect the state of knowledge at any point in time.
Sources: CLAUDE.md
Optimistic Concurrency Control (OCC)
OCC prevents conflicting updates by checking whether the data has changed since it was last read, ensuring data consistency without requiring locks.
Memory Decay and Salience
The decay engine implements time-based importance scoring that automatically reduces the importance of memories over time.
Decay Cycle Tool
The run_decay_cycle tool executes a single pass of time-based importance decay across all agent memories.
{
name: 'run_decay_cycle',
description: 'Run a single pass of time-based importance decay across all agent memories. Returns count of decayed and forgotten memories.',
inputSchema: {
type: 'object',
properties: {},
additionalProperties: false,
},
}
Sources: src/server/toolDefinitions.ts
Decay-Based Memory Queries
| Tool | Purpose | Key Parameters |
|---|---|---|
get_decayed_memories | List memories below decay threshold | threshold (default: 0.1) |
forget_weak_memories | Bulk-delete memories below threshold | threshold, maxCount, dryRun |
Difference from other deletion mechanisms:
forget_memory: Uses content matchingarchive_entities: Uses criteria-based move to archiveforget_weak_memories: Uses decay-based importance scoring
{
name: 'get_decayed_memories',
description: 'List memories whose importance has fallen below a threshold due to time-based decay. Unlike get_stale_entities (which uses freshness timestamps), this uses decay engine importance calculations.',
inputSchema: {
type: 'object',
properties: {
threshold: { type: 'number', description: 'Importance threshold (default: 0.1)' },
},
additionalProperties: false,
},
}
Sources: src/server/toolDefinitions.ts
Artifact Management
Artifacts capture structured outputs from tool executions for later retrieval and analysis.
Artifact Types
| Type | Description |
|---|---|
tool_output | Results from tool invocations |
code_snippet | Generated or analyzed code |
api_response | External API responses |
search_result | Search query results |
file_content | File read contents |
user_input | User-provided prompts |
Artifact Tools
create_artifact: async (ctx, args) => {
const content = validateWithSchema(args.content, z.string().min(1), 'Invalid content');
const toolName = validateWithSchema(args.toolName, z.string().min(1), 'Invalid toolName');
const artifactType = validateWithSchema(
args.artifactType,
z.enum(['tool_output', 'code_snippet', 'api_response', 'search_result', 'file_content', 'user_input']),
'Invalid artifactType'
);
const description = args.description !== undefined
? validateWithSchema(args.description, z.string(), 'Invalid description')
: undefined;
const sessionId = args.sessionId !== undefined
? validateWithSchema(args.sessionId, z.string(), 'Invalid sessionId')
: undefined;
const artifact = await getArtifactManager(ctx).createArtifact({
content, toolName, artifactType, description, sessionId,
});
return formatToolResponse(artifact);
},
get_artifact: async (ctx, args) => {
const ref = validateWithSchema(args.ref, z.string().min(1), 'Invalid ref');
const artifact = await getArtifactManager(ctx).getArtifact(ref);
if (!artifact) {
return formatTextResponse(`Artifact "${ref}" not found`);
}
return formatToolResponse(artifact);
},
list_artifacts: async (ctx, args) => {
const filter: ArtifactFilter = {};
if (args.toolName !== undefined) {
filter.toolName = validateWithSchema(args.toolName, z.string(), 'Invalid toolName');
}
// ...
}
Sources: src/server/toolHandlers.ts
Phase 16 Advanced Features (v12.3.0)
Decision Rationale and ADR Dual-Write
The system supports dual-writing decision rationale in both structured format and Architecture Decision Records (ADR) markdown format.
Sources: CLAUDE.md
Tool Affordance and Observation Pipeline
| Component | Description |
|---|---|
ToolCallObserver | Pipeline for observing and analyzing tool calls |
| Tool Affordance | Metadata describing available tool capabilities |
| Observation Dedup | Prevents duplicate observations in the system |
| Spell Correction | 3 tools for automatic typo correction in queries |
Structured Project Context
12 tools providing structured access to project metadata and context for better decision-making.
Heuristic Guidelines
10 tools implementing rule-based guidance for memory management and retrieval decisions.
Tool Categories Summary
The system organizes its 213 tools across 58 categories, with the advanced features distributed across:
| Category | Feature Type |
|---|---|
| Governance | RBAC, audit logging |
| Compression | Duplicate detection, merge, auto-compress |
| Analytics | Graph stats, integrity validation |
| Decay & Salience | Time-based importance decay |
| Import/Export | Multi-format data handling |
Sources: CLAUDE.md
Storage Considerations
Advanced features persist data in the same storage backends as core entities:
| Storage Type | File Location | Configuration |
|---|---|---|
| JSONL | memory.jsonl, memory-saved-searches.jsonl, memory-tag-aliases.jsonl | Default |
| SQLite | memory.db | Set MEMORY_STORAGE_TYPE=sqlite |
Data files reside in the project root (not dist/), and are gitignored to prevent accidental commits.
Sources: CLAUDE.md
Manager Context Accessors
Advanced features access the core library through the ManagerContext:
| Accessor | Purpose |
|---|---|
ctx.analyticsManager | Graph statistics and validation |
ctx.compressionManager | Duplicate detection and merging |
ctx.archiveManager | Long-term memory archival |
ctx.ioManager | Import/export operations |
ctx.graphTraversal | Advanced graph navigation |
ctx.semanticSearch | Embedding-based search |
ctx.rankedSearch | TF-IDF based search |
ctx.storage | Direct GraphStorage access |
Sources: CLAUDE.md
Testing Coverage
Advanced features are covered by the test suite with the following coverage metrics:
| Metric | Coverage |
|---|---|
| Statements | 80.7% |
| Lines | 81.4% |
| Functions | 79.5% |
| Branches | 68.3% |
Test files are organized in tests/e2e/tools/ with one file per tool group including governance, freshness, and entropy categories.
Sources: CLAUDE.md
Sources: CLAUDE.md
Collaboration and Security
Related topics: Tool Reference, Temporal and Advanced Features
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Related Pages
Related topics: Tool Reference, Temporal and Advanced Features
Collaboration and Security
The memory-mcp system provides a comprehensive suite of collaboration and security features designed to enable multi-agent workflows while maintaining data integrity, access control, and auditability. These features are built on the underlying memoryjs library (v1.14+) and exposed through 213 MCP tools across 58 categories.
Overview
Collaboration and Security in memory-mcp encompasses four primary domains:
| Domain | Purpose | Key Components |
|---|---|---|
| Governance | Access control policies | RBAC, CRUD permissions |
| Audit | Activity tracking | Operation logs, agent attribution |
| Artifacts | Collaboration artifacts | Tool outputs, code snippets, session data |
| Data Integrity | Export security | PII redaction, format validation |
Sources: CLAUDE.md:14-16
Architecture
subgraph "MCP Client Layer"
A[AI Agent 1]
B[AI Agent 2]
C[Human User]
end
subgraph "memory-mcp Server"
D[MCP Protocol Handler]
E[Tool Router]
F[Governance Layer]
end
subgraph "memoryjs Core"
G[EntityManager]
H[RelationManager]
I[AuditManager]
J[ArtifactManager]
end
subgraph "Storage"
K[(JSONL/SQLite)]
end
A --> D
B --> D
C --> D
D --> E
E --> F
F --> G
F --> H
E --> I
E --> J
G --> K
H --> K
I --> K
J --> K
Governance and Access Control
Role-Based Access Control (RBAC)
memory-mcp implements RBAC through the memoryjs library, providing granular control over entity and relation operations. Sources: CLAUDE.md:16
Governance Policy Management
The governance_set_policy tool enables administrators to configure CRUD permissions for the knowledge graph:
governance_set_policy: async (ctx, args) => {
const {
allowCreate = true,
allowUpdate = true,
allowDelete = true
} = args;
const governance = getGovernance(ctx);
await governance.setPolicy({
canCreate: allowCreate ? undefined : () => false,
canUpdate: allowUpdate ? undefined : () => false,
canDelete: allowDelete ? undefined : () => false,
});
return formatTextResponse(
`Governance policy set: canCreate=${allowCreate}, canUpdate=${allowUpdate}, canDelete=${allowDelete}`
);
}
Sources: src/server/toolHandlers.ts:1-20
Governance Tool Definition
| Parameter | Type | Required | Description |
|---|---|---|---|
allowCreate | boolean | No | Enable entity creation (default: true) |
allowUpdate | boolean | No | Enable entity updates (default: true) |
allowDelete | boolean | No | Enable entity deletion (default: true) |
When a permission flag is false, the governance layer installs a deny function that blocks the operation.
Audit System
Audit Log Architecture
The audit system tracks all graph mutations with full attribution:
A[Graph Operation] --> B{AuditManager}
B --> C[Create Entry]
B --> D[Update Entry]
B --> E[Delete Entry]
B --> F[Merge Entry]
B --> G[Archive Entry]
C --> H[AuditStore]
D --> H
E --> H
F --> H
G --> H
Audit Query Handler
The audit_query tool provides filtered access to audit entries:
audit_query: async (ctx, args) => {
const filter: AuditFilter = {};
if (args.operation !== undefined) {
filter.operation = validateWithSchema(
args.operation,
z.enum(['create', 'update', 'delete', 'merge', 'archive']),
'Invalid operation'
);
}
if (args.agentId !== undefined) {
filter.agentId = validateWithSchema(args.agentId, z.string(), 'Invalid agentId');
}
if (args.entityName !== undefined) {
filter.entityName = validateWithSchema(args.entityName, z.string(), 'Invalid entityName');
}
if (args.since !== undefined) {
filter.fromTime = validateWithSchema(args.since, z.string(), 'Invalid since');
}
if (args.until !== undefined) {
filter.toTime = validateWithSchema(args.until, z.string(), 'Invalid until');
}
const limit = args.limit !== undefined
? validateWithSchema(args.limit, z.number().int().min(1).max(1000), 'Invalid limit')
: 50;
const al = getAuditLog(ctx);
let entries = await al.query(filter);
entries = entries.slice(0, limit);
// ...
}
Sources: src/server/toolHandlers.ts:22-57
Audit Query Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
operation | enum | No | Filter by: create, update, delete, merge, archive |
agentId | string | No | Filter by responsible agent |
entityName | string | No | Filter by affected entity |
since | string | No | Start time (ISO 8601) |
until | string | No | End time (ISO 8601) |
limit | number | No | Max results (1-1000, default: 50) |
Supported Audit Operations
The audit system records the complete lifecycle of graph entities:
| Operation | Description |
|---|---|
create | New entity or relation creation |
update | Modification of existing entities |
delete | Permanent removal from graph |
merge | Entity consolidation operations |
archive | Soft deletion with retention |
Artifact Management
Purpose
Artifacts enable collaboration by persisting tool outputs, code snippets, API responses, and user inputs across sessions. This supports multi-agent workflows where one agent's output becomes another agent's context.
Artifact Types
| Type | Use Case |
|---|---|
tool_output | Raw outputs from MCP tool invocations |
code_snippet | Generated or referenced code |
api_response | External API responses |
search_result | Search query results |
file_content | File contents for reference |
user_input | User-provided content |
Sources: src/server/toolHandlers.ts:59-75
Artifact CRUD Operations
#### Create Artifact
create_artifact: async (ctx, args) => {
const content = validateWithSchema(args.content, z.string().min(1), 'Invalid content');
const toolName = validateWithSchema(args.toolName, z.string().min(1), 'Invalid toolName');
const artifactType = validateWithSchema(
args.artifactType,
z.enum(['tool_output', 'code_snippet', 'api_response', 'search_result', 'file_content', 'user_input']),
'Invalid artifactType'
);
const description = args.description !== undefined
? validateWithSchema(args.description, z.string(), 'Invalid description')
: undefined;
const sessionId = args.sessionId !== undefined
? validateWithSchema(args.sessionId, z.string(), 'Invalid sessionId')
: undefined;
const artifact = await getArtifactManager(ctx).createArtifact({
content, toolName, artifactType, description, sessionId,
});
return formatToolResponse(artifact);
}
Sources: src/server/toolHandlers.ts:59-80
#### List Artifacts with Filtering
list_artifacts: async (ctx, args) => {
const filter: ArtifactFilter = {};
if (args.toolName !== undefined) {
filter.toolName = validateWithSchema(args.toolName, z.string(), 'Invalid toolName');
}
if (args.artifactType !== undefined) {
filter.artifactType = validateWithSchema(
args.artifactType,
z.enum(['tool_output', 'code_snippet', 'api_response', 'search_result', 'file_content', 'user_input']),
'Invalid artifactType'
);
}
if (args.since !== undefined) {
const sinceStr = validateWithSchema(args.since, z.string().regex(/^\d{4}-\d{2}-\d{2}(T[\d:.Z+-]+)?$/, 'since must be an ISO 8601 date string'), 'Invalid since');
const sinceDate = new Date(sinceStr);
if (isNaN(sinceDate.getTime())) {
throw new Error(`Invalid since date: "${sinceStr}" is not a valid date`);
}
filter.since = sinceDate;
}
const artifacts = await getArtifactManager(ctx).listArtifacts(
Object.keys(filter).length > 0 ? filter : undefined
);
return formatToolResponse({ artifacts, count: artifacts.length });
}
Sources: src/server/toolHandlers.ts:95-125
Artifact Filter Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
toolName | string | No | Filter by originating tool |
artifactType | enum | No | Filter by artifact type |
since | string | No | ISO 8601 date for time-based filtering |
Data Integrity and Export Security
PII Redaction
When exporting graph data, memory-mcp supports automatic PII redaction to prevent sensitive information leakage:
A[Export Request] --> B{Export Format}
B -->|XML| C[memoryjs η.5.4]
B -->|JSON-LD| C
C --> D{redactPii: true}
D -->|Yes| E[Redaction Engine]
D -->|No| F[Raw Export]
E --> F
F --> G[Exported File]
Sources: CLAUDE.md:34-35
Export Configuration
| Option | Type | Description | Version |
|---|---|---|---|
redactPii | boolean | Enable PII redaction on export | memoryjs η.6.3+ |
| Export formats | enum | xml, json-ld | memoryjs η.5.4+ |
Compression for Context
The standalone compress-for-context tool provides CTON (Compact Textual Object Notation) compression for managing context windows during multi-agent collaboration:
# Single file compression
node compress-for-context.js data.json
# Aggressive compression for maximum context savings
node compress-for-context.js README.md -l aggressive
# Batch processing
node compress-for-context.js -b -p "*.json" ./src
Sources: tools/compress-for-context/compress-for-context.ts:1-25
Security Architecture
subgraph "Security Layers"
A[Authentication]
B[Authorization]
C[Audit Logging]
D[Data Encryption]
end
subgraph "Access Control Points"
E[governance_set_policy]
F[RBAC via memoryjs]
G[Operation Validation]
end
subgraph "Audit Trail"
H[Operation Tracking]
I[Agent Attribution]
J[Time-based Queries]
end
A --> B
B --> C
C --> D
E --> F
F --> G
G --> H
H --> I
I --> J
Environment Variables for Security
| Variable | Description | Default | Security Impact |
|---|---|---|---|
MEMORY_FILE_PATH | Storage file location | memory.jsonl | Data isolation |
MEMORY_STORAGE_TYPE | Storage backend | jsonl | Persistence security |
MEMORY_EMBEDDING_PROVIDER | Embedding service | none | External data exposure |
MEMORY_OPENAI_API_KEY | API authentication | — | External service auth |
Sources: CLAUDE.md:58-64
Testing Coverage
The collaboration and security features are validated through the test suite:
| Test Category | Location | Coverage Focus |
|---|---|---|
| Integration | tests/integration/ | MCP server lifecycle, security hooks |
| E2E | tests/e2e/tools/ | Per-tool handler validation |
| Governance | tests/e2e/tools/governance.test.ts | Policy enforcement |
| Audit | tests/e2e/tools/audit.test.ts | Log integrity |
| Artifacts | tests/e2e/tools/artifact.test.ts | CRUD operations |
Sources: CLAUDE.md:46-50, docs/architecture/TEST_COVERAGE.md
Best Practices for Multi-Agent Collaboration
- Configure Governance Early: Set appropriate
allowCreate,allowUpdate, andallowDeletepolicies before enabling multi-agent access.
- Enable Audit Logging: Use
audit_querywith appropriate filters to monitor agent activity and detect anomalies.
- Use Artifacts for Context: Store intermediate results as artifacts with descriptive
sessionIdvalues to enable context sharing.
- Enable PII Redaction: Set
redactPii: truewhen exporting data containing sensitive information.
- Rotate Storage Files: Implement periodic rotation of
memory.jsonlormemory.dbwith archival to maintain audit history.
Pull Request Security Requirements
When contributing security-related changes:
- Title: Clear, descriptive summary of the security impact
- Description: Document what changed, why, and potential security implications
- Tests: Include test results demonstrating security controls
- Documentation: Update relevant security documentation
- Backward Compatibility: Confirm no breaking security changes
Sources: CONTRIBUTING.md:37-44
Sources: CLAUDE.md:14-16
Development Guide
Related topics: Getting Started
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Related Pages
Related topics: Getting Started
Development Guide
This guide provides comprehensive information for developers contributing to the memory-mcp project. It covers project setup, architecture, coding standards, testing practices, and the development workflow.
Project Overview
memory-mcp is a Model Context Protocol (MCP) server that provides memory and knowledge graph capabilities. The server exposes 213 tools across 58 categories for managing entities, relations, observations, searches, tags, hierarchies, and analytics.
npm Package: @danielsimonjr/memory-mcp Core Dependency: @danielsimonjr/memoryjs (currently ^2.1.0)
Sources: CLAUDE.md:1
Architecture Overview
Layered Architecture
The project follows a layered architecture where memory-mcp serves as the MCP interface layer on top of the memoryjs core library.
graph TD
subgraph "memory-mcp (this repo)"
A["src/index.ts"] --> B["src/server/MCPServer.ts"]
B --> C["src/server/toolDefs.ts"]
B --> D["src/server/toolHandlers.ts"]
C --> E["Tool Definitions"]
D --> F["Tool Handlers"]
end
subgraph "@danielsimonjr/memoryjs (npm dependency)"
G["ManagerContext"]
G --> H["EntityManager"]
G --> I["RelationManager"]
G --> J["ObservationManager"]
G --> K["SearchManager"]
G --> L["TagManager"]
G --> M["HierarchyManager"]
G --> N["AnalyticsManager"]
G --> O["GraphStorage/SQLiteStorage"]
end
F -->|imports| GSources: CLAUDE.md:15-25
Key Source Files
| File | Purpose |
|---|---|
src/index.ts | Entry point, re-exports ManagerContext as KnowledgeGraphManager |
src/server/MCPServer.ts | MCP server implementation |
src/server/toolDefs.ts | JSON schema definitions for all 213 tools |
src/server/toolHandlers.ts | Implementation handlers for each tool |
Sources: CLAUDE.md:28-31
Project Setup
Prerequisites
- Node.js (compatible with ES2022)
- npm
Installation
cd c:/mcp-servers/memory-mcp
npm install
The prepare script automatically runs npm run build on install, so the dist/ directory is rebuilt automatically.
Sources: CLAUDE.md:54
TypeScript Configuration
The project uses ES2022 target with Node16 module resolution:
{
"compilerOptions": {
"target": "ES2022",
"module": "Node16",
"moduleResolution": "Node16",
"outDir": "./dist",
"rootDir": "./src"
},
"include": ["src/**/*"]
}
Sources: tsconfig.json
Build Scripts
| Script | Purpose |
|---|---|
npm run build | Compile TypeScript to dist/ |
npm run typecheck | Run TypeScript type checking |
npm run test | Run all tests |
npm run test:unit | Run unit tests only |
npm run test:e2e | Run end-to-end tests |
npm run docs:deps | Generate dependency graph documentation |
Sources: package.json
Environment Configuration
The MCP server uses environment variables for configuration:
| Variable | Description | Default |
|---|---|---|
MEMORY_FILE_PATH | Path to storage file | memory.jsonl (cwd) |
MEMORY_STORAGE_TYPE | jsonl or sqlite | jsonl |
MEMORY_EMBEDDING_PROVIDER | openai, local, or none | none |
MEMORY_OPENAI_API_KEY | Required if provider is openai | — |
MEMORY_EMBEDDING_MODEL | Embedding model name | text-embedding-3-small / Xenova/all-MiniLM-L6-v2 |
MEMORY_AUTO_INDEX_EMBEDDINGS | Auto-index on entity creation | false |
Sources: CLAUDE.md:60-67
Storage
Data files live in the project root (not dist/):
- JSONL:
memory.jsonl,memory-saved-searches.jsonl,memory-tag-aliases.jsonl - SQLite:
memory.db(setMEMORY_STORAGE_TYPE=sqlite)
Sources: CLAUDE.md:37-42
Code Style Guidelines
TypeScript Best Practices
- Follow TypeScript best practices
- Use meaningful variable names
- Add JSDoc comments for public methods
- Keep functions focused and small
- Maintain consistent indentation (2 spaces)
Sources: CONTRIBUTING.md:21-25
ManagerContext Access Pattern
When implementing tool handlers, use the ManagerContext accessors to access various managers:
| Accessor | Purpose |
|---|---|
ctx.entityManager | Core CRUD for graph nodes |
ctx.relationManager | Directed edges between entities |
ctx.observationManager | Facts attached to entities |
ctx.searchManager | Search operations |
ctx.tagManager | Tag management |
ctx.hierarchyManager | Parent-child trees |
ctx.analyticsManager | Graph stats and validation |
ctx.compressionManager | Duplicate detection, merge |
ctx.archiveManager | Archive operations |
ctx.ioManager | Import/Export operations |
ctx.graphTraversal | BFS/DFS path finding |
ctx.semanticSearch | Embedding similarity search |
ctx.rankedSearch | TF-IDF ranked search |
ctx.storage | Direct GraphStorage access |
Sources: CLAUDE.md:53-55
Testing Guidelines
Test Structure
The project has 26 test files with 665 tests, achieving approximately 81% statement coverage.
| Tier | Location | Purpose |
|---|---|---|
| Unit | tests/unit/ | Isolated module tests (e.g., response compressor) |
| Integration | tests/integration/ | MCP server lifecycle tests |
| E2E | tests/e2e/tools/ | Per-category tool tests |
| Root | tests/ | Core graph operations and storage path handling |
Sources: CLAUDE.md:71-80
Test Coverage
Coverage verification is done via coverage/coverage-summary.json:
| Metric | Coverage |
|---|---|
| Statements | 80.7% |
| Lines | 81.4% |
| Functions | 79.5% |
| Branches | 68.3% |
Sources: CLAUDE.md:71-72
Vitest Configuration
Tests use Vitest with custom reporting. Configuration file: vitest.config.ts. Coverage targets src/**/*.ts (excludes index barrel files).
Sources: CLAUDE.md:81-82
Testing Best Practices
- Test new features thoroughly
- Include edge cases
- Test backward compatibility
- Verify export formats are valid
- Test with empty graphs and large graphs
Sources: CONTRIBUTING.md:14-18
Testing Notes
- Storage files: JSONL and SQLite files created during tests are in the project root but excluded in
.gitignore— they won't appear ingit status. - Error handling in dispatch:
handleToolCallcatches exceptions from handlers and returns them as MCP-formatted error responses. Check MCP responseisErrorfield when debugging.
Sources: CLAUDE.md:84-87
Adding a New Tool
Step-by-Step Process
graph LR
A["1. Add schema to<br/>toolDefinitions.ts"] --> B["2. Add handler to<br/>toolHandlers.ts"]
B --> C["3. Add e2e test in<br/>tests/e2e/tools/"]
C --> D["4. Update documentation"]Tool Handler Pattern
Handlers follow this pattern:
- Validate arguments with schema validation
- Call manager method via appropriate accessor
- Return formatted response
const TOOL_HANDLERS = {
tool_name: async (ctx, args) => {
// 1. Validate arguments
const param = validateWithSchema(args.param, z.string().min(1), 'Invalid param');
// 2. Call manager method
const result = await getManager(ctx).method(param);
// 3. Return formatted response
return formatToolResponse(result);
},
};
If the response can be large, wrap with withCompression().
Sources: CLAUDE.md:47-52
Tool Categories Overview
The project exposes 213 tools across 58 categories:
| Category | Count | Key Purpose |
|---|---|---|
| Entity | 4 | Core CRUD for graph nodes |
| Relation | 2 | Directed edges between entities |
| Observation | 3 | Facts attached to entities, with normalization |
| Search | 7 | Basic, ranked (TF-IDF), boolean, fuzzy, auto-select |
| Intelligent Search | 3 | Hybrid multi-layer, query analysis, reflection-based |
| Semantic Search | 3 | Embedding similarity via OpenAI or local models |
| Saved Searches | 5 | Store and re-execute frequent queries |
| Tag Management | 6 | Tags, bulk ops, importance scores |
| Tag Aliases | 5 | Tag synonym/alias management |
| Hierarchy | 9 | Parent-child trees, subtree traversal |
| Graph Algorithms | 4 | BFS/DFS path finding, centrality, connected components |
| Analytics | 2 | Graph stats and integrity validation |
| Compression | 4 | Duplicate detection, merge, auto-compress, archive |
| Import/Export | 2 | 7 export formats (xml, json-ld, etc.) |
Sources: CLAUDE.md:33-46
Documentation Guidelines
When adding features, update the following documentation:
| File | Purpose |
|---|---|
README.md | Update with new tools/functionality |
CHANGELOG.md | Document changes |
WORKFLOW.md | Update if development process changes |
| Usage examples | Include practical examples |
Sources: CONTRIBUTING.md:30-34
Pull Request Process
PR Checklist
| Step | Requirement |
|---|---|
| Title | Clear, descriptive summary |
| Description | What changed, why it changed, how to test it |
| Tests | Include test results |
| Documentation | Update relevant docs |
| Backward Compatibility | Confirm no breaking changes |
Sources: CONTRIBUTING.md:36-45
PR Workflow
# 1. Create feature branch
git checkout -b feature/your-feature-name
# 2. Make changes and commit
cd c:/mcp-servers/memory-mcp
git add .
git commit -m "Description of your changes"
# 3. Push and create PR
git push origin feature/your-feature-name
# Create PR on GitHub
Sources: CONTRIBUTING.md:1-8
Standalone Tools
The tools/ directory contains standalone utilities, each with its own package.json and buildable to Windows exes via pkg:
| Tool | Purpose |
|---|---|
chunking-for-files | Split/merge large files for context-limited editing |
compress-for-context | CTON compression for LLM context windows |
create-dependency-graph | Generate TypeScript project dependency graphs |
migrate-from-jsonl-to-sqlite | Convert between JSONL and SQLite formats |
Sources: CLAUDE.md:44-51
Publishing to npm
# Token with "bypass 2FA" required — classic tokens are revoked
npm config set //registry.npmjs.org/:_authToken=$(cat c:\mcp-servers\npm_key.txt)
npm publish --access public
Important Notes:
- The
preparescript auto-builds, so separatenpm run buildis not needed before publish - Always bump version in
package.jsonbefore publishing - Verify tarball contents before publishing
Sources: CLAUDE.md:52-58
Verify Tarball Contents
npm pack --dry-run 2>&1 | grep -E "jsonl|\.db|total files|package size"
Sources: CLAUDE.md:59
Reporting Issues
| Type | Action |
|---|---|
| Bug Reports | Open an issue with detailed reproduction steps |
| Feature Requests | Open an issue describing the use case |
| Questions | Check existing issues or open a new one |
This project follows the Model Context Protocol community guidelines.
Sources: CONTRIBUTING.md:60-65
License
By contributing, you agree that your contributions will be licensed under the MIT License.
Sources: CONTRIBUTING.md:68-70
Sources: CLAUDE.md:1
Doramagic Pitfall Log
Source-linked risks stay visible on the manual page so the preview does not read like a recommendation.
The project should not be treated as fully validated until this signal is reviewed.
Users cannot judge support quality until recent activity, releases, and issue response are checked.
The project may affect permissions, credentials, data exposure, or host boundaries.
The project may affect permissions, credentials, data exposure, or host boundaries.
Doramagic Pitfall Log
Doramagic extracted 6 source-linked risk signals. Review them before installing or handing real data to the project.
1. Capability assumption: README/documentation is current enough for a first validation pass.
- Severity: medium
- Finding: README/documentation is current enough for a first validation pass.
- User impact: The project should not be treated as fully validated until this signal is reviewed.
- Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
- Evidence: capability.assumptions | github_repo:1093926095 | https://github.com/danielsimonjr/memory-mcp | README/documentation is current enough for a first validation pass.
2. Maintenance risk: Maintainer activity is unknown
- Severity: medium
- Finding: Maintenance risk is backed by a source signal: Maintainer activity is unknown. Treat it as a review item until the current version is checked.
- User impact: Users cannot judge support quality until recent activity, releases, and issue response are checked.
- Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
- Evidence: evidence.maintainer_signals | github_repo:1093926095 | https://github.com/danielsimonjr/memory-mcp | last_activity_observed missing
3. Security or permission risk: no_demo
- Severity: medium
- Finding: no_demo
- User impact: The project may affect permissions, credentials, data exposure, or host boundaries.
- Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
- Evidence: downstream_validation.risk_items | github_repo:1093926095 | https://github.com/danielsimonjr/memory-mcp | no_demo; severity=medium
4. Security or permission risk: no_demo
- Severity: medium
- Finding: no_demo
- User impact: The project may affect permissions, credentials, data exposure, or host boundaries.
- Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
- Evidence: risks.scoring_risks | github_repo:1093926095 | https://github.com/danielsimonjr/memory-mcp | no_demo; severity=medium
5. Maintenance risk: issue_or_pr_quality=unknown
- Severity: low
- Finding: issue_or_pr_quality=unknown。
- User impact: Users cannot judge support quality until recent activity, releases, and issue response are checked.
- Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
- Evidence: evidence.maintainer_signals | github_repo:1093926095 | https://github.com/danielsimonjr/memory-mcp | issue_or_pr_quality=unknown
6. Maintenance risk: release_recency=unknown
- Severity: low
- Finding: release_recency=unknown。
- User impact: Users cannot judge support quality until recent activity, releases, and issue response are checked.
- Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
- Evidence: evidence.maintainer_signals | github_repo:1093926095 | https://github.com/danielsimonjr/memory-mcp | release_recency=unknown
Source: Doramagic discovery, validation, and Project Pack records
Community Discussion Evidence
These external discussion links are review inputs, not standalone proof that the project is production-ready.
Count of project-level external discussion links exposed on this manual page.
Open the linked issues or discussions before treating the pack as ready for your environment.
Community Discussion Evidence
Doramagic exposes project-level community discussion separately from official documentation. Review these links before using memory-mcp with real data or production workflows.
- MCP server that indexes codebases into a knowledge graph - Reddit - reddit / searxng_indexed
- README/documentation is current enough for a first validation pass. - GitHub / issue
Source: Project Pack community evidence and pitfall evidence