Reviews API

The Reviews API allows you to programmatically create, retrieve, and manage AI-powered code reviews for your pull requests.

The Review Object

{
  "id": "rev_abc123",
  "pull_request": {
    "url": "https://github.com/owner/repo/pull/123",
    "number": 123,
    "title": "Add user authentication",
    "repository": "owner/repo",
    "branch": "feature/auth",
    "author": "johndoe"
  },
  "status": "completed",
  "score": 92,
  "summary": "High quality code with minor suggestions",
  "stats": {
    "files_changed": 12,
    "lines_added": 245,
    "lines_deleted": 34,
    "comments_count": 8,
    "issues": {
      "critical": 0,
      "important": 2,
      "warning": 4,
      "suggestion": 2
    }
  },
  "created_at": "2025-01-15T10:00:00Z",
  "completed_at": "2025-01-15T10:00:45Z",
  "organization_id": "org_xyz789",
  "team_id": "team_def456"
}

Attributes

AttributeTypeDescription
idstringUnique review identifier
pull_requestobjectPull request details
statusenumReview status: pending, in_progress, completed, failed
scoreintegerCode quality score (0-100)
summarystringAI-generated review summary
statsobjectReview statistics
created_attimestampWhen review was created
completed_attimestampWhen review was completed
organization_idstringOrganization ID
team_idstringTeam ID

Create a Review

Create a new code review for a pull request.

POST /v1/reviews

Parameters

ParameterTypeRequiredDescription
pull_request_urlstringYesGitHub PR URL
auto_reviewbooleanNoStart review automatically (default: true)
inline_commentsbooleanNoPost inline comments (default: true)
check_securitybooleanNoInclude security scan (default: true)
check_performancebooleanNoInclude performance analysis (default: true)
team_idstringNoAssociate with specific team

Example Request

curl -X POST https://api.mesrai.com/v1/reviews \
  -H "Authorization: Bearer msr_live_..." \
  -H "Content-Type: application/json" \
  -d '{
    "pull_request_url": "https://github.com/owner/repo/pull/123",
    "auto_review": true,
    "team_id": "team_def456"
  }'

Response

{
  "data": {
    "id": "rev_abc123",
    "status": "in_progress",
    "pull_request": {
      "url": "https://github.com/owner/repo/pull/123",
      "number": 123
    },
    "created_at": "2025-01-15T10:00:00Z"
  }
}

Retrieve a Review

Retrieve an existing review by ID.

GET /v1/reviews/:id

Example Request

curl https://api.mesrai.com/v1/reviews/rev_abc123 \
  -H "Authorization: Bearer msr_live_..."

Response

{
  "data": {
    "id": "rev_abc123",
    "status": "completed",
    "score": 92,
    "summary": "High quality code with minor suggestions",
    "pull_request": { ... },
    "stats": { ... }
  }
}

List Reviews

List all reviews with optional filtering.

GET /v1/reviews

Query Parameters

ParameterTypeDescription
limitintegerItems per page (default: 25, max: 100)
afterstringCursor for pagination
statusenumFilter by status
team_idstringFilter by team
repositorystringFilter by repository
created_aftertimestampFilter by creation date
created_beforetimestampFilter by creation date
sortstringSort field (e.g., -created_at)

Example Request

curl "https://api.mesrai.com/v1/reviews?status=completed&limit=50&sort=-created_at" \
  -H "Authorization: Bearer msr_live_..."

Response

{
  "data": [
    {
      "id": "rev_abc123",
      "status": "completed",
      "score": 92,
      "created_at": "2025-01-15T10:00:00Z"
    },
    {
      "id": "rev_def456",
      "status": "completed",
      "score": 88,
      "created_at": "2025-01-15T09:30:00Z"
    }
  ],
  "pagination": {
    "has_more": true,
    "next_cursor": "rev_def456"
  }
}

Cancel a Review

Cancel an in-progress review.

POST /v1/reviews/:id/cancel

Example Request

curl -X POST https://api.mesrai.com/v1/reviews/rev_abc123/cancel \
  -H "Authorization: Bearer msr_live_..."

Response

{
  "data": {
    "id": "rev_abc123",
    "status": "cancelled"
  }
}

Retry a Failed Review

Retry a failed review.

POST /v1/reviews/:id/retry

Example Request

curl -X POST https://api.mesrai.com/v1/reviews/rev_abc123/retry \
  -H "Authorization: Bearer msr_live_..."

Review Comments

List Comments

Get all comments for a review.

GET /v1/reviews/:id/comments

Example Request

curl https://api.mesrai.com/v1/reviews/rev_abc123/comments \
  -H "Authorization: Bearer msr_live_..."

Response

{
  "data": [
    {
      "id": "cmt_xyz789",
      "type": "security",
      "severity": "critical",
      "message": "Potential SQL injection vulnerability",
      "file": "src/api/users.js",
      "line": 42,
      "suggestion": "Use parameterized queries instead of string concatenation",
      "code_snippet": "const query = `SELECT * FROM users WHERE id = ${userId}`"
    },
    {
      "id": "cmt_uvw456",
      "type": "performance",
      "severity": "warning",
      "message": "N+1 query detected",
      "file": "src/api/posts.js",
      "line": 67
    }
  ]
}

Comment Object

AttributeTypeDescription
idstringComment identifier
typeenumsecurity, performance, style, bug, suggestion
severityenumcritical, important, warning, info
messagestringComment message
filestringFile path
lineintegerLine number
suggestionstringSuggested fix
code_snippetstringRelevant code

Review Statistics

Get detailed statistics for a review.

GET /v1/reviews/:id/stats

Response

{
  "data": {
    "files_analyzed": 12,
    "lines_analyzed": 2450,
    "complexity_avg": 4.2,
    "test_coverage": 87,
    "issues_by_type": {
      "security": 2,
      "performance": 4,
      "style": 8,
      "bug": 1,
      "suggestion": 12
    },
    "issues_by_severity": {
      "critical": 1,
      "important": 3,
      "warning": 8,
      "info": 17
    },
    "processing_time_ms": 45000,
    "tokens_used": 12450
  }
}

Webhooks

Subscribe to review events via webhooks:

  • review.created - Review was created
  • review.in_progress - Review started processing
  • review.completed - Review finished successfully
  • review.failed - Review failed
  • review.cancelled - Review was cancelled

See Webhooks API for details.

Best Practices

1. Poll for Completion

Reviews typically complete in 30-60 seconds. Poll the status:

async function waitForCompletion(reviewId) {
  while (true) {
    const review = await mesrai.reviews.retrieve(reviewId)
 
    if (review.status === 'completed') {
      return review
    }
 
    if (review.status === 'failed') {
      throw new Error('Review failed')
    }
 
    // Wait 5 seconds before next check
    await new Promise(resolve => setTimeout(resolve, 5000))
  }
}

2. Use Webhooks for Real-time Updates

Instead of polling, use webhooks:

// Setup webhook
await mesrai.webhooks.create({
  url: 'https://your-app.com/webhooks/mesrai',
  events: ['review.completed', 'review.failed']
})
 
// Handle webhook
app.post('/webhooks/mesrai', (req, res) => {
  const event = req.body
 
  if (event.type === 'review.completed') {
    const review = event.data
    console.log(`Review ${review.id} completed with score ${review.score}`)
  }
 
  res.sendStatus(200)
})

3. Handle Errors Gracefully

try {
  const review = await mesrai.reviews.create({ ... })
} catch (error) {
  if (error.code === 'invalid_pr_url') {
    // Handle invalid PR URL
    console.error('Invalid PR URL provided')
  } else if (error.code === 'rate_limit_exceeded') {
    // Wait and retry
    await sleep(60000)
    return retry()
  } else {
    // Log and alert
    logger.error('Failed to create review', error)
  }
}

4. Use Idempotency for Safety

const idempotencyKey = `review-${prNumber}-${timestamp}`
 
const review = await mesrai.reviews.create({
  pullRequestUrl: prUrl,
  idempotencyKey
})

5. Batch Processing

Process multiple PRs efficiently:

const prs = [
  'https://github.com/owner/repo/pull/1',
  'https://github.com/owner/repo/pull/2',
  'https://github.com/owner/repo/pull/3'
]
 
// Create reviews in parallel
const reviews = await Promise.all(
  prs.map(url => mesrai.reviews.create({ pullRequestUrl: url }))
)
 
// Wait for all to complete
const completed = await Promise.all(
  reviews.map(r => waitForCompletion(r.id))
)
 
console.log(`Completed ${completed.length} reviews`)

Common Use Cases

CI/CD Integration

Integrate with your CI/CD pipeline:

# .github/workflows/code-review.yml
name: AI Code Review
 
on: [pull_request]
 
jobs:
  review:
    runs-on: ubuntu-latest
    steps:
      - name: Trigger Mesrai Review
        run: |
          curl -X POST https://api.mesrai.com/v1/reviews \
            -H "Authorization: Bearer ${{ secrets.MESRAI_API_KEY }}" \
            -H "Content-Type: application/json" \
            -d "{
              \"pull_request_url\": \"${{ github.event.pull_request.html_url }}\",
              \"auto_review\": true
            }"

Automated Reporting

Generate daily review reports:

const startOfDay = new Date()
startOfDay.setHours(0, 0, 0, 0)
 
const reviews = await mesrai.reviews.list({
  createdAfter: startOfDay.toISOString(),
  status: 'completed',
  limit: 100
})
 
const stats = {
  total: reviews.data.length,
  avgScore: reviews.data.reduce((sum, r) => sum + r.score, 0) / reviews.data.length,
  criticalIssues: reviews.data.reduce((sum, r) => sum + r.stats.issues.critical, 0)
}
 
console.log(`Daily Report: ${stats.total} reviews, avg score ${stats.avgScore}`)

Quality Gates

Block merges based on review score:

const review = await mesrai.reviews.create({ ... })
await waitForCompletion(review.id)
 
if (review.score < 80) {
  console.error(`Review score ${review.score} below threshold`)
  process.exit(1)
}
 
if (review.stats.issues.critical > 0) {
  console.error(`${review.stats.issues.critical} critical issues found`)
  process.exit(1)
}
 
console.log('Quality gate passed ✓')

Rate Limits

Reviews API rate limits:

PlanRate LimitBurst
Free10 reviews/hour20 reviews/day
Pro100 reviews/hour500 reviews/day
Enterprise1000 reviews/hourUnlimited

Rate limits are per organization. Contact sales for higher limits.

Next Steps

Need help? Contact api@mesrai.com or join our Discord.