UNPKG

universal-mcp-orchestration-optimizer

Version:

⚔ OPTIMIZER EDITION: Ultra-lightweight context optimization tools. 99% smaller package for quick setup, profile management, and performance tuning of existing MCP installations.

294 lines (241 loc) • 9.61 kB
#!/usr/bin/env node /** * Universal MCP Optimizer * Ultra-lightweight optimization tools (500KB package) * Works with ANY existing MCP setup */ const fs = require('fs'); const path = require('path'); const { execSync } = require('child_process'); class MCPOptimizer { constructor() { this.version = '1.0.0'; this.projectRoot = process.cwd(); this.profiles = { minimal: { agents: ['orchestration-manager', 'developer', 'devops', 'technical-writer'], tokens: 10000, description: '4 core agents for essential development' }, standard: { agents: ['orchestration-manager', 'developer', 'frontend-developer', 'backend-engineer', 'devops', 'qa-engineer', 'database-architect', 'ui-ux-designer', 'technical-writer', 'code-review'], tokens: 25000, description: '10 agents for comprehensive development' } }; } async run(command = 'auto') { console.log('⚔ Universal MCP Optimizer v' + this.version); console.log('šŸ“¦ Ultra-lightweight optimization (500KB package)'); console.log('šŸ”§ Works with ANY existing MCP setup\n'); try { switch (command) { case 'auto': await this.autoOptimize(); break; case 'minimal': await this.applyProfile('minimal'); break; case 'standard': await this.applyProfile('standard'); break; case 'analyze': await this.analyzeContext(); break; case 'status': await this.showStatus(); break; default: this.showHelp(); } } catch (error) { console.error('āŒ Optimization failed:', error.message); this.showFallbackOptions(); } } async autoOptimize() { console.log('šŸŽÆ Auto-optimizing based on project type...'); const projectType = this.detectProjectType(); const recommendedProfile = this.getRecommendedProfile(projectType); console.log(`šŸ” Detected: ${projectType} project`); console.log(`šŸ’” Recommended: ${recommendedProfile} profile`); await this.applyProfile(recommendedProfile); } detectProjectType() { if (fs.existsSync('package.json')) { const pkg = JSON.parse(fs.readFileSync('package.json', 'utf8')); const deps = {...pkg.dependencies, ...pkg.devDependencies}; if (deps.react || deps.vue || deps.angular) return 'frontend'; if (deps.express || deps.fastify || deps.koa) return 'backend'; return 'node'; } if (fs.existsSync('requirements.txt') || fs.existsSync('pyproject.toml')) return 'python'; if (fs.existsSync('go.mod')) return 'golang'; if (fs.existsSync('Cargo.toml')) return 'rust'; return 'general'; } getRecommendedProfile(projectType) { switch (projectType) { case 'frontend': case 'backend': case 'node': case 'python': return 'standard'; default: return 'minimal'; } } async applyProfile(profileName) { const profile = this.profiles[profileName]; if (!profile) { throw new Error(`Unknown profile: ${profileName}`); } console.log(`šŸš€ Applying ${profileName} profile...`); console.log(`šŸ“Š Agents: ${profile.agents.length}, Estimated tokens: ~${profile.tokens.toLocaleString()}`); // Create MCP configuration await this.createMCPConfiguration(profileName, profile); // Update Claude settings if present this.updateClaudeSettings(profileName); // Add commands to package.json this.addOptimizationCommands(); console.log(`āœ… ${profileName} profile applied successfully!`); console.log(`šŸ“‰ Context reduced to ~${profile.tokens.toLocaleString()} tokens`); } async createMCPConfiguration(profileName, profile) { const mcpDir = path.join(this.projectRoot, '.mcp-orchestrator'); const profilesDir = path.join(mcpDir, 'profiles'); if (!fs.existsSync(profilesDir)) { fs.mkdirSync(profilesDir, { recursive: true }); } const profileConfig = { name: profileName, description: profile.description, estimatedTokens: profile.tokens, agents: profile.agents, optimizedBy: 'universal-mcp-orchestration-optimizer', appliedAt: new Date().toISOString() }; fs.writeFileSync( path.join(profilesDir, `${profileName}.json`), JSON.stringify(profileConfig, null, 2) ); } updateClaudeSettings(profileName) { const settingsPath = path.join(this.projectRoot, '.claude', 'settings.local.json'); if (fs.existsSync(settingsPath)) { try { const settings = JSON.parse(fs.readFileSync(settingsPath, 'utf8')); settings.mcp = { ...settings.mcp, currentProfile: profileName, optimizedBy: 'universal-mcp-orchestration-optimizer', lastOptimized: new Date().toISOString() }; fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2)); console.log('šŸ”§ Updated Claude settings'); } catch (error) { console.warn('āš ļø Could not update Claude settings'); } } } addOptimizationCommands() { const packageJsonPath = path.join(this.projectRoot, 'package.json'); if (fs.existsSync(packageJsonPath)) { try { const pkg = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8')); if (!pkg.scripts) pkg.scripts = {}; const commands = { 'mcp:optimize': 'mcp-optimize auto', 'mcp:minimal': 'mcp-optimize minimal', 'mcp:standard': 'mcp-optimize standard', 'mcp:analyze': 'mcp-optimize analyze', 'mcp:status': 'mcp-optimize status' }; let added = 0; for (const [script, command] of Object.entries(commands)) { if (!pkg.scripts[script]) { pkg.scripts[script] = command; added++; } } if (added > 0) { fs.writeFileSync(packageJsonPath, JSON.stringify(pkg, null, 2)); console.log(`šŸ“ Added ${added} optimization commands to package.json`); } } catch (error) { console.warn('āš ļø Could not update package.json'); } } } async analyzeContext() { console.log('šŸ“Š Analyzing current context usage...'); try { const output = execSync('claude mcp list 2>/dev/null | grep -c "Connected"', { encoding: 'utf8' }); const agentCount = parseInt(output.trim()) || 0; const estimatedTokens = agentCount * 2600; console.log(`\nšŸ“ˆ Current Context Analysis:`); console.log(` • Agents loaded: ${agentCount}`); console.log(` • Estimated tokens: ~${estimatedTokens.toLocaleString()}`); if (estimatedTokens > 25000) { console.log(`\nāš ļø WARNING: High context usage (${estimatedTokens} tokens)`); console.log(`šŸ’” Recommendation: Run 'mcp-optimize minimal' to reduce by 80%`); } else if (estimatedTokens > 15000) { console.log(`\nšŸ“Œ Moderate context usage`); console.log(`šŸ’” Consider: Run 'mcp-optimize minimal' for better performance`); } else { console.log(`\nāœ… Optimal context usage`); } } catch (error) { console.log('ā„¹ļø Could not analyze context (Claude not running)'); } } async showStatus() { console.log('šŸ“Š MCP Optimizer Status'); console.log('═══════════════════════'); const mcpDir = path.join(this.projectRoot, '.mcp-orchestrator'); if (fs.existsSync(mcpDir)) { console.log('āœ… MCP optimization configured'); const profileFiles = fs.readdirSync(path.join(mcpDir, 'profiles')).filter(f => f.endsWith('.json')); console.log(`šŸ“‹ Available profiles: ${profileFiles.map(f => f.replace('.json', '')).join(', ')}`); } else { console.log('āŒ MCP optimization not configured'); console.log('šŸ’” Run: mcp-optimize auto'); } await this.analyzeContext(); } showHelp() { console.log(` ⚔ Universal MCP Optimizer Commands: Usage: mcp-optimize [command] Commands: auto Auto-optimize based on project type minimal Apply minimal profile (4 agents, ~10k tokens) standard Apply standard profile (10 agents, ~25k tokens) analyze Analyze current context usage status Show optimizer status and recommendations Examples: mcp-optimize auto # Smart optimization mcp-optimize minimal # Fastest performance mcp-optimize analyze # Check token usage `); } showFallbackOptions() { console.log('\nšŸ”„ Fallback options:'); console.log('1. Manual profile creation in .mcp-orchestrator/profiles/'); console.log('2. Claude settings update in .claude/settings.local.json'); console.log('3. Check GitHub issues: https://github.com/ytrofr/MCP/issues'); } } // CLI execution if (require.main === module) { const args = process.argv.slice(2); const command = args[0] || 'auto'; const optimizer = new MCPOptimizer(); optimizer.run(command).catch(error => { console.error('šŸ’„ Fatal error:', error.message); process.exit(1); }); } module.exports = MCPOptimizer;