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
- Faster feedback loops: Get a meaningful review within seconds of committing, before a human reviewer ever sees the pull request.
- Consistency: The agent applies the same checklist every time, eliminating the variability that comes with different human reviewers.
- Context awareness: Because Claude Code can read your entire repository, it reviews code in context rather than in isolation.
- Reviewer leverage: Human reviewers spend their time on the nuanced architectural debates instead of catching missing null checks.
- Onboarding aid: New team members can run the agent on their own branches and learn project conventions before requesting review.
Prerequisites
Before you begin, make sure you have the following:
- Node.js 18 or higher installed on your machine.
- An Anthropic API key with access to Claude, exported as
ANTHROPIC_API_KEY. - The Claude Code CLI installed globally:
npm install -g @anthropic-ai/claude-code. - A git repository with at least one branch containing changes you want to review.
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
- Keep instructions in version control. Your review criteria should evolve with your codebase. Treating the instruction file as code means changes are reviewed and documented.
- Be specific about what matters. Generic instructions produce generic reviews. Call out project-specific concerns like authentication patterns, database migration safety, or API backward compatibility.
- Suppress noise. Explicitly tell the agent to ignore issues that your linter, type checker, or test suite already catches. This keeps the review focused on things only a reasoning agent can find.
- Require evidence. Instruct the agent to cite file paths and line numbers for every finding. Vague observations like "this could be more efficient" are not actionable.
- Set severity thresholds. Define what critical, warning, and suggestion mean in your context so the output is interpretable at a glance.
- Do not auto-block merges. Use the agent as an advisory layer, not a gate. Human judgment should always have the final say, especially for business-logic decisions.
- Iterate on the prompt. When the agent misses something a human reviewer would have caught, update the instruction file. Over time, the agent accumulates your team's collective review wisdom.
- Log and review outputs. Store review outputs so you can track whether the agent's quality improves as you refine instructions. This also creates a useful audit trail.
Common Pitfalls to Avoid
- Trusting the agent on security-critical code without human verification. The agent is a first-pass filter, not a replacement for security review on sensitive changes.
- Letting the agent run tests that mutate state. If your test suite writes to a database or makes external API calls, scope the agent's permissions or provide a safe test command.
- Feeding the entire repository into every review. Use the filtered diff tool and targeted file reads to keep context focused and costs predictable.
- Ignoring cost. Each review consumes API tokens. Monitor usage, especially when running on every push in CI, and consider gating CI reviews to specific event types.
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.