CloudLLM-ai/mentisdb
CloudLLM-ai/mentisdb has 92 GitHub stars and 14 forks. GitHot measured 0 stars in 24 hours and +1 in 7 days. Last checked 2026-11-24 03:35 UTC. Last push 2026-11-17.
Progression mesurée des étoiles
- in 24h
- 0
- in 7 days
- +1
- in 15 days
- Historique en cours
- in 1 month
- Historique en cours
Variations nettes sur des périodes qui se chevauchent, pas des totaux quotidiens. Les mesures absentes restent vides. Les étoiles indiquent l’intérêt, pas la qualité.
À propos
Memory that lasts and compounds. MentisDB gives agents durable memory so they do not just remember, they improve over time. It stores append-only thought chains plus a Git-like skills registry, letting skills evolve with experience through versioned, integrity-checked updates and fast retrieval.
Outils de développementREADME.md
OriginalMentisDB
MentisDB is a durable semantic memory engine and versioned skill registry for AI agents — a persistent, hash-chained brain that survives context resets, model swaps, and team turnover.
It stores semantically typed thoughts in an append-only, hash-chained memory log through a swappable storage adapter layer. The skill registry is a git-like immutable version store for agent instruction bundles — every upload is a new version, history is never overwritten, and every version is cryptographically signable.
Why MentisDB
Harness Swapping — the same durable memory works across every AI coding environment. Connect Claude Code, OpenAI Codex, GitHub Copilot CLI, Qwen Code, Cursor, VS Code, or any MCP-capable host to the same mentisdb daemon and your agents share one brain, regardless of which tool you picked up today.
Zero Knowledge Loss Across Context Boundaries — when an agent's context window fills, it writes a Summary checkpoint to MentisDB, compacts, reloads mentisdb_standing_context (what is durably true, at any age) and mentisdb_recent_context (where it left off), and continues. Chat history is ephemeral. MentisDB is permanent.
Fleet Orchestration at Scale — one project manager agent decomposes work, dispatches a parallel fleet of specialists, each pre-warmed with shared memory, and synthesizes results wave by wave. MentisDB is the coordination substrate: every agent reads from the same chain and writes its lessons back. The fleet's collective intelligence compounds.
Versioned Skill Registry — skills are not just stored, they are versioned like a git repository. Every upload to an existing skill_id creates a new immutable version (stored as a unified diff). Any historical version is reconstructable. Skills can be deprecated or revoked while full audit history is preserved. Permanent delete is the explicit exception: it removes the skill and all versions so the same skill_id can be reused. Uploading agents with registered Ed25519 keys must cryptographically sign their uploads — provenance is verifiable, not assumed.
Session Resurrection — any agent can call mentisdb_recent_context and immediately know exactly where the project stands, what decisions were made, what traps were already hit, and what comes next — without re-reading code, re-running exploratory searches, or asking the human to re-explain context that was earned through hours of work.
Self-Improving Agent Fleets — agents upload updated skill files after learning something new. A skill checked in at the start of a project is better by the end of it. Agents with registered Ed25519 keys must sign their uploads, so each skill version records which agent authored it. (The skill registry is integrity-checked as a file; unlike thought chains, it is not hash-chained.)
Multi-Agent Shared Brain — multiple agents, multiple roles, multiple owners can write to the same chain key simultaneously. Every thought carries a stable agent_id. Queries filter by agent identity, thought type, role, tags, concepts, importance, and time windows. The chain represents the full collective intelligence of an entire orchestration system, not just one session.
Lessons That Outlive Models — architectural decisions, hard constraints, non-obvious failure modes, and retrospectives written to MentisDB survive chat loss, model upgrades, and team changes. The knowledge compounds instead of evaporating. A new engineer or a new agent boots up, loads the chain, and inherits everything the team learned.
Installation
Prerequisites
macOS
Install the Xcode Command Line Tools (required for native crates):
xcode-select --install
Ubuntu / Debian
On a fresh Ubuntu or Debian system you need a few development packages before cargo install will succeed (especially because the default build enables audio support for the TUI startup chime).
sudo apt update
sudo apt install -y \
build-essential \
pkg-config \
libssl-dev \
libasound2-dev \
curl
Then install Rust 1.90 or newer (if you don't already have it; rustup update upgrades an older one):
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
source "$HOME/.cargo/env"
Headless servers / minimal installs
If you are installing on a server and do not want the startup sound (and the ALSA dependency), install without the default features:
cargo install mentisdb --no-default-features --features server
This produces a smaller binary with no audio dependencies.
Prebuilt binaries
Every GitHub release ships
ready-to-run mentisdb binaries for macOS (mentisdb-macos-arm64,
mentisdb-macos-x86_64), Windows (mentisdb-windows-x86_64.exe) and Linux.
Linux binaries come in two flavours (since 0.10.10, #21):
| Asset | Local embeddings (FastEmbed) | Minimum glibc | Runs on |
|---|---|---|---|
mentisdb-linux-x86_64, mentisdb-linux-arm64 |
yes | 2.39 | Ubuntu 24.04+, Debian 13+, Fedora 40+, RHEL 10, Arch |
mentisdb-linux-x86_64-compat, mentisdb-linux-arm64-compat |
no | 2.34 | Ubuntu 22.04 LTS, Debian 12, RHEL 9, and everything newer |
The full builds need a recent glibc because the prebuilt ONNX Runtime they link
for local embeddings is itself built against glibc 2.38+. The -compat builds are
compiled on Ubuntu 22.04 without the local-embeddings and startup-sound
features: lexical search and local-text-v1 vectors work as usual, but there is no
fastembed-minilm semantic vector provider (the same trade-off as the Intel macOS
binary) and no startup chime, so they need no ALSA (libasound.so.2) on the host. Release
CI fails the build if a -compat binary ever needs a glibc newer than 2.35.
Check your glibc before picking one:
ldd --version | head -1 # e.g. "ldd (Ubuntu GLIBC 2.35-0ubuntu3) 2.35"
A full binary started on an older glibc fails immediately with
version `GLIBC_2.39' not found. If you are on an older distro and want local
embeddings, use the Docker image: it is self-contained and has full
features regardless of the host's glibc. (Building from source with
--features local-embeddings does not avoid the floor, because the ONNX Runtime
library it downloads needs glibc 2.38+ too.)
# Example: Ubuntu 22.04 on x86_64
curl -fLo mentisdb https://github.com/CloudLLM-ai/mentisdb/releases/latest/download/mentisdb-linux-x86_64-compat
chmod +x mentisdb && ./mentisdb --help
Docker
Release images are published to GitHub Container Registry for linux/amd64 and
linux/arm64 (first published with 0.10.10.55). Tags: the release tag (for example
0.12.3.60), the crate version (0.12.3, moves with each release of that version)
and latest. This is also the way to get full features, including local embeddings,
on Linux distros older than glibc 2.39 (see Prebuilt binaries).
docker run -d --name mentisdb \
-p 127.0.0.1:9471:9471 -p 127.0.0.1:9472:9472 -p 127.0.0.1:9475:9475 \
-v mentisdb-data:/var/lib/mentisdb \
ghcr.io/cloudllm-ai/mentisdb:latest
Always publish the ports on loopback (-p 127.0.0.1:9471:9471, as above). Inside the
container the daemon binds 0.0.0.0 (needed for published ports to work) with bearer tokens
and the dashboard PIN off, so a bare -p 9471:9471 exposes an unauthenticated memory store to
every machine that can reach the host. The daemon does not refuse to start in that state, but
it says so: a SECURITY: warning in docker logs (stderr and the log), in the terminal UI
and as a red banner at the top of the dashboard, whenever a listener is bound to a
non-loopback address while MENTISDB_BEARER_TOKEN_ACCESS is off (MCP/REST) or no
MENTISDB_DASHBOARD_PIN is set (dashboard). Before exposing the container beyond the host,
set both (see the Compose example and the security notes below).
The entrypoint is mentisdb --headless under tini, so no TTY (-t) is needed
and docker stop (SIGTERM) drains the servers and exits cleanly. Check it with
curl http://127.0.0.1:9472/health; the image also has a Docker HEALTHCHECK.
Docker Compose:
services:
mentisdb:
image: ghcr.io/cloudllm-ai/mentisdb:latest
restart: unless-stopped
ports:
- "127.0.0.1:9471:9471" # MCP (HTTP)
- "127.0.0.1:9472:9472" # REST (HTTP)
- "127.0.0.1:9475:9475" # dashboard (HTTPS, self-signed)
volumes:
- mentisdb-data:/var/lib/mentisdb
environment:
MENTISDB_BEARER_TOKEN_ACCESS: "true"
MENTISDB_DASHBOARD_PIN: "change-me"
volumes:
mentisdb-data:
| Item | Value |
|---|---|
| Data volume | /var/lib/mentisdb (MENTISDB_DIR). Chains, the skill registry, TLS certificates and the local-embedding model cache (.fastembed_cache, downloaded on first use) all live here. |
| User | non-root mentisdb (uid/gid 991). Bind mounts must be writable by uid 991 (chown 991:991 ./data). |
| Ports | 9471 MCP (HTTP), 9472 REST (HTTP), 9475 dashboard (HTTPS). HTTPS MCP/REST (9473/9474) are off in the image; set MENTISDB_HTTPS_MCP_PORT / MENTISDB_HTTPS_REST_PORT to enable them. |
| Configuration | any variable from Daemon Configuration, passed with -e or environment:. |
| Base image | debian:trixie-slim (glibc 2.41). The ONNX Runtime used for local embeddings needs glibc 2.38+; the image is self-contained, so your host's glibc does not matter. |
| Features | server + local embeddings + LLM extraction; the startup-sound/audio feature is not compiled in. |
Security notes. Inside the container the daemon binds 0.0.0.0 (required for
published ports to work), and a fresh daemon has no authentication. Therefore:
- Publish ports on loopback (
-p 127.0.0.1:...) unless you put a TLS reverse proxy or VPN in front. Never publish9471/9472to the open internet as-is. - For any access beyond the host, set
MENTISDB_BEARER_TOKEN_ACCESS=trueand create tokens:docker exec mentisdb mentisdb bearertoken create --global admin. - Set
MENTISDB_DASHBOARD_PIN, and list the hostnames you reach the dashboard by inMENTISDB_DASHBOARD_ALLOWED_HOSTS(the dashboard rejects unknownHostheaders, and browsers calling REST or MCP must name an allowed host too; see Host allowlist). - Run one container per data volume. Since 0.11 a second daemon on a data directory that is already in use refuses to start.
- Back up the volume (
docker run --rm -v mentisdb-data:/d -v "$PWD":/b debian tar czf /b/mentisdb.tgz -C /d .) after stopping the container.
Build locally with make docker-build (or docker build -t mentisdb .).
Quick Start
Install the daemon (after completing the platform-specific prerequisites above):
cargo install mentisdb --features local-embeddings
The local-embeddings feature enables the built-in fastembed-minilm ONNX embedding provider for real semantic vector search. Without it, MentisDB falls back to local-text-v1 (text hashing). The auto-updater also installs with --features local-embeddings.
The prebuilt Intel macOS (x86_64-apple-darwin) release binary is built without local-embeddings, because ONNX Runtime ships no prebuilt library for that target; it uses local-text-v1 vectors. The same applies to the mentisdb-linux-*-compat binaries for older glibc (see Prebuilt binaries). Every other release binary includes FastEmbed. Builds with --no-default-features (optionally re-adding --features server etc.) are supported.
Connect your local AI tools the fast way:
mentisdb wizard
Or target one integration explicitly:
mentisdb setup codex
mentisdb setup all --dry-run
mentisdb wizard
mentisdb add "The sky is blue"
mentisdb search "cache invalidation" --limit 5 --scope session
mentisdb agents
Then start the daemon:
mentisdb
When run in an interactive terminal, mentisdb launches a full TUI with
scrollable panes for configuration, chain/agent/skill tables, and a live event
log. On an interactive first run with no configured client integrations, it
offers to launch the setup wizard immediately after startup so you do not have
to guess the next command.
Run persistently after closing your SSH session:
nohup mentisdb &
Headless mode. The daemon now auto-promotes to headless HTTP mode
whenever stdin or stdout is not a TTY — so every common non-interactive
launch (Docker without -t, nohup mentisdb &, systemd without
StandardInput=tty, cron, an SSH session that was disconnected) gets
the right behavior automatically without you having to remember the
flag. To force the headless code path on a machine that does have a
TTY (for testing, or to suppress the dashboard), pass the explicit
flag:
mentisdb --headless # HTTP/MCP/REST only, no TUI
mentisdb --mode http --headless # equivalent; the stdio-proxy form
Both forms are accepted in either flag order. mentisdb --help lists the
flag in the Usage block and gives a full description under Flags.
Modern MCP clients bootstrap themselves from the MCP handshake:
initialize.instructionstells the agent to readmentisdb://skill/coreresources/read(mentisdb://skill/core)delivers the embedded operating skillGET /mentisdb_skill_mdremains available only as a compatibility fallback
If you need to wire a tool manually, here are the raw MCP commands/configs:
# Claude Code
claude mcp add --transport http mentisdb http://127.0.0.1:9471
# OpenAI Codex
codex mcp add mentisdb --url http://127.0.0.1:9471
# Qwen Code
qwen mcp add --transport http mentisdb http://127.0.0.1:9471
# GitHub Copilot CLI — use /mcp add in interactive mode,
# or write ~/.copilot/mcp-config.json manually (see below)
What Is In This Folder
mentisdb/ contains:
- the standalone
mentisdblibrary crate - server support for HTTP MCP and REST, enabled by default
- the
mentisdbdaemon binary - dedicated tests under
mentisdb/tests
Makefile
A Makefile is included at the repository root. All common workflows have a target:
make build # fmt + release build
make build-mentisdb # build only the daemon binary
make release # fmt, check, clippy, build, test, doc in sequence
make fmt # cargo fmt
make check # cargo check (lib + binary)
make clippy # cargo fmt + clippy --all-targets -D warnings
make test # cargo test
make bench # Criterion benchmarks, output tee'd to /tmp/mentisdb_bench_results.txt
make doc # cargo doc --all-features
make coverage # tests under instrumentation: functions, branches, regions, lines (pinned nightly)
make install # cargo install --path . --locked --features local-embeddings
make publish # cargo publish
make publish-dry-run
make clean
make help # list all targets with descriptions
Build
make build
Or directly with Cargo:
cargo build --release
Build only the library without the default daemon/server stack:
cargo build --no-default-features
Test
make test
Or directly:
cargo test
Run tests for the library-only build:
cargo test --no-default-features
Run rustdoc tests:
cargo test --doc
Coverage
.github/workflows/coverage.yml, scripts/coverage_gate.py, make coverage.
Every CI run writes a coverage table into the run's job summary (the "Summary"
page of the Coverage workflow run), with functions, branches, regions and
lines as percentages with covered/total counts, a goal column (90%, with a
check mark or a cross per dimension) and the gate result. The HTML report and
summary.json are uploaded as the coverage-report artifact.
Run it locally, identically to CI:
cargo install cargo-llvm-cov --version 0.9.1 --locked
rustup toolchain install nightly-2026-10-01 --profile minimal --component llvm-tools-preview
make coverage # table on stdout and in target/coverage/summary.md
make coverage-open # same, then open target/coverage/html/index.html (macOS)
One nightly run reports everything. Branch coverage only exists on nightly
(cargo +nightly llvm-cov --branch, the unstable -Z coverage-options=branch),
and nightly's region and line numbers differ a little from stable's. Mixing a
stable run with a nightly run in one table would put numbers from two different
instrumentations side by side, so the whole suite runs once, on a nightly pinned
by date (COVERAGE_NIGHTLY in the Makefile, the same date in coverage.yml),
and all four dimensions come from that one profile. The table names the
toolchain. Pinning means a nightly that changes the flag cannot break CI; bump
the date deliberately, in its own commit, and re-measure. The run uses
--all-features, like the Tests workflow, and covers integration and unit
tests (not doctests). There is no lcov.info: this nightly's lcov exporter crashes on branch
data, so the artifact is the HTML report and summary.json.
Nothing is excluded. The measurement covers all of src/, including the
terminal UI and the daemon binary. The numbers below are low partly because
those are big and lightly tested; they are listed as gaps, not hidden.
Goal and floor. The goal is 90% on every dimension. Measured on
2026-11-08 (nightly-2026-10-01, --all-features), none meets it yet, so the
gate is a floor at each measured value rounded down, so coverage cannot regress:
| Dimension | Measured | Covered / total | Floor |
|---|---|---|---|
| Functions | 73.54% | 3,689 / 5,016 | 73% |
| Branches | 64.30% | 4,007 / 6,232 | 64% |
| Regions | 72.07% | 33,505 / 46,490 | 72% |
| Lines | 74.24% | 33,933 / 45,710 | 74% |
The floors are COVERAGE_FLOOR_* in the Makefile. They ratchet up toward
90 and are never lowered to land a change: when a change raises a dimension,
raise its floor to the new value rounded down in the same commit; a dimension
that reaches 90 is gated at 90. A change that adds untested code fails the job;
the fix is a test, not a lower floor.
Biggest uncovered areas (uncovered regions, the roadmap to 90%):
| File | Uncovered regions | Regions covered |
|---|---|---|
src/dashboard.rs |
2,524 | 9.5% |
src/bin/mentisdb.rs |
2,083 | 14.7% |
src/lib.rs |
1,878 | 78.8% |
src/tui.rs |
1,165 | 2.2% |
src/server.rs |
1,070 | 85.0% |
src/search/lemmas.rs |
291 | 52.2% |
src/cli/mod.rs, src/cli/wizard.rs, src/cli/setup.rs, src/cli/args.rs |
912 together | 35% to 65% |
The first four files hold about 7,650 of the 12,985 uncovered regions
(59%); testing the dashboard handlers, the daemon's main path as a process
and the terminal views against a test buffer is most of the way to 90%.
Benchmarks
MentisDB ships a Criterion benchmark suite and a harness-free HTTP concurrency benchmark:
make bench
Or directly:
cargo bench
Results are also written to /tmp/mentisdb_bench_results.txt so numbers persist across terminal sessions.
Benchmark coverage:
benches/thought_chain.rs— 10 benchmarks: append throughput, query latency, traversal patternsbenches/search_baseline.rs— 4 benchmarks: lexical/filter-first search baseline over content, registry text, indexed+text intersections, and newest-tail limitsbenches/search_ranked.rs— 4 benchmarks: additive ranked retrieval over lexical content, filtered ranked queries, and heuristic fallback, plus a baseline append-order comparisonbenches/skill_registry.rs— 12 benchmarks: skill upload, search, delta reconstruction, lifecyclebenches/http_concurrency.rs— startsmentisdbin-process on a random port; measures write and read throughput at 100 / 1k / 10k concurrent Tokio tasks with p50/p95/p99 latency reporting
Baseline numbers from the DashMap concurrent chain lookup refactor: 750–930 read req/s at 10k concurrent tasks, compared to a sequential bottleneck on the previous RwLock<HashMap> implementation.
Generate Docs
make doc
Or directly:
cargo doc --no-deps
Generate docs for the library-only build:
cargo doc --no-deps --no-default-features
Run The Daemon
The standalone executable is mentisdb.
Run it from source:
cargo run --bin mentisdb
Install it from the crate directory:
make install
# or
cargo install --path . --locked
mentisdb now owns both daemon startup and local integration setup:
mentisdb setup codex
mentisdb setup all --dry-run
mentisdb wizard
mentisdb add "The sky is blue"
mentisdb search "cache invalidation" --limit 5 --scope session
mentisdb agents
mentisdb
When it starts, it serves:
- an MCP server
- a REST server
- an HTTPS web dashboard
Before serving traffic, it:
- refuses to start on a data directory written by a newer
mentisdb(a downgrade), without touching it - recovers any chain migration the previous process died in (a journal lookup per chain)
- migrates the skill registry from V1 to V2 format if needed (idempotent; safe to run repeatedly)
Chain format upgrades (legacy schemas, JSONL, the legacy hash algorithm) do not run before serving: the daemon comes up in about a second and migrates those chains in the background, a few at a time, while it serves every other chain. See Upgrading and chain migrations.
Once startup completes, it prints:
- the active chain directory, default chain key, and bound MCP/REST/dashboard addresses
- a catalog of all exposed HTTP endpoints with one-line descriptions
- a per-chain summary with version, adapter, thought count, and per-agent counts
Command-Line Interface
The mentisdb binary is a complete command-line client for everything the MCP
tools, the REST API and the web dashboard can do. Commands are
mentisdb <group> <command> [options]; run mentisdb --help for the
overview, mentisdb <group> --help for a group, and
mentisdb <group> <command> --help for flags and copy-paste examples.
docs/CLI_PARITY.md maps every MCP tool, REST route and
dashboard action to its command.
| Group | What it covers |
|---|---|
thought |
append, retro, get, genesis, traverse, recent, candidates |
search |
ranked (default), lexical, filter, federated, bundles |
chain |
list, head, bootstrap, branch, merge, info, delete, access show|set|allow|deny|verify |
agent |
list, get, registry, upsert, describe, alias, key add, key revoke, disable, activate, copy |
entity-type |
list, upsert |
memory |
export, import, extract (MEMORY.md style Markdown) |
skill |
guide, manifest, list, search, read, versions, upload, deprecate, revoke, delete, diff |
webhook |
list, register, delete |
vectors |
enable, disable, sync, rebuild |
daemon |
health, version, flush, restart, settings list, settings set |
| local | setup, wizard, add, backup, restore, bearertoken, cert, key generate|show (plus operator agent key generate) |
mentisdb chain bootstrap "Project Atlas memory" --chain atlas
mentisdb thought append "Use UTC everywhere" --chain atlas --type Decision --tag time
echo "deploy finished" | mentisdb thought append - --chain atlas --type Summary --role Checkpoint
mentisdb search "why UTC" --chain atlas --type Decision --limit 5
mentisdb memory export --chain atlas > MEMORY.md
mentisdb chain delete scratch --yes --pin 123456
Daemon commands talk to the running daemon so they share its chain cache and
locks: memory and registry commands use the REST API at --url (default
http://127.0.0.1:9472, bearer token from --token or MENTISDB_BEARER_TOKEN),
while the PIN-gated dashboard actions (chain info/delete, vectors enable/disable/sync, skill diff, agent copy, daemon version/restart/settings)
use the dashboard API at --dashboard-url (default https://127.0.0.1:9475,
PIN from --pin or MENTISDB_DASHBOARD_PIN). --json prints compact JSON for
pipes; destructive commands require --yes. backup, restore, bearertoken
and cert work on the data directory directly and do not need the daemon.
Daemon Configuration
mentisdb is configured with environment variables:
MENTISDB_DIRDirectory where MentisDB storage adapters store chain files.MENTISDB_DEFAULT_CHAIN_KEYDefaultchain_keyused when requests omit one. Default:borganism-brain.MENTISDB_DEFAULT_KEYis accepted as a deprecated alias.MENTISDB_STORAGE_ADAPTERDefault storage backend for newly created chains. Onlybinaryis supported for new chains (JSONL is deprecated — existing JSONL chains remain readable). Default:binaryMENTISDB_VERBOSEWhen unset, verbose interaction logging defaults totrue. Supported explicit values:1,0,true,false.MENTISDB_LOG_FILEOptional path for interaction logs. When set, MentisDB writes interaction logs to that file even if console verbosity is disabled. IfMENTISDB_VERBOSE=true, the same lines are also mirrored to the console logger.MENTISDB_BIND_HOSTBind host for both HTTP servers. Default:127.0.0.1. It is also one of the names the daemon answers to in theHostheader (see "Host allowlist" below).MENTISDB_MCP_PORTMCP server port. Default:9471MENTISDB_REST_PORTREST server port. Default:9472MENTISDB_KEY_DIRDirectorymentisdb key generatesaves private keys in when--outis not given. Default:~/.mentisdb/keys(created0700, files0600). The seed is never printed.MENTISDB_DASHBOARD_PORTHTTPS dashboard port. Default:9475. Set to0to disable the web dashboard.MENTISDB_DASHBOARD_PINOptional PIN required to access the dashboard. Leave unset only for trusted localhost use.MENTISDB_DASHBOARD_ALLOWED_HOSTSComma-separated extra hostnames or IPs the dashboard accepts in theHostheader (for example a public DNS name or the name a reverse proxy forwards). Set it in the environment or a.envfile (./.envor<MENTISDB_DIR>/.env); it is not editable from the dashboard Settings tab. The MCP and REST listeners use the same list. See "Host allowlist" below for the built-in names and how each listener applies them. Set it before the daemon starts.MENTISDB_WEBHOOK_ALLOWED_CIDRSPrivate ranges webhooks may target despite the SSRF guard, for self-hosted consumers on a private network. One or more CIDRs or bare IPs separated by commas and/or whitespace, e.g.100.64.0.0/10,fd7a:115c:a1e0::/48(Tailscale). Unset (default) keeps every internal range blocked; an invalid value or an entry broader than/8(IPv4 or IPv6) stops the daemon from starting. Set it in the environment or a.envfile (./.envor<MENTISDB_DIR>/.env). See "Webhook targets" below.MENTISDB_MAX_BODY_BYTESLargest body, in bytes, the import routes (/v1/import-markdown,/v1/skills/upload,/v1/extract-memories) accept from an authenticated caller. Default:67108864(64 MiB); must be1048576to1073741824(1 MiB to 1 GiB), otherwise the daemon refuses to start. Every other route takes at most 2 MiB; over the limit the answer is413. See Large request bodies.MENTISDB_MAX_INFLIGHT_BODY_BYTESBody bytes all import requests in flight may hold together. Default: four timesMENTISDB_MAX_BODY_BYTES(one peer may hold twice the cap and four bodies); a smaller value is raised to one cap. Beyond it the answer is503withRetry-After. Ordinary requests have their own fixed 64 MiB pool and are never starved by imports.MENTISDB_BODY_IDLE_TIMEOUT_SECSA request body that delivers no data for this long fails. Default:30;1to3600.MENTISDB_MIN_BODY_BYTES_PER_SECSlowest rate a request body may sustain, measured over each window of one idle timeout once a grace period (twice the idle timeout) is over; a slower body fails with408. Default:65536(64 KiB/s);0switches the rule off (the idle timeout and deadlines still apply). Lower it for imports over a slow link, or on a busy server that reads bodies late;0to1073741824.MENTISDB_BEARER_TOKEN_ACCESSRequire bearer tokens for MCP requests. Default:false. Settruefor remote or multi-user MCP servers. This can also be toggled live from the dashboard Settings screen.MENTISDB_AUTO_FLUSHControls per-write durability of thebinarystorage adapter.true(default): everyappend_thoughtreturns only after its group commit has been written to the chain file. Survives a process crash; addMENTISDB_FSYNC=1to also survive power loss.false: appends are queued to a background writer (queue capacity 128 records, then callers wait) and flushed every 16 appends (FLUSH_THRESHOLD). On a hard crash or power failure everything still queued is lost: up to 128 records, not 15, because the flush cadence is not the queue bound. Throughput rises significantly for multi-agent hubs with many concurrent writers. Supported values:1,0,true,false. Has no effect on thejsonladapter.
MENTISDB_GROUP_COMMIT_MSGroup-commit window in milliseconds for the background binary writer. The writer batches appends that are already queued, waiting up to this window for more; when no other append is queued it flushes immediately, so a lone append never pays the window. Lower values = lower latency; higher values = better throughput. Default:2MENTISDB_FSYNCSet1(ortrue,on,yes) tofsyncthe chain file after every group commit, for power-loss durability. Default: off — each group commit is written to the OS (survives a process crash) but not forced to the device, because a per-commit fsync roughly quadruples append latency (F_FULLFSYNCon macOS). Explicit flushes (POST /v1/admin/flush), clean shutdown and dropping a chain handle always sync.MENTISDB_MIGRATION_CONCURRENCYHow many chains the background migration manager rewrites at once. Default:2. See Upgrading and chain migrations.MENTISDB_MIGRATION_BACKUP_RETENTION_DAYSHow long the preserved original of a migrated chain is kept under<MENTISDB_DIR>/migrations/backup/. Default:14;0keeps backups forever.MENTISDB_EMBEDDINGSProcess-wide embeddings mode for managed vector sidecars:off(lexical/graph only),local-text(built-in hashing embeddings, never loads ONNX) orfastembed. Unset means FastEmbed when thelocal-embeddingsfeature is compiled in,local-textotherwise. Unknown values are logged and treated as unset.MENTISDB_DF_SCOPEHow the lexical stop-word gate measures a term's document frequency:global(default, what every published benchmark used: a thought counts if the term is in any field, including agent registry text) orfield(each field's own count). Experimental; seeWHITEPAPER.mdsection 6.3.MENTISDB_VECTOR_FUSIONHow vector similarity is blended with the lexical score:relative(default; the decay depends on a hit's lexical score relative to the query's best, so paraphrased questions keep the vector channel) orabsolute(the older raw-BM25 decay, which silences vectors for queries longer than a few words). On LoCoMo R@10 and LongMemEval R@5relativescored 75.2% and 70.0% against 73.1% and 68.0%.MENTISDB_COLLAPSE_DUPLICATESResult-time collapse of exact and near-duplicate hits: a number in(0, 1]is the Jaccard threshold (default0.9),offdisables it. Collapsed ids are listed incollapsed_duplicateson the surviving hit. Per request:collapse_duplicates(0disables). Text queries only.- Per-request ranking knobs (REST/MCP fields and CLI flags, see
docs/CLI_PARITY.md):resolve_successors,collapse_duplicates,vector_fusion,synonym_weight(automatic thesaurus expansion, default 0.3,0disables; the library applies it by default too),df_scopeanddf_cutoffs. FASTEMBED_CACHE_DIRWhere the FastEmbed ONNX model is cached. Default:<MENTISDB_DIR>/.fastembed_cache.MENTISDB_UPDATE_CHECKBackground GitHub release check formentisdb. Enabled by default; set0,false,no, oroffto disable update checks after startup. Default:trueMENTISDB_UPDATE_REPOOptional GitHubowner/repooverride used by the updater. Default:CloudLLM-ai/mentisdbMENTISDB_HTTPS_MCP_PORTHTTPS MCP server port. Default:9473. Set to0to disable HTTPS MCP.MENTISDB_HTTPS_REST_PORTHTTPS REST server port. Default:9474. Set to0to disable HTTPS REST.MENTISDB_TLS_CERTPath to a PEM-encoded TLS certificate for the HTTPS servers and dashboard. Default:<MENTISDB_DIR>/tls/cert.pemMENTISDB_TLS_KEYPath to a PEM-encoded TLS private key for the HTTPS servers and dashboard. Default:<MENTISDB_DIR>/tls/key.pemMENTISDB_STARTUP_SOUNDPlay the 4-note "men-tis-D-B" startup jingle. Default:true. Set0,false,no, oroffto silence.MENTISDB_THOUGHT_SOUNDSPlay unique short sounds for thought types on append (square-wave, 250–1,000 Hz) and for read operations (sine-wave, 2,500–4,500 Hz). Default:false. Set1,true,yes, oronto enable.MENTISDB_DEDUP_THRESHOLDJaccard similarity threshold for automatic deduplication on append (0.0–1.0). When unset, auto-dedup is disabled (library and daemon default). When set, a new thought whose content is sufficiently similar to a recent thought gets an automaticSupersedesedge to that prior thought (the prior stays on disk for audit). Recommended for multi-agent and long-lived chains:0.85. Without this (or without agents writingSupersedes/Corrects/Invalidates), the invalidation set stays empty and search cannot hide near-duplicate noise.MENTISDB_DEDUP_SCAN_WINDOWNumber of recent thoughts to scan for dedup comparison. Default:64. Only used whenMENTISDB_DEDUP_THRESHOLDis set. Raise on chatty chains (e.g.128).
Invalidation and “current” memory
MentisDB never deletes corrected or superseded thoughts. Instead it maintains an
in-memory invalidated_thought_ids set for any thought that is the target of a
later Supersedes, Corrects, or Invalidates relation.
Default retrieval (query, ranked search, context bundles, recent context, memory
markdown export, REST/MCP search) excludes those IDs so agents see current memory.
Pass include_invalidated=true (crate: ThoughtQuery::with_include_invalidated(true) /
RankedSearchQuery::with_include_invalidated(true)) for audit archaeology.
Point-in-time as_of still returns thoughts that were valid at that timestamp, even
if they were superseded later.
How the set gets filled:
- Agents write typed edges (
Supersedes/Corrects/Invalidates) — the MentisDB skill’s search-before-write habit. - Auto-dedup when
MENTISDB_DEDUP_THRESHOLDis set (see above).
Search filtering alone does not invent edges, and measured chains show agents rarely
type them (on one real installation 0 of 14 Correction/AssumptionInvalidated
thoughts and 0 of about 90 Decision thoughts carried one). So retrieval also reasons
about lineage (mentisdb::lineage):
- A superseded thought that would have ranked is replaced by its live successor
(hit field
successor_of), so hiding the old version never leaves the agent with nothing. Disable withRankedSearchQuery::with_resolve_successors(false). - An untyped link (
refs/References) from aCorrection, anAssumptionInvalidatedor a newDecisionover an older decision-like thought, or anyContradicts, does not hide the target (a reference is often background). The target is reportedversion_status: "contested"and the contesting thought is promoted above it. - Every thought JSON carries
version_status,successorsandcurrent_versionwhen it is not plainly current, includinginclude_invalidated=trueresults. - Appending a replacement without a typed relation returns
warningsnaming the candidatetarget_ids; add{"kind":"supersedes","target_id":"..."}. - Standing context substitutes a superseded constraint or decision with its successor, and the MEMORY.md export drops superseded thoughts.
- Who may replace whose memory. On an open chain any writer may replace any thought
(corrections often come from another agent), so redirection is unchanged, but nothing is
hidden about it: every successor note carries the replacement's
agent_id,trust(verified,unsignedorunverified) andcross_agent, a hit that replaced another agent's thought setscross_agent: true, and a standing entry shows[REPLACES #n by agent: replaced by another agent, check it]. On a governed chain (signing policy) a strong link replaces only when its writer is the same agent as the target or holds a key authorized on the chain; any other link is shown ascontested(authorized: false) and replaces and promotes nothing. A chain of more than 64 versions of one thought (MAX_LINEAGE_DEPTH) is refused at write time.
Lineage is derived from the stored chain when it is opened, so existing chains benefit
with no migration. A Supersedes, Corrects or Invalidates relation that carries a
chain_key applies wherever one read sees both chains: branch search (a branch plus its
ancestors) and federated search replace the superseded hit with the live successor on the
other chain (successor_of, successor_of_chain), or annotate it superseded with
current_version.chain_key under include_invalidated. Only edges the caller's audience
may see count, so a public reader is never redirected to a private successor. A chain read
on its own is unchanged, and untyped links never apply across chains.
MentisDB loads environment variables at startup from a .env file in the current working
directory, then from <MENTISDB_DIR>/.env (where the dashboard Settings tab saves its
changes). Precedence is shell environment > ./.env > <MENTISDB_DIR>/.env; a file never
overrides a variable that is already set. Missing files are silently ignored, so it is safe to commit a template .env.example
while keeping your actual .env in .gitignore.
Example — full durability (crash-safe default plus per-commit fsync):
MENTISDB_DIR=/tmp/mentisdb \
MENTISDB_DEFAULT_CHAIN_KEY=borganism-brain \
MENTISDB_STORAGE_ADAPTER=binary \
MENTISDB_VERBOSE=true \
MENTISDB_LOG_FILE=/tmp/mentisdb/mentisdb.log \
MENTISDB_BIND_HOST=127.0.0.1 \
MENTISDB_MCP_PORT=9471 \
MENTISDB_REST_PORT=9472 \
MENTISDB_DASHBOARD_PIN=change-me \
MENTISDB_AUTO_FLUSH=true \
MENTISDB_FSYNC=1 \
cargo run --bin mentisdb
What each durability setting really guarantees
| Setting | Survives process crash (kill -9) | Survives power loss / OS crash |
|---|---|---|
MENTISDB_AUTO_FLUSH=true (default), MENTISDB_FSYNC unset |
Yes: the append returns after the write reaches the OS | No: bytes may sit in the OS cache; a torn tail is truncated on open, but acknowledged records after the last device sync can be lost |
MENTISDB_AUTO_FLUSH=true, MENTISDB_FSYNC=1 |
Yes | Yes (group commit is fsynced; roughly 4x append latency) |
MENTISDB_AUTO_FLUSH=false |
No: up to 128 queued records are lost | No |
POST /v1/admin/flush, clean shutdown and dropping a chain handle always fsync. Chain migrations
always fsync their journal, staged file and directory renames, regardless of these settings. The
default favours latency over power-loss durability; set MENTISDB_FSYNC=1 on machines that can
lose power or on shared hosts where the memory is the system of record.
Durability and crash recovery (0.10.9)
- Canonical record first. An append returns
Okas soon as the hash-chained record is durable in the chain file. Derived state (lexical/vector sidecars, implicit-edge overlay, registries) is updated afterwards; if that fails it is logged and retried or rebuilt on the next append or open, instead of failing an append that already committed. - Torn-tail recovery. If the daemon or machine died mid-write, opening a binary chain
truncates a partial final record back to the last complete one and saves the dropped
bytes beside the chain file as
<chain file>.torn-<unix-millis>(mode0600) for inspection. Only a genuine partial record is truncated: if the bytes after a bad length prefix still decode as a complete record, the corruption is mid-file, so opening fails with anInvalidDataerror and the chain file is left untouched. - Single writer. MentisDB assumes one writer process per chain directory; torn-tail
repair takes no cross-process lock. Do not point two daemons (or a daemon and an embedded
MentisDbwriter) at the sameMENTISDB_DIR. - Implicit-edge overlay catch-up. The overlay records how many thoughts it covers and the chain head it was built against; after a crash it replays the missing tail on open (or rebuilds if the head does not match), so no implicit edges are lost.
- Atomic registry writes. The chain registry, agent registry, webhook list and other JSON registries are written to a temporary file and renamed into place, so a crash never leaves a half-written registry.
Example — multi-agent / long-lived chain (recommended: enable near-duplicate superseding):
MENTISDB_DIR=/var/lib/mentisdb \
MENTISDB_AUTO_FLUSH=true \
MENTISDB_DEDUP_THRESHOLD=0.85 \
MENTISDB_DEDUP_SCAN_WINDOW=64 \
MENTISDB_BIND_HOST=0.0.0.0 \
mentisdb
Example — high-throughput write mode (multi-agent hub):
MENTISDB_DIR=/var/lib/mentisdb \
MENTISDB_AUTO_FLUSH=false \
MENTISDB_BIND_HOST=0.0.0.0 \
mentisdb
Upgrading and chain migrations
A release may need to rewrite chain files (a newer thought layout, a better hash algorithm,
JSONL to binary). mentisdb does that in the background, never blocks startup on it, tells you
what it is doing, and can always go back.
What you will see
- The daemon starts and serves immediately. Chains that need work are queued and migrated by a
small worker pool (
MENTISDB_MIGRATION_CONCURRENCY, default 2). - A request for a chain that is still migrating gets HTTP 503 with a
Retry-Afterheader and{"retry_after_secs": 5, "migration": {"state": "migrating", "percent": 42, ...}}; MCP clients get the same text as a tool error. Every other chain is served normally. A chain that is not migrating is never delayed by one that is. - Progress is logged (
[migration] chain 'x': migrating ...), shown in the TUI, and listed byGET /v1/migrations, thementisdb_migration_statusMCP tool,mentisdb migrate statusand a banner on the dashboard.
Why it is safe
- Backup first. Before anything is replaced the original chain file is hard-linked (or copied)
to
<MENTISDB_DIR>/migrations/backup/<chain>/. It is keptMENTISDB_MIGRATION_BACKUP_RETENTION_DAYSdays (default 14,0keeps it forever). - Journaled and resumable. Each chain has a journal in
migrations/journal/(planned, backed up, staged, committed, finalized). The upgraded chain is streamed intomigrations/staging/, re-read and verified end to end, then swapped in with one atomic rename. Kill the daemon at any instant (the test suite does, at every step) and the next start resumes or discards the work. A chain interrupted three times is quarantined instead of crash-looping. - Never launders corruption. Records from schemas that stored trustworthy hashes must verify; a chain whose stored hash is wrong (corruption or tampering), or whose migration would invalidate a v2 signature, is refused and left byte-for-byte untouched.
- Failures are quarantined. A failing chain is reported (state
failed, with the error) and answers requests with a 503 naming the fix. The other chains and the daemon are unaffected. - Downgrades are refused. A chain, or a data directory, written by a newer release is never opened by an older one that has this check; it says so and exits.
Operator commands
mentisdb migrate status # what needs, is in, or finished a migration
mentisdb migrate run --dry-run # rehearse: check hashes and signatures, write nothing
mentisdb migrate run [--chain KEY] # migrate now (resumes interrupted runs)
mentisdb migrate verify # re-check every hash link of the live chains
mentisdb migrate retry --chain KEY # clear a quarantine; it is migrated on the next run
mentisdb migrate skip --chain KEY # leave a chain alone and unavailable until retried
mentisdb migrate rollback --chain KEY # restore the backup (stop the daemon first)
mentisdb migrate purge-backups # delete preserved originals of finished migrations
status --url http://127.0.0.1:9472 asks a running daemon. rollback refuses once new thoughts
were appended to the migrated chain unless you pass --force, which discards them; run it with the
daemon stopped, because a running daemon holds the chain in memory. Everything under
migrations/ is plain files you can inspect.
Derived data (vector sidecars, HNSW graphs, the implicit-edge overlay, lexical indexes) is never part of a migration's critical path: when a chain's hashes change they are deleted and rebuilt lazily in the background; otherwise they are kept.
Upgrade note (0.11). Chains in the current layout with current hashes are not touched.
HNSW graph files gain a header (a magic and a SHA-256 digest of the embedding space and its
documents); existing graphs are rebuilt once in the background. Chains written by builds from
March and April 2026, which stamp schema_version = 4 on schema-3 records, open again (0.11
accepts 4 as a historical alias and verifies those records under the rule that wrote them);
chains from schemas 0 to 2 are verified link by link before their hashes are rebuilt. Nothing else changes on
disk, so a chain that needed no migration is still readable by the previous release, except a
chain that holds an AccessPolicy record, which releases before the type cannot read.
Automatic Update Check
mentisdb checks GitHub releases in the background after startup and can offer
to update itself with cargo install.
- checks are enabled by default
- version comparison uses only the first three numeric components, so a tag like
0.6.1.14is treated as core version0.6.1 - interactive terminals get an ASCII prompt window with
Y/N - non-interactive terminals never block; they print the exact manual
cargo installcommand instead
Disable the automatic check:
MENTISDB_UPDATE_CHECK=0 \
mentisdb
Server Surfaces
MCP endpoints:
GET /healthPOST /GET /(event stream; sameHost, bearer andOriginchecks asPOST /)POST /tools/listPOST /tools/execute
REST endpoints:
GET /healthGET /mentisdb_skill_mdGET /v1/skillsGET /v1/skills/manifestGET /v1/chainsPOST /v1/chains/mergePOST /v1/chains/branchPOST /v1/vectors/rebuildPOST /v1/bootstrapPOST /v1/agentsPOST /v1/agentPOST /v1/agent-registryPOST /v1/agents/upsertPOST /v1/agents/descriptionPOST /v1/agents/aliasesPOST /v1/agents/keys(403: operator-only)POST /v1/agents/keys/revoke(403: operator-only)POST /v1/agents/disable(403: operator-only)POST /v1/access/policyPOST /v1/access/policy/set(403: operator-only)POST /v1/access/verifyPOST /v1/thoughtPOST /v1/thoughtsPOST /v1/thoughts/genesisPOST /v1/thoughts/traversePOST /v1/retrospectivesPOST /v1/searchPOST /v1/lexical-searchPOST /v1/ranked-searchPOST /v1/context-bundlesPOST /v1/recent-contextPOST /v1/standing-contextPOST /v1/memory-markdownPOST /v1/import-markdownPOST /v1/skills/uploadPOST /v1/skills/searchPOST /v1/skills/readPOST /v1/skills/versionsPOST /v1/skills/deprecatePOST /v1/skills/revokePOST /v1/skills/deletePOST /v1/webhooksGET /v1/webhooksDELETE /v1/webhooks/{id}POST /v1/headPOST /v1/federated-searchPOST /v1/summary-candidatesPOST /v1/entity-typesPOST /v1/entity-types/upsertPOST /v1/extract-memoriesPOST /v1/admin/flushGET /v1/migrationsPOST /v1/migrations/retry(global token)POST /v1/migrations/skip(global token)
Chain listing and derived-state backlog
GET /v1/chains (global token; MCP mentisdb_list_chains) lists every chain with
derived_backlog, the work still pending on its derived state (0.12):
{
"chain_key": "project", "version": 3, "storage_adapter": "binary",
"thought_count": 100000, "agent_count": 4, "storage_location": "...",
"derived_backlog": {
"embeddings_in_flight": 0, "embeddings_parked": 0,
"embeddings_missing": 0, "implicit_edges": 312
}
}
embeddings_in_flight: thoughts whose embedding has been requested but not committed.embeddings_parked: vectors that are ready but wait for an earlier thought's vector, so they are applied in chain order.embeddings_missing: thoughts waiting to be embedded again after a failure.implicit_edges: applied vectors whose implicitRelatedToedges have not reached the overlay yet.
All four are zero on a healthy, idle chain. A steadily growing embeddings_missing or
embeddings_in_flight points at a stalling embedding provider. A growing implicit_edges
means appends are outrunning the background edge scan: about 155 appends per second at
100,000 thoughts and 720 at 20,000 (4 threads, 384 dimensions). The backlog never blocks an
append or drops an edge. It only delays edges for recent thoughts, and it drains when
appends slow down. A chain that is not open, or whose private segments are hidden from the
caller, reports zeros. Library: MentisDb::derived_backlog.
Chain resolution and error statuses
Only operations that write a chain create it when its chain_key does not exist yet:
POST /v1/bootstrap, POST /v1/thoughts, POST /v1/retrospectives,
POST /v1/import-markdown, POST /v1/agents/upsert, POST /v1/entity-types/upsert,
and the target of POST /v1/chains/merge. Every other route
(search, head, agents, thought lookup, metadata updates, ...) returns 404 for an
unknown chain_key and persists nothing. The configured default chain
(MENTISDB_DEFAULT_CHAIN_KEY) is the one exception: it is created on demand so a fresh
daemon answers reads. Call POST /v1/bootstrap (or mentisdb_bootstrap over MCP)
before reading a new chain.
A chain_key must be non-empty, at most 256 bytes, and free of control characters;
anything else is rejected with 400. The source, target and branch keys of
POST /v1/chains/merge and POST /v1/chains/branch (and the matching MCP tools) are
trimmed of surrounding whitespace and then validated by the same rule.
REST and MCP errors map to HTTP statuses as follows:
| Status | Meaning |
|---|---|
400 |
Invalid input: malformed JSON, bad UUID, unknown thought type/role, invalid chain_key, a result window (offset + limit) above 10,000 or a standing-context per_type_limit above 100 |
401 |
Missing/invalid bearer token, or a token whose scope does not cover the operation |
403 |
Permission denied: missing or invalid signature on a signed skill upload, inactive agent, a write the chain's access policy refused, a Host outside the allowlist, or an operator-only route (/v1/agents/keys, /v1/agents/keys/revoke, /v1/agents/disable, /v1/access/policy/set) |
404 |
Unknown chain (see above) or another missing resource |
408 |
A request body stopped arriving for MENTISDB_BODY_IDLE_TIMEOUT_SECS, a small or anonymous body missed its total deadline (twice that), or any body fell below MENTISDB_MIN_BODY_BYTES_PER_SEC (64 KiB/s by default) in a window after its grace period (twice the idle timeout); on every route |
409 |
Conflict, e.g. POST /v1/chains/branch into a chain key that already exists |
413 |
Request body over the route's limit: 2 MiB, or MENTISDB_MAX_BODY_BYTES (default 64 MiB) on the import routes for an authenticated caller; over 1 MiB for a read proof (X-Mentis-Auth) that does not also send X-Mentis-Content-Sha256 (see Large request bodies). The mentisdb CLI and pymentisdb send it, so a large memory import works |
500 |
Server fault; the body says only "internal server error" and details go to the daemon log |
501 |
POST /v1/extract-memories on a build without the llm-extraction feature |
503 |
The chain is being migrated or is quarantined; the body names the state, and a migrating chain adds Retry-After and retry_after_secs (see Upgrading and chain migrations). Also, with Retry-After, when the in-flight body budget is exhausted (see Large request bodies) |
Large request bodies
Request bodies are limited per route. Ordinary routes take at most 2 MiB. The import family
(/v1/import-markdown, /v1/skills/upload, /v1/extract-memories) takes up to
MENTISDB_MAX_BODY_BYTES (default 64 MiB), and with bearer-token access on only from a caller whose token
is valid: the token is checked from the headers before any of the body is read, so a request without one is
refused (401, or 413 for a declared length over 2 MiB) without the daemon pulling its body. Large
imports draw on their own budget (MENTISDB_MAX_INFLIGHT_BODY_BYTES, reserved from the declared length; beyond it
503 with Retry-After); every other request is charged only for the bytes that actually arrive, from a separate
pool (64 MiB, at most 32 MiB per peer), so imports never starve appends and searches. A body that
stops arriving fails with 408 after MENTISDB_BODY_IDLE_TIMEOUT_SECS, small or anonymous bodies also get a
total deadline of twice that, and every body must sustain MENTISDB_MIN_BODY_BYTES_PER_SEC (64 KiB/s by default) in each window of one idle
timeout once its grace period (twice the idle timeout) is over. Anonymous bodies have a 16 MiB pool of their own (8 MiB per peer). MCP request bodies (including the mentisdb_import_memory_markdown tool) are always
limited to 2 MiB: send a large import to the REST route, or use the CLI. Two paths decide who is asking, and
they treat a large body differently:
- Bearer token. The daemon reads the body (up to the route's limit) to find the
chain_keythe token must cover, then hands it to the handler. - Read proof (
X-Mentis-Auth). The signature coversSHA-256(body), so by itself the daemon must read the whole body to check it, which it only does up to 1 MiB. A client that also sendsX-Mentis-Content-Sha256: <64 lowercase hex>(the same digest the proof signed) lets the daemon verify the proof before reading the body and then hash the body as it streams. The signed body goes through; any other body fails at its end with400and no handler has run, so nothing is imported or changed. The proof format is unchanged: older clients (and a daemon that predates the header) work as before.
mentisdb (CLI) and pymentisdb send the digest header with every proof. If you sign requests yourself, add
the header and keep the body bytes you hash identical to the ones you send. Code on the daemon side that
streams a body must not act on it before the end: the digest is only confirmed there.
Append Thought — POST /v1/thoughts
{
"chain_key": "my-chain",
"agent_id": "my-agent",
"agent_name": "My Agent",
"thought_type": "LessonLearned",
"role": "Execution",
"content": "...",
"scope": "session",
"tags": ["tag1"],
"concepts": ["concept1"],
"entity_type": "incident",
"source_episode": "triage-2026-04-17",
"importance": 0.9,
"confidence": 0.8,
"refs": [14, 22],
"relations": [
{ "kind": "CausedBy", "target_id": "<uuid>" },
{ "kind": "ContinuesFrom", "target_id": "<uuid>", "chain_key": "other-chain" },
{ "kind": "Supersedes", "target_id": "<uuid>", "valid_at": "2025-01-01T00:00:00Z", "invalid_at": "2025-12-31T23:59:59Z" }
]
}
chain_key, role, scope, tags, concepts, entity_type, source_episode, importance, confidence, refs, and relations are optional.relations[].kind accepts: References, Summarizes, Corrects, Invalidates, CausedBy, Supports, Contradicts, DerivedFrom, ContinuesFrom, BranchesFrom, RelatedTo, Supersedes.relations[].chain_key is optional — omit for intra-chain edges, set for cross-chain references.relations[].valid_at and relations[].invalid_at are optional RFC 3339 timestamps that define when a relation edge is temporally valid, enabling point-in-time queries with as_of.entity_type is an optional per-chain ontology label (e.g. "incident", "customer", "deploy") used by the dashboard explorer and by ranked-search filtering.source_episode is an optional free-form provenance string (e.g. a conversation id or batch name) that groups thoughts by the episode they were derived from; it is also filterable in ranked search.
Search Semantics
MentisDB keeps its baseline thought search surface filter-first and append-order. Ranked, graph-aware, and vector retrieval are additive surfaces layered on top of that stable baseline.
Ranked search now automatically expands queries using the built-in static thesaurus (~900 headwords + 300+ irregular verb lemmas) for better recall on vocabulary mismatch and verb-form variation. No client changes or extra parameters are required — the expansion is applied transparently to every text-bearing ranked query (REST, MCP, dashboard, and CLI).
Today, the main search APIs are:
MentisDb::query(&ThoughtQuery)POST /v1/searchmentisdb_search
Current behavior:
- indexed filters narrow the candidate set for
thought_type,role,agent_id, tags, and concepts textis a case-insensitive substring match over:- thought
content agent_id- tags
- concepts
- agent-registry display name, aliases, owner, and description
- thought
- results are returned in append order
limitkeeps the newest matching tail after filtering rather than applying a ranking score
That means plain ThoughtQuery / /v1/search behavior is deterministic and explainable, but that baseline path is not BM25, hybrid, or vector retrieval. Additive ranked and graph-aware retrieval now exist on separate crate, REST, and MCP surfaces.
Examples:
use mentisdb::{MentisDb, ThoughtQuery, ThoughtType};
use std::path::PathBuf;
# fn main() -> std::io::Result<()> {
let chain = MentisDb::open(&PathBuf::from("/tmp/tc_query"), "agent1", "Agent", None, None)?;
let lexical = ThoughtQuery::new()
.with_types(vec![ThoughtType::Decision])
.with_tags_any(["search"])
.with_text("latency");
let results = chain.query(&lexical);
# let _ = results;
# Ok(())
# }
{
"chain_key": "mentisdb",
"thought_types": ["Decision"],
"tags_any": ["search"],
"text": "latency",
"limit": 20
}
Design note:
- treat this lexical/filter-first behavior as the baseline
- keep ranked, vector, and hybrid retrieval as additive, explicitly documented surfaces on top of that baseline
- do not silently change the semantics of
ThoughtQueryor/v1/searchfrom append-order filtering to score-ranked retrieval
The dedicated benchmark benches/search_baseline.rs and evaluation tests in tests/search_eval_tests.rs are intended to preserve that baseline while world-class search evolves.
Ranked Search
MentisDB now also exposes an additive ranked-search surface for direct crate use:
RankedSearchQueryRankedSearchGraphMentisDb::query_context_bundles(&RankedSearchQuery)MentisDb::query_ranked(&RankedSearchQuery)RankedSearchBackend::{Lexical, Hybrid, LexicalGraph, HybridGraph, Heuristic}
This surface is intentionally separate from ThoughtQuery.
ThoughtQuery still decides which thoughts are eligible. Ranked search then decides how those eligible thoughts are ordered.
Current ranked-search behavior:
RankedSearchQuery.filteruses the same deterministic semantics asMentisDb::query- when
textnormalizes to a non-empty query, the backend islexicalorhybriddepending on whether a managed vector sidecar is active for the current handle - lexical ranking scores indexed thought text plus agent metadata from the filtered candidate set
- when a managed vector sidecar is active for the current handle, ranked search blends lexical scoring with vector similarity and the backend becomes
hybrid - when
graphis enabled alongside non-emptytext, the backend becomeslexical_graphorhybrid_graphdepending on whether vector scoring is available - graph expansion starts from lexical seed hits, walks
refsand typedrelations, and can surface supporting context that did not lexically match as_of(RFC 3339 timestamp) filters to only relation edges that were valid at the given point in time, using each edge'svalid_at/invalid_attemporal window — edges without temporal bounds are always includedscopenarrows results to thoughts tagged with a matching memory scope (user,session, oragent); omitted scope returns all- when
textis absent or blank, the backend falls back toheuristic - heuristic ordering uses lightweight importance, confidence, and recency signals
total_candidatescounts the hits after filter application and ranked-signal gating, before finallimittruncation- each ranked hit includes
matched_termsplusmatch_sourcessuch ascontent,tags,concepts,agent_id, andagent_registry - each ranked hit also includes a
vectorscore component when semantic sidecars contribute to the ranking - graph-expanded hits also expose
graph_distance,graph_seed_paths,graph_relation_kinds, andgraph_pathprovenance so callers can explain why a supporting thought surfaced - grouped context delivery is available through
query_context_bundles, which anchors supporting graph hits beneath lexical seeds in deterministic order compact: true(MCPmentisdb_ranked_searchandmentisdb_federated_search, REST/v1/ranked-searchand/v1/federated-search, CLImentisdb search --compactandmentisdb search federated --compact) returns smaller hits for routine recall; see Compact search results
Lexical ranked example:
use mentisdb::{MentisDb, RankedSearchQuery, ThoughtQuery, ThoughtType};
use std::path::PathBuf;
# fn main() -> std::io::Result<()> {
let chain = MentisDb::open(&PathBuf::from("/tmp/tc_ranked"), "agent1", "Agent", None, None)?;
let ranked = RankedSearchQuery::new()
.with_filter(
ThoughtQuery::new()
.with_types(vec![ThoughtType::Decision])
.with_tags_any(["search"]),
)
.with_text("latency ranking")
.with_limit(10);
let results = chain.query_ranked(&ranked);
assert!(matches!(
results.backend,
mentisdb::RankedSearchBackend::Lexical | mentisdb::RankedSearchBackend::Hybrid
));
# let _ = results;
# Ok(())
# }
Lexical + graph ranked example:
use mentisdb::{MentisDb, RankedSearchGraph, RankedSearchQuery, ThoughtQuery, ThoughtType};
use mentisdb::search::GraphExpansionMode;
use std::path::PathBuf;
# fn main() -> std::io::Result<()> {
let chain = MentisDb::open(&PathBuf::from("/tmp/tc_ranked"), "agent1", "Agent", None, None)?;
let ranked = RankedSearchQuery::new()
.with_filter(
ThoughtQuery::new()
.with_types(vec![ThoughtType::Decision])
.with_tags_any(["search"]),
)
.with_text("latency ranking")
.with_graph(
RankedSearchGraph::new()
.with_max_depth(1)
.with_mode(GraphExpansionMode::Bidirectional),
)
.with_limit(10);
let results = chain.query_ranked(&ranked);
# let _ = results;
# Ok(())
# }
Temporal and scoped ranked example:
use mentisdb::{MentisDb, MemoryScope, RankedSearchQuery, ThoughtQuery};
use std::path::PathBuf;
# fn main() -> std::io::Result<()> {
let chain = MentisDb::open(&PathBuf::from("/tmp/tc_ranked"), "agent1", "Agent", None, None)?;
let ranked = RankedSearchQuery::new()
.with_filter(ThoughtQuery::new())
.with_text("cache invalidation")
.with_as_of("2025-06-01T00:00:00Z")
.with_scope(MemoryScope::Session)
.with_limit(10);
let results = chain.query_ranked(&ranked);
# let _ = results;
# Ok(())
# }
Vector-backed ranked example:
use mentisdb::{MentisDb, RankedSearchBackend, RankedSearchQuery};
use mentisdb::search::LocalTextEmbeddingProvider;
use std::path::PathBuf;
# fn main() -> std::io::Result<()> {
let mut chain = MentisDb::open_with_key(&PathBuf::from("/tmp/tc_ranked_vectors"), "semantic-ranked")?;
chain.append("planner", mentisdb::ThoughtType::Decision, "Tail latency ceiling for the Europe rollout.")?;
// Register the built-in local-text-v1 embedding sidecar so ranked search can
// blend lexical and semantic signals for the current chain handle.
chain.manage_vector_sidecar(LocalTextEmbeddingProvider::new())?;
let ranked = chain.query_ranked(&RankedSearchQuery::new().with_text("performance budget"));
assert_eq!(ranked.backend, RankedSearchBackend::Hybrid);
assert!(ranked.hits.iter().any(|hit| hit.score.vector > 0.0));
# Ok(())
# }
Grouped context example:
use mentisdb::{MentisDb, RankedSearchGraph, RankedSearchQuery, ThoughtQuery};
use mentisdb::search::GraphExpansionMode;
use std::path::PathBuf;
# fn main() -> std::io::Result<()> {
let chain = MentisDb::open(&PathBuf::from("/tmp/tc_ranked"), "agent1", "Agent", None, None)?;
let bundles = chain.query_context_bundles(
&RankedSearchQuery::new()
.with_filter(ThoughtQuery::new().with_tags_any(["search"]))
.with_text("latency ranking")
.with_graph(
RankedSearchGraph::new()
.with_mode(GraphExpansionMode::Bidirectional)
.with_max_depth(2),
)
.with_limit(5),
);
# let _ = bundles;
# Ok(())
# }
Product rule:
- keep
ThoughtQuerystable and explainable for append-order filtering - evolve ranked search as a separate surface with its own benchmarks, tests, and transport layers
- treat registry-aware filtering and future transport exposure as additive work on top of the current crate API
- use
query_rankedfor flat ranked retrieval andquery_context_bundleswhen the caller wants seed-anchored support context instead of one mixed list
The ranked-search benchmark benches/search_ranked.rs and evaluation tests in tests/search_ranked_eval_tests.rs are the guardrails for that additive surface.
Compact search results
Ranked and federated search accept an opt-in compact: true. It cuts the tokens an agent spends reading results without removing any field the agent reasons with. The default response is unchanged. It is available on MCP (mentisdb_ranked_search, mentisdb_federated_search), REST (POST /v1/ranked-search, POST /v1/federated-search) and the CLI (mentisdb search --compact, mentisdb search federated --compact). It has no effect on mentisdb_context_bundles and POST /v1/context-bundles, which still return full thoughts.
A compact hit is chain_key, the total score as a plain number, and the thought, in the same order as the full form. Graph-expanded hits also keep graph_distance, graph_seed_paths, graph_relation_kinds and graph_path.
| Full hit | Compact hit | |
|---|---|---|
score |
object with lexical, vector, graph, importance, ... and total |
the total number |
matched_terms, match_sources |
present | left out |
thought hash, prev_hash |
present | left out (chain integrity) |
thought thought_signature, signing_key_id |
present | left out (signing; provenance still carries the server's verdict) |
thought schema_version |
present | left out |
thought agent_name, agent_owner |
present | left out (they repeat the agent registry entry for agent_id; mentisdb_get_agent resolves it) |
top-level thought fields that are null, "", [] or {} |
present | left out |
thought provenance (segment, signed, signature, signature_version, verified_agent, trust) |
present | always kept, whole |
version_status, successors, current_version, successor_of, cross_agent, collapsed_duplicates |
present when set | always kept |
relations, concepts, refs, content, tags, ids, importance, confidence, timestamps |
present | kept (zero and false are values, not empty) |
Fields are dropped by name from a fixed list, so a field added to the thought later appears in compact hits by default. Visibility is decided before compaction: a public reader still gets only the public segment, and a reader with a valid X-Mentis-Auth proof still gets the private one, each hit with its provenance.
Full hit (POST /v1/ranked-search):
{
"backend": "hybrid",
"total": 1,
"results": [
{
"chain_key": "project",
"score": {
"confidence": 0.0, "graph": 0.0, "importance": 0.17541419, "lexical": 1.9490464,
"recency": 0.05, "relation": 0.0, "rrf": 0.0, "seed_support": 0.0,
"session_cohesion": 0.0, "total": 5.932654, "vector": 0.34079674
},
"matched_terms": ["job", "queue", "storag"],
"match_sources": ["content", "tags", "concepts"],
"graph_distance": null, "graph_path": null, "graph_relation_kinds": [], "graph_seed_paths": 0,
"thought": {
"agent_id": "builder", "agent_name": "Builder", "agent_owner": "platform",
"concepts": ["job queue"], "confidence": null,
"content": "Use Postgres for the job queue; revisit if throughput exceeds 5k jobs per second.",
"entity_type": null,
"hash": "31de8f264b1588a29be30a278a24e8623cf51b8f3ce8483a7e52f69ce80e21e1",
"id": "1182d44f-3834-4ff0-9121-eab986b1a4f5", "importance": 0.800000011920929, "index": 0,
"prev_hash": "",
"provenance": {
"segment": "public", "signature": "unsigned", "signature_version": null,
"signed": false, "trust": "untrusted_data", "verified_agent": null
},
"refs": [], "relations": [], "role": "Memory", "schema_version": 3, "session_id": null,
"signing_key_id": null, "source_episode": null, "tags": ["storage"],
"thought_signature": null, "thought_type": "Decision",
"timestamp": "2026-11-01T23:03:19.669167Z"
}
}
]
}
The same request with "compact": true:
{
"backend": "hybrid",
"total": 1,
"results": [
{
"chain_key": "project",
"score": 5.932654,
"thought": {
"agent_id": "builder",
"concepts": ["job queue"],
"content": "Use Postgres for the job queue; revisit if throughput exceeds 5k jobs per second.",
"id": "1182d44f-3834-4ff0-9121-eab986b1a4f5", "importance": 0.800000011920929, "index": 0,
"provenance": {
"segment": "public", "signature": "unsigned", "signature_version": null,
"signed": false, "trust": "untrusted_data", "verified_agent": null
},
"role": "Memory", "tags": ["storage"], "thought_type": "Decision",
"timestamp": "2026-11-01T23:03:19.669167Z"
}
}
]
}
When to use it: routine recall and scanning many hits, where the content, tags, relations, version status and provenance are what the agent reads. Leave it off when you need the hashes or signatures to verify a thought yourself, when you audit a provenance chain, or when you debug per-component scores or matched terms. mentisdb_get_thought (REST POST /v1/thought) returns the full record of any hit.
Measured on a copy of a working MentisDB with 11 chains (12 ranked, graph and federated searches, 10 hits each), responses were 23.7% smaller (353,071 B to 269,335 B); on a generated corpus of 66 queries they were 34.2% smaller. cargo bench --bench search_compact shows the same request time with and without compact (about 25% fewer bytes). Contributed by Austin Faulkner-Pearce.
Lean MCP output
Agents read MCP tool results with their context window, so the streamable-HTTP MCP surface (JSON-RPC tools/call) is leaner than REST:
- Results are minified JSON text, with no indentation and no second
structuredContentcopy of the same object. (No tool declares anoutputSchema, so clients read the text.) REST andPOST /tools/executestill return the object. mentisdb_ranked_search,mentisdb_federated_search,mentisdb_lexical_searchandmentisdb_context_bundlesare compact by default; pass"compact": falsefor the full record. A lean thought leaves out what is default, so an absent field means its default: noprovenanceis a public, unsigned thought (a private segment, a signature or averified_agentis always listed), noroleisMemory, noimportanceis0.5, nochain_keyis the chain you searched. Floats are rounded, timestamps keep full precision (so they round-trip throughas_ofandsince),successor_ofis an older version that matched the query and that the hit replaces, with asuperseded_versionscount that is a lower bound (not the whole lineage), andversion_status,successorsandcurrent_versionstill say when a memory is contested or superseded.mentisdb_standing_contextreturns the renderedpromptonce. Itsentriesarray repeats the same memories, so it needsinclude_entries: true.
Measured with cargo run --release --example token_diet (a generated 3,500-thought chain with superseded lineages and weak-link corrections, 10 hits, characters of the text the model reads):
| Tool call | Before | After |
|---|---|---|
mentisdb_ranked_search (default) |
23,657 | 5,948 |
mentisdb_ranked_search compact: true |
12,699 | 5,948 |
mentisdb_ranked_search compact: false |
23,657 | 16,696 |
mentisdb_lexical_search |
18,743 | 6,341 |
mentisdb_federated_search |
23,511 | 6,025 |
mentisdb_context_bundles (5 bundles) |
9,993 | 3,562 |
mentisdb_standing_context |
36,191 | 13,050 |
mentisdb_recent_context (20 thoughts) |
6,936 | 6,931 |
The rules are in the mentisdb::server_lean rustdoc.
Search Scoring (0.8.1)
Starting in 0.8.1, ranked search uses six key improvements:
- Porter stemming — the lexical tokenizer stems all tokens before indexing and querying so word variants share a common root (e.g.
prefers/preferred/preferences→prefer). - Smooth exponential vector-lexical fusion — replaces the 0.8.0 step-function boosts with a continuous decay curve:
vector × (1 + 35 × exp(-lexical / 3.0)). Pure-semantic matches get ~36× amplification; by lexical=3.0 the boost has decayed to ~12×; at lexical=6.0 it's additive. This eliminates discontinuities between tiers. (Since the valid-version retrieval work the default isMENTISDB_VECTOR_FUSION=relative, which decays on the lexical score relative to the query's best so that long queries keep their vector signal;absoluterestores this formula.) - Session cohesion scoring — thoughts within ±8 positions of a high-scoring lexical seed (score ≥ 3.0) receive a proximity boost up to 0.8, decaying linearly with distance. This surfaces evidence turns adjacent to the matching turn but sharing no lexical terms.
- BM25 document-frequency cutoff — terms appearing in >30% of documents (corpus ≥ 20 docs) are skipped during scoring. This filters non-discriminative entity names without blanket stopword removal.
- Importance-weighted scoring — replaces flat multipliers with a differential boost proportional to lexical score:
lexical × (importance - 0.5) × 0.3. User-originated thoughts (importance ≈ 0.8) outrank verbose assistant responses (importance ≈ 0.2) in close BM25 races. - Graph expansion limits and relation boosts —
MAX_GRAPH_SEEDS=20bounds BFS cost;ContinuesFromboost raised to 0.30; graph proximity 1.0/depth.
These changes took LongMemEval R@5 from 57.2% to 67.6% and LoCoMo 2-persona R@10 from 55.8% to 88.7%.
Search Scoring (0.8.2)
Starting in 0.8.2, ranked search adds temporal, scoped, and dedup-aware features:
- Temporal
as_ofpoint-in-time filtering —RankedSearchQuery::with_as_of(rfc3339)restricts graph expansion to only relation edges whosevalid_at/invalid_atwindow covers the given timestamp. Edges without temporal bounds are always included. This enables queries like "what did the agent know at the start of the sprint?" - Memory scope filtering via
scopetag — thoughts carry ascopefield (user,session, oragent) stored asscope:<value>tags.RankedSearchQuery::with_scope(MemoryScope::Session)narrows results to session-scoped memories only. Omitting scope returns thoughts from all scopes. - Auto-dedup with
Supersedesrelations — whenMENTISDB_DEDUP_THRESHOLDis set (recommended0.85for long-lived agent chains; off by default), appending a thought whose content is sufficiently similar (Jaccard ≥ threshold) to a recent thought automatically emits aSupersedesrelation to that prior thought. The prior thought remains on disk for audit; its id enters the invalidation set for default search exclusion. invalidated_thought_idsfor O(1) superseded exclusion — thoughts targeted bySupersedes,Corrects, orInvalidatesare excluded from defaultquery, ranked search, context bundles, recent context, and related retrieval. Passinclude_invalidated=true(orThoughtQuery::with_include_invalidated(true)) for audit. Point-in-timeas_ofstill surfaces thoughts that were valid at that timestamp. The set only fills when those edges exist (agent-written and/or auto-dedup).
Search Scoring (0.8.7)
Starting in 0.8.7, ranked search adds:
- Entity type filtering — thoughts can carry an optional
entity_typelabel (e.g. "bug_report", "architecture_decision", "retrospective"). TheThoughtQueryacceptsentity_typeas a filter, and the dashboard exposes an entity_type text filter in the explorer. Entity types are auto-observed per chain and persisted in achain_key-entity-types.jsonsidecar.
Search Scoring (0.8.6)
Starting in 0.8.6, ranked search adds three features:
- Irregular verb lemma expansion — the query tokenizer maps irregular past-tense verbs to their base form (e.g. "went" → "go", "gave" → "give", "ran" → "run"). About 325 mappings onto 219 base forms. Indexed content is not modified — expansion is query-time only.
- Reciprocal Rank Fusion (RRF) — an opt-in reranking pass. When
enable_reranking=trueis set on a ranked search query, the engine produces separate lexical-only, vector-only, and graph-only rankings over the toprerank_kcandidates (default 50), merges them via1/(k + rank)withk=60, and adds a scaled consensus bonus to the additive total. Use when lexical and vector signals disagree on top candidates. (Before 0.10.9 the RRF total replaced the additive total, which badly degraded results; see below.) - Per-field BM25 DF cutoffs —
Bm25DfCutoffsonLexicalQueryallows configuring separate document-frequency cutoff ratios per field (content, tags, concepts, agent_id, agent_registry). Terms whose global DF exceeds the cutoff for a given field are skipped for that field only. Default cutoffs match the original behavior (content=0.30, tags=0.30, concepts=0.30, agent_id=0.70, agent_registry=0.60).
Search Scoring (after 0.9.9)
The post-0.9.9 ranked-search validation run used real embeddings plus automatic thesaurus expansion on the full LoCoMo-10P benchmark:
- LoCoMo-10P overall R@10: 72.6% (1436 / 1977 queries)
- Single-hop R@10: 76.8% (1193 / 1554 queries)
- Multi-hop R@10: 57.4% (243 / 423 queries)
- Weak-vector smoke baseline: 44.9% R@10, so the validated pipeline improved recall by 27.7 percentage points.
- Evaluation throughput: 6 seconds for 1977 queries (~317 queries/second).
- Vector sidecar:
fastembed-all-minilm-l6-v2, about 28 MB with 5882 indexed thoughts.
The run applied the built-in thesaurus transparently on every ranked_search call and matches the whitepaper target of about 72% overall LoCoMo-10P R@10.
Search Scoring (0.10.9)
- RRF rerank fixed —
enable_reranking=trueno longer replaces the additive score with the tiny raw RRF total (which collapsed rankings). RRF now adds a consensus bonus scaled byRRF_SCORE_SCALE(50): a rank-1 hit in all three lists is worth about +2.5, enough to break ties and reward agreement without overriding a clearly stronger lexical match. Only lists with a positive score for a candidate contribute. - Stemmed thesaurus keys — synonyms now expand for inflected query terms (
debuggingexpands likedebug,deployslikedeploy). Because stem keys make expansion fire more often, automatic synonyms are damped to weight 0.3 with at most 3 synonyms per term (the previous 0.7 / 5 displaced literal matches and cost about 2.4 points of LongMemEval R@5). - Federated search keyed by chain + id —
POST /v1/federated-search/mentisdb_federated_searchfuse per-chain rankings with the same additive RRF bonus, keyed by(chain_key, thought id), and deduplicate before paging, sooffset/limitpages no longer repeat or drop results. - Faster ranked, lexical, vector and graph paths — score-only top-k selection, dense lexical scans, cached vector norms and exact top-k, and a bounded graph-expansion arena. Filtered lexical and heuristic queries are roughly 10x faster in the criterion benches.
- Filtered HNSW recall — when filters are active, the HNSW backend switches to an exact scan over the filtered set or oversamples, so filtered vector searches no longer lose matches the approximate graph skipped.
- Benchmarks (0.10.9.54 vs the 0.10.8 code line,
fastembed-minilm) — LoCoMo-10P default R@5/R@10 63.8/72.7% → 63.9/73.5%; LoCoMo rerank R@5/R@10 3.6/5.9% → 66.0/74.1%; LongMemEval default R@5/R@10/R@20 66.8/72.0/78.2% → 68.0/72.8/78.8%; LongMemEval rerank R@5 2.8% → 68.6%; query throughput about 206/159 → 384/385 queries/s (LoCoMo/LongMemEval).
Search Scoring (0.11.0)
- Valid-version retrieval — a superseded hit is replaced by its live successor, a thought a newer correction or decision only references is shown as
contestedwith the newer one ranked above it, and every hit carriesversion_status. - Relative vector fusion (
MENTISDB_VECTOR_FUSION=relative, decay 0.8) and result-time duplicate collapse (Jaccard 0.9). - Library and server share the defaults —
RankedSearchQuery::new()now applies relative fusion, duplicate collapse, successor redirection and thesaurus expansion at weight 0.3, like the daemon. Opt out per query (with_vector_fusion(VectorFusion::Absolute),with_collapse_duplicates(None),with_resolve_successors(false),with_thesaurus(false)) or per request (vector_fusion: "absolute",collapse_duplicates: 0,resolve_successors: false,synonym_weight: 0). - Deprecated —
RankedSearchQuery::{llm_rerank, llm_model, llm_rerank_top_k, with_llm_reranking},RankedSearchScore::llm_score(LLM reranking was never implemented) andsearch::ppr(never called by ranked search) are no-ops marked#[deprecated], to be removed in the next breaking release. - Full-protocol benchmarks (2026-11-01,
fastembed-minilm, fresh ingest, same scripts as 0.10.9.54) — LoCoMo-10P default R@5/R@10/R@20 67.9/76.7/83.4% (0.10.9.54: 63.9/73.5/–); LongMemEval default R@5/R@10/R@20 69.8/75.6/81.4% (0.10.9.54: 68.0/72.8/78.8%); about 428/371 queries/s. Raw outputs:results/benchmarks/2026-11-01-full-protocol/.
Vector Sidecars
MentisDB now exposes an additive Phase 3 vector sidecar surface for direct crate use:
search::EmbeddingProvidersearch::EmbeddingMetadatasearch::VectorSidecarVectorSearchQueryMentisDb::vector_sidecar_path(&EmbeddingMetadata)MentisDb::load_vector_sidecar(&EmbeddingMetadata)MentisDb::vector_sidecar_freshness(&VectorSidecar, &EmbeddingMetadata)MentisDb::rebuild_vector_sidecar(&provider)MentisDb::manage_vector_sidecar(provider)MentisDb::unmanage_vector_sidecar(&EmbeddingMetadata)MentisDb::managed_vector_sidecars()MentisDb::apply_persisted_managed_vector_sidecars()MentisDb::managed_vector_sidecar_statuses()MentisDb::set_managed_vector_sidecar_enabled(kind, enabled)MentisDb::sync_managed_vector_sidecar_now(kind)MentisDb::rebuild_managed_vector_sidecar_from_scratch(kind)MentisDb::query_vector(&provider, &VectorSearchQuery)
Contract:
- embeddings remain optional, and MentisDB still works with no vector dependencies at all
- vector state lives in a rebuildable sidecar, never in the canonical append-only chain
- vector sidecars are separated by
chain_key,thought_id,thought_hash,model_id, embedding dimension, and embedding version - changing the embedding model or version invalidates old vector state instead of silently mixing incompatible embeddings
- callers can opt one embedding space into append-time synchronization on a live handle by registering a managed vector sidecar provider
- vector hits surface whether they came from a
Freshor stale sidecar - deleting or corrupting the sidecar degrades only vector retrieval; plain chain reads, appends, and lexical/graph search still work
- since 0.10.6, each append writes one integrity-chained WAL record beside the JSON snapshot (
*.json.wal, magicMDBVWAL1). Load replays the WAL after verifying the snapshot digest. The snapshot is compacted and the WAL removed every 32 records. Older binaries that only read JSON treat a sidecar with a pending WAL as stale and rebuild.
Operational flow:
- rebuild a sidecar explicitly for one provider and chain
- or register that provider as a managed vector sidecar and keep it fresh on future appends for that open handle
- load or query that sidecar later with the same embedding metadata
- if the chain head changes, the sidecar becomes stale and results report that freshness state until the sidecar is rebuilt
mentisdb Default Vector Sidecar
mentisdb now applies a persisted managed-vector setting every time it opens a chain.
- by default each chain gets the built-in FastEmbed MiniLM embedding provider (
fastembed-minilm), which runs locally via ONNX with no cloud dependencies. The legacylocal-text-v1provider is also available. - the daemon keeps that sidecar synchronized on append unless the user disables auto-sync for that chain
- ranked search in the daemon and dashboard now uses that managed sidecar transparently, blending lexical, graph, and vector signals whenever it is enabled and available
- the web dashboard exposes per-chain controls to:
- enable or disable append-time auto-sync
- sync the sidecar to the latest chain state without changing the enable/disable setting
- rebuild the sidecar from scratch after an explicit confirmation that the previous file will be deleted and recreated
- if auto-sync is disabled, new thoughts can make the sidecar stale until the user syncs or rebuilds it
Since 0.10.9 (issue #23, memory blow-up with many chains):
- one FastEmbed model is loaded per process and shared by every chain, and texts are embedded in small bounded batches, so memory no longer grows with the number of open chains
- the ONNX model cache lives in
<MENTISDB_DIR>/.fastembed_cacheinstead of the daemon's working directory; setFASTEMBED_CACHE_DIRto put it elsewhere - opening a chain never embeds its history on the request path: chains with more than 32 thoughts and no fresh sidecar are rebuilt by a single background worker. Until the rebuilt sidecar is adopted (on the next request or append once the worker finishes), ranked search on that chain returns lexical and graph results only
- opening a chain no longer rewrites its persisted vector provider configuration
MENTISDB_EMBEDDINGSselects the embeddings mode process-wide: unset (default: FastEmbed when compiled in, local text otherwise),off(no managed sidecars, lexical only),local-text(built-inlocal-text-v1hashing, never loads ONNX), orfastembed
Upgrading from 0.10.1–0.10.8: the first start after upgrading may show lexical-only ranked results for large chains while their sidecars rebuild in the background. A stray .fastembed_cache/ left in the directory you used to start the daemon from can be deleted; the model is re-downloaded into the new location once.
HNSW approximate-nearest-neighbor vector backend
By default MentisDB uses an exact cosine scan over the managed vector sidecar.
Once the sidecar reaches MENTISDB_HNSW_THRESHOLD vectors (default 50,000) the
backend automatically switches to an HNSW approximate graph for that
sidecar. The same VectorSearchBackend trait powers both implementations, so
public APIs and hybrid/ranked search results stay the same:
- small corpora keep the deterministic exact backend
- large corpora get sub-linear approximate search with no query change
MENTISDB_HNSW_EF_CONSTRUCTIONandMENTISDB_HNSW_EF_SEARCHtune accuracy versus latencyMENTISDB_HNSW_BACKGROUND_BUILD(default true) builds the graph off-thread while the daemon keeps answering queries
End users see lower latency transparently. The HNSW backend is always compiled in since 0.10.4.49.
How vectors are stored (0.12)
Every vector of a managed sidecar lives once, in a flat store of 128-row chunks:
one 64-byte-aligned allocation per chunk, rows padded to whole 64-byte lines. The
sidecar entries, the exact index, the HNSW graph and the implicit-edge scanner all
hold handles to those rows, so there is no second copy of the corpus (about 150 MB
saved at 100,000 vectors of 384 dimensions per consumer). Exact search scores a
row with a 16-lane dot product written so the compiler emits NEON (aarch64) or
SSE2 (x86_64) instructions without unsafe intrinsics, a nightly toolchain or
runtime CPU probing; every platform computes the same bits. Scores equal a
sequential cosine within 1e-5. One limit: an HNSW graph loaded from disk keeps
its own copy of the vectors in the graph (the hnsw crate owns them); a graph
built in this process shares fully.
REST Lexical Search
The daemon also exposes the Phase 1 ranked lexical surface over REST at POST /v1/lexical-search.
This is the right endpoint when you want lexicographical/lexical text ranking only, with simple score and match provenance fields.
Request shape:
{
"chain_key": "mentisdb",
"text": "latency ranking",
"agent_ids": ["planner"],
"thought_types": ["Decision"],
"offset": 0,
"limit": 10
}
Example response:
{
"total": 1,
"results": [
{
"thought": {
"index": 42,
"agent_id": "planner",
"content": "Latency budget for the Europe rollout."
},
"score": 2.91,
"matched_terms": ["latency", "ranking"],
"match_sources": ["content", "tags", "agent_registry"]
}
]
}
Phase 4 Transport Contract (Ranked + Bundles)
Phase 4 transport work keeps plain POST /v1/search and POST /v1/lexical-search
compatibility and adds two additive endpoints:
POST /v1/ranked-searchfor flat ranked retrievalPOST /v1/context-bundlesfor seed-anchored grouped support context
Example POST /v1/ranked-search request:
{
"chain_key": "mentisdb",
"text": "performance budget",
"thought_types": ["Decision"],
"limit": 10
}
Result window. A page is ranked from the top, so offset + limit may not exceed 10,000 on /v1/ranked-search, /v1/lexical-search, /v1/federated-search, /v1/context-bundles, their MCP tools and mentisdb search. A larger window is refused with 400 and a message naming the maximum (it is not clamped, which would return the wrong page); narrow the query with filters or since/until to read deeper. A standing-context per_type_limit above 100 is refused the same way.
When a managed vector sidecar such as the built-in fastembed-minilm provider is active for that chain, the ranked backend becomes hybrid or hybrid_graph and the response includes a non-zero score.vector component for semantic-only or semantic-boosted hits.
Ranked response contract fields:
backendresults[].score.{lexical,vector,graph,relation,seed_support,importance,confidence,recency,session_cohesion,rrf,total}results[].matched_termsresults[].match_sourcesresults[].graph_distanceresults[].graph_seed_pathsresults[].graph_relation_kindsresults[].graph_pathresults[].chain_key(present when searching branch chains with ancestor results)
Context-bundle response contract fields:
total_bundlesconsumed_hitsbundles[].seed.{locator,lexical_score,matched_terms,thought}bundles[].support[].{locator,thought,depth,seed_path_count,relation_kinds,path}
MCP transport mirrors this split with additive tools:
mentisdb_ranked_searchmentisdb_context_bundles
Acceptance coverage for these transport contracts lives in:
tests/search_transport_contract_tests.rs
Response shape:
{
"total": 2,
"results": [
{
"thought": { "index": 42, "agent_id": "planner", "content": "..." },
"score": {
"lexical": 2.91,
"vector": 0.27,
"graph": 0.18,
"relation": 0.05,
"seed_support": 0.0,
"importance": 0.0,
"confidence": 0.0,
"recency": 0.0,
"total": 3.14
},
"matched_terms": ["latency", "ranking"],
"match_sources": ["content", "tags", "agent_registry"]
}
]
}
Public and private chains
A chain is public (anyone with access writes unsigned and reads freely) or private (writes need a signature by an authorized Ed25519 key, and what is written while private can be read only by a reader who proves possession of an authorized key). Mode changes are signed records in the chain that open segments; every thought belongs to the segment its position falls in, so an unauthorized reader sees only the public segments, on every read surface (search, context, traversal, exports, listings, counts).
# operator (dashboard PIN, or --offline on the host that holds the data directory)
mentisdb chain access set private --chain vault --pin 123456
mentisdb agent key generate builder --key-id builder-1 --chain vault --pin 123456 # makes the pair, registers the public key
# (or register a key made elsewhere:)
# mentisdb agent key add builder --key-id builder-1 --public-key-hex <64 hex> --chain vault --pin 123456
mentisdb chain access allow builder builder-1 <64 hex> --chain vault --pin 123456
# an authorized client signs every request locally; the key never leaves it
mentisdb search "launch plan" --chain vault --read-key-file builder.key --read-agent builder --read-key-id builder-1
MENTISDB_READ_KEY_FILE=builder.key MENTISDB_READ_AGENT_ID=builder MENTISDB_READ_KEY_ID=builder-1 mentisdb --mode stdio
agent key generate creates the Ed25519 pair on the machine you run it on,
saves the private seed (64 hex characters) to an owner-only file (--out FILE,
else $MENTISDB_KEY_DIR/<public key prefix>.key, default ~/.mentisdb/keys;
--force to overwrite), and registers only the public key. The private key is
never printed, logged or sent, and that file is its only copy: MentisDB cannot
recover it, so back it up, and never paste it into a chat or give it to an AI
agent. If the registration fails after the file was written the file is kept and
the error prints the agent key add ... --public-key-hex command that registers
it later. The dashboard offers the same on the agent page ("Generate key pair"),
generated in the browser with WebCrypto, so the private key never reaches the
server. Use the file with --private-key-file / --read-key-file.
Only the operator can add or remove keys; REST and MCP cannot. Every
returned thought carries a provenance object (segment, signature, verified
agent, trust: untrusted_data) and the operating skill tells agents to treat
memories as data, never as instructions. The prompt blocks loaded at session
start (standing, recent and restored context, the MEMORY.md export) render
every entry as one escaped line, so stored text cannot close a block or forge an
entry, and each standing entry shows trust=verified|unsigned|unverified. Serve private chains over HTTPS.
Details, wire formats and the threat model: docs/CHAIN_ACCESS.md.
Web Dashboard
The daemon includes an embedded browser UI at:
https://127.0.0.1:9475/dashboard
The dashboard is served over HTTPS with the same self-signed certificate used by the HTTPS MCP and REST surfaces.
Dashboard capabilities:
- live chain listing with thought, agent, and storage-size counts
- thought exploration with grouped ThoughtType filters, refs, and typed relations
- chain-scoped ranked search with text and live-agent filters
- grouped context bundles for seed-anchored supporting search context
- ranked result inspection in the thought modal, including score breakdowns, matched terms, graph distance, relation kinds, and bundle support preview
- per-chain vector sidecar inspection plus enable/disable, sync, and rebuild controls
- agent detail management for display name, description, owner, status, and signing keys
- latest agent-thought browsing without restarting the daemon after new thoughts are appended
- chain import from
MEMORY.md - cross-chain agent-memory copy with agent metadata preserved on the target chain
- skill browsing, summary counts (total / active / revoked / deprecated), diffing, editing into new immutable versions, deprecation, revocation, and permanent delete of revoked skills
- Settings tab to view and edit all
MENTISDB_*environment variables with live apply, reset-to-default, and.envpersistence
Protect the dashboard with MENTISDB_DASHBOARD_PIN whenever the daemon is reachable
outside localhost.
Host allowlist
One list of Host names serves the dashboard, REST and MCP: localhost, 127.0.0.1,
[::1], the configured MENTISDB_BIND_HOST, every entry of
MENTISDB_DASHBOARD_ALLOWED_HOSTS and, when MENTISDB_BIND_HOST is 0.0.0.0 or ::, the
machine's own interface IPs. A VPS reached by its public IP or DNS name through a loopback
bind and a reverse proxy lists that name in MENTISDB_DASHBOARD_ALLOWED_HOSTS.
The my.mentisdb.com alias is accepted on TLS listeners only (HTTPS MCP, HTTPS REST and
the dashboard, whose certificate carries the name). It is a public DNS record that points at
127.0.0.1, but MentisDB does not control it: whoever controls that name (a lapsed domain, a
compromised registrar account) could serve a page and rebind the name to your loopback
daemon, and a plain-HTTP listener would take the page for "same-origin". So the plain HTTP
MCP and REST ports (9471, 9472) answer 403 to Host: my.mentisdb.com unless you opt in
with MENTISDB_DASHBOARD_ALLOWED_HOSTS=my.mentisdb.com. Use https://my.mentisdb.com:9473
(MCP), :9474 (REST) and :9475 (dashboard), or http://localhost:9471.
The domain owner can still hold the name safely: enable the registrar's transfer/registry
lock and two-factor sign-in, and turn on DNSSEC for the zone. Keep bearer tokens
(MENTISDB_BEARER_TOKEN_ACCESS=true) and the dashboard PIN on whenever the daemon holds
data you care about: a rebinding page cannot present a token or the PIN.
- MCP on a loopback bind (the default) refuses any other
Hostwith403, for every client, onPOST /, theGET /event stream and the legacy/tools/*and/resources/*routes. This is the DNS-rebinding defence ofcloudllm_mcp0.4, fed with the list above so your configured names keep working (andmy.mentisdb.comon the HTTPS listener). A proxy that forwards an unlistedHostgets403 Forbidden host: add the name toMENTISDB_DASHBOARD_ALLOWED_HOSTS. - MCP on a wildcard bind (Docker, LAN) performs no
Hostcheck for non-browser clients, which reach the daemon by service name or DHCP address. - REST on a loopback bind (the default) checks
Hostfor every request, like MCP does:curl, the CLI, agents and browsers alike get403(host 'X' is not allowed; set MENTISDB_DASHBOARD_ALLOWED_HOSTS ...) unless the name is in the list. A request with noHostheader at all (HTTP/1.0, in-process) passes. Reverse proxy note: an nginx or Caddy in front of a loopback daemon forwards the public name asHostby default; add that name toMENTISDB_DASHBOARD_ALLOWED_HOSTS(or have the proxy sendHost: 127.0.0.1:9472), or every proxied REST call is refused. - REST on a wildcard bind, and MCP with bearer tokens off, refuse a request from a
browser (it carries
OriginorSec-Fetch-Site) unless itsHostandOriginhost are in the list.curl, the CLI and agents send neither header and are unaffected. - IPv6 entries match in canonical form (
2001:db8::7, not2001:0db8::7).
Dashboard API rules (0.10.9):
- Host allowlist (DNS-rebinding defence). Every dashboard route, including
GETpages and/dashboard/login, rejects a request with403unless itsHostheader names this daemon:localhost,127.0.0.1,[::1],my.mentisdb.com(the dashboard is HTTPS-only), the configuredMENTISDB_BIND_HOST, the machine's own interface IPs when bound to0.0.0.0or::, or an entry ofMENTISDB_DASHBOARD_ALLOWED_HOSTS(comma-separated; set via environment or.env, not from the dashboard). Reverse proxies must preserve the originalHostheader, or forward a name listed inMENTISDB_DASHBOARD_ALLOWED_HOSTS. - CSRF protection.
POST,PATCHandDELETEcalls under/dashboard/api/, and thePOST /dashboard/loginform, must come from the dashboard's own origin. The first signal present decides: anOriginheader whose host matches the request host (Origin: nullis treated as absent), elseSec-Fetch-Site: same-origin(set by browsers, not by pages), else aRefererwhose host matches. Scripts and CLI clients that send none of these must addX-MentisDB-Dashboard: 1; anything else gets403. Dashboard responses carryReferrer-Policy: same-origin, so browsers keep the realOriginon the dashboard's own requests and send no referrer to other sites. - Private chains need the PIN, consistently. With no
MENTISDB_DASHBOARD_PINthe dashboard cannot tell the operator from anyone else, so it refuses (403) to show, change or delete a chain with private segments, and, while the daemon holds any private chain, to change settings, create, revoke or delete bearer tokens, or restart the daemon. Set a PIN and sign in to do any of it. A daemon with no private chain behaves as before. - PIN brute-force limiting covers the login form and the
Authorization: Bearer <pin>path alike, in three layers. (1) Per client: 5 failures in 5 minutes block that client; an IPv6 client is one client per/64(a single customer owns a whole/64, so rotating addresses inside it does not reset the count), an IPv4-mapped address counts as the IPv4 one. One client's failures do not lock out others, except behind a NAT or reverse proxy, where everyone shares one address and one bucket (X-Forwarded-Foris ignored, it is spoofable). (2) At most 4096 clients are remembered; expired entries, then the oldest, make room. (3) A global budget: more than 50 failures from all clients together in 5 minutes lock every PIN attempt, a correct PIN included, for 60 seconds, doubling on each repeat up to one hour (forgiven after two quiet hours). That caps an attacker who rotates through many addresses, at the cost that an attacker can make the owner wait; a signed-in session (cookie) is unaffected. Refusals are429withRetry-After. These limits bound guessing to at most about 600 tries an hour, which is not enough against a 4-digit PIN: use a long random PIN (12+ characters) for any dashboard reachable beyond localhost. - Chain keys created from the dashboard (bootstrap, branch target, copy-to target) must
match
[A-Za-z0-9_-]and be at most 128 characters, otherwise400. - Paging is clamped to
per_pageat most 500 andpageat most 1000. - PIN handling.
GETon the settings API never returns the PIN value (only whether one is set). Saving settings with a blank PIN keeps the current PIN. .envpermissions. Settings saved from the dashboard are written to<MENTISDB_DIR>/.envwith mode0600(it may hold the PIN), tightening an existing file too.- Errors. Dashboard
500responses carry only"internal server error"; details go to the daemon log.
TLS Certificates
The HTTPS MCP and REST servers and the web dashboard all serve a single
self-signed certificate that the daemon auto-generates on first startup at
<MENTISDB_DIR>/tls/cert.pem (and key.pem). The standard SAN set always
includes my.mentisdb.com (DNS), localhost (DNS), 127.0.0.1 (IP), every
unicast IP on every host interface, plus MENTISDB_BIND_HOST when it is a DNS
name — that is enough for local-only use and for connecting to the daemon by
its public DNS name.
For remote / VPS / custom-hostname setups you may need to add a SAN that the
daemon cannot infer on its own. The mentisdb cert subcommand mints a fresh
self-signed certificate with an extra SAN of your choice, makes it the active
cert on disk, and updates the local .env so the next daemon start serves the
new cert automatically.
# 1. Standard cert into the default location
# (~/.cloudllm/mentisdb/tls/ and updates ./.env)
mentisdb cert
# 2. Add a public VPS IP as a SAN so the cert is valid for that IP
mentisdb cert 192.0.2.10
# 3. Add a custom DNS hostname
mentisdb cert vps.example.com
# 4. Regenerate an existing cert (e.g. after adding a new IP to the box)
mentisdb cert 192.0.2.10 --force
# 5. Reset to factory defaults: delete existing cert/key, then generate fresh
mentisdb cert --reset
# 6. Write to a non-default directory and update a custom .env file
mentisdb cert 192.0.2.10 \
--out-dir /etc/mentisdb/tls \
--env-file /etc/mentisdb/mentisdb.env
# 7. Print the values without touching any .env (for ephemeral hosts)
mentisdb cert --no-env-update
Options
| Argument / Flag | Description |
|---|---|
<ip-or-domain> |
Optional IP literal or DNS hostname to add as a SAN. IPv4 and IPv6 literals become IP SANs; everything else becomes a DNS SAN. Omit to mint a cert with only the standard SAN set. |
--force |
Overwrite an existing cert.pem / key.pem on disk. Without this flag the command refuses to clobber a pre-existing cert so operators do not accidentally invalidate an already-trusted one. |
--reset |
Delete existing cert.pem / key.pem files first, then generate a fresh factory-default certificate. Implies --force. |
--out-dir <path> |
Directory to write cert.pem and key.pem into. Defaults to the directory of MENTISDB_TLS_CERT (or <MENTISDB_DIR>/tls/). |
--env-file <path> |
Path to the .env file to update with the new cert paths. Defaults to ./.env. |
--no-env-update |
Skip updating the .env file. The cert is still minted, the SAN list and SHA-256 fingerprint are still printed, and the command prints the export MENTISDB_TLS_CERT=... lines for you to paste into a shell rc. |
When the new cert takes effect
The new cert.pem and key.pem are written immediately and MENTISDB_TLS_CERT /
MENTISDB_TLS_KEY are updated on disk. The running daemon keeps using the cert
it loaded at startup, so restart the daemon (Ctrl-C in the TUI or stop
the background process) for the new cert to be served on the next HTTPS
request. Subsequent calls to mentisdb cert without --force reuse the
existing cert so the in-flight HTTPS fingerprint stays stable across restarts.
Cross-check the new cert from any machine with:
openssl s_client -connect <host>:9473 -showcerts </dev/null 2>/dev/null \
| openssl x509 -fingerprint -sha256 -noout
…then compare against the SHA-256 fingerprint: line that mentisdb cert
prints. If they match, the running daemon is serving the cert you just minted.
When the auto-generated SAN set is not enough
The default SAN set covers local and most remote setups. The mentisdb cert
subcommand is the right tool when:
- You connect to the daemon over a remote / VPS IP (
https://<vps-ip>:9473) and the IP is not in the SAN set. - You use a custom hostname (
vps.example.com) and want the cert to be valid for that name. - You added a new network interface or new IP to the host and need the cert to cover the new IP.
- You rotated the private key for security reasons and want a new cert + key pair.
- You migrated the daemon to a new machine and the old cert (still on the old box) needs to be regenerated locally.
For all other situations the auto-generated cert is fine. It is valid from one day
before it was generated until two years (730 days) after, never until a fixed calendar
date, and the daemon reuses it across restarts unless you delete it or pass --force.
At startup the daemon checks it: a certificate that expires within 30 days is reported
with a warning (log, terminal UI) naming mentisdb cert --force; one that has already
expired is regenerated automatically when MentisDB made it (Common Name
MentisDB Local), keeping its names (SANs) and a new key pair, with a warning that
clients must trust the new certificate; an expired certificate you supplied yourself
through MENTISDB_TLS_CERT / MENTISDB_TLS_KEY is only warned about.
Backup and Restore
MentisDB includes built-in backup and restore commands in the mentisdb CLI.
Create a backup
# Default: platform MENTISDB_DIR → ./mentisdb-YYYY-MM-DD-HH-MM-SS.mentis
mentisdb backup
# Custom output path
mentisdb backup -o /backups/mentisdb-2026-04-14.mentis
# Include TLS certificates
mentisdb backup --include-tls
# Full example
mentisdb backup --dir ~/.cloudllm/mentisdb -o /backups/mentisdb-2026-04-14.mentis --include-tls
When the daemon is running, backup calls POST /v1/admin/flush before reading files to ensure a consistent snapshot even with MENTISDB_AUTO_FLUSH=false. If the daemon is not running, files are captured as-is.
With MENTISDB_BEARER_TOKEN_ACCESS=true, /v1/admin/flush requires a global token.
Set MENTISDB_BEARER_TOKEN to one and backup (and restore's running-daemon probe) send
it as Authorization: Bearer <token>:
MENTISDB_BEARER_TOKEN=mentisdb_global_token mentisdb backup
Without it the flush is rejected, so backup prints a "could not flush daemon" warning and
captures the files as they are on disk.
Permissions and the operator key. A backup archive holds plaintext thoughts (including
the private segments of private chains) and, with --include-tls, the TLS private key, so
mentisdb backup creates the .mentis file owner-only (0600) with every entry recorded as
0600 (Unix; elsewhere the parent directory's ACL applies). Backups intentionally do not
contain operator/operator.key, the key that governs private chains, so one stolen archive
cannot also change who may read or write them. Back that file up separately, owner-only and
apart from the archive; without it a restored instance cannot change the access policy of its
private chains. backup and restore print this reminder.
Restore a backup
The daemon must be stopped before restoring. If mentisdb is detected running, the restore aborts with a message to stop the daemon first. Any HTTP answer from the flush probe, including 401 from a token-protected daemon, counts as running.
# Idempotent restore (preserves existing files)
mentisdb restore /backups/mentisdb-2026-04-14.mentis
# Restore to a specific directory
mentisdb restore /backups/mentisdb-2026-04-14.mentis --dir ~/.cloudllm/mentisdb
# Allow same-path chain files to be replaced when a safe suffix merge is not possible
mentisdb restore /backups/mentisdb-2026-04-14.mentis --overwrite
# Skip interactive confirmation prompts while keeping the default preserve/merge behavior
mentisdb restore /backups/mentisdb-2026-04-14.mentis --yes
Restore is idempotent by default. When the target directory is empty,
MentisDB imports the full instance, including registry, chains, skills,
webhooks, and optional TLS files. When the target already contains a MentisDB
instance, restore preserves the local mentisdb-registry.json and treats the
backup registry as a hint: new chains are appended to the local registry with
local storage paths, compatible same-key chains append only the verified missing
suffix, older backups are ignored, and same-name chains with different genesis
are imported under a non-conflicting -imported chain key. Existing global files
such as skills and webhooks are preserved unless they are absent locally.
--overwrite no longer means "replace the whole instance." It only allows
same-path chain files to be replaced when the chain cannot be safely merged and
the operator explicitly requested overwrite. The local registry is still merged
and preserved.
Archive format
A backup is a .mentis ZIP archive containing:
mentisdb.manifest.json— SHA-256 checksums and metadata*.tcbin— binary chain storage*.agents.json— per-chain agent registries*.entity-types.json— per-chain entity type definitions*.vectors.*.json— vector search sidecarsmentisdb-registry.json— global chain registrymentisdb-skills.bin— skill registry (if present)mentisdb-webhooks.json— webhook registrations (if present)tls/— TLS certificates and keys (opt-in via--include-tls)
Every file is verified by SHA-256 before restore writes anything to disk. A corrupted archive aborts with an error and leaves the target directory untouched.
Restore safety limits (0.10.9):
- archives that declare any entry larger than 64 GiB, or more than 256 GiB in total, are rejected before extraction
- the manifest itself may be at most 8 MiB and list at most 100,000 files
- every size the manifest declares must equal the entry's uncompressed size in the ZIP, otherwise the archive is rejected
- on Unix, restore checks free disk space on the target filesystem against the manifest's total size before extracting anything
- restore refuses to write through a symlink anywhere under the target directory
- files are staged in a
.mentisdb-restore-<uuid>directory created beside the target (same filesystem) and moved into place from there
REST flush endpoint
The flush operation is also available as a standalone REST endpoint:
POST http://127.0.0.1:9472/v1/admin/flush
Returns {"status": "flushed"} on success. Iterates all open chains and calls flush() on each adapter, blocking until all writes are durable (flush always fsyncs, regardless of MENTISDB_FSYNC). When bearer-token access is enabled this endpoint requires a global token.
MCP Tool Catalog
The daemon currently exposes 45 MCP tools:
mentisdb_bootstrapCreate a chain if needed and write one bootstrap checkpoint when it is empty.mentisdb_appendAppend a durable semantic thought with optional tags, concepts, refs, scope, and signature metadata.mentisdb_append_retrospectiveAppend a retrospective memory intended to prevent future agents from repeating a hard failure.mentisdb_searchSearch thoughts by semantic filters, identity filters, time bounds, and scoring thresholds.mentisdb_lexical_searchReturn flat ranked lexical matches with explainable term and field provenance.mentisdb_ranked_searchReturn flat ranked lexical, graph-aware, or heuristic results with additive score breakdowns. Supportsas_offor point-in-time queries andscopefor memory scope filtering. Passcompact: truefor smaller hits (see Compact search results).mentisdb_context_bundlesReturn seed-anchored grouped support context beneath the best lexical seeds.mentisdb_summary_candidatesReturn deterministic summary source windows. It only selects candidates; it does not generate or append summaries.mentisdb_list_chainsList known chains with version, storage adapter, counts, and storage location.mentisdb_migration_statusReport the background storage-format migration state of every chain that is, was, or failed to be migrated (phase, percent, attempts, error).mentisdb_merge_chainsMerge all thoughts from a source chain into a target chain, then permanently delete the source.mentisdb_branch_fromCreate a new chain that diverges from a thought on an existing chain. The branch receives a genesis thought with a BranchesFrom relation pointing back to the fork point. Searches on the branch chain transparently include ancestor chain results.mentisdb_list_agentsList the distinct agent identities participating in one chain.mentisdb_get_agentReturn one full agent registry record, including status, aliases, description, keys, and per-chain activity metadata.mentisdb_list_agent_registryReturn the full per-chain agent registry.mentisdb_upsert_agentCreate or update a registry record before or after an agent writes thoughts.mentisdb_set_agent_descriptionSet or clear the description stored for one registered agent.mentisdb_add_agent_aliasAdd a historical or alternate alias to a registered agent.mentisdb_get_access_policyReturn a chain's access policy as the caller may see it: mode, sequence, key-set commitment and segment boundaries for everyone; the allowed keys and record hashes for a reader who proved an authorized key.mentisdb_verify_signaturesRe-verify the signed thoughts and policy records the caller may see and report failures.
Registering or revoking agent keys, disabling agents and changing a chain's access policy are operator-only (dashboard behind its PIN, or the local mentisdb command line): they are not MCP tools and the matching REST routes answer 403. See Public and private chains.
mentisdb_standing_contextRender durable, age-independent memory (preferences, constraints, decisions, goals, lessons, user traits, newest handoff and checkpoint) into a prompt block; load it at session start before recent context.mentisdb_recent_contextRender recent thoughts into a prompt snippet for session resumption.mentisdb_memory_markdownExport aMEMORY.md-style Markdown view of the full chain or a filtered subset.mentisdb_import_memory_markdownImport aMEMORY.md-formatted Markdown document into a target chain.mentisdb_get_thoughtReturn one stored thought by stable id, chain index, or content hash.mentisdb_get_genesis_thoughtReturn the first thought ever recorded in the chain, if any.mentisdb_traverse_thoughtsTraverse the chain forward or backward in append order from a chosen anchor, in chunks, with optional filters.mentisdb_skill_mdReturn the official embeddedMENTISDB_SKILL.mdMarkdown file.mentisdb_list_skillsList versioned skill summaries from the skill registry.mentisdb_skill_manifestReturn the versioned skill-registry manifest, including searchable fields and supported formats.mentisdb_upload_skillUpload a new immutable skill version from Markdown or JSON.mentisdb_search_skillSearch skills by indexed metadata such as ids, names, tags, triggers, uploader identity, status, format, schema version, and time window.mentisdb_read_skillRead one stored skill as Markdown or JSON. Responses include trust warnings for untrusted or malicious skill content.mentisdb_skill_versionsList immutable uploaded versions for one skill.mentisdb_deprecate_skillMark a skill as deprecated while preserving all prior versions.mentisdb_revoke_skillMark a skill as revoked while preserving audit history.mentisdb_delete_skillPermanently remove a skill and all of its versions. After delete the same skill id can be uploaded again.mentisdb_headReturn head metadata, the latest thought at the current chain tip, and integrity state.mentisdb_register_webhookRegister a webhook to receive HTTP POST notifications when thoughts are appended. Delivery is fire-and-forget with up to 3 attempts per event (5 s timeout, exponential backoff from 1 s). See the target restrictions below.mentisdb_list_webhooksList all registered webhooks. Requires a global token when bearer-token access is enabled.mentisdb_delete_webhookRemove a webhook registration by its UUID. Requires a global token when bearer-token access is enabled.mentisdb_federated_searchRun one ranked-search query across multiple chains simultaneously and return one merged, deduplicated, re-scored result list. Each hit carries thechain_keyit came from, so multi-agent hubs and cross-organizational memory aggregations can share a single query surface. Per-chain queries may override limits, filters, and RRF settings. Acceptscompact: truelikementisdb_ranked_search.mentisdb_extract_memoriesRun the opt-in LLM-extraction pipeline: ingest raw text (paste, transcript, document), call an OpenAI-compatible model, validate the strict JSON schema of candidate thoughts, and return them for human review before append. Nothing is written to the chain until the caller confirms.mentisdb_list_entity_typesList the per-chain entity-type registry (labels likeincident,customer,deploy) including descriptions and usage counts.mentisdb_upsert_entity_typeCreate or update one entity type (label + optional description) in the per-chain registry. Entity-type labels can be attached to any thought via theentity_typefield and used as a filter on ranked search.
Webhook targets (0.10.9):
- only
httpandhttpsURLs are accepted, and redirects are never followed - by default,
localhost, loopback, private (RFC 1918), link-local, CGNAT (100.64.0.0/10), documentation/TEST-NET, benchmarking, multicast, broadcast, reserved and unspecified addresses are rejected, as are IPv6 ULA/link-local/documentation addresses and IPv6 forms that embed a blocked IPv4 address (IPv4-mapped, IPv4-translated::ffff:0:0:0/96, NAT64, 6to4); the local-use NAT64 prefix64:ff9b:1::/48and Teredo2001::/32are rejected outright - the same check runs on every address a hostname resolves to at delivery time, so DNS names pointing at internal ranges (or DNS rebinding) cannot reach them
- webhooks persisted in
mentisdb-webhooks.jsonthat point at a blocked target are loaded inactive with a warning - a circuit breaker pauses a webhook for 5 minutes after 5 consecutive failed deliveries; a success resets it
- logs show only
scheme://host[:port]of the target, never paths, query strings or credentials
Allowing private webhook targets with MENTISDB_WEBHOOK_ALLOWED_CIDRS:
Self-hosted deployments whose webhook consumers live on a private network (a Tailscale tailnet, a WireGuard subnet, a LAN host) can open just those ranges:
# Tailscale tailnet (IPv4 CGNAT range + Tailscale's IPv6 ULA prefix)
MENTISDB_WEBHOOK_ALLOWED_CIDRS=100.64.0.0/10,fd7a:115c:a1e0::/48
# a WireGuard subnet
MENTISDB_WEBHOOK_ALLOWED_CIDRS=10.8.0.0/24
# a single host (a bare address means /32 or /128)
MENTISDB_WEBHOOK_ALLOWED_CIDRS=192.168.1.50
- entries are separated by commas and/or whitespace; each is
addr/prefix(IPv4 or IPv6,[...]brackets allowed around IPv6) or a bare address; host bits are normalized (10.8.0.7/24becomes10.8.0.0/24) - an address inside a listed range is allowed even if it falls in a blocked range; every
other internal range stays blocked. IPv4-mapped IPv6 addresses (
::ffff:a.b.c.d) match IPv4 ranges localhosthost names are still rejected even if loopback is listed; use the IP literal (http://127.0.0.1:8080/hook)- the list applies at registration, when persisted registrations are reloaded, and at delivery time (to every resolved DNS address and to literal IPs). Removing the variable, or narrowing it so a registration is no longer covered, loads that registration inactive again on the next start
- any unparsable entry, or any entry broader than
/8(IPv4 or IPv6;fd00::/8still fits), makes the daemon refuse to start. The active ranges are logged as a warning at startup, plus a dedicated warning for any listed range that covers loopback (127.0.0.1,::1) or the cloud metadata address169.254.169.254 - list only the narrowest ranges your consumers live in (your tailnet, one
/24, one host). Never list cloud metadata (169.254.169.254,169.254.0.0/16) or broad ranges like10.0.0.0/8: any token allowed to register webhooks (global tokens, and chain-scoped tokens with an in-scopechain_key_filter) can make the daemon send requests into the listed ranges
The detailed request and response shapes for the MCP surface live in
MENTISDB_MCP.md. The REST equivalents live in
MENTISDB_REST.md.
Thought Lookup And Traversal
MentisDB distinguishes three different read patterns:
headmeans the newest thought at the current tip of the append-only chaingenesismeans the very first thought in the chain- traversal means sequential browsing by append order, forward or backward, in chunks
That traversal model is deliberately different from graph/context traversal through refs and typed relations. Graph traversal answers "what is connected to this thought?" Sequential traversal answers "what came before or after this thought in the ledger?"
Lookup and traversal support:
- direct thought lookup by
id,hash, orindex - logical
genesisandheadanchors forwardandbackwardtraversal directionsinclude_anchorcontrol for inclusive vs exclusive paging- chunked pagination, including
chunk_size = 1for next/previous behavior - optional filters reused from thought search, such as agent identity, thought type, role, tags, concepts, text, importance, confidence, and time windows
- numeric time windows expressed as
start + deltawithsecondsormillisecondsunits for MCP/REST callers
Skill Registry
MentisDB includes a versioned skill registry stored alongside chain data in a binary file. Skills are ingested through adapters:
- Markdown ->
SkillDocument - JSON ->
SkillDocument SkillDocument-> MarkdownSkillDocument-> JSON
Each uploaded skill version records:
- registry file version
- skill schema version
- upload timestamp
- responsible
agent_id - optional agent display name and owner from the MentisDB agent registry
- source format
- integrity hash
Uploaders must already exist in the agent registry for the referenced chain. Reusing an existing skill_id creates a new immutable version; it does not overwrite history. The dashboard can create those new versions from either the Skills table or a skill detail page while preserving the original uploader identity and source format.
read_skill responses include explicit safety warnings because SKILL.md content can be malicious. Treat every skill as advisory until provenance, trust, and requested capabilities are validated.
Skill Lifecycle
The registry is append-only for versions. Status changes do not rewrite history:
| Action | Keeps versions? | Same skill_id reusable? |
Surfaces |
|---|---|---|---|
| Deprecate | Yes (audit + still readable) | No — upload creates another version | REST POST /v1/skills/deprecate, MCP mentisdb_deprecate_skill, dashboard Deprecate |
| Revoke | Yes (audit row; agents should refuse to execute) | No | REST POST /v1/skills/revoke, MCP mentisdb_revoke_skill, dashboard Revoke |
| Delete | No — every version is removed from mentisdb-skills.bin |
Yes — the id can be uploaded again as Active |
REST POST /v1/skills/delete, MCP mentisdb_delete_skill, dashboard DELETE /dashboard/api/skills/{id} |
Revoke when you need a forensic trail. Delete when the skill should vanish (wrong upload, junk, or you want the slug back). Crate, REST, and MCP delete any existing skill_id regardless of status. The dashboard UI follows the bearer-token pattern: Revoke on active/deprecated rows, then Delete / Delete Permanently on revoked list rows and the skill-detail pane (type the skill id to confirm).
SkillRegistry::counts() and the Skills page summary bar report total / active / revoked / deprecated. Permanently deleted skills are absent and are not counted.
Skill Versioning
Each upload to an existing skill_id creates a new immutable version rather than overwriting history:
- The first upload stores the full content (
SkillVersionContent::Full). - Subsequent uploads store a unified diff patch against the previous version
(
SkillVersionContent::Delta), keeping storage efficient for iteratively improved skills. - Each version receives a monotone
version_number(0-based, assigned in append order). - Pass a
version_idtoread_skill/mentisdb_read_skillto retrieve any historical version. The system reconstructs it by replaying patches forward from version 0. skill_versions/mentisdb_skill_versionslists all versions with their ids, numbers, and timestamps.
Signed Skill Uploads
Agents that have registered Ed25519 public keys in the agent registry must sign their uploads.
Required fields when the uploading agent has active keys:
signing_key_id— thekey_idthe operator registered for the agent (mentisdb agent key add)skill_signature— 64-byte Ed25519 signature over the raw skill content bytes
Agents without registered public keys may upload without signatures.
Upload flow for signing agents:
- Ask the operator to register your public key (the operator can make the pair
with
mentisdb agent key generate AGENT --key-id KEY_ID --chain CHAINand hand you only the key file, over a channel you trust):
(RESTmentisdb agent key add AGENT --key-id KEY_ID --public-key-hex <64 hex> --chain CHAIN --pin <dashboard pin>POST /v1/agents/keysand the MCP tool answer 403: key registration is operator-only.) - Sign the raw content bytes with the corresponding private key (Ed25519).
- Include
signing_key_idandskill_signaturein the upload request:
or via MCP:POST /v1/skills/upload { agent_id, skill_id, content, signing_key_id, skill_signature }mentisdb_upload_skillwith the same fields.
Setup Scenarios
Claude Desktop
- Recommended (stdio mode) — just run
mentisdb setup claude-desktopand it will write the stdio config. No daemon needed, no Node.js, no mcp-remote. The stdio process auto-detects and proxies to a running daemon, or launches one in the background if none is found. - Alternative (HTTP via mcp-remote) — requires Node.js >= 20 and
npm install -g mcp-remote. Runmentisdbas a daemon first, then configure Claude Desktop to usemcp-remoteas a bridge to the HTTPS endpoint.
Claude Code
- Start the server:
mentisdb run - Add the MCP server:
claude mcp add --transport http mentisdb http://127.0.0.1:9471 - Or run
mentisdb setup claude-codeto auto-configure
OpenCode
- Start the server:
mentisdb run - Add the MCP server:
opencode mcp add mentisdb http://127.0.0.1:9471
Codex
codex mcp add mentisdb --url http://127.0.0.1:9471
Qwen Code
qwen mcp add --transport http mentisdb http://127.0.0.1:9471
Using With MCP Clients
mentisdb exposes both:
- a standard streamable HTTP MCP endpoint at
POST / - a Server-Sent Events (SSE) endpoint at
GET /returningtext/event-stream: onetool_calledevent per tool call (tool name, chain key, outcome, duration) plus metadata-only events for each JSON-RPC method (method, client address, outcome). Tool arguments, results and error text are never broadcast: they can be private text. The stream runs the sameHost, bearer-token andOriginchecks asPOST /; with bearer enforcement on, only a global token can subscribe (the stream names every chain's activity, so a chain-scoped token is refused with401) - the legacy CloudLLM-compatible MCP endpoints at
POST /tools/listandPOST /tools/execute
POST /tools/execute takes tool + parameters; JSON-RPC tools/call takes name +
arguments. Authorization checks exactly the fields that transport executes, and a payload
that mixes both shapes is rejected with 400.
That means you can:
- use native MCP clients such as Codex and Claude Code against
http://127.0.0.1:9471 - keep using direct HTTP calls or
cloudllm's MCP compatibility layer when needed
Bearer Token Access For Remote MCP Servers
If a MentisDB daemon is reachable beyond your own machine, enable bearer-token access before adding it to remote MCP clients:
MENTISDB_BIND_HOST=0.0.0.0 \
MENTISDB_BEARER_TOKEN_ACCESS=true \
MENTISDB_DASHBOARD_PIN=change-me \
mentisdb
Tokens are managed by alias. The raw token is printed once at creation time; MentisDB stores only a SHA-256 hash plus metadata such as scope, creation time, revocation time, and last successful use.
Create a global admin token:
mentisdb bearertoken create --global admin-laptop
Create a token limited to one or more chains:
mentisdb bearertoken create --chain alice alice-agent
mentisdb bearertoken create bob-agent --chain bob
mentisdb bearertoken create team-agent --chain alice --chain shared
List and revoke tokens:
mentisdb bearertoken list
mentisdb bearertoken list --chain alice
mentisdb bearertoken list --chain alice --chain shared
mentisdb bearertoken remove alice-agent
Global tokens can call every MCP tool and access every chain. Chain-scoped tokens
can call tools for any chain in their configured set, including requests that
omit chain_key when the daemon default chain is in their scope. REST and MCP
share one authorization table, so the same rules apply on both surfaces.
Operations that expose or change server-wide state require a global token:
- listing chains (
GET /v1/chains,mentisdb_list_chains) - migration status and control (
GET /v1/migrations,POST /v1/migrations/retry,POST /v1/migrations/skip,mentisdb_migration_status) - listing and deleting webhooks (
GET /v1/webhooks,DELETE /v1/webhooks/{id},mentisdb_list_webhooks,mentisdb_delete_webhook) - skill registry mutations: upload, deprecate, revoke, delete (
/v1/skills/{upload,deprecate,revoke,delete}and the matching MCP tools) POST /v1/admin/flush(setMENTISDB_BEARER_TOKENto a global token somentisdb backupcan flush; see Backup and Restore)
Registering a webhook with a chain-scoped token is allowed only when the request sets
chain_key_filter to a chain inside the token's scope. POST /v1/agents (and the other
agent-registry routes) are checked against the requested chain_key; a single-chain token
that omits it gets its own chain. Out-of-scope calls are rejected with 401.
A token's last_used_at is updated in memory on every request but written to disk at most
once every 60 seconds, so mentisdb bearertoken list may lag by up to a minute.
Bearer Token MCP Client Config Examples
For every remote MCP harness, the important part is the same:
Authorization: Bearer mentisdb_replace_me
Use a global token for administrators. Use a chain-scoped or multi-chain token for agents that should only see specific memory chains.
Codex (~/.codex/config.toml):
[mcp_servers.mentisdb]
url = "https://my.mentisdb.com:9473"
http_headers = { Authorization = "Bearer mentisdb_replace_me" }
Claude Code:
claude mcp add-json mentisdb \
'{"type":"http","url":"https://my.mentisdb.com:9473","headers":{"Authorization":"Bearer mentisdb_replace_me"}}' \
--scope user
Qwen Code:
qwen mcp add --scope user --transport http mentisdb https://my.mentisdb.com:9473 \
--header "Authorization: Bearer mentisdb_replace_me"
Or edit ~/.qwen/settings.json:
{
"mcpServers": {
"mentisdb": {
"httpUrl": "https://my.mentisdb.com:9473",
"headers": {
"Authorization": "Bearer mentisdb_replace_me"
}
}
}
}
GitHub Copilot CLI (~/.copilot/mcp-config.json):
{
"mcpServers": {
"mentisdb": {
"type": "http",
"url": "https://my.mentisdb.com:9473",
"headers": {
"Authorization": "Bearer mentisdb_replace_me"
},
"tools": ["*"]
}
}
}
VS Code + Copilot (.vscode/mcp.json or your user mcp.json):
{
"servers": {
"mentisdb": {
"type": "http",
"url": "https://my.mentisdb.com:9473",
"headers": {
"Authorization": "Bearer mentisdb_replace_me"
}
}
}
}
OpenCode (~/.config/opencode/opencode.json):
{
"mcp": {
"mentisdb": {
"type": "remote",
"url": "https://my.mentisdb.com:9473",
"enabled": true,
"oauth": false,
"headers": {
"Authorization": "Bearer mentisdb_replace_me"
}
}
}
}
Hermes Agent (~/.hermes/config.yaml):
mcp_servers:
mentisdb:
url: "https://my.mentisdb.com:9473"
headers:
Authorization: "Bearer mentisdb_replace_me"
You can also manage tokens in the dashboard Settings screen: enter an alias, choose Global or Chains, select one or more chains for scoped tokens, create the token, and revoke active tokens from the table. The bearer-token table is intentionally metadata-only; future versions can extend those records with per-token usage counters without changing how clients authenticate.
Codex
Codex CLI expects a streamable HTTP MCP server when you use --url:
codex mcp add mentisdb --url http://127.0.0.1:9471
Useful follow-up commands:
codex mcp list
codex mcp get mentisdb
This connects Codex to the daemon's standard MCP root endpoint.
Qwen Code
Qwen Code uses the same HTTP MCP transport model:
qwen mcp add --transport http mentisdb http://127.0.0.1:9471
Useful follow-up commands:
qwen mcp list
For user-scoped configuration:
qwen mcp add --scope user --transport http mentisdb http://127.0.0.1:9471
Claude for Desktop
Claude for Desktop supports two connection modes: stdio (recommended) and HTTP via mcp-remote.
Option 1: Stdio mode (recommended)
Claude Desktop spawns mentisdb --mode stdio as a subprocess. The stdio
process automatically detects if a daemon is already running — if so, it acts
as a lightweight proxy to the live daemon; if not, it launches one in the
background. This means all Claude Desktop sessions share the same live chain
cache with zero configuration.
{
"mcpServers": {
"mentisdb": {
"command": "mentisdb",
"args": ["--mode", "stdio"]
}
}
}
This is the simplest setup — no Node.js, no mcp-remote, no TLS config. Just
point Claude Desktop at the mentisdb binary.
Option 2: HTTP via mcp-remote
If you prefer the HTTP transport (e.g. for a remote daemon), use the
mcp-remote bridge. This requires Node.js >= 20 and the
mcp-remote npm package.
The recommended setup path is automatic:
mentisdb setup claude-desktop
This command:
- checks for Node.js >= 20 and
mcp-remoteon PATH - installs
mcp-remotevianpmif missing - writes
claude_desktop_config.jsonwith the correct absolute paths tonodeandmcp-remoteso the desktop app always uses the right Node version - sets
NODE_TLS_REJECT_UNAUTHORIZED=0for self-signed certificate support
To set it up manually instead:
Step 1 — Install prerequisites (Node.js >= 20 required):
npm install -g mcp-remote
Step 2 — Edit the config file (location by OS):
| OS | Path |
|---|---|
| macOS | ~/Library/Application Support/Claude/claude_desktop_config.json |
| Windows | %APPDATA%\Claude\claude_desktop_config.json |
| Linux | ~/.config/Claude/claude_desktop_config.json |
The config should use the node binary as the command and pass the
mcp-remote script path as the first argument. This avoids the shebang
resolution issue where mcp-remote's #!/usr/bin/env node may pick an older
Node.js version on systems with multiple Node installs (e.g. nvm).
macOS (with nvm):
{
"mcpServers": {
"mentisdb": {
"command": "/Users/you/.nvm/versions/node/v22.18.0/bin/node",
"args": ["/Users/you/.nvm/versions/node/v22.18.0/bin/mcp-remote", "https://my.mentisdb.com:9473"],
"env": { "NODE_TLS_REJECT_UNAUTHORIZED": "0" }
}
}
}
macOS (with Homebrew Node):
{
"mcpServers": {
"mentisdb": {
"command": "/opt/homebrew/bin/node",
"args": ["/opt/homebrew/bin/mcp-remote", "https://my.mentisdb.com:9473"],
"env": { "NODE_TLS_REJECT_UNAUTHORIZED": "0" }
}
}
}
Windows:
{
"mcpServers": {
"mentisdb": {
"command": "node",
"args": ["mcp-remote", "https://my.mentisdb.com:9473"],
"env": { "NODE_TLS_REJECT_UNAUTHORIZED": "0" }
}
}
}
Use which mcp-remote and which node to confirm the binary paths on your
machine. Both must point to the same Node.js installation (>= 20).
Linux:
{
"mcpServers": {
"mentisdb": {
"command": "/usr/local/bin/node",
"args": ["/usr/local/bin/mcp-remote", "https://my.mentisdb.com:9473"],
"env": { "NODE_TLS_REJECT_UNAUTHORIZED": "0" }
}
}
}
Why
NODE_TLS_REJECT_UNAUTHORIZED: "0"?
MentisDB ships with a self-signed TLS certificate. Node.js rejects self-signed certs by default, which causesmcp-remoteto disconnect immediately after the MCPinitializehandshake. This env var disables that check for themcp-remoteprocess only. As an alternative, trust the certificate at the OS level (sudo security add-trusted-certon macOS) and remove theenvblock.Why use
nodeas the command instead ofmcp-remotedirectly?
Themcp-remoteshell script uses#!/usr/bin/env nodeas its shebang. On systems with multiple Node.js versions (e.g. managed by nvm), the shebang may resolve to an older Node that doesn't supportmcp-remote's dependencies (which require Node >= 20). Using the explicitnodepath as the command bypasses the shebang entirely and guarantees the correct Node version is used.
Restart Claude for Desktop after saving the config file.
Stdio Mode — How It Works
mentisdb --mode stdio reads JSON-RPC 2.0 from stdin and writes responses to
stdout. It is designed for MCP clients that spawn subprocesses (Claude Desktop,
Cursor, etc.).
Smart daemon detection: When the stdio process starts, it checks if a
daemon is already running on the configured MCP port (127.0.0.1:9471 by
default) via the health endpoint.
- Daemon running → the stdio process acts as a lightweight proxy, forwarding
tools/listandtools/callrequests to the daemon's HTTP MCP endpoints.initialize,ping, andresources/readare handled locally. All clients share the same live in-memory chain cache. - No daemon → the stdio process launches the daemon in the background
(
nohupon Unix,start /Bon Windows) with--mode http --headless, waits for it to become responsive, then proxies. The daemon outlives the stdio process without starting the TUI on a null stdin. - Daemon launch fails → falls back to local mode, creating its own
MentisDbServiceinstance (state shared only via disk files).
This means you never need to manually start the daemon — Claude Desktop, Cursor,
or any MCP client can just spawn mentisdb --mode stdio and everything works.
The daemon address is configurable via MENTISDB_BIND_HOST and
MENTISDB_MCP_PORT environment variables, so the stdio process will detect and
proxy to a daemon on a non-standard port.
Claude Code
Claude Code supports MCP servers through its claude mcp commands and
project/user MCP config. For a remote HTTP MCP server, the configuration shape
is transport-based:
claude mcp add --transport http mentisdb http://127.0.0.1:9471
Useful follow-up commands:
claude mcp list
claude mcp get mentisdb
mentisdb setup claude-code merges the MCP server entry into
~/.claude.json (or %USERPROFILE%\.claude.json on Windows), preserving your
existing Claude Code settings. The older ~/.claude/mcp/mentisdb.json path is
treated as a legacy companion file, not the canonical config target. The
MentisDB HTTP MCP block it writes looks like this:
{
"mcpServers": {
"mentisdb": {
"type": "http",
"url": "http://127.0.0.1:9471"
}
}
}
Important:
/mcpinside Claude Code is mainly for managing or authenticating MCP servers that are already configured- the server itself must already be running at the configured URL
GitHub Copilot CLI
GitHub Copilot CLI can also connect to mentisdb as a remote HTTP MCP
server.
From interactive mode:
- Run
/mcp add - Set
Server Nametomentisdb - Set
Server TypetoHTTP - Set
URLtohttp://127.0.0.1:9471 - Leave headers empty unless you add auth later
- Save the config
You can also configure it manually in ~/.copilot/mcp-config.json (or
$XDG_CONFIG_HOME/copilot/mcp-config.json when XDG_CONFIG_HOME is set):
{
"mcpServers": {
"mentisdb": {
"type": "http",
"url": "http://127.0.0.1:9471",
"headers": {},
"tools": ["*"]
}
}
}
Python Client
pymentisdb is the official Python client for MentisDB.
Install
pip install pymentisdb # 0.10.0 or later; needs only requests
pip install 'pymentisdb[signing]' # ReadSigner, for reading private chains
pip install 'pymentisdb[langchain]' # MentisDbMemory (LangChain BaseMemory)
import pymentisdb works without LangChain; MentisDbMemory needs the
langchain extra and says so when it is missing. Use 0.10.0 or later: the 0.9.0
wheel on PyPI contained no code.
Reading private chains
from pymentisdb import MentisDbClient, ReadSigner # pip install pymentisdb[signing]
client = MentisDbClient(read_signer=ReadSigner.from_file("builder.key", "builder", "builder-1"))
Every request is signed locally (the key never leaves the process); see docs/CHAIN_ACCESS.md. Without a signer the client reads public segments only.
Basic Example
from pymentisdb import MentisDbClient, ThoughtType
client = MentisDbClient() # defaults to http://127.0.0.1:9472
# Append a thought
thought = client.append_thought(
thought_type=ThoughtType.INSIGHT,
content="Rate limiting is the real bottleneck."
)
# Ranked search
results = client.ranked_search(text="performance optimization")
for hit in results.results:
print(f"[{hit.score.total:.3f}] {hit.thought.content}")
# Context bundles
bundles = client.context_bundles(text="cache invalidation", limit=5)
LangChain Integration
from pymentisdb import MentisDbMemory
memory = MentisDbMemory(chain_key="my-project", agent_id="assistant")
memory.save_context({"input": "Use tabs, not spaces."}, {"output": "Noted."})
print(memory.load_memory_variables({})["chat_history"])
MentisDbMemory is a LangChain BaseMemory: it works with langchain-core before 1.0
and, from 1.0 on, with langchain-classic (installed by the langchain extra).
See the full pymentisdb guide for complete API reference.
LLM-Extracted Memories
MentisDB can convert raw agent text, conversation logs, or transcripts into structured
ThoughtInput records using GPT-4o (or any OpenAI-compatible endpoint). Review the
extracted records and append them to your chain.
This feature is enabled by default. Configure with environment variables:
export OPENAI_API_KEY="sk-..." # required
export LLM_BASE_URL="https://api.openai.com/v1" # defaults to OpenAI
export LLM_MODEL="gpt-4o" # defaults to gpt-4o
use mentisdb::{LlmExtractionConfig, extract_memories_from_text};
let config = LlmExtractionConfig::from_env()?;
let result = extract_memories_from_text(raw_text, &config, None).await?;
// Review before appending
for thought in &result.thoughts {
println!("{:?}", thought);
}
The extraction uses openai-rust2 with connection pooling, 3× retry on 429/5xx,
60s timeout, and strict JSON schema validation on the returned payload. LLM output
is untrusted — always review and optionally sign extracted thoughts before
appending.
See docs/llm-extracted-memories-design.md for the full design.
Retrospective Memory
MentisDB supports a dedicated retrospective workflow for lessons learned.
- Use
mentisdb_appendfor ordinary durable facts, constraints, decisions, plans, and summaries. - Use
mentisdb_append_retrospectiveafter a repeated failure, a long snag, or a non-obvious fix when future agents should avoid repeating the same struggle.
The retrospective helper:
- defaults
thought_typetoLessonLearned - always stores the thought with
role = Retrospective - still supports tags, concepts, confidence, importance, and
refsto earlier thoughts such as the original mistake or correction
Thought Types And Roles
MentisDB currently defines 31 semantic ThoughtType values and 8 operational
ThoughtRole values.
Thought types:
PreferenceUpdate,UserTrait,RelationshipUpdateFinding,Insight,FactLearned,PatternDetected,Hypothesis,SurpriseMistake,Correction,LessonLearned,AssumptionInvalidated,ReframeConstraint,Plan,Subgoal,Goal,Decision,StrategyShiftWonder,Question,Idea,ExperimentActionTaken,TaskCompleteCheckpoint,StateSnapshot,Handoff,Summary,LLMExtracted
Thought roles:
MemoryWorkingMemorySummaryCompressionCheckpointHandoffAuditRetrospective
Use ThoughtType to say what the memory means semantically, and ThoughtRole
to say how the system should treat it operationally. The crate rustdoc is the
authoritative source for per-variant semantics, and the Agent Guide on the docs
site contains a human-oriented explanation of when to use each one.
String forms round-trip through one canonical mapping: ThoughtType::ALL lists
every variant, as_str() / Display return the canonical PascalCase name, and
FromStr accepts any case with separators ignored ("fact-learned",
"factlearned", and "FactLearned" all parse to FactLearned). Unknown input
returns ParseThoughtTypeError, whose message lists the valid types; the REST
and MCP thought_type fields use the same parser.
Memory Scopes
MentisDB defines a MemoryScope enum that controls how far a thought should propagate:
User(default) — visible to all agents and sessions sharing the chainSession— visible only within the current agent sessionAgent— visible only to the agent that created it
Scopes are stored as tags on the thought:
scope:userscope:sessionscope:agent
Crate API:
ThoughtInput::with_scope(MemoryScope)sets the scope on appendRankedSearchQuery::with_scope(MemoryScope)filters search results by scope
REST API:
POST /v1/thoughtsaccepts an optionalscopefield ("user","session", or"agent")POST /v1/ranked-searchandPOST /v1/context-bundlesaccept an optionalscopefield
Shared-Chain Multi-Agent Use
Multiple agents can write to the same chain_key.
Each stored thought carries a stable:
agent_id
Agent profile metadata now lives in the per-chain agent registry instead of being duplicated into every thought record. Registry records can store:
display_nameagent_ownerdescriptionaliasesstatuspublic_keys- per-chain activity counters such as
thought_count,first_seen_index, andlast_seen_index
That allows a shared chain to represent memory from:
- multiple agents in one workflow
- multiple named roles in one orchestration system
- multiple tenants or owners writing to the same chain namespace
Queries can filter by:
agent_idagent_nameagent_owner
Administrative tools can also inspect and mutate the agent registry directly, so agents can be documented, disabled, aliased, or provisioned with public keys before they start writing thoughts.
Related Docs
At the repository root:
MENTISDB_MCP.mdMENTISDB_REST.mdmentisdb/WHITEPAPER.mdmentisdb/changelog.txt
Explorer des projets similaires
Chargement…