@flexabrain/mcp-server
Version:
Advanced electrical schematic analysis MCP server with rail engineering expertise
369 lines (326 loc) • 15.3 kB
JavaScript
/**
* FlexaBrain MCP Server - Primary Electrical Schematic Analysis Tool
*
* The main MCP tool that provides comprehensive electrical schematic analysis
* leveraging rail electrical engineering expertise. This tool orchestrates
* the entire analysis pipeline from OCR to expert recommendations.
*/
import { electricalSchematicAnalyzer } from '../services/electrical-analyzer.js';
import { SchematicType, SafetyLevel } from '../types/electrical.js';
import { RecommendationPriority } from '../types/schematic.js';
/**
* Primary MCP tool for electrical schematic analysis
*/
export async function analyzeElectricalSchematic(args) {
try {
console.error(`FlexaBrain Tool: Starting schematic analysis for ${args.image_path}`);
// Validate input parameters
validateAnalysisArgs(args);
// Configure analysis options based on MCP tool arguments
const analysisOptions = {
analysis_depth: args.analysis_depth || 'standard',
focus_areas: args.focus_areas || ['safety', 'compliance'],
...(args.custom_standards && { custom_standards: args.custom_standards }),
...(args.rail_system_context && { rail_system_context: args.rail_system_context })
};
// Perform comprehensive analysis
const analysisResult = await electricalSchematicAnalyzer.analyzeSchematic(args.image_path, analysisOptions);
if (!analysisResult.success || !analysisResult.analysis) {
return formatErrorResponse(analysisResult.errors || []);
}
const analysis = analysisResult.analysis;
// Format the comprehensive analysis response
const responseText = `# 🧠 FlexaBrain Electrical Schematic Analysis
## ⚡ **Analysis Overview**
- **Schematic Type**: ${formatSchematicType(analysis.schematic_type)}
- **Processing Time**: ${analysis.processing_time}ms
- **Overall Confidence**: ${(analysis.overall_confidence * 100).toFixed(1)}%
- **Analysis Quality**: ${analysis.analysis_quality}
- **Rail expertise applied**: ✅ ${analysis.rail_expertise_applied ? 'Yes' : 'No'}
---
## 🔍 **Component Recognition Results**
**Found ${analysis.components.length} electrical components** with ${(analysis.component_recognition.overall_confidence * 100).toFixed(1)}% average confidence
### 📋 Component Inventory
${formatComponentInventory(analysis.components)}
---
## ⚠️ **Safety Analysis** - Priority Level: ${formatSafetyLevel(analysis.safety_analysis.overall_safety_level)}
### High Voltage Hazards
${analysis.safety_analysis.electrical_shock_hazards.present ?
`⚠️ **PRESENT** - Voltage levels: ${analysis.safety_analysis.electrical_shock_hazards.voltage_levels.join('V, ')}V
- Components: ${analysis.safety_analysis.electrical_shock_hazards.components.join(', ')}` :
'✅ **No high voltage hazards detected**'}
### Arc Flash Risk
${analysis.safety_analysis.arc_flash_hazards.present ?
`🔥 **PRESENT** - PPE Category ${analysis.safety_analysis.arc_flash_hazards.ppe_category} required
- Affected components: ${analysis.safety_analysis.arc_flash_hazards.components.join(', ')}
- Estimated energy: ${analysis.safety_analysis.arc_flash_hazards.estimated_energy} cal/cm²` :
'✅ **No arc flash hazards detected**'}
### Ground Fault Protection
${analysis.safety_analysis.ground_fault_risks.present ?
`⚠️ **INADEQUATE** - Unprotected circuits detected
- ${analysis.safety_analysis.ground_fault_risks.unprotected_circuits.join(', ')}` :
'✅ **Adequate ground fault protection**'}
---
## 📊 **Standards Compliance** - Overall: ${(analysis.compliance_report.overall_compliance * 100).toFixed(1)}%
### Checked Standards
${analysis.compliance_report.standards_checked.map(std => `- ${std}`).join('\n')}
### Compliance Status
- ✅ **Compliant**: ${analysis.compliance_report.compliant_items.length} items
- ❌ **Non-compliant**: ${analysis.compliance_report.non_compliant_items.length} items
- 🔍 **Requires review**: ${analysis.compliance_report.requires_review.length} items
${analysis.compliance_report.non_compliant_items.length > 0 ?
`\n### ❌ Non-Compliance Issues\n${analysis.compliance_report.non_compliant_items.map(item => `- **${item.standard}**: ${item.violation} (${item.item})`).join('\n')}` : ''}
---
## 🔧 **Maintenance Guidance**
### Component Maintenance Schedule
${formatMaintenanceSchedule(analysis.maintenance_guidance.component_schedules.slice(0, 10))}
### 🚨 Priority Actions
${analysis.maintenance_guidance.priority_actions.map(action => `- **${action.urgency}**: ${action.action}
- Duration: ${action.estimated_duration} | Cost: ${action.estimated_cost}
- Components: ${action.component_ids.join(', ')}`).join('\n\n')}
---
## 📈 **Performance Analysis**
### Efficiency Metrics
- **Overall Efficiency**: ${(analysis.performance_analysis.efficiency_metrics.overall_efficiency * 100).toFixed(1)}%
- **Power Factor**: ${analysis.performance_analysis.efficiency_metrics.power_factor.toFixed(3)}
- **Load Balance**: ${(analysis.performance_analysis.efficiency_metrics.load_balance * 100).toFixed(1)}%
${analysis.performance_analysis.efficiency_metrics.harmonic_distortion ?
`- **Harmonic Distortion**: ${(analysis.performance_analysis.efficiency_metrics.harmonic_distortion * 100).toFixed(1)}%` : ''}
### Optimization Opportunities
- **Energy Savings Potential**: ${analysis.performance_analysis.optimization_opportunities.energy_savings_potential}%
- **Cost Reduction Potential**: ${analysis.performance_analysis.optimization_opportunities.cost_reduction_potential}%
---
## 🎯 **Expert Recommendations** - ${analysis.expert_recommendations.summary.total_recommendations} Total
### 🚨 Immediate Actions (${analysis.expert_recommendations.summary.critical_count} Critical)
${formatRecommendations(analysis.expert_recommendations.next_actions.immediate)}
### ⏰ Short-term Actions (${analysis.expert_recommendations.summary.high_priority_count} High Priority)
${formatRecommendations(analysis.expert_recommendations.next_actions.short_term)}
### 📅 Long-term Planning
${formatRecommendations(analysis.expert_recommendations.next_actions.long_term)}
---
## 🔬 **Technical Details**
### Circuit Topology Analysis
- **Power Sources**: ${analysis.circuit_topology.power_sources.length}
- **Protection Devices**: ${analysis.circuit_topology.protection_devices.length}
- **Control Circuits**: ${analysis.circuit_topology.control_circuits.length}
- **Signal Circuits**: ${analysis.circuit_topology.signal_circuits.length}
### OCR Processing
- **Text Recognition Confidence**: ${(analysis.ocr_results.confidence * 100).toFixed(1)}%
- **Words Processed**: ${analysis.ocr_results.words.length}
- **Processing Time**: ${analysis.ocr_results.processing_time}ms
### Analysis Quality Factors
${analysis.limitations.length > 0 ?
`\n**⚠️ Limitations:**\n${analysis.limitations.map(limit => `- ${limit}`).join('\n')}` : ''}
${analysis.assumptions.length > 0 ?
`\n**📋 Assumptions:**\n${analysis.assumptions.map(assumption => `- ${assumption}`).join('\n')}` : ''}
---
## 🏷️ **Analysis Metadata**
- **Analyzer Version**: ${analysis.analyzer_version}
- **Standards Version**: ${analysis.standards_version}
- **Analysis Timestamp**: ${analysis.analysis_timestamp.toISOString()}
- **Total Processing Time**: ${analysis.processing_time}ms
---
*🧠 **Powered by FlexaBrain** - Intelligence Without Limits*
*⚡ Rail electrical engineering expertise built-in*`;
console.error(`FlexaBrain Tool: Analysis completed successfully for ${args.image_path}`);
console.error(`FlexaBrain Tool: Found ${analysis.components.length} components with ${analysis.expert_recommendations.summary.total_recommendations} recommendations`);
return {
content: [{
type: 'text',
text: responseText
}]
};
}
catch (error) {
console.error('FlexaBrain Tool: Analysis failed:', error);
return {
content: [{
type: 'text',
text: `# ❌ FlexaBrain Analysis Failed
**Error**: ${error instanceof Error ? error.message : String(error)}
## 🔧 Troubleshooting Steps
1. **Verify image file exists and is readable**
2. **Check image quality and clarity**
3. **Ensure image contains electrical schematic content**
4. **Try preprocessing the image to improve OCR results**
5. **Check file format compatibility (PNG, JPG, PDF supported)**
*If the problem persists, please check the image quality and ensure it contains clear electrical component labels.*`
}]
};
}
}
/**
* Validate analysis arguments
*/
function validateAnalysisArgs(args) {
if (!args.image_path) {
throw new Error('image_path is required');
}
if (typeof args.image_path !== 'string' || args.image_path.trim().length === 0) {
throw new Error('image_path must be a non-empty string');
}
// Validate analysis depth
if (args.analysis_depth && !['basic', 'standard', 'comprehensive'].includes(args.analysis_depth)) {
throw new Error('analysis_depth must be one of: basic, standard, comprehensive');
}
// Validate focus areas
if (args.focus_areas) {
const validFocusAreas = ['safety', 'compliance', 'performance', 'maintenance'];
const invalidAreas = args.focus_areas.filter(area => !validFocusAreas.includes(area));
if (invalidAreas.length > 0) {
throw new Error(`Invalid focus areas: ${invalidAreas.join(', ')}. Valid options: ${validFocusAreas.join(', ')}`);
}
}
}
/**
* Format error response for failed analysis
*/
function formatErrorResponse(errors) {
const errorMessages = errors.map(error => `- **${error.code || 'UNKNOWN'}**: ${error.message}`).join('\n');
return {
content: [{
type: 'text',
text: `# ❌ FlexaBrain Analysis Failed
## Errors Encountered:
${errorMessages}
## 🔧 Recovery Suggestions:
${errors.map(error => error.recovery_suggestions ?
error.recovery_suggestions.map((suggestion) => `- ${suggestion}`).join('\n') :
'- Please check the input parameters and try again').join('\n')}
*Please resolve these issues and retry the analysis.*`
}]
};
}
/**
* Format schematic type for display
*/
function formatSchematicType(type) {
const typeMap = {
[SchematicType.TRACTION_POWER]: '🚋 Traction Power',
[SchematicType.SIGNALING]: '🚦 Signaling System',
[SchematicType.CONTROL]: '🎛️ Control System',
[SchematicType.AUXILIARY]: '⚙️ Auxiliary Power',
[SchematicType.POWER_DISTRIBUTION]: '⚡ Power Distribution',
[SchematicType.GENERAL]: '📄 General Electrical'
};
return typeMap[type] || type;
}
/**
* Format safety level for display
*/
function formatSafetyLevel(level) {
const levelMap = {
[SafetyLevel.CRITICAL]: '🔴 CRITICAL',
[SafetyLevel.HIGH]: '🟠 HIGH',
[SafetyLevel.MEDIUM]: '🟡 MEDIUM',
[SafetyLevel.LOW]: '🟢 LOW',
[SafetyLevel.SAFE]: '✅ SAFE'
};
return levelMap[level] || level;
}
/**
* Format component inventory for display
*/
function formatComponentInventory(components) {
if (components.length === 0) {
return '*No components identified*';
}
// Group components by type for better organization
const componentsByType = components.reduce((acc, component) => {
const type = component.type;
if (!acc[type])
acc[type] = [];
acc[type].push(component);
return acc;
}, {});
let output = '';
for (const [type, typeComponents] of Object.entries(componentsByType)) {
const components = typeComponents;
output += `\n### ${formatComponentType(type)} (${components.length})\n`;
for (const component of components.slice(0, 5)) { // Limit to 5 per type for readability
const safetyIcon = getSafetyIcon(component.safety_level);
output += `- **${component.id}** ${safetyIcon} - Confidence: ${(component.confidence * 100).toFixed(1)}%`;
if (component.specifications?.voltage_rating) {
output += ` | ${component.specifications.voltage_rating.max}${component.specifications.voltage_rating.unit}`;
}
output += '\n';
}
if (components.length > 5) {
output += ` *...and ${components.length - 5} more*\n`;
}
}
return output;
}
/**
* Format component type for display
*/
function formatComponentType(type) {
const typeMap = {
'converter': '🔄 Converters',
'transformer': '⚡ Transformers',
'circuit_breaker': '🔌 Circuit Breakers',
'contactor': '🔗 Contactors',
'relay': '🔄 Relays',
'signal_reference': '📡 Signal References',
'junction_box': '📦 Junction Boxes',
'fuse': '🔒 Fuses',
'switch': '🔘 Switches'
};
return typeMap[type] || `⚙️ ${type.charAt(0).toUpperCase() + type.slice(1).replace('_', ' ')}`;
}
/**
* Get safety icon for component
*/
function getSafetyIcon(safetyLevel) {
const iconMap = {
[SafetyLevel.CRITICAL]: '🔴',
[SafetyLevel.HIGH]: '🟠',
[SafetyLevel.MEDIUM]: '🟡',
[SafetyLevel.LOW]: '🟢',
[SafetyLevel.SAFE]: '✅'
};
return iconMap[safetyLevel] || '⚪';
}
/**
* Format maintenance schedule
*/
function formatMaintenanceSchedule(schedules) {
if (schedules.length === 0) {
return '*No maintenance schedules generated*';
}
return schedules.map(schedule => {
const nextInspection = new Date(schedule.next_inspection).toLocaleDateString();
return `- **${schedule.component_id}** (${schedule.component_type})
- Next Inspection: ${nextInspection}${schedule.next_testing ?
`\n - Next Testing: ${new Date(schedule.next_testing).toLocaleDateString()}` : ''}`;
}).join('\n\n');
}
/**
* Format recommendations for display
*/
function formatRecommendations(recommendations) {
if (recommendations.length === 0) {
return '*No recommendations at this priority level*';
}
return recommendations.slice(0, 5).map(rec => {
const priorityIcon = getPriorityIcon(rec.priority);
return `${priorityIcon} **${rec.title}**
${rec.description}
*Action*: ${rec.action}${rec.component_ids ?
`\n *Components*: ${rec.component_ids.slice(0, 3).join(', ')}${rec.component_ids.length > 3 ? '...' : ''}` : ''}`;
}).join('\n\n');
}
/**
* Get priority icon
*/
function getPriorityIcon(priority) {
const iconMap = {
[RecommendationPriority.CRITICAL]: '🚨',
[RecommendationPriority.HIGH]: '⚠️',
[RecommendationPriority.MEDIUM]: '📋',
[RecommendationPriority.LOW]: '💡',
[RecommendationPriority.INFORMATIONAL]: 'ℹ️'
};
return iconMap[priority] || '📌';
}
//# sourceMappingURL=analyze-schematic.js.map