Treant
Guards ansible-playbook commands by resolving the Ansible inventory they target and denying or asking when it is protected or belongs to another workspace.
Guards wrangler commands by resolving the Cloudflare account they act on and denying or asking when it is protected or belongs to another workspace.
Guards git push commands by resolving the Git host they target and denying or asking when it is protected or belongs to another workspace.
Guards helm commands by resolving the Kubernetes context they target and denying or asking when it is protected or belongs to another workspace.
Guards terraform and terragrunt commands by resolving the Terraform folder they act on and denying or asking when it is protected or belongs to another workspace.
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@Treant show me the session brief for this repo and any open warnings"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
Quick start · Features · How it works · Screenshots · Deploy · Licence
Overview
Treant is a self-hosted MCP server that gives Claude Code, Kiro and any other MCP client a memory that outlives the session. What an agent learns is scrubbed, saved and distilled into a knowledge graph that the next session can search.
Remembers across sessions: a brief at session start and hybrid search over vectors and graph, so agents stop re-learning the same things.
Keeps contexts apart: each workspace (
personal,acme,startup) is its own Postgres schema and role, and a token reaches exactly one.Shares only what is safe: know-how reaches the common
generalschema only through a gate of rules and two independent judges.
Status: source-available, early (0.1.1). The Python package and the CLI are called treant.
Related MCP server: agent-recall
Why Treant
Seen from a coding agent's side of the terminal, four things go wrong without it:
Every session starts from zero. The agent rediscovers the repository layout, the build quirk and the approach it already ruled out last week, and spends tokens doing it. Treant hands it a brief at session start (warnings, open threads, what memory holds about the repository) and a hybrid search over vectors and a graph of everything saved before.
Context bleeds between clients. When one machine serves an employer, a client and your own projects, a single memory store will surface one client's host names in another client's session. In Treant a token reaches one workspace, and the database role behind it has no grant on any other workspace's schema. An isolation test (nightly in the production setup) tries to cross every pair of workspaces and fails loudly if it can.
Shared know-how and private details look alike. A lesson about a library is useful everywhere; the name of a production cluster is not. Each session is distilled into a workspace half and a general half, and the general half reaches the shared schema only after rules (ticket IDs, IPs, account IDs, your domains and terms, every workspace's instance names), an LLM judge and the Jev judge all agree.
Agents run commands against the wrong target. An agent working in one project can still
kubectl deleteagainst whatever context is current.treant-guardreads each shell command before it runs, resolves the kube context, AWS profile, git host, Terraform folder, Ansible inventory or Cloudflare account it acts on, and asks or refuses when that target is protected or belongs to another workspace. It runs locally, without a server.
Features
Memory that carries over
MCP tools:
save_session,search,brief,warnings,update_fact,retract,report_mistake(plus the deprecatedguard_check).Typed saves: journal, facts, decisions, lessons, dead ends, procedures, changes, open threads, preferences, warnings and client memory.
Hybrid search: cosine similarity over the workspace's and
general's vectors, plus facts reached by a one-hop graph walk from the matched nodes.Distillation: a model turns each saved session into nodes, edges and facts. Near-duplicate names are flagged for a merge, superseded facts are recorded as conflicts, and every change keeps its history so it can be restored.
Workspaces isolated by the database
One schema
ws_<name>and one role per workspace; the server runs every transaction underSET LOCAL ROLE, and search drops any hit whose schema is not the token's.Tokens are bound to one workspace and carry action scopes (
create,read,update,delete). Only a SHA-256 of the secret is stored.treant canary plantandtreant isolation-testprove on a schedule that no workspace can reach another through search, brief, guard, the graph walk or a directSELECT.
A gate in front of shared knowledge
Deterministic rules first, then an LLM judge, then the Jev judge. A failing fact is rewritten at most twice, then blocked.
Publishing is automatic or waits for owner review, per workspace. A judge that is down makes the job wait; nothing passes on one judge.
Scrubbed before storage
The client and the server both remove secrets, tokens, IP addresses, private host names and configured terms. A save the scrubber is not sure about is quarantined for the owner instead of stored.
A guard for risky commands
The shipped rule pack covers
kubectl,helm,aws,terraform,terragrunt,git push,ansible-playbookandwrangler; add your own rules in TOML.Modes
protect(default),production,allowlistandoff, per workspace. Fails closed on an invalid config, an internal error or the 3 second budget.
Owner dashboard
Review queue, quarantine, jobs, workspaces and settings, tokens, a memory browser with history and restore, duplicates, merges, conflicts, a graph view, mistakes, measurements and the audit log.
OIDC login (Authelia and Authentik are covered by the tests) with re-authentication for sensitive actions, or a single-owner mode for a trusted network. Server-rendered, no JavaScript.
How it works
The full description is in docs/architecture.md.
System overview
Agents reach treant serve over MCP (streamable HTTP at /mcp) with a bearer token, either
directly or through treant-client, which adds session hooks, a stdio MCP proxy that picks the
token for the current folder, and a background save worker. The worker is the only process that
calls the LLM gateway and the Jev judge; the server and the dashboard use only the embedding
service, to embed search queries. Everything lives in one
Postgres database with a control schema, the shared general schema and one schema per
workspace.
Workspace isolation
A token maps to one workspace and a set of actions. The application connects as a login role that
inherits nothing and switches to the workspace's role for each transaction, so even a bug that asks
for another workspace's schema gets a permission error. Only the gate (as the publisher role) and
the owner (as the admin role) write to general. Canary items in every workspace and a nightly
isolation test check every pair of workspaces.
Save, distillation and the gate
A save is scrubbed, stored as a session revision and a journal entry, and queued. The worker embeds
it (from then on the journal entry is searchable), then distills it with one model call into a workspace half
(applied straight into the workspace graph) and a general half (queued, one gate job per item).
Items that pass are published, or wait for review when the workspace is set to review; the owner
decides on everything else in the dashboard or with treant general approve|drop.
Guard decision
The guard runs in the Claude Code PreToolUse or Kiro preToolUse hook. It follows cd,
export and similar state changes on the same line, resolves each target from flags, environment,
config files or a default_from command, and compares it with the workspace's lists. Any denied
target makes the whole command deny, any other finding makes it ask. When a rule matched and the
workspace has a token, a memory warning on the server can also turn a run into an ask. The rule
language, modes and known gaps are in guard/README.md.
Screenshots
Quick start
Needs Docker with Compose. Everything listens on loopback only.
git clone https://github.com/ashkmb/treant-memory.git && cd treant-memory
cp .env.example .env # then set POSTGRES_PASSWORD and TREANT_LOGIN_PASSWORD
docker compose up -d postgres embed # the first start downloads the embedding model (about 330 MB)
docker compose run --rm admin bootstrap # one-shot: roles, schemas, grants
docker compose run --rm admin workspace create personal
docker compose run --rm admin canary plant personal
docker compose up -d treant worker
curl http://127.0.0.1:8000/healthz # ok
docker compose run --rm admin token create personal --label laptop --actions create,read,update,deleteThe token is printed once and not stored.
Compose pulls the published image ghcr.io/ashkmb/treant-memory:0.1.1 (linux/amd64 and
linux/arm64). To run your own changes instead, run docker compose build first: it builds the
same tag from your checkout. scripts/quickstart-smoke.sh runs all of the above plus a save and
a search over MCP; CI runs it on every push.
MCP directories that list a server's tools can run docker run --rm -i ghcr.io/ashkmb/treant-memory:0.1.1 serve --list-tools: it speaks MCP over stdio, needs no
database or settings, and refuses every tool call.
compose.yml runs postgres (pgvector/pgvector:0.8.7-pg17-bookworm), embed (llama.cpp
server with EmbeddingGemma 300M), treant (serve), worker and a one-shot admin service
for the owner CLI (docker compose run --rm admin <command>). It is meant for one machine.
For a public host put the server behind a TLS reverse proxy and set TREANT_ALLOWED_HOSTS.
Models: what works without them
The quickstart runs without any chat model. Add them in .env when you want distillation and
promotion to general.
Without | What still works | What does not |
LLM gateway ( | Saves are stored, embedded and searchable (journal entries); the guard. | Distillation into nodes and facts, and therefore promotion to |
Jev judge ( | Everything in the workspace, including distillation and the LLM judge. Items that pass the rules and the LLM judge wait in the review queue. | Automatic publishing to |
The LLM gateway is any OpenAI-compatible chat endpoint (LiteLLM was used in development). The
worker posts to <TREANT_LITELLM_URL>/chat/completions with the workspace's alias (default
default) as the model, and the workspace's own key TREANT_LITELLM_KEY_<WORKSPACE>, so each
workspace can have its own model and budget.
The Jev judge is a third-party service (default endpoint https://api.typesafe.ai, override
with TREANT_JEV_URL and TREANT_JEV_MODEL); its key is required for automatic publishing to
general. TREANT_JEV=off turns it off: Jev is never called, and nothing is published without
your approval, whatever the workspace's publish mode. The quickstart starts with Jev off; set
TREANT_JEV=on and TREANT_JEV_API_KEY in .env to turn it on. A workspace with --backend none never sends anything to any model: its general
items are held as blocked (reason judge:none) for the owner.
Connect Claude Code or Kiro
Any MCP client. Connect a client that speaks streamable HTTP to http://127.0.0.1:8000/mcp
with the header Authorization: Bearer <token>. For Claude Code:
claude mcp add --transport http treant-personal http://127.0.0.1:8000/mcp \
--header "Authorization: Bearer <token>"With the hooks (macOS). treant-client adds a brief at session start, an automatic save at
session end, a stdio MCP proxy that picks the token from the folder's workspace, and the command
guard, for Claude Code and Kiro:
uv tool install ./client # puts treant-client on PATH (pulls in ./guard)
treant-client token set personal # prompts; stored in the macOS Keychain
treant-client install --dry-run # review the diffs
treant-client installSet url (and kiro_agent for Kiro) in ~/.config/treant/config.toml, and map your folders to
workspaces under [workspaces] in ~/.config/treant/guard.toml.
client/README.md has the details, including uninstall;
guard/README.md covers the guard's config, modes and rules.
Production deployment
To run Treant in production (Postgres + pgvector, embedding service, LLM gateway, Jev judge,
OIDC dashboard, backups and the nightly isolation test), follow
docs/deploy.md. It ships a ready Compose stack, example env files, systemd
timers and a Caddy example in deploy/.
Server (treant serve, treant worker, treant dashboard, owner CLI):
Variable | Used by | Default |
|
| required there |
|
| required there |
| everything else (login role DSN) | required |
|
| required |
| model name sent to the embedding service |
|
| must stay |
|
| prefix of every database role |
|
|
|
|
| comma-separated public host names; turns on Host and Origin checks | off |
| worker: distillation, rewrites, LLM judge | unset |
| worker: |
|
| worker: the Jev judge | key unset |
Dashboard (treant dashboard):
Variable | Meaning | Default |
| public | required |
| cookie signing secret, at least 32 characters | required |
| comma-separated usernames allowed in | required |
|
|
|
| OIDC provider (with | required with |
| client id; group the user must be in |
|
| listen address; age of a login for sensitive actions |
|
Per-workspace settings (treant workspace set <ws> ...): --backend litellm|none, --alias,
--judge-alias, --publish auto|review, and the gate's deny lists --domain,
--ticket-prefix, --term (terms also drive the server scrubber).
treant serve [--list-tools] # --list-tools: tool list only, stdio, no database
treant bootstrap | upgrade
treant workspace create|list|show|archive <name>
treant workspace set <name> [--backend ...] [--publish ...] [--domain ...] [--term ...] [--reset]
treant workspace purge <name> --confirm <name> # archived workspaces only
treant token create <workspace> --label <l> --actions create,read[,update,delete]
treant token list <workspace> | revoke <id>
treant canary plant <workspace> [--if-missing] | list
treant isolation-test # exit 0 clean, 1 on any fault
treant general list|show|approve|drop ... # the queue to general
treant quarantine list|show|release|drop ...
treant jobs list [--status dead] | retry ...
treant merges list <ws> | conflicts list <ws> | duplicates <ws|general>
treant distill backfill <ws> [--dry-run]
treant serve | worker | dashboard
treant target add|list|remove ... # deprecatedtoken create prints the token once; it is not stored. workspace archive revokes the
workspace's tokens. Owner actions are recorded in control.audit (actor cli, or
dashboard:<user>).
The target commands and the guard_check MCP tool are deprecated and kept for older
clients: the client guard decides locally from its own config and asks the server only for
warnings.
Requirements and limitations
Server: Docker with Compose for the quickstart. The production guide targets Linux with Docker Engine and the Compose plugin v2.24 or newer, and about 2 GB of RAM with the bundled embedder. The quickstart pulls the image from
ghcr.io/ashkmb/treant-memory; the production guide builds it from this repository.Python 3.12+ for
treantandtreant-client(treant-guardneeds 3.11+).Postgres 17 with pgvector 0.8 or newer. No other extension is needed.
One embedding model. The supported model is EmbeddingGemma 300M (768 dimensions). The vector columns are declared
vector(768)and the embedder sends EmbeddingGemma's query and document prompt prefixes, so other models or dimensions do not work without code changes. There is no re-embed command: choose the embedding service before the first save. Any service that serves this model behind an OpenAI-compatible/v1/embeddingsworks; the quickstart uses llama.cpp withggml-org/embeddinggemma-300M-GGUF.Jev for automatic promotion. With
TREANT_JEV=off(or without a Jev key) nothing reachesgeneralunless you approve it. The default Jev endpoint is a third-party internet service, so with Jev on, text that passed the rules and the LLM judge leaves your network; decide whether that is acceptable for your workspaces.treant-clientis macOS only today. It keeps tokens in the macOS Keychain and runs the Kiro sweep as a launchd job. On other systems, connect your MCP client to the server directly (no automatic brief, save or guard hook).The guard catches an agent's mistakes, not an adversary. It reads only the command line it is given; aliases, scripts,
sshand deliberate obfuscation are out of its sight. Inprotectmode a target it cannot read runs; useallowlistmode where that is not enough. The full list is under "Known gaps" in guard/README.md.
Project structure
treant-memory/
├── src/treant/ MCP server, worker, owner CLI and dashboard (package `treant`)
│ ├── dashboard/ owner web UI (Starlette, server-rendered)
│ └── sql/ schema for control, general and workspaces
├── client/ treant-client: Claude Code and Kiro adapters
├── guard/ treant-guard: local command guard and its rule pack
├── deploy/ production Compose stack, env files, scripts, systemd timers, Caddy
├── docs/ architecture.md, deploy.md, images
├── tests/ server test suite
├── compose.yml quickstart stack (loopback only)
└── compose.test.yml Postgres + pgvector for the testsContributing and security
docker compose -f compose.test.yml up -d # Postgres 17 + pgvector on 127.0.0.1:55432
uv sync && uv run ruff check && uv run pytest -q
uv sync --directory client && uv run --directory client ruff check && uv run --directory client pytest -q
uv sync --directory guard && uv run --directory guard ruff check && uv run --directory guard pytest -qThe database tests skip when that Postgres is not reachable. Each run creates its own database and role prefix and drops them afterwards. CI runs all three suites with the database.
Issues are welcome. Pull requests open once the contributor agreement is final; see CONTRIBUTING.md. Report vulnerabilities privately as described in SECURITY.md, not in public issues.
Licence
treant-memory is source-available, not free for every use. Every copy must keep the licence
and the Required Notice line that names the source.
Who | Terms |
Personal and other noncommercial use (including charities, schools, public research) | Free, under the PolyForm Noncommercial License 1.0.0 |
Companies with fewer than 5 people (owners, employees and contractors together) | Free, also commercially, under the Small Company Grant |
Larger companies | Commercial licence from the licensor |
Contributions will be accepted under the Contributor License Agreement (draft, pending legal review; pull requests are not open yet).
To ask for a commercial licence, open a Commercial licence issue or contact Ashkan Kamyab through https://ashkmb.com.
Available Tools
8 toolsbriefSession briefARead-onlyIdempotent
Short orientation to read at the start of a session: current warnings, open threads and recent decisions for this workspace, plus what memory holds about repo when given. With repo_only, only the repo section (no workspace-wide warnings or threads). Read-only; returns brief as plain text of at most 6000 characters. The brief is built from distilled facts, so it stays nearly empty until the worker has distilled some sessions.
Inputs: repo, repo_only. Returns: object
guard_checkCheck targets (deprecated)ARead-onlyIdempotent
Deprecated: the client decides locally now; use warnings. Checks a risky shell command's targets (kube context, AWS profile, git remotes, Terraform root, Ansible inventory) against this workspace's listed targets. Read-only. unresolved lists target kinds that could not be determined (command when the line did not parse); an empty unlisted then does not mean all clear.
Inputs: cwd (required), command (required), aws_profile, git_remotes, +2 more. Returns: object
report_mistakeReport a memory mistakeA
Report that memory misled you: a fact, warning or brief line that turned out wrong or harmful in this session. Describe what memory said and what was actually true. The report goes to the owner's review page and changes no fact by itself. Returns ok, or error.
Inputs: text (required). Returns: object
retractRetract a factADestructiveIdempotent
Retract a fact in this workspace that is wrong, so search and the brief stop returning it. Prefer update_fact when the fact only needs correcting. The fact and its history are kept and the owner can restore it. Needs the token's delete scope. Returns ok, or error: not found, forbidden.
Inputs: fact_id (required). Returns: object
save_sessionSave sessionA
Save this session's knowledge to memory. sections is an object whose keys are:
journal: what was done and the outcome, a few lines
facts: stable truths learned (where config lives, versions, how things connect)
decisions: what was decided, why, and what was rejected
lessons: surprises and root causes
dead_ends: approaches that failed and why
procedures: steps or commands that worked (no command output)
changes: repos, branches, commits, PRs, tickets, what was applied (pointers only, no diffs)
open_threads: unfinished work, next steps, blockers
preferences: corrections on how the owner wants the AI to work
warnings: dangerous things to check first
client_memory: memory files the client wrote or changed this session Unknown keys are kept inside the journal. Saving the same client_session_id again adds a revision. Never include secrets. Set unsure=true if you are not sure the summary is free of secrets; the owner reviews it first.
Inputs: sections (required), client_session_id (required), unsure. Returns: object
searchSearch memoryARead-onlyIdempotent
Search long-term memory by meaning and keywords: this workspace's facts, decisions, lessons, procedures and warnings, plus shared general know-how. Use it before the first action on a named repo, service, cluster or ticket, before proposing a design or a fix, after an error and before retrying, and whenever the user refers to past work. Read-only. Returns mode (hybrid, or keyword when the embedder is down) and hits, each with namespace, kind, type, text, node and score; facts reached through the graph from a direct hit are included.
Inputs: query (required), limit. Returns: object
update_factCorrect a factADestructiveIdempotent
Correct a fact in this workspace: replace its text, or set an open thread's status to closed (done) or back to current. Use it when you learn a fact is outdated or imprecise; use retract when it is simply wrong. The previous text is kept in the fact's history and the owner can restore it. Needs the token's update scope. Returns the fact's new version, or error: not found, invalid input, forbidden.
Inputs: fact_id (required), text, status. Returns: object
warningsWarnings for systemsARead-onlyIdempotent
Current warning facts attached to the named systems, for a check before a risky action (a deploy, a migration, a command against a cluster). Pass the names of the repos, services, hosts or clusters involved. Read-only; returns warnings, a list of texts, empty when memory holds none.
Inputs: names (required). Returns: object
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 8 tools
Most tools are distinct, but search, brief and warnings all surface overlapping memory content (warnings appear in search kinds and in the brief), so an agent may hesitate which to call before a risky action. guard_check is explicitly deprecated yet still exposed, directly competing with warnings for the same safety-check purpose.
Verbs-with-nouns (save_session, update_fact, report_mistake, guard_check) sit alongside bare nouns (search, brief, warnings) and a bare verb (retract). Readable but no single predictable convention.
Eight tools is a well-scoped size for a memory server and each maps to a lifecycle step. The only dead weight is the retired guard_check, which no longer earns its slot.
The write path is strong (save_session with rich sections, update_fact, retract, report_mistake) and the read path covers search, brief and warnings. Gaps are minor: no list/enumerate facts, no get-by-id, and no way to browse sessions or namespaces, though search can approximate these.
Maintenance
Related MCP Connectors
Shared long-term memory for AI agents: save and recall context as a searchable knowledge graph.
Persistent memory and knowledge graphs for AI agents. Hybrid search, context checkpoints, and more.
Persistent knowledge graph for AI-augmented teams. Store decisions, findings, and standing rules across agent sessions with semantic search and typed connections. Includes cross-session memory, audit trail, workspace isolation, and secret detection. Built for teams running agents that need to remember. Free until launch with team tier as default, anon trial available.
Shared memory for coding agents. Stop re-explaining your codebase every session.
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceProvides AI coding agents with persistent, graph-connected memory across projects, enabling cross-project context retrieval via synaptic connections and hybrid search.18 npm8MIT
- AlicenseNot gradedqualityCmaintenanceEnables persistent memory for AI coding agents, allowing them to remember people, decisions, and context across sessions through a knowledge graph and automated briefings.91 PyPI15MIT
- AlicenseNot gradedqualityDmaintenanceProvides AI coding agents with persistent memory by recording sessions and normalizing them into a searchable knowledge graph, then delivering relevant context at the start of the next session.MIT
- AlicenseNot gradedqualityDmaintenanceProvides coding agents with persistent graph-backed memory, storing decisions, reasons, and contradictions across sessions so conversations pick up where they left off.Apache 2.0