Build an AI GitHub PR Reviewer with MCP (Complete Recipe)
π³ MCP Recipe
- What you'll build: An AI assistant that reviews GitHub PRs and posts helpful comments
- MCP servers used: GitHub MCP Server
- Time to complete: 30-45 minutes
- Difficulty: Intermediate
Code reviews are essential but time-consuming. What if you could have an AI assistant that automatically reviews pull requests, catches common issues, and posts helpful suggestionsβall while you focus on architecture decisions?
In this recipe, you'll build exactly that using the GitHub MCP Server and an AI client like Claude Desktop or Cursor. By the end, you'll have a working AI code reviewer that can:
- Fetch PR diffs and file changes from any GitHub repository
- Analyze code for bugs, security issues, and style problems
- Post review comments directly on the PR
- Suggest specific improvements with code snippets
Architecture Overview
The system consists of three components working together:
Claude Desktop or Cursor
Translates AI requests to API calls
Provides PR data and accepts reviews
How it works:
- You ask: "Review PR #123 in owner/repo"
- AI Client β MCP Server: Calls
get_pull_request_difftool - MCP Server β GitHub: Fetches the PR diff via GitHub API
- GitHub β MCP β AI: Returns the code changes
- AI analyzes: Reviews the code for issues, suggestions
- AI β MCP β GitHub: Posts review comments via
create_pull_request_review
Prerequisites
With access to repositories you want to review
With repo scope for private repos
For running the MCP server
Claude Desktop, Cursor, or custom client
Step 1: Create a GitHub Personal Access Token
First, you need a GitHub token that allows the MCP server to access repositories and post comments.
- Go to GitHub Settings β Developer settings β Personal access tokens
- Click "Generate new token (classic)"
- Give it a descriptive name like "MCP PR Reviewer"
- Select these scopes:
repoβ Full control of private repositories (orpublic_repofor public only)read:userβ Read user profile data
- Click "Generate token" and copy it immediately (you won't see it again)
β οΈ Security Note
Never commit your token to version control. Store it in environment variables or a secure secrets manager.
Step 2: Install the GitHub MCP Server
The official GitHub MCP Server is maintained by Anthropic and available via npm:
# Install globally
npm install -g @modelcontextprotocol/server-github
# Or run directly with npx (recommended)
npx @modelcontextprotocol/server-github
The server needs your GitHub token to authenticate. You can pass it via environment variable:
# Set the token (add to your shell profile for persistence)
export GITHUB_PERSONAL_ACCESS_TOKEN="ghp_your_token_here"
Step 3: Configure Your MCP Client
Now connect the GitHub MCP server to your AI client. Choose your client below:
For Claude Desktop
Edit your Claude Desktop config file:
- macOS:
~/Library/Application Support/Claude/claude_desktop_config.json - Windows:
%APPDATA%\Claude\claude_desktop_config.json
Add the GitHub server configuration:
{
"mcpServers": {
"github": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"env": {
"GITHUB_PERSONAL_ACCESS_TOKEN": "ghp_your_token_here"
}
}
}
}
For Cursor IDE
Open Cursor Settings β Tools & MCP, then add:
| Field | Value |
|---|---|
| Name | github |
| Type | command |
| Command | npx -y @modelcontextprotocol/server-github |
Set the GITHUB_PERSONAL_ACCESS_TOKEN environment variable in your shell before launching Cursor.
Step 4: Restart and Verify Connection
After saving the configuration:
- Restart your AI client (Claude Desktop or Cursor)
- Verify the connection by asking: "What GitHub tools do you have access to?"
You should see tools like:
search_repositoriesβ Search GitHub reposget_file_contentsβ Read file contentslist_commitsβ List commit historyget_pull_requestβ Fetch PR detailsget_pull_request_diffβ Get the PR diffcreate_pull_request_reviewβ Post a reviewcreate_issue_commentβ Comment on issues/PRs
β Checkpoint
If you see the GitHub tools listed, you're ready to start reviewing PRs!
Step 5: Review Your First Pull Request
Now for the fun part. Ask the AI to review a PR with a prompt like:
Review the pull request #42 in the repository owner/repo-name.
Focus on:
1. Code quality and readability
2. Potential bugs or edge cases
3. Security concerns
4. Performance implications
5. Test coverage
Provide specific, actionable feedback with code suggestions where helpful.
The AI will:
- Use
get_pull_requestto fetch PR metadata - Use
get_pull_request_diffto get the actual code changes - Analyze the diff and provide feedback
Example Output
Here's what a typical review might look like:
## PR Review: Add user authentication middleware (#42)
### Summary
This PR adds JWT-based authentication middleware. Overall well-structured,
but I found a few issues to address.
### Issues Found
**π΄ Critical: Token not validated for expiration**
// Current code (line 23)
const decoded = jwt.verify(token, SECRET);
// Suggested fix
const decoded = jwt.verify(token, SECRET, { maxAge: '1h' });
**π‘ Warning: Missing error handling**
Line 31: The catch block logs the error but doesn't return a proper
HTTP response, leaving the request hanging.
**π’ Suggestion: Consider rate limiting**
This endpoint could benefit from rate limiting to prevent brute-force
attacks on the authentication layer.
### Test Coverage
The PR doesn't include tests for the new middleware. Consider adding:
- Test for valid token
- Test for expired token
- Test for malformed token
Step 6: Post the Review to GitHub
Once you're satisfied with the AI's analysis, you can have it post the review directly:
Post this review to the pull request with the following:
- Event: COMMENT (or REQUEST_CHANGES if there are critical issues)
- Include all the feedback above as the review body
The AI will use the create_pull_request_review tool to post the review.
Advanced: Custom Review Prompts
Customize the AI's review focus based on your team's needs:
Security-Focused Review
Review PR #123 in owner/repo with a security focus:
Check for:
- SQL injection vulnerabilities
- XSS attack vectors
- Hardcoded secrets or credentials
- Insecure cryptographic practices
- Missing input validation
- Authentication/authorization flaws
Rate severity as: Critical / High / Medium / Low
Performance-Focused Review
Review PR #123 in owner/repo for performance:
Analyze:
- Time complexity of new algorithms
- Database query efficiency (N+1 queries)
- Memory usage patterns
- Unnecessary re-renders (React)
- Bundle size impact
- Caching opportunities
Style and Consistency Review
Review PR #123 in owner/repo for code style:
Check against our style guide:
- Consistent naming conventions
- Proper error handling patterns
- Documentation completeness
- Code organization and modularity
- DRY principle adherence
Automating PR Reviews
Want to automatically review every new PR? You can set up a GitHub Action that triggers the review:
# .github/workflows/ai-review.yml
name: AI Code Review
on:
pull_request:
types: [opened, synchronize]
jobs:
review:
runs-on: ubuntu-latest
steps:
- name: Trigger AI Review
run: |
# Call your MCP-powered review service
curl -X POST https://your-review-service.com/review \
-H "Authorization: Bearer ${{ secrets.REVIEW_API_KEY }}" \
-d '{"repo": "${{ github.repository }}", "pr": ${{ github.event.number }}}'
π‘ Pro Tip
For production automation, consider building a lightweight server that receives GitHub webhooks and orchestrates the MCP + LLM interaction. This keeps your tokens secure and allows for custom logic.
Best Practices
| Practice | Why It Matters |
|---|---|
| Always verify AI suggestions | AI can miss context or suggest incorrect fixes |
| Use COMMENT, not APPROVE | Let humans make final approval decisions |
| Set clear review guidelines | AI works better with specific instructions |
| Limit token permissions | Only grant access to necessary repositories |
| Monitor for sensitive data | Don't expose secrets in review comments |
Troubleshooting
GitHub tools not showing up
Check that:
- Your config file is valid JSON (use a JSON validator)
- The token environment variable is set correctly
- You've restarted the AI client after config changes
- The npx command works in your terminal:
npx @modelcontextprotocol/server-github --help
Authentication errors
Common causes:
- Token has expired β generate a new one
- Token lacks required scopes β needs
repofor private repos - Token was revoked β check GitHub settings
Rate limiting issues
GitHub API has rate limits (5,000 requests/hour for authenticated users). If you hit limits:
- Wait for the rate limit to reset
- Reduce the number of PRs reviewed per session
- Consider using a GitHub App instead of personal token for higher limits
Large PR diff issues
Very large PRs may exceed context limits. Solutions:
- Ask the AI to focus on specific files: "Review only the changes in src/auth/"
- Break the review into multiple requests
- Use the file listing first, then review files individually
What You Built
Congratulations! You now have an AI-powered code reviewer that:
- β Connects to GitHub via MCP
- β Fetches and analyzes pull request diffs
- β Provides detailed code review feedback
- β Posts reviews directly to GitHub
- β Can be customized for security, performance, or style reviews
Next Steps
- Add more MCP servers: Combine with Slack MCP to notify teams of review results
- Build a review service: Create an API that automates reviews for all PRs
- Customize review rules: Add your team's specific code guidelines to prompts
- Track metrics: Log reviews to measure impact on code quality
Test GitHub MCP Server Now
Try the GitHub MCP tools in our online playground
Open MCP Playground βRelated Recipes
Frequently Asked Questions
Can this review private repositories?
repo scope, which grants access to private repositories you have permission to view.Will the AI approve PRs automatically?
COMMENT event type for reviews and letting humans make final approval decisions. This keeps humans in the loop for important decisions.How accurate are the reviews?
Does this work with GitHub Enterprise?
GITHUB_API_URL environment variable to your enterprise API endpoint (e.g., https://github.yourcompany.com/api/v3).What's the cost of using this?
Nikhil Tiwari
15+ years of experience in product development, AI enthusiast, and passionate about building innovative solutions that bridge the gap between technology and real-world applications. Specializes in creating developer tools and platforms that make complex technologies accessible to everyone.