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
JavaScript
/**
* 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;