This is page 1 of 3. Use http://codebase.md/thealchemist6/codecompass-mcp?lines=true&page={x} to view the full context.
# Directory Structure
```
├── .dockerignore
├── .env.example
├── .gitignore
├── config
│ ├── .eslintrc.json
│ ├── .prettierignore
│ ├── .prettierrc
│ ├── README.md
│ └── tsconfig.dev.json
├── CONTRIBUTING.md
├── docker
│ ├── docker-compose.dev.yml
│ ├── docker-compose.yml
│ ├── Dockerfile.dev
│ └── README.md
├── Dockerfile
├── docs
│ ├── API.md
│ ├── DOCKER.md
│ ├── legacy-tools
│ │ ├── chat.ts
│ │ ├── extract.ts
│ │ ├── files.ts
│ │ ├── README.md
│ │ ├── refactor.ts
│ │ ├── repository.ts
│ │ ├── template.ts
│ │ └── transform.ts
│ ├── MONITORING.md
│ ├── README.md
│ └── SETUP.md
├── examples
│ ├── basic-usage.js
│ └── basic-usage.md
├── LICENSE
├── package-lock.json
├── package.json
├── README.md
├── scripts
│ ├── docker-build.sh
│ ├── docker-logs.sh
│ ├── docker-run.sh
│ ├── monitor.js
│ └── start-mcp.sh
├── src
│ ├── index.ts
│ ├── services
│ │ ├── github.ts
│ │ ├── openai.ts
│ │ └── refactor.ts
│ ├── tools
│ │ └── consolidated.ts
│ ├── types
│ │ ├── index.ts
│ │ └── responses.ts
│ └── utils
│ ├── config.ts
│ ├── file-processor.ts
│ ├── logger.ts
│ ├── monitoring.ts
│ ├── security.ts
│ └── validation.ts
├── tests
│ └── verify-installation.sh
└── tsconfig.json
```
# Files
--------------------------------------------------------------------------------
/config/.prettierrc:
--------------------------------------------------------------------------------
```
1 | {
2 | "semi": true,
3 | "singleQuote": true,
4 | "tabWidth": 2,
5 | "trailingComma": "es5",
6 | "printWidth": 100,
7 | "bracketSpacing": true,
8 | "arrowParens": "avoid",
9 | "endOfLine": "lf",
10 | "quoteProps": "as-needed",
11 | "bracketSameLine": false,
12 | "useTabs": false
13 | }
```
--------------------------------------------------------------------------------
/config/.prettierignore:
--------------------------------------------------------------------------------
```
1 | # Build outputs
2 | build/
3 | dist/
4 | *.tsbuildinfo
5 |
6 | # Dependencies
7 | node_modules/
8 |
9 | # Logs
10 | *.log
11 | logs/
12 |
13 | # Environment files
14 | .env*
15 |
16 | # Documentation
17 | docs/
18 | *.md
19 | !README.md
20 |
21 | # Test files
22 | tests/
23 | test-results/
24 | coverage/
25 |
26 | # Config files
27 | *.json
28 | *.yml
29 | *.yaml
30 |
31 | # Legacy files
32 | docs/legacy-tools/
```
--------------------------------------------------------------------------------
/config/.eslintrc.json:
--------------------------------------------------------------------------------
```json
1 | {
2 | "root": true,
3 | "parser": "@typescript-eslint/parser",
4 | "parserOptions": {
5 | "ecmaVersion": 2022,
6 | "sourceType": "module"
7 | },
8 | "plugins": ["@typescript-eslint"],
9 | "extends": [
10 | "eslint:recommended"
11 | ],
12 | "env": {
13 | "node": true,
14 | "es2022": true
15 | },
16 | "rules": {
17 | "no-unused-vars": "off",
18 | "@typescript-eslint/no-unused-vars": ["error", { "argsIgnorePattern": "^_" }],
19 | "no-console": "off",
20 | "prefer-const": "error",
21 | "no-var": "error"
22 | },
23 | "ignorePatterns": [
24 | "build/**",
25 | "dist/**",
26 | "node_modules/**",
27 | "*.js",
28 | "*.mjs",
29 | "tests/**",
30 | "docs/**"
31 | ]
32 | }
```
--------------------------------------------------------------------------------
/.dockerignore:
--------------------------------------------------------------------------------
```
1 | # Dependencies
2 | node_modules/
3 | npm-debug.log*
4 | yarn-debug.log*
5 | yarn-error.log*
6 |
7 | # Build outputs
8 | build/
9 | dist/
10 | *.tsbuildinfo
11 |
12 | # Environment variables
13 | .env
14 | .env.local
15 | .env.development.local
16 | .env.test.local
17 | .env.production.local
18 |
19 | # IDE and editor files
20 | .vscode/
21 | .idea/
22 | *.swp
23 | *.swo
24 | *~
25 |
26 | # OS generated files
27 | .DS_Store
28 | .DS_Store?
29 | ._*
30 | .Spotlight-V100
31 | .Trashes
32 | ehthumbs.db
33 | Thumbs.db
34 |
35 | # Logs
36 | logs/
37 | *.log
38 |
39 | # Runtime data
40 | pids/
41 | *.pid
42 | *.seed
43 | *.pid.lock
44 |
45 | # Coverage directory
46 | coverage/
47 | *.lcov
48 |
49 | # nyc test coverage
50 | .nyc_output
51 |
52 | # Git
53 | .git
54 | .gitignore
55 | .gitattributes
56 |
57 | # Documentation (exclude from production image)
58 | docs/
59 | examples/
60 | *.md
61 | !README.md
62 |
63 | # Test files
64 | tests/
65 | test/
66 | *.test.js
67 | *.test.ts
68 | *.spec.js
69 | *.spec.ts
70 |
71 | # Development files
72 | .prettierrc
73 | .eslintrc
74 | tsconfig.dev.json
75 |
76 | # Docker files
77 | Dockerfile
78 | docker-compose.yml
79 | .dockerignore
```
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
```
1 | # Dependencies
2 | node_modules/
3 | npm-debug.log*
4 | yarn-debug.log*
5 | yarn-error.log*
6 |
7 | # Build outputs
8 | build/
9 | dist/
10 | *.tsbuildinfo
11 |
12 | # Environment variables
13 | .env
14 | .env.local
15 | .env.development.local
16 | .env.test.local
17 | .env.production.local
18 |
19 | # IDE and editor files
20 | .vscode/
21 | .idea/
22 | *.swp
23 | *.swo
24 | *~
25 |
26 | # OS generated files
27 | .DS_Store
28 | .DS_Store?
29 | ._*
30 | .Spotlight-V100
31 | .Trashes
32 | ehthumbs.db
33 | Thumbs.db
34 |
35 | # Logs
36 | logs/
37 | *.log
38 | npm-debug.log*
39 | yarn-debug.log*
40 | yarn-error.log*
41 | lerna-debug.log*
42 |
43 | # Runtime data
44 | pids/
45 | *.pid
46 | *.seed
47 | *.pid.lock
48 |
49 | # Coverage directory used by tools like istanbul
50 | coverage/
51 | *.lcov
52 |
53 | # nyc test coverage
54 | .nyc_output
55 |
56 | # Dependency directories
57 | jspm_packages/
58 |
59 | # TypeScript cache
60 | *.tsbuildinfo
61 | .tsbuildinfo
62 |
63 | # Optional npm cache directory
64 | .npm
65 |
66 | # Optional eslint cache
67 | .eslintcache
68 |
69 | # Microbundle cache
70 | .rpt2_cache/
71 | .rts2_cache_cjs/
72 | .rts2_cache_es/
73 | .rts2_cache_umd/
74 |
75 | # Optional REPL history
76 | .node_repl_history
77 |
78 | # Output of 'npm pack'
79 | *.tgz
80 |
81 | # Yarn Integrity file
82 | .yarn-integrity
83 |
84 | # dotenv environment variables file
85 | .env
86 | .env.test
87 |
88 | # parcel-bundler cache (https://parceljs.org/)
89 | .cache
90 | .parcel-cache
91 |
92 | # Next.js build output
93 | .next
94 |
95 | # Nuxt.js build / generate output
96 | .nuxt
97 | dist
98 |
99 | # Gatsby files
100 | .cache/
101 | public
102 |
103 | # Storybook build outputs
104 | .out
105 | .storybook-out
106 |
107 | # Temporary folders
108 | tmp/
109 | temp/
110 |
111 | # API Keys and sensitive files
112 | *.key
113 | *.pem
114 | config/secrets.json
115 |
116 | # Test results
117 | test-results/
118 | coverage/
119 |
120 | # Test environment files
121 | **/test-env.js
122 | **/test-config.js
123 |
124 | # Local development
125 | .local/
126 | local/
```
--------------------------------------------------------------------------------
/.env.example:
--------------------------------------------------------------------------------
```
1 | # GitHub API Configuration
2 | # Required for repository analysis
3 | # Get your token from: https://github.com/settings/tokens
4 | GITHUB_TOKEN=your_github_token_here
5 |
6 | # Alternative GitHub API key (if different from token)
7 | GITHUB_API_KEY=your_github_api_key_here
8 |
9 | # OpenAI API Configuration (Optional)
10 | # Required for AI-powered features like chat, explanations, and suggestions
11 | # Get your key from: https://platform.openai.com/api-keys
12 | OPENAI_API_KEY=your_openai_api_key_here
13 |
14 | # OpenRouter API Configuration (Alternative to OpenAI)
15 | # Provides access to multiple AI models
16 | # Get your key from: https://openrouter.ai/keys
17 | OPENROUTER_API_KEY=your_openrouter_api_key_here
18 |
19 | # AI Model Configuration
20 | # Default model to use for AI features
21 | # Options: anthropic/claude-3.5-sonnet, openai/gpt-4o, etc.
22 | AI_MODEL=anthropic/claude-3.5-sonnet
23 |
24 | # Server Configuration
25 | # Port for the MCP server (if running in standalone mode)
26 | MCP_PORT=3001
27 |
28 | # Debug Configuration
29 | # Enable debug logging
30 | DEBUG=codecompass:*
31 |
32 | # Cache Configuration
33 | # Cache duration in milliseconds
34 | CACHE_DURATION=3600000
35 |
36 | # Rate Limiting
37 | # Maximum requests per minute
38 | RATE_LIMIT=100
39 |
40 | # Security Configuration
41 | # Maximum file size for analysis (in bytes)
42 | MAX_FILE_SIZE=10485760
43 |
44 | # Maximum total analysis size (in bytes)
45 | MAX_ANALYSIS_SIZE=524288000
46 |
47 | # Enable/disable security checks
48 | ENABLE_SECURITY_CHECKS=true
49 |
50 | # Performance Configuration
51 | # Maximum concurrent GitHub API requests
52 | MAX_CONCURRENT_REQUESTS=10
53 |
54 | # Request timeout in milliseconds
55 | REQUEST_TIMEOUT=30000
56 |
57 | # Memory limits
58 | # Maximum memory usage for analysis
59 | MAX_MEMORY_USAGE=2048
60 |
61 | # Logging Configuration
62 | # Log level: error, warn, info, debug, trace
63 | LOG_LEVEL=info
64 |
65 | # Log file path (optional)
66 | LOG_FILE=./logs/codecompass.log
67 |
68 | # Feature Flags
69 | # Enable/disable specific features
70 | ENABLE_AI_FEATURES=true
71 | ENABLE_REFACTORING=true
72 | ENABLE_TEMPLATE_GENERATION=true
73 | ENABLE_COMPONENT_EXTRACTION=true
74 |
75 | # Advanced Configuration
76 | # Custom user agent for GitHub API requests
77 | USER_AGENT=CodeCompass-MCP/1.0.0
78 |
79 | # Custom base URL for GitHub API (for GitHub Enterprise)
80 | GITHUB_API_BASE_URL=https://api.github.com
81 |
82 | # Webhook configuration (if using webhooks for updates)
83 | WEBHOOK_SECRET=your_webhook_secret_here
84 |
85 | # Analytics configuration (optional)
86 | ANALYTICS_ENABLED=false
87 | ANALYTICS_API_KEY=your_analytics_key_here
```
--------------------------------------------------------------------------------
/docker/README.md:
--------------------------------------------------------------------------------
```markdown
1 | # Docker Configuration
2 |
3 | This directory contains Docker-related files for the CodeCompass MCP project.
4 |
5 | ## Files
6 |
7 | - `Dockerfile.dev` - Development Docker configuration
8 | - `docker-compose.dev.yml` - Development Docker Compose setup
9 | - `docker-compose.yml` - Production Docker Compose setup
10 |
11 | ## Usage
12 |
13 | See the main [Docker documentation](../docs/DOCKER.md) for detailed usage instructions.
14 |
15 | ## Quick Start
16 |
17 | ```bash
18 | # Development
19 | docker-compose -f docker/docker-compose.dev.yml up
20 |
21 | # Production
22 | docker-compose -f docker/docker-compose.yml up
23 | ```
```
--------------------------------------------------------------------------------
/config/README.md:
--------------------------------------------------------------------------------
```markdown
1 | # Configuration Files
2 |
3 | This directory contains development configuration files for the CodeCompass MCP project.
4 |
5 | ## Files
6 |
7 | - `.eslintrc.json` - ESLint configuration for code linting
8 | - `.prettierrc` - Prettier configuration for code formatting
9 | - `.prettierignore` - Files to ignore during formatting
10 | - `tsconfig.dev.json` - TypeScript configuration for development
11 |
12 | ## Usage
13 |
14 | These configuration files are automatically used by the npm scripts:
15 |
16 | ```bash
17 | npm run lint # Uses .eslintrc.json
18 | npm run format # Uses .prettierrc
19 | npm run build:dev # Uses tsconfig.dev.json
20 | ```
21 |
22 | ## Main Configuration
23 |
24 | The main TypeScript configuration is in the root `tsconfig.json` file.
```
--------------------------------------------------------------------------------
/docs/legacy-tools/README.md:
--------------------------------------------------------------------------------
```markdown
1 | # Legacy Tool Definitions
2 |
3 | This directory contains the original individual tool definition files that were used before consolidation.
4 |
5 | ## Files
6 |
7 | - `chat.ts` - Chat and AI interaction tools
8 | - `extract.ts` - Component extraction tools
9 | - `files.ts` - File processing tools
10 | - `refactor.ts` - Code refactoring tools
11 | - `repository.ts` - Repository analysis tools
12 | - `template.ts` - Template generation tools
13 | - `transform.ts` - Code transformation tools
14 |
15 | ## Status
16 |
17 | These files are **no longer used** in the active codebase. All tool definitions have been consolidated into `src/tools/consolidated.ts` for better maintainability and performance.
18 |
19 | ## Purpose
20 |
21 | These files are preserved for:
22 | - Historical reference
23 | - Future modularization if needed
24 | - Tool definition examples
25 | - Documentation purposes
26 |
27 | ## Note
28 |
29 | Do not import these files in the active codebase. Use `src/tools/consolidated.ts` instead.
```
--------------------------------------------------------------------------------
/docs/README.md:
--------------------------------------------------------------------------------
```markdown
1 | # CodeCompass MCP Documentation
2 |
3 | ## 🎯 **Purpose & Value Proposition**
4 |
5 | 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.
6 |
7 | ## 🏗️ **Architecture Overview**
8 |
9 | ### **Core Design Pattern: Service-Oriented Architecture**
10 | ```typescript
11 | // High-level flow
12 | MCP Client → MCP Server → Service Layer → External APIs (GitHub, OpenRouter)
13 | ```
14 |
15 | The system implements a **Service-Oriented Architecture** with clear separation of concerns, enhanced error handling, and production-ready monitoring.
16 |
17 | ### **Component Architecture**
18 |
19 | #### 1. **MCP Server Layer** (`src/index.ts`)
20 | ```typescript
21 | // JSON-RPC MCP Protocol Handler
22 | server.setRequestHandler(CallToolRequestSchema, async (request) => {
23 | const { name, arguments: args } = request.params;
24 | const requestId = monitoring.generateRequestId();
25 |
26 | // Routes to appropriate handlers with monitoring
27 | return await handleTool(name, args, requestId);
28 | });
29 | ```
30 |
31 | **Key Responsibilities:**
32 | - JSON-RPC protocol compliance
33 | - Tool registration and routing (18 tools)
34 | - Enhanced error handling with contextual messages
35 | - Request monitoring and performance tracking
36 | - Response size management with chunking
37 |
38 | #### 2. **Service Layer** (`src/services/`)
39 | ```typescript
40 | // GitHub API integration
41 | class GitHubService {
42 | async getRepositoryInfo(url: string): Promise<RepositoryInfo> {
43 | // Smart rate limiting and caching
44 | return await this.fetchWithRateLimit(url);
45 | }
46 | }
47 |
48 | // OpenRouter integration
49 | class OpenAIService {
50 | async generateCodeReview(code: string, language: string): Promise<ReviewResult> {
51 | // AI-powered analysis with configurable models
52 | return await this.callOpenRouter(code, language);
53 | }
54 | }
55 | ```
56 |
57 | **Design Features:**
58 | - Rate limiting and API management
59 | - Intelligent caching strategies
60 | - Error recovery and retry logic
61 | - Multi-provider AI integration
62 |
63 | #### 3. **Configuration Management** (`src/utils/config.ts`)
64 | ```typescript
65 | // Centralized configuration with validation
66 | interface Config {
67 | github: { token: string; apiUrl: string };
68 | openrouter: { apiKey: string; defaultModel: string };
69 | response: { maxTokens: number; chunkSizes: ChunkSizes };
70 | logging: { level: string; enableTimestamps: boolean };
71 | }
72 |
73 | // Environment-based configuration
74 | const config = ConfigSchema.parse(loadConfigFromEnv());
75 | ```
76 |
77 | **Design Features:**
78 | - Zod schema validation
79 | - Environment variable mapping
80 | - Smart defaults and warnings
81 | - Type-safe configuration access
82 |
83 | #### 4. **Monitoring & Observability** (`src/utils/monitoring.ts`)
84 | ```typescript
85 | // Real-time performance monitoring
86 | class MonitoringService {
87 | startRequest(tool: string, requestId: string): void {
88 | this.metrics.requestCount++;
89 | this.trackPerformance(tool, requestId);
90 | }
91 |
92 | getHealthStatus(): HealthStatus {
93 | return {
94 | status: this.calculateOverallHealth(),
95 | checks: this.runHealthChecks(),
96 | insights: this.generateInsights()
97 | };
98 | }
99 | }
100 | ```
101 |
102 | **Key Features:**
103 | - Request tracking with correlation IDs
104 | - Performance metrics and insights
105 | - Health monitoring with thresholds
106 | - Real-time dashboard capabilities
107 |
108 | ## 🔧 **Key Design Patterns**
109 |
110 | ### **1. Strategy Pattern - Response Size Management**
111 | ```typescript
112 | function formatToolResponse(
113 | response: ToolResponse<T>,
114 | chunkMode: boolean = false,
115 | chunkSize: string = 'medium'
116 | ) {
117 | if (chunkMode) {
118 | return chunkResponse(response, chunkSize);
119 | } else {
120 | return truncateResponse(response, maxTokens);
121 | }
122 | }
123 | ```
124 |
125 | ### **2. Command Pattern - Tool Registration**
126 | ```typescript
127 | const toolHandlers = {
128 | 'fetch_repository_data': handleFetchRepositoryData,
129 | 'search_repository': handleSearchRepository,
130 | 'ai_code_review': handleAICodeReview,
131 | 'health_check': handleHealthCheck
132 | };
133 | ```
134 |
135 | ### **3. Factory Pattern - Error Response Creation**
136 | ```typescript
137 | function createResponse<T>(data: T, error?: any, metadata?: any): ToolResponse<T> {
138 | if (error) {
139 | return {
140 | success: false,
141 | error: {
142 | code: error.code || ErrorCodes.PROCESSING_ERROR,
143 | message: error.message,
144 | suggestion: generateSuggestion(error),
145 | timestamp: new Date().toISOString(),
146 | context: metadata
147 | }
148 | };
149 | }
150 | return { success: true, data, metadata };
151 | }
152 | ```
153 |
154 | ### **4. Observer Pattern - Request Monitoring**
155 | ```typescript
156 | // Automatic request tracking
157 | const monitoredHandler = monitorTool('tool_name', async (args) => {
158 | // Tool logic with automatic performance tracking
159 | return await processRequest(args);
160 | });
161 | ```
162 |
163 | ## 🚀 **Usage Examples**
164 |
165 | ### **Basic Repository Analysis**
166 | ```bash
167 | # Analyze repository structure and dependencies
168 | {
169 | "name": "fetch_repository_data",
170 | "arguments": {
171 | "url": "https://github.com/owner/repo",
172 | "options": {
173 | "include_structure": true,
174 | "include_dependencies": true,
175 | "max_files": 50
176 | }
177 | }
178 | }
179 | ```
180 |
181 | ### **AI-Powered Code Review**
182 | ```bash
183 | # Get intelligent code insights
184 | {
185 | "name": "ai_code_review",
186 | "arguments": {
187 | "url": "https://github.com/owner/repo",
188 | "file_paths": ["src/main.ts", "src/utils.ts"],
189 | "review_focus": ["security", "performance", "maintainability"],
190 | "options": {
191 | "ai_model": "anthropic/claude-3.5-sonnet"
192 | }
193 | }
194 | }
195 | ```
196 |
197 | ### **Batch File Processing**
198 | ```bash
199 | # Process multiple files with security validation
200 | {
201 | "name": "get_file_content",
202 | "arguments": {
203 | "url": "https://github.com/owner/repo",
204 | "file_paths": ["src/", "docs/", "tests/"],
205 | "options": {
206 | "max_concurrent": 10,
207 | "include_metadata": true,
208 | "continue_on_error": true
209 | }
210 | }
211 | }
212 | ```
213 |
214 | ### **Health Monitoring**
215 | ```bash
216 | # Comprehensive system health check
217 | {
218 | "name": "health_check",
219 | "arguments": {
220 | "checks": ["api-limits", "monitoring", "configuration"],
221 | "options": {
222 | "include_metrics": true,
223 | "include_insights": true,
224 | "include_logs": true
225 | }
226 | }
227 | }
228 | ```
229 |
230 | ## 🐳 **Deployment Architecture**
231 |
232 | ### **Docker-First Design**
233 | ```dockerfile
234 | # Production-ready container
235 | FROM node:18-alpine AS runtime
236 | RUN addgroup -g 1001 -S nodejs && \
237 | adduser -S codecompass -u 1001
238 | USER codecompass
239 | WORKDIR /app
240 |
241 | # Health check integration
242 | HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
243 | CMD node -e "console.log('Health check passed')" || exit 1
244 | ```
245 |
246 | **Key Features:**
247 | - Non-root execution for security
248 | - Multi-stage builds for optimization
249 | - Health check integration
250 | - Environment variable configuration
251 | - Resource limits and monitoring
252 |
253 | ### **MCP Integration Commands**
254 | ```bash
255 | # Docker deployment
256 | ./scripts/docker-build.sh
257 | ./scripts/docker-run.sh --env-file .env
258 |
259 | # Local development
260 | npm run dev
261 |
262 | # Production monitoring
263 | ./scripts/monitor.js --watch
264 | ```
265 |
266 | ## 💡 **Integration Patterns**
267 |
268 | ### **For Your Projects**
269 |
270 | #### **1. MCP Server Template**
271 | ```typescript
272 | // Adaptable MCP server structure
273 | class CustomMCPServer {
274 | constructor() {
275 | this.tools = this.registerTools();
276 | this.monitoring = new MonitoringService();
277 | this.config = getConfig();
278 | }
279 |
280 | registerTools() {
281 | return {
282 | 'custom_tool': {
283 | description: 'Your custom functionality',
284 | inputSchema: {
285 | type: 'object',
286 | properties: { /* your schema */ }
287 | }
288 | }
289 | };
290 | }
291 | }
292 | ```
293 |
294 | #### **2. Service Integration Pattern**
295 | ```typescript
296 | // Reusable pattern for external API integration
297 | class ExternalAPIService {
298 | constructor(private config: APIConfig) {
299 | this.client = new APIClient(config);
300 | }
301 |
302 | async makeRequest<T>(endpoint: string, data: any): Promise<T> {
303 | const timer = createPerformanceTimer(`${this.name}-${endpoint}`);
304 | try {
305 | const result = await this.client.request(endpoint, data);
306 | timer.end({ success: true });
307 | return result;
308 | } catch (error) {
309 | timer.end({ success: false, error: error.message });
310 | throw error;
311 | }
312 | }
313 | }
314 | ```
315 |
316 | #### **3. Configuration Management**
317 | ```typescript
318 | // Environment-based configuration pattern
319 | import { z } from 'zod';
320 |
321 | const ConfigSchema = z.object({
322 | apiKey: z.string().min(1),
323 | baseUrl: z.string().url(),
324 | maxRetries: z.number().default(3)
325 | });
326 |
327 | export function createConfig(): Config {
328 | const envConfig = {
329 | apiKey: process.env.API_KEY,
330 | baseUrl: process.env.BASE_URL,
331 | maxRetries: parseInt(process.env.MAX_RETRIES || '3')
332 | };
333 |
334 | return ConfigSchema.parse(envConfig);
335 | }
336 | ```
337 |
338 | ## 🔍 **Code Quality Insights**
339 |
340 | ### **Strengths**
341 | - **Type Safety**: Full TypeScript implementation with strict types
342 | - **Error Handling**: Comprehensive error recovery with contextual messages
343 | - **Monitoring**: Real-time performance tracking and health checks
344 | - **Security**: Input validation and path traversal prevention
345 | - **Docker Integration**: Production-ready containerization
346 | - **Documentation**: Comprehensive API documentation and examples
347 |
348 | ### **Advanced Features**
349 | ```typescript
350 | // Enhanced error handling with suggestions
351 | function createErrorResponse(error: Error, context?: ErrorContext): ErrorResponse {
352 | const suggestions = generateContextualSuggestions(error, context);
353 | return {
354 | code: error.code,
355 | message: error.message,
356 | suggestion: suggestions.primary,
357 | timestamp: new Date().toISOString(),
358 | context: {
359 | tool: context?.tool,
360 | url: context?.url,
361 | requestId: context?.requestId
362 | }
363 | };
364 | }
365 |
366 | // Intelligent response chunking
367 | function chunkResponse<T>(response: T, chunkSize: ChunkSize): ChunkedResponse<T> {
368 | const limits = getChunkLimits(chunkSize);
369 | return {
370 | data: truncateToLimits(response, limits),
371 | metadata: {
372 | chunkIndex: 0,
373 | totalChunks: calculateTotalChunks(response, limits),
374 | hasMore: hasMoreChunks(response, limits)
375 | }
376 | };
377 | }
378 | ```
379 |
380 | ## 🎯 **Adaptation Strategies**
381 |
382 | ### **For Different Use Cases**
383 | 1. **Extend the service layer** for new data sources
384 | 2. **Add custom tool implementations** following the established patterns
385 | 3. **Implement provider-specific configurations** for different APIs
386 |
387 | ### **For Different Environments**
388 | 1. **Kubernetes deployment** with provided Helm charts
389 | 2. **Serverless adaptation** with AWS Lambda or Vercel
390 | 3. **Local development** with hot-reload support
391 |
392 | ### **For Different Protocols**
393 | 1. **Abstract the protocol layer** (MCP → GraphQL, REST, etc.)
394 | 2. **Maintain the service architecture** core
395 | 3. **Adapt the tool registration** system for different schemas
396 |
397 | ## 🎨 **Tool Categories**
398 |
399 | ### **Core Data Tools (6 tools)**
400 | - `fetch_repository_data` - Comprehensive repository analysis
401 | - `search_repository` - Advanced search with regex support
402 | - `get_file_content` - Batch file processing with security
403 | - `analyze_code_structure` - Code structure analysis
404 | - `analyze_dependencies` - Dependency graph analysis
405 | - `calculate_metrics` - Code quality metrics
406 |
407 | ### **Code Transformation Tools (4 tools)**
408 | - `transform_code` - Code transformation and migration
409 | - `extract_components` - Component extraction
410 | - `adapt_code_structure` - Structure adaptation
411 | - `generate_project_template` - Template generation
412 |
413 | ### **Analysis Tools (3 tools)**
414 | - `analyze_architecture` - Architecture analysis
415 | - `compare_implementations` - Implementation comparison
416 | - `validate_code_quality` - Quality validation
417 |
418 | ### **Utility Tools (2 tools)**
419 | - `batch_process` - Batch operation processing
420 | - `health_check` - System health monitoring
421 |
422 | ### **AI-Enhanced Tools (3 tools)**
423 | - `ai_code_review` - AI-powered code review
424 | - `ai_explain_code` - AI code explanation
425 | - `ai_refactor_suggestions` - AI refactoring suggestions
426 |
427 | ## 📊 **Performance Characteristics**
428 |
429 | ### **Response Times**
430 | - **Health Check**: <100ms
431 | - **Repository Analysis**: 2-10s (depending on size)
432 | - **AI Operations**: 5-30s (model dependent)
433 | - **File Processing**: 1-5s (concurrent processing)
434 |
435 | ### **Resource Usage**
436 | - **Memory**: 50-200MB (depending on repository size)
437 | - **CPU**: Minimal (I/O bound operations)
438 | - **Network**: Efficient with rate limiting and caching
439 |
440 | ### **Scalability**
441 | - **Concurrent Requests**: Configurable limits
442 | - **Response Size**: Intelligent chunking
443 | - **Memory Management**: Efficient buffering
444 | - **Docker Support**: Horizontal scaling ready
445 |
446 | This repository demonstrates excellent **architectural patterns** for building **enterprise-grade MCP servers** with **production-ready deployment** capabilities, **comprehensive monitoring**, and **intelligent error handling**.
447 |
448 | ## 🔗 **Related Documentation**
449 |
450 | - [Setup Guide](SETUP.md) - Installation and configuration
451 | - [API Reference](API.md) - Complete tool documentation
452 | - [Docker Guide](DOCKER.md) - Container deployment
453 | - [Monitoring Guide](MONITORING.md) - Observability and metrics
454 | - [Contributing Guide](../CONTRIBUTING.md) - Development guidelines
```
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
```markdown
1 | # CodeCompass MCP
2 |
3 | [](https://opensource.org/licenses/MIT)
4 | [](https://nodejs.org/)
5 | [](https://www.docker.com/)
6 | [](https://www.typescriptlang.org/)
7 |
8 | **Enterprise-grade Model Context Protocol (MCP) Server for intelligent repository analysis and AI-powered development assistance.**
9 |
10 | Connect your development tools to comprehensive GitHub repository analysis with 11 streamlined tools, enhanced error handling, real-time monitoring, and production-ready deployment.
11 |
12 | ## ✨ **Features**
13 |
14 | - 🔍 **Comprehensive Repository Analysis** - Deep insights into code structure, dependencies, and architecture
15 | - 🤖 **AI-Powered Code Review** - Intelligent code analysis with OpenRouter integration (400+ models)
16 | - 🚀 **Production-Ready Deployment** - Docker containers with security best practices
17 | - 📊 **Real-time Monitoring** - Performance metrics, health checks, and observability
18 | - 🛡️ **Enterprise Security** - Input validation, path traversal prevention, and secure processing
19 | - ⚡ **High Performance** - Intelligent chunking, concurrent processing, and response optimization
20 | - 🔧 **Developer Experience** - Comprehensive documentation, examples, and debugging tools
21 |
22 | ## 🚀 **Quick Start**
23 |
24 | ### **Step-by-Step Docker Setup (Recommended)**
25 |
26 | #### 1. **Clone and Navigate**
27 | ```bash
28 | git clone https://github.com/TheAlchemist6/codecompass-mcp.git
29 | cd codecompass-mcp
30 | ```
31 | **Expected output:**
32 | ```
33 | Cloning into 'codecompass-mcp'...
34 | remote: Enumerating objects: 53, done.
35 | remote: Total 53 (delta 0), reused 0 (delta 0), pack-reused 53
36 | Receiving objects: 100% (53/53), 259.84 KiB | 1.85 MiB/s, done.
37 | ```
38 |
39 | #### 2. **Configure Environment**
40 | ```bash
41 | cp .env.example .env
42 | # Edit .env with your real API keys
43 | nano .env # or use your preferred editor
44 | ```
45 |
46 | **Required in `.env` file:**
47 | ```bash
48 | GITHUB_TOKEN=ghp_your_actual_github_token_here
49 | OPENROUTER_API_KEY=sk-or-v1-your_actual_openrouter_key_here
50 | ```
51 |
52 | **🔑 Where to get API keys:**
53 | - **GitHub Token**: [github.com/settings/tokens](https://github.com/settings/tokens) → Generate new token (classic) → Select `repo` scope
54 | - **OpenRouter Key**: [openrouter.ai/keys](https://openrouter.ai/keys) → Create new API key
55 |
56 | #### 3. **Build and Run**
57 | ```bash
58 | ./scripts/docker-build.sh
59 | ./scripts/docker-run.sh --env-file .env
60 | ```
61 | **Expected output:**
62 | ```
63 | ✅ Build successful
64 | Image information:
65 | REPOSITORY TAG IMAGE ID CREATED SIZE
66 | codecompass-mcp latest a1b2c3d4e5f6 2 seconds ago 278MB
67 |
68 | 🚀 Starting CodeCompass MCP server...
69 | ✅ Server started successfully
70 | Health check: healthy
71 | API limits: 5000/hour remaining
72 | ```
73 |
74 | #### 4. **Test Installation**
75 | ```bash
76 | # Test with health check
77 | echo '{"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "health_check"}}' | docker exec -i codecompass-mcp node build/index.js
78 | ```
79 |
80 | ### **Platform Support**
81 | - ✅ **Linux** (Ubuntu 18.04+, CentOS 7+)
82 | - ✅ **macOS** (10.14+, Intel & Apple Silicon)
83 | - ✅ **Windows** (10/11 with Docker Desktop)
84 |
85 | ### **Alternative Installation Methods**
86 |
87 | #### **Local Development**
88 | ```bash
89 | # Install dependencies
90 | npm install
91 |
92 | # Set environment variables
93 | export GITHUB_TOKEN=your_github_token
94 | export OPENROUTER_API_KEY=your_openrouter_key
95 |
96 | # Build and run
97 | npm run build && npm run dev
98 | ```
99 |
100 | #### **Global Installation**
101 | ```bash
102 | npm install -g codecompass-mcp
103 | codecompass-mcp --help
104 | ```
105 |
106 | ## 🔧 **Configuration**
107 |
108 | ### **Required Environment Variables**
109 | ```bash
110 | GITHUB_TOKEN=ghp_your_github_token_here # GitHub API access
111 | OPENROUTER_API_KEY=sk-or-v1-your_key_here # OpenRouter API access
112 | ```
113 |
114 | ### **Optional Configuration**
115 | ```bash
116 | AI_MODEL=anthropic/claude-3.5-sonnet # Default AI model
117 | MAX_RESPONSE_TOKENS=25000 # Response size limit
118 | LOG_LEVEL=info # Logging level
119 | NODE_ENV=production # Environment mode
120 | ```
121 |
122 | ## 🛠️ **Available Tools**
123 |
124 | ### **Core Data Tools (6 tools)**
125 | - **`get_repository_info`** - Repository metadata, statistics, and key information
126 | - **`get_file_tree`** - Complete directory structure and file listing with filtering
127 | - **`search_repository`** - Advanced search with regex patterns and filtering
128 | - **`get_file_content`** - Batch file processing with security validation and metadata
129 | - **`analyze_dependencies`** - Dependency graph analysis and vulnerability detection
130 | - **`analyze_codebase`** - Comprehensive structure, architecture, and metrics analysis
131 |
132 | ### **AI-Enhanced Tools (3 tools)**
133 | - **`review_code`** - AI-powered code review with security, performance, and maintainability insights
134 | - **`explain_code`** - Natural language code explanations and documentation generation
135 | - **`suggest_improvements`** - Intelligent refactoring recommendations and modernization strategies
136 |
137 | ### **Transformation Tools (1 tool)**
138 | - **`transform_code`** - Code transformation, modernization, and migration assistance
139 |
140 | ### **Utility Tools (1 tool)**
141 | - **`health_check`** - System health monitoring and performance metrics
142 |
143 | ## 🐳 **Docker Integration**
144 |
145 | ### **Production Deployment**
146 | ```bash
147 | # Build production image
148 | ./scripts/docker-build.sh
149 |
150 | # Run with environment file
151 | ./scripts/docker-run.sh --env-file .env
152 |
153 | # View logs
154 | ./scripts/docker-logs.sh -f --timestamps
155 | ```
156 |
157 | ### **Docker Compose**
158 | ```yaml
159 | version: '3.8'
160 | services:
161 | codecompass-mcp:
162 | build: .
163 | container_name: codecompass-mcp
164 | restart: unless-stopped
165 | environment:
166 | - GITHUB_TOKEN=${GITHUB_TOKEN}
167 | - OPENROUTER_API_KEY=${OPENROUTER_API_KEY}
168 | - NODE_ENV=production
169 | healthcheck:
170 | test: ["CMD", "node", "-e", "console.log('Health check')"]
171 | interval: 30s
172 | timeout: 10s
173 | retries: 3
174 | ```
175 |
176 | ### **MCP Client Integration**
177 |
178 | #### **Claude Desktop Configuration**
179 | Add to your Claude Desktop configuration file:
180 |
181 | **macOS**: `~/Library/Application Support/Claude/claude_desktop_config.json`
182 | **Windows**: `%APPDATA%\Claude\claude_desktop_config.json`
183 |
184 | ```json
185 | {
186 | "mcpServers": {
187 | "codecompass": {
188 | "command": "docker",
189 | "args": [
190 | "exec", "-i", "codecompass-mcp",
191 | "node", "build/index.js"
192 | ],
193 | "env": {
194 | "GITHUB_TOKEN": "your_github_token_here",
195 | "OPENROUTER_API_KEY": "your_openrouter_key_here"
196 | }
197 | }
198 | }
199 | }
200 | ```
201 |
202 | **Then restart Claude Desktop** and you'll see CodeCompass tools available in the UI.
203 |
204 | #### **Claude Code CLI Integration**
205 | ```bash
206 | # Add MCP server to Claude Code
207 | claude mcp add codecompass-docker -s user -- \
208 | docker exec -i codecompass-mcp node build/index.js
209 | ```
210 |
211 | #### **Other MCP Clients**
212 | - **Cline** (VS Code): Add to MCP configuration
213 | - **Continue** (VS Code/JetBrains): Configure as MCP provider
214 | - **Custom clients**: Use `stdio` transport with `node build/index.js`
215 |
216 | #### **Testing Integration**
217 | ```bash
218 | # Test the connection
219 | echo '{"jsonrpc": "2.0", "id": 1, "method": "tools/list"}' | docker exec -i codecompass-mcp node build/index.js
220 |
221 | # Should return list of 11 tools
222 | ```
223 |
224 | ## 📊 **Monitoring & Observability**
225 |
226 | ### **Real-time Dashboard**
227 | ```bash
228 | # Interactive monitoring dashboard
229 | ./scripts/monitor.js --watch
230 |
231 | # Export metrics
232 | ./scripts/monitor.js --export > metrics.json
233 |
234 | # Health check
235 | curl -X POST http://localhost:3000/health
236 | ```
237 |
238 | ### **Performance Metrics**
239 | - **Response Times**: <100ms for health checks, 2-10s for repository analysis
240 | - **Memory Usage**: 50-200MB depending on repository size
241 | - **Concurrent Processing**: Configurable limits with automatic scaling
242 | - **Error Tracking**: Comprehensive error monitoring with contextual suggestions
243 |
244 | ### **Health Monitoring**
245 | ```json
246 | {
247 | "name": "health_check",
248 | "arguments": {
249 | "checks": ["api-limits", "monitoring", "configuration"],
250 | "options": {
251 | "include_metrics": true,
252 | "include_insights": true
253 | }
254 | }
255 | }
256 | ```
257 |
258 | ## 🔍 **Usage Examples**
259 |
260 | ### **Repository Analysis**
261 | ```json
262 | {
263 | "name": "fetch_repository_data",
264 | "arguments": {
265 | "url": "https://github.com/microsoft/typescript",
266 | "options": {
267 | "include_structure": true,
268 | "include_dependencies": true,
269 | "max_files": 100,
270 | "chunk_mode": true
271 | }
272 | }
273 | }
274 | ```
275 |
276 | ### **AI Code Review**
277 | ```json
278 | {
279 | "name": "ai_code_review",
280 | "arguments": {
281 | "url": "https://github.com/your-org/your-repo",
282 | "file_paths": ["src/main.ts", "src/utils/"],
283 | "review_focus": ["security", "performance", "maintainability"],
284 | "options": {
285 | "ai_model": "anthropic/claude-3.5-sonnet",
286 | "severity_threshold": "medium"
287 | }
288 | }
289 | }
290 | ```
291 |
292 | ### **Batch File Processing**
293 | ```json
294 | {
295 | "name": "get_file_content",
296 | "arguments": {
297 | "url": "https://github.com/your-org/your-repo",
298 | "file_paths": ["src/", "docs/", "tests/"],
299 | "options": {
300 | "max_concurrent": 10,
301 | "include_metadata": true,
302 | "continue_on_error": true
303 | }
304 | }
305 | }
306 | ```
307 |
308 | ## 🏗️ **Architecture**
309 |
310 | ### **Service-Oriented Design**
311 | ```
312 | MCP Client → MCP Server → Service Layer → External APIs
313 | ↓
314 | Monitoring & Logging
315 | ```
316 |
317 | ### **Key Components**
318 | - **MCP Server**: JSON-RPC protocol handling with 11 streamlined tools
319 | - **Service Layer**: GitHub API, OpenRouter integration, and business logic
320 | - **Configuration**: Centralized, type-safe configuration with Zod validation
321 | - **Monitoring**: Real-time performance tracking and health monitoring
322 | - **Security**: Input validation, path traversal prevention, and secure processing
323 |
324 | ## 🔒 **Security Features**
325 |
326 | ### **Input Validation**
327 | - **Zod Schema Validation**: Type-safe input validation for all tools
328 | - **Path Traversal Prevention**: Comprehensive file path security checks
329 | - **Rate Limiting**: Configurable request rate limiting and throttling
330 | - **API Key Management**: Secure environment variable handling
331 |
332 | ### **Container Security**
333 | - **Non-root Execution**: All containers run as unprivileged users
334 | - **Read-only Filesystems**: Security-focused container configuration
335 | - **Resource Limits**: Memory and CPU constraints for stability
336 | - **Health Checks**: Automated health monitoring and recovery
337 |
338 | ## 🎯 **Performance Optimization**
339 |
340 | ### **Intelligent Response Management**
341 | - **Chunking**: Large responses split into manageable chunks
342 | - **Truncation**: Smart truncation preserving data structure
343 | - **Concurrent Processing**: Parallel file processing with configurable limits
344 | - **Caching**: Intelligent caching strategies for frequently accessed data
345 |
346 | ### **Resource Management**
347 | - **Memory Efficiency**: Optimized memory usage with automatic cleanup
348 | - **Request Tracking**: Correlation IDs for distributed tracing
349 | - **Performance Insights**: Automated performance analysis and recommendations
350 | - **Scalability**: Horizontal scaling ready with Docker containers
351 |
352 | ## 📚 **Documentation**
353 |
354 | ### **Complete Documentation Suite**
355 | - **[Setup Guide](docs/SETUP.md)** - Installation and configuration instructions
356 | - **[API Reference](docs/API.md)** - Complete tool documentation with examples
357 | - **[Docker Guide](docs/DOCKER.md)** - Container deployment and management
358 | - **[Monitoring Guide](docs/MONITORING.md)** - Observability and performance monitoring
359 | - **[Architecture Guide](docs/README.md)** - Technical architecture and patterns
360 |
361 | ### **Examples and Templates**
362 | - **[Usage Examples](examples/)** - Real-world usage patterns and templates
363 | - **[Integration Examples](examples/integrations/)** - MCP client integration examples
364 | - **[Configuration Templates](examples/configs/)** - Production-ready configuration examples
365 |
366 | ## 🤝 **Contributing**
367 |
368 | We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details on:
369 | - Development setup and workflow
370 | - Code style and testing requirements
371 | - Pull request process and guidelines
372 | - Bug reporting and feature requests
373 |
374 | ### **Development Setup**
375 | ```bash
376 | # Clone and setup
377 | git clone https://github.com/your-org/codecompass-mcp.git
378 | cd codecompass-mcp
379 |
380 | # Install dependencies
381 | npm install
382 |
383 | # Run tests
384 | npm test
385 |
386 | # Start development server
387 | npm run dev:watch
388 | ```
389 |
390 | ## 🔄 **Roadmap**
391 |
392 | ### **Current Version (1.0.0)**
393 | - ✅ 11 streamlined, atomic tools with clear responsibilities
394 | - ✅ Production-ready Docker deployment
395 | - ✅ Real-time monitoring and observability
396 | - ✅ Enterprise security features
397 | - ✅ Complete documentation suite
398 |
399 | ### **Future Enhancements**
400 | - 🔮 **Conversational Context Management** - Session state and conversation history
401 | - 🔮 **Advanced Caching** - Redis-based caching with intelligent invalidation
402 | - 🔮 **Plugin System** - Extensible architecture for custom tools
403 | - 🔮 **Multi-language Support** - Expanded language support beyond TypeScript/JavaScript
404 | - 🔮 **Kubernetes Integration** - Native Kubernetes deployment with Helm charts
405 |
406 | ## 📄 **License**
407 |
408 | This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
409 |
410 | ## 🙏 **Acknowledgments**
411 |
412 | - **OpenRouter MCP** - Architecture patterns and best practices inspiration
413 | - **MCP Protocol** - Foundation for tool integration and communication
414 | - **Anthropic** - Claude AI integration and development support
415 | - **GitHub** - Repository analysis and API integration
416 | - **Docker** - Containerization and deployment infrastructure
417 |
418 | ## 🆘 **Support**
419 |
420 | ### **Getting Help**
421 | - **Documentation**: Check our comprehensive documentation in the `docs/` directory
422 | - **Issues**: Report bugs and request features on [GitHub Issues](https://github.com/your-org/codecompass-mcp/issues)
423 | - **Discussions**: Join community discussions on [GitHub Discussions](https://github.com/your-org/codecompass-mcp/discussions)
424 |
425 | ### **Common Issues**
426 | - **API Key Setup**: See [Setup Guide](docs/SETUP.md#api-key-setup)
427 | - **Docker Issues**: Check [Docker Guide](docs/DOCKER.md#troubleshooting)
428 | - **Performance**: Review [Monitoring Guide](docs/MONITORING.md#performance-optimization)
429 |
430 | ## 🚀 **Built With**
431 |
432 | - **[TypeScript](https://www.typescriptlang.org/)** - Type-safe JavaScript development
433 | - **[Node.js](https://nodejs.org/)** - JavaScript runtime environment
434 | - **[Docker](https://www.docker.com/)** - Containerization platform
435 | - **[Zod](https://zod.dev/)** - TypeScript-first schema validation
436 | - **[MCP SDK](https://github.com/modelcontextprotocol/typescript-sdk)** - Model Context Protocol implementation
437 |
438 | ---
439 |
440 | **Made with 💜 by Myron Labs**
441 |
442 | *Transform your development workflow with intelligent repository analysis and AI-powered code insights.*
```
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
```markdown
1 | # Contributing to CodeCompass MCP
2 |
3 | Thank you for your interest in contributing to CodeCompass MCP! This document provides guidelines and information for contributors.
4 |
5 | ## 🤝 How to Contribute
6 |
7 | ### Reporting Issues
8 |
9 | 1. **Search existing issues** to avoid duplicates
10 | 2. **Use the issue template** when creating new issues
11 | 3. **Provide detailed information**:
12 | - Steps to reproduce
13 | - Expected vs actual behavior
14 | - Environment details (Node.js version, OS, etc.)
15 | - Error messages and logs
16 |
17 | ### Suggesting Features
18 |
19 | 1. **Check existing feature requests** in issues
20 | 2. **Describe the use case** and problem being solved
21 | 3. **Provide examples** of how the feature would be used
22 | 4. **Consider implementation complexity** and maintenance burden
23 |
24 | ### Pull Requests
25 |
26 | 1. **Fork the repository** and create a feature branch
27 | 2. **Follow the development setup** instructions below
28 | 3. **Make your changes** with appropriate tests
29 | 4. **Update documentation** if needed
30 | 5. **Submit a pull request** with a clear description
31 |
32 | ## 🛠️ Development Setup
33 |
34 | ### Prerequisites
35 |
36 | - Node.js 18+
37 | - npm or yarn
38 | - Git
39 |
40 | ### Installation
41 |
42 | ```bash
43 | # Clone your fork
44 | git clone https://github.com/yourusername/codecompass-mcp.git
45 | cd codecompass-mcp
46 |
47 | # Install dependencies
48 | npm install
49 |
50 | # Build the project
51 | npm run build
52 |
53 | # Run tests
54 | npm test
55 | ```
56 |
57 | ### Development Workflow
58 |
59 | ```bash
60 | # Start development server
61 | npm run dev
62 |
63 | # Start development server with auto-restart
64 | npm run dev:watch
65 |
66 | # Run TypeScript type checking
67 | npm run typecheck
68 |
69 | # Run type checking in watch mode
70 | npm run typecheck:watch
71 |
72 | # Build for development (faster)
73 | npm run build:dev
74 |
75 | # Build with file watching
76 | npm run build:watch
77 |
78 | # Build for production
79 | npm run build
80 |
81 | # Run tests in watch mode
82 | npm run test:watch
83 |
84 | # Run linting
85 | npm run lint
86 |
87 | # Run linting with auto-fix
88 | npm run lint:fix
89 |
90 | # Format code
91 | npm run format
92 |
93 | # Check code formatting
94 | npm run format:check
95 | ```
96 |
97 | ## 📁 Project Structure
98 |
99 | ```
100 | codecompass-mcp/
101 | ├── src/
102 | │ ├── index.ts # Main server entry point
103 | │ ├── services/ # Core services
104 | │ │ ├── github.ts # GitHub API integration
105 | │ │ ├── openai.ts # OpenRouter/AI integration
106 | │ │ └── refactor.ts # Code transformation
107 | │ ├── tools/ # MCP tool definitions
108 | │ │ └── consolidated.ts # All 18 tools
109 | │ ├── types/ # TypeScript type definitions
110 | │ │ ├── index.ts # Core types
111 | │ │ └── responses.ts # Response types
112 | │ └── utils/ # Utility functions
113 | ├── tests/ # Test suites
114 | │ ├── integration/ # Integration tests
115 | │ └── unit/ # Unit tests
116 | ├── docs/ # Documentation
117 | └── examples/ # Usage examples
118 | ```
119 |
120 | ## 🔧 Adding New Tools
121 |
122 | ### Tool Implementation
123 |
124 | 1. **Add tool definition** in `src/tools/consolidated.ts`:
125 | ```typescript
126 | {
127 | name: 'new_tool',
128 | description: 'Description of what the tool does',
129 | inputSchema: {
130 | type: 'object',
131 | properties: {
132 | // Define input parameters
133 | },
134 | required: ['required_param']
135 | }
136 | }
137 | ```
138 |
139 | 2. **Add tool handler** in `src/index.ts`:
140 | ```typescript
141 | case 'new_tool':
142 | return await handleNewTool(args);
143 | ```
144 |
145 | 3. **Implement handler function**:
146 | ```typescript
147 | async function handleNewTool(args: any) {
148 | try {
149 | // Implementation logic
150 | const result = await processNewTool(args);
151 | const response = createResponse(result);
152 | return formatToolResponse(response);
153 | } catch (error) {
154 | const response = createResponse(null, error);
155 | return formatToolResponse(response);
156 | }
157 | }
158 | ```
159 |
160 | ### Tool Guidelines
161 |
162 | - **Follow naming convention**: Use snake_case for tool names
163 | - **Provide clear descriptions**: Help users understand the tool's purpose
164 | - **Include comprehensive schemas**: Define all parameters and options
165 | - **Handle errors gracefully**: Use standardized error responses
166 | - **Add tests**: Include unit and integration tests
167 | - **Update documentation**: Add to API reference
168 |
169 | ## 🧪 Testing
170 |
171 | ### Test Structure
172 |
173 | ```bash
174 | tests/
175 | ├── unit/ # Unit tests
176 | │ ├── services/ # Service tests
177 | │ └── tools/ # Tool tests
178 | └── integration/ # Integration tests
179 | ├── test-all-tools.js # All tools test
180 | └── test-ai-tools.js # AI tools test
181 | ```
182 |
183 | ### Writing Tests
184 |
185 | ```typescript
186 | // Unit test example
187 | describe('GitHub Service', () => {
188 | it('should fetch repository data', async () => {
189 | const result = await githubService.getRepositoryInfo('https://github.com/test/repo');
190 | expect(result).toBeDefined();
191 | expect(result.name).toBe('repo');
192 | });
193 | });
194 |
195 | // Integration test example
196 | describe('fetch_repository_data tool', () => {
197 | it('should return repository analysis', async () => {
198 | const response = await callTool('fetch_repository_data', {
199 | url: 'https://github.com/test/repo'
200 | });
201 | expect(response.success).toBe(true);
202 | expect(response.data).toBeDefined();
203 | });
204 | });
205 | ```
206 |
207 | ### Test Commands
208 |
209 | ```bash
210 | # Run all tests
211 | npm test
212 |
213 | # Run unit tests only
214 | npm run test:unit
215 |
216 | # Run integration tests only
217 | npm run test:integration
218 |
219 | # Run tests with coverage
220 | npm run test:coverage
221 |
222 | # Run tests in watch mode
223 | npm run test:watch
224 | ```
225 |
226 | ## 📝 Code Style
227 |
228 | ### TypeScript Guidelines
229 |
230 | - Use **strict TypeScript** configuration
231 | - Define **interfaces** for all data structures
232 | - Use **type guards** for runtime validation
233 | - Avoid **`any`** type unless absolutely necessary
234 |
235 | ### TypeScript Configuration
236 |
237 | The project uses two TypeScript configurations:
238 |
239 | - **`tsconfig.json`** - Production build with strict type checking
240 | - **`tsconfig.dev.json`** - Development build with optimizations
241 |
242 | #### Key Features:
243 | - **Incremental builds** for faster compilation
244 | - **Source maps** for debugging
245 | - **Path mapping** for clean imports (`@/services/*`, `@/types/*`)
246 | - **Strict type checking** for code quality
247 | - **Node.js compatibility** with ES modules
248 | - **Declaration files** for TypeScript consumers
249 |
250 | ### Formatting
251 |
252 | - Use **Prettier** for code formatting
253 | - Follow **ESLint** rules for code quality
254 | - Use **2 spaces** for indentation
255 | - Max line length: **100 characters**
256 |
257 | ### Naming Conventions
258 |
259 | - **Variables**: `camelCase`
260 | - **Functions**: `camelCase`
261 | - **Classes**: `PascalCase`
262 | - **Constants**: `UPPER_SNAKE_CASE`
263 | - **Files**: `kebab-case.ts`
264 | - **MCP Tools**: `snake_case`
265 |
266 | ## 📚 Documentation
267 |
268 | ### Required Documentation
269 |
270 | - **API Reference**: Update `docs/API.md` for new tools
271 | - **README**: Update main README for significant changes
272 | - **Code Comments**: Add JSDoc comments for public APIs
273 | - **Examples**: Provide usage examples for new features
274 |
275 | ### Documentation Style
276 |
277 | ```typescript
278 | /**
279 | * Analyzes repository structure and complexity
280 | * @param url - GitHub repository URL
281 | * @param options - Analysis options
282 | * @returns Promise<AnalysisResult>
283 | * @throws {Error} When repository is not accessible
284 | */
285 | async function analyzeRepository(url: string, options: AnalysisOptions): Promise<AnalysisResult> {
286 | // Implementation
287 | }
288 | ```
289 |
290 | ## 🔄 CI/CD and Automation
291 |
292 | ### GitHub Actions
293 |
294 | The project uses GitHub Actions for:
295 | - **Automated testing** on pull requests
296 | - **Code quality checks** (linting, formatting)
297 | - **Build verification** on multiple Node.js versions
298 | - **Security scanning** with CodeQL
299 | - **Automated releases** with semantic versioning
300 |
301 | ### Pre-commit Hooks
302 |
303 | ```bash
304 | # Install pre-commit hooks
305 | npm run prepare
306 |
307 | # Hooks run automatically on commit:
308 | # - Code formatting
309 | # - Linting
310 | # - Type checking
311 | # - Test execution
312 | ```
313 |
314 | ## 🚀 Release Process
315 |
316 | ### Version Management
317 |
318 | We use **semantic versioning** (semver):
319 | - **Major** (1.0.0): Breaking changes
320 | - **Minor** (1.1.0): New features, backward compatible
321 | - **Patch** (1.0.1): Bug fixes, backward compatible
322 |
323 | ### Release Steps
324 |
325 | 1. **Create release branch**: `git checkout -b release/v1.1.0`
326 | 2. **Update version**: `npm version minor`
327 | 3. **Update changelog**: Document changes in `CHANGELOG.md`
328 | 4. **Test thoroughly**: Run all tests and manual verification
329 | 5. **Submit PR**: Create pull request for release
330 | 6. **Merge and tag**: After approval, merge and create Git tag
331 | 7. **Publish**: Automated GitHub Actions handles npm publishing
332 |
333 | ## 🛡️ Security
334 |
335 | ### Security Guidelines
336 |
337 | - **No hardcoded secrets**: Use environment variables
338 | - **Validate all inputs**: Use Zod schemas for validation
339 | - **Handle errors safely**: Don't expose sensitive information
340 | - **Keep dependencies updated**: Regular security audits
341 |
342 | ### Reporting Security Issues
343 |
344 | Please report security vulnerabilities to:
345 | - **Email**: [email protected]
346 | - **GitHub**: Use private security advisories
347 | - **Response time**: We aim to respond within 24 hours
348 |
349 | ## 📊 Performance
350 |
351 | ### Performance Guidelines
352 |
353 | - **Cache API responses** when possible
354 | - **Implement rate limiting** for external APIs
355 | - **Use streaming** for large data processing
356 | - **Monitor memory usage** in long-running operations
357 | - **Optimize database queries** if adding persistence
358 |
359 | ### Benchmarking
360 |
361 | ```bash
362 | # Run performance tests
363 | npm run benchmark
364 |
365 | # Profile memory usage
366 | npm run profile
367 | ```
368 |
369 | ## 🤖 AI Integration
370 |
371 | ### OpenRouter Integration
372 |
373 | - **Model selection**: Use intelligent auto-selection
374 | - **Error handling**: Graceful fallbacks for API failures
375 | - **Cost optimization**: Prefer cost-effective models for batch operations
376 | - **Transparency**: Always log model usage and costs
377 |
378 | ### Adding New AI Features
379 |
380 | 1. **Update model characteristics** in `src/services/openai.ts`
381 | 2. **Add model selection logic** for new use cases
382 | 3. **Implement proper error handling** for AI failures
383 | 4. **Add cost warnings** for expensive operations
384 | 5. **Include model transparency** in responses
385 |
386 | ## 📞 Getting Help
387 |
388 | ### Community Resources
389 |
390 | - **GitHub Issues**: Bug reports and feature requests
391 | - **GitHub Discussions**: General questions and ideas
392 | - **Documentation**: Comprehensive guides and API reference
393 | - **Examples**: Working code examples and patterns
394 |
395 | ### Maintainer Contact
396 |
397 | - **GitHub**: @alchemist6
398 | - **Email**: [email protected]
399 | - **Response time**: Usually within 24-48 hours
400 |
401 | ## 📜 Code of Conduct
402 |
403 | ### Our Standards
404 |
405 | - **Be respectful**: Treat all contributors with respect
406 | - **Be inclusive**: Welcome people of all backgrounds
407 | - **Be constructive**: Provide helpful feedback
408 | - **Be collaborative**: Work together toward common goals
409 |
410 | ### Enforcement
411 |
412 | Violations of the code of conduct should be reported to the maintainers. All complaints will be reviewed and investigated promptly and fairly.
413 |
414 | ---
415 |
416 | **Thank you for contributing to CodeCompass MCP!** 🙏
417 |
418 | Your contributions help make code analysis and AI-powered development tools accessible to everyone. Together, we're building something amazing! 🚀
```
--------------------------------------------------------------------------------
/scripts/start-mcp.sh:
--------------------------------------------------------------------------------
```bash
1 | #!/bin/bash
2 |
3 | # CodeCompass MCP Server Startup Script
4 | # This script starts the CodeCompass MCP server with proper configuration
5 |
6 | echo "🚀 Starting CodeCompass MCP Server..."
7 |
8 | # Set environment variables
9 | export NODE_ENV=production
10 |
11 | # Optional: Set GitHub token if available (improves rate limits)
12 | # export GITHUB_TOKEN=your_github_token_here
13 |
14 | # Change to the server directory
15 | cd "$(dirname "$0")"
16 |
17 | # Start the server
18 | node build/index.js
19 |
20 | echo "🛑 CodeCompass MCP Server stopped."
```
--------------------------------------------------------------------------------
/config/tsconfig.dev.json:
--------------------------------------------------------------------------------
```json
1 | {
2 | "extends": "./tsconfig.json",
3 | "compilerOptions": {
4 | // Development-specific overrides
5 | "sourceMap": true,
6 | "inlineSourceMap": false,
7 | "inlineSources": false,
8 | "removeComments": false,
9 |
10 | // Development build optimizations
11 | "incremental": true,
12 | "skipLibCheck": true,
13 |
14 | // Enhanced error reporting
15 | "pretty": true,
16 | "noErrorTruncation": true,
17 |
18 | // Watch mode configuration
19 | "preserveWatchOutput": true
20 | },
21 | "include": [
22 | "src/**/*",
23 | "src/**/*.json"
24 | ],
25 | "exclude": [
26 | "node_modules",
27 | "build",
28 | "tests/**/*.test.ts",
29 | "tests/**/*.spec.ts",
30 | "**/*.d.ts"
31 | ]
32 | }
```
--------------------------------------------------------------------------------
/docker/docker-compose.dev.yml:
--------------------------------------------------------------------------------
```yaml
1 | version: '3.8'
2 |
3 | services:
4 | codecompass-mcp:
5 | build:
6 | context: .
7 | dockerfile: Dockerfile.dev
8 | args:
9 | NODE_ENV: development
10 | environment:
11 | - NODE_ENV=development
12 | - LOG_LEVEL=debug
13 | volumes:
14 | # Mount source code for development
15 | - .:/app
16 | - /app/node_modules
17 | # Mount for development logs
18 | - ./logs:/app/logs
19 | ports:
20 | - "3000:3000"
21 | - "9229:9229" # Debug port
22 | command: ["npm", "run", "dev"]
23 | # Override health check for development
24 | healthcheck:
25 | test: ["CMD", "curl", "-f", "http://localhost:3000/health"]
26 | interval: 30s
27 | timeout: 10s
28 | retries: 3
29 | start_period: 40s
```
--------------------------------------------------------------------------------
/Dockerfile:
--------------------------------------------------------------------------------
```dockerfile
1 | # Use official Node.js runtime as base image
2 | FROM node:18-alpine
3 |
4 | # Set working directory
5 | WORKDIR /app
6 |
7 | # Create non-root user for security
8 | RUN addgroup -g 1001 -S nodejs && \
9 | adduser -S codecompass -u 1001
10 |
11 | # Copy package files
12 | COPY package*.json ./
13 |
14 | # Install all dependencies (including dev dependencies for build)
15 | RUN npm ci && \
16 | npm cache clean --force
17 |
18 | # Copy source code
19 | COPY . .
20 |
21 | # Build the application
22 | RUN npm run build
23 |
24 | # Remove dev dependencies after build
25 | RUN npm prune --production
26 |
27 | # Set ownership of app directory
28 | RUN chown -R codecompass:nodejs /app
29 |
30 | # Switch to non-root user
31 | USER codecompass
32 |
33 | # Expose port for health checks (optional)
34 | EXPOSE 3000
35 |
36 | # Add health check
37 | HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
38 | CMD node -e "console.log('Health check passed')" || exit 1
39 |
40 | # Set environment variables
41 | ENV NODE_ENV=production
42 | ENV LOG_LEVEL=info
43 |
44 | # Start the application
45 | CMD ["node", "build/index.js"]
```
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
```json
1 | {
2 | "compilerOptions": {
3 | // Target and Module Configuration
4 | "target": "ES2022",
5 | "module": "ESNext",
6 | "lib": ["ES2022"],
7 | "moduleResolution": "node",
8 |
9 | // Build Configuration
10 | "outDir": "./build",
11 | "rootDir": "./src",
12 | "incremental": true,
13 | "tsBuildInfoFile": "./build/.tsbuildinfo",
14 |
15 | // Type Checking
16 | "strict": true,
17 | "noImplicitAny": true,
18 | "strictNullChecks": true,
19 | "strictFunctionTypes": true,
20 | "noImplicitReturns": true,
21 | "noFallthroughCasesInSwitch": true,
22 | "noUncheckedIndexedAccess": false,
23 | "exactOptionalPropertyTypes": false,
24 |
25 | // Module Resolution
26 | "esModuleInterop": true,
27 | "allowSyntheticDefaultImports": true,
28 | "resolveJsonModule": true,
29 | "moduleDetection": "force",
30 |
31 | // Emit Configuration
32 | "declaration": true,
33 | "declarationMap": true,
34 | "sourceMap": true,
35 | "removeComments": false,
36 | "importHelpers": true,
37 |
38 | // Advanced Options
39 | "skipLibCheck": true,
40 | "forceConsistentCasingInFileNames": true,
41 | "allowUnusedLabels": false,
42 | "allowUnreachableCode": false,
43 | "noImplicitOverride": true,
44 |
45 | // Path Mapping
46 | "baseUrl": ".",
47 | "paths": {
48 | "@/*": ["src/*"],
49 | "@/types/*": ["src/types/*"],
50 | "@/services/*": ["src/services/*"],
51 | "@/tools/*": ["src/tools/*"],
52 | "@/utils/*": ["src/utils/*"]
53 | },
54 |
55 | // Node.js Compatibility
56 | "types": ["node"],
57 | "allowImportingTsExtensions": false
58 | },
59 | "include": [
60 | "src/**/*",
61 | "src/**/*.json"
62 | ],
63 | "exclude": [
64 | "node_modules",
65 | "build",
66 | "tests",
67 | "**/*.test.ts",
68 | "**/*.spec.ts"
69 | ],
70 | "ts-node": {
71 | "esm": true,
72 | "experimentalSpecifierResolution": "node"
73 | }
74 | }
```
--------------------------------------------------------------------------------
/docker/docker-compose.yml:
--------------------------------------------------------------------------------
```yaml
1 | version: '3.8'
2 |
3 | services:
4 | codecompass-mcp:
5 | build:
6 | context: .
7 | dockerfile: Dockerfile
8 | container_name: codecompass-mcp
9 | environment:
10 | - NODE_ENV=production
11 | - LOG_LEVEL=info
12 | - GITHUB_TOKEN=${GITHUB_TOKEN}
13 | - OPENROUTER_API_KEY=${OPENROUTER_API_KEY}
14 | - OPENAI_MODEL=${OPENAI_MODEL:-anthropic/claude-3.5-sonnet}
15 | - MAX_RESPONSE_TOKENS=${MAX_RESPONSE_TOKENS:-25000}
16 | - MAX_FILE_CONTENT_LENGTH=${MAX_FILE_CONTENT_LENGTH:-1000}
17 | - CACHE_ENABLED=${CACHE_ENABLED:-true}
18 | - CACHE_TTL=${CACHE_TTL:-300000}
19 | - MAX_FILES=${MAX_FILES:-100}
20 | - MAX_FILE_SIZE=${MAX_FILE_SIZE:-1048576}
21 | - MAX_PROCESSING_TIME=${MAX_PROCESSING_TIME:-60000}
22 | volumes:
23 | # Mount for persistent logs (optional)
24 | - codecompass-logs:/app/logs
25 | # Mount for configuration (optional)
26 | - ./config:/app/config:ro
27 | restart: unless-stopped
28 | stdin_open: true
29 | tty: true
30 | # Health check
31 | healthcheck:
32 | test: ["CMD", "node", "-e", "console.log('Health check passed')"]
33 | interval: 30s
34 | timeout: 10s
35 | retries: 3
36 | start_period: 40s
37 | # Resource limits
38 | deploy:
39 | resources:
40 | limits:
41 | cpus: '1.0'
42 | memory: 512M
43 | reservations:
44 | cpus: '0.5'
45 | memory: 256M
46 |
47 | # Optional: Add a logging service
48 | codecompass-logs:
49 | image: fluent/fluent-bit:latest
50 | container_name: codecompass-logs
51 | depends_on:
52 | - codecompass-mcp
53 | volumes:
54 | - codecompass-logs:/var/log/codecompass
55 | - ./docker/fluent-bit.conf:/fluent-bit/etc/fluent-bit.conf:ro
56 | restart: unless-stopped
57 | profiles:
58 | - logging
59 |
60 | volumes:
61 | codecompass-logs:
62 | driver: local
63 |
64 | # Example usage:
65 | # 1. Basic deployment:
66 | # docker-compose up -d
67 | #
68 | # 2. With logging:
69 | # docker-compose --profile logging up -d
70 | #
71 | # 3. Development mode:
72 | # docker-compose -f docker-compose.yml -f docker-compose.dev.yml up
```
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
```json
1 | {
2 | "name": "codecompass-mcp",
3 | "version": "1.0.0",
4 | "description": "Advanced MCP server for GitHub repository analysis, code refactoring, and AI-powered code insights with OpenRouter integration",
5 | "main": "build/index.js",
6 | "type": "module",
7 | "scripts": {
8 | "build": "tsc",
9 | "build:dev": "tsc --project config/tsconfig.dev.json",
10 | "build:watch": "tsc --watch --project config/tsconfig.dev.json",
11 | "start": "node build/index.js",
12 | "dev": "tsx src/index.ts",
13 | "dev:watch": "tsx watch src/index.ts",
14 | "test": "npm run test:unit",
15 | "test:unit": "echo 'Unit tests not implemented yet'",
16 | "test:verify": "bash tests/verify-installation.sh",
17 | "clean": "rm -rf build/ && rm -f *.tsbuildinfo",
18 | "prebuild": "npm run clean",
19 | "typecheck": "tsc --noEmit",
20 | "typecheck:watch": "tsc --noEmit --watch",
21 | "lint": "eslint src/**/*.ts --config config/.eslintrc.json",
22 | "lint:fix": "eslint src/**/*.ts --config config/.eslintrc.json --fix",
23 | "format": "prettier --write src/**/*.ts --config config/.prettierrc",
24 | "format:check": "prettier --check src/**/*.ts --config config/.prettierrc"
25 | },
26 | "keywords": [
27 | "mcp",
28 | "github",
29 | "refactoring",
30 | "code-analysis",
31 | "openrouter",
32 | "ai-tools",
33 | "code-review",
34 | "repository-analysis",
35 | "model-context-protocol",
36 | "claude-desktop"
37 | ],
38 | "author": "Myron Labs Team",
39 | "license": "MIT",
40 | "repository": {
41 | "type": "git",
42 | "url": "https://github.com/codecompass/codecompass-mcp.git"
43 | },
44 | "bugs": {
45 | "url": "https://github.com/codecompass/codecompass-mcp/issues"
46 | },
47 | "homepage": "https://github.com/codecompass/codecompass-mcp#readme",
48 | "dependencies": {
49 | "@modelcontextprotocol/sdk": "^0.6.0",
50 | "@octokit/rest": "^22.0.0",
51 | "zod": "^3.24.2",
52 | "typescript": "^5.6.3",
53 | "@types/node": "^20.16.11",
54 | "nanoid": "^5.1.5",
55 | "openai": "^4.67.1"
56 | },
57 | "devDependencies": {
58 | "tsx": "^4.19.1",
59 | "jest": "^29.7.0",
60 | "@types/jest": "^29.5.13",
61 | "eslint": "^8.57.0",
62 | "@typescript-eslint/eslint-plugin": "^6.21.0",
63 | "@typescript-eslint/parser": "^6.21.0",
64 | "prettier": "^3.3.3"
65 | },
66 | "engines": {
67 | "node": ">=18.0.0"
68 | }
69 | }
```
--------------------------------------------------------------------------------
/tests/verify-installation.sh:
--------------------------------------------------------------------------------
```bash
1 | #!/bin/bash
2 |
3 | echo "🔍 CodeCompass MCP Server Installation Verification"
4 | echo "=================================================="
5 |
6 | # Check Node.js version
7 | echo "1. Checking Node.js version..."
8 | node_version=$(node --version)
9 | echo " Node.js version: $node_version"
10 |
11 | if [[ "$node_version" < "v18" ]]; then
12 | echo " ❌ Node.js 18+ is required. Please upgrade."
13 | exit 1
14 | else
15 | echo " ✅ Node.js version is compatible"
16 | fi
17 |
18 | # Check if server is built
19 | echo
20 | echo "2. Checking if server is built..."
21 | if [ -f "build/index.js" ]; then
22 | echo " ✅ Server is built"
23 | else
24 | echo " ❌ Server not built. Running npm run build..."
25 | npm run build
26 | if [ $? -eq 0 ]; then
27 | echo " ✅ Build completed successfully"
28 | else
29 | echo " ❌ Build failed"
30 | exit 1
31 | fi
32 | fi
33 |
34 | # Check Claude Code configuration
35 | echo
36 | echo "3. Checking Claude Code configuration..."
37 | if [ -f "$HOME/.claude-code/mcp_servers.json" ]; then
38 | echo " ✅ Claude Code MCP configuration exists"
39 | echo " Configuration file: $HOME/.claude-code/mcp_servers.json"
40 | else
41 | echo " ❌ Claude Code MCP configuration not found"
42 | echo " Please make sure Claude Code is installed and configured"
43 | fi
44 |
45 | # Test server startup
46 | echo
47 | echo "4. Testing server startup..."
48 | timeout 5s node build/index.js > /dev/null 2>&1
49 | exit_code=$?
50 | if [ $exit_code -eq 124 ]; then
51 | echo " ✅ Server starts successfully (timeout as expected)"
52 | elif [ $exit_code -eq 0 ]; then
53 | echo " ✅ Server starts successfully"
54 | else
55 | echo " ❌ Server failed to start (exit code: $exit_code)"
56 | exit 1
57 | fi
58 |
59 | # Check GitHub token (optional)
60 | echo
61 | echo "5. Checking GitHub token (optional)..."
62 | if [ -n "$GITHUB_TOKEN" ]; then
63 | echo " ✅ GitHub token is set (higher rate limits)"
64 | else
65 | echo " ⚠️ GitHub token not set (using public API limits)"
66 | echo " To set a token: export GITHUB_TOKEN=your_token_here"
67 | fi
68 |
69 | echo
70 | echo "🎉 Installation verification complete!"
71 | echo
72 | echo "📋 Summary:"
73 | echo " - Node.js: ✅ Compatible"
74 | echo " - Server built: ✅ Ready"
75 | echo " - Configuration: ✅ Configured"
76 | echo " - Server startup: ✅ Working"
77 | echo " - GitHub token: $([ -n "$GITHUB_TOKEN" ] && echo "✅ Set" || echo "⚠️ Not set")"
78 | echo
79 | echo "🚀 You can now use the CodeCompass MCP server with Claude Code!"
80 | echo
81 | echo "Usage examples:"
82 | echo " - 'Analyze this repository: https://github.com/user/repo'"
83 | echo " - 'Extract reusable components from this React project'"
84 | echo " - 'Transform this code to use modern JavaScript features'"
85 | echo
86 | echo "For more information, see the README.md file."
```
--------------------------------------------------------------------------------
/scripts/docker-logs.sh:
--------------------------------------------------------------------------------
```bash
1 | #!/bin/bash
2 |
3 | # CodeCompass MCP Docker Logs Script
4 | # Utility script for viewing container logs
5 |
6 | set -e
7 |
8 | # Colors for output
9 | RED='\033[0;31m'
10 | GREEN='\033[0;32m'
11 | YELLOW='\033[1;33m'
12 | BLUE='\033[0;34m'
13 | NC='\033[0m' # No Color
14 |
15 | # Default values
16 | CONTAINER_NAME="codecompass-mcp"
17 | FOLLOW=false
18 | TAIL_LINES=100
19 | SHOW_TIMESTAMPS=false
20 |
21 | # Function to display usage
22 | show_usage() {
23 | echo "Usage: $0 [OPTIONS]"
24 | echo "Options:"
25 | echo " -n, --name NAME Container name (default: codecompass-mcp)"
26 | echo " -f, --follow Follow log output"
27 | echo " -t, --tail LINES Number of lines to show (default: 100)"
28 | echo " --timestamps Show timestamps"
29 | echo " --all Show all logs (no tail limit)"
30 | echo " -h, --help Show this help message"
31 | echo ""
32 | echo "Examples:"
33 | echo " $0 # Show last 100 lines"
34 | echo " $0 -f # Follow logs"
35 | echo " $0 -t 50 # Show last 50 lines"
36 | echo " $0 --all # Show all logs"
37 | echo " $0 --timestamps -f # Follow with timestamps"
38 | }
39 |
40 | # Parse command line arguments
41 | while [[ $# -gt 0 ]]; do
42 | case $1 in
43 | -n|--name)
44 | CONTAINER_NAME="$2"
45 | shift 2
46 | ;;
47 | -f|--follow)
48 | FOLLOW=true
49 | shift
50 | ;;
51 | -t|--tail)
52 | TAIL_LINES="$2"
53 | shift 2
54 | ;;
55 | --timestamps)
56 | SHOW_TIMESTAMPS=true
57 | shift
58 | ;;
59 | --all)
60 | TAIL_LINES="all"
61 | shift
62 | ;;
63 | -h|--help)
64 | show_usage
65 | exit 0
66 | ;;
67 | *)
68 | echo "Unknown option: $1"
69 | show_usage
70 | exit 1
71 | ;;
72 | esac
73 | done
74 |
75 | echo -e "${BLUE}CodeCompass MCP Docker Logs${NC}"
76 | echo -e "${BLUE}===========================${NC}"
77 | echo "Container: $CONTAINER_NAME"
78 | echo ""
79 |
80 | # Check if container exists
81 | if ! docker ps -a --format "table {{.Names}}" | grep -q "^$CONTAINER_NAME$"; then
82 | echo -e "${RED}Error: Container '$CONTAINER_NAME' not found${NC}"
83 | echo "Available containers:"
84 | docker ps -a --format "table {{.Names}}\t{{.Status}}\t{{.Image}}"
85 | exit 1
86 | fi
87 |
88 | # Check if container is running
89 | if ! docker ps --format "table {{.Names}}" | grep -q "^$CONTAINER_NAME$"; then
90 | echo -e "${YELLOW}Warning: Container '$CONTAINER_NAME' is not running${NC}"
91 | echo "Showing logs from stopped container..."
92 | echo ""
93 | fi
94 |
95 | # Build docker logs command
96 | DOCKER_CMD="docker logs"
97 |
98 | if [ "$SHOW_TIMESTAMPS" = true ]; then
99 | DOCKER_CMD="$DOCKER_CMD --timestamps"
100 | fi
101 |
102 | if [ "$FOLLOW" = true ]; then
103 | DOCKER_CMD="$DOCKER_CMD --follow"
104 | fi
105 |
106 | if [ "$TAIL_LINES" != "all" ]; then
107 | DOCKER_CMD="$DOCKER_CMD --tail $TAIL_LINES"
108 | fi
109 |
110 | DOCKER_CMD="$DOCKER_CMD $CONTAINER_NAME"
111 |
112 | echo -e "${YELLOW}Showing logs for container '$CONTAINER_NAME'${NC}"
113 | if [ "$FOLLOW" = true ]; then
114 | echo -e "${YELLOW}Following logs... (Press Ctrl+C to stop)${NC}"
115 | fi
116 | echo ""
117 |
118 | # Execute the command
119 | eval $DOCKER_CMD
```
--------------------------------------------------------------------------------
/scripts/docker-build.sh:
--------------------------------------------------------------------------------
```bash
1 | #!/bin/bash
2 |
3 | # CodeCompass MCP Docker Build Script
4 | # Based on patterns from OpenRouter MCP repository
5 |
6 | set -e
7 |
8 | # Colors for output
9 | RED='\033[0;31m'
10 | GREEN='\033[0;32m'
11 | YELLOW='\033[1;33m'
12 | BLUE='\033[0;34m'
13 | NC='\033[0m' # No Color
14 |
15 | # Default values
16 | IMAGE_NAME="codecompass-mcp"
17 | TAG="latest"
18 | DOCKERFILE="Dockerfile"
19 | PUSH_TO_REGISTRY=false
20 | REGISTRY=""
21 | BUILD_ARGS=""
22 |
23 | # Function to display usage
24 | show_usage() {
25 | echo "Usage: $0 [OPTIONS]"
26 | echo "Options:"
27 | echo " -t, --tag TAG Set image tag (default: latest)"
28 | echo " -f, --file FILE Dockerfile to use (default: Dockerfile)"
29 | echo " -p, --push Push to registry after build"
30 | echo " -r, --registry REG Registry to push to"
31 | echo " --build-arg KEY=VALUE Build argument"
32 | echo " --dev Use development Dockerfile"
33 | echo " -h, --help Show this help message"
34 | echo ""
35 | echo "Examples:"
36 | echo " $0 # Build with default settings"
37 | echo " $0 --dev # Build development image"
38 | echo " $0 -t v1.0.0 --push # Build and push v1.0.0"
39 | echo " $0 --build-arg NODE_ENV=production"
40 | }
41 |
42 | # Parse command line arguments
43 | while [[ $# -gt 0 ]]; do
44 | case $1 in
45 | -t|--tag)
46 | TAG="$2"
47 | shift 2
48 | ;;
49 | -f|--file)
50 | DOCKERFILE="$2"
51 | shift 2
52 | ;;
53 | -p|--push)
54 | PUSH_TO_REGISTRY=true
55 | shift
56 | ;;
57 | -r|--registry)
58 | REGISTRY="$2"
59 | shift 2
60 | ;;
61 | --build-arg)
62 | BUILD_ARGS="$BUILD_ARGS --build-arg $2"
63 | shift 2
64 | ;;
65 | --dev)
66 | DOCKERFILE="Dockerfile.dev"
67 | TAG="dev"
68 | shift
69 | ;;
70 | -h|--help)
71 | show_usage
72 | exit 0
73 | ;;
74 | *)
75 | echo "Unknown option: $1"
76 | show_usage
77 | exit 1
78 | ;;
79 | esac
80 | done
81 |
82 | # Construct full image name
83 | FULL_IMAGE_NAME="${IMAGE_NAME}:${TAG}"
84 | if [ -n "$REGISTRY" ]; then
85 | FULL_IMAGE_NAME="${REGISTRY}/${FULL_IMAGE_NAME}"
86 | fi
87 |
88 | echo -e "${BLUE}CodeCompass MCP Docker Build${NC}"
89 | echo -e "${BLUE}=============================${NC}"
90 | echo "Image: $FULL_IMAGE_NAME"
91 | echo "Dockerfile: $DOCKERFILE"
92 | echo "Build args: $BUILD_ARGS"
93 | echo ""
94 |
95 | # Check if Dockerfile exists
96 | if [ ! -f "$DOCKERFILE" ]; then
97 | echo -e "${RED}Error: Dockerfile '$DOCKERFILE' not found${NC}"
98 | exit 1
99 | fi
100 |
101 | # Build the image
102 | echo -e "${YELLOW}Building Docker image...${NC}"
103 | docker build \
104 | -t "$FULL_IMAGE_NAME" \
105 | -f "$DOCKERFILE" \
106 | $BUILD_ARGS \
107 | .
108 |
109 | if [ $? -eq 0 ]; then
110 | echo -e "${GREEN}✓ Build successful${NC}"
111 |
112 | # Show image info
113 | echo -e "${BLUE}Image information:${NC}"
114 | docker images "$FULL_IMAGE_NAME"
115 |
116 | # Push to registry if requested
117 | if [ "$PUSH_TO_REGISTRY" = true ]; then
118 | echo -e "${YELLOW}Pushing to registry...${NC}"
119 | docker push "$FULL_IMAGE_NAME"
120 |
121 | if [ $? -eq 0 ]; then
122 | echo -e "${GREEN}✓ Push successful${NC}"
123 | else
124 | echo -e "${RED}✗ Push failed${NC}"
125 | exit 1
126 | fi
127 | fi
128 |
129 | echo -e "${GREEN}✓ Docker build completed successfully${NC}"
130 | echo ""
131 | echo "To run the container:"
132 | echo " docker run -d --name codecompass-mcp $FULL_IMAGE_NAME"
133 | echo ""
134 | echo "To run with environment variables:"
135 | echo " docker run -d --name codecompass-mcp \\"
136 | echo " -e GITHUB_TOKEN=your_token \\"
137 | echo " -e OPENROUTER_API_KEY=your_key \\"
138 | echo " $FULL_IMAGE_NAME"
139 |
140 | else
141 | echo -e "${RED}✗ Build failed${NC}"
142 | exit 1
143 | fi
```
--------------------------------------------------------------------------------
/docs/legacy-tools/repository.ts:
--------------------------------------------------------------------------------
```typescript
1 | import { Tool } from '@modelcontextprotocol/sdk/types.js';
2 |
3 | export const repositoryTools: Tool[] = [
4 | {
5 | name: 'analyze_repository',
6 | description: 'Perform comprehensive analysis of a GitHub repository including structure, dependencies, and refactoring potential',
7 | inputSchema: {
8 | type: 'object',
9 | properties: {
10 | url: {
11 | type: 'string',
12 | description: 'GitHub repository URL (e.g., https://github.com/owner/repo)',
13 | },
14 | options: {
15 | type: 'object',
16 | properties: {
17 | includeTests: {
18 | type: 'boolean',
19 | description: 'Include test files in analysis',
20 | default: true,
21 | },
22 | includeDocs: {
23 | type: 'boolean',
24 | description: 'Include documentation files in analysis',
25 | default: true,
26 | },
27 | maxFiles: {
28 | type: 'number',
29 | description: 'Maximum number of files to analyze',
30 | default: 100,
31 | },
32 | languages: {
33 | type: 'array',
34 | items: { type: 'string' },
35 | description: 'Specific languages to focus on (e.g., ["javascript", "typescript"])',
36 | },
37 | },
38 | },
39 | },
40 | required: ['url'],
41 | },
42 | },
43 | {
44 | name: 'get_repository_info',
45 | description: 'Get basic repository information including metadata, file structure, and key files',
46 | inputSchema: {
47 | type: 'object',
48 | properties: {
49 | url: {
50 | type: 'string',
51 | description: 'GitHub repository URL',
52 | },
53 | branch: {
54 | type: 'string',
55 | description: 'Specific branch to analyze (default: main/master)',
56 | },
57 | },
58 | required: ['url'],
59 | },
60 | },
61 | {
62 | name: 'get_file_tree',
63 | description: 'Get complete file tree structure of a repository with optional filtering',
64 | inputSchema: {
65 | type: 'object',
66 | properties: {
67 | url: {
68 | type: 'string',
69 | description: 'GitHub repository URL',
70 | },
71 | path: {
72 | type: 'string',
73 | description: 'Specific path to start from (default: root)',
74 | },
75 | maxDepth: {
76 | type: 'number',
77 | description: 'Maximum depth to traverse (default: unlimited)',
78 | },
79 | includeHidden: {
80 | type: 'boolean',
81 | description: 'Include hidden files and directories',
82 | default: false,
83 | },
84 | extensions: {
85 | type: 'array',
86 | items: { type: 'string' },
87 | description: 'Filter by file extensions (e.g., [".js", ".ts"])',
88 | },
89 | },
90 | required: ['url'],
91 | },
92 | },
93 | {
94 | name: 'analyze_dependencies',
95 | description: 'Analyze project dependencies and their relationships',
96 | inputSchema: {
97 | type: 'object',
98 | properties: {
99 | url: {
100 | type: 'string',
101 | description: 'GitHub repository URL',
102 | },
103 | includeDevDependencies: {
104 | type: 'boolean',
105 | description: 'Include development dependencies',
106 | default: true,
107 | },
108 | analyzeSecurity: {
109 | type: 'boolean',
110 | description: 'Check for security vulnerabilities',
111 | default: false,
112 | },
113 | suggestAlternatives: {
114 | type: 'boolean',
115 | description: 'Suggest alternative libraries',
116 | default: false,
117 | },
118 | },
119 | required: ['url'],
120 | },
121 | },
122 | {
123 | name: 'get_architecture_overview',
124 | description: 'Get high-level architecture overview of the repository',
125 | inputSchema: {
126 | type: 'object',
127 | properties: {
128 | url: {
129 | type: 'string',
130 | description: 'GitHub repository URL',
131 | },
132 | focusAreas: {
133 | type: 'array',
134 | items: { type: 'string' },
135 | description: 'Specific areas to focus on (e.g., ["frontend", "backend", "database"])',
136 | },
137 | },
138 | required: ['url'],
139 | },
140 | },
141 | {
142 | name: 'identify_patterns',
143 | description: 'Identify architectural patterns and design principles used in the repository',
144 | inputSchema: {
145 | type: 'object',
146 | properties: {
147 | url: {
148 | type: 'string',
149 | description: 'GitHub repository URL',
150 | },
151 | patternTypes: {
152 | type: 'array',
153 | items: { type: 'string' },
154 | description: 'Types of patterns to look for (e.g., ["mvc", "observer", "factory"])',
155 | },
156 | },
157 | required: ['url'],
158 | },
159 | },
160 | ];
```
--------------------------------------------------------------------------------
/docs/legacy-tools/files.ts:
--------------------------------------------------------------------------------
```typescript
1 | import { Tool } from '@modelcontextprotocol/sdk/types.js';
2 |
3 | export const fileTools: Tool[] = [
4 | {
5 | name: 'get_file_content',
6 | description: 'Retrieve the content of a specific file from a GitHub repository',
7 | inputSchema: {
8 | type: 'object',
9 | properties: {
10 | url: {
11 | type: 'string',
12 | description: 'GitHub repository URL',
13 | },
14 | filePath: {
15 | type: 'string',
16 | description: 'Path to the file within the repository',
17 | },
18 | branch: {
19 | type: 'string',
20 | description: 'Branch to read from (default: main/master)',
21 | },
22 | includeMetadata: {
23 | type: 'boolean',
24 | description: 'Include file metadata (size, last modified, etc.)',
25 | default: false,
26 | },
27 | },
28 | required: ['url', 'filePath'],
29 | },
30 | },
31 | {
32 | name: 'get_key_files',
33 | description: 'Extract and analyze key files from a repository (README, config files, main entry points)',
34 | inputSchema: {
35 | type: 'object',
36 | properties: {
37 | url: {
38 | type: 'string',
39 | description: 'GitHub repository URL',
40 | },
41 | fileTypes: {
42 | type: 'array',
43 | items: { type: 'string' },
44 | description: 'Types of key files to extract (e.g., ["config", "entry", "documentation"])',
45 | },
46 | maxSize: {
47 | type: 'number',
48 | description: 'Maximum file size to include (in bytes)',
49 | default: 50000,
50 | },
51 | },
52 | required: ['url'],
53 | },
54 | },
55 | {
56 | name: 'extract_functions',
57 | description: 'Extract specific functions or classes from files',
58 | inputSchema: {
59 | type: 'object',
60 | properties: {
61 | url: {
62 | type: 'string',
63 | description: 'GitHub repository URL',
64 | },
65 | filePath: {
66 | type: 'string',
67 | description: 'Path to the file containing the functions',
68 | },
69 | functionNames: {
70 | type: 'array',
71 | items: { type: 'string' },
72 | description: 'Names of functions to extract (optional - extracts all if not specified)',
73 | },
74 | includeDocumentation: {
75 | type: 'boolean',
76 | description: 'Include function documentation/comments',
77 | default: true,
78 | },
79 | includeDependencies: {
80 | type: 'boolean',
81 | description: 'Include function dependencies and imports',
82 | default: true,
83 | },
84 | },
85 | required: ['url', 'filePath'],
86 | },
87 | },
88 | {
89 | name: 'search_code',
90 | description: 'Search for specific code patterns, functions, or text within the repository',
91 | inputSchema: {
92 | type: 'object',
93 | properties: {
94 | url: {
95 | type: 'string',
96 | description: 'GitHub repository URL',
97 | },
98 | query: {
99 | type: 'string',
100 | description: 'Search query (can be regex or plain text)',
101 | },
102 | searchType: {
103 | type: 'string',
104 | enum: ['text', 'regex', 'function', 'class', 'variable'],
105 | description: 'Type of search to perform',
106 | default: 'text',
107 | },
108 | fileExtensions: {
109 | type: 'array',
110 | items: { type: 'string' },
111 | description: 'File extensions to search in (e.g., [".js", ".ts"])',
112 | },
113 | excludePaths: {
114 | type: 'array',
115 | items: { type: 'string' },
116 | description: 'Paths to exclude from search (e.g., ["node_modules", "dist"])',
117 | },
118 | maxResults: {
119 | type: 'number',
120 | description: 'Maximum number of results to return',
121 | default: 50,
122 | },
123 | },
124 | required: ['url', 'query'],
125 | },
126 | },
127 | {
128 | name: 'get_file_dependencies',
129 | description: 'Analyze dependencies and imports for a specific file',
130 | inputSchema: {
131 | type: 'object',
132 | properties: {
133 | url: {
134 | type: 'string',
135 | description: 'GitHub repository URL',
136 | },
137 | filePath: {
138 | type: 'string',
139 | description: 'Path to the file to analyze',
140 | },
141 | includeIndirect: {
142 | type: 'boolean',
143 | description: 'Include indirect dependencies',
144 | default: false,
145 | },
146 | resolveModules: {
147 | type: 'boolean',
148 | description: 'Resolve module paths to actual files',
149 | default: true,
150 | },
151 | },
152 | required: ['url', 'filePath'],
153 | },
154 | },
155 | {
156 | name: 'analyze_file_complexity',
157 | description: 'Analyze code complexity metrics for specific files',
158 | inputSchema: {
159 | type: 'object',
160 | properties: {
161 | url: {
162 | type: 'string',
163 | description: 'GitHub repository URL',
164 | },
165 | filePaths: {
166 | type: 'array',
167 | items: { type: 'string' },
168 | description: 'Paths to files to analyze',
169 | },
170 | metrics: {
171 | type: 'array',
172 | items: { type: 'string' },
173 | description: 'Complexity metrics to calculate (e.g., ["cyclomatic", "cognitive", "lines"])',
174 | },
175 | },
176 | required: ['url', 'filePaths'],
177 | },
178 | },
179 | {
180 | name: 'get_file_history',
181 | description: 'Get commit history and changes for specific files',
182 | inputSchema: {
183 | type: 'object',
184 | properties: {
185 | url: {
186 | type: 'string',
187 | description: 'GitHub repository URL',
188 | },
189 | filePath: {
190 | type: 'string',
191 | description: 'Path to the file',
192 | },
193 | maxCommits: {
194 | type: 'number',
195 | description: 'Maximum number of commits to retrieve',
196 | default: 10,
197 | },
198 | includeDiff: {
199 | type: 'boolean',
200 | description: 'Include diff information',
201 | default: false,
202 | },
203 | },
204 | required: ['url', 'filePath'],
205 | },
206 | },
207 | ];
```
--------------------------------------------------------------------------------
/examples/basic-usage.js:
--------------------------------------------------------------------------------
```javascript
1 | #!/usr/bin/env node
2 |
3 | /**
4 | * Basic usage example for CodeCompass MCP Server
5 | *
6 | * This example demonstrates how to use the CodeCompass MCP server
7 | * to analyze a GitHub repository and perform basic refactoring operations.
8 | */
9 |
10 | import { MCPClient } from '@modelcontextprotocol/sdk/client/index.js';
11 | import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
12 | import { spawn } from 'child_process';
13 |
14 | async function main() {
15 | // Start the MCP server
16 | const serverProcess = spawn('node', ['../build/index.js'], {
17 | stdio: ['pipe', 'pipe', 'pipe'],
18 | });
19 |
20 | // Create MCP client
21 | const transport = new StdioClientTransport({
22 | reader: serverProcess.stdout,
23 | writer: serverProcess.stdin,
24 | });
25 |
26 | const client = new MCPClient({
27 | name: 'codecompass-example',
28 | version: '1.0.0',
29 | });
30 |
31 | try {
32 | await client.connect(transport);
33 |
34 | console.log('🚀 Connected to CodeCompass MCP Server');
35 | console.log('📊 Starting repository analysis...\n');
36 |
37 | // Example 1: Analyze a popular React repository
38 | console.log('=== Example 1: Repository Analysis ===');
39 | const repoUrl = 'https://github.com/facebook/react';
40 |
41 | const analysis = await client.request({
42 | method: 'tools/call',
43 | params: {
44 | name: 'analyze_repository',
45 | arguments: {
46 | url: repoUrl,
47 | options: {
48 | includeTests: true,
49 | includeDocs: true,
50 | maxFiles: 20, // Limit for demo
51 | },
52 | },
53 | },
54 | });
55 |
56 | console.log('✅ Analysis complete:');
57 | console.log(`- Repository: ${JSON.parse(analysis.content[0].text).info.name}`);
58 | console.log(`- Language: ${JSON.parse(analysis.content[0].text).info.language}`);
59 | console.log(`- Files: ${JSON.parse(analysis.content[0].text).info.fileCount}`);
60 | console.log(`- Dependencies: ${JSON.parse(analysis.content[0].text).dependencies.length}`);
61 | console.log();
62 |
63 | // Example 2: Extract reusable components
64 | console.log('=== Example 2: Component Extraction ===');
65 | const components = await client.request({
66 | method: 'tools/call',
67 | params: {
68 | name: 'extract_reusable_components',
69 | arguments: {
70 | url: repoUrl,
71 | componentTypes: ['ui-components', 'hooks', 'utilities'],
72 | },
73 | },
74 | });
75 |
76 | const componentList = JSON.parse(components.content[0].text);
77 | console.log(`✅ Found ${componentList.length} reusable components:`);
78 | componentList.slice(0, 5).forEach((comp, i) => {
79 | console.log(`${i + 1}. ${comp.name} (${comp.type}) - Reusability: ${comp.reusabilityScore}%`);
80 | });
81 | console.log();
82 |
83 | // Example 3: Get file content
84 | console.log('=== Example 3: File Content Analysis ===');
85 | const fileContent = await client.request({
86 | method: 'tools/call',
87 | params: {
88 | name: 'get_file_content',
89 | arguments: {
90 | url: repoUrl,
91 | filePath: 'package.json',
92 | },
93 | },
94 | });
95 |
96 | const packageJson = JSON.parse(fileContent.content[0].text);
97 | console.log('✅ Package.json analysis:');
98 | console.log(`- Name: ${JSON.parse(packageJson).name}`);
99 | console.log(`- Version: ${JSON.parse(packageJson).version}`);
100 | console.log(`- Description: ${JSON.parse(packageJson).description}`);
101 | console.log();
102 |
103 | // Example 4: Code refactoring
104 | console.log('=== Example 4: Code Refactoring ===');
105 | const sampleCode = `
106 | var userName = "John Doe";
107 | var userEmail = "[email protected]";
108 | function getUserInfo() {
109 | return userName + " - " + userEmail;
110 | }
111 | `;
112 |
113 | const refactoredCode = await client.request({
114 | method: 'tools/call',
115 | params: {
116 | name: 'modernize_code',
117 | arguments: {
118 | code: sampleCode,
119 | language: 'javascript',
120 | targetVersion: 'ES2022',
121 | },
122 | },
123 | });
124 |
125 | console.log('✅ Code modernization:');
126 | console.log('Original:');
127 | console.log(sampleCode);
128 | console.log('Refactored:');
129 | console.log(JSON.parse(refactoredCode.content[0].text).refactoredCode);
130 | console.log();
131 |
132 | // Example 5: AI-powered chat (if OpenAI key is configured)
133 | console.log('=== Example 5: AI-Powered Repository Chat ===');
134 | try {
135 | const chatResponse = await client.request({
136 | method: 'tools/call',
137 | params: {
138 | name: 'chat_with_repository',
139 | arguments: {
140 | url: repoUrl,
141 | message: 'What are the main architectural patterns used in this React codebase?',
142 | },
143 | },
144 | });
145 |
146 | console.log('✅ AI Response:');
147 | console.log(chatResponse.content[0].text);
148 | } catch (error) {
149 | console.log('⚠️ AI features require OpenAI API key configuration');
150 | }
151 | console.log();
152 |
153 | // Example 6: Generate project template
154 | console.log('=== Example 6: Template Generation ===');
155 | const template = await client.request({
156 | method: 'tools/call',
157 | params: {
158 | name: 'generate_boilerplate',
159 | arguments: {
160 | url: repoUrl,
161 | templateType: 'starter',
162 | options: {
163 | name: 'my-react-app',
164 | framework: 'react',
165 | includeTests: true,
166 | includeDocs: true,
167 | },
168 | },
169 | },
170 | });
171 |
172 | const templateData = JSON.parse(template.content[0].text);
173 | console.log('✅ Generated template:');
174 | console.log(`- Name: ${templateData.name}`);
175 | console.log(`- Files: ${templateData.files.length}`);
176 | console.log(`- Dependencies: ${templateData.dependencies.length}`);
177 | console.log();
178 |
179 | console.log('🎉 All examples completed successfully!');
180 | console.log('💡 Try modifying the examples to explore different repositories and options.');
181 |
182 | } catch (error) {
183 | console.error('❌ Error:', error.message);
184 | console.error('💡 Make sure you have a valid GitHub token configured in your environment');
185 | } finally {
186 | await client.close();
187 | serverProcess.kill();
188 | }
189 | }
190 |
191 | // Handle errors and cleanup
192 | process.on('SIGINT', () => {
193 | console.log('\n👋 Goodbye!');
194 | process.exit(0);
195 | });
196 |
197 | process.on('unhandledRejection', (error) => {
198 | console.error('❌ Unhandled error:', error);
199 | process.exit(1);
200 | });
201 |
202 | // Run the example
203 | main().catch(console.error);
```
--------------------------------------------------------------------------------
/scripts/docker-run.sh:
--------------------------------------------------------------------------------
```bash
1 | #!/bin/bash
2 |
3 | # CodeCompass MCP Docker Run Script
4 | # Based on patterns from OpenRouter MCP repository
5 |
6 | set -e
7 |
8 | # Colors for output
9 | RED='\033[0;31m'
10 | GREEN='\033[0;32m'
11 | YELLOW='\033[1;33m'
12 | BLUE='\033[0;34m'
13 | NC='\033[0m' # No Color
14 |
15 | # Default values
16 | CONTAINER_NAME="codecompass-mcp"
17 | IMAGE_NAME="codecompass-mcp:latest"
18 | DETACH=true
19 | REMOVE_EXISTING=false
20 | INTERACTIVE=false
21 | PORT_MAPPING=""
22 | ENV_FILE=""
23 | MOUNT_VOLUMES=""
24 | NETWORK="bridge"
25 |
26 | # Function to display usage
27 | show_usage() {
28 | echo "Usage: $0 [OPTIONS]"
29 | echo "Options:"
30 | echo " -n, --name NAME Container name (default: codecompass-mcp)"
31 | echo " -i, --image IMAGE Image to run (default: codecompass-mcp:latest)"
32 | echo " -p, --port PORT Port mapping (e.g., 8080:8080)"
33 | echo " -e, --env KEY=VALUE Environment variable"
34 | echo " --env-file FILE Environment file"
35 | echo " -v, --volume SRC:DEST Volume mapping"
36 | echo " --network NETWORK Network to use (default: bridge)"
37 | echo " --interactive Run in interactive mode"
38 | echo " --foreground Run in foreground (not detached)"
39 | echo " --remove-existing Remove existing container if it exists"
40 | echo " -h, --help Show this help message"
41 | echo ""
42 | echo "Examples:"
43 | echo " $0 # Run with defaults"
44 | echo " $0 --interactive # Run interactively"
45 | echo " $0 --foreground --remove-existing # Run in foreground, remove existing"
46 | echo " $0 -e GITHUB_TOKEN=token -e OPENROUTER_API_KEY=key"
47 | echo " $0 --env-file .env # Use environment file"
48 | echo " $0 -v /host/data:/app/data # Mount volume"
49 | }
50 |
51 | # Parse command line arguments
52 | ENV_VARS=""
53 | while [[ $# -gt 0 ]]; do
54 | case $1 in
55 | -n|--name)
56 | CONTAINER_NAME="$2"
57 | shift 2
58 | ;;
59 | -i|--image)
60 | IMAGE_NAME="$2"
61 | shift 2
62 | ;;
63 | -p|--port)
64 | PORT_MAPPING="$PORT_MAPPING -p $2"
65 | shift 2
66 | ;;
67 | -e|--env)
68 | ENV_VARS="$ENV_VARS -e $2"
69 | shift 2
70 | ;;
71 | --env-file)
72 | ENV_FILE="$2"
73 | shift 2
74 | ;;
75 | -v|--volume)
76 | MOUNT_VOLUMES="$MOUNT_VOLUMES -v $2"
77 | shift 2
78 | ;;
79 | --network)
80 | NETWORK="$2"
81 | shift 2
82 | ;;
83 | --interactive)
84 | INTERACTIVE=true
85 | DETACH=false
86 | shift
87 | ;;
88 | --foreground)
89 | DETACH=false
90 | shift
91 | ;;
92 | --remove-existing)
93 | REMOVE_EXISTING=true
94 | shift
95 | ;;
96 | -h|--help)
97 | show_usage
98 | exit 0
99 | ;;
100 | *)
101 | echo "Unknown option: $1"
102 | show_usage
103 | exit 1
104 | ;;
105 | esac
106 | done
107 |
108 | echo -e "${BLUE}CodeCompass MCP Docker Run${NC}"
109 | echo -e "${BLUE}==========================${NC}"
110 | echo "Container: $CONTAINER_NAME"
111 | echo "Image: $IMAGE_NAME"
112 | echo "Network: $NETWORK"
113 | echo "Detached: $DETACH"
114 | echo "Interactive: $INTERACTIVE"
115 | echo ""
116 |
117 | # Check if image exists
118 | if ! docker images --format "table {{.Repository}}:{{.Tag}}" | grep -q "$IMAGE_NAME"; then
119 | echo -e "${RED}Error: Image '$IMAGE_NAME' not found${NC}"
120 | echo "Build the image first with: ./scripts/docker-build.sh"
121 | exit 1
122 | fi
123 |
124 | # Remove existing container if requested
125 | if [ "$REMOVE_EXISTING" = true ]; then
126 | if docker ps -a --format "table {{.Names}}" | grep -q "^$CONTAINER_NAME$"; then
127 | echo -e "${YELLOW}Removing existing container...${NC}"
128 | docker rm -f "$CONTAINER_NAME" 2>/dev/null || true
129 | fi
130 | fi
131 |
132 | # Check if container already exists
133 | if docker ps -a --format "table {{.Names}}" | grep -q "^$CONTAINER_NAME$"; then
134 | echo -e "${YELLOW}Container '$CONTAINER_NAME' already exists${NC}"
135 |
136 | # Check if it's running
137 | if docker ps --format "table {{.Names}}" | grep -q "^$CONTAINER_NAME$"; then
138 | echo -e "${GREEN}Container is already running${NC}"
139 | echo "Use 'docker logs $CONTAINER_NAME' to see logs"
140 | echo "Use 'docker exec -it $CONTAINER_NAME /bin/bash' to connect"
141 | exit 0
142 | else
143 | echo -e "${YELLOW}Starting existing container...${NC}"
144 | docker start "$CONTAINER_NAME"
145 | echo -e "${GREEN}✓ Container started${NC}"
146 | exit 0
147 | fi
148 | fi
149 |
150 | # Build docker run command
151 | DOCKER_CMD="docker run"
152 |
153 | if [ "$DETACH" = true ]; then
154 | DOCKER_CMD="$DOCKER_CMD -d"
155 | fi
156 |
157 | if [ "$INTERACTIVE" = true ]; then
158 | DOCKER_CMD="$DOCKER_CMD -it"
159 | fi
160 |
161 | DOCKER_CMD="$DOCKER_CMD --name $CONTAINER_NAME"
162 | DOCKER_CMD="$DOCKER_CMD --network $NETWORK"
163 |
164 | if [ -n "$PORT_MAPPING" ]; then
165 | DOCKER_CMD="$DOCKER_CMD $PORT_MAPPING"
166 | fi
167 |
168 | if [ -n "$ENV_VARS" ]; then
169 | DOCKER_CMD="$DOCKER_CMD $ENV_VARS"
170 | fi
171 |
172 | if [ -n "$ENV_FILE" ]; then
173 | if [ -f "$ENV_FILE" ]; then
174 | DOCKER_CMD="$DOCKER_CMD --env-file $ENV_FILE"
175 | else
176 | echo -e "${RED}Error: Environment file '$ENV_FILE' not found${NC}"
177 | exit 1
178 | fi
179 | fi
180 |
181 | if [ -n "$MOUNT_VOLUMES" ]; then
182 | DOCKER_CMD="$DOCKER_CMD $MOUNT_VOLUMES"
183 | fi
184 |
185 | DOCKER_CMD="$DOCKER_CMD $IMAGE_NAME"
186 |
187 | if [ "$INTERACTIVE" = true ]; then
188 | DOCKER_CMD="$DOCKER_CMD /bin/bash"
189 | fi
190 |
191 | echo -e "${YELLOW}Running container...${NC}"
192 | echo "Command: $DOCKER_CMD"
193 | echo ""
194 |
195 | # Execute the command
196 | eval $DOCKER_CMD
197 |
198 | if [ $? -eq 0 ]; then
199 | echo -e "${GREEN}✓ Container started successfully${NC}"
200 |
201 | if [ "$DETACH" = true ]; then
202 | echo ""
203 | echo "Container '$CONTAINER_NAME' is running in the background"
204 | echo ""
205 | echo "Useful commands:"
206 | echo " docker logs $CONTAINER_NAME # View logs"
207 | echo " docker logs -f $CONTAINER_NAME # Follow logs"
208 | echo " docker exec -it $CONTAINER_NAME /bin/bash # Connect to container"
209 | echo " docker stop $CONTAINER_NAME # Stop container"
210 | echo " docker rm $CONTAINER_NAME # Remove container"
211 | echo ""
212 | echo "Health check:"
213 | echo " docker exec $CONTAINER_NAME node -e \"console.log('Server is running')\""
214 | fi
215 | else
216 | echo -e "${RED}✗ Failed to start container${NC}"
217 | exit 1
218 | fi
```
--------------------------------------------------------------------------------
/src/types/responses.ts:
--------------------------------------------------------------------------------
```typescript
1 | /**
2 | * Standardized response types for CodeCompass MCP Server
3 | * Based on MCP protocol and best practices from real-world implementations
4 | */
5 |
6 | export interface ToolResponse<T = any> {
7 | success: boolean;
8 | data?: T;
9 | error?: {
10 | code: string;
11 | message: string;
12 | details?: any;
13 | suggestion?: string;
14 | timestamp?: string;
15 | context?: {
16 | tool?: string;
17 | url?: string;
18 | query?: string;
19 | };
20 | };
21 | metadata?: {
22 | processing_time: number;
23 | rate_limit_remaining?: number;
24 | cache_hit?: boolean;
25 | continuation_id?: string;
26 | };
27 | }
28 |
29 | export interface RepositoryData {
30 | info: {
31 | name: string;
32 | description: string | null;
33 | owner: string;
34 | stars: number;
35 | language: string | null;
36 | languages: Record<string, number>;
37 | license?: string;
38 | defaultBranch: string;
39 | createdAt: string;
40 | updatedAt: string;
41 | };
42 | structure: {
43 | fileCount: number;
44 | lineCount: number;
45 | fileTree: FileNode[];
46 | keyFiles: Record<string, string>;
47 | };
48 | dependencies: {
49 | external: DependencyInfo[];
50 | internal: Record<string, string[]>;
51 | security: SecurityIssue[];
52 | };
53 | }
54 |
55 | export interface FileNode {
56 | name: string;
57 | path: string;
58 | type: 'file' | 'directory';
59 | size?: number;
60 | children?: FileNode[];
61 | language?: string;
62 | complexity?: number;
63 | }
64 |
65 | export interface DependencyInfo {
66 | name: string;
67 | version: string;
68 | type: 'dependency' | 'devDependency' | 'peerDependency';
69 | source: string;
70 | security?: {
71 | vulnerabilities: number;
72 | risk: 'low' | 'medium' | 'high';
73 | };
74 | }
75 |
76 | export interface SecurityIssue {
77 | type: 'high' | 'medium' | 'low';
78 | description: string;
79 | file: string;
80 | line?: number;
81 | suggestion: string;
82 | }
83 |
84 | export interface CodeStructure {
85 | functions: FunctionInfo[];
86 | classes: ClassInfo[];
87 | imports: ImportInfo[];
88 | exports: ExportInfo[];
89 | complexity: {
90 | cyclomatic: number;
91 | cognitive: number;
92 | maintainability: number;
93 | };
94 | }
95 |
96 | export interface FunctionInfo {
97 | name: string;
98 | signature: string;
99 | startLine: number;
100 | endLine: number;
101 | complexity: number;
102 | parameters: ParameterInfo[];
103 | returnType?: string;
104 | documentation?: string;
105 | }
106 |
107 | export interface ClassInfo {
108 | name: string;
109 | methods: FunctionInfo[];
110 | properties: PropertyInfo[];
111 | extends?: string;
112 | implements?: string[];
113 | }
114 |
115 | export interface ImportInfo {
116 | source: string;
117 | imports: string[];
118 | type: 'import' | 'require' | 'dynamic';
119 | isExternal: boolean;
120 | }
121 |
122 | export interface ExportInfo {
123 | name: string;
124 | type: 'function' | 'class' | 'variable' | 'default';
125 | isDefault: boolean;
126 | }
127 |
128 | export interface ParameterInfo {
129 | name: string;
130 | type?: string;
131 | optional: boolean;
132 | defaultValue?: string;
133 | }
134 |
135 | export interface PropertyInfo {
136 | name: string;
137 | type?: string;
138 | visibility: 'public' | 'private' | 'protected';
139 | static: boolean;
140 | }
141 |
142 | export interface TransformedCode {
143 | originalCode: string;
144 | transformedCode: string;
145 | changes: CodeChange[];
146 | warnings: string[];
147 | instructions: string[];
148 | }
149 |
150 | export interface CodeChange {
151 | type: 'add' | 'remove' | 'modify' | 'move';
152 | file: string;
153 | line?: number;
154 | description: string;
155 | before?: string;
156 | after?: string;
157 | }
158 |
159 | export interface ExtractedComponent {
160 | name: string;
161 | type: 'component' | 'hook' | 'utility' | 'service' | 'type';
162 | path: string;
163 | code: string;
164 | dependencies: string[];
165 | reusabilityScore: number;
166 | complexity: number;
167 | documentation: string;
168 | examples: string[];
169 | }
170 |
171 | export interface ProjectTemplate {
172 | name: string;
173 | description: string;
174 | type: 'starter' | 'library' | 'microservice' | 'fullstack';
175 | files: TemplateFile[];
176 | dependencies: string[];
177 | devDependencies: string[];
178 | scripts: Record<string, string>;
179 | configuration: Record<string, any>;
180 | instructions: string[];
181 | }
182 |
183 | export interface TemplateFile {
184 | path: string;
185 | content: string;
186 | type: 'source' | 'config' | 'test' | 'docs';
187 | language?: string;
188 | executable?: boolean;
189 | }
190 |
191 | export interface ArchitectureAnalysis {
192 | patterns: DetectedPattern[];
193 | frameworks: string[];
194 | structure: ProjectStructure;
195 | entryPoints: string[];
196 | configFiles: string[];
197 | conventions: string[];
198 | }
199 |
200 | export interface DetectedPattern {
201 | name: string;
202 | confidence: number;
203 | files: string[];
204 | description: string;
205 | examples: string[];
206 | }
207 |
208 | export interface ProjectStructure {
209 | type: 'monorepo' | 'single-package' | 'multi-package';
210 | folders: Record<string, string>;
211 | conventions: string[];
212 | }
213 |
214 | export interface CodeMetrics {
215 | complexity: {
216 | cyclomatic: number;
217 | cognitive: number;
218 | maintainability: number;
219 | };
220 | quality: {
221 | score: number;
222 | issues: QualityIssue[];
223 | };
224 | size: {
225 | lines: number;
226 | files: number;
227 | functions: number;
228 | classes: number;
229 | };
230 | dependencies: {
231 | external: number;
232 | internal: number;
233 | circular: string[];
234 | };
235 | }
236 |
237 | export interface QualityIssue {
238 | type: 'complexity' | 'duplication' | 'maintainability' | 'security';
239 | severity: 'low' | 'medium' | 'high';
240 | description: string;
241 | file: string;
242 | line?: number;
243 | suggestion: string;
244 | }
245 |
246 | export interface SearchResult {
247 | query: string;
248 | results: SearchMatch[];
249 | totalMatches: number;
250 | filesSearched: number;
251 | searchTime: number;
252 | }
253 |
254 | export interface SearchMatch {
255 | file: string;
256 | line: number;
257 | content: string;
258 | context: string[];
259 | type: 'exact' | 'partial' | 'regex';
260 | }
261 |
262 | export interface BatchOperation {
263 | operations: BatchOperationItem[];
264 | results: BatchOperationResult[];
265 | totalTime: number;
266 | successCount: number;
267 | failureCount: number;
268 | }
269 |
270 | export interface BatchOperationItem {
271 | type: string;
272 | params: any;
273 | id: string;
274 | }
275 |
276 | export interface BatchOperationResult {
277 | id: string;
278 | success: boolean;
279 | data?: any;
280 | error?: string;
281 | processingTime: number;
282 | }
283 |
284 | // Error codes for consistent error handling
285 | export const ErrorCodes = {
286 | INVALID_INPUT: 'INVALID_INPUT',
287 | REPOSITORY_NOT_FOUND: 'REPOSITORY_NOT_FOUND',
288 | RATE_LIMIT_EXCEEDED: 'RATE_LIMIT_EXCEEDED',
289 | AUTHENTICATION_FAILED: 'AUTHENTICATION_FAILED',
290 | FILE_NOT_FOUND: 'FILE_NOT_FOUND',
291 | PARSE_ERROR: 'PARSE_ERROR',
292 | PROCESSING_ERROR: 'PROCESSING_ERROR',
293 | NETWORK_ERROR: 'NETWORK_ERROR',
294 | TIMEOUT: 'TIMEOUT',
295 | INTERNAL_ERROR: 'INTERNAL_ERROR',
296 | } as const;
297 |
298 | export type ErrorCode = typeof ErrorCodes[keyof typeof ErrorCodes];
```
--------------------------------------------------------------------------------
/src/utils/config.ts:
--------------------------------------------------------------------------------
```typescript
1 | import { z } from 'zod';
2 |
3 | // Configuration schema with validation
4 | const ConfigSchema = z.object({
5 | // GitHub Configuration
6 | github: z.object({
7 | token: z.string().optional(),
8 | apiUrl: z.string().default('https://api.github.com'),
9 | maxRetries: z.number().default(3),
10 | retryDelay: z.number().default(1000),
11 | rateLimitBuffer: z.number().default(10),
12 | }),
13 |
14 | // OpenRouter/AI Configuration
15 | openrouter: z.object({
16 | apiKey: z.string().optional(),
17 | apiUrl: z.string().default('https://openrouter.ai/api/v1'),
18 | defaultModel: z.string().default('anthropic/claude-3.5-sonnet'),
19 | maxRetries: z.number().default(3),
20 | timeout: z.number().default(30000),
21 | }),
22 |
23 | // Response Management
24 | response: z.object({
25 | maxTokens: z.number().default(25000),
26 | maxFileContentLength: z.number().default(1000),
27 | chunkSizes: z.object({
28 | small: z.object({
29 | tokens: z.number().default(10000),
30 | fileContent: z.number().default(500),
31 | filesPerChunk: z.number().default(10),
32 | }),
33 | medium: z.object({
34 | tokens: z.number().default(20000),
35 | fileContent: z.number().default(1000),
36 | filesPerChunk: z.number().default(20),
37 | }),
38 | large: z.object({
39 | tokens: z.number().default(40000),
40 | fileContent: z.number().default(2000),
41 | filesPerChunk: z.number().default(40),
42 | }),
43 | }),
44 | }),
45 |
46 | // Cache Configuration
47 | cache: z.object({
48 | enabled: z.boolean().default(true),
49 | ttl: z.number().default(300000), // 5 minutes
50 | maxSize: z.number().default(100),
51 | }),
52 |
53 | // Logging Configuration
54 | logging: z.object({
55 | level: z.enum(['debug', 'info', 'warn', 'error']).default('info'),
56 | enableTimestamps: z.boolean().default(true),
57 | enableColors: z.boolean().default(true),
58 | }),
59 |
60 | // Processing Limits
61 | limits: z.object({
62 | maxFiles: z.number().default(100),
63 | maxFileSize: z.number().default(1024 * 1024), // 1MB
64 | maxProcessingTime: z.number().default(60000), // 1 minute
65 | maxConcurrentRequests: z.number().default(5),
66 | }),
67 | });
68 |
69 | export type Config = z.infer<typeof ConfigSchema>;
70 |
71 | // Environment variable mappings
72 | const ENV_MAPPINGS = {
73 | 'GITHUB_TOKEN': 'github.token',
74 | 'GITHUB_API_URL': 'github.apiUrl',
75 | 'OPENROUTER_API_KEY': 'openrouter.apiKey',
76 | 'OPENROUTER_API_URL': 'openrouter.apiUrl',
77 | 'OPENAI_MODEL': 'openrouter.defaultModel',
78 | 'MAX_RESPONSE_TOKENS': 'response.maxTokens',
79 | 'MAX_FILE_CONTENT_LENGTH': 'response.maxFileContentLength',
80 | 'CACHE_ENABLED': 'cache.enabled',
81 | 'CACHE_TTL': 'cache.ttl',
82 | 'LOG_LEVEL': 'logging.level',
83 | 'MAX_FILES': 'limits.maxFiles',
84 | 'MAX_FILE_SIZE': 'limits.maxFileSize',
85 | 'MAX_PROCESSING_TIME': 'limits.maxProcessingTime',
86 | };
87 |
88 | // Helper to set nested object property
89 | function setNestedProperty(obj: any, path: string, value: any) {
90 | const keys = path.split('.');
91 | let current = obj;
92 |
93 | for (let i = 0; i < keys.length - 1; i++) {
94 | const key = keys[i];
95 | if (!(key in current)) {
96 | current[key] = {};
97 | }
98 | current = current[key];
99 | }
100 |
101 | const finalKey = keys[keys.length - 1];
102 | current[finalKey] = value;
103 | }
104 |
105 | // Helper to parse environment variable value
106 | function parseEnvValue(value: string): any {
107 | // Try to parse as number
108 | if (/^\d+$/.test(value)) {
109 | return parseInt(value, 10);
110 | }
111 |
112 | // Try to parse as boolean
113 | if (value.toLowerCase() === 'true') return true;
114 | if (value.toLowerCase() === 'false') return false;
115 |
116 | // Return as string
117 | return value;
118 | }
119 |
120 | // Load configuration from environment variables
121 | function loadConfigFromEnv(): Partial<Config> {
122 | const config: any = {};
123 |
124 | for (const [envKey, configPath] of Object.entries(ENV_MAPPINGS)) {
125 | const envValue = process.env[envKey];
126 | if (envValue) {
127 | setNestedProperty(config, configPath, parseEnvValue(envValue));
128 | }
129 | }
130 |
131 | return config;
132 | }
133 |
134 | // Create and validate configuration
135 | export function createConfig(): Config {
136 | const envConfig = loadConfigFromEnv();
137 |
138 | // Provide defaults for missing configuration sections
139 | const configWithDefaults = {
140 | github: {
141 | token: process.env.GITHUB_TOKEN || '',
142 | ...envConfig.github
143 | },
144 | openrouter: {
145 | apiKey: process.env.OPENROUTER_API_KEY || '',
146 | defaultModel: 'anthropic/claude-3.5-sonnet',
147 | ...envConfig.openrouter
148 | },
149 | response: {
150 | maxTokens: 25000,
151 | maxFileContentLength: 5000,
152 | chunkSizes: {
153 | small: { filesPerChunk: 5, fileContent: 1000 },
154 | medium: { filesPerChunk: 10, fileContent: 2000 },
155 | large: { filesPerChunk: 20, fileContent: 5000 }
156 | },
157 | ...envConfig.response
158 | },
159 | cache: {
160 | enabled: true,
161 | ttl: 3600,
162 | ...envConfig.cache
163 | },
164 | logging: {
165 | level: 'info',
166 | enableTimestamps: true,
167 | enableColors: true,
168 | ...envConfig.logging
169 | },
170 | limits: {
171 | maxFiles: 100,
172 | maxFileSize: 10 * 1024 * 1024, // 10MB
173 | maxProcessingTime: 30000, // 30 seconds
174 | maxConcurrentRequests: 10,
175 | ...envConfig.limits
176 | }
177 | };
178 |
179 | // Validate the configuration
180 | const config = ConfigSchema.parse(configWithDefaults);
181 |
182 | // Validate required fields for functionality
183 | const warnings: string[] = [];
184 |
185 | if (!config.github.token && !config.openrouter.apiKey) {
186 | warnings.push('Warning: Neither GITHUB_TOKEN nor OPENROUTER_API_KEY is set. Some features may be limited.');
187 | }
188 |
189 | if (warnings.length > 0) {
190 | console.warn(warnings.join('\n'));
191 | }
192 |
193 | return config;
194 | }
195 |
196 | // Global configuration instance
197 | let globalConfig: Config | null = null;
198 |
199 | export function getConfig(): Config {
200 | if (!globalConfig) {
201 | globalConfig = createConfig();
202 | }
203 | return globalConfig;
204 | }
205 |
206 | // Configuration validation helper
207 | export function validateConfig(config: Partial<Config>): boolean {
208 | try {
209 | ConfigSchema.parse(config);
210 | return true;
211 | } catch (error) {
212 | console.error('Configuration validation error:', error);
213 | return false;
214 | }
215 | }
216 |
217 | // Get model aliases for user-friendly names
218 | export function getModelAliases(): Record<string, string> {
219 | return {
220 | 'claude-3-sonnet': 'anthropic/claude-3.5-sonnet',
221 | 'claude-3-opus': 'anthropic/claude-3-opus',
222 | 'claude-3-haiku': 'anthropic/claude-3-haiku',
223 | 'gpt-4': 'openai/gpt-4',
224 | 'gpt-4-turbo': 'openai/gpt-4-turbo',
225 | 'gpt-4o': 'openai/gpt-4o',
226 | 'gpt-4o-mini': 'openai/gpt-4o-mini',
227 | 'gemini-pro': 'google/gemini-pro',
228 | 'gemini-1.5-pro': 'google/gemini-1.5-pro',
229 | };
230 | }
231 |
232 | // Resolve model alias to full model name
233 | export function resolveModelAlias(model: string): string {
234 | const aliases = getModelAliases();
235 | return aliases[model] || model;
236 | }
```
--------------------------------------------------------------------------------
/src/types/index.ts:
--------------------------------------------------------------------------------
```typescript
1 | export interface FileNode {
2 | name: string;
3 | path: string;
4 | type: 'file' | 'directory';
5 | children?: FileNode[];
6 | size?: number;
7 | sha?: string;
8 | }
9 |
10 | export interface GitHubRepoInfo {
11 | name: string;
12 | description: string | null;
13 | owner: string;
14 | stars: number;
15 | language: string | null;
16 | languages: Record<string, number>;
17 | fileCount: number;
18 | lineCount: number;
19 | fileTree: FileNode[];
20 | keyFiles: Record<string, string>;
21 | license?: string;
22 | defaultBranch: string;
23 | createdAt: string;
24 | updatedAt: string;
25 | }
26 |
27 | export interface DependencyInfo {
28 | name: string;
29 | version: string;
30 | type: 'dependency' | 'devDependency' | 'peerDependency';
31 | source: string; // package.json, requirements.txt, etc.
32 | }
33 |
34 | export interface RepositoryAnalysis {
35 | info: GitHubRepoInfo;
36 | dependencies: DependencyInfo[];
37 | architecture: ArchitectureAnalysis;
38 | codeQuality: CodeQualityMetrics;
39 | refactoringPotential: RefactoringPotential;
40 | }
41 |
42 | export interface ArchitectureAnalysis {
43 | patterns: string[];
44 | frameworks: string[];
45 | structure: ProjectStructure;
46 | entryPoints: string[];
47 | configFiles: string[];
48 | testFiles: string[];
49 | documentationFiles: string[];
50 | }
51 |
52 | export interface ProjectStructure {
53 | type: 'monorepo' | 'single-package' | 'multi-package';
54 | folders: {
55 | src?: string;
56 | tests?: string;
57 | docs?: string;
58 | config?: string;
59 | build?: string;
60 | public?: string;
61 | };
62 | }
63 |
64 | export interface CodeQualityMetrics {
65 | complexity: number;
66 | maintainability: number;
67 | testCoverage?: number;
68 | duplicateCode: number;
69 | codeSmells: string[];
70 | }
71 |
72 | export interface RefactoringPotential {
73 | extractableComponents: ExtractableComponent[];
74 | reusableUtilities: ReusableUtility[];
75 | configurationFiles: string[];
76 | boilerplateCode: string[];
77 | modernizationOpportunities: ModernizationOpportunity[];
78 | }
79 |
80 | export interface ExtractableComponent {
81 | name: string;
82 | path: string;
83 | type: 'component' | 'hook' | 'utility' | 'service' | 'model';
84 | dependencies: string[];
85 | complexity: number;
86 | reusabilityScore: number;
87 | description: string;
88 | }
89 |
90 | export interface ReusableUtility {
91 | name: string;
92 | path: string;
93 | functions: string[];
94 | description: string;
95 | dependencies: string[];
96 | }
97 |
98 | export interface ModernizationOpportunity {
99 | type: 'syntax' | 'dependency' | 'pattern' | 'performance';
100 | description: string;
101 | files: string[];
102 | suggestion: string;
103 | impact: 'low' | 'medium' | 'high';
104 | }
105 |
106 | export interface RefactorOptions {
107 | targetFramework?: string;
108 | targetLanguage?: string;
109 | namingConvention?: NamingConvention;
110 | modernizationLevel?: 'minimal' | 'moderate' | 'aggressive';
111 | removeProjectSpecific?: boolean;
112 | extractComponents?: boolean;
113 | optimizeForPerformance?: boolean;
114 | addTypeScript?: boolean;
115 | }
116 |
117 | export interface NamingConvention {
118 | variables: 'camelCase' | 'snake_case' | 'kebab-case' | 'PascalCase';
119 | functions: 'camelCase' | 'snake_case' | 'kebab-case' | 'PascalCase';
120 | classes: 'PascalCase' | 'camelCase' | 'snake_case';
121 | files: 'camelCase' | 'snake_case' | 'kebab-case' | 'PascalCase';
122 | folders: 'camelCase' | 'snake_case' | 'kebab-case' | 'PascalCase';
123 | }
124 |
125 | export interface RefactorResult {
126 | originalCode: string;
127 | refactoredCode: string;
128 | changes: RefactorChange[];
129 | warnings: string[];
130 | dependencies: string[];
131 | instructions: string[];
132 | }
133 |
134 | export interface RefactorChange {
135 | type: 'add' | 'remove' | 'modify' | 'move';
136 | file: string;
137 | line?: number;
138 | description: string;
139 | oldValue?: string;
140 | newValue?: string;
141 | }
142 |
143 | export interface TemplateOptions {
144 | name: string;
145 | description: string;
146 | framework?: string;
147 | language?: string;
148 | includeTests?: boolean;
149 | includeDocs?: boolean;
150 | includeConfig?: boolean;
151 | }
152 |
153 | export interface GeneratedTemplate {
154 | name: string;
155 | description: string;
156 | files: TemplateFile[];
157 | dependencies: string[];
158 | scripts: Record<string, string>;
159 | instructions: string[];
160 | }
161 |
162 | export interface TemplateFile {
163 | path: string;
164 | content: string;
165 | type: 'source' | 'config' | 'test' | 'documentation';
166 | language?: string;
167 | }
168 |
169 | export interface ComponentLibrary {
170 | name: string;
171 | description: string;
172 | components: LibraryComponent[];
173 | utilities: LibraryUtility[];
174 | types: LibraryType[];
175 | styles: LibraryStyle[];
176 | documentation: string;
177 | packageJson: any;
178 | }
179 |
180 | export interface LibraryComponent {
181 | name: string;
182 | path: string;
183 | props: ComponentProp[];
184 | examples: string[];
185 | documentation: string;
186 | dependencies: string[];
187 | }
188 |
189 | export interface ComponentProp {
190 | name: string;
191 | type: string;
192 | required: boolean;
193 | description: string;
194 | defaultValue?: string;
195 | }
196 |
197 | export interface LibraryUtility {
198 | name: string;
199 | path: string;
200 | functions: UtilityFunction[];
201 | documentation: string;
202 | }
203 |
204 | export interface UtilityFunction {
205 | name: string;
206 | parameters: FunctionParameter[];
207 | returnType: string;
208 | description: string;
209 | examples: string[];
210 | }
211 |
212 | export interface FunctionParameter {
213 | name: string;
214 | type: string;
215 | required: boolean;
216 | description: string;
217 | defaultValue?: string;
218 | }
219 |
220 | export interface LibraryType {
221 | name: string;
222 | definition: string;
223 | description: string;
224 | examples: string[];
225 | }
226 |
227 | export interface LibraryStyle {
228 | name: string;
229 | path: string;
230 | content: string;
231 | type: 'css' | 'scss' | 'styled-components' | 'tailwind';
232 | }
233 |
234 | export interface ChatContext {
235 | repositoryUrl: string;
236 | currentFile?: string;
237 | selectedCode?: string;
238 | conversationHistory: ChatMessage[];
239 | refactoringGoals?: string[];
240 | }
241 |
242 | export interface ChatMessage {
243 | role: 'user' | 'assistant' | 'system';
244 | content: string;
245 | timestamp: Date;
246 | }
247 |
248 | export interface RefactoringPlan {
249 | overview: string;
250 | phases: RefactoringPhase[];
251 | estimatedTimeHours: number;
252 | risks: string[];
253 | recommendations: string[];
254 | }
255 |
256 | export interface RefactoringPhase {
257 | name: string;
258 | description: string;
259 | tasks: RefactoringTask[];
260 | estimatedTimeHours: number;
261 | dependencies: string[];
262 | }
263 |
264 | export interface RefactoringTask {
265 | name: string;
266 | description: string;
267 | type: 'extract' | 'transform' | 'modernize' | 'optimize' | 'test';
268 | files: string[];
269 | estimatedTimeHours: number;
270 | priority: 'low' | 'medium' | 'high';
271 | }
272 |
273 | export interface ArchitectureExplanation {
274 | overview: string;
275 | patterns: PatternExplanation[];
276 | structure: StructureExplanation;
277 | dataFlow: DataFlowExplanation;
278 | dependencies: DependencyExplanation[];
279 | recommendations: string[];
280 | }
281 |
282 | export interface PatternExplanation {
283 | name: string;
284 | description: string;
285 | usage: string;
286 | files: string[];
287 | benefits: string[];
288 | drawbacks: string[];
289 | }
290 |
291 | export interface StructureExplanation {
292 | type: string;
293 | description: string;
294 | folders: FolderExplanation[];
295 | conventions: string[];
296 | }
297 |
298 | export interface FolderExplanation {
299 | name: string;
300 | purpose: string;
301 | files: string[];
302 | conventions: string[];
303 | }
304 |
305 | export interface DataFlowExplanation {
306 | overview: string;
307 | entryPoints: string[];
308 | dataStores: string[];
309 | apiEndpoints: string[];
310 | eventHandlers: string[];
311 | }
312 |
313 | export interface DependencyExplanation {
314 | name: string;
315 | version: string;
316 | purpose: string;
317 | usage: string;
318 | alternatives: string[];
319 | removalComplexity: 'low' | 'medium' | 'high';
320 | }
321 |
322 | export interface ValidationResult {
323 | isValid: boolean;
324 | errors: string[];
325 | warnings: string[];
326 | }
327 |
328 | export interface SecurityCheck {
329 | passed: boolean;
330 | issues: SecurityIssue[];
331 | recommendations: string[];
332 | }
333 |
334 | export interface SecurityIssue {
335 | type: 'high' | 'medium' | 'low';
336 | description: string;
337 | file: string;
338 | line?: number;
339 | suggestion: string;
340 | }
```
--------------------------------------------------------------------------------
/docs/MONITORING.md:
--------------------------------------------------------------------------------
```markdown
1 | # Monitoring and Logging Guide
2 |
3 | CodeCompass MCP includes comprehensive monitoring and logging capabilities inspired by enterprise-grade systems and OpenRouter MCP patterns.
4 |
5 | ## Overview
6 |
7 | The monitoring system provides:
8 | - **Real-time Metrics**: Request counts, response times, error rates, memory usage
9 | - **Performance Insights**: Slowest tools, error-prone operations, peak usage analysis
10 | - **Structured Logging**: JSON and console formats with contextual information
11 | - **Health Checks**: System status monitoring with configurable thresholds
12 | - **Interactive Dashboard**: Real-time command-line monitoring interface
13 |
14 | ## Quick Start
15 |
16 | ### View Current Status
17 |
18 | ```bash
19 | # Single health check
20 | npm run monitor
21 |
22 | # Interactive dashboard (refreshes every 5 seconds)
23 | npm run monitor -- --watch
24 |
25 | # Export metrics to JSON
26 | npm run monitor -- --export > metrics.json
27 | ```
28 |
29 | ### Using the Health Check Tool
30 |
31 | ```bash
32 | # Basic health check
33 | curl -X POST http://localhost:3000/health \
34 | -H "Content-Type: application/json" \
35 | -d '{"name": "health_check"}'
36 |
37 | # Comprehensive health check with insights
38 | curl -X POST http://localhost:3000/health \
39 | -H "Content-Type: application/json" \
40 | -d '{
41 | "name": "health_check",
42 | "arguments": {
43 | "checks": ["api-limits", "system-health", "monitoring", "configuration"],
44 | "options": {
45 | "include_metrics": true,
46 | "include_insights": true,
47 | "include_logs": true
48 | }
49 | }
50 | }'
51 | ```
52 |
53 | ## Monitoring Features
54 |
55 | ### 1. System Metrics
56 |
57 | The monitoring system tracks:
58 |
59 | - **Memory Usage**: Heap usage, RSS, external memory
60 | - **Request Metrics**: Total requests, error count, response times
61 | - **Tool Usage**: Per-tool statistics and performance
62 | - **Uptime**: Server uptime and availability
63 |
64 | ### 2. Performance Insights
65 |
66 | Automatic analysis provides:
67 |
68 | - **Slowest Tools**: Tools with highest average response times
69 | - **Error-Prone Operations**: Tools with highest error rates
70 | - **Peak Usage Hours**: Hourly request distribution
71 | - **Recommendations**: Actionable performance improvements
72 |
73 | ### 3. Health Status
74 |
75 | Multi-level health checks:
76 |
77 | - **Healthy**: All systems operating normally
78 | - **Degraded**: Some performance issues detected
79 | - **Unhealthy**: Critical issues requiring attention
80 |
81 | Health checks monitor:
82 | - Memory usage (threshold: 80%)
83 | - Error rate (threshold: 5%)
84 | - Recent errors (threshold: 5 per 5 minutes)
85 | - Average response time (threshold: 5 seconds)
86 |
87 | ## Logging System
88 |
89 | ### Log Levels
90 |
91 | - **DEBUG**: Detailed diagnostic information
92 | - **INFO**: General operational messages
93 | - **WARN**: Warning conditions
94 | - **ERROR**: Error conditions requiring attention
95 |
96 | ### Log Formats
97 |
98 | #### Console Format (Development)
99 | ```
100 | 2023-12-08T10:30:45.123Z INFO [req-123] Request started: fetch_repository_data
101 | 2023-12-08T10:30:46.456Z INFO [req-123] Request completed: fetch_repository_data (1333ms)
102 | ```
103 |
104 | #### JSON Format (Production)
105 | ```json
106 | {
107 | "timestamp": "2023-12-08T10:30:45.123Z",
108 | "level": "INFO",
109 | "message": "Request started: fetch_repository_data",
110 | "context": {
111 | "tool": "fetch_repository_data",
112 | "requestId": "req-123"
113 | },
114 | "requestId": "req-123"
115 | }
116 | ```
117 |
118 | ### Configuration
119 |
120 | Set log level via environment variable:
121 | ```bash
122 | export LOG_LEVEL=debug # debug, info, warn, error
123 | export NODE_ENV=production # Enables JSON logging
124 | ```
125 |
126 | ## Monitoring Dashboard
127 |
128 | The interactive dashboard provides real-time visibility into:
129 |
130 | ### System Overview
131 | - Uptime and memory usage
132 | - Request statistics and error rates
133 | - Response time percentiles
134 |
135 | ### Tool Performance
136 | - Usage statistics per tool
137 | - Average response times
138 | - Error rates by tool
139 |
140 | ### Recent Activity
141 | - Last 10 requests with status
142 | - Recent log entries
143 | - Error details
144 |
145 | ### Performance Insights
146 | - Slowest tools analysis
147 | - Error-prone operations
148 | - Peak usage patterns
149 | - Automated recommendations
150 |
151 | ## Using the Monitoring API
152 |
153 | ### Programmatic Access
154 |
155 | ```javascript
156 | import { monitoring } from './src/utils/monitoring.js';
157 |
158 | // Get current metrics
159 | const metrics = monitoring.getMetrics();
160 |
161 | // Get health status
162 | const health = monitoring.getHealthStatus();
163 |
164 | // Get performance insights
165 | const insights = monitoring.getPerformanceInsights();
166 |
167 | // Export all data
168 | const exportData = monitoring.exportMetrics();
169 | ```
170 |
171 | ### Request Tracking
172 |
173 | ```javascript
174 | // Manual request tracking
175 | const requestId = monitoring.generateRequestId();
176 | const startTime = Date.now();
177 |
178 | monitoring.startRequest('my_tool', requestId);
179 |
180 | try {
181 | // Your tool logic here
182 | const result = await myTool();
183 | monitoring.completeRequest('my_tool', startTime, true, undefined, requestId);
184 | return result;
185 | } catch (error) {
186 | monitoring.completeRequest('my_tool', startTime, false, error.message, requestId);
187 | throw error;
188 | }
189 | ```
190 |
191 | ### Tool Monitoring Wrapper
192 |
193 | ```javascript
194 | import { monitorTool } from './src/utils/monitoring.js';
195 |
196 | // Wrap any function with automatic monitoring
197 | const monitoredFunction = monitorTool('my_tool', async (param) => {
198 | // Your tool logic
199 | return result;
200 | });
201 | ```
202 |
203 | ## Performance Optimization
204 |
205 | ### Monitoring Overhead
206 |
207 | The monitoring system is designed for minimal overhead:
208 | - Metrics collection: ~0.1ms per request
209 | - Memory usage: ~1MB for 1000 requests
210 | - CPU impact: <1% under normal load
211 |
212 | ### Buffer Management
213 |
214 | - Request metrics: Limited to 1000 recent entries
215 | - Log buffer: Limited to 1000 recent entries
216 | - Automatic cleanup prevents memory leaks
217 |
218 | ## Docker Integration
219 |
220 | Monitoring works seamlessly with Docker:
221 |
222 | ```bash
223 | # View logs from container
224 | ./scripts/docker-logs.sh -f --timestamps
225 |
226 | # Monitor container health
227 | docker exec codecompass-mcp node scripts/monitor.js
228 |
229 | # Export metrics from container
230 | docker exec codecompass-mcp node scripts/monitor.js --export
231 | ```
232 |
233 | ## Production Deployment
234 |
235 | ### Environment Variables
236 |
237 | ```bash
238 | # Enable JSON logging
239 | NODE_ENV=production
240 |
241 | # Set log level
242 | LOG_LEVEL=info
243 |
244 | # Optional: Enable file logging
245 | LOG_FILE=/var/log/codecompass-mcp.log
246 | ```
247 |
248 | ### External Monitoring
249 |
250 | The monitoring system integrates with external systems:
251 |
252 | ```bash
253 | # Prometheus metrics endpoint (if implemented)
254 | curl http://localhost:3000/metrics
255 |
256 | # Health check endpoint
257 | curl http://localhost:3000/health
258 |
259 | # JSON metrics export
260 | curl http://localhost:3000/metrics.json
261 | ```
262 |
263 | ## Troubleshooting
264 |
265 | ### Common Issues
266 |
267 | 1. **High Memory Usage**
268 | - Check metrics buffer size
269 | - Review tool usage patterns
270 | - Consider request rate limiting
271 |
272 | 2. **Slow Response Times**
273 | - Analyze slowest tools
274 | - Implement caching where appropriate
275 | - Use chunking for large responses
276 |
277 | 3. **High Error Rates**
278 | - Review error logs
279 | - Check API rate limits
280 | - Verify configuration
281 |
282 | ### Debug Mode
283 |
284 | Enable debug logging for detailed troubleshooting:
285 |
286 | ```bash
287 | export LOG_LEVEL=debug
288 | npm run dev
289 | ```
290 |
291 | ## Best Practices
292 |
293 | ### 1. Regular Monitoring
294 |
295 | - Check dashboard during development
296 | - Monitor health checks in production
297 | - Set up alerts for critical thresholds
298 |
299 | ### 2. Performance Analysis
300 |
301 | - Review weekly performance reports
302 | - Identify trending issues
303 | - Optimize based on insights
304 |
305 | ### 3. Log Management
306 |
307 | - Rotate log files in production
308 | - Use structured logging for analysis
309 | - Set appropriate log levels
310 |
311 | ### 4. Capacity Planning
312 |
313 | - Monitor resource usage trends
314 | - Plan for peak usage periods
315 | - Scale based on metrics
316 |
317 | ## Integration Examples
318 |
319 | ### CI/CD Health Checks
320 |
321 | ```yaml
322 | # GitHub Actions example
323 | - name: Health Check
324 | run: |
325 | npm run monitor -- --export > metrics.json
326 | # Parse and validate metrics
327 | node scripts/validate-health.js
328 | ```
329 |
330 | ### Load Testing
331 |
332 | ```bash
333 | # Monitor during load testing
334 | npm run monitor -- --watch &
335 | # Run load tests
336 | npm run load-test
337 | ```
338 |
339 | ### Custom Dashboards
340 |
341 | The monitoring system can integrate with:
342 | - Grafana for visualization
343 | - Prometheus for metrics collection
344 | - ELK stack for log analysis
345 | - New Relic for APM
346 |
347 | ## API Reference
348 |
349 | ### Health Check Tool
350 |
351 | ```json
352 | {
353 | "name": "health_check",
354 | "arguments": {
355 | "checks": ["api-limits", "system-health", "monitoring", "configuration"],
356 | "options": {
357 | "include_metrics": true,
358 | "include_insights": true,
359 | "include_logs": true
360 | }
361 | }
362 | }
363 | ```
364 |
365 | ### Monitoring Scripts
366 |
367 | ```bash
368 | # Basic monitoring
369 | node scripts/monitor.js
370 |
371 | # Watch mode
372 | node scripts/monitor.js --watch
373 |
374 | # Export mode
375 | node scripts/monitor.js --export
376 |
377 | # Reset metrics
378 | node scripts/monitor.js --reset
379 | ```
380 |
381 | ## Support
382 |
383 | For monitoring-related issues:
384 | 1. Check the debug logs
385 | 2. Review the performance insights
386 | 3. Consult the troubleshooting guide
387 | 4. Report issues with metrics export
388 |
389 | The monitoring system is designed to be self-diagnosing and provides actionable insights for performance optimization and issue resolution.
```
--------------------------------------------------------------------------------
/src/utils/logger.ts:
--------------------------------------------------------------------------------
```typescript
1 | import { getConfig } from './config.js';
2 |
3 | // Log levels
4 | export enum LogLevel {
5 | DEBUG = 0,
6 | INFO = 1,
7 | WARN = 2,
8 | ERROR = 3,
9 | }
10 |
11 | // Log entry interface
12 | export interface LogEntry {
13 | timestamp: string;
14 | level: LogLevel;
15 | message: string;
16 | context?: Record<string, any>;
17 | error?: Error;
18 | duration?: number;
19 | requestId?: string;
20 | }
21 |
22 | // Logger configuration
23 | interface LoggerConfig {
24 | level: LogLevel;
25 | enableTimestamps: boolean;
26 | enableColors: boolean;
27 | enableJson: boolean;
28 | enableFile: boolean;
29 | logFile?: string;
30 | }
31 |
32 | // Color codes for console output
33 | const COLORS = {
34 | reset: '\x1b[0m',
35 | bright: '\x1b[1m',
36 | dim: '\x1b[2m',
37 | red: '\x1b[31m',
38 | green: '\x1b[32m',
39 | yellow: '\x1b[33m',
40 | blue: '\x1b[34m',
41 | magenta: '\x1b[35m',
42 | cyan: '\x1b[36m',
43 | white: '\x1b[37m',
44 | gray: '\x1b[90m',
45 | };
46 |
47 | // Log level colors
48 | const LEVEL_COLORS = {
49 | [LogLevel.DEBUG]: COLORS.gray,
50 | [LogLevel.INFO]: COLORS.blue,
51 | [LogLevel.WARN]: COLORS.yellow,
52 | [LogLevel.ERROR]: COLORS.red,
53 | };
54 |
55 | // Log level names
56 | const LEVEL_NAMES = {
57 | [LogLevel.DEBUG]: 'DEBUG',
58 | [LogLevel.INFO]: 'INFO',
59 | [LogLevel.WARN]: 'WARN',
60 | [LogLevel.ERROR]: 'ERROR',
61 | };
62 |
63 | class Logger {
64 | private config: LoggerConfig;
65 | private logBuffer: LogEntry[] = [];
66 | private requestCounter = 0;
67 |
68 | constructor() {
69 | const appConfig = getConfig();
70 | this.config = {
71 | level: this.parseLogLevel(appConfig.logging.level),
72 | enableTimestamps: appConfig.logging.enableTimestamps,
73 | enableColors: appConfig.logging.enableColors,
74 | enableJson: process.env.NODE_ENV === 'production',
75 | enableFile: process.env.LOG_FILE !== undefined,
76 | logFile: process.env.LOG_FILE,
77 | };
78 | }
79 |
80 | private parseLogLevel(level: string): LogLevel {
81 | switch (level.toLowerCase()) {
82 | case 'debug': return LogLevel.DEBUG;
83 | case 'info': return LogLevel.INFO;
84 | case 'warn': return LogLevel.WARN;
85 | case 'error': return LogLevel.ERROR;
86 | default: return LogLevel.INFO;
87 | }
88 | }
89 |
90 | private shouldLog(level: LogLevel): boolean {
91 | return level >= this.config.level;
92 | }
93 |
94 | private formatTimestamp(): string {
95 | return new Date().toISOString();
96 | }
97 |
98 | private formatConsoleMessage(entry: LogEntry): string {
99 | let message = '';
100 |
101 | if (this.config.enableColors) {
102 | const color = LEVEL_COLORS[entry.level];
103 | const levelName = LEVEL_NAMES[entry.level].padEnd(5);
104 |
105 | if (this.config.enableTimestamps) {
106 | message += `${COLORS.gray}${entry.timestamp}${COLORS.reset} `;
107 | }
108 |
109 | message += `${color}${levelName}${COLORS.reset} `;
110 |
111 | if (entry.requestId) {
112 | message += `${COLORS.cyan}[${entry.requestId}]${COLORS.reset} `;
113 | }
114 |
115 | message += entry.message;
116 |
117 | if (entry.duration !== undefined) {
118 | message += ` ${COLORS.gray}(${entry.duration}ms)${COLORS.reset}`;
119 | }
120 |
121 | if (entry.context && Object.keys(entry.context).length > 0) {
122 | message += `\n${COLORS.dim}${JSON.stringify(entry.context, null, 2)}${COLORS.reset}`;
123 | }
124 |
125 | if (entry.error) {
126 | message += `\n${COLORS.red}${entry.error.stack || entry.error.message}${COLORS.reset}`;
127 | }
128 | } else {
129 | const levelName = LEVEL_NAMES[entry.level].padEnd(5);
130 |
131 | if (this.config.enableTimestamps) {
132 | message += `${entry.timestamp} `;
133 | }
134 |
135 | message += `${levelName} `;
136 |
137 | if (entry.requestId) {
138 | message += `[${entry.requestId}] `;
139 | }
140 |
141 | message += entry.message;
142 |
143 | if (entry.duration !== undefined) {
144 | message += ` (${entry.duration}ms)`;
145 | }
146 |
147 | if (entry.context && Object.keys(entry.context).length > 0) {
148 | message += `\n${JSON.stringify(entry.context, null, 2)}`;
149 | }
150 |
151 | if (entry.error) {
152 | message += `\n${entry.error.stack || entry.error.message}`;
153 | }
154 | }
155 |
156 | return message;
157 | }
158 |
159 | private formatJsonMessage(entry: LogEntry): string {
160 | return JSON.stringify({
161 | timestamp: entry.timestamp,
162 | level: LEVEL_NAMES[entry.level],
163 | message: entry.message,
164 | context: entry.context,
165 | error: entry.error ? {
166 | message: entry.error.message,
167 | stack: entry.error.stack,
168 | name: entry.error.name,
169 | } : undefined,
170 | duration: entry.duration,
171 | requestId: entry.requestId,
172 | });
173 | }
174 |
175 | private writeLog(entry: LogEntry): void {
176 | if (!this.shouldLog(entry.level)) {
177 | return;
178 | }
179 |
180 | // Add to buffer for monitoring
181 | this.logBuffer.push(entry);
182 | if (this.logBuffer.length > 1000) {
183 | this.logBuffer.shift();
184 | }
185 |
186 | // Console output
187 | if (this.config.enableJson) {
188 | console.log(this.formatJsonMessage(entry));
189 | } else {
190 | console.log(this.formatConsoleMessage(entry));
191 | }
192 |
193 | // File output (if enabled)
194 | if (this.config.enableFile && this.config.logFile) {
195 | // In a real implementation, you'd write to file here
196 | // For now, we'll just use console
197 | }
198 | }
199 |
200 | public generateRequestId(): string {
201 | return `req-${Date.now()}-${++this.requestCounter}`;
202 | }
203 |
204 | public debug(message: string, context?: Record<string, any>, requestId?: string): void {
205 | this.writeLog({
206 | timestamp: this.formatTimestamp(),
207 | level: LogLevel.DEBUG,
208 | message,
209 | context,
210 | requestId,
211 | });
212 | }
213 |
214 | public info(message: string, context?: Record<string, any>, requestId?: string): void {
215 | this.writeLog({
216 | timestamp: this.formatTimestamp(),
217 | level: LogLevel.INFO,
218 | message,
219 | context,
220 | requestId,
221 | });
222 | }
223 |
224 | public warn(message: string, context?: Record<string, any>, requestId?: string): void {
225 | this.writeLog({
226 | timestamp: this.formatTimestamp(),
227 | level: LogLevel.WARN,
228 | message,
229 | context,
230 | requestId,
231 | });
232 | }
233 |
234 | public error(message: string, error?: Error, context?: Record<string, any>, requestId?: string): void {
235 | this.writeLog({
236 | timestamp: this.formatTimestamp(),
237 | level: LogLevel.ERROR,
238 | message,
239 | error,
240 | context,
241 | requestId,
242 | });
243 | }
244 |
245 | public timing(message: string, startTime: number, context?: Record<string, any>, requestId?: string): void {
246 | const duration = Date.now() - startTime;
247 | this.writeLog({
248 | timestamp: this.formatTimestamp(),
249 | level: LogLevel.INFO,
250 | message,
251 | context,
252 | duration,
253 | requestId,
254 | });
255 | }
256 |
257 | public getLogBuffer(): LogEntry[] {
258 | return [...this.logBuffer];
259 | }
260 |
261 | public getStats(): {
262 | totalLogs: number;
263 | errorCount: number;
264 | warnCount: number;
265 | averageResponseTime: number;
266 | } {
267 | const totalLogs = this.logBuffer.length;
268 | const errorCount = this.logBuffer.filter(entry => entry.level === LogLevel.ERROR).length;
269 | const warnCount = this.logBuffer.filter(entry => entry.level === LogLevel.WARN).length;
270 |
271 | const timingEntries = this.logBuffer.filter(entry => entry.duration !== undefined);
272 | const averageResponseTime = timingEntries.length > 0
273 | ? timingEntries.reduce((sum, entry) => sum + (entry.duration || 0), 0) / timingEntries.length
274 | : 0;
275 |
276 | return {
277 | totalLogs,
278 | errorCount,
279 | warnCount,
280 | averageResponseTime,
281 | };
282 | }
283 | }
284 |
285 | // Global logger instance
286 | const logger = new Logger();
287 |
288 | // Helper functions for structured logging
289 | export const log = {
290 | debug: (message: string, context?: Record<string, any>, requestId?: string) =>
291 | logger.debug(message, context, requestId),
292 |
293 | info: (message: string, context?: Record<string, any>, requestId?: string) =>
294 | logger.info(message, context, requestId),
295 |
296 | warn: (message: string, context?: Record<string, any>, requestId?: string) =>
297 | logger.warn(message, context, requestId),
298 |
299 | error: (message: string, error?: Error, context?: Record<string, any>, requestId?: string) =>
300 | logger.error(message, error, context, requestId),
301 |
302 | timing: (message: string, startTime: number, context?: Record<string, any>, requestId?: string) =>
303 | logger.timing(message, startTime, context, requestId),
304 |
305 | generateRequestId: () => logger.generateRequestId(),
306 |
307 | getStats: () => logger.getStats(),
308 |
309 | getLogBuffer: () => logger.getLogBuffer(),
310 | };
311 |
312 | // Performance monitoring helpers
313 | export function createPerformanceTimer(name: string, requestId?: string) {
314 | const startTime = Date.now();
315 |
316 | return {
317 | end: (context?: Record<string, any>) => {
318 | log.timing(`${name} completed`, startTime, context, requestId);
319 | },
320 |
321 | checkpoint: (checkpointName: string, context?: Record<string, any>) => {
322 | log.timing(`${name} - ${checkpointName}`, startTime, context, requestId);
323 | },
324 | };
325 | }
326 |
327 | // Export the logger instance
328 | export { logger };
329 | export default log;
```
--------------------------------------------------------------------------------
/docs/legacy-tools/transform.ts:
--------------------------------------------------------------------------------
```typescript
1 | import { Tool } from '@modelcontextprotocol/sdk/types.js';
2 |
3 | export const transformTools: Tool[] = [
4 | {
5 | name: 'convert_framework',
6 | description: 'Convert code between different frameworks (e.g., React to Vue, Express to Fastify)',
7 | inputSchema: {
8 | type: 'object',
9 | properties: {
10 | code: {
11 | type: 'string',
12 | description: 'Source code to convert',
13 | },
14 | sourceFramework: {
15 | type: 'string',
16 | description: 'Source framework (e.g., "react", "vue", "angular", "express")',
17 | },
18 | targetFramework: {
19 | type: 'string',
20 | description: 'Target framework',
21 | },
22 | conversionOptions: {
23 | type: 'object',
24 | properties: {
25 | preserveStructure: {
26 | type: 'boolean',
27 | description: 'Preserve original code structure as much as possible',
28 | default: true,
29 | },
30 | includeComments: {
31 | type: 'boolean',
32 | description: 'Include explanatory comments in converted code',
33 | default: true,
34 | },
35 | convertStyles: {
36 | type: 'boolean',
37 | description: 'Convert styling approach if applicable',
38 | default: true,
39 | },
40 | convertTests: {
41 | type: 'boolean',
42 | description: 'Convert test files if present',
43 | default: true,
44 | },
45 | },
46 | },
47 | },
48 | required: ['code', 'sourceFramework', 'targetFramework'],
49 | },
50 | },
51 | {
52 | name: 'update_api_patterns',
53 | description: 'Update API patterns and endpoints to modern conventions',
54 | inputSchema: {
55 | type: 'object',
56 | properties: {
57 | code: {
58 | type: 'string',
59 | description: 'Source code containing API patterns',
60 | },
61 | currentPattern: {
62 | type: 'string',
63 | enum: ['rest', 'graphql', 'rpc', 'websocket'],
64 | description: 'Current API pattern',
65 | },
66 | targetPattern: {
67 | type: 'string',
68 | enum: ['rest', 'graphql', 'rpc', 'websocket'],
69 | description: 'Target API pattern',
70 | },
71 | updateOptions: {
72 | type: 'object',
73 | properties: {
74 | addValidation: {
75 | type: 'boolean',
76 | description: 'Add input validation',
77 | default: true,
78 | },
79 | addErrorHandling: {
80 | type: 'boolean',
81 | description: 'Add comprehensive error handling',
82 | default: true,
83 | },
84 | addDocumentation: {
85 | type: 'boolean',
86 | description: 'Add API documentation',
87 | default: true,
88 | },
89 | addSecurity: {
90 | type: 'boolean',
91 | description: 'Add security middleware',
92 | default: true,
93 | },
94 | },
95 | },
96 | },
97 | required: ['code', 'currentPattern', 'targetPattern'],
98 | },
99 | },
100 | {
101 | name: 'extract_business_logic',
102 | description: 'Extract business logic from framework-specific code',
103 | inputSchema: {
104 | type: 'object',
105 | properties: {
106 | code: {
107 | type: 'string',
108 | description: 'Source code containing business logic',
109 | },
110 | framework: {
111 | type: 'string',
112 | description: 'Framework to extract from',
113 | },
114 | extractionOptions: {
115 | type: 'object',
116 | properties: {
117 | createInterfaces: {
118 | type: 'boolean',
119 | description: 'Create interfaces for extracted logic',
120 | default: true,
121 | },
122 | addTypes: {
123 | type: 'boolean',
124 | description: 'Add TypeScript types',
125 | default: true,
126 | },
127 | createTests: {
128 | type: 'boolean',
129 | description: 'Create unit tests for extracted logic',
130 | default: false,
131 | },
132 | separateUtilities: {
133 | type: 'boolean',
134 | description: 'Separate utility functions',
135 | default: true,
136 | },
137 | },
138 | },
139 | },
140 | required: ['code', 'framework'],
141 | },
142 | },
143 | {
144 | name: 'migrate_database_layer',
145 | description: 'Migrate database layer between different ORMs or query builders',
146 | inputSchema: {
147 | type: 'object',
148 | properties: {
149 | code: {
150 | type: 'string',
151 | description: 'Database layer code to migrate',
152 | },
153 | sourceORM: {
154 | type: 'string',
155 | description: 'Source ORM (e.g., "sequelize", "typeorm", "prisma")',
156 | },
157 | targetORM: {
158 | type: 'string',
159 | description: 'Target ORM',
160 | },
161 | migrationOptions: {
162 | type: 'object',
163 | properties: {
164 | preserveRelations: {
165 | type: 'boolean',
166 | description: 'Preserve database relations',
167 | default: true,
168 | },
169 | convertValidation: {
170 | type: 'boolean',
171 | description: 'Convert validation rules',
172 | default: true,
173 | },
174 | generateMigrations: {
175 | type: 'boolean',
176 | description: 'Generate migration files',
177 | default: true,
178 | },
179 | convertSeeds: {
180 | type: 'boolean',
181 | description: 'Convert seed files',
182 | default: true,
183 | },
184 | },
185 | },
186 | },
187 | required: ['code', 'sourceORM', 'targetORM'],
188 | },
189 | },
190 | {
191 | name: 'update_build_system',
192 | description: 'Update build system configuration (webpack, vite, rollup, etc.)',
193 | inputSchema: {
194 | type: 'object',
195 | properties: {
196 | configCode: {
197 | type: 'string',
198 | description: 'Build system configuration code',
199 | },
200 | sourceTool: {
201 | type: 'string',
202 | description: 'Source build tool (e.g., "webpack", "vite", "rollup")',
203 | },
204 | targetTool: {
205 | type: 'string',
206 | description: 'Target build tool',
207 | },
208 | projectType: {
209 | type: 'string',
210 | enum: ['library', 'application', 'monorepo'],
211 | description: 'Type of project',
212 | },
213 | features: {
214 | type: 'array',
215 | items: { type: 'string' },
216 | description: 'Features to preserve/add (e.g., ["typescript", "hot-reload", "tree-shaking"])',
217 | },
218 | },
219 | required: ['configCode', 'sourceTool', 'targetTool'],
220 | },
221 | },
222 | {
223 | name: 'convert_testing_framework',
224 | description: 'Convert tests between different testing frameworks',
225 | inputSchema: {
226 | type: 'object',
227 | properties: {
228 | testCode: {
229 | type: 'string',
230 | description: 'Test code to convert',
231 | },
232 | sourceFramework: {
233 | type: 'string',
234 | description: 'Source testing framework (e.g., "jest", "mocha", "vitest")',
235 | },
236 | targetFramework: {
237 | type: 'string',
238 | description: 'Target testing framework',
239 | },
240 | conversionOptions: {
241 | type: 'object',
242 | properties: {
243 | preserveStructure: {
244 | type: 'boolean',
245 | description: 'Preserve test structure',
246 | default: true,
247 | },
248 | convertMocks: {
249 | type: 'boolean',
250 | description: 'Convert mocking syntax',
251 | default: true,
252 | },
253 | convertAssertions: {
254 | type: 'boolean',
255 | description: 'Convert assertion syntax',
256 | default: true,
257 | },
258 | addSetupTeardown: {
259 | type: 'boolean',
260 | description: 'Add setup/teardown hooks',
261 | default: true,
262 | },
263 | },
264 | },
265 | },
266 | required: ['testCode', 'sourceFramework', 'targetFramework'],
267 | },
268 | },
269 | {
270 | name: 'modernize_syntax',
271 | description: 'Modernize language syntax to use latest features',
272 | inputSchema: {
273 | type: 'object',
274 | properties: {
275 | code: {
276 | type: 'string',
277 | description: 'Source code to modernize',
278 | },
279 | language: {
280 | type: 'string',
281 | description: 'Programming language',
282 | },
283 | sourceVersion: {
284 | type: 'string',
285 | description: 'Source language version',
286 | },
287 | targetVersion: {
288 | type: 'string',
289 | description: 'Target language version',
290 | },
291 | transformations: {
292 | type: 'array',
293 | items: { type: 'string' },
294 | description: 'Specific transformations to apply',
295 | },
296 | preserveCompatibility: {
297 | type: 'boolean',
298 | description: 'Preserve backward compatibility where possible',
299 | default: false,
300 | },
301 | },
302 | required: ['code', 'language', 'targetVersion'],
303 | },
304 | },
305 | ];
```
--------------------------------------------------------------------------------
/docs/legacy-tools/refactor.ts:
--------------------------------------------------------------------------------
```typescript
1 | import { Tool } from '@modelcontextprotocol/sdk/types.js';
2 |
3 | export const refactorTools: Tool[] = [
4 | {
5 | name: 'refactor_for_project',
6 | description: 'Refactor code from a repository to fit a specific target project structure and conventions',
7 | inputSchema: {
8 | type: 'object',
9 | properties: {
10 | url: {
11 | type: 'string',
12 | description: 'GitHub repository URL',
13 | },
14 | targetProject: {
15 | type: 'object',
16 | properties: {
17 | framework: {
18 | type: 'string',
19 | description: 'Target framework (e.g., "react", "vue", "angular")',
20 | },
21 | language: {
22 | type: 'string',
23 | description: 'Target language (e.g., "typescript", "javascript")',
24 | },
25 | structure: {
26 | type: 'object',
27 | description: 'Target project structure and conventions',
28 | },
29 | },
30 | required: ['framework'],
31 | },
32 | refactorOptions: {
33 | type: 'object',
34 | properties: {
35 | namingConvention: {
36 | type: 'string',
37 | enum: ['camelCase', 'snake_case', 'kebab-case', 'PascalCase'],
38 | description: 'Naming convention to apply',
39 | },
40 | modernizationLevel: {
41 | type: 'string',
42 | enum: ['minimal', 'moderate', 'aggressive'],
43 | description: 'Level of modernization to apply',
44 | default: 'moderate',
45 | },
46 | removeProjectSpecific: {
47 | type: 'boolean',
48 | description: 'Remove project-specific code and dependencies',
49 | default: true,
50 | },
51 | extractComponents: {
52 | type: 'boolean',
53 | description: 'Extract reusable components',
54 | default: true,
55 | },
56 | addTypeScript: {
57 | type: 'boolean',
58 | description: 'Convert to TypeScript if applicable',
59 | default: false,
60 | },
61 | },
62 | },
63 | filesToRefactor: {
64 | type: 'array',
65 | items: { type: 'string' },
66 | description: 'Specific files to refactor (optional - refactors all if not specified)',
67 | },
68 | },
69 | required: ['url', 'targetProject'],
70 | },
71 | },
72 | {
73 | name: 'extract_reusable_components',
74 | description: 'Identify and extract reusable components from a repository',
75 | inputSchema: {
76 | type: 'object',
77 | properties: {
78 | url: {
79 | type: 'string',
80 | description: 'GitHub repository URL',
81 | },
82 | componentTypes: {
83 | type: 'array',
84 | items: {
85 | type: 'string',
86 | enum: ['ui-components', 'hooks', 'utilities', 'services', 'models', 'types'],
87 | },
88 | description: 'Types of components to extract',
89 | },
90 | minReusabilityScore: {
91 | type: 'number',
92 | description: 'Minimum reusability score (0-100)',
93 | default: 60,
94 | },
95 | includeDependencies: {
96 | type: 'boolean',
97 | description: 'Include component dependencies',
98 | default: true,
99 | },
100 | },
101 | required: ['url'],
102 | },
103 | },
104 | {
105 | name: 'adapt_dependencies',
106 | description: 'Adapt import paths and dependencies to match target project structure',
107 | inputSchema: {
108 | type: 'object',
109 | properties: {
110 | code: {
111 | type: 'string',
112 | description: 'Source code to adapt',
113 | },
114 | dependencyMappings: {
115 | type: 'object',
116 | description: 'Mapping of old dependencies to new ones',
117 | },
118 | targetStructure: {
119 | type: 'object',
120 | properties: {
121 | srcPath: {
122 | type: 'string',
123 | description: 'Path to source directory',
124 | },
125 | aliasMapping: {
126 | type: 'object',
127 | description: 'Path alias mappings',
128 | },
129 | },
130 | },
131 | language: {
132 | type: 'string',
133 | description: 'Programming language',
134 | },
135 | },
136 | required: ['code'],
137 | },
138 | },
139 | {
140 | name: 'transform_naming_conventions',
141 | description: 'Transform code to use different naming conventions',
142 | inputSchema: {
143 | type: 'object',
144 | properties: {
145 | code: {
146 | type: 'string',
147 | description: 'Source code to transform',
148 | },
149 | fromConvention: {
150 | type: 'string',
151 | enum: ['camelCase', 'snake_case', 'kebab-case', 'PascalCase'],
152 | description: 'Source naming convention',
153 | },
154 | toConvention: {
155 | type: 'string',
156 | enum: ['camelCase', 'snake_case', 'kebab-case', 'PascalCase'],
157 | description: 'Target naming convention',
158 | },
159 | scope: {
160 | type: 'array',
161 | items: {
162 | type: 'string',
163 | enum: ['variables', 'functions', 'classes', 'files', 'folders'],
164 | },
165 | description: 'Scope of transformation',
166 | default: ['variables', 'functions'],
167 | },
168 | preserveConstants: {
169 | type: 'boolean',
170 | description: 'Preserve constant naming (UPPER_CASE)',
171 | default: true,
172 | },
173 | },
174 | required: ['code', 'fromConvention', 'toConvention'],
175 | },
176 | },
177 | {
178 | name: 'modernize_code',
179 | description: 'Modernize code to use latest language features and patterns',
180 | inputSchema: {
181 | type: 'object',
182 | properties: {
183 | code: {
184 | type: 'string',
185 | description: 'Source code to modernize',
186 | },
187 | language: {
188 | type: 'string',
189 | description: 'Programming language',
190 | },
191 | targetVersion: {
192 | type: 'string',
193 | description: 'Target language version (e.g., "ES2022", "Python 3.10")',
194 | },
195 | transformations: {
196 | type: 'array',
197 | items: { type: 'string' },
198 | description: 'Specific transformations to apply',
199 | },
200 | preserveCompatibility: {
201 | type: 'boolean',
202 | description: 'Preserve backward compatibility',
203 | default: false,
204 | },
205 | },
206 | required: ['code', 'language'],
207 | },
208 | },
209 | {
210 | name: 'remove_project_coupling',
211 | description: 'Remove project-specific coupling and make code more generic',
212 | inputSchema: {
213 | type: 'object',
214 | properties: {
215 | code: {
216 | type: 'string',
217 | description: 'Source code to decouple',
218 | },
219 | language: {
220 | type: 'string',
221 | description: 'Programming language',
222 | },
223 | couplingTypes: {
224 | type: 'array',
225 | items: {
226 | type: 'string',
227 | enum: ['hard-coded-values', 'specific-apis', 'tight-dependencies', 'environment-specific'],
228 | },
229 | description: 'Types of coupling to remove',
230 | },
231 | replacementStrategy: {
232 | type: 'string',
233 | enum: ['parameters', 'config', 'interfaces', 'injection'],
234 | description: 'Strategy for replacing coupled code',
235 | default: 'parameters',
236 | },
237 | },
238 | required: ['code', 'language'],
239 | },
240 | },
241 | {
242 | name: 'optimize_performance',
243 | description: 'Apply performance optimizations to code',
244 | inputSchema: {
245 | type: 'object',
246 | properties: {
247 | code: {
248 | type: 'string',
249 | description: 'Source code to optimize',
250 | },
251 | language: {
252 | type: 'string',
253 | description: 'Programming language',
254 | },
255 | optimizationTypes: {
256 | type: 'array',
257 | items: {
258 | type: 'string',
259 | enum: ['memory', 'cpu', 'io', 'network', 'rendering'],
260 | },
261 | description: 'Types of optimizations to apply',
262 | },
263 | targetEnvironment: {
264 | type: 'string',
265 | enum: ['browser', 'node', 'mobile', 'server'],
266 | description: 'Target runtime environment',
267 | },
268 | preserveReadability: {
269 | type: 'boolean',
270 | description: 'Preserve code readability',
271 | default: true,
272 | },
273 | },
274 | required: ['code', 'language'],
275 | },
276 | },
277 | {
278 | name: 'add_error_handling',
279 | description: 'Add comprehensive error handling to code',
280 | inputSchema: {
281 | type: 'object',
282 | properties: {
283 | code: {
284 | type: 'string',
285 | description: 'Source code to enhance',
286 | },
287 | language: {
288 | type: 'string',
289 | description: 'Programming language',
290 | },
291 | errorHandlingStyle: {
292 | type: 'string',
293 | enum: ['try-catch', 'promises', 'result-type', 'exceptions'],
294 | description: 'Error handling style to use',
295 | },
296 | includeLogs: {
297 | type: 'boolean',
298 | description: 'Include logging statements',
299 | default: true,
300 | },
301 | includeValidation: {
302 | type: 'boolean',
303 | description: 'Include input validation',
304 | default: true,
305 | },
306 | },
307 | required: ['code', 'language'],
308 | },
309 | },
310 | ];
```