# https://github.com/danielsimonjr/memory-mcp 项目说明书

生成时间：2026-05-16 09:20:25 UTC

## 目录

- [Getting Started](#getting-started)
- [Project Structure](#project-structure)
- [Architecture Overview](#architecture-overview)
- [Storage Backends](#storage-backends)
- [Entity-Relation-Observation Model](#entity-model)
- [Tool Reference](#tool-reference)
- [Search Capabilities](#search-capabilities)
- [Temporal and Advanced Features](#temporal-features)
- [Collaboration and Security](#collaboration-security)
- [Development Guide](#development-guide)

<a id='getting-started'></a>

## Getting Started

### 相关页面

相关主题：[Architecture Overview](#architecture-overview), [Development Guide](#development-guide)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [README.md](https://github.com/danielsimonjr/memory-mcp/blob/main/README.md)
- [CLAUDE.md](https://github.com/danielsimonjr/memory-mcp/blob/main/CLAUDE.md)
- [CONTRIBUTING.md](https://github.com/danielsimonjr/memory-mcp/blob/main/CONTRIBUTING.md)
- [package.json](https://github.com/danielsimonjr/memory-mcp/blob/main/package.json)
- [tools/create-dependency-graph/README.md](https://github.com/danielsimonjr/memory-mcp/blob/main/tools/create-dependency-graph/README.md)
</details>

# 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. 资料来源：[CLAUDE.md:1]()

The server acts as a bridge between AI applications and a knowledge graph storage layer, enabling:

- Persistent entity and relation storage
- Semantic and ranked search capabilities
- Time-based memory decay and importance scoring
- Context compression for large inputs
- Multi-format data import/export

## Prerequisites

Before installing Memory MCP, ensure your environment meets these requirements:

| Requirement | Minimum Version | Notes |
|-------------|-----------------|-------|
| Node.js | 18.0+ | ES2022 features required |
| npm | 9.0+ | For package management |
| SQLite | 3.39+ | Only if using SQLite storage |
| TypeScript | 5.0+ | For development work |

资料来源：[CLAUDE.md:20]()

## Installation

### From npm (Recommended for Users)

```bash
npm install @danielsimonjr/memory-mcp
```

This installs the pre-built package with all dependencies. The core library `@danielsimonjr/memoryjs` is automatically included. 资料来源：[CLAUDE.md:24]()

### From Source (Recommended for Development)

```bash
# 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. 资料来源：[CONTRIBUTING.md:1]()

### Verify Installation

After installation, verify the CLI is available:

```bash
mcp-server-memory --help
```

## Configuration

### Environment Variables

Memory MCP supports several environment variables for configuration:

| Variable | Default | Description |
|----------|---------|-------------|
| `MEMORY_STORAGE_TYPE` | `jsonl` | Storage backend: `jsonl` or `sqlite` |
| `MEMORY_DB_PATH` | `memory.db` | Path to SQLite database (when using SQLite) |
| `MEMORY_JSONL_PATH` | `memory.jsonl` | Path to JSONL file (when using JSONL) |

资料来源：[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 资料来源：[CLAUDE.md:14]()

**SQLite Storage**

- Set `MEMORY_STORAGE_TYPE=sqlite` to enable
- Uses `better-sqlite3` for native performance
- Single database file: `memory.db` 资料来源：[tools/migrate-from-jsonl-to-sqlite/migrate-from-jsonl-to-sqlite.ts:1]()

## Architecture Overview

### System Layers

```mermaid
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
```

资料来源：[CLAUDE.md:4-13]()

### Entry Points

| Entry Point | Purpose |
|-------------|---------|
| `dist/index.js` | Main build output |
| `mcp-server-memory` | CLI binary (defined in package.json `bin`) |
| `src/index.ts` | Source entry point |

资料来源：[CLAUDE.md:17]()

### Manager Accessors

The `ManagerContext` provides access to all core managers:

| Accessor | Purpose |
|----------|---------|
| `ctx.entityManager` | Core CRUD for graph nodes |
| `ctx.relationManager` | Directed edges between entities |
| `ctx.observationManager` | Facts attached to entities |
| `ctx.searchManager` | Basic, ranked, boolean, fuzzy search |
| `ctx.semanticSearch` | Embedding similarity via OpenAI or local models |
| `ctx.tagManager` | Tag management with importance scores |
| `ctx.hierarchyManager` | Parent-child trees, subtree traversal |
| `ctx.compressionManager` | Duplicate detection, merge, archive |
| `ctx.graphTraversal` | BFS/DFS path finding, centrality |
| `ctx.analyticsManager` | Graph stats and integrity validation |
| `ctx.storage` | Direct GraphStorage access |

资料来源：[CLAUDE.md:1]()

## Tool Categories Overview

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

| Category | Count | Key Purpose |
|----------|-------|-------------|
| Entity | 4 | Core CRUD for graph nodes |
| Relation | 2 | Directed edges between entities |
| Observation | 3 | Facts attached to entities |
| Search | 7 | Basic, ranked, boolean, fuzzy |
| Semantic Search | 3 | Embedding similarity |
| Intelligent Search | 3 | Hybrid multi-layer, query analysis |
| Saved Searches | 5 | Store and re-execute queries |
| Tag Management | 6 | Tags, bulk ops, importance scores |
| Tag Aliases | 5 | Tag synonym/alias management |
| Hierarchy | 9 | Parent-child trees, subtree traversal |
| Graph Algorithms | 4 | BFS/DFS, centrality, connected components |
| Analytics | 2 | Graph stats and integrity validation |
| Compression | 4 | Dedup, merge, auto-compress, archive |
| Import/Export | 2 | 7 export formats |
| Decay & Salience | 3 | Time-based importance decay |

资料来源：[CLAUDE.md:3]()

## Quick Start with MCP Client

Once Memory MCP is installed and configured, integrate it with your MCP-compatible client:

```json
{
  "mcpServers": {
    "memory": {
      "command": "mcp-server-memory",
      "args": []
    }
  }
}
```

For SQLite storage:

```json
{
  "mcpServers": {
    "memory": {
      "command": "mcp-server-memory",
      "env": {
        "MEMORY_STORAGE_TYPE": "sqlite"
      }
    }
  }
}
```

## Basic Operations

### Creating Entities

```typescript
// Via tool handler (internal usage example)
await ctx.entityManager.createEntity({
  name: "project_alpha",
  entityType: "project",
  observations: ["Initial setup complete"]
});
```

### Searching

```typescript
// 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

```typescript
const compressed = ctx.contextWindowManager.compressForContext(
  largeText,
  { level: 'medium' }
);
```

## Standalone Tools

The `tools/` directory contains standalone utilities:

| Tool | Purpose |
|------|---------|
| `chunking-for-files` | Split/merge large files for context-limited editing |
| `compress-for-context` | CTON compression for LLM context windows |
| `create-dependency-graph` | Generate TypeScript project dependency graphs |
| `migrate-from-jsonl-to-sqlite` | Convert between JSONL and SQLite formats |

资料来源：[CLAUDE.md:18]()

Each tool has its own `package.json` and can be built to Windows executables via `pkg`. 资料来源：[CLAUDE.md:18]()

## Development Setup

### Cloning and Initial Setup

```bash
git clone https://github.com/danielsimonjr/memory-mcp.git
cd memory-mcp
npm install
```

### Creating a Feature Branch

```bash
git checkout -b feature/your-feature-name
```

### Development Workflow

```bash
# 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
```

资料来源：[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)

资料来源：[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

资料来源：[CONTRIBUTING.md:18-22]()

### Running Tests

```bash
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`. 资料来源：[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

资料来源：[CLAUDE.md:17,23]()

### Publishing to npm

```bash
# 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. 资料来源：[CLAUDE.md:25]()

### Verifying Package Contents

Before publishing:

```bash
npm pack --dry-run 2>&1 | grep -E "jsonl|\.db|total files|package size"
```

资料来源：[CLAUDE.md:25]()

## Data Migration

### JSONL to SQLite

```bash
npx tsx tools/migrate-from-jsonl-to-sqlite.ts \
  --from memory.jsonl \
  --to memory.db \
  --verbose
```

### Command Line Arguments

| Argument | Short | Description |
|----------|-------|-------------|
| `--from <path>` | `-f` | Source file path (JSONL or SQLite) |
| `--to <path>` | `-t` | Target file path (JSONL or SQLite) |
| `--verbose` | `-v` | Show detailed progress |
| `--help` | `-h` | Show help message |

资料来源：[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

资料来源：[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

资料来源：[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. 资料来源：[CLAUDE.md:23]()

## Next Steps

After setting up your environment:

1. Explore the [Tool Categories](#tool-categories-overview) to understand available operations
2. Review the [Architecture Overview](#architecture-overview) for system design
3. Set up your preferred [Storage Configuration](#configuration)
4. Run the standalone [Dependency Graph Tool](https://github.com/danielsimonjr/memory-mcp/blob/main/tools/create-dependency-graph/README.md) to visualize project structure
5. Consult the project's issues for feature requests or bug reports

---

<a id='project-structure'></a>

## Project Structure

### 相关页面

相关主题：[Architecture Overview](#architecture-overview), [Development Guide](#development-guide)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [src/index.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/index.ts)
- [src/server/MCPServer.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/MCPServer.ts)
- [src/server/toolDefinitions.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/toolDefinitions.ts)
- [src/server/toolHandlers.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/toolHandlers.ts)
- [tools/create-dependency-graph/README.md](https://github.com/danielsimonjr/memory-mcp/blob/main/tools/create-dependency-graph/README.md)
- [CLAUDE.md](https://github.com/danielsimonjr/memory-mcp/blob/main/CLAUDE.md)
</details>

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

```mermaid
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
```

资料来源：[CLAUDE.md:layered-architecture]()

### Accessor Hierarchy

The `ManagerContext` provides lazy-initialized accessors for all subsystems:

| Accessor | Purpose |
|----------|---------|
| `ctx.entityManager` | Graph node CRUD operations |
| `ctx.relationManager` | Directed edge management |
| `ctx.observationManager` | Facts attached to entities |
| `ctx.searchManager` | Basic, ranked, boolean, fuzzy search |
| `ctx.tagManager` | Tag CRUD and bulk operations |
| `ctx.hierarchyManager` | Parent-child tree structures |
| `ctx.analyticsManager` | Graph statistics and validation |
| `ctx.compressionManager` | Duplicate detection and merging |
| `ctx.archiveManager` | Historical data archival |
| `ctx.ioManager` | Import/export operations |
| `ctx.graphTraversal` | BFS/DFS path finding |
| `ctx.semanticSearch` | Embedding similarity search |
| `ctx.rankedSearch` | TF-IDF ranking |
| `ctx.storage` | Direct GraphStorage access |

资料来源：[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

资料来源：[CLAUDE.md:entry-points](), [CLAUDE.md:error-handling]()

### Tool Definitions (`src/server/toolDefinitions.ts`)

The tool definitions file contains JSON Schema specifications for all 213 tools. Tools are organized into categories:

| Category | Count | Description |
|----------|-------|-------------|
| Entity | 4 | Core CRUD for graph nodes |
| Relation | 2 | Directed edges between entities |
| Observation | 3 | Facts attached to entities |
| Search | 7 | Basic, ranked, boolean, fuzzy search |
| Intelligent Search | 3 | Hybrid multi-layer search |
| Semantic Search | 3 | Embedding-based similarity |
| Saved Searches | 5 | Stored query execution |
| Tag Management | 6 | Tag CRUD and bulk operations |
| Tag Aliases | 5 | Tag synonym management |
| Hierarchy | 9 | Tree structures and traversal |
| Graph Algorithms | 4 | Path finding, centrality |
| Analytics | 2 | Stats and validation |
| Compression | 4 | Duplicate detection, merge |
| Import/Export | 2+ | Multiple format support |

资料来源：[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:
```typescript
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);
}
```

资料来源：[src/server/toolHandlers.ts]()

## Standalone Tools

The `tools/` directory contains independent utilities, each with its own `package.json` and compilable to Windows executables via `pkg`:

### create-dependency-graph

Analyzes TypeScript source files and generates dependency documentation.

| Output | Description |
|--------|-------------|
| `docs/architecture/DEPENDENCY_GRAPH.md` | Human-readable Markdown documentation |
| `docs/architecture/dependency-graph.json` | Machine-readable JSON structure |

Features:
- Scans all TypeScript files in `src/`
- Parses imports and exports
- Categorizes files into logical modules
- Detects circular dependencies
- Generates statistics

Usage:
```bash
npm run docs:deps
# or
npx tsx tools/create-dependency-graph.ts
```

资料来源：[tools/create-dependency-graph/README.md]()

### compress-for-context

CTON (Context Token Optimization Notation) compression for reducing LLM context window usage.

| Option | Description |
|--------|-------------|
| `-o, --output <file>` | Output file path |
| `-f, --format <fmt>` | Force format: json, yaml, markdown, csv, etc. |
| `-l, --level <lvl>` | Compression level: light, medium, aggressive |
| `-b, --batch` | Batch mode for multiple files |
| `-d, --decompress` | Restore compressed file |

### chunking-for-files

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

Commands:
- `chunker split <file>` - Split file into 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`.

```bash
migrate-from-jsonl-to-sqlite --from <source> --to <target> [--verbose]
```

## Storage System

Data files reside in the **project root** (not `dist/`):

| Storage Type | File | Environment Variable |
|--------------|------|---------------------|
| JSONL (default) | `memory.jsonl`, `memory-saved-searches.jsonl`, `memory-tag-aliases.jsonl` | `MEMORY_STORAGE_TYPE=jsonl` |
| SQLite | `memory.db` | `MEMORY_STORAGE_TYPE=sqlite` |

The `memory.db` and `*.jsonl` files are gitignored—they are created/modified at runtime but not tracked by version control.

资料来源：[CLAUDE.md:storage]()

## Build and Publication

### Build Output

| Artifact | Description |
|----------|-------------|
| `dist/index.js` | Main build output |
| `mcp-server-memory` | CLI binary (package.json `bin` field) |

The TypeScript target is ES2022 with Node16 module resolution. The `prepare` script auto-runs `npm run build` on `npm install`, ensuring `dist/` is always rebuilt.

### Publishing to npm

```bash
# 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.

资料来源：[CLAUDE.md:publishing-to-npm]()

## Development Guidelines

### Code Style

| Guideline | Standard |
|-----------|----------|
| Language | TypeScript best practices |
| Indentation | 2 spaces |
| Documentation | JSDoc comments for public methods |
| Function design | Small, focused functions |
| Naming | Meaningful variable names |

### Testing Requirements

When adding features:
- Test with empty graphs and large graphs
- Include edge cases
- Verify backward compatibility
- Ensure export formats are valid

### Documentation Checklist

| File | When to Update |
|------|----------------|
| `README.md` | New tools/functionality |
| `CHANGELOG.md` | Version changes |
| `WORKFLOW.md` | Development process changes |

## File Naming Conventions

| Pattern | Example | Purpose |
|---------|---------|---------|
| `*.ts` | `MCPServer.ts`, `toolHandlers.ts` | TypeScript source files |
| `*.md` | `DEPENDENCY_GRAPH.md` | Generated documentation |
| `*.json` | `dependency-graph.json` | Machine-readable data |
| `*.compact` | output.compact | Compressed files |

## Summary

The memory-mcp project is structured as a thin MCP wrapper around the `@danielsimonjr/memoryjs` library. The core source in `src/` contains only 5 TypeScript files, while the `tools/` directory provides standalone utilities for dependency analysis, context compression, file chunking, and storage migration. The architecture prioritizes backward compatibility, lazy initialization of managers, and clean separation between tool definitions, handlers, and the underlying knowledge graph implementation.

---

<a id='architecture-overview'></a>

## Architecture Overview

### 相关页面

相关主题：[Storage Backends](#storage-backends), [Entity-Relation-Observation Model](#entity-model)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [src/index.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/index.ts)
- [src/server/MCPServer.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/MCPServer.ts)
- [src/server/toolDefs.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/toolDefs.ts)
- [src/server/toolHandlers.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/toolHandlers.ts)
- [CLAUDE.md](https://github.com/danielsimonjr/memory-mcp/blob/main/CLAUDE.md)
- [docs/architecture/ARCHITECTURE.md](https://github.com/danielsimonjr/memory-mcp/blob/main/docs/architecture/ARCHITECTURE.md)
</details>

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

```mermaid
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
```

资料来源：[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

资料来源：[src/index.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/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.

资料来源：[src/server/MCPServer.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/MCPServer.ts)

### ManagerContext (memoryjs)

The `ManagerContext` provides access to all core managers through a unified interface. It implements lazy initialization to optimize startup time and resource usage.

| Manager | Purpose |
|---------|---------|
| `entityManager` | Core CRUD operations for graph nodes |
| `relationManager` | Directed edges between entities |
| `observationManager` | Facts attached to entities with normalization |
| `searchManager` | Basic, ranked, boolean, fuzzy, and auto-select search |
| `tagManager` | Tag operations, bulk operations, importance scores |
| `hierarchyManager` | Parent-child trees, subtree traversal |
| `analyticsManager` | Graph statistics and integrity validation |
| `compressionManager` | Duplicate detection, merge, auto-compress, archive |
| `archiveManager` | Long-term storage management |
| `ioManager` | Import/export operations |
| `graphTraversal` | Graph algorithm utilities |
| `semanticSearch` | Embedding-based similarity search |
| `rankedSearch` | TF-IDF weighted search |
| `storage` | Direct GraphStorage access for advanced use cases |

资料来源：[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:
```typescript
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);
}
```

资料来源：[src/server/toolHandlers.ts:tool pattern]()

### Tool Categories

The system organizes its 213 tools into 58 categories:

| Category | Count | Key Purpose |
|----------|-------|-------------|
| Entity | 4 | Core CRUD for graph nodes |
| Relation | 2 | Directed edges between entities |
| Observation | 3 | Facts attached to entities, with normalization |
| Search | 7 | Basic, ranked, boolean, fuzzy, auto-select |
| Intelligent Search | 3 | Hybrid multi-layer, query analysis, reflection-based |
| Semantic Search | 3 | Embedding similarity via OpenAI or local models |
| Saved Searches | 5 | Store and re-execute frequent queries |
| Tag Management | 6 | Tags, bulk ops, importance scores |
| Tag Aliases | 5 | Tag synonym/alias management |
| Hierarchy | 9 | Parent-child trees, subtree traversal |
| Graph Algorithms | 4 | BFS/DFS path finding, centrality, connected components |
| Analytics | 2 | Graph stats and integrity validation |
| Compression | 4 | Duplicate detection, merge, auto-compress, archive |
| Import/Export | 2 | 7 export formats |

资料来源：[CLAUDE.md:Tool Categories]()

## Storage Layer

The storage layer supports two backends controlled by the `MEMORY_STORAGE_TYPE` environment variable.

### JSONL Storage (Default)

Data files are stored in the project root directory:

| File | Purpose |
|------|---------|
| `memory.jsonl` | Main knowledge graph data |
| `memory-saved-searches.jsonl` | Saved search definitions |
| `memory-tag-aliases.jsonl` | Tag synonym mappings |

### SQLite Storage

When `MEMORY_STORAGE_TYPE=sqlite`, the system uses:
- `memory.db` - Single-file relational database

The SQLite backend provides better performance for large datasets and supports advanced query capabilities through the storage layer.

资料来源：[CLAUDE.md:Storage]()

## Entry Points

| Entry Point | Description |
|-------------|-------------|
| `dist/index.js` | Built output for npm distribution |
| `mcp-server-memory` | CLI binary defined in package.json `bin` field |
| `src/index.ts` | Source entry point |

资料来源：[CLAUDE.md:Entry Points]()

## Data Flow

```mermaid
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:

| Tool | Purpose |
|------|---------|
| `chunking-for-files` | Split/merge large files for context-limited editing |
| `compress-for-context` | CTON compression for LLM context windows |
| `create-dependency-graph` | Generate TypeScript project dependency graphs |
| `migrate-from-jsonl-to-sqlite` | Convert between JSONL and SQLite formats |

资料来源：[CLAUDE.md:Standalone Tools]()

## Version History

The architecture has evolved through multiple phases:

| Phase | Version | Key Changes |
|-------|---------|-------------|
| Phase 13 | Initial | 5 TypeScript source files, memoryjs v2.1.0+ |
| Phase 15 | v12.2.0 | 23 tools for memoryjs v1.14+ features (bitemporal, OCC, RBAC) |
| Phase 16 | v12.3.0 | 53 tools for memoryjs v2.1.0 (exclusions, ADR, context, heuristics) |

资料来源：[CLAUDE.md:Phase History]()

## npm Package Information

- **Package**: `@danielsimonjr/memory-mcp`
- **Core Dependency**: `@danielsimonjr/memoryjs` (version specified in package.json)

资料来源：[CLAUDE.md:npm Information]()

---

<a id='storage-backends'></a>

## Storage Backends

### 相关页面

相关主题：[Architecture Overview](#architecture-overview), [Entity-Relation-Observation Model](#entity-model)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [tools/migrate-from-jsonl-to-sqlite/migrate-from-jsonl-to-sqlite.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/tools/migrate-from-jsonl-to-sqlite/migrate-from-jsonl-to-sqlite.ts)
- [tools/migrate-from-jsonl-to-sqlite/README.md](https://github.com/danielsimonjr/memory-mcp/blob/main/tools/migrate-from-jsonl-to-sqlite/README.md)
- [tools/migrate-from-jsonl-to-sqlite/package.json](https://github.com/danielsimonjr/memory-mcp/blob/main/tools/migrate-from-jsonl-to-sqlite/package.json)
- [CLAUDE.md](https://github.com/danielsimonjr/memory-mcp/blob/main/CLAUDE.md)
- [package.json](https://github.com/danielsimonjr/memory-mcp/blob/main/package.json)
- [src/server/toolDefinitions.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/toolDefinitions.ts)
- [SECURITY.md](https://github.com/danielsimonjr/memory-mcp/blob/main/SECURITY.md)
</details>

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

```mermaid
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.

| Collection | Type | Description |
|------------|------|-------------|
| `entities` | Entity[] | Individual memory items with observations and metadata |
| `relations` | Relation[] | Connections between entities defining semantic relationships |

### Entity Model

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `name` | string | Yes | Unique identifier for the entity |
| `entityType` | string | Yes | Classification category (e.g., "person", "concept", "task") |
| `observations` | string[] | Yes | Array of recorded facts or data points |
| `createdAt` | string | No | ISO timestamp of entity creation |
| `lastModified` | string | No | ISO timestamp of last modification |
| `tags` | string[] | No | Optional categorization labels |
| `importance` | number | No | Priority score (null if unspecified) |
| `parentId` | string | No | Hierarchical parent reference |

资料来源：[tools/migrate-from-jsonl-to-sqlite/migrate-from-jsonl-to-sqlite.ts:50-58]()

### Relation Model

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `from` | string | Yes | Source entity name or ID |
| `to` | string | Yes | Target entity name or ID |
| `relationType` | string | Yes | Semantic relationship type (e.g., "related_to", "part_of") |
| `createdAt` | string | No | ISO timestamp of relation creation |
| `lastModified` | string | No | ISO timestamp of last modification |

资料来源：[tools/migrate-from-jsonl-to-sqlite/migrate-from-jsonl-to-sqlite.ts:60-66]()

## Supported Storage Formats

### JSONL Format

The **JSONL (JSON Lines)** backend stores each entity and relation as a separate JSON object on its own line within plain text files. This format provides human-readable data and simple version control compatibility.

**File Locations (Project Root):**

| File | Purpose |
|------|---------|
| `memory.jsonl` | Primary knowledge graph storage |
| `memory-saved-searches.jsonl` | Stored search configurations |
| `memory-tag-aliases.jsonl` | Tag normalization mappings |

资料来源：[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

资料来源：[tools/migrate-from-jsonl-to-sqlite/README.md:45-55]()

### SQLite Format

The **SQLite** backend provides a relational database optimized for larger datasets and concurrent access patterns. It offers ACID transaction support and full-text search capabilities through FTS5.

**File Location (Project Root):**

| File | Purpose |
|------|---------|
| `memory.db` | Primary SQLite database |

资料来源：[CLAUDE.md:6]()

**SQLite Backend Features:**

| Feature | Description |
|---------|-------------|
| FTS5 Index | Automatic full-text search indexing for fast entity lookups |
| WAL Mode | Write-Ahead Logging for improved concurrent read/write performance |
| Atomic Transactions | Ensures data integrity during write operations |
| Native Performance | Uses better-sqlite3 for 3-10x faster operations compared to WASM alternatives |

资料来源：[tools/migrate-from-jsonl-to-sqlite/migrate-from-jsonl-to-sqlite.ts:14-15]()

## Environment Configuration

Storage behavior is controlled through environment variables that must be set before server initialization.

### Configuration Variables

| Variable | Values | Default | Description |
|----------|--------|---------|-------------|
| `MEMORY_STORAGE_TYPE` | `jsonl`, `sqlite` | `jsonl` | Determines which storage backend to use |
| `MEMORY_FILE_PATH` | Valid file path | `memory.jsonl` (cwd) | Absolute or relative path to primary storage file |

资料来源：[CLAUDE.md:24-28]()

### Configuration Examples

**JSONL (Default):**
```bash
# No environment variables needed - defaults to JSONL
```

**SQLite:**
```json
{
  "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"
      }
    }
  }
}
```

资料来源：[tools/migrate-from-jsonl-to-sqlite/README.md:70-79]()

## Migration Between Formats

The `migrate-from-jsonl-to-sqlite` tool provides bidirectional conversion between JSONL and SQLite storage formats. This enables users to start with simple JSONL storage and migrate to SQLite as their dataset grows.

### Supported File Extensions

| Format | Extensions | Detection Logic |
|--------|------------|-----------------|
| JSONL | `.jsonl`, `.json` | Extension-based detection |
| SQLite | `.db`, `.sqlite`, `.sqlite3` | Extension-based detection |

资料来源：[tools/migrate-from-jsonl-to-sqlite/migrate-from-jsonl-to-sqlite.ts:97-103]()

### Migration Tool Usage

```bash
# 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
```

资料来源：[tools/migrate-from-jsonl-to-sqlite/migrate-from-jsonl-to-sqlite.ts:1-30]()

### Migration Options

| Argument | Short | Description |
|----------|-------|-------------|
| `--from` | `-f` | Source file path (JSONL or SQLite) |
| `--to` | `-t` | Target file path (JSONL or SQLite) |
| `--verbose` | `-v` | Show detailed progress information |
| `--help` | `-h` | Display help message |

### Migration Workflow

```mermaid
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

| Aspect | Behavior |
|--------|----------|
| **Target Creation** | Target file is created if it doesn't exist |
| **Existing Targets** | Target file will be overwritten if it exists |
| **Data Integrity** | Atomic transactions ensure no data loss during migration |
| **Timestamp Handling** | Missing `createdAt` or `lastModified` fields are populated with migration timestamp and a warning is displayed |
| **Saved Searches** | NOT migrated (stored in separate `memory-saved-searches.jsonl` file) |
| **Tag Aliases** | NOT migrated (stored in separate `memory-tag-aliases.jsonl` file) |
| **Large Datasets** | Recommended for graphs with 10,000+ entities |

资料来源：[tools/migrate-from-jsonl-to-sqlite/README.md:20-25]()

## Format Selection Guide

Choose the appropriate storage backend based on your specific use case and dataset characteristics.

| Criteria | JSONL | SQLite |
|----------|-------|--------|
| Dataset Size | < 1,000 entities | 10,000+ entities |
| Transaction Needs | Simple append operations | ACID transactions required |
| Data Inspection | Human-readable preferred | Structured queries needed |
| Concurrent Access | Single process | Multiple readers/writers |
| Debugging | Direct file inspection | Requires SQLite tools |
| Performance | Sufficient for small datasets | Optimized for large graphs |

资料来源：[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:

```json
{
  "mcpServers": {
    "memory": {
      "command": "node",
      "args": ["/path/to/memory-mcp/src/memory/dist/index.js"],
      "env": {
        "MEMORY_FILE_PATH": "/secure/path/memory.jsonl"
      }
    }
  }
}
```

资料来源：[SECURITY.md:8-18]()

### Data Sensitivity

| Format | Export Considerations |
|--------|----------------------|
| JSONL/JSON | Full entity data visible in plain text |
| SQLite | Database contents require database tools to inspect |
| CSV/GraphML Exports | Full data included; filter parameters can limit exported data |

资料来源：[SECURITY.md:19-26]()

## Tool Dependencies

The SQLite backend and migration tool rely on the `better-sqlite3` package for native performance:

```json
{
  "name": "migrate-from-jsonl-to-sqlite",
  "version": "1.1.0",
  "dependencies": {
    "better-sqlite3": "^11.7.0"
  },
  "devDependencies": {
    "@types/better-sqlite3": "^7.6.12"
  }
}
```

资料来源：[tools/migrate-from-jsonl-to-sqlite/package.json:1-12]()

The package is configured with `yao-pkg/pkg` for building standalone executables targeting `node22-win-x64`.

## Related Documentation

| Document | Description |
|----------|-------------|
| [CLAUDE.md](CLAUDE.md) | Project architecture and development guidelines |
| [tools/migrate-from-jsonl-to-sqlite/README.md](tools/migrate-from-jsonl-to-sqlite/README.md) | Detailed migration tool documentation |
| [SECURITY.md](SECURITY.md) | Security considerations for data storage |

---

<a id='entity-model'></a>

## Entity-Relation-Observation Model

### 相关页面

相关主题：[Search Capabilities](#search-capabilities), [Temporal and Advanced Features](#temporal-features)

<details>
<summary>Relevant Source Files</summary>

以下源码文件用于生成本页说明：

- [src/server/toolDefinitions.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/toolDefinitions.ts)
- [src/server/toolHandlers.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/toolHandlers.ts)
- [CLAUDE.md](https://github.com/danielsimonjr/memory-mcp/blob/main/CLAUDE.md)
- [src/index.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/index.ts)
- [package.json](https://github.com/danielsimonjr/memory-mcp/blob/main/package.json)
</details>

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

```mermaid
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
```

资料来源：[CLAUDE.md:layered-architecture](https://github.com/danielsimonjr/memory-mcp/blob/main/CLAUDE.md)

## Core Components

### Entity Manager

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

| Operation | Tool Name | Description |
|-----------|-----------|-------------|
| Create | `create_entity` | Add a new entity to the graph |
| Read | `get_entity` | Retrieve entity by name or ref |
| Update | `update_entity` | Modify entity properties |
| Delete | `delete_entities` | Remove entity from graph |
| List | `list_entities` | Get entities with optional filters |

资料来源：[toolDefinitions.ts:entity-tools](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/toolDefinitions.ts)

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

```mermaid
graph LR
    E1[Entity A] -->|"created_by"| R[Relation]
    R -->|"part_of"| E2[Entity B]
    E1 -->|"depends_on"| R2[Relation]
    R2 -->|"implements"| E3[Entity C]
```

| Operation | Tool Name | Description |
|-----------|-----------|-------------|
| Create | `create_relations` | Batch create directed edges |
| Delete | `delete_relations` | Remove relations by criteria |
| Invalidate | `invalidate_relation` | Bitemporal validity - end a relation |
| Chain | `get_entity_chain` | Traverse relation paths between entities |

资料来源：[toolHandlers.ts:relation-handlers](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/toolHandlers.ts)

**Relation Schema:**
```typescript
interface Relation {
  from: string;      // Source entity name/ref
  relationType: string; // Relationship type (e.g., "depends_on", "part_of")
  to: string;        // Target entity name/ref
  ended?: string;    // Bitemporal end timestamp (undefined = active)
}
```

### Observation Manager

Observations are factual statements attached to entities, providing evidence and context:

| Property | Description |
|----------|-------------|
| `content` | The factual statement |
| `normalized` | Canonical form for comparison |
| `source` | Origin of the observation |
| `confirmed` | Verification status |
| `attachedAt` | Timestamp when attached |

资料来源：[CLAUDE.md:observation](https://github.com/danielsimonjr/memory-mcp/blob/main/CLAUDE.md)

**Key Features:**
- Content normalization for deduplication
- Source tracking for provenance
- Confirmation counting for consensus-based truth

## Tool Categories

The ERO Model exposes 213 tools across 58 categories:

| Category | Count | Purpose |
|----------|-------|---------|
| Entity | 4 | Core CRUD for graph nodes |
| Relation | 2 | Directed edges between entities |
| Observation | 3 | Facts attached to entities |
| Search | 7 | Query graph data |
| Intelligent Search | 3 | Advanced query processing |
| Semantic Search | 3 | Embedding-based retrieval |
| Tag Management | 6 | Entity categorization |
| Hierarchy | 9 | Parent-child tree structures |
| Graph Algorithms | 4 | Path finding, centrality |
| Analytics | 2 | Graph statistics |
| Compression | 4 | Deduplication, archiving |

资料来源：[CLAUDE.md:tool-categories](https://github.com/danielsimonjr/memory-mcp/blob/main/CLAUDE.md)

## Data Flow

```mermaid
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

资料来源：[CLAUDE.md:storage](https://github.com/danielsimonjr/memory-mcp/blob/main/CLAUDE.md)

## Bitemporal Validity

Relations support bitemporal validity for tracking historical state:

```mermaid
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:
```typescript
invalidate_relation(from, relationType, to, ended?)
```

资料来源：[toolHandlers.ts:invalidate-relation](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/toolHandlers.ts)

## Hierarchy Integration

Entities can form hierarchical trees through the HierarchyManager:

| Tool | Purpose |
|------|---------|
| `set_entity_parent` | Assign parent entity |
| `get_children` | Direct descendants |
| `get_parent` | Direct ancestor |
| `get_ancestors` | Full ancestry path |
| `get_descendants` | All descendants (recursive) |
| `get_subtree` | Subtree structure |

资料来源：[toolHandlers.ts:hierarchy-handlers](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/toolHandlers.ts)

## Search Capabilities

The ERO Model provides layered search:

```mermaid
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

资料来源：[CLAUDE.md:search](https://github.com/danielsimonjr/memory-mcp/blob/main/CLAUDE.md)

## Environment Configuration

| Variable | Description | Default |
|----------|-------------|---------|
| `MEMORY_FILE_PATH` | Storage file path | `memory.jsonl` |
| `MEMORY_STORAGE_TYPE` | Backend type | `jsonl` |
| `MEMORY_EMBEDDING_PROVIDER` | Embedding service | `none` |
| `MEMORY_OPENAI_API_KEY` | API key for OpenAI | — |
| `MEMORY_EMBEDDING_MODEL` | Model name | `text-embedding-3-small` |
| `MEMORY_AUTO_INDEX_EMBEDDINGS` | Auto-index on create | `false` |

资料来源：[CLAUDE.md:env-vars](https://github.com/danielsimonjr/memory-mcp/blob/main/CLAUDE.md)

## API Entry Points

| Endpoint | Description |
|----------|-------------|
| `dist/index.js` | Build output entry |
| `src/index.ts` | Source entry (exports ManagerContext as KnowledgeGraphManager) |
| `mcp-server-memory` | CLI binary |

资料来源：[package.json:exports](https://github.com/danielsimonjr/memory-mcp/blob/main/package.json)

## Adding Custom Tools

To extend the ERO Model with new functionality:

1. **Define Schema** in `toolDefinitions.ts`:
```typescript
{
  name: 'new_tool',
  description: 'Tool description',
  inputSchema: {
    type: 'object',
    properties: { /* parameters */ },
    required: ['param1']
  }
}
```

2. **Implement Handler** in `toolHandlers.ts`:
```typescript
new_tool: async (ctx, args) => {
  // Validate arguments
  // Call manager methods
  // Return formatted response
}
```

3. **Add Tests** in `tests/e2e/tools/`

资料来源：[CLAUDE.md:adding-tools](https://github.com/danielsimonjr/memory-mcp/blob/main/CLAUDE.md)

---

<a id='tool-reference'></a>

## Tool Reference

### 相关页面

相关主题：[Search Capabilities](#search-capabilities), [Temporal and Advanced Features](#temporal-features), [Collaboration and Security](#collaboration-security)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [src/server/toolDefinitions.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/toolDefinitions.ts)
- [src/server/toolHandlers.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/toolHandlers.ts)
- [CLAUDE.md](https://github.com/danielsimonjr/memory-mcp/blob/main/CLAUDE.md)
- [CONTRIBUTING.md](https://github.com/danielsimonjr/memory-mcp/blob/main/CONTRIBUTING.md)
- [src/server/MCPServer.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/MCPServer.ts)
</details>

# 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. 资料来源：[CLAUDE.md:1-5]()

## Architecture

### Layered Design

```mermaid
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. 资料来源：[CLAUDE.md:8-12]()

### Tool Execution Flow

```mermaid
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. 资料来源：[CLAUDE.md:85-87]()

## Tool Categories

The tools are organized into 58 categories spanning core graph operations to advanced features like bitemporal validity and causal reasoning.

| Category | Count | Key Purpose |
|----------|-------|-------------|
| Entity | 4 | Core CRUD for graph nodes |
| Relation | 2 | Directed edges between entities |
| Observation | 3 | Facts attached to entities, with normalization |
| Search | 7 | Basic, ranked (TF-IDF), boolean, fuzzy, auto-select |
| Intelligent Search | 3 | Hybrid multi-layer, query analysis, reflection-based |
| Semantic Search | 3 | Embedding similarity via OpenAI or local models |
| Saved Searches | 5 | Store and re-execute frequent queries |
| Tag Management | 6 | Tags, bulk ops, importance scores |
| Tag Aliases | 5 | Tag synonym/alias management |
| Hierarchy | 9 | Parent-child trees, subtree traversal |
| Graph Algorithms | 4 | BFS/DFS path finding, centrality, connected components |
| Analytics | 2 | Graph stats and integrity validation |
| Compression | 4 | Duplicate detection, merge, auto-compress, archive |
| Import/Export | 2 | 7 export formats |

资料来源：[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:

```typescript
{
  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,
  },
}
```

资料来源：[src/server/toolDefinitions.ts:1-20]()

### Example: Artifact Tool Definition

```typescript
{
  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,
  },
}
```

资料来源：[src/server/toolDefinitions.ts:90-115]()

## Handler Implementation Pattern

Tool handlers follow a consistent implementation pattern across all 213 tools:

```typescript
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);
}
```

资料来源：[src/server/toolHandlers.ts:1-30]()

### Validation with Zod

Handlers use Zod schemas for runtime validation:

| Zod Function | Usage |
|--------------|-------|
| `z.string().min(1)` | Non-empty string |
| `z.number().int().min(1).max(1000)` | Bounded integer |
| `z.enum(['option1', 'option2'])` | Constrained string |
| `z.boolean()` | Boolean flag |
| `z.string().regex(/pattern/)` | Pattern-matched string |
| `z.record(z.string(), z.unknown())` | Dictionary object |

```typescript
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'
);
```

资料来源：[src/server/toolHandlers.ts:5-25]()

## Artifact Tools

Artifact tools manage tool outputs, code snippets, API responses, and other generated content with stable references.

### create_artifact

Creates an artifact entity with a stable auto-generated reference.

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `content` | string | Yes | Artifact content stored as an entity observation |
| `toolName` | string | Yes | Name of the tool or source that produced this artifact |
| `artifactType` | enum | Yes | Category: `tool_output`, `code_snippet`, `api_response`, `search_result`, `file_content`, `user_input` |
| `description` | string | No | Human-readable description |
| `sessionId` | string | No | Session context for grouping related artifacts |

```typescript
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);
}
```

资料来源：[src/server/toolHandlers.ts:290-315]()

### get_artifact

Retrieves an artifact entity by its stable ref or entity name.

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `ref` | string | Yes | Stable ref or entity name (e.g. "bash-2026-03-24-a3f2") |

```typescript
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);
}
```

资料来源：[src/server/toolHandlers.ts:318-328]()

### list_artifacts

Lists artifacts with optional filtering by tool name, type, or time.

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `toolName` | string | No | Filter by originating tool |
| `artifactType` | enum | No | Filter by artifact category |
| `since` | string | No | ISO 8601 timestamp for time-based filtering |

```typescript
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 });
}
```

资料来源：[src/server/toolHandlers.ts:330-360]()

## Decay and Salience Tools

These tools manage memory importance over time using time-based decay algorithms.

### run_decay_cycle

Runs a single pass of time-based importance decay across all agent memories.

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| (none) | - | - | No parameters required |

Returns the count of decayed and forgotten memories. 资料来源：[src/server/toolDefinitions.ts:180-195]()

### get_decayed_memories

Lists memories whose importance has fallen below a threshold due to time-based decay.

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `threshold` | number | No | Importance threshold (default: 0.1) |

Unlike `get_stale_entities` which uses freshness timestamps, this tool uses decay engine importance calculations. 资料来源：[src/server/toolDefinitions.ts:197-208]()

### forget_weak_memories

Bulk-deletes memories that fell below a decay threshold.

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `threshold` | number | No | Importance threshold below which to forget |
| `maxCount` | number | No | Maximum number of memories to forget |
| `dryRun` | boolean | No | If true, report what would be forgotten without deleting |

Unlike `forget_memory` (content match) or `archive_entities` (criteria-based move), this uses decay-based importance scoring. 资料来源：[src/server/toolDefinitions.ts:210-222]()

## Governance and Audit Tools

### audit_query

Queries the audit log for operations matching specified criteria.

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `operation` | enum | No | Filter by: `create`, `update`, `delete`, `merge`, `archive` |
| `agentId` | string | No | Filter by agent identifier |
| `entityName` | string | No | Filter by entity name |
| `since` | string | No | Start time (ISO 8601) |
| `until` | string | No | End time (ISO 8601) |
| `limit` | number | No | Maximum entries to return (default: 50, max: 1000) |

```typescript
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 });
}
```

资料来源：[src/server/toolHandlers.ts:400-440]()

## Adding New Tools

The development workflow for adding a new tool follows a three-step process:

```mermaid
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/` 资料来源：[CONTRIBUTING.md:55-62]()

### Handler Pattern Template

```typescript
// ==================== 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()`. 资料来源：[CONTRIBUTING.md:58-60]()

## Environment Configuration

Tools honor the following environment variables:

| Variable | Description | Default |
|----------|-------------|---------|
| `MEMORY_FILE_PATH` | Path to storage file | `memory.jsonl` (cwd) |
| `MEMORY_STORAGE_TYPE` | `jsonl` or `sqlite` | `jsonl` |
| `MEMORY_EMBEDDING_PROVIDER` | `openai`, `local`, or `none` | `none` |
| `MEMORY_OPENAI_API_KEY` | Required if provider is `openai` | — |
| `MEMORY_EMBEDDING_MODEL` | Embedding model name | `text-embedding-3-small` / `Xenova/all-MiniLM-L6-v2` |
| `MEMORY_AUTO_INDEX_EMBEDDINGS` | Auto-index on entity creation | `false` |

资料来源：[CLAUDE.md:66-73]()

## ManagerContext Accessors

Handlers access underlying functionality through the ManagerContext:

| Accessor | Purpose |
|----------|---------|
| `ctx.entityManager` | Core entity CRUD operations |
| `ctx.relationManager` | Relationship management |
| `ctx.observationManager` | Fact attachment to entities |
| `ctx.searchManager` | Full-text and ranked search |
| `ctx.tagManager` | Tag CRUD and bulk operations |
| `ctx.hierarchyManager` | Tree structures and traversal |
| `ctx.analyticsManager` | Graph statistics |
| `ctx.compressionManager` | Deduplication and archiving |
| `ctx.archiveManager` | Historical data management |
| `ctx.ioManager` | Import/export operations |
| `ctx.graphTraversal` | Path finding algorithms |
| `ctx.semanticSearch` | Embedding-based similarity |
| `ctx.rankedSearch` | TF-IDF ranking |
| `ctx.storage` | Direct GraphStorage access |

资料来源：[CLAUDE.md:13-26]()

## Storage Backend

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

| Format | Files |
|--------|-------|
| JSONL | `memory.jsonl`, `memory-saved-searches.jsonl`, `memory-tag-aliases.jsonl` |
| SQLite | `memory.db` (set `MEMORY_STORAGE_TYPE=sqlite`) |

The `prepare` script runs `npm run build` on install, so `dist/` is rebuilt automatically. 资料来源：[CLAUDE.md:48-55]()

## Response Formatting

Handlers return responses using two formatting functions:

| Function | Usage |
|----------|-------|
| `formatToolResponse(data)` | Structured data response (objects, arrays) |
| `formatTextResponse(text)` | Simple text response (errors, confirmations) |

```typescript
// Success with data
return formatToolResponse(artifact);

// Not found / error message
return formatTextResponse(`Artifact "${ref}" not found`);

// List results
return formatToolResponse({ artifacts, count: artifacts.length });
```

资料来源：[src/server/toolHandlers.ts:318-328]()

## TypeScript Configuration

Tools are built with the following TypeScript configuration:

- **Target**: ES2022
- **Module resolution**: Node16
- **Build output**: `dist/index.js`
- **Source entry**: `src/index.ts` 资料来源：[CLAUDE.md:88-90]()

Backward compatibility is maintained by re-exporting `ManagerContext` as `KnowledgeGraphManager` alias, plus core types. 资料来源：[CLAUDE.md:27-29]()

---

<a id='search-capabilities'></a>

## Search Capabilities

### 相关页面

相关主题：[Entity-Relation-Observation Model](#entity-model), [Temporal and Advanced Features](#temporal-features)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [src/server/toolHandlers.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/toolHandlers.ts)
- [src/server/toolDefinitions.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/toolDefinitions.ts)
- [CLAUDE.md](https://github.com/danielsimonjr/memory-mcp/blob/main/CLAUDE.md)
</details>

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

资料来源：[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.

```mermaid
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

| Category | Tool Count | Primary Use Case |
|----------|------------|------------------|
| Search | 7 | Core text-based query operations |
| Intelligent Search | 3 | Advanced query analysis and multi-layer approaches |
| Semantic Search | 3 | Embedding-based similarity matching |
| Saved Searches | 5 | Store and reuse frequent queries |

资料来源：[CLAUDE.md:18-22]()

## Basic Search Operations

### Core Search Handler

The primary search functionality is implemented in `toolHandlers.ts` and supports multiple query types:

```typescript
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 });
}
```

资料来源：[src/server/toolHandlers.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/toolHandlers.ts)

### Search Tool Definition

The MCP tool definition specifies the input schema for the search interface:

```typescript
{
  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,
  },
}
```

资料来源：[src/server/toolDefinitions.ts:1-30]()

## Semantic Search

Semantic search provides embedding-based similarity matching for natural language queries.

### Configuration Requirements

Semantic search requires an embedding provider to be configured via the `MEMORY_EMBEDDING_PROVIDER` environment variable:

| Provider | Description |
|----------|-------------|
| `openai` | Use OpenAI embedding models |
| `local` | Use locally deployed embedding models |

### Handler Implementation

The semantic search handler validates configuration and executes embedding-based queries:

```typescript
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,
  });
}
```

资料来源：[src/server/toolHandlers.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/toolHandlers.ts)

### Similar Entity Discovery

The `find_similar_entities` tool extends semantic search to discover entities similar to a given reference entity:

```typescript
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:

```typescript
// 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
```

资料来源：[CLAUDE.md:10-13]()

## Search Parameters

### Input Validation Schema

All search operations use Zod schemas for input validation to ensure type safety:

| Parameter | Type | Constraints | Default |
|-----------|------|-------------|---------|
| query | string | min(1) | required |
| limit | number | int, min(1), max(100) | undefined |
| minSimilarity | number | min(0), max(1) | undefined |

### Validation Pattern

The tool handlers use a consistent validation pattern:

```typescript
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:

```typescript
return formatToolResponse({
  query,
  results: results.map(r => ({
    entity: r.entity,
    similarity: r.similarity,  // Only for semantic search
  })),
  count: results.length,
});
```

## Configuration

### Environment Variables

| Variable | Required | Values | Purpose |
|----------|----------|--------|---------|
| `MEMORY_EMBEDDING_PROVIDER` | For semantic search | `openai`, `local` | Select embedding backend |
| `MEMORY_STORAGE_TYPE` | No | `jsonl`, `sqlite` | Storage format for graph data |

### Storage Integration

Search operations load the graph from storage before executing queries:

```typescript
const graph = await ctx.storage.loadGraph();
```

The storage layer supports both JSONL and SQLite backends for persistent graph storage.

资料来源：[CLAUDE.md:38-42]()

## Workflow Diagram

```mermaid
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
```

## Related Documentation

- [Query Language Guide](docs/guides/QUERY_LANGUAGE.md) - Syntax and operators for advanced queries
- [Compression Guide](docs/guides/COMPRESSION.md) - Search optimization through deduplication

---

<a id='temporal-features'></a>

## Temporal and Advanced Features

### 相关页面

相关主题：[Entity-Relation-Observation Model](#entity-model), [Tool Reference](#tool-reference)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [CLAUDE.md](https://github.com/danielsimonjr/memory-mcp/blob/main/CLAUDE.md)
- [src/server/toolHandlers.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/toolHandlers.ts)
- [src/server/toolDefinitions.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/toolDefinitions.ts)
- [tools/create-dependency-graph/README.md](https://github.com/danielsimonjr/memory-mcp/blob/main/tools/create-dependency-graph/README.md)
</details>

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

资料来源：[CLAUDE.md](https://github.com/danielsimonjr/memory-mcp/blob/main/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.

```mermaid
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
```

资料来源：[CLAUDE.md](https://github.com/danielsimonjr/memory-mcp/blob/main/CLAUDE.md)

## Governance and Access Control

### Role-Based Access Control (RBAC)

The system implements RBAC through governance policy settings that control what operations agents can perform on memory entities.

#### Governance Policy Tool

| Parameter | Type | Description |
|-----------|------|-------------|
| `allowCreate` | boolean | Permission to create new entities |
| `allowUpdate` | boolean | Permission to update existing entities |
| `allowDelete` | boolean | Permission to delete entities |

**Handler Implementation:**

```typescript
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}`);
}
```

资料来源：[src/server/toolHandlers.ts:1-50](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/toolHandlers.ts)

### Audit Logging

The audit system tracks all operations performed on the knowledge graph for compliance and debugging purposes.

#### Audit Query Parameters

| Parameter | Type | Description | Default |
|-----------|------|-------------|---------|
| `operation` | enum | create, update, delete, merge, archive | — |
| `agentId` | string | Filter by agent identifier | — |
| `entityName` | string | Filter by entity name | — |
| `since` | string | Start time (maps to fromTime) | — |
| `until` | string | End time (maps to toTime) | — |
| `limit` | number | Maximum entries to return | 50 |

**Handler Implementation:**

```typescript
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);
  // ...
}
```

资料来源：[src/server/toolHandlers.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/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.

资料来源：[CLAUDE.md](https://github.com/danielsimonjr/memory-mcp/blob/main/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.

```typescript
{
  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,
  },
}
```

资料来源：[src/server/toolDefinitions.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/toolDefinitions.ts)

### Decay-Based Memory Queries

| Tool | Purpose | Key Parameters |
|------|---------|----------------|
| `get_decayed_memories` | List memories below decay threshold | `threshold` (default: 0.1) |
| `forget_weak_memories` | Bulk-delete memories below threshold | `threshold`, `maxCount`, `dryRun` |

**Difference from other deletion mechanisms:**

- `forget_memory`: Uses content matching
- `archive_entities`: Uses criteria-based move to archive
- `forget_weak_memories`: Uses decay-based importance scoring

```typescript
{
  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,
  },
}
```

资料来源：[src/server/toolDefinitions.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/toolDefinitions.ts)

## Artifact Management

Artifacts capture structured outputs from tool executions for later retrieval and analysis.

### Artifact Types

| Type | Description |
|------|-------------|
| `tool_output` | Results from tool invocations |
| `code_snippet` | Generated or analyzed code |
| `api_response` | External API responses |
| `search_result` | Search query results |
| `file_content` | File read contents |
| `user_input` | User-provided prompts |

### Artifact Tools

```typescript
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');
  }
  // ...
}
```

资料来源：[src/server/toolHandlers.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/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.

资料来源：[CLAUDE.md](https://github.com/danielsimonjr/memory-mcp/blob/main/CLAUDE.md)

### Tool Affordance and Observation Pipeline

| Component | Description |
|-----------|-------------|
| `ToolCallObserver` | Pipeline for observing and analyzing tool calls |
| Tool Affordance | Metadata describing available tool capabilities |
| Observation Dedup | Prevents duplicate observations in the system |
| Spell Correction | 3 tools for automatic typo correction in queries |

### Structured Project Context

12 tools providing structured access to project metadata and context for better decision-making.

### Heuristic Guidelines

10 tools implementing rule-based guidance for memory management and retrieval decisions.

## Tool Categories Summary

The system organizes its 213 tools across 58 categories, with the advanced features distributed across:

| Category | Feature Type |
|----------|--------------|
| Governance | RBAC, audit logging |
| Compression | Duplicate detection, merge, auto-compress |
| Analytics | Graph stats, integrity validation |
| Decay & Salience | Time-based importance decay |
| Import/Export | Multi-format data handling |

资料来源：[CLAUDE.md](https://github.com/danielsimonjr/memory-mcp/blob/main/CLAUDE.md)

## Storage Considerations

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

| Storage Type | File Location | Configuration |
|--------------|---------------|---------------|
| JSONL | `memory.jsonl`, `memory-saved-searches.jsonl`, `memory-tag-aliases.jsonl` | Default |
| SQLite | `memory.db` | Set `MEMORY_STORAGE_TYPE=sqlite` |

Data files reside in the project root (not `dist/`), and are gitignored to prevent accidental commits.

资料来源：[CLAUDE.md](https://github.com/danielsimonjr/memory-mcp/blob/main/CLAUDE.md)

## Manager Context Accessors

Advanced features access the core library through the `ManagerContext`:

| Accessor | Purpose |
|----------|---------|
| `ctx.analyticsManager` | Graph statistics and validation |
| `ctx.compressionManager` | Duplicate detection and merging |
| `ctx.archiveManager` | Long-term memory archival |
| `ctx.ioManager` | Import/export operations |
| `ctx.graphTraversal` | Advanced graph navigation |
| `ctx.semanticSearch` | Embedding-based search |
| `ctx.rankedSearch` | TF-IDF based search |
| `ctx.storage` | Direct GraphStorage access |

资料来源：[CLAUDE.md](https://github.com/danielsimonjr/memory-mcp/blob/main/CLAUDE.md)

## Testing Coverage

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

| Metric | Coverage |
|--------|----------|
| Statements | 80.7% |
| Lines | 81.4% |
| Functions | 79.5% |
| Branches | 68.3% |

Test files are organized in `tests/e2e/tools/` with one file per tool group including governance, freshness, and entropy categories.

资料来源：[CLAUDE.md](https://github.com/danielsimonjr/memory-mcp/blob/main/CLAUDE.md)

---

<a id='collaboration-security'></a>

## Collaboration and Security

### 相关页面

相关主题：[Tool Reference](#tool-reference), [Temporal and Advanced Features](#temporal-features)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [src/server/toolHandlers.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/toolHandlers.ts)
- [CLAUDE.md](https://github.com/danielsimonjr/memory-mcp/blob/main/CLAUDE.md)
- [CONTRIBUTING.md](https://github.com/danielsimonjr/memory-mcp/blob/main/CONTRIBUTING.md)
- [src/server/toolDefs.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/toolDefs.ts)
- [docs/architecture/API.md](https://github.com/danielsimonjr/memory-mcp/blob/main/docs/architecture/API.md)
- [docs/architecture/TEST_COVERAGE.md](https://github.com/danielsimonjr/memory-mcp/blob/main/docs/architecture/TEST_COVERAGE.md)
</details>

# Collaboration and Security

The memory-mcp system provides a comprehensive suite of collaboration and security features designed to enable multi-agent workflows while maintaining data integrity, access control, and auditability. These features are built on the underlying memoryjs library (v1.14+) and exposed through 213 MCP tools across 58 categories.

## Overview

Collaboration and Security in memory-mcp encompasses four primary domains:

| Domain | Purpose | Key Components |
|--------|---------|----------------|
| **Governance** | Access control policies | RBAC, CRUD permissions |
| **Audit** | Activity tracking | Operation logs, agent attribution |
| **Artifacts** | Collaboration artifacts | Tool outputs, code snippets, session data |
| **Data Integrity** | Export security | PII redaction, format validation |

资料来源：[CLAUDE.md:14-16]()

## Architecture

```graph TD
    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. 资料来源：[CLAUDE.md:16]()

### Governance Policy Management

The `governance_set_policy` tool enables administrators to configure CRUD permissions for the knowledge graph:

```typescript
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}`
    );
}
```

资料来源：[src/server/toolHandlers.ts:1-20]()

### Governance Tool Definition

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `allowCreate` | boolean | No | Enable entity creation (default: true) |
| `allowUpdate` | boolean | No | Enable entity updates (default: true) |
| `allowDelete` | boolean | No | Enable entity deletion (default: true) |

When a permission flag is `false`, the governance layer installs a deny function that blocks the operation.

## Audit System

### Audit Log Architecture

The audit system tracks all graph mutations with full attribution:

```graph TD
    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:

```typescript
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);
    // ...
}
```

资料来源：[src/server/toolHandlers.ts:22-57]()

### Audit Query Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `operation` | enum | No | Filter by: `create`, `update`, `delete`, `merge`, `archive` |
| `agentId` | string | No | Filter by responsible agent |
| `entityName` | string | No | Filter by affected entity |
| `since` | string | No | Start time (ISO 8601) |
| `until` | string | No | End time (ISO 8601) |
| `limit` | number | No | Max results (1-1000, default: 50) |

### Supported Audit Operations

The audit system records the complete lifecycle of graph entities:

| Operation | Description |
|-----------|-------------|
| `create` | New entity or relation creation |
| `update` | Modification of existing entities |
| `delete` | Permanent removal from graph |
| `merge` | Entity consolidation operations |
| `archive` | Soft deletion with retention |

## Artifact Management

### Purpose

Artifacts enable collaboration by persisting tool outputs, code snippets, API responses, and user inputs across sessions. This supports multi-agent workflows where one agent's output becomes another agent's context.

### Artifact Types

| Type | Use Case |
|------|----------|
| `tool_output` | Raw outputs from MCP tool invocations |
| `code_snippet` | Generated or referenced code |
| `api_response` | External API responses |
| `search_result` | Search query results |
| `file_content` | File contents for reference |
| `user_input` | User-provided content |

资料来源：[src/server/toolHandlers.ts:59-75]()

### Artifact CRUD Operations

#### Create Artifact

```typescript
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);
}
```

资料来源：[src/server/toolHandlers.ts:59-80]()

#### List Artifacts with Filtering

```typescript
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 });
}
```

资料来源：[src/server/toolHandlers.ts:95-125]()

### Artifact Filter Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `toolName` | string | No | Filter by originating tool |
| `artifactType` | enum | No | Filter by artifact type |
| `since` | string | No | ISO 8601 date for time-based filtering |

## Data Integrity and Export Security

### PII Redaction

When exporting graph data, memory-mcp supports automatic PII redaction to prevent sensitive information leakage:

```graph TD
    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]
```

资料来源：[CLAUDE.md:34-35]()

### Export Configuration

| Option | Type | Description | Version |
|--------|------|-------------|---------|
| `redactPii` | boolean | Enable PII redaction on export | memoryjs η.6.3+ |
| Export formats | enum | `xml`, `json-ld` | memoryjs η.5.4+ |

### Compression for Context

The standalone `compress-for-context` tool provides CTON (Compact Textual Object Notation) compression for managing context windows during multi-agent collaboration:

```bash
# 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
```

资料来源：[tools/compress-for-context/compress-for-context.ts:1-25]()

## Security Architecture

```graph TD
    subgraph "Security Layers"
        A[Authentication]
        B[Authorization]
        C[Audit Logging]
        D[Data Encryption]
    end
    
    subgraph "Access Control Points"
        E[governance_set_policy]
        F[RBAC via memoryjs]
        G[Operation Validation]
    end
    
    subgraph "Audit Trail"
        H[Operation Tracking]
        I[Agent Attribution]
        J[Time-based Queries]
    end
    
    A --> B
    B --> C
    C --> D
    E --> F
    F --> G
    G --> H
    H --> I
    I --> J
```

## Environment Variables for Security

| Variable | Description | Default | Security Impact |
|----------|-------------|---------|-----------------|
| `MEMORY_FILE_PATH` | Storage file location | `memory.jsonl` | Data isolation |
| `MEMORY_STORAGE_TYPE` | Storage backend | `jsonl` | Persistence security |
| `MEMORY_EMBEDDING_PROVIDER` | Embedding service | `none` | External data exposure |
| `MEMORY_OPENAI_API_KEY` | API authentication | — | External service auth |

资料来源：[CLAUDE.md:58-64]()

## Testing Coverage

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

| Test Category | Location | Coverage Focus |
|---------------|----------|----------------|
| Integration | `tests/integration/` | MCP server lifecycle, security hooks |
| E2E | `tests/e2e/tools/` | Per-tool handler validation |
| Governance | `tests/e2e/tools/governance.test.ts` | Policy enforcement |
| Audit | `tests/e2e/tools/audit.test.ts` | Log integrity |
| Artifacts | `tests/e2e/tools/artifact.test.ts` | CRUD operations |

资料来源：[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.

2. **Enable Audit Logging**: Use `audit_query` with appropriate filters to monitor agent activity and detect anomalies.

3. **Use Artifacts for Context**: Store intermediate results as artifacts with descriptive `sessionId` values to enable context sharing.

4. **Enable PII Redaction**: Set `redactPii: true` when exporting data containing sensitive information.

5. **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

资料来源：[CONTRIBUTING.md:37-44]()

---

<a id='development-guide'></a>

## Development Guide

### 相关页面

相关主题：[Getting Started](#getting-started)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [package.json](https://github.com/danielsimonjr/memory-mcp/blob/main/package.json)
- [tsconfig.json](https://github.com/danielsimonjr/memory-mcp/blob/main/tsconfig.json)
- [vitest.config.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/vitest.config.ts)
- [CONTRIBUTING.md](https://github.com/danielsimonjr/memory-mcp/blob/main/CONTRIBUTING.md)
- [CLAUDE.md](https://github.com/danielsimonjr/memory-mcp/blob/main/CLAUDE.md)
</details>

# 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`)

资料来源：[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.

```mermaid
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
```

资料来源：[CLAUDE.md:15-25]()

### Key Source Files

| File | Purpose |
|------|---------|
| `src/index.ts` | Entry point, re-exports `ManagerContext` as `KnowledgeGraphManager` |
| `src/server/MCPServer.ts` | MCP server implementation |
| `src/server/toolDefs.ts` | JSON schema definitions for all 213 tools |
| `src/server/toolHandlers.ts` | Implementation handlers for each tool |

资料来源：[CLAUDE.md:28-31]()

## Project Setup

### Prerequisites

- Node.js (compatible with ES2022)
- npm

### Installation

```bash
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.

资料来源：[CLAUDE.md:54]()

### TypeScript Configuration

The project uses ES2022 target with Node16 module resolution:

```json
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "Node16",
    "moduleResolution": "Node16",
    "outDir": "./dist",
    "rootDir": "./src"
  },
  "include": ["src/**/*"]
}
```

资料来源：[tsconfig.json](https://github.com/danielsimonjr/memory-mcp/blob/main/tsconfig.json)

### Build Scripts

| Script | Purpose |
|--------|---------|
| `npm run build` | Compile TypeScript to `dist/` |
| `npm run typecheck` | Run TypeScript type checking |
| `npm run test` | Run all tests |
| `npm run test:unit` | Run unit tests only |
| `npm run test:e2e` | Run end-to-end tests |
| `npm run docs:deps` | Generate dependency graph documentation |

资料来源：[package.json](https://github.com/danielsimonjr/memory-mcp/blob/main/package.json)

## Environment Configuration

The MCP server uses environment variables for configuration:

| Variable | Description | Default |
|----------|-------------|---------|
| `MEMORY_FILE_PATH` | Path to storage file | `memory.jsonl` (cwd) |
| `MEMORY_STORAGE_TYPE` | `jsonl` or `sqlite` | `jsonl` |
| `MEMORY_EMBEDDING_PROVIDER` | `openai`, `local`, or `none` | `none` |
| `MEMORY_OPENAI_API_KEY` | Required if provider is `openai` | — |
| `MEMORY_EMBEDDING_MODEL` | Embedding model name | `text-embedding-3-small` / `Xenova/all-MiniLM-L6-v2` |
| `MEMORY_AUTO_INDEX_EMBEDDINGS` | Auto-index on entity creation | `false` |

资料来源：[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`)

资料来源：[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)

资料来源：[CONTRIBUTING.md:21-25]()

### ManagerContext Access Pattern

When implementing tool handlers, use the ManagerContext accessors to access various managers:

| Accessor | Purpose |
|----------|---------|
| `ctx.entityManager` | Core CRUD for graph nodes |
| `ctx.relationManager` | Directed edges between entities |
| `ctx.observationManager` | Facts attached to entities |
| `ctx.searchManager` | Search operations |
| `ctx.tagManager` | Tag management |
| `ctx.hierarchyManager` | Parent-child trees |
| `ctx.analyticsManager` | Graph stats and validation |
| `ctx.compressionManager` | Duplicate detection, merge |
| `ctx.archiveManager` | Archive operations |
| `ctx.ioManager` | Import/Export operations |
| `ctx.graphTraversal` | BFS/DFS path finding |
| `ctx.semanticSearch` | Embedding similarity search |
| `ctx.rankedSearch` | TF-IDF ranked search |
| `ctx.storage` | Direct GraphStorage access |

资料来源：[CLAUDE.md:53-55]()

## Testing Guidelines

### Test Structure

The project has 26 test files with 665 tests, achieving approximately 81% statement coverage.

| Tier | Location | Purpose |
|------|----------|---------|
| Unit | `tests/unit/` | Isolated module tests (e.g., response compressor) |
| Integration | `tests/integration/` | MCP server lifecycle tests |
| E2E | `tests/e2e/tools/` | Per-category tool tests |
| Root | `tests/` | Core graph operations and storage path handling |

资料来源：[CLAUDE.md:71-80]()

### Test Coverage

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

| Metric | Coverage |
|--------|----------|
| Statements | 80.7% |
| Lines | 81.4% |
| Functions | 79.5% |
| Branches | 68.3% |

资料来源：[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).

资料来源：[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

资料来源：[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.

资料来源：[CLAUDE.md:84-87]()

## Adding a New Tool

### Step-by-Step Process

```mermaid
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**

```typescript
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()`.

资料来源：[CLAUDE.md:47-52]()

### Tool Categories Overview

The project exposes 213 tools across 58 categories:

| Category | Count | Key Purpose |
|----------|-------|-------------|
| Entity | 4 | Core CRUD for graph nodes |
| Relation | 2 | Directed edges between entities |
| Observation | 3 | Facts attached to entities, with normalization |
| Search | 7 | Basic, ranked (TF-IDF), boolean, fuzzy, auto-select |
| Intelligent Search | 3 | Hybrid multi-layer, query analysis, reflection-based |
| Semantic Search | 3 | Embedding similarity via OpenAI or local models |
| Saved Searches | 5 | Store and re-execute frequent queries |
| Tag Management | 6 | Tags, bulk ops, importance scores |
| Tag Aliases | 5 | Tag synonym/alias management |
| Hierarchy | 9 | Parent-child trees, subtree traversal |
| Graph Algorithms | 4 | BFS/DFS path finding, centrality, connected components |
| Analytics | 2 | Graph stats and integrity validation |
| Compression | 4 | Duplicate detection, merge, auto-compress, archive |
| Import/Export | 2 | 7 export formats (xml, json-ld, etc.) |

资料来源：[CLAUDE.md:33-46]()

## Documentation Guidelines

When adding features, update the following documentation:

| File | Purpose |
|------|---------|
| `README.md` | Update with new tools/functionality |
| `CHANGELOG.md` | Document changes |
| `WORKFLOW.md` | Update if development process changes |
| Usage examples | Include practical examples |

资料来源：[CONTRIBUTING.md:30-34]()

## Pull Request Process

### PR Checklist

| Step | Requirement |
|------|-------------|
| **Title** | Clear, descriptive summary |
| **Description** | What changed, why it changed, how to test it |
| **Tests** | Include test results |
| **Documentation** | Update relevant docs |
| **Backward Compatibility** | Confirm no breaking changes |

资料来源：[CONTRIBUTING.md:36-45]()

### PR Workflow

```bash
# 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
```

资料来源：[CONTRIBUTING.md:1-8]()

## Standalone Tools

The `tools/` directory contains standalone utilities, each with its own `package.json` and buildable to Windows exes via pkg:

| Tool | Purpose |
|------|---------|
| `chunking-for-files` | Split/merge large files for context-limited editing |
| `compress-for-context` | CTON compression for LLM context windows |
| `create-dependency-graph` | Generate TypeScript project dependency graphs |
| `migrate-from-jsonl-to-sqlite` | Convert between JSONL and SQLite formats |

资料来源：[CLAUDE.md:44-51]()

## Publishing to npm

```bash
# 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

资料来源：[CLAUDE.md:52-58]()

### Verify Tarball Contents

```bash
npm pack --dry-run 2>&1 | grep -E "jsonl|\.db|total files|package size"
```

资料来源：[CLAUDE.md:59]()

## Reporting Issues

| Type | Action |
|------|--------|
| **Bug Reports** | Open an issue with detailed reproduction steps |
| **Feature Requests** | Open an issue describing the use case |
| **Questions** | Check existing issues or open a new one |

This project follows the [Model Context Protocol community guidelines](https://modelcontextprotocol.io/community/communication).

资料来源：[CONTRIBUTING.md:60-65]()

## License

By contributing, you agree that your contributions will be licensed under the MIT License.

资料来源：[CONTRIBUTING.md:68-70]()

---

---

## Doramagic Pitfall Log

Project: danielsimonjr/memory-mcp

Summary: Found 6 potential pitfall items; 0 are high/blocking. Highest priority: capability - 能力判断依赖假设.

## 1. capability · 能力判断依赖假设

- Severity: medium
- Evidence strength: source_linked
- Finding: README/documentation is current enough for a first validation pass.
- User impact: 假设不成立时，用户拿不到承诺的能力。
- Suggested check: 将假设转成下游验证清单。
- Guardrail action: 假设必须转成验证项；没有验证结果前不能写成事实。
- Evidence: capability.assumptions | github_repo:1093926095 | https://github.com/danielsimonjr/memory-mcp | README/documentation is current enough for a first validation pass.

## 2. maintenance · 维护活跃度未知

- Severity: medium
- Evidence strength: source_linked
- Finding: 未记录 last_activity_observed。
- User impact: 新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。
- Suggested check: 补 GitHub 最近 commit、release、issue/PR 响应信号。
- Guardrail action: 维护活跃度未知时，推荐强度不能标为高信任。
- Evidence: evidence.maintainer_signals | github_repo:1093926095 | https://github.com/danielsimonjr/memory-mcp | last_activity_observed missing

## 3. security_permissions · 下游验证发现风险项

- Severity: medium
- Evidence strength: source_linked
- Finding: no_demo
- User impact: 下游已经要求复核，不能在页面中弱化。
- Suggested check: 进入安全/权限治理复核队列。
- Guardrail action: 下游风险存在时必须保持 review/recommendation 降级。
- Evidence: downstream_validation.risk_items | github_repo:1093926095 | https://github.com/danielsimonjr/memory-mcp | no_demo; severity=medium

## 4. security_permissions · 存在评分风险

- Severity: medium
- Evidence strength: source_linked
- Finding: no_demo
- User impact: 风险会影响是否适合普通用户安装。
- Suggested check: 把风险写入边界卡，并确认是否需要人工复核。
- Guardrail action: 评分风险必须进入边界卡，不能只作为内部分数。
- Evidence: risks.scoring_risks | github_repo:1093926095 | https://github.com/danielsimonjr/memory-mcp | no_demo; severity=medium

## 5. maintenance · issue/PR 响应质量未知

- Severity: low
- Evidence strength: source_linked
- Finding: issue_or_pr_quality=unknown。
- User impact: 用户无法判断遇到问题后是否有人维护。
- Suggested check: 抽样最近 issue/PR，判断是否长期无人处理。
- Guardrail action: issue/PR 响应未知时，必须提示维护风险。
- Evidence: evidence.maintainer_signals | github_repo:1093926095 | https://github.com/danielsimonjr/memory-mcp | issue_or_pr_quality=unknown

## 6. maintenance · 发布节奏不明确

- Severity: low
- Evidence strength: source_linked
- Finding: release_recency=unknown。
- User impact: 安装命令和文档可能落后于代码，用户踩坑概率升高。
- Suggested check: 确认最近 release/tag 和 README 安装命令是否一致。
- Guardrail action: 发布节奏未知或过期时，安装说明必须标注可能漂移。
- Evidence: evidence.maintainer_signals | github_repo:1093926095 | https://github.com/danielsimonjr/memory-mcp | release_recency=unknown

<!-- canonical_name: danielsimonjr/memory-mcp; human_manual_source: deepwiki_human_wiki -->
