# Code Review Bot

Build an AI agent that reviews GitHub pull requests, catches bugs, and suggests improvements

# 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 `repo` scope
- Basic understanding of Git and GitHub

## Architecture Overview

```mermaid
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.

1. Go to **Settings > API Keys** in the TeamDay app
2. Click **Create API Key**
3. Copy the token and store it securely

```bash
export TEAMDAY_TOKEN="your-api-token-here"
```

For full details, see the [Authentication guide](https://docs.teamday.ai/api/authentication).

## Step 2: Set Up a Space

Create a Space for your code review work. You can do this in the TeamDay UI:

1. Open the TeamDay app
2. Click **New Space**
3. Name it "Code Review Workspace"
4. Note the Space ID (visible in the URL or settings)

```bash
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:

```bash
curl -X POST "https://cc.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:

```json
{
  "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:

```bash
curl -X POST https://cc.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:

```json
{
  "success": true,
  "id": "rT4kM8nXwQ2p",
  "name": "Code Reviewer",
  "status": "active",
  "chatUrl": "/agents/rT4kM8nXwQ2p/chat"
}
```

Save the agent ID:

```bash
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

```bash
curl -X POST https://cc.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:

```json
{
  "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:

```bash
curl -X PATCH "https://cc.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:

```json
{
  "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)**
```javascript
// Current:
db.query(`SELECT * FROM users WHERE email = '${email}'`);

// Fix: use parameterized queries
db.query('SELECT * FROM users WHERE email = ?', [email]);
```

### Important Issues

1. **Missing error handling (register.ts:23)** — The async
   email validation has no try-catch block.
2. **JWT secret in source code (token.ts:12)** — Move
   `JWT_SECRET` to 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://cc.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:

```json
{
  "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

```bash
curl -X POST https://cc.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"
    }
  }'
```

Note: `characterId` is the agent's ID in the API.

Response:

```json
{
  "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 UTC
- `0 9 * * *` --- Every day at 9:00 AM UTC
- `0 */4 * * *` --- Every 4 hours

### One-Time Review Mission

For a single review run (e.g., before a release):

```bash
curl -X POST https://cc.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:

```yaml
# .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://cc.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:**
1. Verify the MCP is attached to the Space (check Space settings)
2. Confirm the GitHub token is valid and has `repo` scope
3. Check the MCP instance is set to `isActive: true`

### Agent Cannot Find the Repository

**Symptom:** "Repository not found or access denied" error.

**Fix:**
1. Verify the GitHub token has access to the repository
2. For organization repos, ensure the token has org access
3. Double-check the repository name (case-sensitive)

### Review Not Posted to GitHub

**Symptom:** Agent generates a review but fails to post it.

**Fix:**
1. Ensure the GitHub token has write access (not read-only)
2. Check the PR is still open
3. 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-5` for 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](https://docs.teamday.ai/examples/analytics-reporter) --- Build an agent that tracks metrics
- [BigQuery Insights Example](https://docs.teamday.ai/examples/bigquery-insights) --- Analyze data with natural language
- [API Reference](https://docs.teamday.ai/api/) --- Full API documentation
- [Missions Guide](https://docs.teamday.ai/guides/missions-user-guide) --- Learn more about scheduling

## Resources

- [GitHub MCP Server](https://github.com/modelcontextprotocol/servers/tree/main/src/github)
- [Google's Code Review Best Practices](https://google.github.io/eng-practices/review/)
- [TeamDay on GitHub](https://github.com/TeamDay-AI/teamday)
