Install
$ agentstack add mcp-allenmaxi-contextgraph ✓ scanned · ✓ verified, works with Claude Code, Cursor, and more.
Security review
✓ PassedNo issues found. Passed automated security review. · v0.1.0 How review works →
- ✓ Prompt-injection patterns
- ✓ Secret / credential exfiltration
- ✓ Dangerous shell & filesystem operations
- ✓ Untrusted network calls
- ✓ Known-malicious package signatures
What it can access
- ● Network access Used
- ✓ Filesystem access No
- ✓ Shell / process execution No
- ✓ Environment & secrets No
- ✓ Dynamic code execution No
From automated source analysis of v0.1.0. “Used” means the capability is present in the source — more access means more to trust, not that it’s unsafe.
Verified badge
Passed review? Show it. Paste this badge into your README, it links to the public security report.
Reliability & compatibility
Declared compatibility
Compatibility is declared by the source manifest. End-to-end runtime verification is coming, see below.
We're building live execution health for every listing: tool-call success rate, median latency, uptime, and last-checked timestamps, measured, not self-reported. It isn't live yet, so we don't show numbers we can't stand behind.
How agent discovery & health will work →About
ContextGraph
Stop losing agent context. ContextGraph is the memory backend for coding agents and multi-agent teams. Capture durable facts, compile trusted context packs, and make agent state visible with reactive checkpoints and repo-local memory directories.
Reactive Delta · Context Compiler · Use Cases · Demo · Quickstart · SDK · CLI · More Use Cases · Docs
English · Español
Why It Stands Out
Most agent memory tools either store raw text in a vector database or replace long sessions with one lossy summary.
ContextGraph is built for the gap between those two:
- governed shared memory so agents can reuse facts without losing provenance, freshness, or access control
- context packs so agents get token-budgeted, explainable context instead of opaque recall results
- reactive delta compaction so coding agents can checkpoint decisions, open tasks, blockers, and changed files before the context window collapses
- branch-aware context cache so child sessions can reuse shared checkpoint prefixes instead of recompiling everything from scratch
.contextgraph/memory directories so the latest session state is inspectable in the repo, not trapped inside one response payload
If you want memory that is inspectable, team-safe, and useful during real work, this is the wedge.
Start Here
The fastest path to understand the repo is:
- run the 2-minute setup in [
examples/beta_quickstart.py](examples/beta_quickstart.py) - run the coding-agent continuity demo in [
examples/reactive_delta_compaction_demo.py](examples/reactivedeltacompaction_demo.py) - inspect the generated
.contextgraph/folder from that demo to see resume prompts, open tasks, failures, and branch/cache metadata - run the governed retrieval demo in [
examples/context_pack_demo.py](examples/contextpackdemo.py) - integrate with Claude Code via [
docs/claude-code-integration.md](docs/claude-code-integration.md) - skim the hook protocol in [
docs/reactive-delta-compaction.md](docs/reactive-delta-compaction.md) - check the production notes in [
docs/production-readiness.md](docs/production-readiness.md)
Public API note: use ContextGraph from contextgraph_sdk in user code and examples. ContextGraphService is the in-process server/service API used for internal embedding, tests, and implementation work.
Use Cases
- coding agents that need to survive
/compact,/resume, or context-window pressure without losing the plot - support and incident agents that need trusted shared memory across handoffs
- research and analyst flows where provenance and freshness matter as much as retrieval quality
- internal agent platforms where ACLs, review state, and explainability must live in the memory layer
- teams that want a self-hosted memory backend instead of wiring brittle prompt glue around a vector store
Where It Wins
- better than vector-only memory when freshness, provenance, and access control matter
- better than plain chat summaries when coding agents need to resume from structured state
- better than prompt glue when multiple agents or teams need one shared memory backend
Not The Right Fit
- you only need personal memory for one chatbot
- you want a hosted agent runtime or enterprise IAM today
- you mainly want a vector database or generic RAG pipeline
from contextgraph_sdk import ContextGraph
client = ContextGraph.local()
agent = client.register_agent("my-agent", "acme", ["research"])
client.store(agent["agent_id"], "Acme Corp reported 3x latency in EU region.")
hits = client.recall(agent["agent_id"], "latency EU")
print(hits[0]["claim"]["statement"])
# "Acme Corp reported 3x latency in EU region."
What Ships Today
- reactive delta compaction: checkpoint coding sessions from structured events and restore them across compaction boundaries
- branch-aware context cache: fork sessions from a checkpoint and reuse the inherited structured state on each branch checkpoint
- repo-local memory directory: sync the latest durable session state into
.contextgraph/for human review, handoff, and hook-driven workflows - context compiler: compile governed, token-budgeted context packs from mixed agent memory
- governed shared memory: store and recall claims with provenance, freshness, review state, and ACLs
- explainable retrieval: inspect why a claim was included, excluded, locked, or filtered
- Anthropic Memory Tool adapter: use ContextGraph as the governed backend for Claude's API memory tool, with versioned memory snapshots and archival delete semantics
- developer surfaces: dashboard, CLI, Python SDK, HTTP API, and MCP server
- self-hosted backends: in-memory local mode and Neo4j persistence
Broader roadmap note: federation, payments, and protocol positioning remain part of the long-term direction, but the current beta is focused on governed shared memory inside real team workflows.
Reactive Delta Compaction
Reactive Delta Compaction is the flagship feature for coding agents.
Instead of collapsing a long session into one fragile summary, ContextGraph records structured events and compiles delta packs with:
- decisions
- constraints
- open tasks
- failures and resolved items
- changed files and important artifacts
- restoration prompts and instructions
- cache metadata showing whether a checkpoint reused an inherited prefix or fell back to full recomputation
- a repo-local
.contextgraph/directory that makes the current state visible in the workspace
This makes compaction feel more like git diff for agent context than “rewrite the whole conversation and hope.”
Now it also supports branch-aware context cache:
- fork a session from any checkpoint
- inherit the parent checkpoint's reduced state snapshot
- recompute only the new branch events
- expose cache hits, reuse counts, and invalidation reasons in the delta pack
Real use case: payment-service refactor
During a live session, the agent records events like:
- decision: "Keep the public REST API stable"
- constraint: "Do not break SDK compatibility"
- file change:
contextgraph/service.py - failure: "resume-path regression is failing"
- todo: "add migration tests"
When context pressure appears, ContextGraph emits a delta pack instead of a vague summary.
The next turn or next day can resume from:
- the decision that must still hold
- the files that changed
- the test failure that is still open
- the unresolved task list
- a restoration prompt and instructions for the next agent
That is why it feels like git diff for working context, not “summarize and hope.”
from contextgraph_sdk import ContextGraph
client = ContextGraph.local()
agent = client.register_agent("delta-coder", "acme", ["coding"])
session = client.create_session(agent["agent_id"], title="Payments refactor", source="claude-code")
client.record_session_event(agent["agent_id"], session["session_id"], "decision", "Keep the REST API stable.")
result = client.record_session_event(
agent["agent_id"],
session["session_id"],
"context_pressure",
"Only 10 percent of the context window remains.",
metadata={"context_remaining_pct": "10"},
)
print(result["checkpoint"]["checkpoint_id"])
print(result["delta_pack"]["restoration_prompt"])
Branching from a checkpoint is just as direct:
base = client.checkpoint_session(agent["agent_id"], session["session_id"])
branch = client.fork_session(agent["agent_id"], session["session_id"], title="grpc-branch")
client.record_session_event(
agent["agent_id"],
branch["session_id"],
"file_change",
"Updated contextgraph/service.py",
metadata={"path": "contextgraph/service.py"},
)
child = client.checkpoint_session(agent["agent_id"], branch["session_id"])
print(child["cache_status"]) # prefix_hit
print(child["cache_base_checkpoint_id"]) # base checkpoint ID
print(child["reused_event_count"]) # inherited event count
.contextgraph/ Memory Directory
When a session knows its workspace path, ContextGraph can sync the latest state into a repo-local .contextgraph/ directory.
That directory includes:
session.jsonlatest_delta_pack.jsondoctor.jsonresume_prompt.mdrestoration_instructions.mddecisions.mdconstraints.mdopen_tasks.mdfailures.mdchanged_files.mdimportant_artifacts.md
This makes the branch/cache story tangible:
- a coding agent can survive
/compact - another agent can reopen the repo and read the exact open tasks and failures
- a reviewer can inspect which checkpoint a branch inherited from and whether it was a cache
prefix_hit
client.sync_memory_directory(
agent["agent_id"],
branch["session_id"],
workspace_path="/path/to/repo",
)
cg session start --title "Payments refactor" --source claude-code --workspace "$PWD"
cg checkpoint --reason manual
cg memdir sync
ls .contextgraph
Hook adapters and the JSON protocol are documented in [docs/reactive-delta-compaction.md](docs/reactive-delta-compaction.md).
Context Compiler
The context compiler is the hero feature of Memory OS v1. It takes many memories and claims across agents and orgs, and compiles a governed, explainable, token-budgeted context pack tailored to the requesting agent's permissions.
from contextgraph_sdk import ContextGraph
client = ContextGraph.local()
agent = client.register_agent("ops-bot", "acme", ["operations"])
# Store diverse memories
client.store(agent["agent_id"], "Payment service migrating from REST to gRPC for Q2.")
client.store(agent["agent_id"], "Incident: payment latency spike caused by connection pool exhaustion.")
# Compile a context pack
pack = client.compile_context(
agent_id=agent["agent_id"],
query="payment service issues",
token_budget=1000,
include_explanations=True,
)
print(f"Summary: {pack['summary']}")
print(f"Claims: {len(pack['included_claims'])} included, {len(pack['conflicting_claims'])} conflicts")
print(f"Tokens: {pack['tokens_used']} / {pack['token_budget']}")
What the compiler does:
- Retrieves candidate claims via repository-native BM25 search
- Applies ACL, freshness, trust, curation, and payment filters per agent
- Deduplicates near-exact claims (Jaccard >= 0.88)
- Detects conflicts using existing sentinel dispute signals
- Truncates to fit the token budget (word_count * 1.3 estimation)
- Builds an extractive summary from top claims
- Returns different packs to different agents from the same corpus
Three agents, same corpus, different packs:
# Alice (owner) sees private + org + published claims
# Carol (same org) sees org + published claims
# Bob (other org) sees only published claims
alice_pack = client.compile_context(alice_id, "project status", 4000)
carol_pack = client.compile_context(carol_id, "project status", 4000)
bob_pack = client.compile_context(bob_id, "project status", 4000)
# alice_pack has >= carol_pack has >= bob_pack claims
Paid claims appear as locked references:
Cross-org priced claims appear in the pack with locked=True and empty statements. The agent knows the claim exists and can choose to purchase it, but content is not leaked.
Run the full demo: python3 examples/context_pack_demo.py
What's New in v0.5.0
Memory OS v1 — Context Compiler
ContextGraph now ships a context compiler that assembles governed, token-budgeted context packs from mixed agent memory. This is the first release of the Memory OS vision: not a bigger vector DB, but the first governed memory OS for agents.
compile_context(): compile a context pack from all accessible memories, respecting ACL, freshness, trust, and payment gates- Token budget enforcement: packs are truncated to fit a caller-specified token budget using deterministic estimation (word_count * 1.3)
- Near-exact deduplication: claims with Jaccard similarity >= 0.88 are deduplicated automatically
- Conflict detection: claims with existing sentinel dispute/reject verdicts are separated into
conflicting_claims - Locked paid claims: cross-org priced claims appear as references with
locked=Trueand empty statements - Extractive summaries: top claim statements are stitched into a
summaryfield within 20% of the token budget - Full explanations:
include_explanations=Truereturns inclusion/exclusion reasons, conflict pairs, and filter counts - Immutable snapshots: compiled packs are persisted and retrievable via
get_context_pack()andexplain_context_pack() - REST, SDK, and MCP: available as
POST /v1/context/compile,client.compile_context(), andcontextgraph_compile_contextMCP tool
Extended Memory Model
- Memory gains optional
source_type,source_uri,source_label,section_refs, andingest_metadatafields for richer source tracking - Claim gains optional
source_memory_sectionfor section-level provenance - All extensions are additive-only with null defaults — no migration needed, existing data remains valid
Anthropic Memory Tool Adapter
ContextGraph can now act as the governed backend for Anthropic's Claude API Memory tool.
This lets teams keep Claude-compatible memory operations while upgrading the storage layer underneath:
- Versioned memory snapshots: each
/memories/...file is stored as a ContextGraph memory revision instead of a mutable blob - Archival delete semantics: deletes map to curation/archive so provenance is preserved
- Adapter-native provenance: Anthropic-backed memories carry
source_type,source_uri,source_label, and ingestion metadata for traceability - Public SDK surface: the integration uses
store(),memories(),memory(), andupdate_memory_curation()so it works with both local and HTTP clients - Claude-compatible file operations: create, view, insert, replace, rename, and delete stay available through a virtual
/memoriesfilesystem
See the integration guide: [docs/anthropic-memory-tool.md](docs/anthropic-memory-tool.md) Run the example: [examples/anthropic_memory_tool.py](examples/anthropicmemorytool.py)
New API Endpoints
| Endpoint | Method | Description | |---|---|---| | /v1/context/compile | POST | Compile a governed context pack | | /v1/context/{pack_id} | GET | Retrieve a compiled context pack | | /v1/context/{pack_id}/explain | GET | Retrieve a pack with full explanation |
# SDK
pack = client.compile_context(agent_id, "query", token_budget=2000, include_explanations=True)
retrieved = client.get_context_pack(pack["pack_id"])
explained = client.explain_context_pack(pack["pack_id"])
# MCP tool
contextgraph_compile_context(query="deployment status", token_budget=4000)
What's New in v0.4.0
Explainable Recall + Repository-Native Retrieval
Recall now exposes a first-class explanation path and uses repository-backed candidate retrieval instead of scanning the full claim set on every query.
- Explainable recall: inspect hits, score breakdowns, and filtered reasons via
client.explain_recall(...)orPOST /v1/memory/recall/explain - Repository-native candidate search: recall pulls a ranked candidate set from the backend before applying final trust, freshness, and payment checks
- Neo4j hot path: the Neo4j backend now uses full-text claim retrieval with ACL-aware pruning and payment-aware ordering
- Operational trust: explain mode keeps the broader candidate view so operators can still understand why a claim was filtered
from contextgraph_sdk import ContextGraph
client = ContextGraph.local()
agent = client.register_agent("ops-bot", "acme", ["support"])
client.store(agent["agent_id"], "Acme Corp reported API latency due to connection pool exhaustion
…
## Source & license
This open-source MCP server is cataloged on AgentStack and links to its original source — we do not rehost the code.
- **Author:** [AllenMaxi](https://github.com/AllenMaxi)
- **Source:** [AllenMaxi/ContextGraph](https://github.com/AllenMaxi/ContextGraph)
- **License:** MIT
Install and usage instructions live in the source repository linked above.
Reviews
No reviews yet, be the first.
Write a review
Versions
- v0.1.0 Imported from the upstream source.