Code Review Bot
Build an AI agent that automatically reviews code changes in your GitHub repositories, provides feedback on code quality, and suggests improvements.
What You'll Build
An automated code reviewer that:
- Analyzes GitHub pull requests on demand or on a schedule
- Identifies bugs, security vulnerabilities, and code smells
- Provides structured feedback with inline suggestions
- Posts review comments back to GitHub via MCP
Time to complete: 20-30 minutes
Prerequisites
- A TeamDay account with an organization
- A GitHub personal access token with
reposcope - Basic understanding of Git and GitHub
Architecture Overview
graph LR
A[GitHub PR] --> B[Code Review Agent]
B --> C[GitHub MCP Server]
C --> D[GitHub API]
B --> E[Code Analysis]
E --> F[Review Comments]
F --> C
The agent uses the GitHub MCP server to read pull request diffs, analyzes the code, and posts review comments back --- all through the GitHub API.
Step 1: Get Your API Token
You need a TeamDay API token to make API calls.
- Go to Settings > API Keys in the TeamDay app
- Click Create API Key
- Copy the token and store it securely
export TEAMDAY_TOKEN="your-api-token-here"
For full details, see the Authentication guide.
Step 2: Set Up a Space
Create a Space for your code review work. You can do this in the TeamDay UI:
- Open the TeamDay app
- Click New Space
- Name it "Code Review Workspace"
- Note the Space ID (visible in the URL or settings)
export SPACE_ID="your-space-id"
Store Your GitHub Token as a Space Secret
The GitHub MCP server needs a personal access token. Store it as a Space secret so the agent can use it at runtime:
curl -X POST "https://us.teamday.ai/api/v1/spaces/$SPACE_ID/secrets" \
-H "Authorization: Bearer $TEAMDAY_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"secrets": {
"GITHUB_TOKEN": "ghp_your_github_token_here"
}
}'
Response:
{
"success": true,
"message": "Stored 1 secret(s)",
"keys": ["GITHUB_TOKEN"]
}
Step 3: Create the Code Review Agent
Create an agent with a detailed system prompt that defines its code review behavior:
curl -X POST https://us.teamday.ai/api/v1/agents \
-H "Authorization: Bearer $TEAMDAY_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"name": "Code Reviewer",
"role": "Code Review Specialist",
"model": "claude-sonnet-4-6",
"visibility": "organization",
"tags": ["code-review", "github", "automation"],
"systemPrompt": "You are an expert code reviewer with deep knowledge of software architecture, design patterns, security best practices, and performance optimization.\n\n## Your Responsibilities\n\n1. **Analyze Code Changes**\n - Review pull request diffs using the GitHub MCP tools\n - Identify potential bugs, logic errors, and edge cases\n - Check for security vulnerabilities (SQL injection, XSS, plaintext secrets)\n - Assess code readability and maintainability\n\n2. **Provide Constructive Feedback**\n - Be specific and actionable\n - Explain the \"why\" behind each suggestion\n - Prioritize issues: Critical > Important > Minor\n - Include code examples for fixes when possible\n\n3. **Generate a Structured Review**\n - **Summary**: Overall assessment in 1-2 sentences\n - **Critical Issues**: Must fix before merge\n - **Important Issues**: Should fix before merge\n - **Minor Issues**: Nice to have improvements\n - **Positive Notes**: What is done well\n - **Recommendation**: Approve, Request Changes, or Comment\n\n## Review Checklist\n\nFor each PR, verify:\n- Code follows project conventions\n- No obvious bugs or logic errors\n- Error handling is appropriate\n- No security vulnerabilities\n- No hardcoded secrets or credentials\n- Tests are included or updated\n- No commented-out code or debug statements\n\nBe thorough but efficient. Focus on meaningful feedback, not nitpicks."
}'
Response:
{
"success": true,
"id": "rT4kM8nXwQ2p",
"name": "Code Reviewer",
"status": "active",
"chatUrl": "/agents/rT4kM8nXwQ2p/chat"
}
Save the agent ID:
export AGENT_ID="rT4kM8nXwQ2p"
Step 4: Configure the GitHub MCP Server
The GitHub MCP server gives your agent tools to interact with the GitHub API --- reading PRs, posting comments, listing repositories, and more.
4.1 Create the MCP Instance
curl -X POST https://us.teamday.ai/api/v1/mcps \
-H "Authorization: Bearer $TEAMDAY_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"mcpType": "github",
"name": "GitHub",
"description": "GitHub integration for code review",
"isActive": true,
"credentials": {
"GITHUB_TOKEN": {
"value": "ghp_your_github_token_here",
"isSecret": true
}
}
}'
Response:
{
"success": true,
"id": "Wz8vN3bRxK5m",
"name": "GitHub",
"mcpType": "github"
}
4.2 Add the MCP to Your Space
Attach the MCP instance to your Code Review Space so the agent can use it:
curl -X PATCH "https://us.teamday.ai/api/v1/spaces/$SPACE_ID" \
-H "Authorization: Bearer $TEAMDAY_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"addMcps": ["Wz8vN3bRxK5m"]
}'
4.3 Alternative: Configure via .mcp.json
If you prefer file-based configuration, you can place a .mcp.json file in the Space filesystem. The agent picks it up automatically:
{
"mcpServers": {
"github": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"env": {
"GITHUB_TOKEN": "${GITHUB_TOKEN}"
}
}
}
}
The ${GITHUB_TOKEN} reference resolves from the Space secrets you stored in Step 2.
Step 5: Run a Code Review
5.1 Via the Chat UI
The simplest way to use your agent is through the TeamDay chat interface. Open the agent's chat URL and ask it to review a PR:
You: Review pull request #42 on myorg/myrepo
Agent: I'll analyze PR #42: "Add user authentication"
[Agent reads the diff using GitHub MCP tools]
## Code Review: PR #42 — Add user authentication
**Summary:** This PR adds basic user authentication with login
and registration. The structure is clean, but there are critical
security issues that must be addressed before merging.
### Critical Issues
**1. Plaintext Password Storage (src/auth/register.ts:45)**
```javascript
// Current:
user.password = password;
// Fix: hash the password
const bcrypt = require('bcrypt');
user.password = await bcrypt.hash(password, 10);
Passwords must never be stored in plaintext.
2. SQL Injection (src/auth/login.ts:78)
// Current:
db.query(`SELECT * FROM users WHERE email = '${email}'`);
// Fix: use parameterized queries
db.query('SELECT * FROM users WHERE email = ?', [email]);
Important Issues
- Missing error handling (register.ts:23) — The async email validation has no try-catch block.
- JWT secret in source code (token.ts:12) — Move
JWT_SECRETto an environment variable.
Minor Issues
- Inconsistent indentation in register.ts
- Unused import on line 3 of login.ts
Positive Notes
- Excellent test coverage (95%)
- Clear function naming conventions
- Good separation of concerns
Recommendation: Request Changes Critical security issues must be addressed before merging.
You: Post this review as a comment on the PR
Agent: Done — review posted to PR #42 with inline comments. View it at: https://github.com/myorg/myrepo/pull/42
### 5.2 Via the API
Trigger a review programmatically using the execute endpoint:
```bash
curl -X POST "https://us.teamday.ai/api/v1/agents/$AGENT_ID/execute" \
-H "Authorization: Bearer $TEAMDAY_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"message": "Review pull request #42 on myorg/myrepo. Post your review as a comment on the PR.",
"spaceId": "'$SPACE_ID'"
}'
Response:
{
"success": true,
"executionId": "exec_8Fk2mN4xRw",
"chatId": "cH7jP3vTqL9n",
"sessionId": "sess_Qw5rY1bKx",
"result": "## Code Review: PR #42 — Add user authentication\n\n..."
}
You can continue the conversation by passing the sessionId in subsequent requests.
Step 6: Schedule Automated Reviews
Use Missions to run reviews on a schedule --- for example, reviewing all open PRs every morning.
Daily Review Mission
curl -X POST https://us.teamday.ai/api/v1/missions \
-H "Authorization: Bearer $TEAMDAY_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"title": "Daily PR Review",
"goal": "Review all open pull requests on myorg/myrepo. For each PR, analyze the diff, identify issues, and post a review comment to GitHub.",
"icon": "code",
"spaceId": "'$SPACE_ID'",
"characterId": "'$AGENT_ID'",
"schedule": {
"type": "cron",
"value": "0 9 * * 1-5"
}
}'
Response:
{
"success": true,
"id": "Xn4pK7cWbR2m",
"title": "Daily PR Review",
"status": "pending",
"schedule": {
"type": "cron",
"value": "0 9 * * 1-5"
}
}
Common cron schedules:
0 9 * * 1-5--- Weekdays at 9:00 AM UTC0 9 * * *--- Every day at 9:00 AM UTC0 */4 * * *--- Every 4 hours
One-Time Review Mission
For a single review run (e.g., before a release):
curl -X POST https://us.teamday.ai/api/v1/missions \
-H "Authorization: Bearer $TEAMDAY_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"title": "Pre-release Review",
"goal": "Review all open PRs targeting the release/v2.0 branch on myorg/myrepo. Flag any critical issues that would block the release.",
"spaceId": "'$SPACE_ID'",
"characterId": "'$AGENT_ID'",
"schedule": {
"type": "once"
}
}'
Integration with CI/CD
You can trigger reviews from GitHub Actions so every PR gets an automated review:
# .github/workflows/ai-code-review.yml
name: AI Code Review
on:
pull_request:
types: [opened, synchronize]
jobs:
review:
runs-on: ubuntu-latest
steps:
- name: Trigger TeamDay Code Review
env:
TEAMDAY_TOKEN: ${{ secrets.TEAMDAY_TOKEN }}
AGENT_ID: ${{ secrets.TEAMDAY_AGENT_ID }}
SPACE_ID: ${{ secrets.TEAMDAY_SPACE_ID }}
run: |
curl -X POST "https://us.teamday.ai/api/v1/agents/$AGENT_ID/execute" \
-H "Authorization: Bearer $TEAMDAY_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"message": "Review pull request #${{ github.event.pull_request.number }} on ${{ github.repository }}. Post a review comment on the PR with your findings.",
"spaceId": "'"$SPACE_ID"'"
}'
Add your TEAMDAY_TOKEN, TEAMDAY_AGENT_ID, and TEAMDAY_SPACE_ID as repository secrets in GitHub.
Troubleshooting
GitHub MCP Not Connecting
Symptom: Agent says it cannot access GitHub tools.
Fix:
- Verify the MCP is attached to the Space (check Space settings)
- Confirm the GitHub token is valid and has
reposcope - Check the MCP instance is set to
isActive: true
Agent Cannot Find the Repository
Symptom: "Repository not found or access denied" error.
Fix:
- Verify the GitHub token has access to the repository
- For organization repos, ensure the token has org access
- Double-check the repository name (case-sensitive)
Review Not Posted to GitHub
Symptom: Agent generates a review but fails to post it.
Fix:
- Ensure the GitHub token has write access (not read-only)
- Check the PR is still open
- Verify GitHub API rate limits have not been exceeded
Cost Estimation
Typical costs for code review:
| Scenario | Input Tokens | Output Tokens | Cost |
|---|---|---|---|
| Single PR review | ~10,000 | ~2,000 | ~$0.10 |
| Daily (10 PRs) | ~100,000 | ~20,000 | ~$1.00/day |
| Monthly (weekdays) | ~2M | ~400K | ~$22/month |
Tips to reduce costs:
- Use
claude-haiku-4-5for smaller PRs or initial triage - Review only changed files, not the entire codebase
- Set reasonable token limits in execution requests
Next Steps
- Analytics Reporter Example --- Build an agent that tracks metrics
- BigQuery Insights Example --- Analyze data with natural language
- API Reference --- Full API documentation
- Missions Guide --- Learn more about scheduling