UNPKG

azureai-optimizer

Version:

AI-Powered Azure Infrastructure Optimization via Model Context Protocol

219 lines (205 loc) 8.04 kB
/** * Tool Registry * Manages registration and execution of optimization tools */ import { Logger } from '../utils/logger.js'; import { MCPError, ErrorCode } from '../utils/errors.js'; // Import tool implementations import { CostAnalysisTool } from './cost-analysis.js'; import { SecurityAssessmentTool } from './security-assessment.js'; import { RightSizingTool } from './right-sizing.js'; import { PerformanceAnalysisTool } from './performance-analysis.js'; export class ToolRegistry { tools = new Map(); resources = new Map(); config; logger; constructor(config = {}) { this.config = config; this.logger = new Logger('ToolRegistry'); } async initialize() { try { this.logger.info('🛠️ Initializing tool registry...'); // Register core optimization tools await this.registerTool(new CostAnalysisTool(this.config)); await this.registerTool(new SecurityAssessmentTool(this.config)); await this.registerTool(new RightSizingTool(this.config)); await this.registerTool(new PerformanceAnalysisTool(this.config)); // Register resources this.registerResource({ uri: 'azureai://docs/cost-optimization-guide', name: 'Cost Optimization Guide', description: 'Comprehensive guide for Azure cost optimization best practices', mimeType: 'text/markdown' }); this.registerResource({ uri: 'azureai://docs/security-compliance-frameworks', name: 'Security Compliance Frameworks', description: 'Documentation for supported compliance frameworks (SOC2, ISO27001, NIST)', mimeType: 'text/markdown' }); this.logger.info(`✅ Registered ${this.tools.size} tools and ${this.resources.size} resources`); } catch (error) { this.logger.error('❌ Failed to initialize tool registry:', error); throw error; } } async registerTool(tool) { // Check if tool is enabled if (this.config.enabledTools && !this.config.enabledTools.includes(tool.name)) { this.logger.debug(`⏭️ Skipping disabled tool: ${tool.name}`); return; } this.tools.set(tool.name, tool); this.logger.debug(`📝 Registered tool: ${tool.name}`); } registerResource(resource) { this.resources.set(resource.uri, resource); this.logger.debug(`📄 Registered resource: ${resource.uri}`); } async getTools() { return Array.from(this.tools.values()); } async getToolNames() { return Array.from(this.tools.keys()); } async getResources() { return Array.from(this.resources.values()); } async executeTool(name, args, context) { const tool = this.tools.get(name); if (!tool) { throw new MCPError(ErrorCode.METHOD_NOT_FOUND, `Tool not found: ${name}`); } try { this.logger.info(`🔧 Executing tool: ${name}`); this.logger.debug(`📝 Arguments:`, args); // Validate input schema this.validateToolInput(tool, args); // Execute the tool const startTime = Date.now(); const result = await tool.execute(args, context); const executionTime = Date.now() - startTime; this.logger.info(`✅ Tool ${name} completed in ${executionTime}ms`); // Add execution metadata return { ...result, metadata: { tool: name, executionTime, timestamp: new Date().toISOString(), ...result.metadata } }; } catch (error) { this.logger.error(`❌ Tool execution failed for ${name}:`, error); if (error instanceof MCPError) { throw error; } throw new MCPError(ErrorCode.INTERNAL_ERROR, `Tool execution failed: ${error instanceof Error ? error.message : 'Unknown error'}`); } } async readResource(uri, context) { const resource = this.resources.get(uri); if (!resource) { throw new MCPError(ErrorCode.NOT_FOUND, `Resource not found: ${uri}`); } try { this.logger.info(`📖 Reading resource: ${uri}`); // Generate resource content based on URI let content; switch (uri) { case 'azureai://docs/cost-optimization-guide': content = await this.generateCostOptimizationGuide(context); break; case 'azureai://docs/security-compliance-frameworks': content = await this.generateComplianceFrameworksDoc(context); break; default: throw new MCPError(ErrorCode.NOT_FOUND, `Resource content not available: ${uri}`); } return { uri: resource.uri, mimeType: resource.mimeType, content }; } catch (error) { this.logger.error(`❌ Resource read failed for ${uri}:`, error); if (error instanceof MCPError) { throw error; } throw new MCPError(ErrorCode.INTERNAL_ERROR, `Resource read failed: ${error instanceof Error ? error.message : 'Unknown error'}`); } } validateToolInput(_tool, args) { // Basic validation - in production, use a proper JSON schema validator if (!args || typeof args !== 'object') { throw new MCPError(ErrorCode.INVALID_PARAMS, 'Tool arguments must be an object'); } // Check required subscription_id for Azure tools if (!args.subscription_id) { throw new MCPError(ErrorCode.INVALID_PARAMS, 'subscription_id is required for Azure optimization tools'); } } async generateCostOptimizationGuide(context) { return `# Azure Cost Optimization Guide ## Overview This guide provides comprehensive strategies for optimizing Azure costs for subscription: ${context.subscriptionId} ## Key Strategies ### 1. Right-Sizing Resources - Analyze VM utilization patterns - Optimize database performance tiers - Review storage access patterns ### 2. Reserved Instances & Savings Plans - Evaluate RI coverage opportunities - Compare commitment options - Monitor utilization rates ### 3. Resource Lifecycle Management - Implement auto-shutdown policies - Remove unused resources - Optimize development environments ### 4. Monitoring & Alerting - Set up cost alerts - Regular cost reviews - Trend analysis ## Tools Available Use the following AzureAI Optimizer tools for automated analysis: - \`analyze_cost_optimization\` - Comprehensive cost analysis - \`right_size_resources\` - Resource optimization recommendations - \`unused_resource_detection\` - Identify waste Generated: ${new Date().toISOString()}`; } async generateComplianceFrameworksDoc(context) { return `# Security Compliance Frameworks ## Supported Frameworks ### SOC 2 Type II - Access controls and authentication - System monitoring and logging - Data encryption requirements - Incident response procedures ### ISO 27001 - Information security management - Risk assessment and treatment - Security controls implementation - Continuous improvement ### NIST Cybersecurity Framework - Identify security risks - Protect critical assets - Detect security events - Respond to incidents - Recover from attacks ## Assessment Tools Use \`security_compliance_check\` tool with framework parameter: - \`framework: "SOC2"\` - \`framework: "ISO27001"\` - \`framework: "NIST"\` ## Subscription Context Assessment for: ${context.subscriptionId} Generated: ${new Date().toISOString()}`; } } //# sourceMappingURL=registry.js.map