mnestic-mcp

v0.3.0
mnestic-mcp Checked 2 hours ago Published 18 days ago

Local memory MCP server backed by mnestic — hybrid BM25+vector+graph recall with per-leg attribution and time travel, all on your machine.

Upstream's last commit was 2024-12-04. mnestic continues the engine, with these capabilities on top of it: Everything else — CozoScript, the storage engines, the data model — is upstream CozoDB, unchanged unless noted in CHANGELOG-FORK.md. No storage-format change; existing databases open without migration. mnestic-rocks moves to 0.1.14.

Summary extracted from the README.

mnestic

mnestic is an independently maintained fork of CozoDB, a transactional relational-graph-vector database that uses Datalog for queries — "the hippocampus for AI." This fork continues the project as a substrate for agentic memory, with performance, correctness, and operational fixes on top of upstream 481af05 (the last upstream commit, 2024-12-04).

mnestic is not the official CozoDB and is not affiliated with or endorsed by its original authors. All credit for the original design belongs to Ziyang Hu and the Cozo Project Authors. See FORK.md for provenance and licensing, and CHANGELOG-FORK.md for what diverges from upstream.

[ English | 中文 ]

What mnestic adds over CozoDB

Upstream's last commit was 2024-12-04. mnestic continues the engine, with these capabilities on top of it:

  • Cached graph projections — ::graph create G { edges: knows } names an in-memory adjacency that twelve graph algorithms reuse across queries instead of rebuilding on every call. Always fresh: a projection never serves data differing from what the consuming transaction's own scan would return, and a write to a source frees what was built from it. (spec)
  • Budgeted weighted traversal — BudgetedTraversal expands cheapest-first from a set of seeds, over non-negative weights, under a global distinct-node budget (plus optional cost ceiling and exact hop bound) and an in-expansion admission gate, emitting each admitted node's (cost, parent, depth). Deterministic by construction, interruptible, and able to consume a cached graph projection — the primitive for filling a fixed context window with the cheapest graph neighborhood around a set of search hits. (spec)
  • Bitemporality — a TxTime column type with a crash-safe monotone commit clock, :as_of reads, the two-level (valid time, transaction time) resolution, and ::history / ::history_gc / ::evict. (spec)
  • Calendar-aware datetime library — component extractors (dt_year … dt_dow), dt_trunc, calendar-aware dt_add / dt_diff, timezone-aware dt_format, and dt_to_validity — the typed bridge from float Unix seconds to a Validity's integer microseconds, so a timestamp reaches the valid-time axis as a validity rather than a bare number whose unit the engine must guess.
  • Provenance semirings — user-defined absorptive combines inside recursion (Db::register_custom_aggr), the min_cost_k bounded-meet aggregate returning the k best derivations with their evidence chains, and :reconcile recompute-based belief revision. (spec)
  • Skyline / Pareto-frontier aggregates — pareto_min / pareto_max keep, per group, the non-dominated set over a numeric vector (native componentwise dominance), surfacing a contested set — answers none of which beats another — instead of collapsing to one winner. Reachable from every binding through plain run_script; arbitrary caller-defined dominance is available in Rust via register_bounded_meet_aggr. (spec)
  • In-engine hybrid retrieval — reciprocal-rank fusion over vector, full-text and graph legs as one Datalog-composable fixed rule, with MMR diversification. Each leg is optional, and a graph leg can run as budgeted cheapest-first expansion — seeded from the vector/FTS hits — to fill a fixed context budget with the cheapest graph neighborhood around what recall found.
  • Read-only Cypher — an openCypher subset translated to CozoScript (alpha; feature cypher, off by default). (spec)
  • Stored / named queries — ::query create/list/show/run/remove persists reusable, optionally typed and defaulted read rules. Invoke one by name or as a normal rule atom; atom form is hygienically spliced before magic-set rewriting, so caller bindings specialize through the stored rule chain. (spec)
  • Atomic Parquet / Arrow copy-in — the feature-gated host API imports one local Parquet or Arrow IPC file into an existing relation in a single transaction, with explicit conversion/resource limits and a report naming search indexes that require rebuilding. (spec)
  • Candidate-scoped full-text retrieval — candidates: restricts an FTS atom to an allowlist of base-relation primary keys before top-k truncation, while retaining corpus-global BM25 scores for eligible documents. (spec)
  • Faster lookups and plans — equality pushdown turns post-filter point lookups into keyed seeks (~28× at 5k rows), plus a deterministic greedy join reorder and a default-on factorized count() rewrite.
  • Non-blocking vector index builds — HNSW builds in RAM in parallel and no longer blocks reads for minutes; search-path neighbour vectors batch-fetch through RocksDB MultiGet.
  • Operational recovery — ::reindex rebuilds a relation's HNSW / FTS / LSH indexes in place from the configuration the database already stores, so a bulk load or a backup restore (neither of which maintains those indexes) has a repair path that is not "drop it and reconstruct the creation script by hand"; and ::repair_corrupt surgically deletes truncated tuples instead of forcing you to drop a database that fails an integrity check.
  • Interruptibility that works — ::kill and :timeout abort running queries, including long graph-adjacency builds.
  • Governed multi-transactions — a native Rust host-owned worker retains admission through cancellation and cleanup, with one deadline, bounded idle waiting, inherited statement memory limits and warning flushes. Any query error aborts the transaction; the legacy API remains available. (contract)

Everything else — CozoScript, the storage engines, the data model — is upstream CozoDB, unchanged unless noted in CHANGELOG-FORK.md.

New in 0.20.0

Complete transaction-time indexing, triggers, projections, and history-preserving backup/restore — plus keyed planner seeks, parallel native hybrid_search, and GCC 15+ RocksDB builds.

  • Transaction-time (TxTime) current-belief search, B-tree indexes, triggers, graph projections, and history I/O: FTS, HNSW, LSH, and secondary B-tree indexes (::index create) maintain current asserted beliefs on tt-only relations (with off-lock RocksDB SortedKvArena SST backfills, WRITE_ONLY shadow dual-write maintenance, and persistent shadow VectorCache). :as_of vector queries execute a bounded exact history scan (hnsw_history_scan, 200,000-row fail-closed bound). ::set_triggers (on put/on rm) and cached ::graph projections work on tt-only relations, and export_txtime_state / import_relations_with_history / import_from_backup preserve full TxTime history, gc_floor, and monotonic tt_hwm.
  • Planner keyed access & stored negation: Trailing equalities, full-key joins with nonadjacent value columns (stored_point_join), and stored negations (stored_neg_point_join) use keyed point lookups instead of full-relation scans. Unindexed stored joins emit missing_index_advisory in ::explain and query.missing_index in ::warnings.
  • Native parallel hybrid_search & HNSW/FTS query speedups: Single-snapshot parallel leg execution in Db::hybrid_search (GraphLeg adds target_relation/target_node_col/target_id_col/limit), 128 MiB default RocksDB block cache, raw-KV HNSW neighbour decoding, zero-allocation FTS posting fast path, and batched top-k fetches.
  • Operational diagnostics & GCC 15+ fix: Shared relation storage IDs now surface storage.relation_id_collision through ::warnings at open, and mnestic-rocks moves to 0.1.14 to include <cstdint> for GCC 15+ builds.

No storage-format change; existing databases open without migration. mnestic-rocks moves to 0.1.14.

From 0.19.4

A full-text posting with no row no longer fails the search. A search reads the row of every ranked hit, and a missing row raised corrupted index, so one stale posting failed every query that ranked it. The search now skips that hit, returns the next-best one in its place, and records an fts.dangling_posting warning (::warnings); cozo::fts_dangling_postings_skipped() returns the process-wide count.

Such postings exist where a relation with only a full-text index was updated in place by a release through 0.12.0 and never rebuilt, or where rows were removed by bulk import. ::reindex <relation> removes them.

No storage-format change; mnestic-rocks stays 0.1.13.

From 0.19.3

Full-text search no longer rescans its index when writes overlap. BM25 needs each index's document and token totals. They lived only in memory, so a search after opening a database, or one whose snapshot overlapped a write commit, rescanned every posting of the index. On RocksDB at 40,000 documents such a search took 1,168 ms at the median against 122 ms warm; the scan grows with the index.

  • db.enable_persisted_fts_stats() (RocksDB) stores the totals inside each index as a base record plus one delta record per write transaction. Writers never contend on them. A read-only search sums them for its snapshot: exact, and no scan.
  • db.seed_fts_stats() computes the base once without pausing writers; db.fold_fts_stats(min_deltas) folds deltas into the base (call it periodically); db.verify_fts_stats() and db.repair_fts_stats() check and correct them against a scan.
  • Records are trusted only if nothing else wrote to the store since the last clean close, compared through RocksDB's sequence number. After a crash, a restore, or a write by an engine without this feature, they are ignored until reseeded. Off unless enabled.

Also new: governed transactions from Python (see the PyPI readme). No storage version change; mnestic-rocks moves to 0.1.13.

From 0.19.2

Faster writes, complete filtered search, no ANN-orphaned rows. Measured at 40,000 rows (dim 384) against 0.19.0 on SQLite:

  • SQLite uses a write-ahead log by default (synchronous = FULL, so an acknowledged commit still survives power loss), a 32 MiB page cache, a 5 s busy timeout, and WITHOUT ROWID storage for new files. Update p50 300 → 20 ms, delete p50 193 → 7 ms, hybrid search p50 189 → 37 ms. Existing files switch to WAL on first open and gain -wal/-shm sidecars while open; use ::backup to copy a database. Opt out with {"journal_mode": "delete"}.
  • No corpus scan on the write path: the first write after opening a database with a full-text index took 7.8 s; it now takes 0.03 s. The first search seeds BM25 totals instead.
  • Unchanged fields skip index work: editing only text keeps the HNSW entry; re-embedding keeps the FTS postings.
  • Filtered vector search is complete: when fewer than k candidates pass a filter:, the search scores every eligible row exactly (bounded at 200,000 rows, else warns hnsw.filtered_incomplete). A 1.9% filter went from recall@10 0.18 to 1.0; a partial index remains the fast path (0.999 at 8 ms).
  • HNSW orphan guards: fallback repairs no longer leave a vector with no incoming edge, which no search could reach. No writes are rejected under churn (0.19.0: 517 of 6,000).
  • Python mnestic.MnesticError (an Exception subclass; args[0] unchanged) with code, kind, retryable and message.

No storage-format change; mnestic-rocks stays 0.1.12.

From 0.19.1

HNSW repair limits fall back with a structured hnsw.repair_fallback warning instead of failing the write (0.19.0 rejected 3,293 writes over ten churn rounds at 10,000 rows). Rows the fallback leaves hard to reach stay available to exact scans, keyed queries and other indexes; ::reindex <relation> rebuilds the graph.

From 0.19.0

0.19.0 added governed native Rust transactions and repaired transactional FTS statistics and HNSW mutation connectivity.

  • Governed transactions (native Rust): db.governed_transaction(write, options) returns a serialized client and host-owned worker. One deadline, bounded idle waiting, inherited statement memory limits and warning flushes apply across the transaction; every query error rolls it back. Hosts retain admission until the worker exits. Cancellation is cooperative and can race a commit, so hosts must reconcile uncertain outcomes. Python and other bindings do not expose this API.
  • BREAKING (results): FTS scores/top-k now use statistics from the querying transaction's posting snapshot and pending writes. Aborts and failed commits no longer leak speculative totals. Recheck score thresholds and ranking fixtures; there is no legacy-statistics switch. Overlapping snapshots may rescan postings.
  • Rebuild pre-0.19 HNSW indexes with ::reindex <relation> after a backup, then validate search against exact base-row/vector queries. New mutations preserve directed paths; existing disconnections and missing legacy reverse records need that explicit rebuild. From 0.19.1 a repair that exceeds local degree/work caps falls back instead of failing the write and records an hnsw.repair_fallback warning.
  • ::warnings stays responsive during active memory/SQLite transactions. parser.string_decoding_changed is retired as promised; decoding is unchanged. The permanent 0.18 migration guidance still applies to legacy scripts.

Storage encoding and mnestic-rocks 0.1.12 are unchanged. The local repair caps are not total memory or latency guarantees; filtered-ANN eligibility and its approximate-recall limitations remain. Schedule maintenance time for index rebuilds and evaluate write costs on your workload. A focused comparison between two 0.19 builds measured write p95 increases of 3.1% on RocksDB and 11.8% on SQLite, with seed-sensitive tails; a separate one-seed window also showed roughly 16% increases in selected exact scans. These are not 0.18-to-0.19 measurements or a bound on upgrade cost. No general speedup or exact ANN recall is promised.

Full upgrade guidance is in the CHANGELOG-FORK.md.

Introduction

CozoDB is a general-purpose, transactional, relational database that uses Datalog for query, is embeddable but can also handle huge amounts of data and concurrency, and focuses on graph data and algorithms. It supports time travel and it is performant!

What does embeddable mean here?

A database is almost surely embedded if you can use it on a phone which never connects to any network (this situation is not as unusual as you might think). SQLite is embedded. MySQL/Postgres/Oracle are client-server.

A database is embedded if it runs in the same process as your main program. This is in contradistinction to client-server databases, where your program connects to a database server (maybe running on a separate machine) via a client library. Embedded databases generally require no setup and can be used in a much wider range of environments.

We say CozoDB is embeddable instead of embedded since you can also use it in client-server mode, which can make better use of server resources and allow much more concurrency than in embedded mode.

Why graphs?

Because data are inherently interconnected. Most insights about data can only be obtained if you take this interconnectedness into account.

Most existing graph databases start by requiring you to shoehorn your data into the labelled-property graph model. We don't go this route because we think the traditional relational model is much easier to work with for storing data, much more versatile, and can deal with graph data just fine. Even more importantly, the most piercing insights about data usually come from graph structures implicit several levels deep in your data. The relational model, being an algebra, can deal with it just fine. The property graph model, not so much, since that model is not very composable.

What is so cool about Datalog?

Datalog can express all relational queries. Recursion in Datalog is much easier to express, much more powerful, and usually runs faster than in SQL. Datalog is also extremely composable: you can build your queries piece by piece.

Recursion is especially important for graph queries. CozoDB's dialect of Datalog supercharges it even further by allowing recursion through a safe subset of aggregations, and by providing extremely efficient canned algorithms (such as PageRank) for the kinds of recursions frequently required in graph analysis.

As you learn Datalog, you will discover that the rules of Datalog are like functions in a programming language. Rules are composable, and decomposing a query into rules can make it clearer and more maintainable, with no loss in efficiency. This is unlike the monolithic approach taken by the SQL select-from-where in nested forms, which can sometimes read like golfing.

Time travel?

Time travel in the database setting means tracking changes to data over time and allowing queries to be logically executed at a point in time to get a historical view of the data.

In a sense, this makes your database immutable, since nothing is really deleted from the database ever.

In Cozo, instead of having all data automatically support time travel, we let you decide if you want the capability for each of your relation. Every extra functionality comes with its cost, and you don't want to pay the price if you don't use it.

For the reason why you might want time travel for your data, we have written a short story.

How performant?

On a 2020 Mac Mini with the RocksDB persistent storage engine (CozoDB supports many storage engines):

  • Running OLTP queries for a relation with 1.6M rows, you can expect around 100K QPS (queries per second) for mixed read/write/update transactional queries, and more than 250K QPS for read-only queries, with database peak memory usage around 50MB.
  • Speed for backup is around 1M rows per second, for restore is around 400K rows per second, and is insensitive to relation (table) size.
  • For OLAP queries, it takes around 1 second (within a factor of 2, depending on the exact operations) to scan a table with 1.6M rows. The time a query takes scales roughly with the number of rows the query touches, with memory usage determined mainly by the size of the return set.
  • Two-hop graph traversal completes in less than 1ms for a graph with 1.6M vertices and 31M edges.
  • The Pagerank algorithm completes in around 50ms for a graph with 10K vertices and 120K edges, around 1 second for a graph with 100K vertices and 1.7M edges, and around 30 seconds for a graph with 1.6M vertices and 32M edges.

For more numbers and further details, we have a writeup about performance here.

Getting started

For mnestic itself, start with the Python quickstart: pip install mnestic, then one script that opens a persistent store, builds vector and full-text indexes, retrieves with per-leg attribution, updates, backs up, reopens and restores. Coming from Neo4j, see Cypher to CozoScript. The upstream CozoDB material below still teaches the query language, but its WASM demo runs upstream CozoDB, not mnestic.

Usually, to learn a database, you need to install it first. This is unnecessary for CozoDB as a testimony to its extreme embeddability, since you can run a complete CozoDB instance in your browser, at near-native speed for most operations!

So open up the CozoDB in WASM page, and then:

Or you can skip ahead for the information about installing CozoDB into your favourite environment first.

Teasers

If you are in a hurry and just want a taste of what querying with CozoDB is like, here it is. In the following *route is a relation with two columns fr and to, representing a route between those airports, and FRA is the code for Frankfurt Airport.

How many airports are directly connected to FRA?

?[count_unique(to)] := *route{fr: 'FRA', to}
count_unique(to)
310

How many airports are reachable from FRA by one stop?

?[count_unique(to)] := *route{fr: 'FRA', to: stop},
                       *route{fr: stop, to}
count_unique(to)
2222

How many airports are reachable from FRA by any number of stops?

reachable[to] := *route{fr: 'FRA', to}
reachable[to] := reachable[stop], *route{fr: stop, to}
?[count_unique(to)] := reachable[to]
count_unique(to)
3462

What are the two most difficult-to-reach airports by the minimum number of hops required, starting from FRA?

shortest_paths[to, shortest(path)] := *route{fr: 'FRA', to},
                                      path = ['FRA', to]
shortest_paths[to, shortest(path)] := shortest_paths[stop, prev_path],
                                      *route{fr: stop, to},
                                      path = append(prev_path, to)
?[to, path, p_len] := shortest_paths[to, path], p_len = length(path)

:order -p_len
:limit 2
to path p_len
YPO ["FRA","YYZ","YTS","YMO","YFA","ZKE","YAT","YPO"] 8
BVI ["FRA","AUH","BNE","ISA","BQL","BEU","BVI"] 7

What is the shortest path between FRA and YPO, by actual distance travelled?

start[] <- [['FRA']]
end[] <- [['YPO]]
?[src, dst, distance, path] <~ ShortestPathDijkstra(*route[], start[], end[])
src dst distance path
FRA YPO 4544.0 ["FRA","YUL","YVO","YKQ","YMO","YFA","ZKE","YAT","YPO"]

CozoDB attempts to provide nice error messages when you make mistakes:

?[x, Y] := x = 1, y = x + 1

Install

We suggest that you try out CozoDB before you install it in your environment.

How you install CozoDB depends on which environment you want to use it in. Follow the links in the table below:

mnestic currently ships the Rust crate (crates.io/mnestic) and a Python binding (PyPI mnestic — pip install mnestic). The matrix below is upstream CozoDB's binding set, preserved for reference.

Language/Environment Official platform support Storage
Python Linux (x86_64), Mac (ARM64, x86_64), Windows (x86_64) MQR
NodeJS Linux (x86_64, ARM64), Mac (ARM64, x86_64), Windows (x86_64) MQR
Web browser Modern browsers supporting web assembly M
Java (JVM) Linux (x86_64, ARM64), Mac (ARM64, x86_64), Windows (x86_64) MQR
Clojure (JVM) Linux (x86_64, ARM64), Mac (ARM64, x86_64), Windows (x86_64) MQR
Android Android (ARM64, ARMv7, x86_64, x86) MQ
iOS/MacOS (Swift) iOS (ARM64, simulators), Mac (ARM64, x86_64) MQ
Rust Source only, usable on any platform with std support MQRST
Golang Linux (x86_64, ARM64), Mac (ARM64, x86_64), Windows (x86_64) MQR
C/C++/language with C FFI Linux (x86_64, ARM64), Mac (ARM64, x86_64), Windows (x86_64) MQR
Standalone HTTP server Linux (x86_64, ARM64), Mac (ARM64, x86_64), Windows (x86_64) MQRST
Lisp Linux (x86_64 so far) MR
Smalltalk Win10 & Linux (Ubuntu 23.04) x86_64 tested, MacOS should probably work MQR

For the storage column:

  • M: in-memory, non-persistent backend
  • Q: SQLite storage backend
  • R: RocksDB storage backend
  • S: Sled storage backend
  • T: TiKV distributed storage backend

The Rust doc has some tips on choosing storage, which is helpful even if you are not using Rust. Even if a storage/platform is not officially supported, you can still try to compile your version to use, maybe with some tweaks in the code.

Tuning the RocksDB backend for CozoDB

RocksDB has a lot of options, and by tuning them you can achieve better performance for your workload. This is probably unnecessary for 95% of users, but if you are the remaining 5%, CozoDB gives you the options to tune RocksDB directly if you are using the RocksDB storage engine.

When you create the CozoDB instance with the RocksDB backend option, you are asked to provide a path to a directory to store the data (will be created if it does not exist). If you put a file named options inside this directory, the engine will expect this to be a RocksDB options file and use it. If you are using the standalone cozo executable, you will get a log message if this feature is activated.

Note that improperly set options can make your database misbehave! In general, you should run your database once, copy the options file from data/OPTIONS-XXXXXX from within your database directory, and use that as a base for your customization. If you are not an expert on RocksDB, we suggest you limit your changes to adjusting those numerical options that you at least have a vague understanding.

Architecture

CozoDB consists of three layers stuck on top of each other, with each layer only calling into the layer below:

Storage engine

The storage engine defines a storage trait for the storage backend, which is an interface with required operations, mainly the provision of a key-value store for binary data with range scan capabilities. There are various implementations:

  • In-memory, non-persistent backend
  • SQLite storage backend
  • RocksDB storage backend
  • Sled storage backend
  • TiKV distributed storage backend

Depending on the build configuration, not all backends may be available in a binary release. The SQLite backend is special in that it is also used as the backup file format, which allows the exchange of data between databases with different backends. If you are using the database embedded in Rust, you can even provide your own custom backend.

The storage engine also defines a row-oriented binary data format, which the storage engine implementation does not need to know anything about. This format contains an implementation of the memcomparable format used for the keys, which enables the storage of rows of data as binary blobs that, when sorted lexicographically, give the correct order. This also means that data files for the SQLite backend cannot be queried with SQL in the usual way, and access must be through the decoding process in CozoDB.

Query engine

The query engine part provides various functionalities:

  • function/aggregation/algorithm definitions
  • database schema
  • transaction
  • query compilation
  • query execution

This part is where most of the code of CozoDB is concerned. The CozoScript manual has a chapter about the execution process.

Users interact with the query engine with the Rust API.

Language/environment wrapper

For all languages/environments except Rust, this part just translates the Rust API into something that can be easily consumed by the targets. For Rust, there is no wrapper. For example, in the case of the standalone server, the Rust API is translated into HTTP endpoints, whereas in the case of NodeJS, the (synchronous) Rust API is translated into a series of asynchronous calls from the JavaScript runtime.

If you want to make CozoDB usable in other languages, this part is where your focus should be. Any existing generic interop libraries between Rust and your target language would make the job much easier. Otherwise, you can consider wrapping the C API, as this is supported by most languages. For the languages officially supported, only Golang wraps the C API directly.

Status of the project

CozoDB is still very young, but we encourage you to try it out for your use case. Any feedback is welcome.

Versions before 1.0 do not promise syntax/API stability or storage compatibility.

Experimental (alpha): a read-only Cypher query surface — translate an openCypher subset to CozoScript so you can evaluate the engine without first learning Datalog — is available behind the off-by-default cypher feature (DbInstance::run_cypher / cypher_to_script; Python run_cypher). Design, scope, and limitations: docs/specs/cypher-read.md. Datalog remains the native, full-power query language.

Licensing and contributing

This project is licensed under MPL-2.0 or later. See here if you are interested in contributing to the project.