UNPKG

@flexabrain/mcp-server

Version:

Advanced electrical schematic analysis MCP server with rail engineering expertise

695 lines 35.5 kB
import { electricalSchematicAnalyzer } from '../services/electrical-analyzer.js'; /** * MCP Tool: Check Safety Compliance * * Performs comprehensive safety compliance assessment for electrical systems * based on rail engineering safety standards, arc flash analysis, and * hazard identification with expert recommendations for risk mitigation. */ export async function checkSafetyCompliance(args) { try { // Configure analysis for safety compliance focus const analysisOptions = { analysis_depth: args.assessment_level === 'comprehensive' ? 'comprehensive' : args.assessment_level === 'standard' ? 'standard' : 'basic', focus_areas: ['safety', 'compliance'], custom_standards: args.safety_standards || ['NFPA 70E', 'IEEE 1584', 'OSHA 1910', 'EN 50155'], ...(args.rail_system_context && { rail_system_context: { system_type: args.rail_system_context.system_type, voltage_system: args.rail_system_context.voltage_level, region: 'GLOBAL', applicable_standards: args.safety_standards || ['NFPA 70E', 'IEEE 1584', 'OSHA 1910', 'EN 50155'] } }) }; // Perform comprehensive safety analysis const analysisResult = await electricalSchematicAnalyzer.analyzeSchematic(args.image_path, analysisOptions); if (!analysisResult.success || !analysisResult.analysis) { throw new Error('Safety compliance check failed: ' + (analysisResult.errors?.[0]?.message || 'Unknown error')); } const analysis = analysisResult.analysis; // Generate comprehensive safety compliance report let report = '# 🛡️ Safety Compliance Assessment Report\n\n'; // Executive Safety Summary report += generateSafetySummary(analysis.safety_analysis, args); // Safety Standards Compliance Overview report += generateSafetyStandardsOverview(args.safety_standards || ['NFPA 70E', 'IEEE 1584', 'OSHA 1910']); // Hazard Identification & Assessment report += generateHazardAssessment(analysis.safety_analysis, analysis.components, args); // Arc Flash Analysis if (args.include_arc_flash !== false) { report += generateArcFlashAnalysis(analysis.safety_analysis, analysis.components, args); } // Electrical Shock Protection report += generateShockProtectionAnalysis(analysis.safety_analysis, analysis.components); // Personal Protective Equipment (PPE) Requirements report += generatePPERequirements(analysis.safety_analysis, args); // Safety Critical Components Assessment report += generateSafetyCriticalAssessment(analysis.components, analysis.safety_analysis); // Ground Fault Protection Analysis report += generateGroundFaultAnalysis(analysis.safety_analysis, analysis.circuit_topology); // Fire Hazard Assessment report += generateFireHazardAssessment(analysis.safety_analysis, analysis.components); // Safety Procedures & Work Practices report += generateSafetyProcedures(analysis.safety_analysis, args); // Compliance Violations & Corrective Actions report += generateComplianceViolations(analysis.safety_analysis, analysis.compliance_report); // Safety Recommendations report += generateSafetyRecommendations(analysis.expert_recommendations, analysis.safety_analysis); // Safety Labels & Warnings if (args.generate_labels) { report += generateSafetyLabels(analysis.components, analysis.safety_analysis); } // Compliance Summary & Action Plan report += generateComplianceActionPlan(analysis, args); return report; } catch (error) { return `❌ **Error checking safety compliance**\n\nError: ${error instanceof Error ? error.message : String(error)}`; } } /** * Generate safety executive summary */ function generateSafetySummary(safetyAnalysis, args) { const overallSafety = safetyAnalysis.overall_safety_level; const safetyIcon = overallSafety === 'critical' ? '🔴 CRITICAL' : overallSafety === 'high' ? '🟠 HIGH RISK' : overallSafety === 'medium' ? '🟡 MODERATE' : '🟢 LOW RISK'; let summary = '## 📋 Safety Compliance Executive Summary\n\n'; summary += `**Overall Safety Level**: ${safetyIcon}\n`; summary += `**Assessment Level**: ${args.assessment_level?.toUpperCase() || 'STANDARD'}\n`; summary += `**Standards Applied**: ${args.safety_standards?.length || 4} safety standards\n\n`; // Key safety findings summary += '### Key Safety Findings\n\n'; const arcFlashPresent = safetyAnalysis.arc_flash_hazards?.present || false; const shockHazardPresent = safetyAnalysis.electrical_shock_hazards?.present || false; const groundFaultRisk = safetyAnalysis.ground_fault_risks?.present || false; const fireHazardPresent = safetyAnalysis.fire_hazards?.present || false; summary += `- **Arc Flash Hazards**: ${arcFlashPresent ? '⚠️ Present' : '✅ Not Identified'}\n`; summary += `- **Electrical Shock Risk**: ${shockHazardPresent ? '⚠️ Present' : '✅ Low Risk'}\n`; summary += `- **Ground Fault Risk**: ${groundFaultRisk ? '⚠️ Present' : '✅ Protected'}\n`; summary += `- **Fire Hazards**: ${fireHazardPresent ? '⚠️ Present' : '✅ Low Risk'}\n\n`; // Immediate actions required const immediateActions = getImmediateActions(safetyAnalysis); if (immediateActions.length > 0) { summary += '### ⚡ Immediate Actions Required\n\n'; for (const action of immediateActions) { summary += `- ${action}\n`; } summary += '\n'; } else { summary += '### ✅ Status: No immediate safety actions required\n\n'; } return summary; } /** * Generate safety standards overview */ function generateSafetyStandardsOverview(standards) { let overview = '## 📚 Safety Standards Overview\n\n'; const standardDescriptions = { 'NFPA 70E': 'Standard for Electrical Safety in the Workplace - Covers electrical safety work practices', 'IEEE 1584': 'Guide for Performing Arc-Flash Hazard Calculations - Arc flash incident energy calculations', 'OSHA 1910': 'Occupational Safety and Health Standards - General industry electrical safety requirements', 'EN 50155': 'Railway applications - Electronic equipment used on rolling stock - Safety requirements', 'IEC 60364': 'Low-voltage electrical installations - Installation safety requirements', 'IEEE 80': 'Guide for Safety in AC Substation Grounding - Grounding system safety', 'ANSI Z535': 'Safety Signs and Tags - Safety labeling and warning requirements' }; overview += '### Applicable Safety Standards\n\n'; overview += '| Standard | Description | Focus Area |\n'; overview += '|----------|-------------|------------|\n'; for (const standard of standards) { const description = standardDescriptions[standard] || 'Safety standard for electrical systems'; const focusArea = standard.includes('70E') ? 'Work Practices' : standard.includes('1584') ? 'Arc Flash' : standard.includes('OSHA') ? 'Regulatory' : standard.includes('EN') ? 'Rail Safety' : 'General Safety'; overview += `| **${standard}** | ${description} | ${focusArea} |\n`; } overview += '\n'; return overview; } /** * Generate comprehensive hazard assessment */ function generateHazardAssessment(safetyAnalysis, components, args) { let hazards = '## ⚠️ Hazard Identification & Assessment\n\n'; hazards += '### Identified Hazards Summary\n\n'; hazards += '| Hazard Type | Risk Level | Components Affected | Mitigation Priority |\n'; hazards += '|-------------|------------|---------------------|---------------------|\n'; // Arc flash hazards const arcFlash = safetyAnalysis.arc_flash_hazards; if (arcFlash?.present) { const riskLevel = arcFlash.estimated_energy > 40 ? '🔴 Critical' : arcFlash.estimated_energy > 8 ? '🟠 High' : '🟡 Moderate'; hazards += `| Arc Flash | ${riskLevel} | ${arcFlash.components.length} | Immediate |\n`; } // Electrical shock hazards const shock = safetyAnalysis.electrical_shock_hazards; if (shock?.present) { const maxVoltage = Math.max(...shock.voltage_levels); const riskLevel = maxVoltage >= 1000 ? '🔴 Critical' : maxVoltage >= 400 ? '🟠 High' : '🟡 Moderate'; hazards += `| Electrical Shock | ${riskLevel} | ${shock.components.length} | High |\n`; } // Ground fault risks const groundFault = safetyAnalysis.ground_fault_risks; if (groundFault?.present) { hazards += `| Ground Fault | 🟠 High | ${groundFault.unprotected_circuits.length} circuits | High |\n`; } // Fire hazards const fire = safetyAnalysis.fire_hazards; if (fire?.present) { const riskLevel = fire.overloaded_circuits?.length > 0 ? '🟠 High' : '🟡 Moderate'; hazards += `| Fire/Overheating | ${riskLevel} | Multiple | Medium |\n`; } hazards += '\n'; // Detailed hazard analysis hazards += '### Detailed Hazard Analysis\n\n'; // High voltage components hazard analysis const highVoltageComponents = components.filter(c => c.specifications?.voltage_rating && c.specifications.voltage_rating.max >= 1000); if (highVoltageComponents.length > 0) { hazards += '#### High Voltage Hazards\n\n'; hazards += `**Components**: ${highVoltageComponents.map(c => c.id).join(', ')}\n\n`; hazards += '**Hazard Types**:\n'; hazards += '- **Electrical Shock**: Contact with energized parts can cause severe injury or death\n'; hazards += '- **Arc Flash**: High energy discharge can cause burns and explosive blast\n'; hazards += '- **Arc Blast**: Pressure wave can cause physical trauma\n'; hazards += '- **Step/Touch Potential**: Ground potential differences during faults\n\n'; hazards += '**Risk Factors**:\n'; hazards += '- High available fault current\n'; hazards += '- Energized work practices\n'; hazards += '- Inadequate approach boundaries\n'; hazards += '- Insufficient PPE\n\n'; } return hazards; } /** * Generate arc flash analysis */ function generateArcFlashAnalysis(safetyAnalysis, components, args) { let arcFlash = '## ⚡ Arc Flash Analysis (IEEE 1584)\n\n'; const arcFlashData = safetyAnalysis.arc_flash_hazards; if (!arcFlashData?.present) { arcFlash += '✅ **No significant arc flash hazards identified**\n\n'; arcFlash += 'System appears to be low energy or adequately protected.\n\n'; return arcFlash; } arcFlash += '### Arc Flash Hazard Assessment\n\n'; arcFlash += `**Incident Energy**: ${arcFlashData.estimated_energy} cal/cm²\n`; arcFlash += `**PPE Category**: ${arcFlashData.ppe_category}\n`; arcFlash += `**Arc Flash Boundary**: ${calculateArcFlashBoundary(arcFlashData.estimated_energy)} inches\n`; arcFlash += `**Components at Risk**: ${arcFlashData.components.join(', ')}\n\n`; // PPE requirements based on incident energy arcFlash += '### Required Personal Protective Equipment\n\n'; const ppeCategory = arcFlashData.ppe_category; arcFlash += '| PPE Item | Requirement | Standard |\n'; arcFlash += '|----------|-------------|----------|\n'; if (ppeCategory >= 1) { arcFlash += '| Arc-rated shirt & pants | 4 cal/cm² minimum | ASTM F1506 |\n'; arcFlash += '| Arc-rated face shield | Required | ASTM F2178 |\n'; arcFlash += '| Safety glasses | Required | ANSI Z87.1 |\n'; arcFlash += '| Hard hat | Arc-rated | ASTM F2178 |\n'; } if (ppeCategory >= 2) { arcFlash += '| Arc-rated suit | 8 cal/cm² minimum | ASTM F1506 |\n'; arcFlash += '| Arc-rated gloves | Required | ASTM F2675 |\n'; arcFlash += '| Leather footwear | Required | ASTM F2413 |\n'; } if (ppeCategory >= 3) { arcFlash += '| Arc-rated suit | 25 cal/cm² minimum | ASTM F1506 |\n'; arcFlash += '| Arc-rated hood | Required | ASTM F2178 |\n'; } if (ppeCategory >= 4) { arcFlash += '| Arc-rated suit | 40 cal/cm² minimum | ASTM F1506 |\n'; arcFlash += '| Ventilated hood | Required | ASTM F2178 |\n'; } arcFlash += '\n'; // Arc flash mitigation strategies arcFlash += '### Arc Flash Mitigation Strategies\n\n'; arcFlash += '1. **Engineering Controls**:\n'; arcFlash += ' - Install arc-resistant switchgear\n'; arcFlash += ' - Implement current-limiting devices\n'; arcFlash += ' - Use remote operation where possible\n'; arcFlash += ' - Install arc flash relays for fast clearing\n\n'; arcFlash += '2. **Administrative Controls**:\n'; arcFlash += ' - Develop energized work procedures\n'; arcFlash += ' - Implement work permit system\n'; arcFlash += ' - Provide comprehensive training\n'; arcFlash += ' - Schedule periodic safety assessments\n\n'; arcFlash += '3. **Personal Protective Equipment**:\n'; arcFlash += ' - Provide appropriate PPE category equipment\n'; arcFlash += ' - Ensure proper fit and maintenance\n'; arcFlash += ' - Train on correct usage and limitations\n'; arcFlash += ' - Inspect PPE before each use\n\n'; return arcFlash; } /** * Generate electrical shock protection analysis */ function generateShockProtectionAnalysis(safetyAnalysis, components) { let shock = '## ⚡ Electrical Shock Protection Analysis\n\n'; const shockData = safetyAnalysis.electrical_shock_hazards; if (!shockData?.present) { shock += '✅ **Low electrical shock risk identified**\n\n'; return shock; } shock += '### Shock Hazard Assessment\n\n'; shock += `**Voltage Levels Present**: ${shockData.voltage_levels.join('V, ')}V\n`; shock += `**Components at Risk**: ${shockData.components.length}\n\n`; // Voltage classification const maxVoltage = Math.max(...shockData.voltage_levels); shock += '### Voltage Classification & Requirements\n\n'; if (maxVoltage >= 1000) { shock += '#### High Voltage (≥1000V)\n'; shock += '- **Qualified Person Required**: Only qualified electrical workers\n'; shock += '- **Approach Boundaries**: Establish restricted and limited approach boundaries\n'; shock += '- **PPE Requirements**: Voltage-rated gloves and tools required\n'; shock += '- **Safety Procedures**: Lockout/tagout and energy verification mandatory\n\n'; } else if (maxVoltage >= 50) { shock += '#### Low Voltage (50-1000V)\n'; shock += '- **Training Required**: Electrical safety training for workers\n'; shock += '- **PPE Requirements**: Insulated tools and appropriate gloves\n'; shock += '- **Safety Procedures**: De-energize when possible, test before touch\n\n'; } // Protection methods shock += '### Protection Methods\n\n'; shock += '1. **Elimination/Substitution**:\n'; shock += ' - De-energize equipment when possible\n'; shock += ' - Use lower voltage alternatives\n'; shock += ' - Implement remote operation\n\n'; shock += '2. **Engineering Controls**:\n'; shock += ' - Install proper enclosures and guarding\n'; shock += ' - Implement GFCI protection\n'; shock += ' - Use insulation and barriers\n'; shock += ' - Install warning signs and labels\n\n'; shock += '3. **Administrative Controls**:\n'; shock += ' - Develop safe work procedures\n'; shock += ' - Provide electrical safety training\n'; shock += ' - Implement permit systems\n'; shock += ' - Regular safety inspections\n\n'; shock += '4. **Personal Protective Equipment**:\n'; shock += ' - Voltage-rated gloves\n'; shock += ' - Insulated tools\n'; shock += ' - Non-conductive footwear\n'; shock += ' - Flame-resistant clothing\n\n'; return shock; } /** * Generate PPE requirements */ function generatePPERequirements(safetyAnalysis, args) { let ppe = '## 🦺 Personal Protective Equipment Requirements\n\n'; // Determine PPE category based on hazards const arcFlashCategory = safetyAnalysis.arc_flash_hazards?.ppe_category || 0; const hasHighVoltage = safetyAnalysis.electrical_shock_hazards?.voltage_levels?.some((v) => v >= 1000) || false; ppe += '### PPE Category Assessment\n\n'; ppe += `**Arc Flash PPE Category**: ${arcFlashCategory}\n`; ppe += `**High Voltage Work**: ${hasHighVoltage ? 'Yes - Additional requirements apply' : 'No'}\n`; ppe += `**Operating Environment**: ${args.rail_system_context?.environment || 'Standard'}\n\n`; // Standard PPE requirements ppe += '### Required PPE by Work Type\n\n'; ppe += '#### Routine Maintenance & Inspection\n'; ppe += '- Safety glasses (ANSI Z87.1)\n'; ppe += '- Hard hat (ANSI Z89.1)\n'; ppe += '- Safety shoes (ASTM F2413)\n'; ppe += '- Work gloves (cut resistant)\n'; ppe += '- High-visibility clothing (ANSI 107)\n\n'; if (arcFlashCategory > 0) { ppe += '#### Energized Electrical Work\n'; ppe += `- Arc-rated clothing (${getMinimumArcRating(arcFlashCategory)} cal/cm²)\n`; ppe += '- Arc-rated face shield or hood\n'; ppe += '- Arc-rated gloves\n'; ppe += '- Voltage-rated electrical gloves\n'; ppe += '- Insulated tools\n\n'; } if (hasHighVoltage) { ppe += '#### High Voltage Work\n'; ppe += '- Voltage-rated gloves (Class 2 or higher)\n'; ppe += '- Voltage-rated sleeves\n'; ppe += '- Hot stick/insulated tools\n'; ppe += '- Blankets and line hose\n'; ppe += '- Approach boundary barriers\n\n'; } // Rail-specific PPE if (args.rail_system_context) { ppe += '#### Rail Industry Specific PPE\n'; ppe += '- High-visibility reflective vest (ANSI 107 Class 3)\n'; ppe += '- Steel-toed boots with electrical hazard rating\n'; ppe += '- Communication equipment (radio/cell phone)\n'; ppe += '- Emergency whistle or horn\n'; ppe += '- Flashlight with spare batteries\n\n'; } return ppe; } /** * Generate safety critical components assessment */ function generateSafetyCriticalAssessment(components, safetyAnalysis) { let assessment = '## 🔴 Safety Critical Components Assessment\n\n'; const criticalComponents = components.filter(c => c.safety_level === 'critical'); const highRiskComponents = components.filter(c => c.safety_level === 'high'); assessment += '### Component Risk Classification\n\n'; assessment += '| Component | Risk Level | Hazard Type | Special Requirements |\n'; assessment += '|-----------|------------|-------------|----------------------|\n'; for (const component of criticalComponents) { const hazardType = determineHazardType(component); const requirements = getSafetyRequirements(component.type); assessment += `| **${component.id}** | 🔴 Critical | ${hazardType} | ${requirements} |\n`; } for (const component of highRiskComponents.slice(0, 5)) { // Limit for readability const hazardType = determineHazardType(component); const requirements = getSafetyRequirements(component.type); assessment += `| **${component.id}** | 🟠 High | ${hazardType} | ${requirements} |\n`; } assessment += '\n'; if (criticalComponents.length > 0) { assessment += '### Critical Component Safety Procedures\n\n'; for (const component of criticalComponents) { assessment += `#### ${component.id} Safety Protocol\n\n`; assessment += getSafetyProtocol(component); assessment += '\n'; } } return assessment; } /** * Generate ground fault analysis */ function generateGroundFaultAnalysis(safetyAnalysis, circuitTopology) { let groundFault = '## 🔌 Ground Fault Protection Analysis\n\n'; const groundFaultData = safetyAnalysis.ground_fault_risks; const groundingSystem = circuitTopology.grounding_system; groundFault += '### Grounding System Status\n\n'; groundFault += `**System Adequacy**: ${groundingSystem.is_adequate ? '✅ Adequate' : '❌ Inadequate'}\n`; groundFault += `**Ground Fault Protection**: ${groundingSystem.has_ground_fault_protection ? '✅ Present' : '❌ Missing'}\n`; if (groundFaultData?.present) { groundFault += `**Unprotected Circuits**: ${groundFaultData.unprotected_circuits.length}\n`; groundFault += `**Risk Level**: 🟠 High\n\n`; groundFault += '### Ground Fault Risks\n\n'; for (const circuit of groundFaultData.unprotected_circuits) { groundFault += `- **${circuit}**: No ground fault protection detected\n`; } groundFault += '\n'; groundFault += '### Required Corrective Actions\n\n'; for (const recommendation of groundFaultData.recommendations) { groundFault += `- ${recommendation}\n`; } groundFault += '\n'; } else { groundFault += `**Risk Level**: 🟢 Low\n\n`; groundFault += '✅ **Ground fault protection appears adequate**\n\n'; } return groundFault; } /** * Generate fire hazard assessment */ function generateFireHazardAssessment(safetyAnalysis, components) { let fire = '## 🔥 Fire Hazard Assessment\n\n'; const fireData = safetyAnalysis.fire_hazards; if (!fireData?.present) { fire += '✅ **Low fire hazard risk identified**\n\n'; return fire; } fire += '### Fire Risk Analysis\n\n'; fire += `**Overloaded Circuits**: ${fireData.overloaded_circuits?.length || 0}\n`; fire += `**Inadequate Protection**: ${fireData.inadequate_protection?.length || 0} circuits\n\n`; // Heat-generating components const heatComponents = components.filter(c => ['converter', 'transformer', 'motor'].includes(c.type)); if (heatComponents.length > 0) { fire += '### Heat-Generating Components\n\n'; fire += '| Component | Fire Risk | Mitigation Required |\n'; fire += '|-----------|-----------|---------------------|\n'; for (const component of heatComponents) { const riskLevel = component.type === 'transformer' ? '🟠 Medium' : '🟡 Low'; const mitigation = component.type === 'transformer' ? 'Temperature monitoring' : component.type === 'converter' ? 'Cooling system maintenance' : 'Regular inspection'; fire += `| ${component.id} | ${riskLevel} | ${mitigation} |\n`; } fire += '\n'; } fire += '### Fire Prevention Measures\n\n'; fire += '1. **Electrical Protection**:\n'; fire += ' - Install appropriate overcurrent protection\n'; fire += ' - Use properly rated conductors\n'; fire += ' - Ensure proper connections and terminations\n\n'; fire += '2. **Environmental Controls**:\n'; fire += ' - Maintain adequate ventilation\n'; fire += ' - Control combustible materials\n'; fire += ' - Install fire detection systems\n\n'; fire += '3. **Maintenance Practices**:\n'; fire += ' - Regular thermal inspections\n'; fire += ' - Clean electrical enclosures\n'; fire += ' - Monitor loading conditions\n\n'; return fire; } /** * Generate safety procedures */ function generateSafetyProcedures(safetyAnalysis, args) { let procedures = '## 📋 Safety Procedures & Work Practices\n\n'; procedures += '### Lockout/Tagout (LOTO) Procedures\n\n'; procedures += '1. **Preparation**:\n'; procedures += ' - Identify all energy sources\n'; procedures += ' - Notify affected personnel\n'; procedures += ' - Obtain proper lockout devices\n\n'; procedures += '2. **Shutdown**:\n'; procedures += ' - De-energize equipment using normal controls\n'; procedures += ' - Isolate all energy sources\n'; procedures += ' - Apply lockout devices\n\n'; procedures += '3. **Verification**:\n'; procedures += ' - Test equipment to ensure de-energization\n'; procedures += ' - Use qualified test equipment\n'; procedures += ' - Document verification results\n\n'; if (safetyAnalysis.arc_flash_hazards?.present) { procedures += '### Energized Work Procedures\n\n'; procedures += '1. **Justification**: Document why energized work is necessary\n'; procedures += '2. **Risk Assessment**: Complete job safety analysis\n'; procedures += '3. **PPE Selection**: Determine appropriate PPE category\n'; procedures += '4. **Qualified Personnel**: Ensure workers are qualified\n'; procedures += '5. **Supervision**: Provide adequate supervision\n'; procedures += '6. **Emergency Response**: Establish emergency procedures\n\n'; } procedures += '### Emergency Response Procedures\n\n'; procedures += '#### Electrical Shock Response\n'; procedures += '1. Do not touch the victim while energized\n'; procedures += '2. De-energize the source if safely possible\n'; procedures += '3. Call emergency services (911)\n'; procedures += '4. Provide first aid if qualified\n'; procedures += '5. Document the incident\n\n'; procedures += '#### Arc Flash Incident Response\n'; procedures += '1. Ensure personal safety first\n'; procedures += '2. Call emergency services immediately\n'; procedures += '3. Do not move severely burned victims\n'; procedures += '4. Provide cool water for minor burns\n'; procedures += '5. Preserve incident scene for investigation\n\n'; return procedures; } /** * Generate compliance violations */ function generateComplianceViolations(safetyAnalysis, complianceReport) { let violations = '## 🚫 Safety Compliance Violations\n\n'; const safetyViolations = complianceReport?.non_compliant_items?.filter((item) => item.standard?.includes('70E') || item.standard?.includes('1584') || item.standard?.includes('OSHA')) || []; if (safetyViolations.length === 0) { violations += '✅ **No safety compliance violations identified**\n\n'; return violations; } violations += '### Identified Violations\n\n'; violations += '| Standard | Component | Violation | Severity | Required Action |\n'; violations += '|----------|-----------|-----------|----------|------------------|\n'; for (const violation of safetyViolations) { const severityIcon = violation.severity === 'HIGH' ? '🔴' : violation.severity === 'MEDIUM' ? '🟠' : '🟡'; violations += `| ${violation.standard} | ${violation.item} | ${violation.reason} | ${severityIcon} ${violation.severity} | ${violation.required_action || 'Review and correct'} |\n`; } violations += '\n'; return violations; } /** * Generate safety recommendations */ function generateSafetyRecommendations(expertRecommendations, safetyAnalysis) { let recommendations = '## 💡 Safety Recommendations\n\n'; const safetyRecs = expertRecommendations?.recommendations?.filter((r) => r.type === 'SAFETY' || r.category === 'safety') || []; recommendations += '### Priority Safety Actions\n\n'; // Group by priority const critical = safetyRecs.filter((r) => r.priority === 'CRITICAL'); const high = safetyRecs.filter((r) => r.priority === 'HIGH'); const medium = safetyRecs.filter((r) => r.priority === 'MEDIUM'); for (const rec of critical) { recommendations += `#### 🔴 ${rec.title}\n`; recommendations += `${rec.description}\n\n`; recommendations += `**Action**: ${rec.action}\n`; if (rec.component_ids?.length > 0) { recommendations += `**Components**: ${rec.component_ids.join(', ')}\n`; } recommendations += '\n'; } for (const rec of high) { recommendations += `#### 🟠 ${rec.title}\n`; recommendations += `${rec.description}\n\n`; recommendations += `**Action**: ${rec.action}\n`; recommendations += '\n'; } // Additional safety recommendations based on analysis if (safetyAnalysis.overall_safety_level === 'critical' || safetyAnalysis.overall_safety_level === 'high') { recommendations += '### Additional Safety Measures\n\n'; recommendations += '- Conduct comprehensive electrical safety audit\n'; recommendations += '- Implement enhanced training program\n'; recommendations += '- Install additional safety monitoring systems\n'; recommendations += '- Review and update emergency procedures\n\n'; } return recommendations; } /** * Generate safety labels */ function generateSafetyLabels(components, safetyAnalysis) { let labels = '## 🏷️ Required Safety Labels & Warnings\n\n'; labels += '### Arc Flash Labels\n\n'; if (safetyAnalysis.arc_flash_hazards?.present) { const arcFlashComponents = safetyAnalysis.arc_flash_hazards.components; labels += '#### Arc Flash Warning Label Template\n\n'; labels += '```\n'; labels += '⚠️ DANGER - ARC FLASH HAZARD\n'; labels += `Incident Energy: ${safetyAnalysis.arc_flash_hazards.estimated_energy} cal/cm²\n`; labels += `PPE Category: ${safetyAnalysis.arc_flash_hazards.ppe_category}\n`; labels += `Arc Flash Boundary: ${calculateArcFlashBoundary(safetyAnalysis.arc_flash_hazards.estimated_energy)}\"\n`; labels += 'Energized work prohibited without proper PPE\n'; labels += 'and qualified personnel\n'; labels += '```\n\n'; labels += '**Required Locations**:\n'; for (const component of arcFlashComponents) { labels += `- ${component} equipment\n`; } labels += '\n'; } // High voltage warning labels const highVoltageComponents = components.filter(c => c.specifications?.voltage_rating && c.specifications.voltage_rating.max >= 1000); if (highVoltageComponents.length > 0) { labels += '### High Voltage Warning Labels\n\n'; labels += '#### High Voltage Warning Template\n\n'; labels += '```\n'; labels += '⚡ DANGER - HIGH VOLTAGE\n'; labels += 'KEEP OUT\n'; labels += 'AUTHORIZED PERSONNEL ONLY\n'; labels += 'DEADLY VOLTAGE INSIDE\n'; labels += '```\n\n'; labels += '**Required Locations**:\n'; for (const component of highVoltageComponents) { labels += `- ${component.id} enclosure\n`; } labels += '\n'; } return labels; } /** * Generate compliance action plan */ function generateComplianceActionPlan(analysis, args) { let actionPlan = '## 📊 Compliance Action Plan\n\n'; actionPlan += '### Summary Metrics\n\n'; const safetyLevel = analysis.safety_analysis.overall_safety_level; const complianceLevel = Math.round(analysis.compliance_report.overall_compliance * 100); actionPlan += `- **Overall Safety Level**: ${safetyLevel.toUpperCase()}\n`; actionPlan += `- **Compliance Percentage**: ${complianceLevel}%\n`; actionPlan += `- **Components Assessed**: ${analysis.components.length}\n`; actionPlan += `- **Standards Applied**: ${args.safety_standards?.length || 4}\n\n`; actionPlan += '### Implementation Timeline\n\n'; actionPlan += '#### Immediate (0-30 days)\n'; actionPlan += '- Address critical safety violations\n'; actionPlan += '- Install required safety labels\n'; actionPlan += '- Provide emergency safety training\n'; actionPlan += '- Implement lockout/tagout procedures\n\n'; actionPlan += '#### Short-term (1-3 months)\n'; actionPlan += '- Complete arc flash study\n'; actionPlan += '- Install additional protection devices\n'; actionPlan += '- Update safety procedures\n'; actionPlan += '- Conduct safety audit\n\n'; actionPlan += '#### Long-term (3-12 months)\n'; actionPlan += '- Upgrade electrical systems as needed\n'; actionPlan += '- Implement predictive maintenance\n'; actionPlan += '- Regular safety assessments\n'; actionPlan += '- Continuous improvement program\n\n'; actionPlan += '---\n'; actionPlan += `*Safety compliance assessment completed on ${new Date().toISOString().split('T')[0]} using FlexaBrain MCP Server v${analysis.analyzer_version}*\n`; return actionPlan; } // Helper functions function getImmediateActions(safetyAnalysis) { const actions = []; if (safetyAnalysis.arc_flash_hazards?.present) { actions.push('Install arc flash warning labels'); actions.push('Provide appropriate PPE for electrical work'); } if (safetyAnalysis.ground_fault_risks?.present) { actions.push('Install ground fault circuit interrupters'); } if (safetyAnalysis.electrical_shock_hazards?.present) { const maxVoltage = Math.max(...safetyAnalysis.electrical_shock_hazards.voltage_levels); if (maxVoltage >= 1000) { actions.push('Establish approach boundaries for high voltage equipment'); actions.push('Ensure only qualified personnel work on high voltage systems'); } } return actions; } function calculateArcFlashBoundary(incidentEnergy) { // Simplified calculation - in practice, use IEEE 1584 equations return Math.round(incidentEnergy * 2); // inches } function getMinimumArcRating(category) { const ratings = [0, 4, 8, 25, 40]; return ratings[category] || 40; } function determineHazardType(component) { if (component.specifications?.voltage_rating && component.specifications.voltage_rating.max >= 1000) { return 'High Voltage, Arc Flash'; } switch (component.type) { case 'converter': case 'transformer': return 'Arc Flash, Fire'; case 'circuit_breaker': return 'Arc Flash, Mechanical'; default: return 'Electrical Shock'; } } function getSafetyRequirements(componentType) { const requirements = { 'converter': 'PPE Category 3, Qualified person', 'transformer': 'High voltage safety, Oil testing', 'circuit_breaker': 'Arc flash protection, LOTO', 'relay': 'System isolation, Calibrated equipment' }; return requirements[componentType] || 'Standard electrical safety'; } function getSafetyProtocol(component) { let protocol = `**Pre-work Safety Check**:\n`; protocol += `- Verify de-energized state\n`; protocol += `- Apply lockout/tagout procedures\n`; protocol += `- Test with qualified test equipment\n`; protocol += `- Don appropriate PPE\n\n`; protocol += `**Work Procedures**:\n`; protocol += `- Maintain safe approach distances\n`; protocol += `- Use insulated tools only\n`; protocol += `- Have qualified observer present\n`; protocol += `- Follow written procedures\n\n`; protocol += `**Post-work Verification**:\n`; protocol += `- Remove all tools and materials\n`; protocol += `- Verify proper reassembly\n`; protocol += `- Remove lockout devices in reverse order\n`; protocol += `- Test system operation\n`; return protocol; } //# sourceMappingURL=check-safety-compliance.js.map