Skip to main content
RapidDev - Software Development Agency
mcp-tutorial

How to use MCP for automated code review

Automate code reviews using MCP by connecting GitHub and Filesystem servers to an AI assistant. The AI reads pull request diffs via the GitHub MCP server, inspects the actual source files via the Filesystem server, and produces structured review comments with file references and line numbers. This catches bugs, style violations, and security issues that manual review misses.

What you'll learn

  • How to configure GitHub and Filesystem MCP servers for code review
  • How to build a review workflow that reads PR diffs and source files
  • How to generate structured review comments with file and line references
  • How to integrate AI code review into GitHub Actions CI
Book a free consultation
4.9Clutch rating
600+Happy partners
17+Countries served
190+Team members
Advanced8 min read30-45 minMCP TypeScript SDK v1.x, GitHub MCP Server, Filesystem MCP Server, Claude Desktop / CursorMarch 2026RapidDev Engineering Team
TL;DR

Automate code reviews using MCP by connecting GitHub and Filesystem servers to an AI assistant. The AI reads pull request diffs via the GitHub MCP server, inspects the actual source files via the Filesystem server, and produces structured review comments with file references and line numbers. This catches bugs, style violations, and security issues that manual review misses.

AI-Powered Code Review with MCP Servers

Code review is one of the highest-value use cases for MCP. By connecting GitHub and Filesystem MCP servers, an AI assistant can read pull request diffs, access the full repository context, and produce detailed review comments. Unlike simple diff-based tools, MCP gives the AI access to the entire codebase, so it understands how changes affect other files, whether imports exist, and whether the code follows project conventions.

Prerequisites

  • GitHub MCP server installed or configured
  • Filesystem MCP server configured with repository access
  • Claude Desktop or Cursor with MCP support
  • A GitHub repository with pull requests to review
  • GitHub personal access token with repo scope

Step-by-step guide

1

Configure the GitHub MCP server for PR access

Set up the GitHub MCP server in your MCP client configuration. The server provides tools to list PRs, read diffs, get file contents from branches, and post review comments. You need a GitHub personal access token with repo scope. Add the server to your Claude Desktop or Cursor MCP config with the token as an environment variable.

typescript
1// Claude Desktop: ~/Library/Application Support/Claude/claude_desktop_config.json
2{
3 "mcpServers": {
4 "github": {
5 "command": "npx",
6 "args": ["-y", "@modelcontextprotocol/server-github"],
7 "env": {
8 "GITHUB_PERSONAL_ACCESS_TOKEN": "ghp_your_token_here"
9 }
10 }
11 }
12}

Expected result: GitHub MCP server appears in your client's tool list with PR-related tools available.

2

Add the Filesystem MCP server for full repository context

The Filesystem server gives the AI direct access to read source files in the repository. This is critical for code review because the AI needs to see not just the diff, but the surrounding code, imported modules, and configuration files. Configure it to allow read-only access to your repository directory.

typescript
1// Add to your mcpServers configuration:
2{
3 "mcpServers": {
4 "github": { /* ... from previous step */ },
5 "filesystem": {
6 "command": "npx",
7 "args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/your/repo"],
8 "env": {}
9 }
10 }
11}

Expected result: Filesystem MCP server provides read_file, list_files, and search_files tools for the repository.

3

Build a structured code review prompt

Create a system prompt or instruction set that tells the AI how to perform code reviews. The prompt should specify: which tools to use, what to look for (bugs, security, style, performance), how to format comments, and the project's coding standards. Reference your .cursorrules or project conventions so the AI applies your team's specific standards.

typescript
1// Example review prompt for Claude Desktop / Cursor:
2// "Review PR #42 in the repository owner/repo-name.
3//
4// Steps:
5// 1. Use the GitHub tools to fetch the PR diff and changed files list
6// 2. For each changed file, use the filesystem tools to read the full file
7// 3. Check for:
8// - Logic bugs and edge cases
9// - Security vulnerabilities (injection, XSS, auth bypass)
10// - TypeScript type safety issues
11// - Missing error handling
12// - Performance concerns
13// - Code style violations per our .cursorrules
14// 4. Format each finding as:
15// FILE: path/to/file.ts
16// LINE: 42
17// SEVERITY: critical | warning | suggestion
18// ISSUE: Description of the problem
19// FIX: Suggested code change
20//
21// Be specific with line numbers and provide concrete fix suggestions."

Expected result: A structured prompt that guides the AI to perform thorough, consistent code reviews.

4

Build a custom MCP server for automated review pipelines

For CI/CD integration, build a custom MCP server that wraps the GitHub API and adds review-specific tools: get_pr_diff, get_changed_files, post_review_comment. This server handles authentication, pagination, and formatting so the AI gets clean data. The post_review_comment tool writes comments back to the PR with file paths and line numbers.

typescript
1// src/tools/review-tools.ts
2import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3import { z } from "zod";
4
5export function registerReviewTools(server: McpServer) {
6 server.tool(
7 "get_pr_diff",
8 "Get the diff for a pull request",
9 {
10 owner: z.string(),
11 repo: z.string(),
12 prNumber: z.number(),
13 },
14 async ({ owner, repo, prNumber }) => {
15 const response = await fetch(
16 `https://api.github.com/repos/${owner}/${repo}/pulls/${prNumber}`,
17 {
18 headers: {
19 Authorization: `Bearer ${process.env.GITHUB_TOKEN}`,
20 Accept: "application/vnd.github.v3.diff",
21 },
22 }
23 );
24 const diff = await response.text();
25 return { content: [{ type: "text", text: diff }] };
26 }
27 );
28
29 server.tool(
30 "post_review_comment",
31 "Post a review comment on a specific line of a PR",
32 {
33 owner: z.string(),
34 repo: z.string(),
35 prNumber: z.number(),
36 body: z.string().describe("Comment text"),
37 path: z.string().describe("File path relative to repo root"),
38 line: z.number().describe("Line number in the diff"),
39 },
40 async ({ owner, repo, prNumber, body, path, line }) => {
41 const response = await fetch(
42 `https://api.github.com/repos/${owner}/${repo}/pulls/${prNumber}/comments`,
43 {
44 method: "POST",
45 headers: {
46 Authorization: `Bearer ${process.env.GITHUB_TOKEN}`,
47 "Content-Type": "application/json",
48 },
49 body: JSON.stringify({ body, path, line, side: "RIGHT" }),
50 }
51 );
52 if (!response.ok) {
53 const error = await response.text();
54 return { content: [{ type: "text", text: `Error: ${error}` }], isError: true };
55 }
56 return { content: [{ type: "text", text: `Comment posted on ${path}:${line}` }] };
57 }
58 );
59}

Expected result: Custom MCP tools that fetch PR diffs and post review comments with line-level precision.

5

Integrate into GitHub Actions for automated PR reviews

Run the AI code review automatically on every PR by triggering it from GitHub Actions. The workflow checks out the code, starts the MCP server, connects an AI client, and posts review comments. Use a script that calls your MCP server's tools programmatically. For teams needing a turnkey solution, RapidDev offers pre-built AI code review integrations that work out of the box with MCP.

typescript
1# .github/workflows/ai-review.yml
2name: AI Code Review
3on:
4 pull_request:
5 types: [opened, synchronize]
6
7jobs:
8 review:
9 runs-on: ubuntu-latest
10 permissions:
11 pull-requests: write
12 contents: read
13 steps:
14 - uses: actions/checkout@v4
15 with:
16 fetch-depth: 0
17 - uses: actions/setup-node@v4
18 with:
19 node-version: 20
20 - name: Install MCP review server
21 run: cd review-server && npm ci && npx tsc
22 - name: Run AI code review
23 env:
24 GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
25 ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
26 PR_NUMBER: ${{ github.event.pull_request.number }}
27 REPO_OWNER: ${{ github.repository_owner }}
28 REPO_NAME: ${{ github.event.repository.name }}
29 run: node review-server/dist/run-review.js

Expected result: Every PR automatically receives AI-generated code review comments via GitHub Actions.

Complete working example

src/review-server.ts
1import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
3import { z } from "zod";
4
5const GITHUB_TOKEN = process.env.GITHUB_TOKEN!;
6
7async function ghFetch(path: string, options: RequestInit = {}) {
8 const res = await fetch(`https://api.github.com${path}`, {
9 ...options,
10 headers: {
11 Authorization: `Bearer ${GITHUB_TOKEN}`,
12 Accept: "application/vnd.github.v3+json",
13 ...options.headers,
14 },
15 });
16 return res;
17}
18
19const server = new McpServer({ name: "code-review-server", version: "1.0.0" });
20
21server.tool("get_pr_info", "Get PR title, description, and changed files", {
22 owner: z.string(), repo: z.string(), pr: z.number(),
23}, async ({ owner, repo, pr }) => {
24 const res = await ghFetch(`/repos/${owner}/${repo}/pulls/${pr}`);
25 const data = await res.json();
26 const files = await ghFetch(`/repos/${owner}/${repo}/pulls/${pr}/files`);
27 const fileList = await files.json();
28 return { content: [{ type: "text", text: JSON.stringify({
29 title: data.title, body: data.body, files: fileList.map((f: any) => ({
30 filename: f.filename, status: f.status, additions: f.additions, deletions: f.deletions,
31 })),
32 }, null, 2) }] };
33});
34
35server.tool("get_file_diff", "Get diff for a specific file in a PR", {
36 owner: z.string(), repo: z.string(), pr: z.number(), filename: z.string(),
37}, async ({ owner, repo, pr, filename }) => {
38 const res = await ghFetch(`/repos/${owner}/${repo}/pulls/${pr}/files`);
39 const files = await res.json();
40 const file = files.find((f: any) => f.filename === filename);
41 if (!file) return { content: [{ type: "text", text: "File not found in PR" }], isError: true };
42 return { content: [{ type: "text", text: file.patch || "(binary file)" }] };
43});
44
45server.tool("post_comment", "Post a review comment on the PR", {
46 owner: z.string(), repo: z.string(), pr: z.number(),
47 body: z.string(), path: z.string(), line: z.number(),
48}, async ({ owner, repo, pr, body, path, line }) => {
49 const res = await ghFetch(`/repos/${owner}/${repo}/pulls/${pr}/comments`, {
50 method: "POST",
51 headers: { "Content-Type": "application/json" },
52 body: JSON.stringify({ body, path, line, side: "RIGHT" }),
53 });
54 if (!res.ok) return { content: [{ type: "text", text: `Error: ${await res.text()}` }], isError: true };
55 return { content: [{ type: "text", text: `Comment posted on ${path}:${line}` }] };
56});
57
58async function main() {
59 const transport = new StdioServerTransport();
60 await server.connect(transport);
61 console.error("Code review MCP server running");
62}
63main().catch(e => { console.error(e); process.exit(1); });

Common mistakes when using MCP for automated code review

Why it's a problem: Reviewing only the diff without reading the full files for context

How to avoid: Use the Filesystem server to read complete files, not just changed lines. The AI needs surrounding code to spot bugs like missing imports or broken function signatures.

Why it's a problem: Posting review comments with wrong line numbers because of diff format confusion

How to avoid: Use the GitHub diff line numbers (from the patch), not the absolute file line numbers. The GitHub API expects diff-relative line numbers for PR comments.

Why it's a problem: Not scoping the GitHub token to specific repositories, creating unnecessary security risk

How to avoid: Use fine-grained personal access tokens scoped to only the repositories that need AI review.

Why it's a problem: Running automated reviews without human oversight, creating noisy or incorrect comments

How to avoid: Start with the AI drafting reviews for human approval before enabling fully automated posting. Tune the review prompt based on feedback.

Best practices

  • Read full files alongside diffs so the AI understands the complete context
  • Include project coding standards in the review prompt for consistent feedback
  • Start with human-reviewed AI suggestions before enabling fully automated comments
  • Use fine-grained GitHub tokens scoped to specific repositories
  • Post comments with specific file paths and line numbers for actionable feedback
  • Categorize findings by severity (critical, warning, suggestion) for prioritization
  • Rate limit review comments to avoid overwhelming PR authors with noise

Still stuck?

Copy one of these prompts to get a personalized, step-by-step explanation.

ChatGPT Prompt

I want to automate code reviews using MCP. Show me how to configure GitHub and Filesystem MCP servers, build a review prompt that checks for bugs and security issues, and create a custom MCP server with tools to fetch PR diffs and post review comments with line numbers.

MCP Prompt

Build an MCP server for automated code review. Include get_pr_info, get_file_diff, and post_comment tools that use the GitHub API. Show the Claude Desktop config and a GitHub Actions workflow for automated PR reviews.

Frequently asked questions

Can MCP-based code review replace human reviewers?

No. AI code review is best as a first pass that catches common issues (bugs, security, style) before human review. It saves reviewer time but should not be the only review step for production code.

How many credits does an AI code review cost?

A typical PR review with 5-10 changed files uses 2,000-5,000 tokens of input and 500-1,000 tokens of output per file. With Claude 3.5 Sonnet, this costs roughly $0.05-$0.15 per review.

Can I customize what the AI checks for?

Yes. Modify the review prompt to focus on specific concerns: security, performance, accessibility, test coverage, or your project's specific conventions.

Does this work with GitLab or Bitbucket?

The pattern works with any Git platform. Replace the GitHub API calls with GitLab or Bitbucket API equivalents. The MCP server structure remains the same.

Can RapidDev set up automated AI code review for our team?

Yes. RapidDev offers pre-built code review integrations using MCP that work with GitHub, GitLab, and Bitbucket, including custom review rules and CI/CD pipeline setup.

RapidDev

Talk to an Expert

Our team has built 600+ apps. Get personalized help with your project.

Book a free consultation

Need help with your project?

Our experts have built 600+ apps and can accelerate your development. Book a free consultation — no strings attached.

Book a free consultation

We put the rapid in RapidDev

Need a dedicated strategic tech and growth partner? Discover what RapidDev can do for your business! Book a call with our team to schedule a free, no-obligation consultation. We'll discuss your project and provide a custom quote at no cost.