Skip to main content

AI IDE security hook: blocks directories, scans secrets, and protects AI interactions

Project description

AI Guardian

AI IDE security hook: controls MCP/skill permissions, blocks directories, scans secrets

License Python 3.9+

Status: ๐Ÿ”’ Private Development

AI Guardian provides comprehensive protection for AI IDE interactions through multiple security layers.

Quick Start

# 1. Install Gitleaks (macOS)
brew install gitleaks

# 2. Install AI Guardian
git clone https://github.com/itdove/ai-guardian.git
cd ai-guardian
pip install -e .

# 3. Configure Claude Code hooks
# Add to ~/.claude/settings.json - see Configuration section below

# 4. (Optional) Set up MCP/Skill permissions
mkdir -p ~/.config/ai-guardian
cp ai-guardian-example.json ~/.config/ai-guardian/ai-guardian.json
# Edit the file to allow your specific skills and MCP servers

Features

๐Ÿ›ก๏ธ Directory Blocking

Block AI access to sensitive directories using .ai-read-deny marker files:

  • Recursive protection (blocks directory and all subdirectories)
  • Fast performance (file existence check only)
  • Clear error messages indicating protected paths
# Protect credentials
cd ~/.ssh && touch .ai-read-deny
cd ~/.aws && touch .ai-read-deny

# Protect secrets
cd ~/project/secrets && touch .ai-read-deny

๐Ÿ”’ Secret Scanning

Multi-layered secret detection before AI interactions:

  • Prompt scanning: Check user prompts before sending to AI
  • File scanning: Verify files before AI reads them
  • Powered by Gitleaks - industry-standard scanner
  • Comprehensive pattern detection (API keys, tokens, private keys, etc.)

๐ŸŽ›๏ธ MCP Server & Skill Permissions

Control which MCP servers and skills Claude Code can use with fine-grained allow/deny lists:

Security Model - Defense in Depth:

ai-guardian provides enterprise-level enforcement that works alongside Claude Code's built-in settings.json permissions:

Layer Controls Can be bypassed? Use case
settings.json Built-in tools, MCP, Subagents Yes (user can edit) User/project preferences
ai-guardian Skills, MCP, Built-ins No (remote policies) Enterprise enforcement

Why use both:

  • โœ… Remote enforcement - Centrally managed policies that users can't bypass
  • โœ… Dynamic updates - Change enterprise restrictions without touching local configs
  • โœ… Skills support - Only place to control Skills (not in settings.json)
  • โœ… Auto-discovery - GitHub/GitLab skill directories
  • โœ… Unified management - One config for all tool types

Default Security Posture:

  • โœ… Built-in tools (Read, Write, Bash): Managed by settings.json, can be restricted by ai-guardian
  • โœ… MCP Servers: Managed by settings.json, can be restricted by ai-guardian
  • ๐Ÿšซ Skills: Blocked by default (must be explicitly allowed via ai-guardian)

Features:

  • Matcher-based rules: Each tool type has its own allow/deny lists
  • Pattern-based matching: daf-*, mcp__notebooklm-mcp__notebook_*
  • Block dangerous patterns: *rm -rf*, /etc/*
  • Auto-discover skills from GitHub/GitLab directories
  • Local filesystem skill discovery
  • Remote policy configuration (enterprise/team policies)
  • Multi-level config: project โ†’ user โ†’ remote

Example Configuration (~/.config/ai-guardian/ai-guardian.json):

{
  "permissions": [
    {
      "matcher": "Skill",
      "mode": "allow",
      "patterns": ["daf-*", "gh-cli"]
    },
    {
      "matcher": "mcp__*",
      "mode": "allow",
      "patterns": ["mcp__notebooklm-mcp__notebook_*"]
    }
  ],
  "_comment": "Optional: Use permissions_directories for dynamic discovery (advanced)",
  "_comment2": "Recommended: Use remote_configs instead (see below)",
  "remote_configs": {
    "urls": [
      {
        "url": "https://example.com/enterprise-policy.json",
        "enabled": true
      }
    ]
  }
}

Permission Rule Format:

  • Each rule has a matcher (which tools it applies to)
  • A mode ("allow" or "deny")
  • A list of patterns to match
  • Precedence: All "deny" rules checked first (from any config source), then "allow" rules

Defense in Depth:

Claude Code's settings.json permissions provide user-level control for built-in tools and MCP servers. ai-guardian adds enterprise-level enforcement on top:

  • settings.json: User/project preferences (can be edited locally)
  • ai-guardian remote policies: Enterprise restrictions (cannot be bypassed)
  • Skills: Only controlled by ai-guardian (not in settings.json)

Use ai-guardian to add Bash/Write/MCP matchers for centrally managed restrictions that complement settings.json permissions.

Setup: See Configuration โ†’ MCP Server & Skill Permissions section below for detailed setup instructions.

Managing Permissions:

  • โœ… Recommended: Use remote_configs to fetch complete policy from URL (easier to manage)
  • โš ๏ธ Advanced: Use permissions_directories for dynamic discovery from GitHub/GitLab (local dev only)

See ai-guardian-example.json for full documentation and more examples.

๐ŸŽฏ Multi-IDE Support

IDE Prompt Scanning File Scanning Status
Claude Code CLI โœ… โœ… Full support
VS Code Claude โœ… โœ… Full support
Cursor IDE โœ… โœ… Full support

Auto-detects IDE type and uses the appropriate response format.

Requirements

  • Python 3.9 or higher
  • Gitleaks 8.x - Open-source secret scanner

Installing Gitleaks

macOS:

brew install gitleaks

Linux:

VERSION=8.18.1
wget "https://github.com/gitleaks/gitleaks/releases/download/v${VERSION}/gitleaks_${VERSION}_linux_x64.tar.gz"
tar -xzf "gitleaks_${VERSION}_linux_x64.tar.gz"
sudo mv gitleaks /usr/local/bin/

Windows:

choco install gitleaks
# Or download from: https://github.com/gitleaks/gitleaks/releases

Verify:

gitleaks version

Installation

Basic Installation:

git clone https://github.com/itdove/ai-guardian.git
cd ai-guardian
pip install -e .

With Skill Discovery (Optional):

For auto-discovering skills from GitHub/GitLab directories:

pip install -e ".[skill-discovery]"

This installs the optional requests library for fetching remote skill directories.

When to Use ai-guardian vs settings.json

Scenario Use settings.json Use ai-guardian Why
Control Skills โŒ Not supported โœ… Required Skills not available in settings.json
User MCP preferences โœ… Recommended โŒ Optional User can manage locally
Enterprise MCP restrictions โš ๏ธ User can bypass โœ… Required Remote policies cannot be bypassed
Built-in tool restrictions โœ… First choice โš ๏ธ For extras settings.json is the standard way
Enterprise built-in restrictions โš ๏ธ User can bypass โœ… Required Add restrictions beyond settings.json
Auto-discover skills โŒ Not supported โœ… Use this GitHub/GitLab directory discovery
Dynamic enterprise policies โŒ Static files โœ… Use this Remote configs auto-refresh

Recommended Architecture:

settings.json: User/project preferences for MCP and built-in tools
      โ†“
ai-guardian: Skills (required) + enterprise enforcement layer
      โ†“
Remote policies: Centrally managed, cannot be bypassed

Configuration

Claude Code

Add to ~/.claude/settings.json:

{
  "hooks": {
    "UserPromptSubmit": [
      {
        "matcher": "*",
        "hooks": [
          {
            "type": "command",
            "command": "ai-guardian",
            "statusMessage": "๐Ÿ›ก๏ธ Scanning prompt..."
          }
        ]
      }
    ],
    "PreToolUse": [
      {
        "matcher": "*",
        "hooks": [
          {
            "type": "command",
            "command": "ai-guardian",
            "statusMessage": "๐Ÿ›ก๏ธ Checking tool permissions..."
          }
        ]
      }
    ]
  }
}

Cursor IDE

Create ~/.cursor/hooks.json:

{
  "version": 1,
  "hooks": {
    "beforeSubmitPrompt": [
      {
        "command": "ai-guardian"
      }
    ],
    "beforeReadFile": [
      {
        "command": "ai-guardian"
      }
    ]
  }
}

MCP Server & Skill Permissions (Optional)

Control which MCP servers and skills Claude Code can access. This is optional - by default, built-in tools are allowed and Skills/MCP are blocked.

Step 1: Create Configuration Directory

mkdir -p ~/.config/ai-guardian

Step 2: Create Configuration File

Create ~/.config/ai-guardian/ai-guardian.json:

# Copy the example configuration
curl -o ~/.config/ai-guardian/ai-guardian.json \
  https://raw.githubusercontent.com/itdove/ai-guardian/main/ai-guardian-example.json

# Or create manually with your editor
vi ~/.config/ai-guardian/ai-guardian.json

Step 3: Configure Permissions

Basic Configuration (Skills and Optional MCP Restrictions):

Essential for Skills (required), optional for adding enterprise-level MCP restrictions beyond settings.json:

{
  "permissions": [
    {
      "matcher": "Skill",
      "mode": "allow",
      "patterns": ["daf-*", "gh-cli"]
    },
    {
      "_comment": "Optional: Enterprise MCP restrictions (complements settings.json)",
      "matcher": "mcp__*",
      "mode": "allow",
      "patterns": ["mcp__notebooklm-mcp__notebook_*"]
    }
  ]
}

Note: MCP and built-in tools can be controlled via settings.json permissions. Add them to ai-guardian for enterprise enforcement via remote policies.

Enterprise Configuration (with additional restrictions and auto-discovery):

Enterprise policies can add extra restrictions on built-in tools beyond what settings.json provides.

{
  "permissions": [
    {
      "matcher": "Skill",
      "mode": "allow",
      "patterns": ["daf-*", "gh-cli", "git-cli"]
    },
    {
      "matcher": "mcp__*",
      "mode": "allow",
      "patterns": [
        "mcp__notebooklm-mcp__notebook_list",
        "mcp__notebooklm-mcp__notebook_get",
        "mcp__atlassian__getJiraIssue"
      ]
    },
    {
      "_comment": "Enterprise-level restrictions (optional)",
      "matcher": "Bash",
      "mode": "deny",
      "patterns": ["*rm -rf*", "*dd *"]
    },
    {
      "matcher": "Write",
      "mode": "deny",
      "patterns": ["/etc/*", "/sys/*"]
    }
  ],
  "permissions_directories": {
    "allow": [
      {
        "url": "https://github.com/your-org/skills/tree/main/skills",
        "category": "Skill",
        "token_env": "GITHUB_TOKEN"
      }
    ]
  }
}

When a Tool is Blocked

When ai-guardian blocks a skill or MCP tool, it shows a helpful error message with the exact configuration to add:

======================================================================
๐Ÿšซ TOOL ACCESS DENIED
======================================================================

Tool: Skill
Blocked by: not in allow list

To allow this tool, add to ~/.config/ai-guardian/ai-guardian.json:

  {
    "permissions": [
      {
        "matcher": "Skill",
        "mode": "allow",
        "patterns": [
          "*"  # Allow all skills
        ]
      }
    ]
  }

Or ask your administrator to update the enterprise policy.
======================================================================

Quick fix: Copy the suggested configuration from the error message and add it to your ai-guardian.json file.

Configuration Locations (Precedence Order)

  1. Project config (highest priority): ./.ai-guardian.json in project root
  2. User config: ~/.config/ai-guardian/ai-guardian.json
  3. Remote configs: Fetched from URLs in remote_configs
  4. Defaults: Built-in defaults (allow all built-ins, block skills/MCP)

Remote Configs vs Directory Discovery

Use remote_configs (Recommended):

{
  "remote_configs": {
    "urls": [{
      "url": "https://your-org.com/ai-guardian-policy.json",
      "enabled": true
    }]
  }
}

Benefits:

  • โœ… Complete control - permissions, deny rules, everything in one place
  • โœ… Easier to audit - clear list of what's allowed
  • โœ… Faster - no GitHub API calls or directory scanning
  • โœ… Works for all tool types - not just Skills
  • โœ… Better for production/enterprise

Use permissions_directories (Advanced/Local Dev):

{
  "permissions_directories": [
    {
      "matcher": "Skill",
      "mode": "allow",
      "url": "https://github.com/your-org/skills/tree/main/skills",
      "token_env": "GITHUB_TOKEN"
    }
  ]
}

Use cases:

  • โš ๏ธ Local development with file-based skill directories
  • โš ๏ธ Dynamic environments where you can't pre-list skills
  • โš ๏ธ Prototyping before creating a formal remote policy

For most users: Use remote_configs and maintain a complete policy file.

Pattern Matching Examples

Matcher Pattern Matches Description
Skill gh-cli Exactly gh-cli skill Exact skill name
Skill daf-* daf-active, daf-status, etc. All skills starting with daf-
mcp__* mcp__notebooklm-mcp__notebook_* All notebook tools Wildcard MCP tools
Bash *rm -rf* Any bash command containing rm -rf Dangerous command patterns
Write /etc/* Any write to /etc directory Path-based blocking

How matching works:

  • Skill matcher checks patterns against input.skill value
  • Bash matcher checks patterns against input.command value
  • Write/Read matchers check patterns against input.file_path value
  • mcp__* matcher checks patterns against full tool name

Verify Configuration

Test that your configuration is loaded correctly:

# This will be blocked if Skills are not in your allow list
echo '{"hook_event_name": "PreToolUse", "tool_use": {"name": "Skill:unknown-skill"}}' | ai-guardian

# This should be allowed (built-in tool)
echo '{"hook_event_name": "PreToolUse", "tool_use": {"name": "Read"}}' | ai-guardian

Usage

Test the Hook

# Test clean prompt (should pass)
echo '{"prompt": "Hello world"}' | ai-guardian
# Output: โœ“ No secrets detected

# Test with a GitHub token (should block)
echo '{"prompt": "token: ghp_1234567890abcdefghijklmnopqrstuvwxyz"}' | ai-guardian  #notsecret
# Output: ๐Ÿ”’ SECRET DETECTED (exit code 2)

Protect Directories

# Protect your configuration
cd ~/.config && touch .ai-read-deny

# Protect project secrets
cd ~/my-project/secrets && touch .ai-read-deny

# Protect dependencies
cd ~/my-project/node_modules && touch .ai-read-deny

Custom Secret Patterns

Create .gitleaks.toml in your project:

# Allow specific patterns
[allowlist]
description = "Allowed patterns"
regexes = [
    '''example-api-key-12345''',
]
paths = [
    '''tests/fixtures/.*''',
]

# Add custom patterns
[[rules]]
id = "custom-api-key"
description = "Custom API Key Pattern"
regex = '''mycompany_[0-9a-f]{32}'''

See Gitleaks Configuration for more options.

Pattern Server (Advanced)

Optional: Integrate with a custom pattern server for enhanced, auto-updating secret detection rules.

Note: This is an advanced enterprise feature. Most users should use the default Gitleaks patterns or project-specific .gitleaks.toml files.

Configuration (~/.config/ai-guardian/ai-guardian.json):

{
  "pattern_server": {
    "enabled": true,
    "url": "https://your-pattern-server.example.com",
    "patterns_endpoint": "/patterns/gitleaks/8.18.1",
    "auth": {
      "method": "bearer",
      "token_env": "AI_GUARDIAN_PATTERN_TOKEN",
      "token_file": "~/.config/ai-guardian/pattern-token"
    },
    "cache": {
      "path": "~/.cache/ai-guardian/patterns.toml",
      "refresh_interval_hours": 12,
      "expire_after_hours": 168
    }
  }
}

Setup:

# 1. Get your Bearer token from your pattern server's web interface
#    Example: Visit https://your-pattern-server.example.com/token
#    Copy the JWT token provided

# 2. Provide the token (choose ONE method):

# Option A: Environment variable (temporary, session-only)
export AI_GUARDIAN_PATTERN_TOKEN="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."

# Option B: Token file (persistent, recommended)
echo "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." > ~/.config/ai-guardian/pattern-token
chmod 600 ~/.config/ai-guardian/pattern-token

# 3. Enable pattern server in config (see above)

# 4. Patterns will auto-download on first scan

How it works:

  1. AI Guardian checks if patterns need refresh (every 12 hours)
  2. Looks up Bearer token (tries token_env first, then token_file)
  3. Downloads latest patterns from your pattern server using Bearer auth
  4. Caches patterns locally for 7 days
  5. Uses cached patterns if pattern server is unavailable (fail-safe)

Configuration Priority:

  1. Pattern Server (if enabled and available) - highest priority
  2. Project .gitleaks.toml - overrides for specific projects
  3. Default Gitleaks patterns - built-in fallback

Environment Variables

Configure ai-guardian behavior with environment variables:

Variable Description Default
AI_GUARDIAN_IDE_TYPE Override IDE auto-detection (claude or cursor) Auto-detect
AI_GUARDIAN_SKILL_CACHE_TTL_HOURS Skill directory cache TTL in hours 24
AI_GUARDIAN_REFRESH_INTERVAL_HOURS Remote config refresh interval 12
AI_GUARDIAN_EXPIRE_AFTER_HOURS Remote config expiration time 168 (7 days)
AI_GUARDIAN_PATTERN_TOKEN Bearer token for pattern server authentication None

Example:

export AI_GUARDIAN_IDE_TYPE=claude
export AI_GUARDIAN_SKILL_CACHE_TTL_HOURS=48

How It Works

User types prompt / Uses tool
       โ†“
[AI Guardian Hook]
       โ†“
   MCP/Skill check โ”€โ”€โ†’ Not allowed? โ”€โ”€โ†’ BLOCK โŒ
       โ†“ (allowed)
   Directory check? โ”€โ”€โ†’ .ai-read-deny exists? โ”€โ”€โ†’ BLOCK โŒ
       โ†“ (no marker)
   Scan with Gitleaks
       โ†“
   Secret found? โ”€โ”€โ†’ Yes โ”€โ”€โ†’ BLOCK โŒ
       โ†“ (no)
   ALLOW โœ… โ”€โ”€โ†’ Send to AI

Security Design

  • โœ… Fail-open: If scanning errors occur, allows operation (availability over security)
  • โœ… In-memory scanning: Uses /dev/shm on Linux for performance
  • โœ… Secure cleanup: Overwrites temp files before deletion
  • โœ… No logging: Secrets are never logged or stored

Future Plans

  • Integration with leaktk project
  • Web UI for managing policies and blocked directories
  • Policy audit logging and compliance reporting
  • Enhanced pattern matching with regex support

License

Apache 2.0 - see LICENSE file for details.

Acknowledgments


๐Ÿ”’ Private Repository - Will be made public after testing

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

ai_guardian-1.0.0.tar.gz (46.2 kB view details)

Uploaded Source

Built Distribution

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

ai_guardian-1.0.0-py3-none-any.whl (34.4 kB view details)

Uploaded Python 3

File details

Details for the file ai_guardian-1.0.0.tar.gz.

File metadata

  • Download URL: ai_guardian-1.0.0.tar.gz
  • Upload date:
  • Size: 46.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.11

File hashes

Hashes for ai_guardian-1.0.0.tar.gz
Algorithm Hash digest
SHA256 ad4c3b00d3c1cc81e0341ca9548b98330e0253cff1e9a5edf7b1f4f5aa89e688
MD5 1b22e9526c713624aa8d446aa576166e
BLAKE2b-256 6cb853c0e313bcfe7efd59d84c2dbb5ef098dc2334a514a4dfd7f574498b22ba

See more details on using hashes here.

File details

Details for the file ai_guardian-1.0.0-py3-none-any.whl.

File metadata

  • Download URL: ai_guardian-1.0.0-py3-none-any.whl
  • Upload date:
  • Size: 34.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.11

File hashes

Hashes for ai_guardian-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 c0fe1569a38c4c3bcdd48b2ce3d78a2bb1b2f4eaec83440ab00831aa16501a0a
MD5 a1bde141bfe0e3039631d82230ea10c2
BLAKE2b-256 027e9bdc6437cdb86fbb5eb08faaf81727a282f7abe2710c2814787f121e0d23

See more details on using hashes here.

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