npm package: @flexabrain/mcp-server
Description: Advanced electrical schematic analysis MCP server with rail engineering expertise
Author: FlexaBrain Team
Latest version: 1.0.0

# 🧠 FlexaBrain MCP Server

**Intelligence Without Limits** - Advanced electrical schematic analysis powered by rail engineering expertise.

[![TypeScript](https://img.shields.io/badge/TypeScript-5.0+-blue.svg)](https://www.typescriptlang.org/)
[![MCP](https://img.shields.io/badge/MCP-Compatible-green.svg)](https://modelcontextprotocol.io/)
[![Node.js](https://img.shields.io/badge/Node.js-18+-green.svg)](https://nodejs.org/)
[![License](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)

## 🚆 **What is FlexaBrain MCP Server?**

FlexaBrain MCP Server is a specialized **Model Context Protocol (MCP) server** that provides intelligent electrical schematic analysis with deep **rail electrical engineering expertise**. It combines advanced OCR, machine learning-based component classification, and domain-specific knowledge to deliver comprehensive analysis, safety assessments, and expert recommendations for electrical schematics.

### 🎯 **Core Value Proposition**

- **🚋 Rail Engineering Expertise**: Built-in knowledge of traction power, signaling, and control systems
- **🔍 Intelligent Analysis**: Advanced OCR + ML-powered component recognition  
- **⚡ Safety-First Approach**: Arc flash analysis, electrical hazard assessment, PPE recommendations
- **📊 Standards Compliance**: Automated validation against IEC, IEEE, EN, and rail-specific standards
- **🔧 Maintenance Intelligence**: Predictive maintenance scheduling based on component types and usage
- **🎯 Expert Recommendations**: Context-aware suggestions for optimization and safety improvements

---

## 🚀 **Quick Start**

### Prerequisites

- **Node.js 18+**
- **npm or yarn**
- **MCP-compatible client** (Claude Desktop, VS Code with MCP extension, etc.)

### Installation

```bash
# Clone the repository
git clone https://github.com/your-org/flexabrain-mcp.git
cd flexabrain-mcp

# Install dependencies
npm install

# Build the project
npm run build

# Run tests
npm test
```

### Basic Usage

```typescript
import { analyzeElectricalSchematic } from './src/tools/analyze-schematic.js';

// Analyze a traction power schematic
const result = await analyzeElectricalSchematic({
  image_path: './schematics/metro-traction-power.png',
  analysis_depth: 'comprehensive',
  rail_system_context: {
    system_type: 'METRO',
    voltage_system: '1500V DC',
    region: 'US',
    applicable_standards: ['EN 50155', 'IEC 61375']
  },
  focus_areas: ['safety', 'compliance', 'maintenance']
});

console.log(result.content[0].text); // Rich analysis report
```

---

## 🛠️ **MCP Tools Overview**

FlexaBrain provides **8 specialized MCP tools** for comprehensive electrical analysis:

### 1. 🔍 **Analyze Electrical Schematic**
```typescript
analyzeElectricalSchematic({
  image_path: string,
  analysis_depth?: 'basic' | 'standard' | 'comprehensive',
  focus_areas?: ('safety' | 'compliance' | 'performance' | 'maintenance')[],
  rail_system_context?: RailSystemContext
})
```
**Primary analysis tool providing complete schematic assessment with safety analysis, compliance checking, and expert recommendations.**

### 2. 📋 **Extract Component Inventory**
```typescript
extractComponentInventory({
  image_path: string,
  output_format: 'JSON' | 'CSV' | 'PDF',
  include_specifications?: boolean,
  group_by_category?: boolean
})
```
**Generates detailed component catalogs with specifications, maintenance requirements, and categorization.**

### 3. ✅ **Validate Electrical Standards**
```typescript
validateElectricalStandards({
  image_path: string,
  standards: string[],
  rail_system_type?: string,
  region?: 'EU' | 'US' | 'ASIA' | 'GLOBAL'
})
```
**Comprehensive standards compliance validation against IEC, IEEE, EN, and rail-specific regulations.**

### 4. ⚡ **Analyze Power Flow**
```typescript
analyzePowerFlow({
  image_path: string,
  system_voltage?: number,
  analysis_focus?: 'traction' | 'auxiliary' | 'signaling' | 'complete',
  include_harmonics?: boolean
})
```
**Advanced power system analysis with efficiency calculations, load balancing, and optimization recommendations.**

### 5. 🔧 **Generate Maintenance Schedule**
```typescript
generateMaintenanceSchedule({
  image_path: string,
  rail_system_type: string,
  maintenance_strategy: 'PREVENTIVE' | 'PREDICTIVE' | 'CONDITION_BASED',
  time_horizon_months: number
})
```
**Intelligent maintenance scheduling based on component types, usage patterns, and rail engineering best practices.**

### 6. ⚠️ **Check Safety Compliance**
```typescript
checkSafetyCompliance({
  image_path: string,
  voltage_level: number,
  safety_standards: string[],
  include_arc_flash_analysis?: boolean,
  include_ppe_recommendations?: boolean
})
```
**Comprehensive safety analysis including arc flash hazard assessment, electrical shock risks, and PPE requirements.**

### 7. 🖼️ **Transform Schematic Image**
```typescript
transformSchematicImage({
  input_path: string,
  output_path?: string,
  operations: ('enhance_contrast' | 'denoise' | 'binarize' | 'deskew')[],
  enhancement_level?: 'basic' | 'standard' | 'aggressive'
})
```
**Advanced image preprocessing for improved OCR accuracy and analysis quality.**

### 8. 📊 **Batch Analyze Schematics**
```typescript
batchAnalyzeSchematics({
  input_directory: string,
  file_pattern?: string,
  analysis_depth?: 'basic' | 'standard' | 'comprehensive',
  generate_comparison?: boolean,
  parallel_processing?: boolean
})
```
**Efficient batch processing with comparison analysis and consolidated reporting.**

---

## 🚆 **Rail Engineering Expertise**

FlexaBrain's competitive advantage lies in its **deep rail electrical engineering knowledge**:

### 🔌 **Traction Power Systems**
- **DC Systems**: 600V, 750V, 1500V, 3000V third rail and overhead
- **AC Systems**: 25kV 50Hz/60Hz, 15kV 16⅔Hz high-speed rail
- **Dual Systems**: Multi-voltage compatibility analysis
- **Components**: Traction converters, choppers, inverters, transformers

### 🚦 **Signaling & Control**
- **Signal References**: 8-digit identification pattern recognition  
- **Control Systems**: ATC, ATS, CBTC, PTC, ERTMS compatibility
- **Interlocking Logic**: Safety-critical circuit validation
- **Communication**: Train-to-wayside, wayside-to-control center

### 🔧 **Component Recognition Patterns**
```typescript
// Traction Converters: A601, A1234B, CONV01
/^(A|CONV|INV|REC)\d+[A-Z]?$/

// Circuit Breakers: CB101, Q205, BR999
/^(CB|Q|BR|MCB)\d+[A-Z]?$/  

// Signal References: 12345678 (8-digit)
/^\d{8}$/

// Transformers: T201, TR305A, TRANS01
/^(TR?|TRANS|TX)\d+[A-Z]?$/
```

### ⚡ **Safety & Standards**
- **Arc Flash Analysis**: IEEE 1584-2018 calculations
- **PPE Categories**: NFPA 70E compliance
- **Rail Standards**: EN 50155, IEC 61375, TSI compliance
- **Grounding Systems**: TN, TT, IT system validation

---

## 🏗️ **Architecture Overview**

```mermaid
graph TB
    A[MCP Client] --> B[FlexaBrain MCP Server]
    B --> C[OCR Service]
    B --> D[Component Classifier]
    B --> E[Electrical Analyzer]
    
    C --> F[Tesseract.js]
    D --> G[Rail Component Database]
    E --> H[Safety Analysis Engine]
    E --> I[Standards Validator]
    E --> J[Maintenance Scheduler]
    
    G --> K[Traction Power Patterns]
    G --> L[Signaling Patterns]  
    G --> M[Control Patterns]
```

### 🧩 **Core Components**

1. **OCR Service** - Tesseract.js with electrical schematic optimizations
2. **Component Classifier** - ML-powered recognition with rail expertise
3. **Electrical Analyzer** - Main orchestrator coordinating all analysis
4. **Safety Engine** - Arc flash, electrical hazard, and risk assessment
5. **Standards Validator** - Automated compliance checking
6. **Maintenance Scheduler** - Predictive maintenance recommendations

---

## 📖 **Usage Examples**

### Example 1: Metro Traction Power Analysis

```typescript
const result = await analyzeElectricalSchematic({
  image_path: './schematics/metro-substation.png',
  analysis_depth: 'comprehensive',
  rail_system_context: {
    system_type: 'METRO',
    voltage_system: '750V DC',
    region: 'EU',
    applicable_standards: ['EN 50155', 'EN 50121']  
  },
  focus_areas: ['safety', 'compliance', 'maintenance']
});

// Rich analysis including:
// - Component inventory (converters, breakers, contactors)
// - Safety analysis (arc flash category, PPE requirements) 
// - Standards compliance (EN 50155 validation)
// - Maintenance schedule (quarterly inspections)
// - Expert recommendations (optimization opportunities)
```

### Example 2: High-Speed Rail Signaling Analysis

```typescript
const signalAnalysis = await analyzeElectricalSchematic({
  image_path: './schematics/ertms-signaling.png',
  analysis_depth: 'standard',
  rail_system_context: {
    system_type: 'HIGH_SPEED', 
    voltage_system: '25kV AC',
    region: 'EU',
    applicable_standards: ['ERTMS', 'TSI', 'CENELEC']
  },
  focus_areas: ['safety', 'compliance']
});

// Specialized analysis for:
// - Signal reference validation (8-digit patterns)
// - ERTMS/ETCS compatibility checking
// - Safety-critical circuit validation
// - EMC compliance assessment
```

### Example 3: Batch Processing with Comparison

```typescript
const batchResults = await batchAnalyzeSchematics({
  input_directory: './project-schematics/',
  file_pattern: '*.png',
  analysis_depth: 'standard',
  generate_comparison: true,
  output_format: 'JSON',
  parallel_processing: true
});

// Comprehensive batch analysis:
// - Individual schematic reports
// - Cross-schematic consistency checking  
// - Design pattern analysis
// - Consolidated recommendations
// - Project-level compliance summary
```

---

## 🔧 **Configuration**

### Environment Variables

```bash
# OCR Configuration
TESSERACT_LANG=eng
TESSERACT_PSM=6
OCR_CONFIDENCE_THRESHOLD=0.6

# Analysis Configuration  
MIN_COMPONENT_CONFIDENCE=0.7
TARGET_ACCURACY=0.85
MAX_PROCESSING_TIME=30000

# Rail System Defaults
DEFAULT_RAIL_SYSTEM=METRO
DEFAULT_VOLTAGE_SYSTEM=1500V_DC
DEFAULT_REGION=US
```

### Custom Standards

```typescript
// Add custom validation standards
const customAnalysis = await validateElectricalStandards({
  image_path: './schematic.png',
  standards: [
    'EN 50155',      // Railway applications - Electronic equipment
    'IEC 61375',     // Train communication network
    'IEEE 1584',     // Arc flash hazard calculation
    'NFPA 70E',      // Electrical safety in workplace
    'CUSTOM-RAIL-001' // Your custom standard
  ],
  custom_criteria: [
    'All 25kV components must have surge protection',
    'Signal circuits require redundant paths',
    'Arc flash boundaries clearly marked'
  ]
});
```

---

## 🧪 **Testing**

FlexaBrain includes comprehensive test coverage:

```bash
# Run all tests
npm test

# Run specific test suites
npm run test:services    # Core service tests
npm run test:tools       # MCP tool tests  
npm run test:integration # End-to-end tests

# Generate coverage report
npm run test:coverage
```

### Test Categories

- **🔧 Unit Tests**: Individual service and component testing
- **🔗 Integration Tests**: MCP tool and workflow testing  
- **⚡ Performance Tests**: Load testing and benchmarking
- **🛡️ Safety Tests**: Error handling and edge case validation
- **🚆 Domain Tests**: Rail engineering expertise validation

---

## 🚀 **Deployment**

### Docker Deployment

```dockerfile
FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY dist/ ./dist/
EXPOSE 3000
CMD ["node", "dist/index.js"]
```

```bash
# Build and run
docker build -t flexabrain-mcp .
docker run -p 3000:3000 flexabrain-mcp
```

### MCP Client Integration

#### Claude Desktop
```json
{
  "mcpServers": {
    "flexabrain": {
      "command": "node",
      "args": ["/path/to/flexabrain-mcp/dist/index.js"],
      "env": {
        "TESSERACT_LANG": "eng"
      }
    }
  }
}
```

#### VS Code MCP Extension
```json
{
  "mcp.servers": [
    {
      "name": "FlexaBrain",
      "command": "node /path/to/flexabrain-mcp/dist/index.js"
    }
  ]
}
```

---

## 📚 **Documentation**

- **[API Reference](./docs/API.md)** - Complete tool documentation
- **[Rail Engineering Guide](./docs/RAIL_ENGINEERING.md)** - Domain expertise details  
- **[Developer Guide](./docs/DEVELOPMENT.md)** - Extension and customization
- **[Safety Guidelines](./docs/SAFETY.md)** - Electrical safety best practices
- **[Standards Reference](./docs/STANDARDS.md)** - Supported standards and compliance

---

## 🤝 **Contributing**

We welcome contributions from the rail engineering and software development communities!

### Development Setup

```bash
git clone https://github.com/your-org/flexabrain-mcp.git
cd flexabrain-mcp
npm install
npm run dev    # Development mode with hot reload
```

### Contribution Areas

- **🚆 Rail Engineering**: Additional component patterns, standards, safety rules
- **🧠 AI/ML**: Enhanced component recognition and classification algorithms  
- **🔧 Tools**: New MCP tools for specialized analysis workflows
- **📖 Documentation**: Usage examples, tutorials, best practices
- **🧪 Testing**: Additional test cases and edge case coverage

---

## 📄 **License**

MIT License - see [LICENSE](LICENSE) file for details.

---

## 🙏 **Acknowledgments**

- **Rail Engineering Community** for domain expertise and validation
- **Tesseract.js Team** for excellent OCR capabilities
- **MCP Protocol Contributors** for the extensible architecture
- **IEC, IEEE, EN Standards Bodies** for comprehensive electrical standards

---

## 📞 **Support & Contact**

- **🐛 Issues**: [GitHub Issues](https://github.com/your-org/flexabrain-mcp/issues)
- **💬 Discussions**: [GitHub Discussions](https://github.com/your-org/flexabrain-mcp/discussions)  
- **📧 Email**: support@flexabrain.com
- **🌐 Website**: [flexabrain.com](https://flexabrain.com)

---

*🧠 **FlexaBrain MCP Server** - Bringing rail electrical engineering expertise to AI-powered schematic analysis.*

*⚡ Intelligence Without Limits*