A production-ready AI agent for automated code review, security vulnerability detection, and code quality analysis using static analysis, LLMs, and security scanning tools.
- 🔍 Automated Code Review - AI-powered PR reviews with inline comments
- 🛡️ Security Scanning - OWASP Top 10, CVE detection
- 🐛 Bug Detection - Logic errors, race conditions, memory leaks
- 📊 Code Quality Metrics - Complexity, maintainability, test coverage
- 🚀 Performance Analysis - Identify bottlenecks and optimizations
- 🔄 CI/CD Integration - GitHub Actions, GitLab CI, Jenkins
- Ollama / CodeLlama - Code understanding and generation
- Semgrep - Static analysis and pattern matching
- Bandit - Python security linting
- ESLint - JavaScript/TypeScript linting
- SonarQube - Code quality platform (optional)
- Trivy - Dependency vulnerability scanning
- FastAPI - REST API
- PostgreSQL - Review history storage
- Redis - Caching and queuing
code-review-agent/
├── src/
│ ├── agent/
│ │ ├── code_reviewer.py # Core review logic
│ │ ├── security_scanner.py # Security vulnerability detection
│ │ ├── quality_analyzer.py # Code quality metrics
│ │ ├── performance_analyzer.py # Performance analysis
│ │ └── llm_reviewer.py # LLM-based review
│ ├── analyzers/
│ │ ├── semgrep_analyzer.py # Semgrep integration
│ │ ├── static_analyzer.py # AST-based analysis
│ │ └── dependency_scanner.py # Dependency vulnerability check
│ ├── api/
│ │ ├── main.py # FastAPI application
│ │ └── webhooks.py # GitHub/GitLab webhooks
│ ├── integrations/
│ │ ├── github.py # GitHub API integration
│ │ ├── gitlab.py # GitLab API integration
│ │ └── ci_cd.py # CI/CD integration
│ └── models/
│ ├── database.py # Review storage
│ └── schemas.py # Pydantic schemas
├── rules/
│ ├── semgrep/ # Custom Semgrep rules
│ ├── security/ # Security check rules
│ └── quality/ # Quality standards
├── tests/
├── requirements.txt
└── docker-compose.yml
- Python 3.10+
- Ollama with CodeLlama (ollama.ai)
- Semgrep (semgrep.dev)
- Docker (optional)
cd code-review-agent
# Create virtual environment
python -m venv venv
source venv/bin/activate
# Install dependencies
pip install -r requirements.txt
# Install Semgrep
pip install semgrep
# Pull Ollama model
ollama pull codellama:13b
# Setup database
createdb code_review_agent
alembic upgrade head
# Configure environment
cp .env.example .env
# Add GitHub/GitLab tokens
# Start services
docker-compose up -d
# Run API server
uvicorn src.api.main:app --reload# Review a single file
python -m code_review_agent review path/to/file.py
# Review entire PR/commit
python -m code_review_agent review-pr --pr 123 --repo owner/repo
# Security scan only
python -m code_review_agent security-scan src/
# Quality analysis
python -m code_review_agent quality-check src/
# Full analysis with report
python -m code_review_agent analyze --output report.htmlPOST /api/v1/review/pr
{
"repo": "owner/repo",
"pr_number": 123,
"comment_inline": true,
"severity_threshold": "medium"
}POST /api/v1/review/code
{
"code": "def unsafe_query(user_input):\n query = f\"SELECT * FROM users WHERE id = {user_input}\"\n return db.execute(query)",
"language": "python",
"context": "database query function"
}POST /api/v1/security/scan
{
"repo": "owner/repo",
"branch": "main",
"scan_dependencies": true
}from code_review_agent import CodeReviewer
# Initialize reviewer
reviewer = CodeReviewer(
model="codellama:13b",
rules=["security", "best-practices", "performance"]
)
# Review code
with open("my_code.py") as f:
code = f.read()
result = reviewer.review(
code=code,
language="python",
context="API endpoint handler"
)
# Print findings
for finding in result.findings:
print(f"\n{finding.severity.upper()}: {finding.title}")
print(f"Line {finding.line_number}: {finding.description}")
print(f"Suggestion: {finding.suggestion}")
if finding.code_snippet:
print(f"\nFixed code:\n{finding.code_snippet}")
# Review metrics
print(f"\nReview Score: {result.score}/100")
print(f"Security Issues: {result.security_issues_count}")
print(f"Quality Issues: {result.quality_issues_count}")from code_review_agent import GitHubReviewer
# Initialize GitHub reviewer
gh_reviewer = GitHubReviewer(token="ghp_xxx")
# Review PR with inline comments
review = gh_reviewer.review_pr(
repo="owner/repo",
pr_number=123,
post_comments=True,
auto_approve_if_clean=True
)
# Summary
print(f"Review Status: {review.status}")
print(f"Issues Found: {review.issues_count}")
print(f"Comments Posted: {review.comments_posted}")name: AI Code Review
on: [pull_request]
jobs:
review:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: AI Code Review
uses: agenticai/code-review-action@v1
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
severity-threshold: medium
post-comments: true
fail-on-high: truecode_review:
stage: test
image: agenticai/code-review-agent:latest
script:
- code-review-agent review-mr --mr $CI_MERGE_REQUEST_IID
only:
- merge_requestsDetects:
- SQL Injection - Unsafe database queries
- XSS (Cross-Site Scripting) - Unsafe HTML rendering
- CSRF - Missing CSRF protection
- Command Injection - Unsafe shell command execution
- Path Traversal - Unsafe file operations
- Hardcoded Secrets - API keys, passwords in code
- Weak Cryptography - Insecure algorithms (MD5, DES)
- Authentication Issues - Weak auth, missing checks
- Authorization Issues - Missing access controls
- Insecure Deserialization
- Known CVEs - In dependencies
Analyzes:
- Complexity - Cyclomatic complexity, cognitive complexity
- Maintainability - Code smells, duplication
- Test Coverage - Unit test coverage gaps
- Code Style - PEP 8, ESLint, etc.
- Documentation - Missing docstrings, comments
- Best Practices - Language-specific patterns
- Error Handling - Missing try-catch, error cases
- Type Safety - Type hints, null checks
Identifies:
- N+1 Queries - Database query optimization
- Memory Leaks - Unclosed resources, circular references
- Inefficient Algorithms - O(n²) where O(n log n) possible
- Unnecessary Computation - Redundant calculations
- Resource Contention - Race conditions, deadlocks
- Blocking Operations - Sync calls in async code
LLM reviews for:
- Logic Errors - Bugs in business logic
- Edge Cases - Unhandled scenarios
- API Design - RESTful best practices
- Naming - Variable and function naming
- Architecture - Design patterns, SOLID principles
- Readability - Code clarity and structure
- security-critical: OWASP Top 10, CWE Top 25
- security-standard: Common security issues
- quality-high: Strict quality standards
- quality-standard: Balanced quality checks
- performance: Performance optimizations
- best-practices: Language-specific best practices
Create custom Semgrep rules:
# rules/custom/no-eval.yaml
rules:
- id: no-eval-usage
pattern: eval(...)
message: "Avoid using eval() - security risk"
severity: ERROR
languages: [python, javascript]
metadata:
category: security
cwe: "CWE-95: Improper Neutralization of Directives"Apply custom rules:
reviewer = CodeReviewer(
custom_rules_dir="./rules/custom"
)Edit .env:
# Ollama
OLLAMA_HOST=http://localhost:11434
OLLAMA_MODEL=codellama:13b
# GitHub Integration
GITHUB_TOKEN=ghp_xxx
GITHUB_WEBHOOK_SECRET=your_secret
# GitLab Integration
GITLAB_TOKEN=glpat-xxx
GITLAB_WEBHOOK_SECRET=your_secret
# Database
DATABASE_URL=postgresql://user:pass@localhost/code_review
# Redis
REDIS_URL=redis://localhost:6379/0
# Review Settings
SEVERITY_THRESHOLD=medium
MAX_FINDINGS_PER_REVIEW=50
AUTO_FIX_ENABLED=false
POST_INLINE_COMMENTS=true
# Security Scanning
ENABLE_DEPENDENCY_SCAN=true
ENABLE_SECRET_SCAN=true
TRIVY_ENABLED=true
# SonarQube (optional)
SONAR_HOST=http://localhost:9000
SONAR_TOKEN=your_token{
"summary": {
"total_findings": 12,
"critical": 2,
"high": 3,
"medium": 5,
"low": 2,
"score": 68
},
"findings": [
{
"id": "sql-injection-001",
"severity": "critical",
"category": "security",
"title": "SQL Injection Vulnerability",
"description": "Unsafe SQL query with user input",
"file": "api/users.py",
"line": 45,
"code": "query = f\"SELECT * FROM users WHERE id = {user_id}\"",
"suggestion": "Use parameterized queries",
"fixed_code": "query = \"SELECT * FROM users WHERE id = %s\"\ndb.execute(query, (user_id,))",
"references": ["CWE-89", "OWASP A03:2021"]
}
]
}Beautiful HTML reports with:
- Executive summary
- Findings by severity
- Code snippets with highlights
- Fix suggestions
- Trend charts
GitHub-flavored markdown for PR comments.
- Single file review: 2-5 seconds
- PR review (10 files): 15-30 seconds
- Full repository scan: 2-10 minutes (depends on size)
- Security scan: 30-60 seconds
- Dependency scan: 10-20 seconds
Automatically fix certain issues:
reviewer = CodeReviewer(auto_fix=True)
result = reviewer.review_and_fix(
code=code,
fix_categories=["formatting", "imports", "simple-security"]
)
# Get fixed code
fixed_code = result.fixed_codeReview only changed lines (faster for PRs):
result = reviewer.review_diff(
base_commit="abc123",
head_commit="def456",
repo_path="."
)Train the agent on your team's preferences:
# Mark false positive
reviewer.mark_false_positive(finding_id="fp-001")
# Mark as accepted pattern
reviewer.accept_pattern(
pattern="using_specific_library",
reason="Company standard"
)# Run all tests
pytest tests/
# Test specific analyzer
pytest tests/test_security_scanner.py
# Test with sample code
pytest tests/ --code-samples=samples/- Support more languages (Rust, Go, Kotlin)
- Machine learning model training on codebase
- IDE plugins (VS Code, IntelliJ)
- Team analytics dashboard
- Custom rule marketplace
- Auto-refactoring suggestions
See CONTRIBUTING.md
MIT License - see LICENSE
- Documentation: useagenticai.in
- Issues: GitHub Issues
- Email: info@useagenticai.in
Built with ❤️ by the AgenticAI team