Skip to main content

Policy-driven context firewall for AI workflows — scan and redact sensitive data before prompts, logs, or traces leave your environment.

Project description

ContextDuty

The AI context firewall. Stop secrets from reaching any AI tool — before the prompt is assembled.

PyPI version Python 3.10+ License: MIT CI MCP Compatible 273 Tests


What is ContextDuty?

ContextDuty is a local-first security product that prevents secrets, API keys, and PII from leaking into AI coding assistants. It works with every AI tool — Cursor, GitHub Copilot, Claude, Windsurf, Cody, Amazon Q — current and future.

One install. Every AI tool. Zero cloud dependencies.

pip install contextduty
contextduty protect        # blocks secrets from ALL AI tools at once
contextduty proxy start    # intercepts HTTPS traffic to 21 AI APIs

Architecture

flowchart TD
    WS["🗂️  YOUR WORKSPACE\n.env · config.py · keys/ · terraform.tfvars"]

    WS --> L1 & L2 & L3 & L4 & L5

    L1["🛡️  Layer 1 — Workspace Ignore\n────────────────────────\n.cursorignore\n.copilotignore\n.codeiumignore\n.tabnine_ignore\n.amazonq/ignore\n.cody/ignore\n\nBlocks 6 AI tools from\never indexing secret files"]

    L2["🔒  Layer 2 — Git Hook\n────────────────────────\npre-commit scan\n\nBlocks commits that\ncontain secrets before\nthey enter git history"]

    L3["🌐  Layer 3 — HTTPS Proxy\n────────────────────────\n21 AI API endpoints\n\nRedacts secrets from\nrequest bodies in-flight\nbefore they leave machine"]

    L4["🤖  Layer 4 — MCP Server\n────────────────────────\nCursor · Claude · VS Code\n\nScans tool-call responses\nbefore they enter the\nAI context window"]

    L5["⚙️  Layer 5 — CI/CD\n────────────────────────\nGitHub Actions\n\nBlocks PRs that contain\nsecrets — policy-as-code\nenforcement in pipeline"]

    L1 & L2 & L3 & L4 & L5 --> AI

    AI["✅  AI TOOLS — ALL PROTECTED\nCursor · Copilot · Claude · Windsurf · Cody · Amazon Q\nOpenAI · Anthropic · Gemini · Azure OpenAI · and 11 more"]

    style WS fill:#1e1e2e,stroke:#6c6f85,color:#cdd6f4
    style L1 fill:#1e3a5f,stroke:#89b4fa,color:#cdd6f4
    style L2 fill:#1e3a5f,stroke:#89b4fa,color:#cdd6f4
    style L3 fill:#1e3a5f,stroke:#89b4fa,color:#cdd6f4
    style L4 fill:#1e3a5f,stroke:#89b4fa,color:#cdd6f4
    style L5 fill:#1e3a5f,stroke:#89b4fa,color:#cdd6f4
    style AI fill:#1a3a1a,stroke:#a6e3a1,color:#cdd6f4
Layer What it does
1 — Workspace Ignore Generates ignore files for 6 AI tools — secrets never get indexed
2 — Git Hook Pre-commit scan blocks secrets from entering version history
3 — HTTPS Proxy Intercepts 21 AI API endpoints, redacts secrets in-flight
4 — MCP Server Scans tool-call responses before they enter the AI context window
5 — CI/CD Policy-as-code enforcement — PRs with secrets cannot merge

Quick start

# 1. Install
pip install contextduty

# 2. Go to your project root (where .git lives) — all commands run from here
cd your-project/

# 3. Try the interactive demo (20 seconds)
contextduty demo

# 4. Create a policy file
contextduty init

# 5. Block ALL AI tools from reading your secrets
contextduty protect

# 6. Block secrets from entering git history
contextduty install-hooks

# 7. Intercept live AI API calls (requires separate install)
pip install 'contextduty[proxy]'
contextduty proxy setup          # one-time: installs CA cert (needs sudo)
contextduty proxy start          # start intercepting

Note: contextduty install-hooks must be run from your project root (the folder that contains .git/). It will fail if run from a subdirectory.


See it in action

ContextDuty demo — scan, redact, protect, block

Secrets detected → redacted with deterministic masks → commit blocked → AI tools protected.
Run it yourself: contextduty demo


Layer 1 — Universal workspace protection

One command generates ignore files for every AI tool:

$ contextduty protect

────────────────────────────────────────────────────────
  ContextDuty  Universal AI Workspace Protection
────────────────────────────────────────────────────────

    12 file(s) contain secrets/PII

    Written 6 ignore files:

       .cursorignore        Cursor
       .copilotignore       GitHub Copilot
       .codeiumignore       Codeium / Windsurf
       .tabnine_ignore      Tabnine
       .amazonq/ignore      Amazon Q
       .cody/ignore         Sourcegraph Cody

Watch mode — auto-updates when files change:

contextduty protect watch   # runs continuously, updates all 6 ignore files

Future-proof: When a new AI tool launches, we add 3 lines to the registry. Your workspace is instantly protected.


Layer 2 — Pre-commit hook

# Run from your project root (the folder that contains .git/)
cd your-project/
contextduty install-hooks

Every git commit is scanned. If secrets are found, the commit is rejected:

$ git commit -m "add deployment config"

[ContextDuty] BLOCKED: config.py
  aws_key: 1 finding(s)
  openai_key: 1 finding(s)

╔══════════════════════════════════════════════════════════════╗
║  ContextDuty blocked this commit.                           ║
║  Remove or redact them before committing.                   ║
╚══════════════════════════════════════════════════════════════╝

Layer 3 — HTTPS proxy (real-time interception)

The proxy sits between your AI tools and their API endpoints. It intercepts requests to 21 AI API hosts and redacts secrets from the request body before they leave your machine.

# Step 1 — install proxy dependencies (mitmproxy, ~50 packages)
pip install 'contextduty[proxy]'

# Step 2 — one-time CA cert setup (needs sudo, run once per machine)
contextduty proxy setup

# Step 3 — start intercepting
contextduty proxy start

──────────────────────────────────────────────────────
  ContextDuty Proxy
──────────────────────────────────────────────────────

  Listening on   127.0.0.1:8080
  Intercepting   21 AI API endpoints
  Policy         .contextduty.json

What it intercepts:

Provider Endpoints
OpenAI api.openai.com
Anthropic (Claude) api.anthropic.com
Cursor cursor.sh, api2.cursor.sh
GitHub Copilot copilot.github.com, api.githubcopilot.com
Google (Gemini) generativelanguage.googleapis.com, aiplatform.googleapis.com
Azure OpenAI openai.azure.com
Codeium / Windsurf server.codeium.com
Amazon Q codewhisperer.us-east-1.amazonaws.com
Sourcegraph Cody sourcegraph.com
Others Cohere, Mistral, Groq, Together, Perplexity, DeepSeek, Fireworks, Tabnine

Declarative field walker — the proxy knows exactly where each provider puts user content in their JSON payload (messages, context, system prompts) and only scans those fields. Adding a new provider = adding field paths, zero code changes.


Layer 4 — MCP server (Cursor / Claude / VS Code)

ContextDuty runs as an MCP server. When AI agents fetch files or database results via tools, ContextDuty intercepts the response:

// ~/.cursor/mcp.json or ~/.claude/claude_desktop_config.json
{
  "mcpServers": {
    "contextduty": { "command": "contextduty-mcp" }
  }
}
Agent calls:  read_file("customers.json")
Tool returns: {"name": "Jane Smith", "ssn": "123-45-6789"}
ContextDuty:  {"name": "<PERSON_a3f2>", "ssn": "<SSN_b7c1>"}

→ Real values never enter the prompt. Never reach the AI model.

Layer 5 — CI/CD enforcement

# .github/workflows/contextduty.yml
- name: ContextDuty scan
  run: |
    pip install contextduty
    contextduty scan src/ --policy .contextduty.json

With "mode": "block", the pipeline exits non-zero. PR cannot merge.


Jupyter / Colab / Databricks — notebook API

Data scientists who live in notebooks and don't use git still need protection. One import, zero config:

# Cell 1
from contextduty.notebook import guard, redact

# Cell 2 — scan any text before sending to an API
guard("""
    aws_secret_access_key = wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
    db_url = postgres://admin:password123@prod-db:5432/users
""")
# ⚠️ ContextDuty: 2 secret(s) found!
#   • aws_secret: 1 occurrence(s)
#   • postgres_dsn: 1 occurrence(s)

# Cell 3 — get a clean version
clean = redact("db = postgres://admin:secret@prod:5432/app")
# → "db = <POSTGRES_DSN_a1b2c3d4>"
Function What it does
guard(text) Scan + print a visible warning (rich HTML in Jupyter, plain text in terminal)
redact(text) Return text with all secrets replaced by deterministic masks
scan(text) Return structured ScanTextResult for programmatic use

Notebook file scanning.ipynb files are also scanned by contextduty scan, install-hooks, and redact. Cell sources, markdown cells, and cell outputs (including display_data and execute_result) are all covered.

📓 Try the example notebook →


Detection: 43 built-in detectors

Category Detectors
Cloud / Infra aws_key, aws_secret, aws_mfa_serial, gcp_service_account, gcp_api_key, azure_client_secret, azure_storage_key
VCS / CI github_pat, github_oauth, github_app_token, github_refresh_token, gitlab_pat, gitlab_runner_token
Payment stripe_secret, stripe_restricted, stripe_publishable, stripe_webhook, paypal_secret, credit_card
Messaging slack_bot_token, slack_user_token, slack_workspace_token, slack_config_token, twilio_account_sid, twilio_auth_token, sendgrid_key, mailgun_key
AI / ML openai_key, anthropic_key, huggingface_token, cohere_key, replicate_key
Databases postgres_dsn, mysql_dsn, mongodb_dsn, redis_dsn, elasticsearch_dsn, sqlserver_dsn
Generic secrets api_key, generic_secret, private_key_block, certificate_block, pgp_private, bearer_token, jwt_token, basic_auth_url, env_secret
IaC terraform_state_secret, docker_auth, k8s_secret_data
PII email, phone, ssn, passport
Healthcare npi_number, dea_number, icd10_code
Crypto / Web3 ethereum_private_key, bitcoin_private_key_wif, mnemonic_phrase

Deterministic masks: AKIAIOSFODNN7EXAMPLE always becomes <AWS_KEY_1a5d44a2dc> — same value, same mask, everywhere. Audit logs stay correlatable without storing raw secrets.

Custom detectors — add your own regex patterns:

{
  "custom_detectors": {
    "employee_id": "\\bEMP-[0-9]{6}\\b",
    "patient_mrn": "\\bMRN-[0-9]{8}\\b"
  }
}

Policy system

contextduty init   # creates .contextduty.json
{
  "mode": "redact",
  "detectors": ["email", "phone", "aws_key", "openai_key", "github_pat", "db_dsn"],
  "custom_detectors": {},
  "detector_modes": { "aws_key": "block", "openai_key": "block" },
  "allow_patterns": { "email": ["@example\\.com$", "@test\\.internal$"] }
}
Mode Behavior
redact Replace matched values with deterministic masks
warn Log findings, don't modify, don't block
block Exit non-zero — for CI and pre-commit hard stops

Policy layering — team baseline + repo override:

{ "extends": "../../policies/org-baseline.json", "mode": "block" }

Compliance baselines included: policies/soc2-baseline.json, policies/hipaa-baseline.json


Audit dashboard

contextduty dashboard --demo    # try it with synthetic data
contextduty dashboard           # reads ~/.contextduty/audit.jsonl

Local web UI with dark theme: findings by detector, 30-day timeline, blocked commits, developer activity, CSV export. Zero dependencies, all data stays on your machine.


All commands

Command Description
contextduty demo Interactive demo — catches secrets in 20 seconds
contextduty protect Write ignore files for ALL 6 AI tools at once
contextduty protect watch Background daemon, auto-update on file changes
contextduty protect status Show what's protected and what's not
contextduty proxy setup One-time CA cert install
contextduty proxy start Start HTTPS interception proxy
contextduty proxy stop Stop the proxy
contextduty proxy status Check if proxy is running
contextduty cursor setup Cursor-specific workspace protection
contextduty cursor watch Cursor-specific watch mode
contextduty scan <file|dir> Scan and print JSON findings
contextduty redact --in <f> --out <f> Redact file, write clean copy
contextduty install-hooks Install git pre-commit hook
contextduty uninstall-hooks Remove the hook
contextduty dashboard Open local audit dashboard
contextduty report Summarize an audit log
contextduty policy validate Validate and resolve policy file
contextduty init Create default .contextduty.json

Project structure

src/contextduty/
├── config.py              # Centralized paths, env vars, constants
├── engine.py              # Core scan/redact engine (43 detectors, .ipynb support)
├── detectors.py           # Regex detector definitions
├── policy.py              # Policy loading, validation, inheritance
├── cli.py                 # CLI entry point (18 commands)
├── protect.py             # Universal workspace protection
├── cursor.py              # Cursor-specific shortcut
├── notebook.py            # Jupyter/Colab/Databricks API (guard, redact, scan)
├── demo.py                # Interactive demo
├── dashboard.py           # Local audit web UI
├── core/
│   ├── __init__.py        # Public API (lazy imports)
│   └── exceptions.py      # Typed exception hierarchy
├── ui/
│   └── output.py          # NO_COLOR-compliant terminal formatting
├── adapters/
│   └── ide.py             # AI tool registry + ignore file generation
└── proxy/
    ├── scope.py           # 21 AI API hosts (single source of truth)
    ├── interceptor.py     # Declarative JSON field walker
    ├── addon.py           # mitmproxy request handler
    ├── server.py          # Proxy lifecycle (start/stop/daemon)
    ├── ca.py              # CA certificate management
    ├── system.py          # OS proxy configuration
    └── feed.py            # Live terminal feed for interceptions

How it compares

ContextDuty LLM Gateways .gitignore
Blocks AI indexing (Cursor, Copilot, etc.) ✅ 6 tools
Pre-commit secret scanning
HTTPS proxy (intercepts any AI API) ✅ 21 endpoints ✅ (different purpose)
MCP tool-call interception
Runs 100% locally
Policy-as-code Partial
Works offline / air-gapped
Your data sent to third parties Never Sometimes N/A

Local development

git clone https://github.com/SHUBHAGYTA24/contextduty
cd contextduty
pip install -e ".[dev]"
make check    # format + lint + 273 tests

Roadmap

  • 43 built-in detectors
  • Pre-commit hook (contextduty install-hooks)
  • MCP server (Cursor, Claude, VS Code)
  • Directory scanning (contextduty scan src/)
  • Audit dashboard (contextduty dashboard)
  • Per-detector modes and allow patterns
  • Policy layering with extends
  • Interactive demo (contextduty demo)
  • Universal workspace protection (contextduty protect) — 6 AI tools
  • HTTPS proxy intercepting 21 AI API endpoints
  • Declarative field walker (new AI provider = add paths, zero code)
  • Enterprise architecture (config, exceptions, UI, adapters)
  • Published on PyPI (pip install contextduty)
  • Jupyter / Colab / Databricks notebook API (guard, redact, scan)
  • .ipynb file scanning (cells, outputs, display_data)
  • NLP-based PII detection (Presidio integration)
  • VS Code / Cursor extension
  • Prometheus metrics endpoint

License

MIT. Issues and PRs welcome. Open an issue if a detector is missing or misfiring.

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

contextduty-0.2.6.tar.gz (87.3 kB view details)

Uploaded Source

Built Distribution

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

contextduty-0.2.6-py3-none-any.whl (74.1 kB view details)

Uploaded Python 3

File details

Details for the file contextduty-0.2.6.tar.gz.

File metadata

  • Download URL: contextduty-0.2.6.tar.gz
  • Upload date:
  • Size: 87.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.12.8

File hashes

Hashes for contextduty-0.2.6.tar.gz
Algorithm Hash digest
SHA256 f81e13ac64c65982ec3edca127453db4457e8e2cb46fdeff3da6bfbe29bcdeb4
MD5 a7afa957d0f6048a66547b60a2b40762
BLAKE2b-256 7e8da9f3f9f88cd588ef19d22ad696eeaf2f02d7a082cad03a4571714ee4088d

See more details on using hashes here.

Provenance

The following attestation bundles were made for contextduty-0.2.6.tar.gz:

Publisher: publish.yml on SHUBHAGYTA24/contextduty

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file contextduty-0.2.6-py3-none-any.whl.

File metadata

  • Download URL: contextduty-0.2.6-py3-none-any.whl
  • Upload date:
  • Size: 74.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.12.8

File hashes

Hashes for contextduty-0.2.6-py3-none-any.whl
Algorithm Hash digest
SHA256 dbdc6121a5c7fc7fc836bee1fbf9099934115d0bd744df97c9f4761bedbc8b5d
MD5 d3325387f58bd57ee5269200964a35ee
BLAKE2b-256 7cbfe99649d524554ddbc7db70a179f5f3c00fad316be533e7d02b974d3e3c91

See more details on using hashes here.

Provenance

The following attestation bundles were made for contextduty-0.2.6-py3-none-any.whl:

Publisher: publish.yml on SHUBHAGYTA24/contextduty

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

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