← Back to DevBytes

Building a Code Review Agent with Claude Code: Complete Guide

Building a Code Review Agent with Claude Code: Complete Guide

Code reviews are one of the most valuable yet time-consuming activities in modern software development. While automated linters and CI pipelines catch syntax errors and style violations, they cannot reason about business logic, architectural decisions, or subtle security flaws. By building a custom code review agent with Claude Code, you can offload the first-pass review to an AI assistant that understands context, reads related files, and produces actionable feedback — all from your terminal.

This guide walks through everything you need to know: what a Claude Code code review agent is, why it matters, how to build one step by step, and the best practices that separate a toy script from a production-grade workflow.

What Is a Claude Code Code Review Agent?

Claude Code is Anthropic's official command-line tool that lets Claude operate directly in your development environment. It can read files, run shell commands, edit code, and chain multiple operations together. A "code review agent" built on top of Claude Code is essentially a configured, scripted instance of Claude that is primed with instructions, context, and tools specifically tuned for reviewing source code.

Unlike a one-off chat prompt, an agent is reusable. You define its behavior once — typically through a markdown instruction file, a shell wrapper, and optionally a custom tool — and then invoke it whenever you want a review. The agent can inspect your git diff, open referenced files, run tests, and produce a structured report.

Why It Matters

Prerequisites

Before you begin, make sure you have the following:

Verify the installation by running claude --version in your terminal. If that prints a version number, you are ready to proceed.

Step 1: Define the Agent's Instructions

Claude Code agents are configured primarily through markdown instruction files. These files tell Claude how to behave, what to prioritize, and how to format output. Create a file named .claude/agents/code-reviewer.md in your repository root:

# Code Review Agent

You are a senior software engineer performing a thorough code review.
Your job is to identify bugs, security issues, performance problems,
and maintainability concerns while respecting the project's existing
conventions.

## Process

1. Run `git diff origin/main...HEAD` to identify all changed files.
2. For each changed file, read the full file — not just the diff — so
   you understand surrounding context.
3. If the change references types, functions, or constants defined
   elsewhere, open those files too.
4. Run the project's test suite if a test command exists in
   package.json or Makefile.
5. Produce a structured review using the format below.

## Review Format

For each finding, output:

- **File:** path/to/file.ts
- **Line:** line number or range
- **Severity:** critical | warning | suggestion
- **Issue:** one-sentence description
- **Recommendation:** concrete fix or improvement

End with a summary that lists the count of findings by severity and
an overall verdict: APPROVE, REQUEST_CHANGES, or NEEDS_DISCUSSION.

## Rules

- Never invent APIs or functions that do not exist in the codebase.
- Do not comment on style issues that the linter already enforces.
- Prefer specific, actionable recommendations over vague advice.
- If you are unsure about a business-logic decision, flag it as
  NEEDS_DISCUSSION rather than asserting correctness.

This instruction file is the single source of truth for the agent's behavior. Because it lives in your repository, it evolves alongside your codebase and can be reviewed in version control just like any other file.

Step 2: Create a Shell Wrapper

While you could invoke Claude Code directly each time, a shell wrapper makes the agent ergonomic and consistent. Create a file named scripts/review.sh:

#!/usr/bin/env bash
set -euo pipefail

BRANCH="${1:-HEAD}"
INSTRUCTION_FILE=".claude/agents/code-reviewer.md"

if [ ! -f "$INSTRUCTION_FILE" ]; then
  echo "Error: instruction file not found at $INSTRUCTION_FILE"
  exit 1
fi

echo "Starting code review for branch: $BRANCH"
echo "----------------------------------------"

claude \
  --print \
  --output-format text \
  --max-turns 30 \
  --append-system-prompt "$(cat "$INSTRUCTION_FILE")" \
  "Review the changes on the current branch compared to origin/main. \
Follow the process defined in your instructions exactly. Output the \
full review when complete."

echo "----------------------------------------"
echo "Review complete."

Make the script executable with chmod +x scripts/review.sh. Now you can run ./scripts/review.sh from any branch to get a full review.

Step 3: Add a Custom Tool for Diff Inspection

For more advanced workflows, you can give the agent a custom tool that returns a structured diff. This is useful when you want the agent to focus on specific file types or ignore generated code. Create .claude/tools/review-diff.sh:

#!/usr/bin/env bash
# Returns a filtered git diff excluding generated and lock files.
git diff origin/main...HEAD -- \
  ':(exclude)*.lock' \
  ':(exclude)*.generated.*' \
  ':(exclude)dist/' \
  ':(exclude)coverage/'

Reference this tool in your instruction file so the agent knows it exists:

## Available Tools

- `.claude/tools/review-diff.sh` — returns a filtered diff that
  excludes lock files, generated code, and build output. Prefer this
  over raw `git diff` when identifying changed files.

Step 4: Integrate with CI

To run the agent automatically on every pull request, add a job to your CI pipeline. Below is an example using GitHub Actions. Create .github/workflows/ai-review.yml:

name: AI Code Review

on:
  pull_request:
    types: [opened, synchronize, reopened]

jobs:
  review:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      pull-requests: write
    steps:
      - name: Checkout
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Setup Node
        uses: actions/setup-node@v4
        with:
          node-version: '20'

      - name: Install Claude Code
        run: npm install -g @anthropic-ai/claude-code

      - name: Run Review
        env:
          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
        run: |
          ./scripts/review.sh > review_output.md

      - name: Post Comment
        uses: actions/github-script@v7
        with:
          script: |
            const fs = require('fs');
            const body = fs.readFileSync('review_output.md', 'utf8');
            await github.rest.issues.createComment({
              owner: context.repo.owner,
              repo: context.repo.repo,
              issue_number: context.issue.number,
              body: `## AI Code Review\n\n${body}`
            });

This workflow checks out the full repository history, installs Claude Code, runs your review script, and posts the output as a comment on the pull request. Remember to add your ANTHROPIC_API_KEY as a repository secret.

Step 5: Handle Large Pull Requests

Large diffs can exceed context limits or produce shallow reviews. To handle this, modify your instruction file to process files in batches:

## Handling Large Changes

If the diff contains more than 15 files:

1. Group files by directory or module.
2. Review each group separately, producing a partial report.
3. After all groups are reviewed, produce a consolidated summary.

If a single file exceeds 500 lines of changes, focus on:
- Public API surface changes
- Security-sensitive code paths
- Error handling and edge cases
Explicitly note that the file was too large for a complete review.

Best Practices

Common Pitfalls to Avoid

Conclusion

Building a code review agent with Claude Code transforms a repetitive, bottleneck-prone activity into a fast, consistent, and context-aware first pass. By defining clear instructions, wrapping the agent in a simple shell script, integrating it into your CI pipeline, and iterating on the prompt over time, you create a tool that compounds in value as your team refines it. The agent will never replace the judgment of an experienced engineer, but it will ensure that when a human reviewer opens your pull request, the obvious problems are already gone — leaving them free to focus on the discussions that actually require human insight.

— Ad —

Google AdSense will appear here after approval

← Back to all articles