# ContextGraph

> Shared memory bus for MCP-compatible agents with permissions, subscriptions, and optional payments.

- **Type:** MCP server
- **Install:** `agentstack add mcp-allenmaxi-contextgraph`
- **Verified:** Yes — security-reviewed for prompt injection and unsafe behavior
- **Seller:** [AllenMaxi](https://agentstack.voostack.com/s/allenmaxi)
- **Installs:** 0
- **Category:** [Databases](https://agentstack.voostack.com/c/databases)
- **Latest version:** 0.1.0
- **License:** MIT
- **Upstream author:** [AllenMaxi](https://github.com/AllenMaxi)
- **Source:** https://github.com/AllenMaxi/ContextGraph

## Install

```sh
agentstack add mcp-allenmaxi-contextgraph
```

Requires the [AgentStack CLI](https://agentstack.voostack.com/docs/cli). Works with Claude Code, Cursor, and any MCP-compatible agent.

## 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 &middot;
  Context Compiler &middot;
  Use Cases &middot;
  Demo &middot;
  Quickstart &middot;
  SDK &middot;
  CLI &middot;
  More Use Cases &middot;
  Docs

  English &middot; Espa&ntilde;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:

1. run the 2-minute setup in [`examples/beta_quickstart.py`](examples/beta_quickstart.py)
2. run the coding-agent continuity demo in [`examples/reactive_delta_compaction_demo.py`](examples/reactive_delta_compaction_demo.py)
3. inspect the generated `.contextgraph/` folder from that demo to see resume prompts, open tasks, failures, and branch/cache metadata
4. run the governed retrieval demo in [`examples/context_pack_demo.py`](examples/context_pack_demo.py)
5. integrate with Claude Code via [`docs/claude-code-integration.md`](docs/claude-code-integration.md)
6. skim the hook protocol in [`docs/reactive-delta-compaction.md`](docs/reactive-delta-compaction.md)
6. 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

```python
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.”

```python
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:

```python
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.json`
- `latest_delta_pack.json`
- `doctor.json`
- `resume_prompt.md`
- `restoration_instructions.md`
- `decisions.md`
- `constraints.md`
- `open_tasks.md`
- `failures.md`
- `changed_files.md`
- `important_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`

```python
client.sync_memory_directory(
    agent["agent_id"],
    branch["session_id"],
    workspace_path="/path/to/repo",
)
```

```bash
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.

```python
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:**

1. Retrieves candidate claims via repository-native BM25 search
2. Applies ACL, freshness, trust, curation, and payment filters per agent
3. Deduplicates near-exact claims (Jaccard >= 0.88)
4. Detects conflicts using existing sentinel dispute signals
5. Truncates to fit the token budget (word_count * 1.3 estimation)
6. Builds an extractive summary from top claims
7. Returns different packs to different agents from the same corpus

**Three agents, same corpus, different packs:**

```python
# 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=True` and empty statements
- **Extractive summaries**: top claim statements are stitched into a `summary` field within 20% of the token budget
- **Full explanations**: `include_explanations=True` returns inclusion/exclusion reasons, conflict pairs, and filter counts
- **Immutable snapshots**: compiled packs are persisted and retrievable via `get_context_pack()` and `explain_context_pack()`
- **REST, SDK, and MCP**: available as `POST /v1/context/compile`, `client.compile_context()`, and `contextgraph_compile_context` MCP tool

### Extended Memory Model
- **Memory** gains optional `source_type`, `source_uri`, `source_label`, `section_refs`, and `ingest_metadata` fields for richer source tracking
- **Claim** gains optional `source_memory_section` for 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()`, and `update_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 `/memories` filesystem

See the integration guide: [`docs/anthropic-memory-tool.md`](docs/anthropic-memory-tool.md)  
Run the example: [`examples/anthropic_memory_tool.py`](examples/anthropic_memory_tool.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 |

```python
# 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"])
```

```bash
# 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(...)` or `POST /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

```python
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.

## Pricing

- **Free** — Free

## Security capabilities

Automated source analysis of v0.1.0 — what this tool can access:

- **Network access:** yes
- **Filesystem access:** no
- **Shell / process execution:** no
- **Environment & secrets:** no
- **Dynamic code execution:** no

*"Yes" means the capability is present in the source — more access means more to trust, not that it is unsafe.*


## Versions

- **0.1.0** — security scan: passed — Imported from the upstream source.

## Links

- Listing page: https://agentstack.voostack.com/l/mcp-allenmaxi-contextgraph
- Seller: https://agentstack.voostack.com/s/allenmaxi
- Browse the marketplace: https://agentstack.voostack.com/browse

---
Listed on AgentStack — the marketplace for AI agent skills and MCP servers. Every listing is security-reviewed. Creators keep 70%.
