Code review bot with GitHub
Create an AI-powered bot that analyzes pull requests for security issues, code smells, and style violations
Build an AI-powered code review bot that reads changes from your git repository, analyzes them for security vulnerabilities, code smells, and style issues, then posts general and line-specific review comments to GitHub — requesting changes when it finds problems and approving clean pull requests.
What you'll learn
- Configuring the GitHub provider
- Setting up OAuth for GitHub repositories
- Creating an AI agent that reviews code
- Posting GitHub review comments programmatically
Before you begin
- Review Workforce concepts
- Create API keys
- GitHub account with a repository and at least one PR
- Anthropic API key (Claude Sonnet 4 or newer recommended)
Time to complete: 10-15 minutes
Prerequisites
Before building the code review bot, ensure you have:
-
Metorial setup:
- Active Metorial account at platform.metorial.com
- Project created in your organization
- Metorial API key (generate in Dashboard → Developer → API Keys)
-
GitHub repository:
- Local clone of your GitHub repository
- Repository with write access on GitHub
- At least one pull request for testing
- Admin access to authorize OAuth
-
AI provider:
- Anthropic API key (Claude Sonnet 4 or newer recommended for code analysis)
-
Development environment:
- Node.js 18+ (TypeScript) or Python 3.9+ installed
- Basic knowledge of async/await patterns
Architecture overview
The code review bot workflow:
- Input: User provides local repository path, branch names, and PR number
- Fetch Code Changes: Bot reads git diff locally from your repository
- AI Analysis: Claude analyzes the diff for:
- Security vulnerabilities (SQL injection, XSS, exposed secrets)
- Code smells (duplication, long functions, complexity)
- Style violations (naming, formatting, consistency)
- Best practices (error handling, documentation, testing)
- Post Review: Bot posts the review to GitHub via the GitHub provider:
- Overall summary comment
- Line-specific feedback on issues
- Review decision (approve or request changes)
Tools used: Local git (read code changes) + AI Model (code analysis) + GitHub provider (post reviews)
Step 1: Configure GitHub provider
Configure the GitHub provider from Metorial's catalog to enable your bot to interact with GitHub.
Navigate to provider catalog
In the Metorial Dashboard, go to Providers and search for "GitHub".
Create a GitHub integration
Click the GitHub provider, then click Use Provider → Integration.
Choose the GitHub auth method, create or select auth credentials, and review the tool filters for repository, issue, pull request, and file-content access.
Note your deployment ID
After setup, copy the provider deployment or integration ID shown in the dashboard. You'll need this for OAuth setup and in your bot code.
Info
Save your GitHub provider ID—you'll need it for OAuth setup (Step 2) and in your bot code (Step 3).
Step 2: Set up OAuth authentication
Your code review bot needs permission to access your GitHub repositories.
Install dependencies
Install the Metorial SDK and Anthropic:
Create OAuth session
Run this code to generate the GitHub OAuth URL:
Authorize in browser
- Open the printed OAuth URL in your browser
- Sign in to GitHub if needed
- Review and approve the permissions (the bot needs
reposcope to read PRs and post comments) - You'll be redirected to your callback URL (or see a confirmation page)
Store auth config ID
Save the auth config ID securely. You'll reuse it for all future bot operations without re-authorizing.
For production apps, store auth config IDs in your database per user/repository.
Note
Required OAuth Scopes:
The GitHub provider requires the repo scope for posting reviews, which provides:
- Write access to post review comments and line-specific feedback
- Permission to approve PRs or request changes on your repositories
Note: If you plan to implement webhook-based automation (mentioned in Production Considerations), you may need additional scopes like admin:repo_hook. The basic bot functionality shown in this tutorial only requires repo.
The required scopes are automatically requested when you authorize via the OAuth URL.
Step 3: Build the code review bot
Create the main bot that analyzes pull requests and posts review comments.
What this code does:
- Reads git diff locally from your repository between the base and feature branches
- Creates a provider session with GitHub provider for posting reviews
- Sends the diff to Claude with analysis instructions
- AI analyzes the code and identifies issues
- AI posts review to GitHub using
create_pull_request_reviewtool with findings - Handles multi-step workflow through agentic loop until review is complete
- Handles errors gracefully: If tool calls fail, the AI receives error messages and can retry or adjust its approach
Info
This uses Claude's agentic capabilities—the AI decides which tools to call and when. You don't need to write explicit logic for fetching files, analyzing code, or posting comments.
Step 4: Test with a security issue
Let's test the bot with a PR containing a security vulnerability.
Scenario: Create a test PR with SQL injection vulnerability.
Test PR content (example):
Run the bot:
Expected behavior:
- Bot reads git diff from local repository for PR #123
- AI detects SQL injection vulnerability in the query string
- Bot posts review with:
- General comment: "Found 1 security vulnerability that needs immediate attention."
- Line-specific comment on the SQL query line: "🚨 SQL injection vulnerability detected. User input is directly interpolated into the query. Use parameterized queries instead:
SELECT * FROM users WHERE id = ?with bound parameters."
- Bot submits review with REQUEST_CHANGES status
Note
The bot workflow:
- Reads git diff from your local repository
- Sends diff content to AI for analysis
- AI identifies the security issue in the code
- AI calls
create_pull_request_reviewtool to post review to GitHub withREQUEST_CHANGESstatus and detailed comments
The AI autonomously analyzes code and posts reviews—no manual orchestration needed!
Step 5: Test with clean code
Test the bot with a clean PR to verify the approval workflow.
Scenario: PR with well-written code.
Test PR content (example):
Run the bot:
Expected behavior:
- Bot reads git diff from local repository for PR #124
- AI finds:
- ✓ Proper documentation with JSDoc comments
- ✓ Clear function names following conventions
- ✓ Security-conscious implementation (XSS prevention)
- ✓ No code smells or style violations
- Bot posts review comment: "Code looks excellent! Clean implementation with proper documentation, security considerations, and clear naming. The XSS sanitization is thorough and the email validation regex is appropriate."
- Bot submits review with APPROVE status
Troubleshooting
Common issues and solutions when building your code review bot:
Note
If you encounter errors not covered here, check the Metorial dashboard logs (Monitoring section) to see detailed tool execution traces and error messages. You can also inspect the actual API requests being made.
Advanced customization
Enhance your code review bot with these customizations:
Add company-specific coding standards to the AI prompt (e.g., "all public functions must have JSDoc comments", "use async/await instead of promises").
Customize prompts for different languages:
- Python: PEP 8 compliance, type hints
- TypeScript: strict mode, interface usage
- JavaScript: ESLint rules, modern syntax
Categorize issues as CRITICAL, WARNING, or SUGGESTION and adjust review status accordingly. Only block PRs for critical security issues.
Generate suggested code fixes for common issues. The AI can propose corrections in review comments (e.g., reformatted code, added error handling).
Example: Adding custom rules
Update the AI prompt with your standards:
Production considerations
Before deploying to production:
- Webhook Integration: Set up GitHub webhooks to trigger reviews automatically when PRs are opened or updated. You'll need the
admin:repo_hookOAuth scope and a webhook endpoint that receives GitHub events. See GitHub's Webhook documentation for implementation details. - Rate Limiting: Implement rate limiting to avoid hitting GitHub API limits (5000 requests/hour for authenticated apps)
- Concurrency: Queue reviews to handle multiple PRs simultaneously without overwhelming the AI API
- Error Handling: Add try/catch blocks and retry logic for API failures
- Review History: Store review results in a database for analytics and team insights
- Configurable Rules: Allow teams to customize review criteria per repository via config files
- Cost Management: Monitor AI API usage and token costs, especially for large PRs with many files
- Privacy: Ensure sensitive code doesn't get logged or sent to unauthorized services
Info
Performance Tip:
For large PRs (>20 files), consider:
- Reviewing only changed lines instead of full files
- Batching file reviews to reduce token usage
- Implementing a maximum file size limit
- Allowing users to request specific file reviews