🚀 MCP Code Audit Server
This is a comprehensive TypeScript MCP server that leverages local AI models via Ollama to conduct intelligent code audits. It assesses code from multiple dimensions, including security, completeness, performance, quality, architecture, testing, and documentation.
🚀 Quick Start
The MCP Code Audit Server is a powerful tool for conducting in - depth code audits. To get started, follow the installation steps below and then explore the various features and usage scenarios.
✨ Features
Multi - Dimensional Code Analysis
- Security: Detects OWASP Top 10 vulnerabilities, authentication flaws, and injection attacks.
- Completeness: Identifies TODOs, empty functions, missing error handling, and unfinished implementations.
- Performance: Analyzes algorithmic complexity, memory leaks, and optimization opportunities.
- Quality: Checks for code smells, adherence to SOLID principles, and maintainability issues.
- Architecture: Evaluates design patterns, separation of concerns, and dependency management.
- Testing: Finds testability issues, missing coverage, and race conditions.
- Documentation: Verifies API docs, code comments, and compliance with standards.
Intelligent Model Selection
- Multi - model support: Supports CodeLlama, DeepSeek - Coder, StarCoder2, Granite - Code, Qwen2.5 - Coder.
- Specialization - based routing: Assigns different models for different audit types.
- Fallback strategies: Automatically switches to fallback models on failures.
- Performance optimization: Offers fast and thorough modes.
Advanced Features
- Context - aware analysis: Performs framework - specific checks for React, Express, Django, etc.
- Priority - based auditing: Fast mode (security + completeness) for rapid feedback.
- Language support: Supports 10+ programming languages with language - specific rules.
- Configurable severity: Allows customization of issue severity thresholds.
- Auto - fix suggestions: Provides confidence - scored fix recommendations.
- Complexity analysis: Calculates cyclomatic, cognitive, and maintainability metrics.
📦 Installation
Global Installation (Recommended)
npm install -g @moikas/code-audit-mcp
code-audit setup
code-audit setup --auto
code-audit start
Development Installation
git clone <repository-url>
cd code-audit-mcp
npm install
npm run build
npm run test-local
Development Setup
Prerequisites
- Node.js: 18.0.0 or higher
- npm: v8.0.0 or higher
- Git: For version control and pre - commit hooks
- VS Code: Recommended IDE (see
.vscode/extensions.json for extensions)
Initial Setup
git clone https://github.com/warrengates/code-audit-mcp.git
cd code-audit-mcp
npm install
npm run build
npm run quality-check
npm run test-local
Pre - commit Hooks
This project uses Husky and lint - staged for automatic code quality checks:
- ESLint: Checks code for errors and style issues.
- Prettier: Formats code consistently.
- TypeScript: Type checks all TypeScript files.
Pre - commit hooks run automatically on git commit. To manually run quality checks:
npm run quality-check
npm run quality-fix
npm run lint
npm run format:check
npm run type-check
The setup script will:
- ✅ Check prerequisites (Node.js, npm, tsx)
- 🩺 Verify Ollama installation and health
- 📦 Install recommended AI models
- 🧪 Test MCP server functionality
- 📝 Generate example configuration
Manual Setup
If you prefer manual installation:
npm install
ollama pull codellama:7b
ollama pull granite-code:8b
npm run build
npm run dev
💻 Usage Examples
CLI Commands
code-audit setup
code-audit start
code-audit start --daemon
code-audit stop
code-audit health
code-audit models --list
code-audit models --pull codellama:7b
code-audit config --show
code-audit config --set ollama.host=http://remote:11434
code-audit mcp status
code-audit mcp configure
code-audit mcp remove
code-audit update
Development Mode
npm run dev
npm run build
npm run test-local
MCP Integration
Automatic Configuration (Recommended)
The setup wizard now automatically configures code - audit as an MCP server:
code-audit setup
code-audit mcp configure
This will automatically add code - audit to:
- Claude Desktop:
~/Library/Application Support/Claude/claude_desktop_config.json
- Claude Code (Global):
~/.config/claude/mcp-settings.json
- Claude Code (Project):
.claude/mcp-settings.json
Manual Configuration
If you prefer manual configuration, add to your MCP configuration:
{
"mcpServers": {
"code-audit": {
"command": "code-audit",
"args": ["start", "--stdio"],
"env": {}
}
}
}
For more details, see:
- MCP Configuration Guide
- Claude Code Integration
Available Tools
audit_code - Main audit tool
{
"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"
}
}
}
Parameters:
code (required): Code to audit
language (required): Programming language
auditType: security | completeness | performance | quality | architecture | testing | documentation | all
priority: fast (security + completeness only) | thorough (all audit types)
context: Additional context for framework - specific analysis
maxIssues: Limit number of issues returned (default: 50)
health_check - Server health status
{
"name": "health_check",
"arguments": {}
}
list_models - Available AI models
{
"name": "list_models",
"arguments": {}
}
📚 Documentation
Server Configuration
Create a configuration file or use environment variables:
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,
},
};
Auditor Configuration
Each auditor can be individually configured:
{
enabled: boolean;
severity: Severity[];
rules: Record<string, boolean>;
thresholds: Record<string, number>;
}
Model Selection
Configure model preferences for different scenarios:
const performanceConfig = {
strategy: 'PerformanceModelSelectionStrategy',
fallbackModels: ['codellama:7b', 'granite-code:8b'],
};
const qualityConfig = {
strategy: 'QualityModelSelectionStrategy',
fallbackModels: ['deepseek-coder:33b', 'codellama:13b'],
};
🔧 Technical Details
Supported Models
Essential Models (Recommended)
- CodeLlama 7B: Fast, general - purpose code analysis
- Granite Code 8B: Excellent for security analysis
Comprehensive Setup
- CodeLlama 13B: Better accuracy for complex analysis
- DeepSeek - Coder 6.7B: Superior performance analysis
- StarCoder2 7B: Specialized for testing analysis
- Qwen2.5 - Coder 7B: Good for documentation analysis
Full Setup (Advanced)
- DeepSeek - Coder 33B: Highest accuracy (requires 16GB+ RAM)
- StarCoder2 15B: Advanced testing and architecture analysis
- Llama 3.1 8B: Excellent for documentation
Model Installation
ollama pull codellama:7b
ollama pull granite-code:8b
ollama pull codellama:13b
ollama pull deepseek-coder:6.7b
ollama pull starcoder2:7b
ollama pull qwen2.5-coder:7b
ollama pull deepseek-coder:33b
ollama pull starcoder2:15b
ollama pull llama3.1:8b
Language Support
Fully Supported
- JavaScript/TypeScript: React, Node.js, Express - specific checks
- Python: Django, Flask, FastAPI - specific analysis
- Java: Spring Boot, security - focused analysis
- Go: Goroutine safety, performance patterns
- Rust: Memory safety, performance optimization
Well Supported
- C#: .NET patterns, security analysis
- PHP: Laravel, WordPress security checks
- Ruby: Rails - specific patterns
- Swift: iOS - specific patterns
- Kotlin: Android - specific analysis
Basic Support
- C/C++: Memory safety, performance
- SQL: Injection detection, query optimization
- HTML/CSS: XSS prevention, performance
- Docker: Security configuration
- YAML/JSON: Configuration validation
Example Output
{
"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": [
],
"priorityFixes": [
],
"quickWins": [
],
"technicalDebt": [
]
},
"metrics": {
"duration": 1250,
"modelResponseTime": 800,
"coverage": {
"linesAnalyzed": 15,
"functionsAnalyzed": 1,
"complexity": 3
}
}
}
Performance Optimization
Fast Mode for Rapid Development
{
"auditType": "all",
"priority": "fast"
}
Context - Aware Analysis
{
"context": {
"framework": "react",
"environment": "production",
"performanceCritical": true,
"projectType": "web"
}
}
Caching Configuration
{
performance: {
maxConcurrentAudits: 3,
cacheEnabled: true,
cacheTtl: 300
}
}
Audit Types Deep Dive
Security Audit
- OWASP Top 10 Coverage: SQL injection, XSS, authentication flaws
- Language - specific: Prototype pollution (JS), pickle usage (Python)
- Framework - specific: CSRF protection (Express), SQL injection (Django)
Performance Audit
- Algorithmic Analysis: O(n²) detection, nested loop optimization
- Memory Management: Leak detection, object pooling opportunities
- Database Optimization: N+1 queries, missing indexes
- Async Patterns: Blocking operations, Promise handling
Quality Audit
- Code Smells: Long methods, large classes, duplicate code
- SOLID Principles: SRP, OCP, LSP, ISP, DIP violations
- Maintainability: Cyclomatic complexity, cognitive load
- Naming Conventions: Consistency, clarity, domain alignment
Development
VS Code Setup
This project includes comprehensive VS Code configuration for optimal development experience:
Recommended Extensions
Install recommended extensions for the best experience:
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
Or open VS Code and accept the workspace recommendations popup.
Workspace Settings
The .vscode/settings.json includes:
- Auto - formatting: Format on save with Prettier
- Linting: Real - time ESLint feedback
- TypeScript: Enhanced IntelliSense and error checking
- Import management: Auto - import and path intellisense
- Git integration: Pre - configured for the workflow
Debugging
Use the included debug configurations:
- Debug Server: Launch and debug the MCP server
- Debug CLI: Debug CLI commands
- Debug Tests: Step through test execution
Press F5 or use the Debug panel to start debugging.
Project Structure
code-audit-mcp/
├── src/
│ ├── server.ts # Main MCP server
│ ├── types.ts # TypeScript interfaces
│ ├── auditors/ # Audit implementations
│ │ ├── base.ts # Base auditor class
│ │ ├── security.ts # Security auditor
│ │ ├── completeness.ts # Completeness auditor
│ │ ├── performance.ts # Performance auditor
│ │ └── ...
│ ├── ollama/ # Ollama integration
│ │ ├── client.ts # HTTP client wrapper
│ │ ├── models.ts # Model configuration
│ │ └── prompts.ts # Audit prompts
│ └── utils/ # Utilities
│ ├── codeParser.ts # Code parsing
│ ├── complexity.ts # Complexity analysis
│ └── logger.ts # Logging utilities
├── cli/
│ └── setup.ts # Setup script
├── .vscode/ # VS Code configuration
│ ├── settings.json # Workspace settings
│ ├── extensions.json # Recommended extensions
│ └── launch.json # Debug configurations
├── .husky/ # Git hooks
│ └── pre-commit # Pre-commit checks
└── tests/ # Test suites
Building and Testing
npm run dev
npm run build
npm run lint
npm run format
npm test
npm run test:watch
npm run test:coverage
npm run start
Adding Custom Auditors
- Create a new auditor class extending
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);
}
}
- Register in
auditors/index.ts:
import { CustomAuditor } from './custom.js';
export const auditorClasses = {
custom: CustomAuditor,
};
- Add configuration:
const config = {
auditors: {
custom: {
enabled: true,
severity: ['high', 'medium'],
rules: {},
},
},
};
Troubleshooting
Common Issues
Ollama Connection Failed
ollama list
ollama serve
curl http://localhost:11434/api/tags
Model Not Found
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"}'
TypeScript Compilation Errors
rm -rf dist/
rm -rf node_modules/
npm install
npx tsc --noEmit
npm update
Memory Issues
free -h
ollama pull codellama:7b
{
"performance": {
"maxConcurrentAudits": 1
}
}
Performance Tuning
Model Selection Optimization
const ciConfig = {
strategy: 'PerformanceModelSelectionStrategy',
priority: 'fast',
};
const reviewConfig = {
strategy: 'QualityModelSelectionStrategy',
priority: 'thorough',
};
Resource Management
{
ollama: {
timeout: 60000,
retryAttempts: 5,
healthCheckInterval: 30000
},
performance: {
maxConcurrentAudits: 2,
cacheEnabled: true,
cacheTtl: 600
}
}
📄 API Reference
Tool Schemas
audit_code
interface AuditRequest {
code: string;
language: string;
auditType: AuditType;
file?: string;
context?: AuditContext;
priority?: 'fast' | 'thorough';
maxIssues?: number;
includeFixSuggestions?: boolean;
}
Response Format
interface AuditResult {
requestId: string;
issues: AuditIssue[];
summary: AuditSummary;
coverage: AuditCoverage;
suggestions: AuditSuggestions;
metrics: AuditMetrics;
model: string;
timestamp: string;
version: string;
}
Error Codes
| Code |
Description |
Resolution |
INVALID_REQUEST |
Malformed request |
Check required parameters |
CODE_TOO_LARGE |
Code exceeds size limit |
Split into smaller chunks |
LANGUAGE_NOT_SUPPORTED |
Unsupported language |
Use supported language |
NO_AVAILABLE_MODEL |
No suitable model found |
Install required models |
OLLAMA_UNAVAILABLE |
Ollama service down |
Start Ollama service |
MODEL_NOT_FOUND |
Requested model missing |
Pull model with ollama pull |
GENERATION_FAILED |
AI generation failed |
Check model health, retry |
AUDIT_FAILED |
General audit failure |
Check logs, verify configuration |
🤝 Contributing
We welcome contributions! Please see our Contributing Guidelines for details.
Development Setup
git clone https://github.com/your-username/code-audit-mcp.git
cd code-audit-mcp
npm install
npm run dev
npm test
Code Standards
- TypeScript: Strict mode enabled
- ESLint: Airbnb configuration
- Prettier: Automated formatting
- Testing: Jest with >80% coverage
- Documentation: JSDoc for all public APIs
Development Documentation
- Contributing Guidelines: How to contribute to the project
- VS Code Setup: Optimal IDE configuration
- Pre - commit Hooks: Automated quality checks
- Troubleshooting: Solutions to common issues
📄 License
MIT License - see LICENSE for details.
🙏 Acknowledgments
- Anthropic for the Model Context Protocol specification
- Ollama for local AI model serving
- Meta for CodeLlama models
- DeepSeek for specialized coding models
- BigCode for StarCoder models
📞 Support
Built with ❤️ for better code quality through AI - powered analysis