本项目是一个全面的TypeScript MCP服务器,借助本地AI模型(通过Ollama)对代码进行智能审计,涵盖安全性、完整性、性能、质量、架构、测试和文档等多个维度。
MCP代码审计服务器是一款强大的工具,可利用本地AI模型对代码进行多维度的审计。以下是快速上手的步骤:
# 从npm全局安装
npm install -g @moikas/code-audit-mcp
# 运行交互式设置(包括MCP配置)
code-audit setup
# 或者使用自动MCP配置进行设置
code-audit setup --auto
# 启动MCP服务器
code-audit start
# 克隆仓库
git clone
cd code-audit-mcp
# 安装依赖
npm install
# 构建项目
npm run build
# 本地测试
npm run test-local
.vscode/extensions.json
安装扩展)# 克隆并进入目录
git clone https://github.com/warrengates/code-audit-mcp.git
cd code-audit-mcp
# 安装依赖(包括husky设置)
npm install
# 构建项目
npm run build
# 运行质量检查
npm run quality-check
# 测试设置
npm run test-local
本项目使用Husky和lint - staged进行自动代码质量检查:
预提交钩子会在git commit
时自动运行。若要手动运行质量检查:
# 运行所有质量检查
npm run quality-check
# 修复可自动修复的问题
npm run quality-fix
# 单独检查
npm run lint # ESLint检查
npm run format:check # Prettier检查
npm run type-check # TypeScript检查
设置脚本将执行以下操作:
若您倾向于手动安装:
# 安装依赖
npm install
# 安装必要的模型
ollama pull codellama:7b
ollama pull granite-code:8b
# 构建项目
npm run build
# 测试服务器
npm run dev
# 交互式设置向导
code-audit setup
# 启动MCP服务器(前台运行)
code-audit start
# 作为后台守护进程启动
code-audit start --daemon
# 停止正在运行的服务器
code-audit stop
# 检查系统健康状况
code-audit health
# 管理AI模型
code-audit models --list
code-audit models --pull codellama:7b
# 配置管理
code-audit config --show
code-audit config --set ollama.host=http://remote:11434
# MCP服务器管理
code-audit mcp status
code-audit mcp configure
code-audit mcp remove
# 检查更新
code-audit update
# 开启热重载的开发模式
npm run dev
# 构建TypeScript代码
npm run build
# 本地测试包
npm run test-local
设置向导现在会自动将code - audit配置为MCP服务器:
# 在设置期间配置
code-audit setup
# 或者在安装后配置
code-audit mcp configure
这将自动将code - audit添加到以下位置:
~/Library/Application Support/Claude/claude_desktop_config.json
~/.config/claude/mcp-settings.json
.claude/mcp-settings.json
若您倾向于手动配置,请将以下内容添加到MCP配置中:
{
"mcpServers": {
"code-audit": {
"command": "code-audit",
"args": ["start", "--stdio"],
"env": {}
}
}
}
更多详细信息,请参考:
audit_code
- 主要审计工具{
"name": "audit_code",
"arguments": {
"code": "function processPayment(amount) {\n const query = `SELECT * FROM users WHERE id = ${userId}`;\n // TODO: implement payment logic\n}",
"language": "javascript",
"auditType": "all",
"priority": "thorough",
"context": {
"framework": "express",
"environment": "production",
"performanceCritical": true,
"projectType": "api"
}
}
}
参数说明:
code
(必需):要审计的代码language
(必需):编程语言auditType
:可选值为security
、completeness
、performance
、quality
、architecture
、testing
、documentation
、all
priority
:可选值为fast
(仅安全性 + 完整性)、thorough
(所有审计类型)context
:用于特定框架分析的额外上下文maxIssues
:限制返回的问题数量(默认值:50)health_check
- 服务器健康状态检查{
"name": "health_check",
"arguments": {}
}
list_models
- 列出可用的AI模型{
"name": "list_models",
"arguments": {}
}
可创建配置文件或使用环境变量进行配置:
const config = {
name: 'code-audit-mcp',
version: '1.0.0',
ollama: {
host: 'http://localhost:11434',
timeout: 30000,
retryAttempts: 3,
retryDelay: 1000,
},
auditors: {
security: {
enabled: true,
severity: ['critical', 'high', 'medium'],
rules: {
sql_injection: true,
xss_vulnerability: true,
hardcoded_secret: true,
},
},
performance: {
enabled: true,
severity: ['high', 'medium', 'low'],
thresholds: {
cyclomaticComplexity: 10,
nestingDepth: 4,
},
},
},
logging: {
level: 'info',
enableMetrics: true,
enableTracing: false,
},
};
每个审计器都可以单独配置:
{
enabled: boolean; // 启用/禁用审计器
severity: Severity[]; // 包含的严重程度级别
rules: Record<string, boolean>; // 启用/禁用的特定规则
thresholds: Record<string, number>; // 数值阈值
}
可针对不同场景配置模型偏好:
// 对性能要求较高的代码
const performanceConfig = {
strategy: 'PerformanceModelSelectionStrategy', // 始终优先选择快速模型
fallbackModels: ['codellama:7b', 'granite-code:8b'],
};
// 注重质量的分析
const qualityConfig = {
strategy: 'QualityModelSelectionStrategy', // 始终优先选择准确的模型
fallbackModels: ['deepseek-coder:33b', 'codellama:13b'],
};
# 必备模型(约7GB)
ollama pull codellama:7b
ollama pull granite-code:8b
# 全面配置(约30GB)
ollama pull codellama:13b
ollama pull deepseek-coder:6.7b
ollama pull starcoder2:7b
ollama pull qwen2.5-coder:7b
# 完整配置(约80GB)
ollama pull deepseek-coder:33b
ollama pull starcoder2:15b
ollama pull llama3.1:8b
{
"requestId": "audit_12345",
"issues": [
{
"id": "sql_injection_2",
"location": { "line": 2, "column": 15 },
"severity": "critical",
"type": "sql_injection",
"category": "security",
"title": "SQL injection vulnerability in query construction",
"description": "Direct string interpolation in SQL query allows SQL injection attacks",
"suggestion": "Use parameterized queries or prepared statements",
"confidence": 0.95,
"fixable": true,
"ruleId": "SEC001",
"documentation": "OWASP Top 10: A03:2021 – Injection"
},
{
"id": "todo_3",
"location": { "line": 3 },
"severity": "medium",
"type": "todo_comment",
"category": "completeness",
"title": "TODO comment indicates incomplete implementation",
"description": "Found TODO comment: // TODO: implement payment logic",
"suggestion": "Implement the missing functionality or remove the TODO comment",
"confidence": 1.0,
"fixable": false,
"ruleId": "COMP001"
}
],
"summary": {
"total": 2,
"critical": 1,
"high": 0,
"medium": 1,
"low": 0,
"info": 0,
"byCategory": {
"security": 1,
"completeness": 1
}
},
"suggestions": {
"autoFixable": [
/* fixable issues */
],
"priorityFixes": [
/* critical/high severity */
],
"quickWins": [
/* low effort, high impact */
],
"technicalDebt": [
/* long-term improvements */
]
},
"metrics": {
"duration": 1250,
"modelResponseTime": 800,
"coverage": {
"linesAnalyzed": 15,
"functionsAnalyzed": 1,
"complexity": 3
}
}
}
{
"auditType": "all",
"priority": "fast" // 仅安全性 + 完整性
}
{
"context": {
"framework": "react",
"environment": "production",
"performanceCritical": true,
"projectType": "web"
}
}
{
performance: {
maxConcurrentAudits: 3,
cacheEnabled: true,
cacheTtl: 300 // 5分钟
}
}
本项目包含全面的VS Code配置,以提供最佳的开发体验:
安装推荐的扩展以获得最佳体验:
# 安装所有推荐的扩展
code --install-extension dbaeumer.vscode-eslint
code --install-extension esbenp.prettier-vscode
code --install-extension ms-vscode.vscode-typescript-next
code --install-extension usernamehw.errorlens
code --install-extension yoavbls.pretty-ts-errors
或者打开VS Code并接受工作区推荐弹出窗口。
.vscode/settings.json
包含以下设置:
使用包含的调试配置:
按F5
或使用调试面板开始调试。
code-audit-mcp/
├── src/
│ ├── server.ts # 主MCP服务器
│ ├── types.ts # TypeScript接口
│ ├── auditors/ # 审计实现
│ │ ├── base.ts # 基础审计器类
│ │ ├── security.ts # 安全审计器
│ │ ├── completeness.ts # 完整性审计器
│ │ ├── performance.ts # 性能审计器
│ │ └── ...
│ ├── ollama/ # Ollama集成
│ │ ├── client.ts # HTTP客户端包装器
│ │ ├── models.ts # 模型配置
│ │ └── prompts.ts # 审计提示
│ └── utils/ # 实用工具
│ ├── codeParser.ts # 代码解析
│ ├── complexity.ts # 复杂度分析
│ └── logger.ts # 日志记录工具
├── cli/
│ └── setup.ts # 设置脚本
├── .vscode/ # VS Code配置
│ ├── settings.json # 工作区设置
│ ├── extensions.json # 推荐扩展
│ └── launch.json # 调试配置
├── .husky/ # Git钩子
│ └── pre-commit # 预提交检查
└── tests/ # 测试套件
# 开发
npm run dev # 开启热重载启动
npm run build # 编译TypeScript代码
npm run lint # 运行ESLint检查
npm run format # 使用Prettier格式化代码
# 测试
npm test # 运行测试套件
npm run test:watch # 监听模式
npm run test:coverage # 生成覆盖率报告
# 生产
npm run start # 启动生产服务器
BaseAuditor
:import { BaseAuditor } from './base.js';
export class CustomAuditor extends BaseAuditor {
constructor(config, ollamaClient, modelManager) {
super('custom', config, ollamaClient, modelManager);
}
// 重写方法以实现自定义逻辑
protected async postProcessIssues(rawIssues, request, language) {
// 自定义后处理
return super.postProcessIssues(rawIssues, request, language);
}
}
auditors/index.ts
中注册:import { CustomAuditor } from './custom.js';
export const auditorClasses = {
// ... 现有审计器
custom: CustomAuditor,
};
const config = {
auditors: {
custom: {
enabled: true,
severity: ['high', 'medium'],
rules: {},
},
},
};
# 检查Ollama是否正在运行
ollama list
# 启动Ollama服务
ollama serve
# 检查端口可用性
curl http://localhost:11434/api/tags
# 列出已安装的模型
ollama list
# 安装缺失的模型
ollama pull codellama:7b
# 检查服务器中模型的可用性
curl -X POST http://localhost:11434/api/generate \
-H "Content-Type: application/json" \
-d '{"model": "codellama:7b", "prompt": "test"}'
# 清除构建缓存
rm -rf dist/
rm -rf node_modules/
npm install
# 检查TypeScript配置
npx tsc --noEmit
# 更新依赖
npm update
# 检查可用内存
free -h
# 使用较小的模型
ollama pull codellama:7b # 代替codellama:34b
# 减少并发审计
{
"performance": {
"maxConcurrentAudits": 1
}
}
// 对于CI/CD环境 - 优先考虑速度
const ciConfig = {
strategy: 'PerformanceModelSelectionStrategy',
priority: 'fast',
};
// 对于代码审查 - 优先考虑准确性
const reviewConfig = {
strategy: 'QualityModelSelectionStrategy',
priority: 'thorough',
};
{
ollama: {
timeout: 60000, // 对于大文件增加超时时间
retryAttempts: 5, // 增加重试次数以提高可靠性
healthCheckInterval: 30000 // 更频繁地进行健康检查
},
performance: {
maxConcurrentAudits: 2, // 对于有限的RAM减少并发审计数
cacheEnabled: true, // 对于重复分析启用缓存
cacheTtl: 600 // 10分钟的缓存时间
}
}
interface AuditRequest {
code: string; // 必需:要审计的代码
language: string; // 必需:编程语言
auditType: AuditType; // 可选:默认 'all'
file?: string; // 可选:用于上下文的文件路径
context?: AuditContext; // 可选:额外的上下文
priority?: 'fast' | 'thorough'; // 可选:默认 'thorough'
maxIssues?: number; // 可选:默认 50
includeFixSuggestions?: boolean; // 可选:默认 true
}
interface AuditResult {
requestId: string;
issues: AuditIssue[];
summary: AuditSummary;
coverage: AuditCoverage;
suggestions: AuditSuggestions;
metrics: AuditMetrics;
model: string;
timestamp: string;
version: string;
}
代码 | 描述 | 解决方案 |
---|---|---|
INVALID_REQUEST |
请求格式错误 | 检查必需参数 |
CODE_TOO_LARGE |
代码超过大小限制 | 拆分为较小的块 |
LANGUAGE_NOT_SUPPORTED |
不支持的语言 | 使用支持的语言 |
NO_AVAILABLE_MODEL |
未找到合适的模型 | 安装所需的模型 |
OLLAMA_UNAVAILABLE |
Ollama服务不可用 | 启动Ollama服务 |
MODEL_NOT_FOUND |
请求的模型缺失 | 使用ollama pull 拉取模型 |
GENERATION_FAILED |
AI生成失败 | 检查模型健康状况,重试 |
AUDIT_FAILED |
一般审计失败 | 检查日志,验证配置 |
我们欢迎贡献!请参考贡献指南获取详细信息。
# 分叉并克隆仓库
git clone https://github.com/your-username/code-audit-mcp.git
cd code-audit-mcp
# 安装依赖
npm install
# 以开发模式运行
npm run dev
# 运行测试
npm test
# 提交拉取请求
本项目采用MIT许可证,详情请参考LICENSE。
本项目由❤️ 打造,旨在通过AI分析提升代码质量