{
  "markdown": "# CozoDB Memory MCP Server\n\n[![npm](https://img.shields.io/npm/v/cozo-memory)](https://www.npmjs.com/package/cozo-memory)\n[![Node](https://img.shields.io/node/v/cozo-memory)](https://nodejs.org)\n[![License](https://img.shields.io/badge/license-Apache%202.0-blue)](LICENSE)\n[![MCP Badge](https://lobehub.com/badge/mcp/tobs-code-cozo-memory)](https://lobehub.com/mcp/tobs-code-cozo-memory)\n\n> **Why Cozo Memory?**  \n> 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).\n>\n> 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.\n\n**Local-first memory for Claude & AI agents with hybrid search, Graph-RAG, and time-travel – runs entirely on your machine. Optional [Ollama](https://ollama.ai) integration enables LLM-powered actions (cleanup, reflect, summarize, agentic retrieval).**\n\n## Table of Contents\n\n- [Quick Start](#quick-start)\n- [Key Features](#key-features)\n- [Positioning & Comparison](#positioning--comparison)\n- [Installation](#installation)\n- [Integration](#integration)\n- [Documentation](#documentation)\n- [Troubleshooting](#troubleshooting)\n\n## Quick Start\n\n### Option 1: Install via npm (Recommended)\n\n```bash\n# Install globally\nnpm install -g cozo-memory\n\n# Or run directly with npx (no installation needed)\nnpx cozo-memory\n```\n\n### Option 2: Build from Source\n\n```bash\ngit clone https://github.com/tobs-code/cozo-memory\ncd cozo-memory\nnpm install && npm run build\nnpm run start\n```\n\nNow add the server to your MCP client (e.g. Claude Desktop) – see [Integration](#integration) below.\n\n## Key Features\n\n🔍 **Hybrid Search** - Combines semantic (HNSW), full-text (FTS), and graph signals via Reciprocal Rank Fusion for intelligent retrieval\n\n🧠 **Agentic Retrieval** - Auto-routing engine analyzes query intent via local LLM to select optimal search strategy (Vector, Graph, or Community)\n\n⏱️ **Time-Travel Queries** - Version all changes via CozoDB Validity; query any point in history with full audit trails\n\n🎯 **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\n\n⏳ **Temporal Conflict Resolution** - Automatic detection and resolution of contradictory observations with semantic analysis and audit preservation\n\n🏠 **100% Local** - Embeddings via ONNX/Transformers; data stays on your machine. Some advanced features (cleanup, reflect, summarize, agentic search) require an optional [Ollama](https://ollama.ai) service for local LLM inference — but the core search, CRUD, and graph operations work **without any LLM**.\n\n🧠 **Multi-Hop Reasoning** - Logic-aware graph traversal with vector pivots for deep relational reasoning\n\n🗂️ **Hierarchical Memory** - Multi-level architecture (L0-L3) with intelligent compression and LLM-backed summarization\n\n> **[→ See all features](docs/FEATURES.md)** | **[Version History](CHANGELOG.md)**\n\n## Positioning & Comparison\n\n### Why CozoDB instead of SQLite + Chroma + NetworkX?\n\nA common first question is: *\"Why not just combine existing tools?\"*\n\n| If you need... | Typical separate stack | CozoDB Memory |\n| :--- | :--- | :--- |\n| Structured data & relations | **SQLite** / PostgreSQL | ✅ Built-in relational engine |\n| Semantic / vector search | **Chroma** / Qdrant / Pinecone | ✅ HNSW + FTS + RRF in one engine |\n| Graph traversal & reasoning | **NetworkX** / Neo4j | ✅ Native graph queries + PageRank |\n| Time-travel / versioning | Custom audit tables | ✅ Built-in `Validity` time-travel |\n| Unified query language | Multiple APIs + glue code | ✅ Single Datalog query across all dimensions |\n\n**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:\n\n- **One query language** (Datalog) reaches every dimension.\n- **No sync lag** between separate indexes.\n- **No ETL bridge** between \"vector results\" and \"graph expansion.\"\n- **Smaller operational surface**: one database file, one process, one dependency chain.\n\n### Comparison with other memory solutions\n\nMost \"Memory\" MCP servers fall into two categories:\n1. **Simple Knowledge Graphs**: CRUD operations on triples, often only text search\n2. **Pure Vector Stores**: Semantic search (RAG), but little understanding of complex relationships\n\nThis 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.\n\n| Feature | **CozoDB Memory (This Project)** | **Official Reference (`@modelcontextprotocol/server-memory`)** | **mcp-memory-service (Community)** | **Database Adapters (Qdrant/Neo4j)** |\n| :--- | :--- | :--- | :--- | :--- |\n| **Backend** | **CozoDB** (Graph + Vector + Relational + FTS in one engine) | JSON file (`memory.jsonl`) | SQLite / Cloudflare | Specialized DB (only Vector or Graph) |\n| **Search Logic** | **Agentic (Auto-Route)**: Hybrid + Graph + Summaries | Keyword only / Exact Graph Match | Vector + Keyword | Mostly only one dimension |\n| **Inference** | **Yes**: Built-in engine for implicit knowledge | No | No (\"Dreaming\" is consolidation) | No (Retrieval only) |\n| **Community** | **Yes**: Hierarchical Community Summaries | No | No | Only clustering (no summary) |\n| **Time-Travel** | **Yes**: Queries at any point in time (`Validity`) | No (current state only) | History available, no native DB feature | No |\n| **Maintenance** | **Janitor**: LLM-backed cleanup | Manual | Automatic consolidation | Mostly manual |\n| **Deployment** | **Local** (Node.js + Embedded DB) | Local (Docker/NPX) | Local or Cloud | Often requires external DB server |\n\nThe 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.\n\n## Installation\n\n### Prerequisites\n\n- Node.js 20+ (recommended)\n- **RAM: 1.7 GB minimum** (for default bge-m3 model)\n  - Model download: ~600 MB\n  - Runtime memory: ~1.1 GB\n  - ⚡ **Too heavy?** Use `EMBEDDING_MODEL=Xenova/all-MiniLM-L6-v2` – only **~400 MB RAM** needed (see [Embedding Model Options](#embedding-model-options))\n- CozoDB native dependency is installed via `cozo-node`\n\n### Optional: Ollama for LLM-powered actions\n\nSome advanced actions use a local LLM via [Ollama](https://ollama.ai) for intelligent\nprocessing. **The core server works without Ollama** (CRUD, search, graph operations),\nbut the following actions require it:\n\n| Action | Purpose |\n|--------|---------|\n| `cleanup` | LLM-backed observation consolidation |\n| `reflect` | Generate insights, detect contradictions |\n| `summarize_communities` | LLM-generated community summaries |\n| `compact` | Session / entity compaction with LLM summarization |\n| `agentic_search` | Query intent classification for auto-routing |\n\n**Setup (if you need these features):**\n```bash\n# 1. Install Ollama from https://ollama.ai\n# 2. Pull a model (e.g. small + fast for dev):\nollama pull demyagent-4b-i1:Q6_K\n# 3. Ollama runs automatically on http://localhost:11434\n```\n\nIf Ollama is not running, the affected actions gracefully fall back to non-LLM behavior\n(where possible) or return a clear error message.\n\n### Via npm (Easiest)\n\n```bash\n# Install globally\nnpm install -g cozo-memory\n\n# Or use npx without installation\nnpx cozo-memory\n```\n\n### From Source\n\n```bash\ngit clone https://github.com/tobs-code/cozo-memory\ncd cozo-memory\nnpm install\nnpm run build\n```\n\n### Windows Quickstart\n\n```bash\nnpm install\nnpm run build\nnpm run start\n```\n\n**Notes:**\n- On first start, `@xenova/transformers` downloads the embedding model (may take time)\n- Embeddings are processed on the CPU\n\n### Embedding Model Options\n\nCozoDB Memory supports multiple embedding models via the `EMBEDDING_MODEL` environment variable:\n\n| Model | Size | RAM | Dimensions | Best For |\n|-------|------|-----|------------|----------|\n| `Xenova/bge-m3` (default) | ~600 MB | ~1.7 GB | 1024 | High accuracy, production use |\n| `Xenova/all-MiniLM-L6-v2` | ~80 MB | ~400 MB | 384 | Low-spec machines, development |\n| `Xenova/bge-small-en-v1.5` | ~130 MB | ~600 MB | 384 | Balanced performance |\n\n**Configuration Options:**\n\n**Option 1: Using `.env` file (Easiest for beginners)**\n\n```bash\n# Copy the example file\ncp .env.example .env\n\n# Edit .env and set your preferred model\nEMBEDDING_MODEL=Xenova/all-MiniLM-L6-v2\n```\n\n**Option 2: MCP Server Config (For Claude Desktop / Kiro)**\n\n```json\n{\n  \"mcpServers\": {\n    \"cozo-memory\": {\n      \"command\": \"npx\",\n      \"args\": [\"cozo-memory\"],\n      \"env\": {\n        \"EMBEDDING_MODEL\": \"Xenova/all-MiniLM-L6-v2\"\n      }\n    }\n  }\n}\n```\n\n**Option 3: Command Line**\n\n```bash\n# Use lightweight model for development\nEMBEDDING_MODEL=Xenova/all-MiniLM-L6-v2 npm run start\n```\n\n**Download Model First (Recommended):**\n\n```bash\n# Set model in .env or via command line, then:\nEMBEDDING_MODEL=Xenova/all-MiniLM-L6-v2 npm run download-model\n```\n\n**Note:** Changing models requires re-embedding existing data. The model is downloaded once on first use.\n\n## Integration\n\n### Claude Desktop\n\n#### Using npx (Recommended)\n\n```json\n{\n  \"mcpServers\": {\n    \"cozo-memory\": {\n      \"command\": \"npx\",\n      \"args\": [\"cozo-memory\"]\n    }\n  }\n}\n```\n\n#### Using global installation\n\n```json\n{\n  \"mcpServers\": {\n    \"cozo-memory\": {\n      \"command\": \"cozo-memory\"\n    }\n  }\n}\n```\n\n#### Using local build\n\n```json\n{\n  \"mcpServers\": {\n    \"cozo-memory\": {\n      \"command\": \"node\",\n      \"args\": [\"C:/Path/to/cozo-memory/dist/index.js\"]\n    }\n  }\n}\n```\n\n### Framework Adapters\n\nOfficial adapters for seamless integration with popular AI frameworks:\n\n**🦜 LangChain Adapter**\n\n```bash\nnpm install @cozo-memory/langchain @cozo-memory/adapters-core\n```\n\n```typescript\nimport { CozoMemoryChatHistory, CozoMemoryRetriever } from '@cozo-memory/langchain';\n\nconst chatHistory = new CozoMemoryChatHistory({ sessionName: 'user-123' });\nconst retriever = new CozoMemoryRetriever({ useGraphRAG: true, graphRAGDepth: 2 });\n```\n\n**🦙 LlamaIndex Adapter**\n\n```bash\nnpm install @cozo-memory/llamaindex @cozo-memory/adapters-core\n```\n\n```typescript\nimport { CozoVectorStore } from '@cozo-memory/llamaindex';\n\nconst vectorStore = new CozoVectorStore({ useGraphRAG: true });\n```\n\n**Documentation:** See [adapters/README.md](./adapters/README.md) for complete examples and API reference.\n\n## CLI & TUI\n\n### CLI Tool\n\nFull-featured CLI for all operations:\n\n```bash\n# System operations\ncozo-memory system health\ncozo-memory system metrics\n\n# Entity operations\ncozo-memory entity create -n \"MyEntity\" -t \"person\"\ncozo-memory entity get -i <entity-id>\n\n# Search\ncozo-memory search query -q \"search term\" -l 10\ncozo-memory search agentic -q \"agentic query\"\n\n# Graph operations\ncozo-memory graph pagerank\ncozo-memory graph communities\n\n# Export/Import\ncozo-memory export json -o backup.json\ncozo-memory import file -i data.json -f cozo\n\n# All commands support -f json or -f pretty for output formatting\n```\n\n> **See CLI help for complete command reference: `cozo-memory --help`**\n\n### TUI (Terminal User Interface)\n\nInteractive TUI with mouse support powered by Python Textual:\n\n```bash\n# Install Python dependencies (one-time)\npip install textual\n\n# Launch TUI\nnpm run tui\n# or directly:\ncozo-memory-tui\n```\n\n**TUI Features:**\n- 🖱️ Full mouse support (click buttons, scroll, select inputs)\n- ⌨️ Keyboard shortcuts (q=quit, h=help, r=refresh)\n- 📊 Interactive menus for all operations\n- 🎨 Rich terminal UI with colors and animations\n\n## Architecture Overview\n\n```mermaid\ngraph TB\n    Client[MCP Client<br/>Claude Desktop, etc.]\n    Server[MCP Server<br/>FastMCP + Zod Schemas]\n    Services[Memory Services]\n    Embeddings[Embeddings<br/>ONNX Runtime]\n    Search[Hybrid Search<br/>RRF Fusion]\n    Cache[Semantic Cache<br/>L1 + L2]\n    Inference[Inference Engine<br/>Multi-Strategy]\n    DB[(CozoDB SQLite<br/>Relations + Validity<br/>HNSW Indices<br/>Datalog/Graph)]\n    \n    Client -->|stdio| Server\n    Server --> Services\n    Services --> Embeddings\n    Services --> Search\n    Services --> Cache\n    Services --> Inference\n    Services --> DB\n    \n    style Client fill:#e1f5ff,color:#000\n    style Server fill:#fff4e1,color:#000\n    style Services fill:#f0e1ff,color:#000\n    style DB fill:#e1ffe1,color:#000\n```\n\n> **See [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) for detailed architecture documentation**\n\n## MCP Tools Overview\n\nThe interface is reduced to **5 consolidated tools**:\n\n| Tool | Purpose | Key Actions |\n|------|---------|-------------|\n| `mutate_memory` | Write operations | create_entity, update_entity, delete_entity, add_observation, create_relation, transactions, sessions, tasks, update_observation, batch_delete, manage_tags, batch |\n| `query_memory` | Read operations | search, advancedSearch, context, graph_rag, graph_walking, agentic_search, adaptive_retrieval, list_entities, get_entity_detail, get_session_context, list_sessions |\n| `analyze_graph` | Graph analysis | explore, communities, pagerank, betweenness, hits, shortest_path, semantic_walk |\n| `manage_system` | Maintenance | health, metrics, stats, export, import, cleanup, defrag, reflect, snapshots |\n| `edit_user_profile` | User preferences | Edit global user profile with preferences and work style |\n\n> **See [docs/API.md](docs/API.md) for complete API reference with all parameters and examples**\n\n## Troubleshooting\n\n### Common Issues\n\n**First Start Takes Long**\n- The embedding model download takes 30-90 seconds on first start (Transformers loads ~500MB of artifacts)\n- This is normal and only happens once\n- Subsequent starts are fast (< 2 seconds)\n\n**LLM-powered actions require Ollama**\n- The following actions use a local LLM for intelligent processing: `cleanup`, `reflect`, `summarize_communities`, `compact`, `agentic_search`\n- Install Ollama from https://ollama.ai\n- Pull the desired model: `ollama pull demyagent-4b-i1:Q6_K` (or your preferred model)\n- Without Ollama, these actions fall back to non-LLM behavior or return a clear error\n- **Core features (CRUD, search, graph, infer) work without any LLM**\n\n**Windows-Specific**\n- Embeddings are processed on CPU for maximum compatibility\n- RocksDB backend requires Visual C++ Redistributable if using that option\n\n**Performance Issues**\n- First query after restart is slower (cold cache)\n- Use `health` action to check cache hit rates\n- Consider RocksDB backend for datasets > 100k entities\n\n> **See [docs/BENCHMARKS.md](docs/BENCHMARKS.md) for performance optimization tips**\n\n## Documentation\n\n- **[docs/API.md](docs/API.md)** - Complete MCP tools reference with all parameters and examples\n- **[docs/ARCHITECTURE.md](docs/ARCHITECTURE.md)** - System architecture, data model, and technical details\n- **[docs/BENCHMARKS.md](docs/BENCHMARKS.md)** - Performance metrics, evaluation results, and optimization tips\n- **[docs/FEATURES.md](docs/FEATURES.md)** - Detailed feature documentation with usage examples\n- **[docs/USER-PROFILING.md](docs/USER-PROFILING.md)** - User preference profiling and personalization\n- **[CHANGELOG.md](CHANGELOG.md)** - Version history and release notes\n- **[CONTRIBUTING.md](CONTRIBUTING.md)** - Development guidelines\n\n## Development\n\n### Structure\n\n- `src/index.ts`: MCP Server + Tool Registration\n- `src/memory-service.ts`: Core business logic\n- `src/db-service.ts`: Database operations\n- `src/embedding-service.ts`: Embedding Pipeline + Cache\n- `src/hybrid-search.ts`: Search Strategies + RRF\n- `src/inference-engine.ts`: Inference Strategies\n- `src/api_bridge.ts`: Express API Bridge (optional)\n\n### Scripts\n\n```bash\nnpm run build        # TypeScript Build\nnpm run dev          # ts-node Start of MCP Server\nnpm run start        # Starts dist/index.js (stdio)\nnpm run bridge       # Build + Start of API Bridge\nnpm run benchmark    # Runs performance tests\nnpm run eval         # Runs evaluation suite\n```\n\n## Contributing\n\nContributions are welcome! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines.\n\n## License\n\nApache 2.0 - See [LICENSE](LICENSE) for details.\n\n## Acknowledgments\n\nBuilt with:\n- [CozoDB](https://github.com/cozodb/cozo) - Embedded graph database\n- [ONNX Runtime](https://onnxruntime.ai/) - Local embedding generation\n- [Transformers.js](https://huggingface.co/docs/transformers.js) - Xenova/bge-m3 model\n- [FastMCP](https://github.com/jlowin/fastmcp) - MCP server framework\n\nResearch foundations:\n- GraphRAG-R1 (Yu et al., WWW 2026) - conceptual inspiration for adaptive retrieval\n- HopRAG (ACL 2025) - conceptual inspiration for multi-hop reasoning\n- T-GRAG (Li et al., 2025) - conceptual inspiration for temporal conflict resolution\n- FEEG Framework (Samuel et al., 2026) - conceptual inspiration for query intent classification\n- Allan-Poe (arXiv:2511.00855) - conceptual inspiration for dynamic fusion\n",
  "bytes": 17647,
  "sha": "04d8eece126cdf867f205f5165595286edde1bb4e568955f292f45d4fed89ddd",
  "repo_slug": "tobs-code/cozo-memory",
  "fonte": "repo",
  "truncated": false,
  "api": "https://agentalog.com/api/listings/mcp_io_github_tobs_code_cozo_memory_e1489ed2/readme"
}