Cozo Memory

io.github.tobs-code由 GitHub 账号 tobs-code 发布v1.0.3更新于 Oct 24, 2026

Local-first memory system for AI agents with hybrid search and graph reasoning

发布方自己的服务:Memory.fit

概览

AI 生成的概览

本地优先的记忆服务器,为 AI 助手提供基于 CozoDB 的持久记忆,支持向量、全文与图混合检索及历史回溯。

可以做什么
写入与管理记忆:创建、更新、删除实体、观察、关系、会话和任务,支持标签与批量操作,并可编辑全局用户偏好画像。读取与检索:混合搜索、高级搜索、上下文查询、Graph-RAG 与图遍历、自适应与智能检索,以及列出实体和会话。分析知识图谱:探索、社区、PageRank、介数、HITS、最短路径和语义游走。维护系统:健康检查、指标、统计、导出、导入、清理、碎片整理、反思和快照。可选的 Ollama 操作提供 LLM 清理、反思、社区摘要、压缩和查询意图路由。
适用场景
适合需要助手跨会话记住过往对话与事实,并基于其间关系进行推理,而非仅做普通文档 RAG 的场景。也适合希望记忆完全保存在本机、带版本历史和矛盾处理的用户。
运行要求
以 npm 包 cozo-memory 通过 npx 或全局安装,在本地以 stdio 运行;建议 Node.js 20 以上。默认嵌入模型约需 1.7 GB 内存,首次启动下载约 600 MB;可通过 EMBEDDING_MODEL 变量选择更轻量的模型。高级操作需要本地 Ollama 服务,核心增删改查、搜索和图操作不需要。
安装前请注意
它会在本机保存持久记忆和用户画像,写入操作可创建、更新和删除实体、观察与关系,包括批量删除。更换嵌入模型需要重新嵌入已有数据。可选的 Ollama 操作会把内容发送给本地 LLM 服务,README 还提到可选的 Express API 桥接。

安装

在 SourceWeft 中

  1. 打开 控制台中的 Cozo Memory,将其添加到工作区。
  2. 为需要使用其工具的对话启用该服务。

Desktop only,通过 STDIO。 STDIO 服务会启动本地进程,因此需要 SourceWeft 桌面宿主。

其他 MCP 客户端

参照 仓库 中的启动说明。

README

CozoDB Memory MCP Server

[npm] [Node] [License] [MCP Badge]

Why Cozo Memory?
LLMs have short-term memory limits. Standard RAG retrieves documents but can't connect facts across time. Cozo Memory gives your AI agent persistent, structured memory – it remembers past conversations, infers relationships, detects contradictions, and explores its knowledge graph – fully on your machine, with optional local LLM integration via Ollama for intelligent actions (cleanup, reflection, summarization, agentic routing).

Most memory stacks combine separate databases: SQLite for facts, Chroma for vector search, NetworkX for graphs. CozoDB replaces all of that with one embedded engine: relational, graph, vector, and full-text search in a single query language, one file, zero sync lag.

Local-first memory for Claude & AI agents with hybrid search, Graph-RAG, and time-travel – runs entirely on your machine. Optional Ollama integration enables LLM-powered actions (cleanup, reflect, summarize, agentic retrieval).

Table of Contents

Quick Start

Option 1: Install via npm (Recommended)

bash
# Install globallynpm install -g cozo-memory
# Or run directly with npx (no installation needed)npx cozo-memory

Option 2: Build from Source

bash
git clone https://github.com/tobs-code/cozo-memorycd cozo-memorynpm install && npm run buildnpm run start

Now add the server to your MCP client (e.g. Claude Desktop) – see Integration below.

Key Features

🔍 Hybrid Search - Combines semantic (HNSW), full-text (FTS), and graph signals via Reciprocal Rank Fusion for intelligent retrieval

🧠 Agentic Retrieval - Auto-routing engine analyzes query intent via local LLM to select optimal search strategy (Vector, Graph, or Community)

⏱️ Time-Travel Queries - Version all changes via CozoDB Validity; query any point in history with full audit trails

🎯 GraphRAG-R1-Inspired Adaptive Retrieval - Intelligent system with Progressive Retrieval Attenuation (PRA) and Cost-Aware F1 (CAF) scoring, conceptually inspired by GraphRAG-R1 (Yu et al., WWW 2026) and adapted for CozoDB, that learns from usage

⏳ Temporal Conflict Resolution - Automatic detection and resolution of contradictory observations with semantic analysis and audit preservation

🏠 100% Local - Embeddings via ONNX/Transformers; data stays on your machine. Some advanced features (cleanup, reflect, summarize, agentic search) require an optional Ollama service for local LLM inference — but the core search, CRUD, and graph operations work without any LLM.

🧠 Multi-Hop Reasoning - Logic-aware graph traversal with vector pivots for deep relational reasoning

🗂️ Hierarchical Memory - Multi-level architecture (L0-L3) with intelligent compression and LLM-backed summarization

→ See all features | Version History

Positioning & Comparison

Why CozoDB instead of SQLite + Chroma + NetworkX?

A common first question is: "Why not just combine existing tools?"

If you need...Typical separate stackCozoDB Memory
Structured data & relationsSQLite / PostgreSQL✅ Built-in relational engine
Semantic / vector searchChroma / Qdrant / Pinecone✅ HNSW + FTS + RRF in one engine
Graph traversal & reasoningNetworkX / Neo4j✅ Native graph queries + PageRank
Time-travel / versioningCustom audit tables✅ Built-in Validity time-travel
Unified query languageMultiple APIs + glue code✅ Single Datalog query across all dimensions

The core insight: Most memory stacks bolt vector search onto a graph DB, or graph search onto a vector DB. CozoDB is different: it is a single engine that natively combines relational, graph, vector, and full-text search. That means:

  • One query language (Datalog) reaches every dimension.
  • No sync lag between separate indexes.
  • No ETL bridge between "vector results" and "graph expansion."
  • Smaller operational surface: one database file, one process, one dependency chain.

Comparison with other memory solutions

Most "Memory" MCP servers fall into two categories:

  1. Simple Knowledge Graphs: CRUD operations on triples, often only text search
  2. Pure Vector Stores: Semantic search (RAG), but little understanding of complex relationships

This server fills the gap in between ("Sweet Spot"): A local, database-backed memory engine combining vector, graph, and keyword signals — powered by CozoDB's unified engine rather than a patchwork of separate databases.

FeatureCozoDB Memory (This Project)Official Reference (@modelcontextprotocol/server-memory)mcp-memory-service (Community)Database Adapters (Qdrant/Neo4j)
BackendCozoDB (Graph + Vector + Relational + FTS in one engine)JSON file (memory.jsonl)SQLite / CloudflareSpecialized DB (only Vector or Graph)
Search LogicAgentic (Auto-Route): Hybrid + Graph + SummariesKeyword only / Exact Graph MatchVector + KeywordMostly only one dimension
InferenceYes: Built-in engine for implicit knowledgeNoNo ("Dreaming" is consolidation)No (Retrieval only)
CommunityYes: Hierarchical Community SummariesNoNoOnly clustering (no summary)
Time-TravelYes: Queries at any point in time (Validity)No (current state only)History available, no native DB featureNo
MaintenanceJanitor: LLM-backed cleanupManualAutomatic consolidationMostly manual
DeploymentLocal (Node.js + Embedded DB)Local (Docker/NPX)Local or CloudOften requires external DB server

The core advantage is Intelligence and Traceability: By combining an Agentic Retrieval Layer with Hierarchical GraphRAG, the system can answer both specific factual questions and broad thematic queries with much higher accuracy than pure vector stores.

Installation

Prerequisites

  • Node.js 20+ (recommended)
  • RAM: 1.7 GB minimum (for default bge-m3 model)
    • Model download: ~600 MB
    • Runtime memory: ~1.1 GB
    • ⚡ Too heavy? Use EMBEDDING_MODEL=Xenova/all-MiniLM-L6-v2 – only ~400 MB RAM needed (see Embedding Model Options)
  • CozoDB native dependency is installed via cozo-node

Optional: Ollama for LLM-powered actions

Some advanced actions use a local LLM via Ollama for intelligent processing. The core server works without Ollama (CRUD, search, graph operations), but the following actions require it:

ActionPurpose
cleanupLLM-backed observation consolidation
reflectGenerate insights, detect contradictions
summarize_communitiesLLM-generated community summaries
compactSession / entity compaction with LLM summarization
agentic_searchQuery intent classification for auto-routing

Setup (if you need these features):

bash
# 1. Install Ollama from https://ollama.ai# 2. Pull a model (e.g. small + fast for dev):ollama pull demyagent-4b-i1:Q6_K# 3. Ollama runs automatically on http://localhost:11434

If Ollama is not running, the affected actions gracefully fall back to non-LLM behavior (where possible) or return a clear error message.

Via npm (Easiest)

bash
# Install globallynpm install -g cozo-memory
# Or use npx without installationnpx cozo-memory

From Source

bash
git clone https://github.com/tobs-code/cozo-memorycd cozo-memorynpm installnpm run build

Windows Quickstart

bash
npm installnpm run buildnpm run start

Notes:

  • On first start, @xenova/transformers downloads the embedding model (may take time)
  • Embeddings are processed on the CPU

Embedding Model Options

CozoDB Memory supports multiple embedding models via the EMBEDDING_MODEL environment variable:

ModelSizeRAMDimensionsBest For
Xenova/bge-m3 (default)~600 MB~1.7 GB1024High accuracy, production use
Xenova/all-MiniLM-L6-v2~80 MB~400 MB384Low-spec machines, development
Xenova/bge-small-en-v1.5~130 MB~600 MB384Balanced performance

Configuration Options:

Option 1: Using .env file (Easiest for beginners)

bash
# Copy the example filecp .env.example .env
# Edit .env and set your preferred modelEMBEDDING_MODEL=Xenova/all-MiniLM-L6-v2

Option 2: MCP Server Config (For Claude Desktop / Kiro)

json
{  "mcpServers": {    "cozo-memory": {      "command": "npx",      "args": ["cozo-memory"],      "env": {        "EMBEDDING_MODEL": "Xenova/all-MiniLM-L6-v2"      }    }  }}

Option 3: Command Line

bash
# Use lightweight model for developmentEMBEDDING_MODEL=Xenova/all-MiniLM-L6-v2 npm run start

Download Model First (Recommended):

bash
# Set model in .env or via command line, then:EMBEDDING_MODEL=Xenova/all-MiniLM-L6-v2 npm run download-model

Note: Changing models requires re-embedding existing data. The model is downloaded once on first use.

Integration

Claude Desktop

Using npx (Recommended)
json
{  "mcpServers": {    "cozo-memory": {      "command": "npx",      "args": ["cozo-memory"]    }  }}
Using global installation
json
{  "mcpServers": {    "cozo-memory": {      "command": "cozo-memory"    }  }}
Using local build
json
{  "mcpServers": {    "cozo-memory": {      "command": "node",      "args": ["C:/Path/to/cozo-memory/dist/index.js"]    }  }}

Framework Adapters

Official adapters for seamless integration with popular AI frameworks:

🦜 LangChain Adapter

bash
npm install @cozo-memory/langchain @cozo-memory/adapters-core
typescript
import { CozoMemoryChatHistory, CozoMemoryRetriever } from '@cozo-memory/langchain';
const chatHistory = new CozoMemoryChatHistory({ sessionName: 'user-123' });const retriever = new CozoMemoryRetriever({ useGraphRAG: true, graphRAGDepth: 2 });

🦙 LlamaIndex Adapter

bash
npm install @cozo-memory/llamaindex @cozo-memory/adapters-core
typescript
import { CozoVectorStore } from '@cozo-memory/llamaindex';
const vectorStore = new CozoVectorStore({ useGraphRAG: true });

Documentation: See adapters/README.md for complete examples and API reference.

CLI & TUI

CLI Tool

Full-featured CLI for all operations:

bash
# System operationscozo-memory system healthcozo-memory system metrics
# Entity operationscozo-memory entity create -n "MyEntity" -t "person"cozo-memory entity get -i <entity-id>
# Searchcozo-memory search query -q "search term" -l 10cozo-memory search agentic -q "agentic query"
# Graph operationscozo-memory graph pagerankcozo-memory graph communities
# Export/Importcozo-memory export json -o backup.jsoncozo-memory import file -i data.json -f cozo
# All commands support -f json or -f pretty for output formatting

See CLI help for complete command reference: cozo-memory --help

TUI (Terminal User Interface)

Interactive TUI with mouse support powered by Python Textual:

bash
# Install Python dependencies (one-time)pip install textual
# Launch TUInpm run tui# or directly:cozo-memory-tui

TUI Features:

  • 🖱️ Full mouse support (click buttons, scroll, select inputs)
  • ⌨️ Keyboard shortcuts (q=quit, h=help, r=refresh)
  • 📊 Interactive menus for all operations
  • 🎨 Rich terminal UI with colors and animations

Architecture Overview

mermaid
graph TB    Client[MCP Client<br/>Claude Desktop, etc.]    Server[MCP Server<br/>FastMCP + Zod Schemas]    Services[Memory Services]    Embeddings[Embeddings<br/>ONNX Runtime]    Search[Hybrid Search<br/>RRF Fusion]    Cache[Semantic Cache<br/>L1 + L2]    Inference[Inference Engine<br/>Multi-Strategy]    DB[(CozoDB SQLite<br/>Relations + Validity<br/>HNSW Indices<br/>Datalog/Graph)]        Client -->|stdio| Server    Server --> Services    Services --> Embeddings    Services --> Search    Services --> Cache    Services --> Inference    Services --> DB        style Client fill:#e1f5ff,color:#000    style Server fill:#fff4e1,color:#000    style Services fill:#f0e1ff,color:#000    style DB fill:#e1ffe1,color:#000

See docs/ARCHITECTURE.md for detailed architecture documentation

MCP Tools Overview

The interface is reduced to 5 consolidated tools:

ToolPurposeKey Actions
mutate_memoryWrite operationscreate_entity, update_entity, delete_entity, add_observation, create_relation, transactions, sessions, tasks, update_observation, batch_delete, manage_tags, batch
query_memoryRead operationssearch, advancedSearch, context, graph_rag, graph_walking, agentic_search, adaptive_retrieval, list_entities, get_entity_detail, get_session_context, list_sessions
analyze_graphGraph analysisexplore, communities, pagerank, betweenness, hits, shortest_path, semantic_walk
manage_systemMaintenancehealth, metrics, stats, export, import, cleanup, defrag, reflect, snapshots
edit_user_profileUser preferencesEdit global user profile with preferences and work style

See docs/API.md for complete API reference with all parameters and examples

Troubleshooting

Common Issues

First Start Takes Long

  • The embedding model download takes 30-90 seconds on first start (Transformers loads ~500MB of artifacts)
  • This is normal and only happens once
  • Subsequent starts are fast (< 2 seconds)

LLM-powered actions require Ollama

  • The following actions use a local LLM for intelligent processing: cleanup, reflect, summarize_communities, compact, agentic_search
  • Install Ollama from https://ollama.ai
  • Pull the desired model: ollama pull demyagent-4b-i1:Q6_K (or your preferred model)
  • Without Ollama, these actions fall back to non-LLM behavior or return a clear error
  • Core features (CRUD, search, graph, infer) work without any LLM

Windows-Specific

  • Embeddings are processed on CPU for maximum compatibility
  • RocksDB backend requires Visual C++ Redistributable if using that option

Performance Issues

  • First query after restart is slower (cold cache)
  • Use health action to check cache hit rates
  • Consider RocksDB backend for datasets > 100k entities

See docs/BENCHMARKS.md for performance optimization tips

Documentation

Development

Structure

  • src/index.ts: MCP Server + Tool Registration
  • src/memory-service.ts: Core business logic
  • src/db-service.ts: Database operations
  • src/embedding-service.ts: Embedding Pipeline + Cache
  • src/hybrid-search.ts: Search Strategies + RRF
  • src/inference-engine.ts: Inference Strategies
  • src/api_bridge.ts: Express API Bridge (optional)

Scripts

bash
npm run build        # TypeScript Buildnpm run dev          # ts-node Start of MCP Servernpm run start        # Starts dist/index.js (stdio)npm run bridge       # Build + Start of API Bridgenpm run benchmark    # Runs performance testsnpm run eval         # Runs evaluation suite

Contributing

Contributions are welcome! Please see CONTRIBUTING.md for guidelines.

License

Apache 2.0 - See LICENSE for details.

Acknowledgments

Built with:

Research foundations:

  • GraphRAG-R1 (Yu et al., WWW 2026) - conceptual inspiration for adaptive retrieval
  • HopRAG (ACL 2025) - conceptual inspiration for multi-hop reasoning
  • T-GRAG (Li et al., 2025) - conceptual inspiration for temporal conflict resolution
  • FEEG Framework (Samuel et al., 2026) - conceptual inspiration for query intent classification
  • Allan-Poe (arXiv:2511.00855) - conceptual inspiration for dynamic fusion

来源:README.md,提交 341cd38

工具

0
SourceWeft 尚未在沙箱中启动过该软件包,因此其工具未知。

版本历史

1
  1. v1.0.3最新Sep 16, 2026

评分

已满足适用检查项的 50%

该评分衡量此收录条目的完整程度,依据注册中心条目、端点与公开来源计算得出。它不是对服务器本身的评价,也不表示服务器安全或当前可用:可连通性是带日期的检查结果,评分也不包含安装量或用户评价。

  • 近 30 天内可连通25 分

    请保持端点能够响应 MCP 握手;SourceWeft 每 30 天探测一次。

  • 已声明认证方式10 分

    请在注册中心条目中声明凭据请求头,或保持端点能够响应探测,以便判定其认证方式。

  • 已列出工具15 分

    请让服务器在无凭据时响应 tools/list,或发布可在沙箱中无凭据启动的软件包。

  • 描述必需15 分
  • 图标10 分
  • 文档15 分
  • 许可证10 分

其他 Memory 集成