Build an AI Agent That Reviews Pull Requests
Updated 2026-11-10
A pull request review agent reads a PR diff, highlights risky changes, and either prints a structured review or posts comments through the GitHub REST API. This guide uses Python and the same tool-loop pattern as Build your first AI agent in Python. For IDE-assisted reviews, start with GitHub MCP server instead of reimplementing API calls. Last tested 2026-11-10.
Prerequisites
- Python 3.10+ and an LLM API key
- A GitHub personal access token (classic or fine-grained) with at least read access to the target repo
- Permission to post PR reviews on that repo if you enable the write step
Docs used:
- REST: Get a pull request
- REST: List pull requests files
- REST: Create a review for a pull request
- Fine-grained PAT permissions
Steps
1. Create a token with least privilege
For a public repo read-only review:
- Fine-grained PAT: Repository access → selected repo → Contents: Read-only, Pull requests: Read-only
- Classic PAT:
public_repo(public) orrepo(private)
To post review comments, add Pull requests: Read and write (fine-grained) or keep repo on classic tokens.
Store the token in GITHUB_TOKEN. Never commit it.
2. Install dependencies
pip install openai requests
export GITHUB_TOKEN="ghp_..." OPENAI_API_KEY="sk-..."
3. Fetch PR metadata and file patches
# pr_review_agent.py
import os, json, textwrap, requests
from openai import OpenAI
OWNER, REPO, PR_NUMBER = "octocat", "Hello-World", 1
API = f"https://api.github.com/repos/{OWNER}/{REPO}"
HDRS = {
"Authorization": f"Bearer {os.environ['GITHUB_TOKEN']}",
"Accept": "application/vnd.github+json",
"X-GitHub-Api-Version": "2022-11-28",
}
def github_get(path: str):
r = requests.get(f"{API}{path}", headers=HDRS, timeout=30)
r.raise_for_status()
return r.json()
def fetch_pr_files(max_patch_chars: int = 12000) -> str:
pr = github_get(f"/pulls/{PR_NUMBER}")
files = github_get(f"/pulls/{PR_NUMBER}/files?per_page=100")
chunks = [f"PR #{PR_NUMBER}: {pr['title']}\n{pr.get('body') or ''}\n"]
used = 0
for f in files:
patch = f.get("patch") or "(binary or large diff omitted)"
block = f"\n## {f['filename']} (+{f['additions']}/-{f['deletions']})\n{patch}\n"
if used + len(block) > max_patch_chars:
chunks.append("\n[truncated remaining files]\n")
break
chunks.append(block)
used += len(block)
return "".join(chunks)
Patches omit huge files; cap max_patch_chars to stay inside model context.
4. Define review tools for the agent loop
client = OpenAI()
MODEL = os.environ.get("MODEL", "gpt-4.1-mini")
def summarize_pr(_: str = "") -> str:
"""Load the PR diff and return it for the model to review."""
return fetch_pr_files()
def post_draft_review(summary: str) -> str:
"""Post a COMMENT event review (not APPROVE) with the summary body."""
body = {"body": summary, "event": "COMMENT"}
r = requests.post(f"{API}/pulls/{PR_NUMBER}/reviews", headers=HDRS, json=body, timeout=30)
if r.status_code >= 400:
return f"error {r.status_code}: {r.text[:500]}"
return f"review id {r.json().get('id')}"
FUNCS = {"summarize_pr": summarize_pr, "post_draft_review": post_draft_review}
TOOLS = [
{"type": "function", "function": {
"name": "summarize_pr",
"description": "Fetch PR title, body, and per-file patches.",
"parameters": {"type": "object", "properties": {}}}},
{"type": "function", "function": {
"name": "post_draft_review",
"description": "Post a COMMENT review on the PR with the given markdown summary.",
"parameters": {"type": "object",
"properties": {"summary": {"type": "string"}},
"required": ["summary"]}}},
]
Wire FUNCS and TOOLS into the loop from Build your first AI agent in Python with max_steps=6.
5. Run a read-only review locally
prompt = (
"Review this pull request. List security risks, missing tests, and style issues. "
"Do not post to GitHub unless I say POST."
)
# ... run_agent(prompt) ...
print(fetch_pr_files()[:2000])
Inspect the model output before you enable post_draft_review.
6. Trigger on new PRs (optional)
Use a GitHub Actions pull_request workflow that runs the script with GITHUB_TOKEN from secrets.GITHUB_TOKEN. Keep human approval before post_draft_review executes in CI.
Common errors
404 on private repos. The token lacks repo access or the workflow’s GITHUB_TOKEN is limited to the same repo fork rules.
403 insufficient scopes. Add Pull request write permission before calling create review.
Empty patch fields. GitHub omits patches for large or binary files. Fetch blob contents with the Contents API for specific paths.
Model hallucinates file names. Force a summarize_pr tool call first so the diff comes from GitHub, not imagination.
Review spam. Cap max_steps and require a human flag before post_draft_review. See Fix: AI agent stuck in a loop.
FAQ
How do I build an AI agent that reviews pull requests?
Give the agent tools to download PR files via the REST API, summarize risks with an LLM, and optionally post a COMMENT review. Start read-only, then add write tools.
Can GitHub MCP replace this script?
Yes for interactive review in Cursor. GitHub MCP exposes hosted tools; this guide fits CI, custom prompts, or org policies that need a repo-owned bot user.
Should the agent APPROVE or REQUEST_CHANGES?
Default to COMMENT until a human trusts the prompt. GitHub’s API accepts APPROVE, REQUEST_CHANGES, or COMMENT; misuse can block merges.
How do I review only certain paths?
Filter files in fetch_pr_files by extension or directory before you pass text to the model.