Skip to main content
Glama
mnemosis-mcp

mnemosis-mcp

by liyexiaoyi

Mnemosis

仿生设计的 AI Agent 长期记忆层:记住、检索、强化、遗忘、整合,并保留不确定性。

Mnemosis is a human-inspired memory layer for AI agents. It manages the life of a memory: episodic experiences and semantic facts, retrieval and reinforcement, forgetting and review, consolidation and explicit feedback. The agent chooses what to store and how to use the returned evidence.

The core runs locally with Python 3.10+ and SQLite, with no third-party runtime dependencies. Dense embeddings, NumPy acceleration, a Rust BM25 kernel and local-model evidence annotation are optional.

License: MIT CI Open in GitHub Codespaces

中文介绍 · Beginner guide / 零基础教程 · Storage design / 存储设计

What makes it biomimetic?

Mechanism

What it does

Boundary

Episodic + semantic memory

Keeps experiences and reusable facts in separate tracks.

Stored claims still depend on their sources.

Association + reinforcement

Uses cues and links to recall related memories and strengthen accessibility.

Familiarity is not factual correctness.

Forgetting + spaced review

Models changing accessibility and schedules review.

Decay is not a fact's expiry date.

Sleep consolidation

Replays, deduplicates, links and consolidates memories; tracks source contributions.

Distinct source records need not be independent or verified.

Explicit feedback + metacognition

Records caller judgments and reports gaps, uncertainty and conflicts.

A confidence value does not guarantee a true answer.

These are engineering mechanisms inspired by memory, not a biological brain simulation. Read-only recall and diagnostics let applications inspect memory without reinforcing it. See feedback and source boundaries.

Related MCP server: Cortex

Install

Install the default GitHub branch:

python -m pip install git+https://github.com/liyexiaoyi/Mnemosis.git

To run examples or work on the source:

git clone https://github.com/liyexiaoyi/Mnemosis.git
cd Mnemosis
python -m pip install -e .
python examples/demo.py

Quick start

from mnemosis import MemoryEngine
from mnemosis.types import MemoryKind, SourceRecord, SourceType

engine = MemoryEngine("memory.db", auto_warmup=False)
try:
    engine.remember(
        "Alice prefers green tea.",
        kind=MemoryKind.SEMANTIC,
        source=SourceRecord(origin=SourceType.USER),
        cues=["Alice", "tea", "preference"],
        importance=0.9,
    )

    # Inspect without changing persistent learning state.
    for result in engine.recall("Alice tea preference", top_k=3, read_only=True):
        print(result.item.content, result.score)

    print("knowledge gaps:", engine.check("Alice's favorite movie").gaps)
    engine.sleep()  # offline consolidation
finally:
    engine.close()

remember_turn splits and stores a conversation turn; remember_many imports batches. The caller decides what is worth retaining. Normal recall may reinforce memories; use read_only=True for evaluation or candidate inspection. A retrieval score measures ranking, not truth probability.

Connect an agent with MCP

After installation, add this configuration to an MCP-compatible client:

{
  "mcpServers": {
    "mnemosis": {
      "command": "mnemosis-mcp",
      "args": ["--db", "/absolute/path/to/memory.db"]
    }
  }
}

On Windows, put Python's Scripts directory on PATH or use the absolute path to mnemosis-mcp.exe. Use --expose core for everyday tools, --expose advanced for the default set, or --expose experimental to include experimental tools. See MCP setup.

mnemosis --db memory.db remember "Alice prefers green tea." --kind semantic
mnemosis --db memory.db recall "Alice tea"
mnemosis --db memory.db check "Alice's favorite movie"
mnemosis --db memory.db sleep
mnemosis-mcp --db memory.db --expose core

Streamable HTTP is also available with --transport http --host 127.0.0.1 --port 8000. For remote access, configure authentication and TLS at the deployment boundary. SQLite suits local, single-process use; serialize high-level calls when sharing an engine across concurrent agent loops.

Retrieval and mathematical models

The existing biomimetic recall remains the default. Additional strategies are opt-in, with separate mathematical responsibilities:

Component

Approach

Documentation

Lexical retrieval

BM25 uses term frequency, rarity and record length; optional bounded RRF fusion.

BM25

English word forms

Grouped inflection cues with bounded overlap and mean-rarity normalization.

Inflection cues

Candidate admission

Protects 64 lexical candidates and up to 36 eligible vector candidates, with lexical refill to 100.

Quota admission

Semantic reranking

Allocates the existing rerank budget to admitted vector candidates while retaining primary candidates where possible.

Mathematical responsibilities

Evidence composition

Combines relevance with weighted, saturated aspect coverage; optional refinement and required-role constraints.

Evidence selection, ranked evidence

Feedback calibration

Smoothed outcome estimates and population-weighted calibration statistics.

Calibration

Candidate coverage, rank scores, evidence utility and feedback estimates are different quantities. Improving one does not prove better final answers. Quota admission requires a matching vector index and embedder. Supplied evidence labels remain a caller responsibility.

For dense embeddings, run a local embedding service and configure it explicitly:

mnemosis-mcp --db memory.db --embedder ollama

Embedding caches and vector indexes are stored beside the database and can be rebuilt. Python orchestrates the memory lifecycle; SQL handles storage, NumPy can accelerate vector operations and Rust can accelerate BM25 scoring. See language boundaries, Rust setup and vector acceleration.

Experimental grounded evidence recall

MemoryEngine.recall_evidence connects read-only retrieval to local-model role annotations, unique exact source quotations and bounded mathematical evidence selection. It requires an explicitly configured annotator; the MCP tool also requires experimental exposure.

Reports distinguish feasible, infeasible, undetermined, annotation_failed and not_applicable. Missing support remains unknown. An exact quotation checks the source text, not semantic entailment or factual truth. Incorrect roles, reversed actions, incomplete quotes and timeouts remain known limitations. This path is not the default.

See the API, budgets and status semantics.

Validation and benchmarks

The 2026-10-11 local checkpoint passed 1,399 tests and 374 subtests with the available NumPy/Rust backends, plus 18 capability checks. A frozen 704-query replay previously preserved original recall rankings and storage state across 20 configurations. These are regression checks, not a market ranking.

Public-data retrieval subsets and authored mathematical cases exercise different stages. Candidate admission gains have not established a final Top-k accuracy gain. Recent support-prompt experiments regressed and were reverted. See validation status and limitations.

python -m pip install -e ".[dev]"
python -m pytest -q
python benchmarks/ci_regression.py

Optional native checks require the relevant backend to be installed and enabled; see Rust verification. Local timings depend on hardware, data, models and cache state.

The repository includes a LongMemEval comparison runner:

python benchmarks/fetch_longmemeval.py
python benchmarks/longmemeval_bench.py --data work/longmemeval_s_cleaned.json --questions 20

Comparison dependencies and model services must be configured separately. Sampled historical comparisons are not a claim of general superiority over other agent-memory projects.

Contributing and license

Contributions, reproducible benchmarks and failure cases are welcome. See the roadmap. Licensed under MIT.

Available Tools

98 tools
action_queueB

Order active intentions as an action queue: overdue first, then upcoming by deadline, with clashing intentions flagged (goal-directed priority, ACT-R; Anderson 1983).

Inputs: limit.

agent_learning_sessionB

Run one end-to-end learning session: score practice attempts, diff a second snapshot against the baseline and plan the next loop (testing effect + knowledge tracing).

Inputs: count, answers.

analogy_bridgeB

Find cross-topic memory pairs with shared structure for analogical transfer (structure-mapping; Gentner, 1983; Holyoak & Thagard, 1995).

Inputs: limit, min_structure.

association_reportA

Summarize the memory association network: total links, connected/isolated memories, average links and the most-connected memories (spreading activation).

Inputs: limit.

calibrate_decayA

Calibrate the forgetting rate from real retrieval history (median survival span -> decay rate).

Inputs: no named parameters.

checkD

Metacognitive check: confidence, contradictions, gaps, blocked.

Inputs: query (required), top_k.

cleanup_previewA

Preview which episodic traces the sleep prune pass would recycle (unimportant, never accessed, old) - without deleting anything.

Inputs: limit.

compare_memoriesB

Compare two memories: token overlap, shared cues and a verdict (duplicate / conflict / distinct) for source monitoring and schema integration (Johnson et al. 1993).

Inputs: id_a (required), id_b (required).

concept_coverA

Show how a multi-concept Chinese question is split into chunks, which memories cover each chunk and the final top-k (working-memory chunking; Miller, 1956).

Inputs: query (required), top_k.

conflict_adviceA

For each memory conflict, score both sides (evidence, confidence, recency, source trust) and recommend which to keep or ask the user to clarify.

Inputs: limit.

context_packB

Pack the best matching memories for several queries into one bounded context: deduplicated, score-ranked, character-budgeted (cognitive load, Sweller 1988).

Inputs: queries (required), top_k, max_chars.

coverage_reportC

Report review coverage per topic schema: memory count, reviewed count, coverage ratio, average retrievability/importance and status.

Inputs: limit.

curve_fitB

Personalize each memory's forgetting forecast from retrieval history and predict days until retrievability crosses a threshold (individual forgetting rates; Murre & Chessa, 2011).

Inputs: memory_id, threshold, horizon_days.

decision_reviewB

Review a finished plan against its results: success rate, score, verdict, patterns and distilled lessons (post-task metacognitive monitoring, Koriat & Goldsmith 1996).

Inputs: plan (required), results (required).

dedupe_memoriesA

Merge near-duplicate traces on demand; returns how many duplicates were merged.

Inputs: no named parameters.

dependency_mapB

Build a plan's dependency graph and critical path (hierarchical planning, Miller & Cohen 2001; critical-path method): levels, predecessors, parallel groups and the gating chain.

Inputs: plan (required).

effort_estimateA

Estimate per-step and total effort for a plan, including critical-path hours and a 20% buffer for the planning fallacy (Buehler et al. 1994).

Inputs: plan (required), base_hours.

explain_memoryA

Explain one memory's full state: content, cues, retrievability, importance, strength, confidence, evidence, links, suppression, access and review state.

Inputs: memory_id (required).

export_memoriesA

Export all active memories as a portable JSON payload (versioned, includes retrieval stats).

Inputs: no named parameters.

forgetB

Move a memory to the recycle bin.

Inputs: memory_id (required).

forgetting_riskB

Rank memories by forgetting risk (importance x forgetting): the riskiest ones should be reviewed first.

Inputs: limit.

goal_replayB

Replay goal-related memories to plan the next move: recall evidence, extract past lessons, reactivate overdue intentions and score replay readiness (prefrontal-hippocampal replay; Jensen et al., 2024; Watanabe et al., 2023).

Inputs: goal (required), top_k.

import_memoriesC

Import memories from an export payload; returns the number imported.

Inputs: payload (required).

intent_cancelB

Cancel an intention without completing it.

Inputs: intent_id (required).

intent_completeB

Mark an intention as completed.

Inputs: intent_id (required).

intent_conflictsB

Detect intention clashes: two active intentions due within a short window, or sharing the same context cue.

Inputs: time_window_minutes.

intent_dueA

List active intentions whose deadline has arrived.

Inputs: limit.

intent_rememberB

Register a future intention (prospective memory): content, deadline and optional context cue.

Inputs: due_at (required), content (required), importance, context_cue.

intent_reportA

Summarize the intention register: active, overdue, next upcoming, completed and cancelled counts.

Inputs: no named parameters.

interference_reportA

Report cue-crowded clusters (too many memories on one cue) that cause interference, with a suggestion to add differentiating cues (Wickens 1972).

Inputs: limit, shared_cue_min.

kg_exportA

Export the memory network as a knowledge-graph edge list (nodes + deduplicated undirected edges) for external visualization (semantic networks, Collins & Quillian 1969).

Inputs: no named parameters.

learning_loopC

Build a ready-to-run learning loop: what to review first, one self-test question for the weakest topic, and the snapshot to take afterwards (spacing + testing effect + knowledge tracing).

Inputs: count.

lesson_learnedC

Extract lessons learned from project memories: successes, failures and lessons as reusable schemas (schema reuse, Bartlett 1932).

Inputs: limit, memory_ids.

life_storyA

Summarize the store as lifetime periods: group episodic traces into time buckets with event counts, top themes, average importance and highlights (Conway & Pleydell-Pearce 2000).

Inputs: limit, period_days.

list_conflictsA

Return active memory conflicts: same cue, both confident, different content. Agents can use this to spot contradictions before answering.

Inputs: no named parameters.

math_ladderC

Climb the math abstraction ladder (concrete -> symbolic -> general rule), using formulas already stored in memory (Amalric & Dehaene, 2019; concreteness fading).

Inputs: problem (required), top_k.

memory_auditA

Deep lifecycle audit: active/recycled counts, revised and emotional traces, conflicts, due now, average retrievability and importance.

Inputs: no named parameters.

memory_healthA

One overall memory-health score (0-100) with itemized penalties: linked ratio, crowded cues, conflicts, overdue/clashing intentions and suppressed memories (metacognitive monitoring).

Inputs: no named parameters.

memory_mapA

Summarize what the memory holds: topics with counts and average retrievability, plus a weak/ok/strong strength histogram. Powers the human-readable memory map chart.

Inputs: limit, topic_min.

memory_statusA

Return a memory-health snapshot: active counts by kind, average strength/importance, how many memories are due right now, and how many conflicts exist.

Inputs: no named parameters.

multi_hop_reportA

Walk the association network hop by hop from a start memory: which memories are 1 hop, 2 hops etc. away (spreading activation, Collins & Loftus 1975).

Inputs: start_id (required), depth, limit.

next_intervalC

Recommend each memory's next review interval from retrieval history (adaptive spacing; Karpicke & Bauernschmidt, 2011).

Inputs: memory_id.

numeric_reasoningB

Sanity-check numbers and units in a Chinese math or physics problem: unit mixes, division by zero, and consistency with known facts in memory (number sense, Dehaene 1997; mental models, Johnson-Laird 1983).

Inputs: problem (required), context_memory_ids.

physics_simulateB

Run a mental physics simulation: detect scene type, extract quantities, recall the applicable law from memory (or built-in rules) and play the scene forward in ordered phases (intuitive physics engine; Battaglia et al., 2013; Fischer et al., 2016).

Inputs: scene (required), top_k.

planA

Agent planning: turn a goal into an ordered step plan, reusing the person's own past steps or a referenced person's steps as an analogical template.

Inputs: goal (required), top_k, effort.

plan_qualityB

Score a Chinese agent plan's quality: step count, explicit verbs, dependency ordering, duplicates and alignment with project memories (cognitive control, Miller & Cohen 2001; means-ends analysis, Newell & Simon 1972).

Inputs: plan (required), context_memory_ids.

plan_rehearsalA

Mentally rehearse a plan before executing: predict each step's success probability from outcome history, flag the weakest step and offer a remembered fallback (constructive episodic simulation; Schacter & Addis, 2007).

Inputs: goal (required), top_k.

plan_rewriteB

Rewrite a weak Chinese plan into an executable one: normalize steps to action verbs, remove duplicates and order along the standard build flow (executive planning, Miller & Cohen 2001).

Inputs: plan (required).

plan_supportB

Retrieve supporting memories for each plan step so the agent executes with context (working memory pulls from long-term memory; Baddeley & Hitch 1974).

Inputs: plan (required), top_k.

plan_trackerC

Track execution status of each plan step (pending / in_progress / done / blocked) with a completion ratio (goal monitoring, Miller & Cohen 2001).

Inputs: plan (required), statuses.

practice_answerB

Score a retrieval attempt, apply testing-effect reinforcement, and return the correct content as feedback.

Inputs: attempt (required), memory_id (required), generation_bonus, suppress_competitors.

practice_dueA

Active retrieval practice: list due memories as cues only (no answer), for testing-effect self-quizzing.

Inputs: kind, limit, vary_cues, interleave, +5 more.

practice_forecastA

Forecast which memories are due within the next N days, with due times, so the agent can plan a week of reviews ahead of time.

Inputs: days.

practice_planB

Return the next practice session as a review plan: each card with its scheduled next review time, current retrievability, and historical success rate.

Inputs: limit.

practice_reportA

Score a whole practice round (list of id/attempt) and return one session report with per-card feedback.

Inputs: answers (required).

practice_sessionB

Run one complete practice session: returns the coming session plan plus the scored report for the answers (difficulty and next-review suggestions).

Inputs: answers (required), limit.

predict_stepC

Predict a step's success probability from its outcome history (prediction-error updated records).

Inputs: step (required).

project_briefB

Assemble a project brief from related memories and intentions: background, known requirements, known risks and pending actions (schema activation, Bartlett 1932).

Inputs: title (required), limit, memory_ids.

project_riskC

Score project risk from memories and intention state: known problem traces, conflicts, overdue intentions and clashing schedules (memory-driven risk management).

Inputs: memory_ids, compare_limit.

reasonC

Reasoning recall: assemble the full premise pack for a math / compare / transitive question.

Inputs: query (required), top_k.

reasoning_traceB

Build a replay-friendly reasoning trace from stored memories: recall evidence, extract quantities, build per-step trace and optionally store the derived conclusion as an inference memory (math reasoning circuits; Menon, 2016; Watanabe et al., 2023).

Inputs: problem (required), top_k, topic, store_conclusion.

rebuild_vectorsA

Re-embed active memories missing from the vector index (repairs a failed batch embedding).

Inputs: no named parameters.

recallC

Recall memories matching a query.

Inputs: query (required), kind, top_k, context, +1 more.

recall_logA

Return the most recent recall entries (query, top result, confidence, timestamp) as a bounded audit log.

Inputs: limit.

recall_traceA

Explain why a query recalls what it recalls: candidates scanned, top results with scores and reasons (metacognitive explanation).

Inputs: query (required), top_k.

record_outcomeA

Record an execution outcome (success/fail + note) for an agent project step (evidence accumulation).

Inputs: goal (required), step (required), success (required), note.

rememberC

Store a memory (episodic or semantic).

Inputs: content (required), cues, kind, affect, +4 more.

remember_turnA

Save one conversation turn in a single call: splits the text into sentences and stores each with automatic cues. Call this after every user/assistant exchange to keep memory automatic.

Inputs: text (required), max_segments.

replanA

Re-plan after a failed step: move the failing person's step to the end (avoided), keep successful alternatives, and store the re-planning decision.

Inputs: goal (required), failed_step (required), top_k.

resolve_conflictsA

Resolve memory conflicts on demand: lopsided-evidence conflicts retire the stale trace, balanced ones lose confidence (accommodation + REM-style resolution).

Inputs: no named parameters.

restoreA

Restore a memory from the recycle bin.

Inputs: memory_id (required).

retrieval_qualityC

Measure retrieval quality across queries: average top score, retrievability, hit rate and weak rate (metacognitive monitoring of retrieval, Koriat & Goldsmith 1996).

Inputs: limit, top_k, queries.

reviewC

Record a spaced-repetition outcome (success/fail).

Inputs: memory_id (required), success.

review_batchA

Apply a batch of spaced-repetition outcomes: each answer is {id, success}; returns the adaptive scheduler state (streak, next review) for every card.

Inputs: answers (required).

review_consistencyA

Monitor adherence to the spaced-review schedule: flag overdue reviews, report an adherence ratio and plain advice (Cepeda et al., 2006; self-regulated learning monitoring).

Inputs: no named parameters.

review_dueB

List memories due for spaced review; optionally prefer desirable-difficulty items (hard but likely to succeed).

Inputs: limit, difficulty_target, desirable_difficulty.

review_loadA

Estimate upcoming review pressure: due now, overdue, due within N days, weak traces, and a weighted load index.

Inputs: days.

schema_reportC

Group memories into topic schemas by their primary cue: cluster size, average importance, kind mix and samples (schema theory, Bartlett 1932).

Inputs: limit.

search_batchB

Run several recall queries in one call; returns one result group per query in input order (single MCP round trip for a whole question list).

Inputs: queries (required), kind, top_k.

session_summaryA

Summarize one work session's memories: semantic facts, episodic events, plus conflict and duplicate pairs for post-session consolidation.

Inputs: memory_ids (required), compare_limit.

similarity_reportB

Find confusable memory pairs by content-token overlap (near-duplicates or pairs needing better separation).

Inputs: limit, threshold.

sleepA

Run sleep consolidation (promote, prune, reflect, conflicts).

Inputs: no named parameters.

sleep_and_planB

Run the full sleep cycle, then return the consolidation summary, weak-important replay count, and refreshed practice plan/forecast.

Inputs: days.

sleep_replayB

Sleep replay: strengthen surprising outcome records and consolidate each step's experience into a '历史成功率' summary.

Inputs: no named parameters.

spacing_planB

Build a spaced review schedule: fading memories early, strong ones later, topics interleaved (distributed practice; Cepeda et al., 2006).

Inputs: days, limit.

statsD

Memory statistics.

Inputs: no named parameters.

summarize_clusterB

Summarize a cluster of related memories as one gist: shared cues, frequent terms, evidence and previews (fuzzy-trace theory, Brainerd & Reyna 1990).

Inputs: memory_ids (required).

suppressed_reportA

List currently suppressed memories with previews.

Inputs: no named parameters.

suppress_memoriesA

Temporarily block memories from retrieval (directed forgetting): traces stay in the store but stop surfacing in recall until unsuppressed.

Inputs: memory_ids (required).

tag_memoriesB

Add or remove tags (cues) on memories in bulk; tags are first-class retrieval cues.

Inputs: tags (required), memory_ids (required), action.

temporal_anchorA

Show which memory the time-anchor pass inserted for a '上次/下次/最近/什么时候' style question, so agents can verify last-vs-next retrieval picks the record with the right date (ordinal time processing; Gauthier et al., 2020). Read-only.

Inputs: query (required), top_k.

timeline_reportB

Autobiographical timeline: episodic memories in chronological order grouped by day, optionally within a start/end window.

Inputs: end, limit, start.

topic_drift_reportB

Compare topic distribution between the two most recent periods: which themes grew, shrank, appeared or disappeared (schema reconstruction, Bartlett 1932).

Inputs: limit, period_days.

unsuppress_memoriesB

Restore suppressed memories to retrieval.

Inputs: memory_ids (required).

updateC

Revise a memory (reconsolidation).

Inputs: memory_id (required), cues, content, confidence, +1 more.

working_setD

Recently used memories for prompt injection.

Inputs: limit.

working_set_budgetA

Check whether the working set fits working-memory capacity and recommend topic chunking when overloaded (7±2 chunks, Miller 1956; 4±1 focus, Cowan 2001; cognitive load, Sweller 1988).

Inputs: limit, optimal, capacity.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    C2.7/5.0

    Scored across 98 tools

    Disambiguation2/5

    With 98 tools, many share overlapping responsibilities (e.g., practice_report/practice_session/practice_due/practice_answer; memory_status/memory_audit/memory_health/memory_map/stats; sleep/sleep_replay/sleep_and_plan; plan/replan/plan_rewrite/plan_quality/plan_tracker). An agent selecting a tool will frequently need to parse subtle description differences, and several report tools seem to summarize the same underlying state.

    Naming Consistency4/5

    Tool names mostly use snake_case and many follow verb_noun, but there are many noun-phrase names (memory_health, schema_report, lifecycle_audit, dependency_map, concept_cover) and one-word commands (sleep, check, update, plan, search). This is a readable convention but not consistently predictable.

    Tool Count1/5

    98 tools is extreme for any MCP server. Even if each tool has a cognitive justification, this scale makes the tool set hard to navigate and causes selection latency, so it is not well-scoped.

    Completeness5/5

    The surface covers the full memory lifecycle—store, retrieve, update, forget, restore, batch review, spaced repetition, sleep consolidation, intentions, planning, reasoning, exports, and audits. There are no obvious dead ends; every major operation appears to have at least one tool.

    Maintenance

    ActivityNo data
    ResponsivenessSyncing

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      D
      maintenance
      Gives AI agents persistent memory with semantic search, automatic extraction, and memory decay, accessible via MCP protocol.
      9 npm
      MIT
    • A
      license
      Not graded
      quality
      D
      maintenance
      Local-first AI memory layer with hybrid retrieval and brain-inspired namespaces. Enables agents to save, search, and manage memories directly via MCP tools.
      6 npm
      MIT
    • A
      license
      Not graded
      quality
      B
      maintenance
      Provides AI agents with persistent, human-like memory infrastructure via MCP, enabling them to store, search, summarize, and forget episodic, semantic, procedural, and working memories across sessions.
      823 npm
      MIT
    • A
      license
      Not graded
      quality
      C
      maintenance
      Provides AI agents with persistent local memory management, including semantic recall, knowledge graph traversal, and automatic memory consolidation, enabling structured long-term memory across MCP clients.
      Apache 2.0