@flexabrain/mcp-server
Version:
Advanced electrical schematic analysis MCP server with rail engineering expertise
429 lines • 17.5 kB
JavaScript
/**
* FlexaBrain MCP Server - AI Agent Integration Strategy
*
* Integration strategy for Oracle, Sentinel, and Sage agents with
* enhanced PDF schematic processing pipeline for traction generator
* monitoring control systems.
*/
/**
* FlexaBrain Agent Integration Manager
*
* Orchestrates communication between PDF schematic processing pipeline
* and FlexaBrain AI agents (Oracle, Sentinel, Sage).
*/
export class AgentIntegrationManager {
db;
config;
analysisQueue = new Map();
activeAnalyses = new Map();
constructor(database, config) {
this.db = database;
this.config = config;
}
/**
* Process newly extracted schematic data with all enabled agents
*/
async processSchematicData(processingResult) {
const documentId = processingResult.document_id;
// Log processing start
await this.db.logProcessingEvent({
document_id: documentId,
log_level: 'info',
message: 'Starting AI agent analysis pipeline',
severity: 'low'
});
try {
// Create analysis requests for each component
const analysisRequests = [];
for (const page of processingResult.pages) {
for (const component of page.components) {
// Oracle - Predictive Analysis
if (this.config.agents.oracle.enabled) {
analysisRequests.push({
documentId,
componentId: component.id,
analysisType: 'predictive_maintenance',
priority: this.determineComponentPriority(component),
requestedBy: 'schematic_processor'
});
}
// Sentinel - Anomaly Detection
if (this.config.agents.sentinel.enabled) {
analysisRequests.push({
documentId,
componentId: component.id,
analysisType: 'anomaly_detection',
priority: this.determineComponentPriority(component),
requestedBy: 'schematic_processor'
});
}
// Sage - Compliance Analysis
if (this.config.agents.sage.enabled) {
analysisRequests.push({
documentId,
componentId: component.id,
analysisType: 'compliance_check',
priority: this.determineComponentPriority(component),
requestedBy: 'schematic_processor'
});
}
}
}
// Process requests in batches
await this.processAnalysisRequests(analysisRequests);
// Generate document-level insights
await this.generateDocumentLevelAnalysis(documentId);
}
catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
const errorStack = error instanceof Error ? error.stack : undefined;
const logData = {
document_id: documentId,
log_level: 'error',
message: `Agent integration failed: ${errorMessage}`,
severity: 'high'
};
if (errorStack) {
logData.stack_trace = errorStack;
}
await this.db.logProcessingEvent(logData);
throw error;
}
}
/**
* Oracle Agent - Predictive Maintenance Analysis
*/
async analyzeWithOracle(request) {
const startTime = Date.now();
try {
// Get component data
const components = await this.db.getComponentsByDocument(request.documentId);
const targetComponent = request.componentId
? components.find(c => c.id === request.componentId)
: null;
// Oracle predictive analysis based on component type and historical data
const oracleAnalysis = await this.performOracleAnalysis(targetComponent || null, components);
const response = {
requestId: request.documentId,
agentName: 'oracle',
status: 'completed',
results: oracleAnalysis,
confidence: oracleAnalysis.confidence,
processingTime: Date.now() - startTime
};
// Store results in database
if (request.componentId) {
await this.db.createAgentAnalysis({
document_id: request.documentId,
component_id: request.componentId,
agent_name: 'oracle',
analysis_type: request.analysisType,
analysis_results: oracleAnalysis,
confidence_score: oracleAnalysis.confidence,
prediction_data: oracleAnalysis.predictions,
processing_time: response.processingTime,
expires_at: new Date(Date.now() + this.config.agents.oracle.predictionHorizon * 3600000)
});
}
return response;
}
catch (error) {
return {
requestId: request.documentId,
agentName: 'oracle',
status: 'failed',
results: {},
confidence: 0,
processingTime: Date.now() - startTime,
errors: [error instanceof Error ? error.message : String(error)]
};
}
}
/**
* Sentinel Agent - Real-time Monitoring and Anomaly Detection
*/
async analyzeWithSentinel(request) {
const startTime = Date.now();
try {
// Get component data
const components = await this.db.getComponentsByDocument(request.documentId);
const targetComponent = request.componentId
? components.find(c => c.id === request.componentId)
: null;
// Sentinel anomaly detection and monitoring setup
const sentinelAnalysis = await this.performSentinelAnalysis(targetComponent || null, components);
const response = {
requestId: request.documentId,
agentName: 'sentinel',
status: 'completed',
results: sentinelAnalysis,
confidence: sentinelAnalysis.confidence,
processingTime: Date.now() - startTime,
recommendations: sentinelAnalysis.monitoringRecommendations
};
// Store results in database
if (request.componentId) {
await this.db.createAgentAnalysis({
document_id: request.documentId,
component_id: request.componentId,
agent_name: 'sentinel',
analysis_type: request.analysisType,
analysis_results: sentinelAnalysis,
confidence_score: sentinelAnalysis.confidence,
anomaly_data: sentinelAnalysis.anomalies,
processing_time: response.processingTime
});
}
return response;
}
catch (error) {
return {
requestId: request.documentId,
agentName: 'sentinel',
status: 'failed',
results: {},
confidence: 0,
processingTime: Date.now() - startTime,
errors: [error instanceof Error ? error.message : String(error)]
};
}
}
/**
* Sage Agent - Business Intelligence and Compliance Analysis
*/
async analyzeWithSage(request) {
const startTime = Date.now();
try {
// Get document and component data
const document = await this.db.getDocument(request.documentId);
const components = await this.db.getComponentsByDocument(request.documentId);
const targetComponent = request.componentId
? components.find(c => c.id === request.componentId)
: null;
// Sage business intelligence and compliance analysis
const sageAnalysis = await this.performSageAnalysis(document, targetComponent || null, components);
const response = {
requestId: request.documentId,
agentName: 'sage',
status: 'completed',
results: sageAnalysis,
confidence: sageAnalysis.confidence,
processingTime: Date.now() - startTime,
recommendations: sageAnalysis.businessRecommendations
};
// Store results in database
if (request.componentId) {
await this.db.createAgentAnalysis({
document_id: request.documentId,
component_id: request.componentId,
agent_name: 'sage',
analysis_type: request.analysisType,
analysis_results: sageAnalysis,
confidence_score: sageAnalysis.confidence,
business_insights: sageAnalysis.insights,
processing_time: response.processingTime
});
}
return response;
}
catch (error) {
return {
requestId: request.documentId,
agentName: 'sage',
status: 'failed',
results: {},
confidence: 0,
processingTime: Date.now() - startTime,
errors: [error instanceof Error ? error.message : String(error)]
};
}
}
/**
* Process multiple analysis requests in batches
*/
async processAnalysisRequests(requests) {
const batchSize = this.config.processingPipeline.batchSize;
for (let i = 0; i < requests.length; i += batchSize) {
const batch = requests.slice(i, i + batchSize);
if (this.config.processingPipeline.enableParallelProcessing) {
// Process batch in parallel
const promises = batch.map(request => this.processAnalysisRequest(request));
await Promise.allSettled(promises);
}
else {
// Process batch sequentially
for (const request of batch) {
await this.processAnalysisRequest(request);
}
}
}
}
/**
* Process individual analysis request
*/
async processAnalysisRequest(request) {
const requestId = `${request.documentId}-${request.componentId}-${request.analysisType}`;
// Check if analysis is already in progress
if (this.activeAnalyses.has(requestId)) {
return await this.activeAnalyses.get(requestId);
}
// Create analysis promise based on agent
let analysisPromise;
if (request.analysisType.includes('predictive') || request.analysisType.includes('oracle')) {
analysisPromise = this.analyzeWithOracle(request);
}
else if (request.analysisType.includes('anomaly') || request.analysisType.includes('monitoring')) {
analysisPromise = this.analyzeWithSentinel(request);
}
else if (request.analysisType.includes('compliance') || request.analysisType.includes('business')) {
analysisPromise = this.analyzeWithSage(request);
}
else {
// Default to Sage for unknown analysis types
analysisPromise = this.analyzeWithSage(request);
}
// Add timeout wrapper
const timeoutPromise = new Promise((_, reject) => setTimeout(() => reject(new Error('Analysis timeout')), this.config.processingPipeline.analysisTimeout));
this.activeAnalyses.set(requestId, Promise.race([analysisPromise, timeoutPromise]));
try {
const result = await this.activeAnalyses.get(requestId);
this.activeAnalyses.delete(requestId);
return result;
}
catch (error) {
this.activeAnalyses.delete(requestId);
throw error;
}
}
/**
* Determine component analysis priority based on type and safety level
*/
determineComponentPriority(component) {
// Generator components get high priority
if (component.component_type?.includes('generator') || component.component_type?.includes('GEN')) {
return 'high';
}
// Circuit breakers and protection devices get high priority
if (component.component_type?.includes('CB') || component.component_type?.includes('breaker')) {
return 'high';
}
// Control systems get medium priority
if (component.component_type?.includes('control') || component.component_type?.includes('CTRL')) {
return 'medium';
}
// Monitoring points get medium priority
if (component.component_type?.includes('monitor') || component.component_type?.includes('sensor')) {
return 'medium';
}
// Everything else gets low priority
return 'low';
}
/**
* Generate document-level analysis combining all agent insights
*/
async generateDocumentLevelAnalysis(documentId) {
// For now, just create a placeholder document-level analysis
// In a real implementation, this would fetch all analyses and combine them
const combinedInsights = {
oracle_predictions: [],
sentinel_anomalies: [],
sage_compliance: []
};
// Store document-level analysis
await this.db.createAgentAnalysis({
document_id: documentId,
agent_name: 'sage', // Sage handles business-level insights
analysis_type: 'document_summary',
analysis_results: combinedInsights,
confidence_score: 0.85, // Placeholder confidence
business_insights: combinedInsights,
processing_time: 0
});
}
/**
* Oracle-specific analysis logic
*/
async performOracleAnalysis(component, allComponents) {
// Simulated Oracle predictive analysis
return {
confidence: 0.85,
predictions: {
failureProbability: 0.15,
maintenanceWindow: '30-45 days',
recommendedActions: ['Schedule inspection', 'Monitor temperature trends'],
riskFactors: ['Age of component', 'Operating environment']
},
trendAnalysis: {
degradationRate: 'moderate',
expectedLifespan: '5-7 years remaining',
criticalParameters: ['temperature', 'vibration']
}
};
}
/**
* Sentinel-specific analysis logic
*/
async performSentinelAnalysis(component, allComponents) {
// Simulated Sentinel monitoring analysis
return {
confidence: 0.92,
anomalies: {
detected: false,
riskLevel: 'low',
monitoringPoints: ['temperature', 'current', 'vibration']
},
monitoringRecommendations: [
'Set up continuous temperature monitoring',
'Implement vibration analysis',
'Monitor electrical parameters'
],
alertThresholds: {
temperature: { warning: 75, alarm: 85, trip: 95 },
vibration: { warning: 10, alarm: 15, trip: 20 },
current: { warning: 110, alarm: 125, trip: 140 }
}
};
}
/**
* Sage-specific analysis logic
*/
async performSageAnalysis(document, component, allComponents) {
// Simulated Sage business intelligence analysis
return {
confidence: 0.88,
insights: {
complianceStatus: 'compliant',
businessImpact: 'low',
costAnalysis: {
maintenanceCost: 15000,
replacementCost: 75000,
downtimeCost: 50000
}
},
businessRecommendations: [
'Schedule predictive maintenance',
'Consider spare parts inventory',
'Plan maintenance window during low-demand period'
],
complianceChecks: {
safetyStandards: 'passed',
environmentalRegulations: 'passed',
operationalRequirements: 'passed'
}
};
}
/**
* Get analysis status for a document
*/
async getAnalysisStatus(documentId) {
const logs = await this.db.getProcessingLogs(documentId, 'error');
return {
completed: 0, // Placeholder - would count completed analyses
failed: logs.length,
pending: this.analysisQueue.size,
totalInsights: 0 // Placeholder - would count total insights
};
}
}
export default AgentIntegrationManager;
//# sourceMappingURL=agent-integration-strategy.js.map