Skip to content

About

MCP prototype that checks agent memory for stale facts, contradictions, secrets and missing evidence using Cognee.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

4 stars

Watchers

0 watching

Forks

Latest commit

Β 

History

160 Commits

Folders and files

Repository files navigation

ContextFirewall β€” guardrails for the memory layer

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.


Built on Cognee MCP Backend Frontend CI License: MIT PRs welcome Live

β—† Live console Β· ⚑ MCP endpoint Β· πŸ“– API docs



β–Ά See it work β€” the four Cognee verbs, live

ContextFirewall demo β€” remember, recall, improve, forget on the live console

β–² real console, real Cognee calls (Neo4j Β· Postgres Β· pgvector Β· Qwen2.5-72B) β€” no mocks Β· πŸ”Š narrated walkthrough β€” 60s, with sound β†— Β· silent MP4 β†— Β· 40s brand teaser β†—


The problem

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 deploy command 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.

The four firewall checks
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.


Connect your agent (MCP)

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/mcp

Claude 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-mcp

This 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" } } }

The six tools

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_context before you act, remember durable facts as you learn them, improve_rules when a task is done, and forget_memory to retract anything that should never come back.

Full client setup and privacy notes are in mcp/README.md.


Built on Cognee's full memory lifecycle

remember β†’ recall β†’ improve β†’ forget

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.


Privacy first

  • πŸ”’ 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=1 is set for you when unset). If you ever want to opt back in, set TELEMETRY_DISABLED=0 in your environment β€” see backend/.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.


Architecture

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 a uvx stdio package under mcp/ for laptops whose only dependency is the mcp SDK. 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.

API

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?"}'

Run locally

# 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 dev

For 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.


Configuration

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.

Backend

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.

Frontend

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 demo data β€” and what is real

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 by make 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 β€” "/search sustains 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.

Evidence (real runs, no mocks)

  • The full MCP verb cycle is validated over both transports on real Cognee + Hugging Face: get_trusted_context / audit_context return 6 approved and 4 blocked for exactly the right reasons; remember adds an auditable memory; improve_rules distils real Rule nodes; forget_memory removes from graph and vector.
  • scripts/mcp_http_probe.py and scripts/mcp_full_probe.py exercise the hosted endpoint; mcp/tests/test_mcp.py covers the stdio path and the protocol handshake.
  • cognify runs live on Qwen2.5-72B; GRAPH_COMPLETION reasons 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: /health reports graph: neo4j, relational: postgres, vector: pgvector.

Roadmap

  • 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 remember calls.
  • Cross-session accumulating memory with the firewall governing the growing graph.
  • Managed Cognee Cloud as a hosting option alongside self-host.

Contributing

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.


Contributors

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.


β—† Open the console Β· ⚑ Connect over MCP Β· πŸ›‘οΈ Source

About

MCP prototype that checks agent memory for stale facts, contradictions, secrets and missing evidence using Cognee.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

4 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages