A trust firewall for your AI coding agent's memory. Every memory your agent recalls, stores, distils, or forgets flows through Cognee and four firewall checks — so stale, contradicted, secret-bearing, and unsupported memory never reaches the model.
◆ Live console · ⚡ MCP endpoint · 📖 API docs
▲ real console, real Cognee calls (Neo4j · Postgres · pgvector · Qwen2.5-72B) — no mocks · 🔊 narrated walkthrough — 60s, with sound ↗ · silent MP4 ↗ · 40s brand teaser ↗
AI coding agents are getting long-term memory. But memory that is stale, contradicted, leaked, or unproven is worse than no memory — it silently steers the next agent wrong:
- a remembered
deploycommand that changed last week, - a "fix" that was later disproven,
- an API key captured in a transcript,
- a confident claim with no evidence behind it.
Today, all of these flow straight back into the next session's context. ContextFirewall audits every remembered fact before it is reused, and gives you a forget control — dropping into any MCP-capable agent stack in one line.
| Check | A memory is blocked when… |
|---|---|
| 🟡 Staleness / validity | a newer value supersedes it (the deploy target changed) |
| 🔴 Contradiction | a better-supported memory disagrees (the weaker side loses, the winner passes) |
| 🔵 Secret / sensitivity | it carries a credential — redacted at ingest, so it never persists and never reaches the pack |
| 🟢 Evidence / trust | it is unsupported: a low trust score with no evidence recorded in the session |
Only memories that pass all four are assembled into a trusted context pack. The ungoverned raw recall is shown side by side, so you can see exactly what the firewall kept out. A human — or the agent, via forget_memory — can retract any memory; it is deleted from Cognee so it can never resurface.
ContextFirewall is a Model Context Protocol server with two transports and one identical six-tool surface, so it drops into whatever agent you use.
Claude Code — hosted (one line, no install):
claude mcp add --transport http contextfirewall https://himanshukumarjha-contextfirewall.hf.space/mcpClaude Code — local stdio client (uvx, connects to the configured backend):
claude mcp add contextfirewall \
--env CF_API_BASE=https://himanshukumarjha-contextfirewall.hf.space \
-- uvx --from "git+https://github.com/himanshu748/ContextFirewall#subdirectory=mcp" contextfirewall-mcpThis runs the MCP client locally; the example sends requests to the hosted backend. For a self-hosted backend, set CF_API_BASE to its URL. The backend's model and embedding configuration determines where inference runs.
Cursor / Cline / generic (~/.cursor/mcp.json or mcp.json):
{ "mcpServers": { "contextfirewall": { "url": "https://himanshukumarjha-contextfirewall.hf.space/mcp" } } }Windsurf (~/.codeium/windsurf/mcp_config.json) — the key is serverUrl, not url:
{ "mcpServers": { "contextfirewall": { "serverUrl": "https://himanshukumarjha-contextfirewall.hf.space/mcp" } } }| Tool | Cognee verb | What it does |
|---|---|---|
get_trusted_context(task) |
recall | Returns a trusted context pack: only memories that pass all four checks. |
audit_context(task) |
recall | Per-memory verdicts — approved, blocked, the failing check and why, plus the memory_id. |
remember(text, subject, kind) |
remember | Store a durable fact; auditable on the next recall. Secrets are redacted at ingest. |
forget_memory(memory_id) |
forget | Delete a memory from the graph and the vector store so it can never resurface. |
improve_rules() |
improve / memify | Distil reusable Rule nodes from recorded sessions. |
list_coding_rules(query) |
recall | Retrieve the distilled coding rules (CODING_RULES search). |
The loop: call
get_trusted_contextbefore you act,rememberdurable facts as you learn them,improve_ruleswhen a task is done, andforget_memoryto retract anything that should never come back.
Full client setup and privacy notes are in mcp/README.md.
ContextFirewall exercises all four Cognee verbs, and every MCP tool maps onto one. Depth here is the point.
| Verb | How ContextFirewall uses it |
|---|---|
| Remember | cognee.add + cognify build the entity graph from a session transcript, plus a typed Repo → AgentSession → SessionEvent → Memory graph (with supersedes relations) so the firewall has deterministic objects to audit. remember(...) is the single-shot path. |
| Recall | cognee.search (GRAPH_COMPLETION) for the ungoverned baseline, plus vector recall over the memory nodes joined with their graph properties to gather the candidates the firewall audits. |
| Improve | memify distils durable Rule nodes into the coding_agent_rules node set, retrievable via SearchType.CODING_RULES; trust scores are derived from evidence and reinforcement. |
| Forget | governance: a rejected or blocked memory is removed from both the graph and the vector store. |
The graph is load-bearing: staleness rides on temporal supersession, contradiction is adjudicated within a recalled cluster of same-subject memories, and the trusted pack is assembled from typed nodes — not a flat vector list.
- 🔒 Secrets are redacted at ingest, then again on every read. When a session is remembered, any detected credential (API key, DB URI, private key, AWS key, GitLab CI/CD job token, Stripe live secret/restricted key, JWT,
secret=…assignment, high-entropy token) is stripped before it is written to the graph, the vector store, or the cognified transcript. It never persists — and the firewall still blocks the memory it came from. Every read path (/audit,/pack,/graph, recall) redacts again as a second, defense-in-depth layer. - 🧭 Local by default. In dev, Cognee's stores are local files (SQLite + LanceDB + the default graph); by default the model and embeddings still call the Hugging Face router, but point them at a local OpenAI-compatible endpoint (see the Local model option below) and nothing leaves the machine. Managed Neo4j Aura + Supabase pgvector are only for the hosted demo; self-host and your memory graph stays yours.
- 📵 No product telemetry. Cognee's built-in product telemetry is disabled by default (
TELEMETRY_DISABLED=1is set for you when unset). If you ever want to opt back in, setTELEMETRY_DISABLED=0in your environment — seebackend/.env.example. - 🧩 Per-account namespace isolation. An authenticated caller's API key resolves to a private namespace; reads are scoped to that namespace only — your console never mixes in the public sample data. Supabase RLS locks the underlying tables.
- 💻 Local model option. Model and embedding endpoints are env-configurable — point them at a local OpenAI-compatible server (e.g. Ollama) for a fully offline deployment.
See backend/app/firewall/secrets.py for the detector and backend/app/identity.py for namespace resolution.
Claude Code · Cursor · Windsurf · Cline · any MCP client
│
▼
┌──────────────────────────────────────────────────────────────┐
│ MCP server /mcp (streamable HTTP, stateless) │
│ REST API /pack /audit /remember /forget ... │
├──────────────────────────────────────────────────────────────┤
│ one firewall core → 4 checks → trusted pack │
├──────────────────────────────────────────────────────────────┤
│ Cognee = graph + vector + relational store │
└──────────────────────────────────────────────────────────────┘
▲
│
Live console (Next.js / Vercel) ──────────────┘
dev: SQLite · LanceDB · Kuzu graph │ prod: Neo4j Aura · Supabase pgvector
- MCP server — the headline surface, mounted at
/mcp(streamable HTTP, stateless), plus auvxstdio package undermcp/for laptops whose only dependency is themcpSDK. Both expose the same six tools, implemented separately for each transport; the parity test planned in #43 is meant to keep them aligned. - Backend — FastAPI + Cognee SDK (Python 3.12), deployed as a Docker Hugging Face Space. MCP tools and REST endpoints call one firewall/Cognee core — no duplicated logic.
- Model layer — Hugging Face inference router: Qwen2.5-72B-Instruct for graph extraction and contradiction adjudication, BAAI/bge-small-en-v1.5 embeddings (384-dim).
- Storage — env-switched in
bootstrap.py: local stores in dev, Supabase Postgres + pgvector and Neo4j Aura in prod. Identical code. - Frontend — Next.js + Tailwind on Vercel: an interactive force-directed knowledge graph, the Connect view, session replay, and a polling firewall activity feed.
The MCP tools are the primary surface; these REST endpoints back them and power the console.
| Method | Path | Purpose |
|---|---|---|
ANY |
/mcp |
MCP server (streamable HTTP): the six firewall tools |
GET |
/health |
live profile (providers, model) + node counts |
POST |
/pack |
gated trusted context pack (and the ungoverned baseline) |
POST |
/audit |
recall + run the four checks, per-memory verdicts |
POST |
/remember · /ingest |
remember one fact / a recorded session |
POST |
/improve · GET /rules |
distil coding rules (memify) / recall them |
POST |
/forget |
delete a memory from Cognee (governance) |
GET |
/graph · /activity |
knowledge-graph nodes+edges / live firewall feed |
GET |
/sessions/{id}/timeline |
session replay |
POST |
/demo/seed |
ingest the bundled sample session (idempotent) |
Try the trusted pack against the live API:
curl -s -X POST https://himanshukumarjha-contextfirewall.hf.space/pack \
-H 'content-type: application/json' \
-d '{"query": "How do I deploy taskflow-api safely?"}'# Backend
cd backend
uv venv --python 3.12 .venv && uv pip install -r requirements.txt
cp .env.example .env # add your Hugging Face API key
set -a && . ./.env && set +a
PYTHONPATH=. .venv/bin/python scripts/dev_integration.py # end-to-end check on real Cognee
PYTHONPATH=. .venv/bin/uvicorn app.main:app --port 8000 # MCP at /mcp, API at /
# Frontend
cd frontend
npm install
echo "NEXT_PUBLIC_API_URL=http://localhost:8000" > .env.local
npm run devFor local dev you only need a Hugging Face API key; Cognee uses local file stores. Set the Postgres/pgvector/Neo4j variables and the same code externalizes storage.
Every environment variable read by backend/app and frontend/. The backend loads backend/.env (without overriding already-set variables); see backend/.env.example and frontend/.env.local.example. "Prod" means the Hugging Face Space / Vercel deployment with external stores.
| Variable | Default (in code) | Purpose | Dev / Prod |
|---|---|---|---|
HUGGINGFACE_API_KEY |
none | Fallback LLM key when LLM_API_KEY is unset (bootstrap.py, llm.py). |
Both |
LLM_API_KEY |
none; falls back to HUGGINGFACE_API_KEY |
API key for Cognee's LLM and the direct chat client. Without a key, chat raises LLMUnavailable. |
Both (required for LLM features) |
LLM_PROVIDER |
custom |
Cognee LLM provider. | Both |
LLM_MODEL |
openai/Qwen/Qwen2.5-72B-Instruct:novita |
Chat / graph-extraction model, resolved once in app/config.py and shared by Cognee and the direct chat client (llm.py). The openai/ prefix is stripped for the direct client. |
Both |
LLM_ENDPOINT |
https://router.huggingface.co/v1 |
LLM base endpoint for Cognee; the direct chat client derives {LLM_ENDPOINT}/chat/completions from it. |
Both |
LLM_CHAT_ENDPOINT |
{LLM_ENDPOINT}/chat/completions |
Optional explicit full chat-completions URL; overrides the derived one in llm.py. |
Optional |
LLM_INSTRUCTOR_MODE |
markdown_json_mode when LLM_PROVIDER=custom, otherwise unset |
Instructor mode passed to Cognee. | Optional |
EMBEDDING_PROVIDER |
hf_router |
hf_router installs the HF feature-extraction engine; other values fall through to Cognee. |
Both |
EMBEDDING_MODEL |
BAAI/bge-small-en-v1.5 |
Embedding model. | Both |
EMBEDDING_DIMENSIONS |
384 |
Embedding vector size. | Both |
EMBEDDING_API_KEY |
falls back to the resolved LLM key | Key for hf_router embeddings. |
Optional |
EMBEDDING_ENDPOINT |
none (derived from the model) | Override the hf_router embeddings URL. |
Optional |
EMBEDDING_BATCH_SIZE |
16 |
hf_router embedding batch size. |
Optional |
CF_DATA_DIR |
backend/.cf_data (code); /home/user/app/.cf_data (Docker image) |
Root for Cognee's local system/data stores. The Docker image sets this variable explicitly. | Both |
CF_REDACTION_PREVIEW |
prefix+suffix |
Audit-reason preview: prefix+suffix shows the first 4 and last 3 characters and length; prefix shows only the first 4 and length; none shows *** (recommended for privacy). Secrets under 20 characters are always fully masked, and invalid settings fall back to none. The setting never changes the typed redaction markers stored at ingest. |
Both |
ENABLE_BACKEND_ACCESS_CONTROL |
false (set via setdefault) |
Cognee setting; ContextFirewall forces a single-tenant default. | Optional |
CACHING |
false (set via setdefault) |
Cognee session cache. | Optional |
COGNEE_SKIP_CONNECTION_TEST |
true (set via setdefault) |
Skips Cognee's embedding pre-flight. | Optional |
GRAPH_DATABASE_PROVIDER |
none (Cognee default) | Graph store provider, e.g. neo4j. |
Prod |
GRAPH_DATABASE_URL |
"" |
Neo4j URL (only when provider is neo4j). |
Prod |
GRAPH_DATABASE_USERNAME |
neo4j |
Neo4j user. | Prod |
GRAPH_DATABASE_PASSWORD |
"" |
Neo4j password. | Prod |
DB_PROVIDER |
none (SQLite default) | Set to postgres to use Postgres for Cognee's relational store. |
Prod |
DB_HOST |
"" (Cognee); unset disables the API-key store (identity.py) |
Postgres host. Also enables the API-key store in identity.py. |
Prod |
DB_PORT |
5432 |
Postgres port (Cognee + API-key store). | Prod |
DB_NAME |
postgres |
Postgres database (Cognee + API-key store). | Prod |
DB_USERNAME |
"" |
Postgres user (Cognee + API-key store). | Prod |
DB_PASSWORD |
"" |
Postgres password (Cognee + API-key store). | Prod |
VECTOR_DB_PROVIDER |
none (LanceDB default) | Vector store provider, e.g. pgvector. |
Prod |
CF_ADMIN_TOKEN |
none | A matching X-Admin-Token authorizes /reset, lifts the demo-immutability guard for /forget (write and namespace checks still apply), and enables POST /demo/seed?reset=true to wipe all Cognee stores, not just demo data, before reseeding. Without a valid token, /reset returns 403 and demo seeding ignores reset=true. |
Optional |
CF_WRITE_TOKEN |
none | Bearer token granting admin write access to the public namespace when no valid API key is sent. | Optional |
HF_TOKEN in backend/.env.example is not read by the app; only backend/scripts/hf_embed_probe.py uses it as a fallback for HUGGINGFACE_API_KEY.
| Variable | Default (in code) | Purpose | Dev / Prod |
|---|---|---|---|
NEXT_PUBLIC_API_URL |
http://localhost:8000 |
Backend base URL (trailing / stripped). |
Both (set to the Space URL in prod) |
NEXT_PUBLIC_SUPABASE_URL |
none | Supabase project URL for console auth. | Optional |
NEXT_PUBLIC_SUPABASE_ANON_KEY |
none | Supabase anon/publishable key. If either Supabase variable is unset, the console runs read-only and hides the auth UI. | Optional |
The console sends a Content-Security-Policy for its own origin, the configured
backend and Supabase (including its secure WebSocket endpoint), plus clickjacking
and MIME-sniffing protections. Next.js 14's inline hydration scripts currently
require script-src 'unsafe-inline'; production builds do not allow
unsafe-eval. The public landing page also serves robots.txt and sitemap.xml.
The bundled demo is a sample agent session on a fictional taskflow-api repo (FastAPI, Postgres, Redis, Stripe). An agent onboards and picks up a search-latency ticket. The ten memories are clearly-illustrative inputs, engineered so each check is exercised:
- Staleness —
flyctl deploy --remote-only(Feb) is superseded bymake release(Jun). - Contradiction — "JWT access tokens never expire" (trust 0.45) loses to "expire after 15 minutes, use the refresh flow" (verified).
- Secret — an AWS access key in a worker-config note is detected and redacted (
AKIA…PLE). - Evidence — "
/searchsustains 1,000,000 req/s, no caching" is unsupported (trust 0.10) and blocked.
Everything downstream of those inputs is real system output: the verdicts, trust scores, the knowledge graph, the distilled rules, and the trusted pack all come from live Cognee and the live model. No verdict is hard-coded, and no results are fabricated.
- The full MCP verb cycle is validated over both transports on real Cognee + Hugging Face:
get_trusted_context/audit_contextreturn 6 approved and 4 blocked for exactly the right reasons;rememberadds an auditable memory;improve_rulesdistils realRulenodes;forget_memoryremoves from graph and vector. scripts/mcp_http_probe.pyandscripts/mcp_full_probe.pyexercise the hosted endpoint;mcp/tests/test_mcp.pycovers the stdio path and the protocol handshake.cognifyruns live on Qwen2.5-72B;GRAPH_COMPLETIONreasons correctly over the temporal deploy-command change.- Backend unit tests (
backend/tests/) run offline and are executed by CI on every pull request. - Production runs on managed stores:
/healthreportsgraph: neo4j,relational: postgres,vector: pgvector.
- Trust re-weighting over time — reinforce memories that prove correct, decay those that don't.
- Continuous auto-recording of live agent sessions, instead of explicit
remembercalls. - Cross-session accumulating memory with the firewall governing the growing graph.
- Managed Cognee Cloud as a hosting option alongside self-host.
Contributions are welcome — from typo fixes to new firewall checks. Start with
CONTRIBUTING.md for setup, tests, and the project's invariants, then pick an issue
labelled good first issue
or help wanted.
- Code of Conduct
- Security policy — please report vulnerabilities privately
- MIT License
Thanks to these external contributors whose pull requests have been merged into ContextFirewall:
| Contributor | Merged contributions |
|---|---|
| @HarshRajSinghania | Constant-time comparisons for admin and write tokens (#30). |
| @mikemikimike | UTC normalization for mixed memory timestamps (#33). |
| @unvisible789 | Documentation for environment variables and configuration defaults (#34). |
| @dannyward630 | Namespace filtering before graph limits and clearer truncation/error handling (#50). |
| @alanveloper-epam | Full UTC timestamps for remembered facts and staleness regression coverage (#54). |
| @kushkrg | Privacy-safe telemetry defaults (#60) and namespace-safe memory deletion (#61). |
| @jdotc1 | Prevented cross-namespace memory existence disclosure during deletion (#64). |
| @lhjl-j | Safer empty-result recall (#82), correct forget HTTP statuses (#83), and accurate MCP docs (#84). |
| @Kushagra481 | Shared LLM model, API key, and endpoint configuration (#85). |
See the contributors graph and commit history for the full record of contributions.
The demo uses a clearly labeled sample session. Cognee and model integrations run live, and the firewall verdicts shown are genuine system output.
