AI代码分析服务器

一个基于Codex和Gemini CLI的AI代码分析服务器,提供智能、自动化的代码审查功能,支持多AI代理和结果聚合。

  • by physics91
  • TypeScript
  • 本地部署
  • 更新于
在 GitHub 查看 physics91/ai-code-review-mcp

使用说明

AI代码代理MCP服务器

一个全面的模型上下文协议(MCP)服务器,使用Codex CLI和Gemini CLI提供AI驱动的代码分析功能。该服务器支持智能、自动化的代码分析,支持多个AI代理、查找聚合以及详细的安全和性能评估。

特性

  • 双AI审查引擎:利用Codex和Gemini进行全面的代码分析
  • 综合评论:通过智能重复数据删除汇总多个审阅者的发现
  • 类型安全:使用TypeScript和Zod构建,用于运行时验证
  • 可配置的:通过JSON、环境变量或代码提供广泛的配置选项
  • 生产准备就绪:包括重试逻辑、错误处理、日志记录和监视
  • 安全:输入验证、CLI清理和安全第一设计
  • 灵活的:支持多种编程语言并审查重点领域

架构概述

+---------------------------------------------------------------+
|                      MCP Client (Claude)                       |
+---------------------------+-----------------------------------+
                            | MCP Protocol (stdio)
                            v
+---------------------------------------------------------------+
|                 Code Review MCP Server                         |
|  +------------------+         +------------------+            |
|  |  Codex Service   |         |  Gemini Service  |            |
|  |  (CLI Direct)    |         |  (CLI Direct)    |            |
|  +--------+---------+         +--------+---------+            |
|           |                            |                       |
|           +------------+---------------+                       |
|                        v                                       |
|           +--------------------+                               |
|           | Review Aggregator  |                               |
|           | & Deduplication    |                               |
|           +--------------------+                               |
+---------------------------------------------------------------+

安装

来自NPM(推荐)

# Install globally
npm install -g ai-code-agent-mcp

# Or use directly with npx
npx ai-code-agent-mcp

NPM包: ai代码代理mcp

来源

git clone https://github.com/physics91/ai-code-review-mcp.git
cd ai-code-review-mcp
npm install
npm run build
npm link

使用Docker

docker pull code-review-mcp:latest
docker run -v ./config.json:/config.json code-review-mcp

先决条件

  • Node.js 20.0.0或更高版本
  • 已安装并配置Gemini CLI(供Gemini评测)
  • 已安装并配置Codex CLI(用于Codex审查)

安装CLIs

Codex CLI

# Install from npm
npm install -g @anthropic-ai/codex

# Verify installation
codex --version

双子星命令行工具

# Example installation (adjust based on your system)
npm install -g @google/gemini-cli
# or
brew install gemini-cli

CLI路径自动检测

服务器会根据您的平台和环境自动检测CLI路径。在大多数情况下,您不需要指定确切的路径!

优先顺序

  1. 环境变量 (最高优先级)

    • CODEX_CLI_PATH -自定义Codex CLI路径
    • GEMINI_CLI_PATH -自定义Gemini CLI路径
  2. 配置文件 -中的显式路径 config.json

  3. 平台特定路径 (自动检测)

    • macOS/Linux:

      • /usr/local/bin/{cli}
      • /usr/bin/{cli}
      • /opt/{cli}/bin/{cli}
      • ~/.local/bin/{cli}
      • /opt/homebrew/bin/{cli} (macOS Homebrew)
    • 窗户:

      • %APPDATA%\npm\{cli}.cmd
      • C:\Program Files\{cli}\{cli}.exe
      • C:\Program Files\Google\Gemini\gemini.exe (仅限双子座)
  4. 系统路径 - which (Unix)或 where (Windows)命令

  5. 后备方案 -假设CLI位于PATH中

配置选项

选项1:自动检测(推荐)

{
  "codex": {
    "cliPath": "auto"  // Automatically detects CLI path
  },
  "gemini": {
    "cliPath": "auto"  // Automatically detects CLI path
  }
}

选项2:环境变量

# Set custom CLI paths
export CODEX_CLI_PATH="/custom/path/codex"
export GEMINI_CLI_PATH="/opt/google/gemini/gemini"

选项3:显式配置

{
  "codex": {
    "cliPath": "/usr/local/bin/codex"
  },
  "gemini": {
    "cliPath": "/opt/gemini/bin/gemini"
  }
}

选项4:默认命令名

{
  "codex": {
    "cliPath": "codex"  // Uses 'codex' from PATH
  },
  "gemini": {
    "cliPath": "gemini"  // Uses 'gemini' from PATH
  }
}

检测日志

服务器在启动时记录检测到的CLI路径:

[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"
}

检测源:

  • env -来自环境变量
  • config -来自配置文件
  • detected -从平台特定路径自动检测
  • which -发现使用 which/where 命令
  • default -回退到命令名(如果不在PATH中,可能会失败)

配置

Claude桌面集成

添加到您的Claude Desktop配置(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"
      }
    }
  }
}

注意:默认情况下,CLI路径会自动检测。仅设置 CODEX_CLI_PATH 或 GEMINI_CLI_PATH 如果你需要覆盖检测。

配置文件

创建 config.json 在您的项目中,或使用默认配置:

{
  "server": {
    "name": "code-review-mcp",
    "version": "1.2.1",
    "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
    }
  }
}

注: "cliPath": "auto" 启用自动CLI路径检测。您还可以指定:

  • "auto" -自动检测(推荐)
  • "codex" / "gemini" -使用PATH中的命令
  • 绝对路径-CLI二进制文件的显式路径

环境变量

创建 .env 文件:

# 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=true

用法

可用工具

MCP服务器公开了以下工具:

1.使用索引分析代码

使用Codex AI执行代码分析。

输入参数:

{
  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
  };
}

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"]
  }
}

输出:

{
  "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.与戈米尼一起分析代码

使用Gemini CLI执行代码分析。

输入参数: 同 analyze_code_with_codex

示例用法:

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.分析代码组合

使用Codex和Gemini进行代码分析,然后汇总结果。

输入参数:

{
  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
  };
}

示例用法:

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
  }
}

输出:

{
  "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.获取分析状态

检查异步分析操作的状态(以获得未来的异步支持)。

输入参数:

{
  analysisId: string; // UUID of the analysis
}

高级用法

自定义审核焦点

{
  "code": "...",
  "context": {
    "reviewFocus": ["security", "performance"]
  }
}

重点领域:

  • security:SQL注入、XSS、身份验证问题
  • performance:算法效率低下,内存泄漏
  • style:代码格式、命名约定
  • bugs:逻辑错误、边缘情况
  • all:全面审查(默认)

严重性筛选

{
  "code": "...",
  "options": {
    "severity": "high" // Only show critical and high severity issues
  }
}

并行执行

为了更快地进行组合分析:

{
  "code": "...",
  "options": {
    "parallelExecution": true // Run Codex and Gemini concurrently
  }
}

配置参考

服务器配置

选项 类型 默认值 描述
server.name string “ai代码代理mcp” 服务器名称
server.version string “1.2.1” 服务器版本
server.logLevel string “info” 日志级别(调试/信息/警告/错误)

Codex配置

选项 类型 默认值 描述
codex.enabled boolean true 启用Codex分析
codex.timeout number 60000 超时(毫秒)
codex.retryAttempts number 3 重试次数
codex.model string null Codex模型覆盖

Gemini配置

选项 类型 默认值 描述
gemini.enabled boolean true 启用Gemini分析
gemini.cliPath string “/usr/local/bin/gemini” gemini CLI的路径
gemini.timeout number 60000 超时(毫秒)
gemini.retryAttempts number 3 重试次数
gemini.model string null Gemini模型覆盖

分析配置

选项 类型 默认值 描述
analysis.maxCodeLength number 50000 最大代码长度(字节)
analysis.deduplication.enabled boolean true 启用查找重复数据删除
analysis.deduplication.similarityThreshold 数值 0.8 相似性阈值(0-1)

错误处理

服务器包括全面的错误处理:

// Errors are returned in a structured format
{
  "success": false,
  "error": {
    "type": "TIMEOUT_ERROR",
    "message": "Review timed out after 60000ms",
    "code": "ERR_TIMEOUT",
    "details": { ... }
  }
}

常见错误类型:

  • VALIDATION_ERROR:输入参数无效
  • TIMEOUT_ERROR:操作超时
  • CLI_EXECUTION_ERROR:CLI执行失败
  • PARSE_ERROR:无法解析CLI输出
  • CONFIGURATION_ERROR:配置无效

安全注意事项

  1. 输入验证:所有输入都使用Zod模式进行验证
  2. CLI安全:CLI路径已列入白名单,无法进行shell注入
  3. 代码长度限制:通过大负载防止DoS
  4. 消毒:从日志中编辑敏感数据
  5. 重试限制:防止无限次重试循环

演出

绩效目标:

  • 单次分析:<5s(典型),<30s(最大)
  • 组合分析:<8s(典型),<60s(最大)
  • 内存使用量:<200MB(活动),<50MB(空闲)
  • 并发评论:10(默认),50(最多)

日志记录

使用Pino的结构化JSON日志:

{
  "level": "info",
  "timestamp": "2025-01-17T10:30:00.000Z",
  "msg": "Analysis completed",
  "analysisId": "uuid",
  "source": "codex",
  "duration": 4532,
  "findings": 12
}

通过环境设置日志级别:

CODE_REVIEW_MCP_LOG_LEVEL=debug

发展

设置

git clone https://github.com/physics91/ai-code-agent-mcp.git
cd ai-code-agent-mcp
npm install

发展模式

npm run dev

构建

npm run build

测试

# Run tests
npm test

# Run tests with coverage
npm run test:coverage

# Run tests with UI
npm run test:ui

类型检查

npm run typecheck

掉毛

npm run lint
npm run lint:fix

故障排除

未找到Codex MCP工具

解决方案:确保Codex MCP工具在您的MCP客户端中正确注册。

Gemini CLI执行失败

解决方案:

  1. 验证是否安装了Gemini CLI: gemini --version
  2. 检查配置中的CLI路径
  3. 确保可执行权限: chmod +x /path/to/gemini

分析超时

解决方案:

  1. 增加配置中的超时时间
  2. 减少代码长度
  3. 检查系统资源

内存使用率高

解决方案:

  1. 如果不需要,禁用缓存
  2. 减少 maxConcurrent 设置
  3. 检查日志是否存在内存泄漏

文档

有关详细文档,请参阅:

核心文件

参考

发展历程

贡献

欢迎投稿!请阅读我们的投稿指南和行为准则。

  1. 分叉存储库
  2. 创建要素分支
  3. 进行更改
  4. 添加测试
  5. 提交拉取请求

许可证

MIT许可证-有关详细信息,请参阅许可证文件

支持

  • GitHub问题:https://github.com/physics91/ai-code-agent-mcp/issues
  • 文档:https://github.com/physics91/ai-code-agent-mcp/wiki
  • 讨论:https://github.com/physics91/ai-code-agent-mcp/discussions

路线图

短期(3-6个月)

  • []支持其他AI分析器
  • []自定义分析模板
  • []分析历史和分析
  • []Webhook通知
  • []多文件项目分析
  • []人工智能辩论/讨论功能

长期(6-12个月)

  • []基于机器学习的查找优先级
  • []CI/CD集成
  • []分析协作功能
  • []插件系统
  • []Web仪表板

致谢


版本: 1.2.1 最后更新: 2025-12-15 状态:生产就绪