Skip to main content

A temporal, governed context layer for agentic AI systems — bitemporal, attributed, permissioned Claims.

Project description

Context Vault

PyPI PyPI downloads npm License: MIT Python 3.11+

Governed memory for AI agents — every fact is stored as a versioned, time-bound, access-controlled, auditable claim. Agents retrieve what is current, permitted, and traceable. Conflicting facts are detected and reconciled, not silently overwritten.

Other memory systems help your agent remember more.
Context Vault makes sure it remembers what's true, what it's allowed to know, and proves what it knew.


Try it right now — no databases, no API key

pip install context-vault-ai
uvx --from context-vault-ai context-vault demo

That's it. The full governed-memory tour runs completely offline, in-memory, no setup required. You'll see conflict detection, time-travel queries, and the audit trail in action.


Table of Contents


What it does

Most AI memory systems are retrieval caches — smarter lookups over stored text. Context Vault is a governed context graph: every write goes through conflict detection, every fact carries a time window and an access label, and every operation is logged to a tamper-evident audit chain.

Five operations — nothing outside them:

Operation What it does
Assert Write a new fact. Automatically checks for contradictions, supersessions, duplicates, and refinements against existing facts. Never silently overwrites.
Resolve Read facts relevant to a query at a point in time, scoped to what the caller is allowed to see. Answers like "what did we believe about Priya on March 1st?"
Reconcile Route conflicting facts to human review or auto-resolve by policy (recency, trust, confidence).
Decay Age out or compress stale facts according to per-type policies.
Audit Replay exactly what any principal saw at any time. Hash-chained, tamper-evident, exportable.

What you get out of the box:

  • Conflict detection with a 6-way taxonomy (not just "conflict / no conflict")
  • Bitemporal queries: valid time (when a fact was true in the world) + system time (when you learned it)
  • Deny-by-default access control — unlabeled facts are private to their asserter
  • An immutable, hash-chained audit log
  • Multi-tenant workspaces — agents share nothing unless explicitly permitted
  • GDPR erase: redact + archive, never hard-delete

Installation

# Core — the engine, in-memory store, CLI demo. ~40 MB, no compile step.
pip install context-vault-ai

# With durable storage (Neo4j + Postgres)
pip install "context-vault-ai[self-host]"

# With the HTTP API server
pip install "context-vault-ai[api]"

# With the MCP server
pip install "context-vault-ai[mcp]"

# Everything you need to self-host the full stack
pip install "context-vault-ai[self-host,api,mcp]"

# With semantic embeddings (sentence-transformers; pulls PyTorch)
pip install "context-vault-ai[embeddings]"

Which extras do you need?

You want to… Extra
Try the offline demo (none — core only)
Store facts in Python scripts (ephemeral) (none — uses in-memory store)
Store facts durably (Neo4j + Postgres) self-host
Run the REST API / serve over HTTP api
Use the MCP server in Claude / Cursor mcp
Use semantic vector search embeddings
Cluster-wide rate limiting redis
LangGraph / LangChain integration langgraph
CrewAI integration crewai
LlamaIndex integration llamaindex
Claude Agent SDK integration claude-agent-sdk
OIDC / SSO oidc
GDPR crypto-shred (AES-256-GCM) audit-encryption
GDPR crypto-shred (AWS KMS, STRONG tier) audit-kms

Level 1 — Python (two minutes, no infrastructure)

Install the core package. No databases, no API key required for the structured API.

import os
os.environ.setdefault("VAULT_STORE", "memory")  # ephemeral in-memory store

from context_vault import Memory

m = Memory()

# Assert a structured fact (no API key needed)
m.vault.assert_claim_from(
    subject="Priya",
    predicate="job title",
    object="VP of Sales",
    principal_id="my-agent"
)

# Resolve — asks "what do we know about Priya's job title right now?"
results = m.recall("what is Priya's job title?", user="my-agent")
print(results)
# → "Priya: job title is VP of Sales (confidence 1.0, asserted just now)"

# Forget — archives the fact, never deletes it
m.forget("job title", user="my-agent")

With an Anthropic API key — use free-text remember (the LLM extracts structured facts):

import os
os.environ["ANTHROPIC_API_KEY"] = "sk-ant-..."
os.environ["VAULT_STORE"] = "memory"

from context_vault import Memory

m = Memory()
m.remember("Priya joined the enterprise plan and prefers Slack", user="priya")
print(m.recall("how should I contact Priya?", user="priya"))

Conflict detection in action:

m.vault.assert_claim_from(subject="Alice", predicate="works at", object="Acme Corp", principal_id="agent")
m.vault.assert_claim_from(subject="Alice", predicate="works at", object="Beta Inc",  principal_id="agent")
# ↑ The second assert is automatically classified as TEMPORAL_SUPERSESSION
# → the "Acme Corp" fact is closed with today's date; "Beta Inc" becomes current
# → no silent overwrite, full history preserved

The in-memory store is ephemeral — data is lost when the process exits. For durable storage, see Level 2.


Level 2 — Durable store + full Python SDK

Start Neo4j and Postgres (one command), then use the full SDK:

docker compose up -d       # Neo4j on 7474/7687, Postgres on 5433
from context_vault.app import build_vault
from context_vault.sdk import VaultClient
from context_vault.models.principal import Principal

# Build the vault (connects to Neo4j + Postgres via env vars or defaults)
vault = build_vault()
vault.init()

# Create a principal (an agent identity with access labels)
principal = Principal(id="agent-sales", role="agent", labels=["team:sales"])

# Use the typed SDK client
client = VaultClient(vault, principal)

# Assert a time-bound fact — valid from 2024-01-01 onwards
client.assert_fact(
    subject="Priya",
    predicate="account tier",
    object="Enterprise",
    valid_from="2024-01-01"
)

# Resolve — ask a natural-language question, get ranked facts back
for claim in client.resolve("what tier is Priya on?"):
    print(claim.edge_str())
    # → Priya --[account tier]--> Enterprise  (2024-01-01 → open)

# Time-travel: what did we believe on 2023-12-01?
for claim in client.resolve("what tier is Priya on?", as_of="2023-12-01"):
    print(claim.edge_str())
    # → (empty — fact wasn't asserted until 2024-01-01)

Assert a structured claim directly:

from context_vault.models.claim import Claim
from datetime import datetime, timezone

vault.assert_claim(
    subject="acme-contract-2025",
    predicate="renewal date",
    object="2025-09-30",
    principal=principal,
    valid_from=datetime(2025, 1, 1, tzinfo=timezone.utc),
    valid_to=datetime(2026, 1, 1, tzinfo=timezone.utc),
)

Audit replay — what did agent-sales see on March 1st?

log = vault.audit_replay(principal, as_of="2025-03-01")
for entry in log:
    print(entry)

Level 3 — HTTP REST API

The HTTP API is the most complete interface — it includes auth, multi-tenancy, conflict detection, admin console, and a governance UI.

Start the server:

pip install "context-vault-ai[self-host,api]"
docker compose up -d                               # Neo4j + Postgres
uvicorn context_vault.http_api:app --port 8000     # API server

Or with the CLI:

context-vault serve --port 8000

Sign up and get an API key (no admin dance):

# Sign up — creates your org + admin account, returns a cv_... API key (shown once)
KEY=$(curl -s -X POST http://localhost:8000/signup \
  -H "content-type: application/json" \
  -d '{"org":"Acme","username":"admin@acme.test","password":"demo1234"}' \
  | python -c 'import sys,json; print(json.load(sys.stdin)["api_key"])')

echo "Your key: $KEY"

Assert a fact:

curl -X POST http://localhost:8000/assert \
  -H "authorization: Bearer $KEY" \
  -H "content-type: application/json" \
  -d '{
    "subject": "Priya",
    "predicate": "lives in",
    "object": "London",
    "valid_from": "2024-06-01"
  }'

Resolve — time- and permission-aware query:

curl -X POST http://localhost:8000/resolve \
  -H "authorization: Bearer $KEY" \
  -H "content-type: application/json" \
  -d '{"query": "where does Priya live?", "as_of": "2026-06-01"}'

Get a profile — everything known about a subject:

curl "http://localhost:8000/profile?subject=Priya" \
  -H "authorization: Bearer $KEY"

Mint a key for a new agent under your tenant:

curl -X POST http://localhost:8000/keys \
  -H "authorization: Bearer $KEY" \
  -H "content-type: application/json" \
  -d '{"name": "agent-a", "labels": []}'

Admin console: open http://localhost:8000/admin in a browser — full governance UI with a live conflict detector, claims graph, audit chain viewer, and reconciliation queue.

Ask UI (non-technical users): open http://localhost:8000/ask — a plain-language interface for asking questions and adding facts, no code required.

Full API reference: every endpoint is documented at http://localhost:8000/docs (OpenAPI/Swagger).


Level 4 — MCP server (Claude, Cursor, any MCP client)

Context Vault ships a full MCP server. Add it to Claude Desktop, Claude Code, or Cursor to give your AI assistant governed, time-aware memory.

Add to your MCP config (Claude Desktop or Cursor):

{
  "mcpServers": {
    "context-vault": {
      "command": "uvx",
      "args": ["--from", "context-vault-ai[mcp]", "context-vault-mcp"]
    }
  }
}

For Claude Code, add this to .mcp.json in your project root.

With an Anthropic API key (enables free-text remember):

{
  "mcpServers": {
    "context-vault": {
      "command": "uvx",
      "args": ["--from", "context-vault-ai[mcp]", "context-vault-mcp"],
      "env": {
        "ANTHROPIC_API_KEY": "sk-ant-..."
      }
    }
  }
}

Tools available to the AI:

Tool What it does
remember Store a fact in free text — the LLM extracts structure and conflict-checks the write
recall Ask a question, get governed, time-correct context back
vault_assert Assert a structured (subject, predicate, object) claim — no API key needed
vault_resolve Raw facts + claim IDs for a specific principal at a point in time
vault_register_principal Set visibility labels for governed sharing across a team
vault_audit_replay Replay exactly what a principal saw at/before a given time

With durable storage (data persists across restarts):

{
  "mcpServers": {
    "context-vault": {
      "command": "uvx",
      "args": ["--from", "context-vault-ai[mcp,self-host]", "context-vault-mcp"],
      "env": {
        "VAULT_STORE": "neo4j",
        "ANTHROPIC_API_KEY": "sk-ant-...",
        "NEO4J_URI": "bolt://localhost:7687",
        "NEO4J_PASSWORD": "vaultpass123",
        "VAULT_PG_DSN": "postgresql://vault:vaultpass123@localhost:5433/vault_audit"
      }
    }
  }
}

The server is also listed on the official MCP registry as io.github.RajdeepDas43/context-vault.


Level 5 — Framework adapters

Drop Context Vault into your existing agent stack as a governed memory backend. All adapters use the same vault_tools(memory) pattern — one line to wire in.

LangGraph / LangChain

pip install "context-vault-ai[langgraph]"
from context_vault import Memory
from context_vault.integrations.langgraph import vault_tools

memory = Memory()
tools = vault_tools(memory)   # returns [vault_remember, vault_recall] as LangChain tools

# Use tools in your LangGraph graph / agent
from langgraph.prebuilt import create_react_agent
agent = create_react_agent(llm, tools)

CrewAI

pip install "context-vault-ai[crewai]"
from context_vault import Memory
from context_vault.integrations.crewai import vault_tools

memory = Memory()
tools = vault_tools(memory)   # returns CrewAI Tool objects

from crewai import Agent, Task, Crew
agent = Agent(role="Researcher", tools=tools, ...)

LlamaIndex

pip install "context-vault-ai[llamaindex]"
from context_vault import Memory
from context_vault.integrations.llamaindex import vault_tools

memory = Memory()
tools = vault_tools(memory)   # FunctionTool objects for LlamaIndex agents

Claude Agent SDK

pip install "context-vault-ai[claude-agent-sdk]"
from context_vault import Memory
from context_vault.integrations.claude_agent_sdk import vault_tools

memory = Memory()
tools = vault_tools(memory)   # Claude Agent SDK tool definitions

Microsoft Agent Framework (AutoGen successor)

pip install "context-vault-ai[agent-framework]"
from context_vault import Memory
from context_vault.integrations.agent_framework import vault_tools

memory = Memory()
tools = vault_tools(memory)   # MAF FunctionTool objects

Each adapter wraps the same governed engine — conflict-checked writes, deny-by-default ACL, time-aware recall — with zero boilerplate.


Level 6 — Full self-hosted deployment (Docker)

The fastest path to a production-grade deployment:

git clone https://github.com/RajdeepDas43/context-graph-vault
cd context-graph-vault

cp .env.example .env
# Edit .env — add ANTHROPIC_API_KEY and set a strong VAULT_ADMIN_KEY

docker compose up -d

This brings up:

  • Neo4j (claim store + vector index) on port 7474 (browser) / 7687 (bolt)
  • Postgres (audit log, principals, sessions) on port 5433
  • Context Vault API on port 8000

Check everything is healthy:

curl http://localhost:8000/ready
# {"ready":true,"neo4j":true,"postgres":true,"embedder":"hash","judge":"heuristic"}

Web interfaces:

  • http://localhost:8000/admin — full governance console (technical)
  • http://localhost:8000/ask — plain-language interface (non-technical staff)
  • http://localhost:8000/console — compliance / audit wizard
  • http://localhost:8000/docs — interactive API documentation

Optional overlays:

# Add Redis for cluster-wide rate limiting (required for multi-replica deployments)
docker compose -f docker-compose.yml -f docker-compose.redis.yml up -d

# Add telemetry (Postgres collector + Metabase dashboard)
docker compose -f docker-compose.yml -f docker-compose.telemetry.yml up -d

Kubernetes / Helm:

helm install context-vault ./deploy/helm/context-vault \
  --set neo4j.auth.password=yourpassword \
  --set vault.adminKey=youradminkey

# With Redis-backed cluster-wide quota (multi-replica deployments)
helm install context-vault ./deploy/helm/context-vault \
  --set redis.enabled=true \
  --set vault.adminKey=youradminkey

The chart ships with HPA, PodDisruptionBudget, NetworkPolicy (default-deny), and ServiceAccount pre-configured. Managed-DB wiring (Neo4j Aura, AWS RDS) is available via --set.

# With opt-in scheduled backups (Neo4j at 01:00, Postgres at 02:00)
helm install context-vault ./deploy/helm/context-vault \
  --set backup.enabled=true \
  --set neo4j.auth.password=yourpassword \
  --set vault.adminKey=youradminkey

For single-tenant / VPC installs, set api.singleTenant=true (maps to VAULT_SINGLE_TENANT=1). See Self-host / VPC pilot guide for the full install runbook including the backup/restore audit-integrity gates.


Level 7 — TypeScript / JavaScript SDK

npm install context-vault-sdk
import { VaultClient } from "context-vault-sdk";

const client = new VaultClient({
  baseUrl: "http://localhost:8000",
  apiKey: "cv_...",    // from POST /signup or POST /keys
});

// Assert a fact
await client.assert({
  subject: "Priya",
  predicate: "account tier",
  object: "Enterprise",
  validFrom: "2024-01-01",
});

// Resolve — time- and permission-aware
const results = await client.resolve({
  query: "what tier is Priya on?",
  asOf: new Date().toISOString(),
});

// Get a full profile
const profile = await client.profile({ subject: "Priya" });

The TypeScript SDK targets the HTTP API and works in Node.js, Deno, and browser environments.


Key concept: Claims and conflict detection

A Claim is the atomic unit. Every fact stored in Context Vault is a Claim:

(subject, predicate, object, valid_from, valid_to, confidence, visibility, provenance)

Example: (Priya, works at, Acme Corp, 2024-01-01, 2025-06-01, 0.95, [team:sales], agent-crm)

What happens when you write a conflicting fact?

Context Vault does not have a simple "conflict / no conflict" binary. On every assert, the new fact is compared against existing ones and classified into exactly one of six relations:

Relation Meaning What happens
CONTRADICTION Two claims are logically incompatible over overlapping time Flagged for human review — never auto-resolved
TEMPORAL_SUPERSESSION A functional fact updated over time (new role, new address) Old fact is closed at today; new fact becomes current
REFINEMENT More specific than an existing claim — both are true Both are kept (branched)
DUPLICATE Restates the same fact Merged — corroboration count incremented
INDEPENDENT Unrelated to existing facts Stored as-is
UNSURE Judge is not confident Flagged — never auto-mutated

Collapsing these into "conflict / no-conflict" is how a memory system silently corrupts itself. Context Vault measures a silent-corruption rate: the percentage of real contradictions or supersessions misclassified as independent or duplicate. The current rate on the 54-case adversarial gold set is 0.0% (Claude judge, sonnet-4-6, 96.3% accuracy).

Time-travel queries. Every resolve query accepts two optional timestamps:

# What was true on March 1st?
resolve("where does Priya live?", as_of="2025-03-01")

# What did we *believe* on March 1st (ignoring later corrections)?
resolve("where does Priya live?", as_of="2025-03-01", known_as_of="2025-03-01")

The second form is "bitemporal" — it reconstructs what the system believed at a past system time, not just what was true in the world. Useful for audits and debugging agent decisions.


Configuration reference

All configuration is via environment variables. The defaults work for local development with the Docker compose stack.

Variable Default Description
VAULT_STORE neo4j Storage backend: neo4j (durable), memory (ephemeral, no deps), sqlite (local file)
ANTHROPIC_API_KEY (none) Enables the Claude LLM judge + free-text extraction. Without it, the safe heuristic judge is used.
NEO4J_URI bolt://localhost:7687 Neo4j connection URI
NEO4J_PASSWORD vaultpass123 Neo4j password
VAULT_PG_DSN postgresql://vault:vaultpass123@localhost:5433/vault_audit Postgres connection string
VAULT_ADMIN_KEY (none) Required to access /admin/* endpoints. Set a strong random value in production.
VAULT_EMBEDDER sentence-transformer Embedding backend: sentence-transformer (semantic) or hash (offline, no extras)
VAULT_TENANT_QUOTA_PER_MIN 0 (off) Per-tenant request quota. 0 = unlimited.
VAULT_QUOTA_BACKEND memory Rate-limit backend: memory (per-replica) or redis (cluster-wide, needs [redis] extra)
VAULT_RESOLVE_CACHE 1 (on) Enable the resolve result cache
VAULT_RESOLVE_CACHE_TTL 30 Cache TTL in seconds
VAULT_TMS_CASCADE 0 (off) Enable the Truth Maintenance System cascade (auto-downgrades derived facts when premises change)
VAULT_HYBRID_FRESH_WEIGHT 0.0 (off) Staleness-aware ranking weight. 0.3 is a good starter value.
VAULT_SINGLE_TENANT 0 (off) Single-tenant mode for VPC/self-host pilots. When 1, GDPR erase scope widens to include the shared global space — only enable for intentional single-tenant installs.
VAULT_AUDIT_ENCRYPTION none Audit encryption: none, postgres-keys (AES-256-GCM), or kms (AWS KMS, STRONG tier)
VAULT_OIDC_ISSUER (none) OIDC issuer URL for SSO (needs [oidc] extra)
VAULT_TSA none RFC 3161 trusted timestamping: none or http (needs [tsa] extra)

Minimal production .env:

ANTHROPIC_API_KEY=sk-ant-...
VAULT_ADMIN_KEY=change-me-to-a-strong-random-string
NEO4J_PASSWORD=change-me
VAULT_PG_DSN=postgresql://vault:change-me@localhost:5433/vault_audit

Architecture

Context Vault is built around a pure core, thin shell principle: logic lives in dependency-free pure functions; storage, HTTP, and CLI are thin wrappers.

Memory façade (remember / recall / forget)
        │
        ▼
   Vault orchestrator  ←──────────────────────────────────────┐
   (assert · resolve · reconcile · decay · audit)             │
        │                                                       │
   ┌────┴──────────────────────────────────┐                   │
   │                                        │               Conflict
   ▼                                        ▼               detector
Neo4j claim store              Postgres audit log          (normalize →
(bitemporal claims,            (hash-chained,               prefilter →
 SUPERSEDES edges,              append-only,                 judge →
 vector index)                  per-tenant Merkle)           decide)

Module map:

Module Description
context_vault/memory.py Memory façade — remember / recall / forget
context_vault/vault.py The five-operation orchestrator
context_vault/conflict/ Conflict detection: normalize → prefilter → tiered judge → 6-way decision
context_vault/store/ Neo4j claim store, bitemporal retrieval, vector index
context_vault/audit/ Postgres append-only hash-chained audit log
context_vault/policy/ Per-claim ACL, deny-by-default
context_vault/reconcile/ Human review queue, trust/confidence/recency policy chain
context_vault/extract/ LLM claim extraction from free text
context_vault/embed/ Embeddings (sentence-transformer + hash fallback)
context_vault/trust.py Source trust, corroboration, confidence scoring
context_vault/quota.py Token-bucket rate limiting (in-process + Redis)
context_vault/http_api.py FastAPI REST API + admin console
context_vault/mcp_server.py MCP stdio server
context_vault/sdk.py In-process Python SDK (VaultClient)
context_vault/http_client.py HTTP Python SDK (HttpVaultClient)
context_vault/cli.py CLI (context-vault command)
context_vault/integrations/ Framework adapters (LangGraph, CrewAI, LlamaIndex, Claude Agent SDK, MAF)
sdk-ts/ TypeScript SDK (context-vault-sdk on npm)
frontend/ Product web app (React + Vite + TypeScript)
deploy/helm/ Kubernetes Helm chart (HPA, PDB, NetworkPolicy, ServiceAccount)

CLI reference

# Start the HTTP API + admin console
context-vault serve --port 8000

# Run the interactive offline demo
context-vault demo

# Assert a fact from the command line
context-vault assert \
  --principal agent-a \
  --subject Priya \
  --predicate "lives in" \
  --object London \
  --api-key cv_...

# Resolve — time-aware query
context-vault resolve \
  --principal agent-a \
  --query "where does Priya live?" \
  --as-of 2026-06-01 \
  --api-key cv_...

# Register a principal with visibility labels
context-vault register-principal \
  --id agent-a \
  --labels "team:sales" \
  --api-key cv_...

# Check telemetry (what would be sent — no network call)
context-vault telemetry --send --dry-run

Links


Context Vault is MIT licensed. Built for the teams that need to know not just what their agents know, but what they were allowed to know, and prove it.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

context_vault_ai-0.5.0.tar.gz (4.7 MB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

context_vault_ai-0.5.0-py3-none-any.whl (383.3 kB view details)

Uploaded Python 3

File details

Details for the file context_vault_ai-0.5.0.tar.gz.

File metadata

  • Download URL: context_vault_ai-0.5.0.tar.gz
  • Upload date:
  • Size: 4.7 MB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for context_vault_ai-0.5.0.tar.gz
Algorithm Hash digest
SHA256 f703df2588af99d609f22577340b9ba92b0356d3787ef8fb76838fc1b108ae74
MD5 7c1f2339500f222cc6c536c60db177a6
BLAKE2b-256 a1f8d53a6e4fddf5b020c01786db93469b82b08ab710cb3fef8d520718c5d6ea

See more details on using hashes here.

File details

Details for the file context_vault_ai-0.5.0-py3-none-any.whl.

File metadata

File hashes

Hashes for context_vault_ai-0.5.0-py3-none-any.whl
Algorithm Hash digest
SHA256 92c0f9050bc0857e42c065be4822d4138c1a41aefd6b2b7019f546fcfc8368df
MD5 f76b26c0b63cd12ce17b5d927cd7cecd
BLAKE2b-256 9d5673c00834f333da447a81cf6d77ffd65dfd9d6c75076f06015c9a2d223862

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page