README.mdā¢12.9 kB
# CodeCompass MCP Documentation
## šÆ **Purpose & Value Proposition**
CodeCompass MCP is an **enterprise-grade Model Context Protocol (MCP) Server** that provides intelligent repository analysis, code understanding, and AI-powered development assistance. It bridges development tools with comprehensive GitHub repository analysis capabilities, offering 18 specialized tools for code exploration, documentation generation, and architectural insights.
## šļø **Architecture Overview**
### **Core Design Pattern: Service-Oriented Architecture**
```typescript
// High-level flow
MCP Client ā MCP Server ā Service Layer ā External APIs (GitHub, OpenRouter)
```
The system implements a **Service-Oriented Architecture** with clear separation of concerns, enhanced error handling, and production-ready monitoring.
### **Component Architecture**
#### 1. **MCP Server Layer** (`src/index.ts`)
```typescript
// JSON-RPC MCP Protocol Handler
server.setRequestHandler(CallToolRequestSchema, async (request) => {
const { name, arguments: args } = request.params;
const requestId = monitoring.generateRequestId();
// Routes to appropriate handlers with monitoring
return await handleTool(name, args, requestId);
});
```
**Key Responsibilities:**
- JSON-RPC protocol compliance
- Tool registration and routing (18 tools)
- Enhanced error handling with contextual messages
- Request monitoring and performance tracking
- Response size management with chunking
#### 2. **Service Layer** (`src/services/`)
```typescript
// GitHub API integration
class GitHubService {
async getRepositoryInfo(url: string): Promise<RepositoryInfo> {
// Smart rate limiting and caching
return await this.fetchWithRateLimit(url);
}
}
// OpenRouter integration
class OpenAIService {
async generateCodeReview(code: string, language: string): Promise<ReviewResult> {
// AI-powered analysis with configurable models
return await this.callOpenRouter(code, language);
}
}
```
**Design Features:**
- Rate limiting and API management
- Intelligent caching strategies
- Error recovery and retry logic
- Multi-provider AI integration
#### 3. **Configuration Management** (`src/utils/config.ts`)
```typescript
// Centralized configuration with validation
interface Config {
github: { token: string; apiUrl: string };
openrouter: { apiKey: string; defaultModel: string };
response: { maxTokens: number; chunkSizes: ChunkSizes };
logging: { level: string; enableTimestamps: boolean };
}
// Environment-based configuration
const config = ConfigSchema.parse(loadConfigFromEnv());
```
**Design Features:**
- Zod schema validation
- Environment variable mapping
- Smart defaults and warnings
- Type-safe configuration access
#### 4. **Monitoring & Observability** (`src/utils/monitoring.ts`)
```typescript
// Real-time performance monitoring
class MonitoringService {
startRequest(tool: string, requestId: string): void {
this.metrics.requestCount++;
this.trackPerformance(tool, requestId);
}
getHealthStatus(): HealthStatus {
return {
status: this.calculateOverallHealth(),
checks: this.runHealthChecks(),
insights: this.generateInsights()
};
}
}
```
**Key Features:**
- Request tracking with correlation IDs
- Performance metrics and insights
- Health monitoring with thresholds
- Real-time dashboard capabilities
## š§ **Key Design Patterns**
### **1. Strategy Pattern - Response Size Management**
```typescript
function formatToolResponse(
response: ToolResponse<T>,
chunkMode: boolean = false,
chunkSize: string = 'medium'
) {
if (chunkMode) {
return chunkResponse(response, chunkSize);
} else {
return truncateResponse(response, maxTokens);
}
}
```
### **2. Command Pattern - Tool Registration**
```typescript
const toolHandlers = {
'fetch_repository_data': handleFetchRepositoryData,
'search_repository': handleSearchRepository,
'ai_code_review': handleAICodeReview,
'health_check': handleHealthCheck
};
```
### **3. Factory Pattern - Error Response Creation**
```typescript
function createResponse<T>(data: T, error?: any, metadata?: any): ToolResponse<T> {
if (error) {
return {
success: false,
error: {
code: error.code || ErrorCodes.PROCESSING_ERROR,
message: error.message,
suggestion: generateSuggestion(error),
timestamp: new Date().toISOString(),
context: metadata
}
};
}
return { success: true, data, metadata };
}
```
### **4. Observer Pattern - Request Monitoring**
```typescript
// Automatic request tracking
const monitoredHandler = monitorTool('tool_name', async (args) => {
// Tool logic with automatic performance tracking
return await processRequest(args);
});
```
## š **Usage Examples**
### **Basic Repository Analysis**
```bash
# Analyze repository structure and dependencies
{
"name": "fetch_repository_data",
"arguments": {
"url": "https://github.com/owner/repo",
"options": {
"include_structure": true,
"include_dependencies": true,
"max_files": 50
}
}
}
```
### **AI-Powered Code Review**
```bash
# Get intelligent code insights
{
"name": "ai_code_review",
"arguments": {
"url": "https://github.com/owner/repo",
"file_paths": ["src/main.ts", "src/utils.ts"],
"review_focus": ["security", "performance", "maintainability"],
"options": {
"ai_model": "anthropic/claude-3.5-sonnet"
}
}
}
```
### **Batch File Processing**
```bash
# Process multiple files with security validation
{
"name": "get_file_content",
"arguments": {
"url": "https://github.com/owner/repo",
"file_paths": ["src/", "docs/", "tests/"],
"options": {
"max_concurrent": 10,
"include_metadata": true,
"continue_on_error": true
}
}
}
```
### **Health Monitoring**
```bash
# Comprehensive system health check
{
"name": "health_check",
"arguments": {
"checks": ["api-limits", "monitoring", "configuration"],
"options": {
"include_metrics": true,
"include_insights": true,
"include_logs": true
}
}
}
```
## š³ **Deployment Architecture**
### **Docker-First Design**
```dockerfile
# Production-ready container
FROM node:18-alpine AS runtime
RUN addgroup -g 1001 -S nodejs && \
adduser -S codecompass -u 1001
USER codecompass
WORKDIR /app
# Health check integration
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
CMD node -e "console.log('Health check passed')" || exit 1
```
**Key Features:**
- Non-root execution for security
- Multi-stage builds for optimization
- Health check integration
- Environment variable configuration
- Resource limits and monitoring
### **MCP Integration Commands**
```bash
# Docker deployment
./scripts/docker-build.sh
./scripts/docker-run.sh --env-file .env
# Local development
npm run dev
# Production monitoring
./scripts/monitor.js --watch
```
## š” **Integration Patterns**
### **For Your Projects**
#### **1. MCP Server Template**
```typescript
// Adaptable MCP server structure
class CustomMCPServer {
constructor() {
this.tools = this.registerTools();
this.monitoring = new MonitoringService();
this.config = getConfig();
}
registerTools() {
return {
'custom_tool': {
description: 'Your custom functionality',
inputSchema: {
type: 'object',
properties: { /* your schema */ }
}
}
};
}
}
```
#### **2. Service Integration Pattern**
```typescript
// Reusable pattern for external API integration
class ExternalAPIService {
constructor(private config: APIConfig) {
this.client = new APIClient(config);
}
async makeRequest<T>(endpoint: string, data: any): Promise<T> {
const timer = createPerformanceTimer(`${this.name}-${endpoint}`);
try {
const result = await this.client.request(endpoint, data);
timer.end({ success: true });
return result;
} catch (error) {
timer.end({ success: false, error: error.message });
throw error;
}
}
}
```
#### **3. Configuration Management**
```typescript
// Environment-based configuration pattern
import { z } from 'zod';
const ConfigSchema = z.object({
apiKey: z.string().min(1),
baseUrl: z.string().url(),
maxRetries: z.number().default(3)
});
export function createConfig(): Config {
const envConfig = {
apiKey: process.env.API_KEY,
baseUrl: process.env.BASE_URL,
maxRetries: parseInt(process.env.MAX_RETRIES || '3')
};
return ConfigSchema.parse(envConfig);
}
```
## š **Code Quality Insights**
### **Strengths**
- **Type Safety**: Full TypeScript implementation with strict types
- **Error Handling**: Comprehensive error recovery with contextual messages
- **Monitoring**: Real-time performance tracking and health checks
- **Security**: Input validation and path traversal prevention
- **Docker Integration**: Production-ready containerization
- **Documentation**: Comprehensive API documentation and examples
### **Advanced Features**
```typescript
// Enhanced error handling with suggestions
function createErrorResponse(error: Error, context?: ErrorContext): ErrorResponse {
const suggestions = generateContextualSuggestions(error, context);
return {
code: error.code,
message: error.message,
suggestion: suggestions.primary,
timestamp: new Date().toISOString(),
context: {
tool: context?.tool,
url: context?.url,
requestId: context?.requestId
}
};
}
// Intelligent response chunking
function chunkResponse<T>(response: T, chunkSize: ChunkSize): ChunkedResponse<T> {
const limits = getChunkLimits(chunkSize);
return {
data: truncateToLimits(response, limits),
metadata: {
chunkIndex: 0,
totalChunks: calculateTotalChunks(response, limits),
hasMore: hasMoreChunks(response, limits)
}
};
}
```
## šÆ **Adaptation Strategies**
### **For Different Use Cases**
1. **Extend the service layer** for new data sources
2. **Add custom tool implementations** following the established patterns
3. **Implement provider-specific configurations** for different APIs
### **For Different Environments**
1. **Kubernetes deployment** with provided Helm charts
2. **Serverless adaptation** with AWS Lambda or Vercel
3. **Local development** with hot-reload support
### **For Different Protocols**
1. **Abstract the protocol layer** (MCP ā GraphQL, REST, etc.)
2. **Maintain the service architecture** core
3. **Adapt the tool registration** system for different schemas
## šØ **Tool Categories**
### **Core Data Tools (6 tools)**
- `fetch_repository_data` - Comprehensive repository analysis
- `search_repository` - Advanced search with regex support
- `get_file_content` - Batch file processing with security
- `analyze_code_structure` - Code structure analysis
- `analyze_dependencies` - Dependency graph analysis
- `calculate_metrics` - Code quality metrics
### **Code Transformation Tools (4 tools)**
- `transform_code` - Code transformation and migration
- `extract_components` - Component extraction
- `adapt_code_structure` - Structure adaptation
- `generate_project_template` - Template generation
### **Analysis Tools (3 tools)**
- `analyze_architecture` - Architecture analysis
- `compare_implementations` - Implementation comparison
- `validate_code_quality` - Quality validation
### **Utility Tools (2 tools)**
- `batch_process` - Batch operation processing
- `health_check` - System health monitoring
### **AI-Enhanced Tools (3 tools)**
- `ai_code_review` - AI-powered code review
- `ai_explain_code` - AI code explanation
- `ai_refactor_suggestions` - AI refactoring suggestions
## š **Performance Characteristics**
### **Response Times**
- **Health Check**: <100ms
- **Repository Analysis**: 2-10s (depending on size)
- **AI Operations**: 5-30s (model dependent)
- **File Processing**: 1-5s (concurrent processing)
### **Resource Usage**
- **Memory**: 50-200MB (depending on repository size)
- **CPU**: Minimal (I/O bound operations)
- **Network**: Efficient with rate limiting and caching
### **Scalability**
- **Concurrent Requests**: Configurable limits
- **Response Size**: Intelligent chunking
- **Memory Management**: Efficient buffering
- **Docker Support**: Horizontal scaling ready
This repository demonstrates excellent **architectural patterns** for building **enterprise-grade MCP servers** with **production-ready deployment** capabilities, **comprehensive monitoring**, and **intelligent error handling**.
## š **Related Documentation**
- [Setup Guide](SETUP.md) - Installation and configuration
- [API Reference](API.md) - Complete tool documentation
- [Docker Guide](DOCKER.md) - Container deployment
- [Monitoring Guide](MONITORING.md) - Observability and metrics
- [Contributing Guide](../CONTRIBUTING.md) - Development guidelines