Skip to main content
Glama

structured-memory-mcp

An MCP server that gives an LLM a persistent, structured brain it reads at session start and writes to as it works, so you never re-explain yourself.

Architecture reference implementation. Python, Postgres + pgvector, about 20 MCP tools, no LLM calls inside the server. Everything in the demo is synthetic.


The problem

Every conversation with an LLM starts cold. The usual fixes all fail in a predictable way:

Fix

Why it breaks

Paste chat history into context

Cost and noise grow forever. Old, superseded statements sit next to current ones with equal authority.

A bigger context window

Same pile, bigger. Nothing says which line is true now.

Plain vector search over everything

Great at "what's similar", blind to "what's current", and it always returns something, even when the honest answer is "nothing".

What's missing isn't capacity. It's structure: knowing which kind of fact you're holding (a rule, a current state, a historical event, a hard number), which one wins when they disagree, and when to say "I don't know."

This repo is one answer: split memory into layers with different jobs, different write rules and different staleness rules, serve them over MCP, and teach the model the protocol on connect.

Related MCP server: Recall

Architecture

flowchart TB
    subgraph Client["MCP client (any host)"]
        Model["LLM"]
    end

    subgraph Server["MCP server — stdio, or http + bearer token"]
        Tools["tool surface (20 tools)"]
        Service["service layer: validate → repository → format"]
        Repo["repository: the only SQL"]
        Tools --> Service --> Repo
    end

    subgraph DB["Postgres + pgvector"]
        subgraph Present["Present tense: state, overwritten in place"]
            direction LR
            Constraints["constraints<br/>standing rules"]
            Records["records<br/>hard data"]
            Pins["pins<br/>state per lane"]
            Wiki["wiki<br/>compiled truth"]
            Threads["threads<br/>open loops"]
        end
        subgraph Past["Past tense: the trail, append-only"]
            Memory["vector memory<br/>hybrid search + honesty floor"]
        end
        subgraph Meta["Meta"]
            Friction["friction<br/>model failure log"]
        end
    end

    Model -- "session start: get_session_continuation()" --> Tools
    Model -- "mid-session: read / write" --> Tools
    Model -- "session close: set_pin, write_wiki, write_memory" --> Tools
    Repo --> DB
    Friction -. "human triage only" .-> Human(("human"))

The seven layers

Layer

Job

Tense

Write rule

constraints

Standing rules, injected every session

present

Added/retired only when the user says so. Never deleted.

pins

One "where things stand + what's next" slot per lane (work, personal, school)

present

Rewritten in place at session close. State, not history.

threads

Open loops tracked below the lane level; quiet ones surface at session start

present

Status changes record only what the user said. Silence never moves a thread.

wiki

One compiled page per entity; CORE pages are always-on operating instructions

present

Rewritten in place with a version bump. Never appended, never dated snapshots.

vector memory

What happened: dated facts and decisions. Hybrid search (vector cosine + BM25, rank-fused) with an honesty floor

past

Append-only, idempotent by key. One fact per write.

records

Hard structured data: invoices, deadlines, measurements

present

Upsert on (kind, title, date). Beats recall when they disagree.

friction

The model's own failure log, evidence-gated

meta

Written by the model, read and acted on by a human only.

Details: docs/architecture.md.

Trust order, in one line

constraints > records > pins > wiki > vector memory > the model's own recall: and if a lower layer is newer than a higher state layer and disagrees, the answer is contested: the model says so and asks, instead of silently picking. Executable version in brain/trust.py; rationale and staleness rules in docs/trust-and-staleness.md.

Session lifecycle

  1. Start: get_session_continuation() returns, deterministically and with no vector search: hard rules → one pin per lane → QUIET THREADS → full text of CORE wiki pages → wiki index.

  2. During: topic-specific history from read_memory / walk_trail; hard data in log_record; the model touches threads, sets constraints, and logs its own friction when it has a concrete artifact.

  3. Close: set_pin for the lane, write_wiki for changed entities, write_memory for durable facts.

Full protocols: docs/protocols.md. Honest failure modes and what the design does about each: docs/failure-modes.md.

Run it locally (about 2 minutes, no API keys)

Prerequisites: Docker, Python 3.11+.

git clone <this-repo> && cd structured-memory-mcp
make setup     # writes .env with a generated DB password (gitignored), creates .venv
make demo      # starts Postgres+pgvector, migrates, seeds a fictional user, runs the walkthrough
make test      # unit tests + integration tests against the live database

make demo plays a scripted session for a fictional freelance analyst (every name, client and number is invented): the session-start payload, a quiet-thread check-in, a search that hits, a search that correctly finds nothing, both trust-order conflicts, the friction evidence gate, and a session close.

An excerpt of real output:

QUIET THREADS — my picture of these is stale; ask to refresh it (silence is missing data, never a verdict):
  Half-marathon training (personal) — quiet 12d (cadence 7d) · Paused after a knee tweak; ...
  Kestrel dashboard handoff (work) — quiet 6d (cadence 3d) · Handoff doc and walkthrough video ...

5. SEARCH THAT SHOULD FIND NOTHING — the honesty floor
No relevant memories found for this query.

6. TRUST ORDER 1 — a record beats a recalled memory
   winner:  record -> $1,450
   flag:    memory disagrees with record; record wins — flag the memory for correction.

7. TRUST ORDER 2 — a NEWER memory contradicts an older pin
   contested: True  (no silent winner)
   flag:      memory is newer than pin and disagrees — the pin may be stale; ask before asserting.

Connect it to an MCP client

After make up migrate seed (or make demo):

# Claude Code
claude mcp add structured-memory -- /absolute/path/to/structured-memory-mcp/.venv/bin/python \
  /absolute/path/to/structured-memory-mcp/server.py

Any MCP host that can spawn a stdio server works: point it at the venv's Python and server.py. The server reads its secrets by name from .env; nothing is baked into the config.

Configuration

All by environment variable; the names are in .env.example. Highlights:

Variable

Purpose

POSTGRES_PASSWORD / DATABASE_URL

Database access (make setup generates a password)

EMBED_PROVIDER

local-hash (default; offline, demo-grade) · voyage · ollama

VOYAGE_API_KEY

Only for EMBED_PROVIDER=voyage (pip install '.[voyage]')

MIN_SIMILARITY

Honesty-floor override (per-provider defaults in brain/config.py)

TRANSPORT

stdio (default) or http (requires MCP_AUTH_TOKEN)

Embeddings: local-hash is a hashed bag-of-words projection. It tracks lexical overlap, not meaning. It exists so the demo and tests run offline. Use a real embedding model for anything real, and recalibrate the floor when you do (docs/failure-modes.md).

What's in the repo

brain/          the server: layers (pure logic), service, tools, repository, search, trust order
migrations/     schema only. No data rows ship in this repo.
demo/           synthetic data for a fictional user + the scripted walkthrough
tests/          pure-logic unit tests, plus integration + MCP-protocol tests (need the DB)
docs/           architecture, trust & staleness, protocols, failure modes, blog draft

Design choices worth a look: pure formatting/selection logic is separated from SQL so every layer's rules are unit-testable without a database; the server makes no LLM calls (retrieval and continuation are deterministic); the honesty floor and the multiplicative re-rank exist because of specific failures documented in docs/failure-modes.md.

Not included (on purpose)

A web dashboard, OAuth, multi-user isolation, automatic contradiction detection across the store, and background "dreaming" jobs.

Writeup

docs/blog/why-structured-memory.md: why structured memory beats dumping chat history into context.

License

MIT

Available Tools

20 tools
get_session_continuationA

CALL THIS FIRST in every conversation. Returns, in order: hard-rule constraints, one pin per lane, QUIET THREADS (if any), the full text of every CORE wiki page, and the wiki index. Deterministic — no vector search.

channel: optional — return only that lane's pin.

Inputs: channel. Returns: result

list_constraintsC

List standing rules. Retired rules are history, not truth.

Inputs: include_inactive. Returns: result

list_entitiesC

List every wiki page: folder, name, version, last update, headline.

Inputs: include_archived. Returns: result

list_frictionB

The HUMAN's triage read path. open | triaged | fixed | dismissed | "" for all.

Inputs: status. Returns: result

list_recordsB

List records, newest first, optionally by kind and ISO date range.

Inputs: kind, limit, to_date, from_date. Returns: result

list_threadsB

List tracked threads with lane, status, last-touched age and cadence.

Inputs: include_closed. Returns: result

load_wikiA

Load compiled wiki pages by exact name — deterministic. Misses suggest near matches.

Inputs: entities (required). Returns: result

log_frictionA

Log YOUR OWN failure in the moment, with a concrete artifact as evidence (the failed result, the user's exact correction). No artifact = do not call. Zero friction is a normal session. Never read this lane to change your behavior.

category: stale_protocol | wrong_tool | bad_retrieval | user_correction | missing_context | tooling_error | other

Inputs: summary (required), category (required), evidence (required), proposed_fix. Returns: result

log_recordB

Store hard data (invoice, deadline, measurement…). Records beat recall: when one disagrees with a remembered fact, the record wins. Upserts on (kind, title, date).

Inputs: kind (required), title (required), occurred_on (required), amount, +1 more. Returns: result

read_memoryA

Hybrid search (vector cosine + BM25, rank-fused, importance/recency re-ranked) over the trail. Use for topic-specific HISTORY — not for current state (that's pins/wiki). Says "No relevant memories found" when nothing clears the honesty floor; believe it.

Inputs: query (required), limit, domain. Returns: result

retire_constraintB

Retire (never delete) the ONE active rule matching the fragment.

Inputs: rule_fragment (required). Returns: result

search_memoryC

Broader sweep with the same ranking as read_memory (more results).

Inputs: query (required), limit, domain. Returns: result

set_constraintB

Add a standing rule when the user states one ("from now on…", "never…").

Inputs: rule (required), category. Returns: result

set_pinA

Session close: set the pin for ONE lane (work | personal | school). Rewrites that lane in place with the full "where things stand + what's next" state — not a delta. Durable facts belong in write_memory; the pin is state, not history.

Inputs: channel (required), content (required). Returns: result

touch_threadB

Mark a thread discussed NOW. Set status ONLY if the user ruled on it — status records what they said, never what silence suggested.

Inputs: name (required), note, status. Returns: result

track_threadB

Create/update a thread when the user names an ongoing project or open loop. cadence_days: quiet days before it surfaces (1-365; 0 = never surfaces on silence). status: live | parked | dropped | done. wake_date: ISO date for parked threads.

Inputs: lane (required), name (required), note, status, +2 more. Returns: result

triage_frictionA

Record the HUMAN's spoken verdict (triaged | fixed | dismissed). A model may never mark its own failure fixed.

Inputs: status (required), friction_id (required), triage_note. Returns: result

walk_trailA

Walk the trail in date order, oldest first, no scoring. For "what happened in March" / "when did X change". ISO dates, inclusive.

Inputs: limit, domain, to_date, from_date. Returns: result

write_memoryA

Persist one durable fact or decision. One specific fact per call, under 300 words.

domain: free-form short label, e.g. decisions | people | projects | general importance: 9-10 decisions · 7-8 relationship/strategy updates · 5 context · 3 ephemeral idempotency_key: unique slug; the same key twice is a safe no-op entities: wiki page names this fact touches (powers topic->page push)

Inputs: content (required), domain, entities, importance, +1 more. Returns: result

write_wikiB

Create or rewrite a page IN PLACE (synthesized current truth, never an appended log). folder="CORE" marks an always-on operating page injected in full every session.

Inputs: entity (required), content (required), folder. Returns: result

Tool Schema Changelog

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

Loading tool schema changelog…

    TDQS

    B3.4/5.0

    Scored across 20 tools

    Disambiguation4/5

    Most tools target distinct resources and actions, but read_memory and search_memory overlap heavily (both hybrid search the trail), and write_memory vs write_wiki could be confused about where durable information belongs. The detailed descriptions help, but the boundaries are not perfectly crisp.

    Naming Consistency5/5

    All tool names use snake_case with a consistent verb_noun pattern (load_wiki, retire_constraint, write_memory, list_constraints, track_thread, etc.). The convention is predictable throughout with no mixed styles.

    Tool Count3/5

    20 tools is heavy for a single MCP server and sits in the borderline range. While each tool covers a distinct facet (memory, wiki, constraints, threads, friction, records, session state), the surface could likely be consolidated to reduce selection overhead.

    Completeness4/5

    The server covers core lifecycle operations across its subdomains: memory read/write/search/walk, wiki load/write/list, constraints list/set/retire, threads list/track/touch, friction log/list/triage, and records log/list. Missing hard delete/update for memories, records, and wiki pages may be intentional by design, but still leaves minor gaps.

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      A
      quality
      C
      maintenance
      Provides an external context buffer so a local model can maintain session memory across long tasks and search and page through large documents without loading them whole into its limited context window.
      15
      1
      MIT
    • A
      license
      Not graded
      quality
      A
      maintenance
      Enables Claude and other AI agents to store decisions, patterns, and knowledge once and retrieve relevant context automatically across sessions, surviving context limits, restarts, and compaction.
      17 npm
      MIT
    • A
      license
      Not graded
      quality
      A
      maintenance
      Enables Claude and other AI agents to persistently store, retrieve, and organize decisions, patterns, and knowledge across sessions, so context survives restarts and compaction.
      17 npm
      MIT