ai-code-agent-mcp
v1.2.1
Published
MCP server for AI-powered code analysis using Codex and Gemini
Maintainers
Readme
AI Code Agent MCP Server
A comprehensive Model Context Protocol (MCP) server that provides AI-powered code analysis capabilities using both Codex CLI and Gemini CLI. This server enables intelligent, automated code analysis with support for multiple AI agents, finding aggregation, and detailed security and performance assessments.
Features
- Dual AI Review Engines: Leverage both Codex and Gemini for comprehensive code analysis
- Combined Reviews: Aggregate findings from multiple reviewers with intelligent deduplication
- Type-Safe: Built with TypeScript and Zod for runtime validation
- Configurable: Extensive configuration options via JSON, environment variables, or code
- Production-Ready: Includes retry logic, error handling, logging, and monitoring
- Secure: Input validation, CLI sanitization, and security-first design
- Flexible: Support for multiple programming languages and review focus areas
Architecture Overview
+---------------------------------------------------------------+
| MCP Client (Claude) |
+---------------------------+-----------------------------------+
| MCP Protocol (stdio)
v
+---------------------------------------------------------------+
| Code Review MCP Server |
| +------------------+ +------------------+ |
| | Codex Service | | Gemini Service | |
| | (CLI Direct) | | (CLI Direct) | |
| +--------+---------+ +--------+---------+ |
| | | |
| +------------+---------------+ |
| v |
| +--------------------+ |
| | Review Aggregator | |
| | & Deduplication | |
| +--------------------+ |
+---------------------------------------------------------------+Installation
From NPM (Recommended)
# Install globally
npm install -g ai-code-agent-mcp
# Or use directly with npx
npx ai-code-agent-mcpNPM Package: ai-code-agent-mcp
From Source
git clone https://github.com/physics91/ai-code-review-mcp.git
cd ai-code-review-mcp
npm install
npm run build
npm linkUsing Docker
docker pull code-review-mcp:latest
docker run -v ./config.json:/config.json code-review-mcpPrerequisites
- Node.js 20.0.0 or higher
- Gemini CLI installed and configured (for Gemini reviews)
- Codex CLI installed and configured (for Codex reviews)
Installing CLIs
Codex CLI
# Install from npm
npm install -g @anthropic-ai/codex
# Verify installation
codex --versionGemini CLI
# Example installation (adjust based on your system)
npm install -g @google/gemini-cli
# or
brew install gemini-cliCLI Path Auto-Detection
The server automatically detects CLI paths based on your platform and environment. You don't need to specify the exact path in most cases!
Priority Order
Environment Variables (highest priority)
CODEX_CLI_PATH- Custom Codex CLI pathGEMINI_CLI_PATH- Custom Gemini CLI path
Config File - Explicit path in
config.jsonPlatform-Specific Paths (auto-detected)
macOS / Linux:
/usr/local/bin/{cli}/usr/bin/{cli}/opt/{cli}/bin/{cli}~/.local/bin/{cli}/opt/homebrew/bin/{cli}(macOS Homebrew)
Windows:
%APPDATA%\npm\{cli}.cmdC:\Program Files\{cli}\{cli}.exeC:\Program Files\Google\Gemini\gemini.exe(Gemini only)
System PATH -
which(Unix) orwhere(Windows) commandFallback - Assumes CLI is in PATH
Configuration Options
Option 1: Auto-Detection (Recommended)
{
"codex": {
"cliPath": "auto" // Automatically detects CLI path
},
"gemini": {
"cliPath": "auto" // Automatically detects CLI path
}
}Option 2: Environment Variables
# Set custom CLI paths
export CODEX_CLI_PATH="/custom/path/codex"
export GEMINI_CLI_PATH="/opt/google/gemini/gemini"Option 3: Explicit Configuration
{
"codex": {
"cliPath": "/usr/local/bin/codex"
},
"gemini": {
"cliPath": "/opt/gemini/bin/gemini"
}
}Option 4: Default Command Name
{
"codex": {
"cliPath": "codex" // Uses 'codex' from PATH
},
"gemini": {
"cliPath": "gemini" // Uses 'gemini' from PATH
}
}Detection Logs
The server logs the detected CLI paths on startup:
[INFO] Codex CLI path detected {
path: "/usr/local/bin/codex",
source: "detected",
exists: true,
platform: "darwin"
}
[INFO] Gemini CLI path detected {
path: "/opt/homebrew/bin/gemini",
source: "detected",
exists: true,
platform: "darwin"
}Detection sources:
env- From environment variableconfig- From configuration filedetected- Auto-detected from platform-specific pathswhich- Found usingwhich/wherecommanddefault- Fallback to command name (may fail if not in PATH)
Configuration
Claude Desktop Integration
Add to your Claude Desktop configuration (claude_desktop_config.json):
{
"mcpServers": {
"code-review": {
"command": "node",
"args": ["/path/to/code-review-mcp/dist/index.js"],
"env": {
"CODE_REVIEW_MCP_LOG_LEVEL": "info",
"CODEX_ENABLED": "true",
"GEMINI_ENABLED": "true"
}
}
}
}Note: CLI paths are auto-detected by default. Only set CODEX_CLI_PATH or GEMINI_CLI_PATH if you need to override the detection.
Configuration File
Create a config.json in your project or use the default configuration:
{
"server": {
"name": "code-review-mcp",
"version": "1.2.0",
"logLevel": "info"
},
"codex": {
"enabled": true,
"cliPath": "auto",
"timeout": 60000,
"retryAttempts": 3,
"model": "gpt-5",
"search": true,
"reasoningEffort": "high",
"args": []
},
"gemini": {
"enabled": true,
"cliPath": "auto",
"timeout": 60000,
"retryAttempts": 3,
"model": "gemini-3-pro-preview",
"args": []
},
"review": {
"maxCodeLength": 50000,
"deduplication": {
"enabled": true,
"similarityThreshold": 0.8
}
}
}Note: "cliPath": "auto" enables automatic CLI path detection. You can also specify:
"auto"- Auto-detect (recommended)"codex"/"gemini"- Use command from PATH- Absolute path - Explicit path to CLI binary
Environment Variables
Create a .env file:
# Copy example configuration
cp .env.example .env
# Edit with your settings
CODEX_CLI_PATH=codex
CODEX_MODEL=claude-opus-4
GEMINI_CLI_PATH=/usr/local/bin/gemini
GEMINI_MODEL=gemini-pro
CODEX_ENABLED=true
GEMINI_ENABLED=trueUsage
Available Tools
The MCP server exposes the following tools:
1. analyze_code_with_codex
Perform code analysis using Codex AI.
Input Parameters:
{
code: string; // Source code to review (max 50KB)
language?: string; // Programming language (auto-detect if omitted)
context?: {
fileName?: string; // File name for context
projectType?: string; // e.g., "web", "backend", "mobile"
reviewFocus?: Array< // What to focus on
'security' | 'performance' | 'style' | 'bugs' | 'all'
>;
};
options?: {
timeout?: number; // Timeout in ms (default: 60000)
includeExplanations?: boolean; // Include detailed explanations
severity?: 'all' | 'high' | 'medium'; // Filter by severity
};
}Example Usage in Claude:
Please analyze this code using Codex:
[Call: analyze_code_with_codex]
{
"code": "function calculateTotal(items) { let total = 0; for(let i=0; i<=items.length; i++) { total += items[i].price; } return total; }",
"language": "javascript",
"context": {
"fileName": "cart.js",
"reviewFocus": ["bugs", "security"]
}
}Output:
{
"success": true,
"reviewId": "uuid",
"timestamp": "2025-01-17T10:30:00.000Z",
"source": "codex",
"summary": {
"totalFindings": 3,
"critical": 1,
"high": 1,
"medium": 1,
"low": 0
},
"findings": [
{
"type": "bug",
"severity": "critical",
"line": 1,
"title": "Off-by-one error in loop",
"description": "Loop condition uses <= instead of <, causing array index out of bounds",
"suggestion": "Change i<=items.length to i<items.length",
"code": "for(let i=0; i<items.length; i++)"
}
],
"overallAssessment": "Code has critical bugs that need immediate fixing",
"recommendations": [
"Add input validation for items parameter",
"Consider using Array.reduce() for cleaner code"
]
}2. analyze_code_with_gemini
Perform code analysis using Gemini CLI.
Input Parameters: Same as analyze_code_with_codex
Example Usage:
Analyze this Python code with Gemini:
[Call: analyze_code_with_gemini]
{
"code": "def process_data(data):\n result = []\n for item in data:\n result.append(item * 2)\n return result",
"language": "python",
"context": {
"reviewFocus": ["performance", "style"]
}
}3. analyze_code_combined
Perform code analysis using both Codex and Gemini, then aggregate results.
Input Parameters:
{
code: string;
language?: string;
context?: {
fileName?: string;
projectType?: string;
reviewFocus?: Array<'security' | 'performance' | 'style' | 'bugs' | 'all'>;
};
options?: {
timeout?: number; // Timeout for entire operation
includeExplanations?: boolean;
severity?: 'all' | 'high' | 'medium';
parallelExecution?: boolean; // Run both analyzers in parallel
includeIndividualAnalyses?: boolean; // Include separate analyses in output
};
}Example Usage:
Please perform a comprehensive analysis using both Codex and Gemini:
[Call: analyze_code_combined]
{
"code": "class UserAuth { login(user, pass) { if(user && pass) { return db.query('SELECT * FROM users WHERE username=' + user); } } }",
"language": "javascript",
"context": {
"fileName": "auth.js",
"reviewFocus": ["security", "bugs"]
},
"options": {
"parallelExecution": true,
"includeIndividualAnalyses": false
}
}Output:
{
"success": true,
"reviewId": "uuid",
"timestamp": "2025-01-17T10:30:00.000Z",
"source": "combined",
"summary": {
"totalFindings": 5,
"critical": 2,
"high": 2,
"medium": 1,
"low": 0,
"consensus": 85
},
"findings": [
{
"type": "security",
"severity": "critical",
"line": 4,
"title": "SQL Injection vulnerability",
"description": "User input directly concatenated into SQL query",
"suggestion": "Use parameterized queries or ORM",
"sources": ["codex", "gemini"],
"confidence": "high"
}
],
"overallAssessment": "Combined analysis from 2 analyzers: Found 2 critical issues that require immediate attention.",
"metadata": {
"analysisDuration": 4523,
"codexDuration": 2341,
"geminiDuration": 2182
}
}4. get_analysis_status
Check the status of an async analysis operation (for future async support).
Input Parameters:
{
analysisId: string; // UUID of the analysis
}Advanced Usage
Custom Review Focus
{
"code": "...",
"context": {
"reviewFocus": ["security", "performance"]
}
}Focus areas:
security: SQL injection, XSS, authentication issuesperformance: Inefficient algorithms, memory leaksstyle: Code formatting, naming conventionsbugs: Logic errors, edge casesall: Comprehensive review (default)
Severity Filtering
{
"code": "...",
"options": {
"severity": "high" // Only show critical and high severity issues
}
}Parallel Execution
For faster combined analyses:
{
"code": "...",
"options": {
"parallelExecution": true // Run Codex and Gemini concurrently
}
}Configuration Reference
Server Configuration
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| server.name | string | "ai-code-agent-mcp" | Server name |
| server.version | string | "1.2.0" | Server version |
| server.logLevel | string | "info" | Log level (debug/info/warn/error) |
Codex Configuration
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| codex.enabled | boolean | true | Enable Codex analysis |
| codex.timeout | number | 60000 | Timeout in milliseconds |
| codex.retryAttempts | number | 3 | Number of retry attempts |
| codex.model | string | null | Codex model override |
Gemini Configuration
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| gemini.enabled | boolean | true | Enable Gemini analysis |
| gemini.cliPath | string | "/usr/local/bin/gemini" | Path to Gemini CLI |
| gemini.timeout | number | 60000 | Timeout in milliseconds |
| gemini.retryAttempts | number | 3 | Number of retry attempts |
| gemini.model | string | null | Gemini model override |
Analysis Configuration
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| analysis.maxCodeLength | number | 50000 | Maximum code length in bytes |
| analysis.deduplication.enabled | boolean | true | Enable finding deduplication |
| analysis.deduplication.similarityThreshold | number | 0.8 | Similarity threshold (0-1) |
Error Handling
The server includes comprehensive error handling:
// Errors are returned in a structured format
{
"success": false,
"error": {
"type": "TIMEOUT_ERROR",
"message": "Review timed out after 60000ms",
"code": "ERR_TIMEOUT",
"details": { ... }
}
}Common error types:
VALIDATION_ERROR: Invalid input parametersTIMEOUT_ERROR: Operation timed outCLI_EXECUTION_ERROR: CLI execution failedPARSE_ERROR: Failed to parse CLI outputCONFIGURATION_ERROR: Invalid configuration
Security Considerations
- Input Validation: All inputs are validated using Zod schemas
- CLI Safety: CLI paths are whitelisted, no shell injection possible
- Code Length Limits: Prevents DoS via large payloads
- Sanitization: Sensitive data is redacted from logs
- Retry Limits: Prevents infinite retry loops
Performance
Performance targets:
- Single analysis: <5s (typical), <30s (maximum)
- Combined analysis: <8s (typical), <60s (maximum)
- Memory usage: <200MB (active), <50MB (idle)
- Concurrent reviews: 10 (default), 50 (maximum)
Logging
Structured JSON logs with Pino:
{
"level": "info",
"timestamp": "2025-01-17T10:30:00.000Z",
"msg": "Analysis completed",
"analysisId": "uuid",
"source": "codex",
"duration": 4532,
"findings": 12
}Set log level via environment:
CODE_REVIEW_MCP_LOG_LEVEL=debugDevelopment
Setup
git clone https://github.com/physics91/ai-code-agent-mcp.git
cd ai-code-agent-mcp
npm installDevelopment Mode
npm run devBuild
npm run buildTesting
# Run tests
npm test
# Run tests with coverage
npm run test:coverage
# Run tests with UI
npm run test:uiType Checking
npm run typecheckLinting
npm run lint
npm run lint:fixTroubleshooting
Codex MCP tool not found
Solution: Ensure the Codex MCP tool is properly registered in your MCP client.
Gemini CLI execution fails
Solution:
- Verify Gemini CLI is installed:
gemini --version - Check CLI path in configuration
- Ensure executable permissions:
chmod +x /path/to/gemini
Analysis timeout
Solution:
- Increase timeout in configuration
- Reduce code length
- Check system resources
High memory usage
Solution:
- Disable cache if not needed
- Reduce
maxConcurrentsetting - Check logs for memory leaks
Documentation
For detailed documentation, please refer to:
Core Documentation
- Implementation Guide - Step-by-step implementation guide
- Usage Examples - Real-world usage examples
- Project Summary - Project overview and objectives
Reference
- Architecture - System architecture and design
- Specifications - Technical specifications
Development History
- Migration Documentation - CLI migration guides
- Development Notes - Implementation status and fixes
Contributing
Contributions are welcome! Please read our contributing guidelines and code of conduct.
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests
- Submit a pull request
License
MIT License - see LICENSE file for details
Support
- GitHub Issues: https://github.com/physics91/ai-code-agent-mcp/issues
- Documentation: https://github.com/physics91/ai-code-agent-mcp/wiki
- Discussions: https://github.com/physics91/ai-code-agent-mcp/discussions
Roadmap
Short-term (3-6 months)
- [ ] Support for additional AI analyzers
- [ ] Custom analysis templates
- [ ] Analysis history and analytics
- [ ] Webhook notifications
- [ ] Multi-file project analysis
- [ ] AI debate/discussion features
Long-term (6-12 months)
- [ ] ML-based finding prioritization
- [ ] CI/CD integrations
- [ ] Analysis collaboration features
- [ ] Plugin system
- [ ] Web dashboard
Acknowledgments
- Built with @modelcontextprotocol/sdk
- Powered by Codex and Gemini AI
- Inspired by the MCP community
Version: 1.2.0 Last Updated: 2025-12-15 Status: Production Ready
