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

Section Related Pages

Continue reading this section for the full explanation and source context.

Section From npm (Recommended for Users)

Continue reading this section for the full explanation and source context.

Section From Source (Recommended for Development)

Continue reading this section for the full explanation and source context.

Section Verify Installation

Continue reading this section for the full explanation and source context.

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:

RequirementMinimum VersionNotes
Node.js18.0+ES2022 features required
npm9.0+For package management
SQLite3.39+Only if using SQLite storage
TypeScript5.0+For development work

Sources: CLAUDE.md:20

Installation

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

# 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:

VariableDefaultDescription
MEMORY_STORAGE_TYPEjsonlStorage backend: jsonl or sqlite
MEMORY_DB_PATHmemory.dbPath to SQLite database (when using SQLite)
MEMORY_JSONL_PATHmemory.jsonlPath 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

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 --> E

Sources: CLAUDE.md:4-13

Entry Points

Entry PointPurpose
dist/index.jsMain build output
mcp-server-memoryCLI binary (defined in package.json bin)
src/index.tsSource entry point

Sources: CLAUDE.md:17

Manager Accessors

The ManagerContext provides access to all core managers:

AccessorPurpose
ctx.entityManagerCore CRUD for graph nodes
ctx.relationManagerDirected edges between entities
ctx.observationManagerFacts attached to entities
ctx.searchManagerBasic, ranked, boolean, fuzzy search
ctx.semanticSearchEmbedding similarity via OpenAI or local models
ctx.tagManagerTag management with importance scores
ctx.hierarchyManagerParent-child trees, subtree traversal
ctx.compressionManagerDuplicate detection, merge, archive
ctx.graphTraversalBFS/DFS path finding, centrality
ctx.analyticsManagerGraph stats and integrity validation
ctx.storageDirect GraphStorage access

Sources: CLAUDE.md:1

Tool Categories Overview

Memory MCP exposes tools organized into 58 categories with 213 total tools:

CategoryCountKey Purpose
Entity4Core CRUD for graph nodes
Relation2Directed edges between entities
Observation3Facts attached to entities
Search7Basic, ranked, boolean, fuzzy
Semantic Search3Embedding similarity
Intelligent Search3Hybrid multi-layer, query analysis
Saved Searches5Store and re-execute queries
Tag Management6Tags, bulk ops, importance scores
Tag Aliases5Tag synonym/alias management
Hierarchy9Parent-child trees, subtree traversal
Graph Algorithms4BFS/DFS, centrality, connected components
Analytics2Graph stats and integrity validation
Compression4Dedup, merge, auto-compress, archive
Import/Export27 export formats
Decay & Salience3Time-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:

ToolPurpose
chunking-for-filesSplit/merge large files for context-limited editing
compress-for-contextCTON compression for LLM context windows
create-dependency-graphGenerate TypeScript project dependency graphs
migrate-from-jsonl-to-sqliteConvert 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.json bin)
  • 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

ArgumentShortDescription
--from <path>-fSource file path (JSONL or SQLite)
--to <path>-tTarget file path (JSONL or SQLite)
--verbose-vShow detailed progress
--help-hShow 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

  1. Title: Clear, descriptive summary
  2. Description: What changed, why it changed, how to test it
  3. Tests: Include test results
  4. Documentation: Update relevant docs
  5. 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:

  1. Explore the Tool Categories to understand available operations
  2. Review the Architecture Overview for system design
  3. Set up your preferred Storage Configuration
  4. Run the standalone Dependency Graph Tool to visualize project structure
  5. Consult the project's issues for feature requests or bug reports

Sources: CLAUDE.md:20

Project Structure

Related topics: Architecture Overview, Development Guide

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Layered Architecture

Continue reading this section for the full explanation and source context.

Section Accessor Hierarchy

Continue reading this section for the full explanation and source context.

Section Entry Point (src/index.ts)

Continue reading this section for the full explanation and source context.

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 --> E

Sources: CLAUDE.md:layered-architecture

Accessor Hierarchy

The ManagerContext provides lazy-initialized accessors for all subsystems:

AccessorPurpose
ctx.entityManagerGraph node CRUD operations
ctx.relationManagerDirected edge management
ctx.observationManagerFacts attached to entities
ctx.searchManagerBasic, ranked, boolean, fuzzy search
ctx.tagManagerTag CRUD and bulk operations
ctx.hierarchyManagerParent-child tree structures
ctx.analyticsManagerGraph statistics and validation
ctx.compressionManagerDuplicate detection and merging
ctx.archiveManagerHistorical data archival
ctx.ioManagerImport/export operations
ctx.graphTraversalBFS/DFS path finding
ctx.semanticSearchEmbedding similarity search
ctx.rankedSearchTF-IDF ranking
ctx.storageDirect 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 ManagerContext as KnowledgeGraphManager)
  • 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: handleToolCall catches exceptions from handlers and returns them as MCP-formatted error responses (checks isError field 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:

CategoryCountDescription
Entity4Core CRUD for graph nodes
Relation2Directed edges between entities
Observation3Facts attached to entities
Search7Basic, ranked, boolean, fuzzy search
Intelligent Search3Hybrid multi-layer search
Semantic Search3Embedding-based similarity
Saved Searches5Stored query execution
Tag Management6Tag CRUD and bulk operations
Tag Aliases5Tag synonym management
Hierarchy9Tree structures and traversal
Graph Algorithms4Path finding, centrality
Analytics2Stats and validation
Compression4Duplicate detection, merge
Import/Export2+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:

  1. Validates input arguments using Zod schemas
  2. Accesses appropriate ManagerContext accessors
  3. 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.

OutputDescription
docs/architecture/DEPENDENCY_GRAPH.mdHuman-readable Markdown documentation
docs/architecture/dependency-graph.jsonMachine-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.

OptionDescription
-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, --batchBatch mode for multiple files
-d, --decompressRestore compressed file

chunking-for-files

Splits large files into editable sections for context-limited editing.

Commands:

  • chunker split <file> - Split file into chunks
  • chunker merge <manifest.json> - Merge chunks back
  • chunker 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 TypeFileEnvironment Variable
JSONL (default)memory.jsonl, memory-saved-searches.jsonl, memory-tag-aliases.jsonlMEMORY_STORAGE_TYPE=jsonl
SQLitememory.dbMEMORY_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

ArtifactDescription
dist/index.jsMain build output
mcp-server-memoryCLI 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

GuidelineStandard
LanguageTypeScript best practices
Indentation2 spaces
DocumentationJSDoc comments for public methods
Function designSmall, focused functions
NamingMeaningful 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

FileWhen to Update
README.mdNew tools/functionality
CHANGELOG.mdVersion changes
WORKFLOW.mdDevelopment process changes

File Naming Conventions

PatternExamplePurpose
*.tsMCPServer.ts, toolHandlers.tsTypeScript source files
*.mdDEPENDENCY_GRAPH.mdGenerated documentation
*.jsondependency-graph.jsonMachine-readable data
*.compactoutput.compactCompressed 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

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Entry Point (src/index.ts)

Continue reading this section for the full explanation and source context.

Section MCPServer (src/server/MCPServer.ts)

Continue reading this section for the full explanation and source context.

Section ManagerContext (memoryjs)

Continue reading this section for the full explanation and source context.

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:#fff3e0

Sources: 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.

ManagerPurpose
entityManagerCore CRUD operations for graph nodes
relationManagerDirected edges between entities
observationManagerFacts attached to entities with normalization
searchManagerBasic, ranked, boolean, fuzzy, and auto-select search
tagManagerTag operations, bulk operations, importance scores
hierarchyManagerParent-child trees, subtree traversal
analyticsManagerGraph statistics and integrity validation
compressionManagerDuplicate detection, merge, auto-compress, archive
archiveManagerLong-term storage management
ioManagerImport/export operations
graphTraversalGraph algorithm utilities
semanticSearchEmbedding-based similarity search
rankedSearchTF-IDF weighted search
storageDirect 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:

CategoryCountKey Purpose
Entity4Core CRUD for graph nodes
Relation2Directed edges between entities
Observation3Facts attached to entities, with normalization
Search7Basic, ranked, boolean, fuzzy, auto-select
Intelligent Search3Hybrid multi-layer, query analysis, reflection-based
Semantic Search3Embedding similarity via OpenAI or local models
Saved Searches5Store and re-execute frequent queries
Tag Management6Tags, bulk ops, importance scores
Tag Aliases5Tag synonym/alias management
Hierarchy9Parent-child trees, subtree traversal
Graph Algorithms4BFS/DFS path finding, centrality, connected components
Analytics2Graph stats and integrity validation
Compression4Duplicate detection, merge, auto-compress, archive
Import/Export27 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:

FilePurpose
memory.jsonlMain knowledge graph data
memory-saved-searches.jsonlSaved search definitions
memory-tag-aliases.jsonlTag 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 PointDescription
dist/index.jsBuilt output for npm distribution
mcp-server-memoryCLI binary defined in package.json bin field
src/index.tsSource 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 Response

Standalone Tools

The tools/ directory contains standalone utilities with their own package.json files, buildable to Windows executables via pkg:

ToolPurpose
chunking-for-filesSplit/merge large files for context-limited editing
compress-for-contextCTON compression for LLM context windows
create-dependency-graphGenerate TypeScript project dependency graphs
migrate-from-jsonl-to-sqliteConvert between JSONL and SQLite formats

Sources: CLAUDE.md:Standalone Tools

Version History

The architecture has evolved through multiple phases:

PhaseVersionKey Changes
Phase 13Initial5 TypeScript source files, memoryjs v2.1.0+
Phase 15v12.2.023 tools for memoryjs v1.14+ features (bitemporal, OCC, RBAC)
Phase 16v12.3.053 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

Section Related Pages

Continue reading this section for the full explanation and source context.

Section KnowledgeGraph Structure

Continue reading this section for the full explanation and source context.

Section Entity Model

Continue reading this section for the full explanation and source context.

Section Relation Model

Continue reading this section for the full explanation and source context.

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:#e8f5e9

Data Models

KnowledgeGraph Structure

The knowledge graph comprises two primary collections that together represent the complete state of the memory system.

CollectionTypeDescription
entitiesEntity[]Individual memory items with observations and metadata
relationsRelation[]Connections between entities defining semantic relationships

Entity Model

FieldTypeRequiredDescription
namestringYesUnique identifier for the entity
entityTypestringYesClassification category (e.g., "person", "concept", "task")
observationsstring[]YesArray of recorded facts or data points
createdAtstringNoISO timestamp of entity creation
lastModifiedstringNoISO timestamp of last modification
tagsstring[]NoOptional categorization labels
importancenumberNoPriority score (null if unspecified)
parentIdstringNoHierarchical parent reference

Sources: tools/migrate-from-jsonl-to-sqlite/migrate-from-jsonl-to-sqlite.ts:50-58

Relation Model

FieldTypeRequiredDescription
fromstringYesSource entity name or ID
tostringYesTarget entity name or ID
relationTypestringYesSemantic relationship type (e.g., "related_to", "part_of")
createdAtstringNoISO timestamp of relation creation
lastModifiedstringNoISO 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):

FilePurpose
memory.jsonlPrimary knowledge graph storage
memory-saved-searches.jsonlStored search configurations
memory-tag-aliases.jsonlTag 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):

FilePurpose
memory.dbPrimary SQLite database

Sources: CLAUDE.md:6

SQLite Backend Features:

FeatureDescription
FTS5 IndexAutomatic full-text search indexing for fast entity lookups
WAL ModeWrite-Ahead Logging for improved concurrent read/write performance
Atomic TransactionsEnsures data integrity during write operations
Native PerformanceUses 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

VariableValuesDefaultDescription
MEMORY_STORAGE_TYPEjsonl, sqlitejsonlDetermines which storage backend to use
MEMORY_FILE_PATHValid file pathmemory.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

FormatExtensionsDetection Logic
JSONL.jsonl, .jsonExtension-based detection
SQLite.db, .sqlite, .sqlite3Extension-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

ArgumentShortDescription
--from-fSource file path (JSONL or SQLite)
--to-tTarget file path (JSONL or SQLite)
--verbose-vShow detailed progress information
--help-hDisplay 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 --> L

Migration Notes and Limitations

AspectBehavior
Target CreationTarget file is created if it doesn't exist
Existing TargetsTarget file will be overwritten if it exists
Data IntegrityAtomic transactions ensure no data loss during migration
Timestamp HandlingMissing createdAt or lastModified fields are populated with migration timestamp and a warning is displayed
Saved SearchesNOT migrated (stored in separate memory-saved-searches.jsonl file)
Tag AliasesNOT migrated (stored in separate memory-tag-aliases.jsonl file)
Large DatasetsRecommended 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.

CriteriaJSONLSQLite
Dataset Size< 1,000 entities10,000+ entities
Transaction NeedsSimple append operationsACID transactions required
Data InspectionHuman-readable preferredStructured queries needed
Concurrent AccessSingle processMultiple readers/writers
DebuggingDirect file inspectionRequires SQLite tools
PerformanceSufficient for small datasetsOptimized 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

FormatExport Considerations
JSONL/JSONFull entity data visible in plain text
SQLiteDatabase contents require database tools to inspect
CSV/GraphML ExportsFull 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.

DocumentDescription
CLAUDE.mdProject architecture and development guidelines
tools/migrate-from-jsonl-to-sqlite/README.mdDetailed migration tool documentation
SECURITY.mdSecurity 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

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Entity Manager

Continue reading this section for the full explanation and source context.

Section Relation Manager

Continue reading this section for the full explanation and source context.

Section Observation Manager

Continue reading this section for the full explanation and source context.

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 --> JL

Sources: CLAUDE.md:layered-architecture

Core Components

Entity Manager

Entities are the primary nodes in the knowledge graph. The EntityManager provides core CRUD operations:

OperationTool NameDescription
Createcreate_entityAdd a new entity to the graph
Readget_entityRetrieve entity by name or ref
Updateupdate_entityModify entity properties
Deletedelete_entitiesRemove entity from graph
Listlist_entitiesGet entities with optional filters

Sources: toolDefinitions.ts:entity-tools

Entity Properties:

  • name (required): Unique identifier
  • memoryType: Classification type (default: semantic)
  • confidence: Trust score (0.0 - 1.0, default: 0.8)
  • tags: Array of associated tags
  • observations: Attached factual metadata
  • createdAt / updatedAt: Temporal timestamps
  • accessCount: Usage tracking
  • confirmationCount: 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]
OperationTool NameDescription
Createcreate_relationsBatch create directed edges
Deletedelete_relationsRemove relations by criteria
Invalidateinvalidate_relationBitemporal validity - end a relation
Chainget_entity_chainTraverse 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:

PropertyDescription
contentThe factual statement
normalizedCanonical form for comparison
sourceOrigin of the observation
confirmedVerification status
attachedAtTimestamp 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:

CategoryCountPurpose
Entity4Core CRUD for graph nodes
Relation2Directed edges between entities
Observation3Facts attached to entities
Search7Query graph data
Intelligent Search3Advanced query processing
Semantic Search3Embedding-based retrieval
Tag Management6Entity categorization
Hierarchy9Parent-child tree structures
Graph Algorithms4Path finding, centrality
Analytics2Graph statistics
Compression4Deduplication, 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 --> T2

The 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:

ToolPurpose
set_entity_parentAssign parent entity
get_childrenDirect descendants
get_parentDirect ancestor
get_ancestorsFull ancestry path
get_descendantsAll descendants (recursive)
get_subtreeSubtree 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:

  1. Basic: Exact and substring matching
  2. Ranked (TF-IDF): Term frequency-inverse document frequency
  3. Fuzzy: Edit distance tolerance
  4. Semantic: Embedding similarity (OpenAI or local models)
  5. Intelligent: Multi-layer hybrid with query analysis

Sources: CLAUDE.md:search

Environment Configuration

VariableDescriptionDefault
MEMORY_FILE_PATHStorage file pathmemory.jsonl
MEMORY_STORAGE_TYPEBackend typejsonl
MEMORY_EMBEDDING_PROVIDEREmbedding servicenone
MEMORY_OPENAI_API_KEYAPI key for OpenAI
MEMORY_EMBEDDING_MODELModel nametext-embedding-3-small
MEMORY_AUTO_INDEX_EMBEDDINGSAuto-index on createfalse

Sources: CLAUDE.md:env-vars

API Entry Points

EndpointDescription
dist/index.jsBuild output entry
src/index.tsSource entry (exports ManagerContext as KnowledgeGraphManager)
mcp-server-memoryCLI binary

Sources: package.json:exports

Adding Custom Tools

To extend the ERO Model with new functionality:

  1. Define Schema in toolDefinitions.ts:
{
  name: 'new_tool',
  description: 'Tool description',
  inputSchema: {
    type: 'object',
    properties: { /* parameters */ },
    required: ['param1']
  }
}
  1. Implement Handler in toolHandlers.ts:
new_tool: async (ctx, args) => {
  // Validate arguments
  // Call manager methods
  // Return formatted response
}
  1. 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

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Layered Design

Continue reading this section for the full explanation and source context.

Section Tool Execution Flow

Continue reading this section for the full explanation and source context.

Section Example: Artifact Tool Definition

Continue reading this section for the full explanation and source context.

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]
    end

The 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 result

Error 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.

CategoryCountKey Purpose
Entity4Core CRUD for graph nodes
Relation2Directed edges between entities
Observation3Facts attached to entities, with normalization
Search7Basic, ranked (TF-IDF), boolean, fuzzy, auto-select
Intelligent Search3Hybrid multi-layer, query analysis, reflection-based
Semantic Search3Embedding similarity via OpenAI or local models
Saved Searches5Store and re-execute frequent queries
Tag Management6Tags, bulk ops, importance scores
Tag Aliases5Tag synonym/alias management
Hierarchy9Parent-child trees, subtree traversal
Graph Algorithms4BFS/DFS path finding, centrality, connected components
Analytics2Graph stats and integrity validation
Compression4Duplicate detection, merge, auto-compress, archive
Import/Export27 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 FunctionUsage
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.

ParameterTypeRequiredDescription
contentstringYesArtifact content stored as an entity observation
toolNamestringYesName of the tool or source that produced this artifact
artifactTypeenumYesCategory: tool_output, code_snippet, api_response, search_result, file_content, user_input
descriptionstringNoHuman-readable description
sessionIdstringNoSession 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.

ParameterTypeRequiredDescription
refstringYesStable 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.

ParameterTypeRequiredDescription
toolNamestringNoFilter by originating tool
artifactTypeenumNoFilter by artifact category
sincestringNoISO 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.

ParameterTypeRequiredDescription
(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.

ParameterTypeRequiredDescription
thresholdnumberNoImportance 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.

ParameterTypeRequiredDescription
thresholdnumberNoImportance threshold below which to forget
maxCountnumberNoMaximum number of memories to forget
dryRunbooleanNoIf 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.

ParameterTypeRequiredDescription
operationenumNoFilter by: create, update, delete, merge, archive
agentIdstringNoFilter by agent identifier
entityNamestringNoFilter by entity name
sincestringNoStart time (ISO 8601)
untilstringNoEnd time (ISO 8601)
limitnumberNoMaximum 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/]
  1. Add schema to toolDefinitions.ts — Define the tool name, description, and input schema in the appropriate category section
  2. Add handler to toolHandlers.ts — Register handler in the TOOL_HANDLERS registry with the pattern: validate args → call manager method → return formatted response
  3. 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:

VariableDescriptionDefault
MEMORY_FILE_PATHPath to storage filememory.jsonl (cwd)
MEMORY_STORAGE_TYPEjsonl or sqlitejsonl
MEMORY_EMBEDDING_PROVIDERopenai, local, or nonenone
MEMORY_OPENAI_API_KEYRequired if provider is openai
MEMORY_EMBEDDING_MODELEmbedding model nametext-embedding-3-small / Xenova/all-MiniLM-L6-v2
MEMORY_AUTO_INDEX_EMBEDDINGSAuto-index on entity creationfalse

Sources: CLAUDE.md:66-73

ManagerContext Accessors

Handlers access underlying functionality through the ManagerContext:

AccessorPurpose
ctx.entityManagerCore entity CRUD operations
ctx.relationManagerRelationship management
ctx.observationManagerFact attachment to entities
ctx.searchManagerFull-text and ranked search
ctx.tagManagerTag CRUD and bulk operations
ctx.hierarchyManagerTree structures and traversal
ctx.analyticsManagerGraph statistics
ctx.compressionManagerDeduplication and archiving
ctx.archiveManagerHistorical data management
ctx.ioManagerImport/export operations
ctx.graphTraversalPath finding algorithms
ctx.semanticSearchEmbedding-based similarity
ctx.rankedSearchTF-IDF ranking
ctx.storageDirect GraphStorage access

Sources: CLAUDE.md:13-26

Storage Backend

Tools persist data to the project root (not dist/):

FormatFiles
JSONLmemory.jsonl, memory-saved-searches.jsonl, memory-tag-aliases.jsonl
SQLitememory.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:

FunctionUsage
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:

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

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Core Search Handler

Continue reading this section for the full explanation and source context.

Section Search Tool Definition

Continue reading this section for the full explanation and source context.

Section Configuration Requirements

Continue reading this section for the full explanation and source context.

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:#f3e5f5

Search Tool Categories

CategoryTool CountPrimary Use Case
Search7Core text-based query operations
Intelligent Search3Advanced query analysis and multi-layer approaches
Semantic Search3Embedding-based similarity matching
Saved Searches5Store 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 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:

ProviderDescription
openaiUse OpenAI embedding models
localUse 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:

ParameterTypeConstraintsDefault
querystringmin(1)required
limitnumberint, min(1), max(100)undefined
minSimilaritynumbermin(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

VariableRequiredValuesPurpose
MEMORY_EMBEDDING_PROVIDERFor semantic searchopenai, localSelect embedding backend
MEMORY_STORAGE_TYPENojsonl, sqliteStorage 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 response

Sources: CLAUDE.md:18

Temporal and Advanced Features

Related topics: Entity-Relation-Observation Model, Tool Reference

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Role-Based Access Control (RBAC)

Continue reading this section for the full explanation and source context.

Section Audit Logging

Continue reading this section for the full explanation and source context.

Section Bitemporal Validity

Continue reading this section for the full explanation and source context.

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 --> R

Sources: 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

ParameterTypeDescription
allowCreatebooleanPermission to create new entities
allowUpdatebooleanPermission to update existing entities
allowDeletebooleanPermission 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

ParameterTypeDescriptionDefault
operationenumcreate, update, delete, merge, archive
agentIdstringFilter by agent identifier
entityNamestringFilter by entity name
sincestringStart time (maps to fromTime)
untilstringEnd time (maps to toTime)
limitnumberMaximum entries to return50

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:

  1. Valid Time: When facts were true in the real world
  2. 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

ToolPurposeKey Parameters
get_decayed_memoriesList memories below decay thresholdthreshold (default: 0.1)
forget_weak_memoriesBulk-delete memories below thresholdthreshold, maxCount, dryRun

Difference from other deletion mechanisms:

  • forget_memory: Uses content matching
  • archive_entities: Uses criteria-based move to archive
  • forget_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

TypeDescription
tool_outputResults from tool invocations
code_snippetGenerated or analyzed code
api_responseExternal API responses
search_resultSearch query results
file_contentFile read contents
user_inputUser-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

ComponentDescription
ToolCallObserverPipeline for observing and analyzing tool calls
Tool AffordanceMetadata describing available tool capabilities
Observation DedupPrevents duplicate observations in the system
Spell Correction3 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:

CategoryFeature Type
GovernanceRBAC, audit logging
CompressionDuplicate detection, merge, auto-compress
AnalyticsGraph stats, integrity validation
Decay & SalienceTime-based importance decay
Import/ExportMulti-format data handling

Sources: CLAUDE.md

Storage Considerations

Advanced features persist data in the same storage backends as core entities:

Storage TypeFile LocationConfiguration
JSONLmemory.jsonl, memory-saved-searches.jsonl, memory-tag-aliases.jsonlDefault
SQLitememory.dbSet 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:

AccessorPurpose
ctx.analyticsManagerGraph statistics and validation
ctx.compressionManagerDuplicate detection and merging
ctx.archiveManagerLong-term memory archival
ctx.ioManagerImport/export operations
ctx.graphTraversalAdvanced graph navigation
ctx.semanticSearchEmbedding-based search
ctx.rankedSearchTF-IDF based search
ctx.storageDirect GraphStorage access

Sources: CLAUDE.md

Testing Coverage

Advanced features are covered by the test suite with the following coverage metrics:

MetricCoverage
Statements80.7%
Lines81.4%
Functions79.5%
Branches68.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

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Role-Based Access Control (RBAC)

Continue reading this section for the full explanation and source context.

Section Governance Policy Management

Continue reading this section for the full explanation and source context.

Section Governance Tool Definition

Continue reading this section for the full explanation and source context.

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:

DomainPurposeKey Components
GovernanceAccess control policiesRBAC, CRUD permissions
AuditActivity trackingOperation logs, agent attribution
ArtifactsCollaboration artifactsTool outputs, code snippets, session data
Data IntegrityExport securityPII 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

ParameterTypeRequiredDescription
allowCreatebooleanNoEnable entity creation (default: true)
allowUpdatebooleanNoEnable entity updates (default: true)
allowDeletebooleanNoEnable 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

ParameterTypeRequiredDescription
operationenumNoFilter by: create, update, delete, merge, archive
agentIdstringNoFilter by responsible agent
entityNamestringNoFilter by affected entity
sincestringNoStart time (ISO 8601)
untilstringNoEnd time (ISO 8601)
limitnumberNoMax results (1-1000, default: 50)

Supported Audit Operations

The audit system records the complete lifecycle of graph entities:

OperationDescription
createNew entity or relation creation
updateModification of existing entities
deletePermanent removal from graph
mergeEntity consolidation operations
archiveSoft 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

TypeUse Case
tool_outputRaw outputs from MCP tool invocations
code_snippetGenerated or referenced code
api_responseExternal API responses
search_resultSearch query results
file_contentFile contents for reference
user_inputUser-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

ParameterTypeRequiredDescription
toolNamestringNoFilter by originating tool
artifactTypeenumNoFilter by artifact type
sincestringNoISO 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

OptionTypeDescriptionVersion
redactPiibooleanEnable PII redaction on exportmemoryjs η.6.3+
Export formatsenumxml, json-ldmemoryjs η.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

VariableDescriptionDefaultSecurity Impact
MEMORY_FILE_PATHStorage file locationmemory.jsonlData isolation
MEMORY_STORAGE_TYPEStorage backendjsonlPersistence security
MEMORY_EMBEDDING_PROVIDEREmbedding servicenoneExternal data exposure
MEMORY_OPENAI_API_KEYAPI authenticationExternal service auth

Sources: CLAUDE.md:58-64

Testing Coverage

The collaboration and security features are validated through the test suite:

Test CategoryLocationCoverage Focus
Integrationtests/integration/MCP server lifecycle, security hooks
E2Etests/e2e/tools/Per-tool handler validation
Governancetests/e2e/tools/governance.test.tsPolicy enforcement
Audittests/e2e/tools/audit.test.tsLog integrity
Artifactstests/e2e/tools/artifact.test.tsCRUD operations

Sources: CLAUDE.md:46-50, docs/architecture/TEST_COVERAGE.md

Best Practices for Multi-Agent Collaboration

  1. Configure Governance Early: Set appropriate allowCreate, allowUpdate, and allowDelete policies before enabling multi-agent access.
  1. Enable Audit Logging: Use audit_query with appropriate filters to monitor agent activity and detect anomalies.
  1. Use Artifacts for Context: Store intermediate results as artifacts with descriptive sessionId values to enable context sharing.
  1. Enable PII Redaction: Set redactPii: true when exporting data containing sensitive information.
  1. Rotate Storage Files: Implement periodic rotation of memory.jsonl or memory.db with archival to maintain audit history.

Pull Request Security Requirements

When contributing security-related changes:

  1. Title: Clear, descriptive summary of the security impact
  2. Description: Document what changed, why, and potential security implications
  3. Tests: Include test results demonstrating security controls
  4. Documentation: Update relevant security documentation
  5. Backward Compatibility: Confirm no breaking security changes

Sources: CONTRIBUTING.md:37-44

Sources: CLAUDE.md:14-16

Development Guide

Related topics: Getting Started

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Layered Architecture

Continue reading this section for the full explanation and source context.

Section Key Source Files

Continue reading this section for the full explanation and source context.

Section Prerequisites

Continue reading this section for the full explanation and source context.

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| G

Sources: CLAUDE.md:15-25

Key Source Files

FilePurpose
src/index.tsEntry point, re-exports ManagerContext as KnowledgeGraphManager
src/server/MCPServer.tsMCP server implementation
src/server/toolDefs.tsJSON schema definitions for all 213 tools
src/server/toolHandlers.tsImplementation 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

ScriptPurpose
npm run buildCompile TypeScript to dist/
npm run typecheckRun TypeScript type checking
npm run testRun all tests
npm run test:unitRun unit tests only
npm run test:e2eRun end-to-end tests
npm run docs:depsGenerate dependency graph documentation

Sources: package.json

Environment Configuration

The MCP server uses environment variables for configuration:

VariableDescriptionDefault
MEMORY_FILE_PATHPath to storage filememory.jsonl (cwd)
MEMORY_STORAGE_TYPEjsonl or sqlitejsonl
MEMORY_EMBEDDING_PROVIDERopenai, local, or nonenone
MEMORY_OPENAI_API_KEYRequired if provider is openai
MEMORY_EMBEDDING_MODELEmbedding model nametext-embedding-3-small / Xenova/all-MiniLM-L6-v2
MEMORY_AUTO_INDEX_EMBEDDINGSAuto-index on entity creationfalse

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 (set MEMORY_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:

AccessorPurpose
ctx.entityManagerCore CRUD for graph nodes
ctx.relationManagerDirected edges between entities
ctx.observationManagerFacts attached to entities
ctx.searchManagerSearch operations
ctx.tagManagerTag management
ctx.hierarchyManagerParent-child trees
ctx.analyticsManagerGraph stats and validation
ctx.compressionManagerDuplicate detection, merge
ctx.archiveManagerArchive operations
ctx.ioManagerImport/Export operations
ctx.graphTraversalBFS/DFS path finding
ctx.semanticSearchEmbedding similarity search
ctx.rankedSearchTF-IDF ranked search
ctx.storageDirect 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.

TierLocationPurpose
Unittests/unit/Isolated module tests (e.g., response compressor)
Integrationtests/integration/MCP server lifecycle tests
E2Etests/e2e/tools/Per-category tool tests
Roottests/Core graph operations and storage path handling

Sources: CLAUDE.md:71-80

Test Coverage

Coverage verification is done via coverage/coverage-summary.json:

MetricCoverage
Statements80.7%
Lines81.4%
Functions79.5%
Branches68.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 in git status.
  • Error handling in dispatch: handleToolCall catches exceptions from handlers and returns them as MCP-formatted error responses. Check MCP response isError field 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:

  1. Validate arguments with schema validation
  2. Call manager method via appropriate accessor
  3. 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:

CategoryCountKey Purpose
Entity4Core CRUD for graph nodes
Relation2Directed edges between entities
Observation3Facts attached to entities, with normalization
Search7Basic, ranked (TF-IDF), boolean, fuzzy, auto-select
Intelligent Search3Hybrid multi-layer, query analysis, reflection-based
Semantic Search3Embedding similarity via OpenAI or local models
Saved Searches5Store and re-execute frequent queries
Tag Management6Tags, bulk ops, importance scores
Tag Aliases5Tag synonym/alias management
Hierarchy9Parent-child trees, subtree traversal
Graph Algorithms4BFS/DFS path finding, centrality, connected components
Analytics2Graph stats and integrity validation
Compression4Duplicate detection, merge, auto-compress, archive
Import/Export27 export formats (xml, json-ld, etc.)

Sources: CLAUDE.md:33-46

Documentation Guidelines

When adding features, update the following documentation:

FilePurpose
README.mdUpdate with new tools/functionality
CHANGELOG.mdDocument changes
WORKFLOW.mdUpdate if development process changes
Usage examplesInclude practical examples

Sources: CONTRIBUTING.md:30-34

Pull Request Process

PR Checklist

StepRequirement
TitleClear, descriptive summary
DescriptionWhat changed, why it changed, how to test it
TestsInclude test results
DocumentationUpdate relevant docs
Backward CompatibilityConfirm 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:

ToolPurpose
chunking-for-filesSplit/merge large files for context-limited editing
compress-for-contextCTON compression for LLM context windows
create-dependency-graphGenerate TypeScript project dependency graphs
migrate-from-jsonl-to-sqliteConvert 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 prepare script auto-builds, so separate npm run build is not needed before publish
  • Always bump version in package.json before 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

TypeAction
Bug ReportsOpen an issue with detailed reproduction steps
Feature RequestsOpen an issue describing the use case
QuestionsCheck 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.

medium README/documentation is current enough for a first validation pass.

The project should not be treated as fully validated until this signal is reviewed.

medium Maintainer activity is unknown

Users cannot judge support quality until recent activity, releases, and issue response are checked.

medium no_demo

The project may affect permissions, credentials, data exposure, or host boundaries.

medium no_demo

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.

Sources 2

Count of project-level external discussion links exposed on this manual page.

Use Review before install

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.

Source: Project Pack community evidence and pitfall evidence