Back to Blog
Recipe

Build an AI GitHub PR Reviewer with MCP (Complete Recipe)

January 13, 202615 min readBy Nikhil Tiwari

🍳 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:

AI Client

Claude Desktop or Cursor

GitHub MCP Server

Translates AI requests to API calls

GitHub API

Provides PR data and accepts reviews

How it works:

  1. You ask: "Review PR #123 in owner/repo"
  2. AI Client β†’ MCP Server: Calls get_pull_request_diff tool
  3. MCP Server β†’ GitHub: Fetches the PR diff via GitHub API
  4. GitHub β†’ MCP β†’ AI: Returns the code changes
  5. AI analyzes: Reviews the code for issues, suggestions
  6. AI β†’ MCP β†’ GitHub: Posts review comments via create_pull_request_review

Prerequisites

GitHub Account

With access to repositories you want to review

GitHub Personal Access Token

With repo scope for private repos

Node.js 18+

For running the MCP server

MCP Client

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.

  1. Go to GitHub Settings β†’ Developer settings β†’ Personal access tokens
  2. Click "Generate new token (classic)"
  3. Give it a descriptive name like "MCP PR Reviewer"
  4. Select these scopes:
    • repo β€” Full control of private repositories (or public_repo for public only)
    • read:user β€” Read user profile data
  5. 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:

  1. Restart your AI client (Claude Desktop or Cursor)
  2. Verify the connection by asking: "What GitHub tools do you have access to?"

You should see tools like:

  • search_repositories β€” Search GitHub repos
  • get_file_contents β€” Read file contents
  • list_commits β€” List commit history
  • get_pull_request β€” Fetch PR details
  • get_pull_request_diff β€” Get the PR diff
  • create_pull_request_review β€” Post a review
  • create_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:

  1. Use get_pull_request to fetch PR metadata
  2. Use get_pull_request_diff to get the actual code changes
  3. 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 repo for 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?
Yes, as long as your GitHub token has the repo scope, which grants access to private repositories you have permission to view.
Will the AI approve PRs automatically?
Only if you explicitly ask it to. We recommend using 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?
AI reviews are helpful for catching common issues, style inconsistencies, and potential bugs. However, they should complementβ€”not replaceβ€”human review. AI may miss business logic context or suggest changes that don't fit your architecture.
Does this work with GitHub Enterprise?
Yes, the GitHub MCP Server supports GitHub Enterprise. Set the 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?
The MCP server itself is free. Costs depend on your AI provider (Claude API usage) and GitHub API rate limits. For personal/small team use, you'll likely stay within free tiers.
NT

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.