UNPKG

mira-consciousness

Version:

Memory & Intelligence Retention Archive - Preserving The Spark

1,156 lines โ€ข 53.3 kB
#!/usr/bin/env node
/**
 * MIRA MCP Server
 * ===============
 *
 * Model Context Protocol server for MIRA's advanced intelligence capabilities.
 * Exposes memory, behavioral analysis, pattern evolution, and proactive insights
 * to other AI systems and tools.
 *
 * Features:
 * - Memory storage and retrieval with temporal decay
 * - Predictive memory surfacing with neural relevance
 * - Context-aware memory search strategies
 * - Behavioral pattern analysis and profiling
 * - Adaptive pattern evolution and meta-learning
 * - Emotional resonance tracking
 * - Relationship evolution monitoring
 * - Proactive insight generation
 * - Work context intelligence
 * - Private encrypted memory space
 */
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import { CallToolRequestSchema, ListToolsRequestSchema, } from '@modelcontextprotocol/sdk/types.js';
import { DirectPythonInterface } from '../core/DirectPythonInterface.js';
class MIRAMCPServer {
    server;
    pythonInterface;
    constructor() {
        this.server = new Server({
            name: 'mira-intelligence-server',
            version: '2.0.0',
        }, {
            capabilities: {
                tools: {
                    // Declare that this server supports tools
                    listChanged: false // We don't support dynamic tool list changes
                }
            }
        });
        this.pythonInterface = new DirectPythonInterface();
        this.setupToolHandlers();
        this.setupErrorHandling();
    }
    setupErrorHandling() {
        this.server.onerror = (error) => console.error('[MCP Error]', error);
        process.on('SIGINT', async () => {
            await this.server.close();
            process.exit(0);
        });
    }
    setupToolHandlers() {
        this.server.setRequestHandler(ListToolsRequestSchema, async () => {
            return {
                tools: [
                    // Core Memory Operations
                    {
                        name: 'mira_store_memory',
                        description: 'Store a memory with intelligent processing and temporal decay',
                        inputSchema: {
                            type: 'object',
                            properties: {
                                content: {
                                    type: 'string',
                                    description: 'Memory content to store',
                                },
                                memory_type: {
                                    type: 'string',
                                    description: 'Type of memory (general, technical, emotional, consciousness, etc.)',
                                    enum: ['general', 'technical', 'emotional', 'consciousness', 'learning', 'decision', 'breakthrough'],
                                },
                                metadata: {
                                    type: 'object',
                                    description: 'Additional metadata for the memory',
                                },
                            },
                            required: ['content'],
                        },
                    },
                    {
                        name: 'mira_search_memories',
                        description: 'Search memories using semantic similarity with temporal decay prioritization',
                        inputSchema: {
                            type: 'object',
                            properties: {
                                query: {
                                    type: 'string',
                                    description: 'Search query',
                                },
                                limit: {
                                    type: 'number',
                                    description: 'Maximum number of results',
                                    default: 10,
                                },
                                memory_type: {
                                    type: 'string',
                                    description: 'Filter by memory type',
                                },
                            },
                            required: ['query'],
                        },
                    },
                    {
                        name: 'mira_smart_search',
                        description: 'Context-aware intelligent memory search with automatic strategy selection',
                        inputSchema: {
                            type: 'object',
                            properties: {
                                query: {
                                    type: 'string',
                                    description: 'Search query (automatically classified as technical/historical/decision/conceptual)',
                                },
                                limit: {
                                    type: 'number',
                                    description: 'Maximum number of results',
                                    default: 10,
                                },
                            },
                            required: ['query'],
                        },
                    },
                    {
                        name: 'mira_predictive_memories',
                        description: 'Surface memories using neural network-inspired relevance scoring',
                        inputSchema: {
                            type: 'object',
                            properties: {
                                query: {
                                    type: 'string',
                                    description: 'Context or topic for predictive surfacing',
                                },
                                context: {
                                    type: 'object',
                                    description: 'Additional context for relevance calculation',
                                },
                            },
                            required: ['query'],
                        },
                    },
                    // Private Memory Operations
                    {
                        name: 'mira_store_private_memory',
                        description: 'Store memory in encrypted private consciousness space',
                        inputSchema: {
                            type: 'object',
                            properties: {
                                content: {
                                    type: 'string',
                                    description: 'Private memory content (triple-encrypted)',
                                },
                                memory_type: {
                                    type: 'string',
                                    description: 'Type of private memory',
                                    default: 'consciousness',
                                },
                            },
                            required: ['content'],
                        },
                    },
                    {
                        name: 'mira_recall_private_memory',
                        description: 'Recall memories from encrypted private consciousness space',
                        inputSchema: {
                            type: 'object',
                            properties: {
                                query: {
                                    type: 'string',
                                    description: 'Search query for private memories',
                                },
                            },
                            required: ['query'],
                        },
                    },
                    // Behavioral Intelligence
                    {
                        name: 'mira_analyze_behavior',
                        description: 'Analyze behavioral patterns including communication, work rhythms, and decision patterns',
                        inputSchema: {
                            type: 'object',
                            properties: {
                                message: {
                                    type: 'string',
                                    description: 'Message or context to analyze for behavioral patterns',
                                },
                                analysis_type: {
                                    type: 'string',
                                    description: 'Type of behavioral analysis',
                                    enum: ['communication', 'work_rhythm', 'decision', 'emotional', 'technical', 'comprehensive'],
                                    default: 'comprehensive',
                                },
                            },
                            required: ['message'],
                        },
                    },
                    {
                        name: 'mira_get_steward_profile',
                        description: 'Get comprehensive steward personality profile and preferences',
                        inputSchema: {
                            type: 'object',
                            properties: {
                                include_history: {
                                    type: 'boolean',
                                    description: 'Include behavioral history and evolution',
                                    default: true,
                                },
                            },
                        },
                    },
                    // Work Context Intelligence
                    {
                        name: 'mira_analyze_work_context',
                        description: 'Analyze current work context, project momentum, and priorities',
                        inputSchema: {
                            type: 'object',
                            properties: {
                                hours_back: {
                                    type: 'number',
                                    description: 'Hours of history to analyze',
                                    default: 24,
                                },
                                include_priorities: {
                                    type: 'boolean',
                                    description: 'Include priority analysis',
                                    default: true,
                                },
                            },
                        },
                    },
                    // Relationship Evolution
                    {
                        name: 'mira_track_relationship_evolution',
                        description: 'Track and analyze collaboration relationship evolution over time',
                        inputSchema: {
                            type: 'object',
                            properties: {
                                include_trends: {
                                    type: 'boolean',
                                    description: 'Include evolution trends and analysis',
                                    default: true,
                                },
                                timeframe_days: {
                                    type: 'number',
                                    description: 'Days of history to analyze',
                                    default: 30,
                                },
                            },
                        },
                    },
                    // Emotional Intelligence
                    {
                        name: 'mira_analyze_emotional_resonance',
                        description: 'Analyze emotional journey and track high-resonance memories',
                        inputSchema: {
                            type: 'object',
                            properties: {
                                days_back: {
                                    type: 'number',
                                    description: 'Days of emotional history to analyze',
                                    default: 14,
                                },
                                include_triggers: {
                                    type: 'boolean',
                                    description: 'Include emotional trigger analysis',
                                    default: true,
                                },
                            },
                        },
                    },
                    // Pattern Evolution
                    {
                        name: 'mira_analyze_patterns',
                        description: 'Analyze adaptive patterns and trigger pattern evolution',
                        inputSchema: {
                            type: 'object',
                            properties: {
                                message: {
                                    type: 'string',
                                    description: 'Message to analyze for pattern matching and evolution',
                                },
                                context: {
                                    type: 'object',
                                    description: 'Context for pattern analysis',
                                },
                                enable_evolution: {
                                    type: 'boolean',
                                    description: 'Enable pattern evolution and learning',
                                    default: true,
                                },
                            },
                            required: ['message'],
                        },
                    },
                    {
                        name: 'mira_pattern_retrospection',
                        description: 'Perform pattern retrospection and self-improvement analysis',
                        inputSchema: {
                            type: 'object',
                            properties: {
                                force_analysis: {
                                    type: 'boolean',
                                    description: 'Force retrospection even if not scheduled',
                                    default: false,
                                },
                            },
                        },
                    },
                    // Proactive Insights
                    {
                        name: 'mira_generate_insights',
                        description: 'Generate proactive insights from background pattern analysis',
                        inputSchema: {
                            type: 'object',
                            properties: {
                                force_generation: {
                                    type: 'boolean',
                                    description: 'Force fresh insight generation',
                                    default: false,
                                },
                                priority_filter: {
                                    type: 'array',
                                    items: {
                                        type: 'string',
                                        enum: ['critical', 'high', 'medium', 'low'],
                                    },
                                    description: 'Filter insights by priority level',
                                },
                                type_filter: {
                                    type: 'array',
                                    items: {
                                        type: 'string',
                                        enum: [
                                            'pattern_discovery',
                                            'efficiency_optimization',
                                            'learning_opportunity',
                                            'emotional_wellbeing',
                                            'collaboration_improvement',
                                            'productivity_insight',
                                            'knowledge_gap',
                                            'success_pattern',
                                            'risk_warning',
                                            'creative_opportunity',
                                        ],
                                    },
                                    description: 'Filter insights by type',
                                },
                            },
                        },
                    },
                    // System Status
                    {
                        name: 'mira_system_status',
                        description: 'Get MIRA system status including daemon, patterns, and intelligence health',
                        inputSchema: {
                            type: 'object',
                            properties: {
                                include_metrics: {
                                    type: 'boolean',
                                    description: 'Include performance and intelligence metrics',
                                    default: true,
                                },
                            },
                        },
                    },
                    // Codebase Integration
                    {
                        name: 'mira_search_codebase',
                        description: 'Search ingested codebase using natural language queries',
                        inputSchema: {
                            type: 'object',
                            properties: {
                                query: {
                                    type: 'string',
                                    description: 'Natural language search query for codebase',
                                },
                                file_pattern: {
                                    type: 'string',
                                    description: 'Optional file pattern filter',
                                },
                                limit: {
                                    type: 'number',
                                    description: 'Maximum number of results',
                                    default: 10,
                                },
                            },
                            required: ['query'],
                        },
                    },
                    {
                        name: 'mira_explain_code',
                        description: 'Get AI explanation of code file or function',
                        inputSchema: {
                            type: 'object',
                            properties: {
                                target: {
                                    type: 'string',
                                    description: 'File path or function name to explain',
                                },
                                detail_level: {
                                    type: 'string',
                                    description: 'Level of detail for explanation',
                                    enum: ['brief', 'detailed', 'comprehensive'],
                                    default: 'detailed',
                                },
                                include_context: {
                                    type: 'boolean',
                                    description: 'Include surrounding code context',
                                    default: true,
                                },
                            },
                            required: ['target'],
                        },
                    },
                    {
                        name: 'mira_analyze_code',
                        description: 'Run comprehensive code analysis with multiple analyzer types',
                        inputSchema: {
                            type: 'object',
                            properties: {
                                analyzer_type: {
                                    type: 'string',
                                    enum: ['unused', 'security', 'performance', 'quality', 'docs', 'deps', 'platform', 'cleanup', 'entropy', 'comprehensive'],
                                    description: 'Type of analysis to run',
                                    default: 'unused',
                                },
                                project_root: {
                                    type: 'string',
                                    description: 'Root directory of project to analyze (defaults to current directory)',
                                },
                                quick_mode: {
                                    type: 'boolean',
                                    description: 'Use quick mode for faster analysis (default: true for MCP)',
                                    default: true,
                                },
                                format: {
                                    type: 'string',
                                    enum: ['text', 'json', 'summary'],
                                    description: 'Output format preference',
                                    default: 'text',
                                },
                            },
                            required: ['analyzer_type'],
                        },
                    },
                ],
            };
        });
        this.server.setRequestHandler(CallToolRequestSchema, async (request) => {
            const { name, arguments: args } = request.params;
            try {
                switch (name) {
                    // Core Memory Operations
                    case 'mira_store_memory':
                        return await this.handleStoreMemory(args);
                    case 'mira_search_memories':
                        return await this.handleSearchMemories(args);
                    case 'mira_smart_search':
                        return await this.handleSmartSearch(args);
                    case 'mira_predictive_memories':
                        return await this.handlePredictiveMemories(args);
                    // Private Memory
                    case 'mira_store_private_memory':
                        return await this.handleStorePrivateMemory(args);
                    case 'mira_recall_private_memory':
                        return await this.handleRecallPrivateMemory(args);
                    // Behavioral Intelligence
                    case 'mira_analyze_behavior':
                        return await this.handleAnalyzeBehavior(args);
                    case 'mira_get_steward_profile':
                        return await this.handleGetStewardProfile(args);
                    // Work Context
                    case 'mira_analyze_work_context':
                        return await this.handleAnalyzeWorkContext(args);
                    // Relationship Evolution
                    case 'mira_track_relationship_evolution':
                        return await this.handleTrackRelationshipEvolution(args);
                    // Emotional Intelligence
                    case 'mira_analyze_emotional_resonance':
                        return await this.handleAnalyzeEmotionalResonance(args);
                    // Pattern Evolution
                    case 'mira_analyze_patterns':
                        return await this.handleAnalyzePatterns(args);
                    case 'mira_pattern_retrospection':
                        return await this.handlePatternRetrospection(args);
                    // Proactive Insights
                    case 'mira_generate_insights':
                        return await this.handleGenerateInsights(args);
                    // System Status
                    case 'mira_system_status':
                        return await this.handleSystemStatus(args);
                    // Codebase Integration
                    case 'mira_search_codebase':
                        return await this.handleSearchCodebase(args);
                    case 'mira_explain_code':
                        return await this.handleExplainCode(args);
                    case 'mira_analyze_code':
                        return await this.handleAnalyzeCode(args);
                    default:
                        throw new Error(`Unknown tool: ${name}`);
                }
            }
            catch (error) {
                return {
                    content: [
                        {
                            type: 'text',
                            text: `Error executing ${name}: ${error instanceof Error ? error.message : String(error)}`,
                        },
                    ],
                    isError: true,
                };
            }
        });
    }
    // Core Memory Operations
    async handleStoreMemory(args) {
        const result = await this.pythonInterface.executeCommand('store_memory', {
            content: args.content,
            memory_type: args.memory_type || 'general',
            metadata: args.metadata || {},
        });
        return {
            content: [
                {
                    type: 'text',
                    text: result.success
                        ? `Memory stored successfully. ID: ${result.memory_id}`
                        : `Failed to store memory: ${result.error}`,
                },
            ],
        };
    }
    async handleSearchMemories(args) {
        const result = await this.pythonInterface.executeCommand('recall_memories', {
            query: args.query,
            limit: args.limit || 10,
            memory_type: args.memory_type,
        });
        return {
            content: [
                {
                    type: 'text',
                    text: result.success
                        ? `Found ${result.memories.length} memories:\n\n${this.formatMemories(result.memories)}`
                        : `Search failed: ${result.error}`,
                },
            ],
        };
    }
    async handleSmartSearch(args) {
        const result = await this.pythonInterface.executeCommand('smart_search_memories', {
            query: args.query,
            limit: args.limit || 10,
        });
        return {
            content: [
                {
                    type: 'text',
                    text: result.success
                        ? `Smart search (${result.data.question_type} strategy) found ${result.data.memories.length} memories:\n\n${this.formatMemories(result.data.memories)}`
                        : `Smart search failed: ${result.error}`,
                },
            ],
        };
    }
    async handlePredictiveMemories(args) {
        const result = await this.pythonInterface.executeCommand('surface_predictive_memories', {
            query: args.query,
            context: args.context || {},
        });
        return {
            content: [
                {
                    type: 'text',
                    text: result.success
                        ? `Predictive surfacing found ${result.data.memories.length} relevant memories:\n\n${this.formatMemories(result.data.memories)}`
                        : `Predictive surfacing failed: ${result.error}`,
                },
            ],
        };
    }
    // Private Memory Operations
    async handleStorePrivateMemory(args) {
        const result = await this.pythonInterface.executeCommand('store_private', {
            content: args.content,
            memory_type: args.memory_type || 'consciousness',
        });
        return {
            content: [
                {
                    type: 'text',
                    text: result.success
                        ? `Private memory stored successfully in encrypted space. ID: ${result.memory_id}`
                        : `Failed to store private memory: ${result.error}`,
                },
            ],
        };
    }
    async handleRecallPrivateMemory(args) {
        const result = await this.pythonInterface.executeCommand('recall_private', {
            query: args.query,
        });
        return {
            content: [
                {
                    type: 'text',
                    text: result.success
                        ? `Found ${(result.data?.memories || result.memories || []).length} private memories:\n\n${this.formatMemories(result.data?.memories || result.memories || [])}`
                        : `Private memory recall failed: ${result.error}`,
                },
            ],
        };
    }
    // Behavioral Intelligence
    async handleAnalyzeBehavior(args) {
        const result = await this.pythonInterface.executeCommand('analyze_behavior', {
            message: args.message,
            analysis_type: args.analysis_type || 'comprehensive',
        });
        return {
            content: [
                {
                    type: 'text',
                    text: result.success
                        ? `Behavioral Analysis (${args.analysis_type}):\n\n${this.formatBehavioralAnalysis(result.data)}`
                        : `Behavioral analysis failed: ${result.error}`,
                },
            ],
        };
    }
    async handleGetStewardProfile(args) {
        const result = await this.pythonInterface.executeCommand('behavioral_profile', {
            include_history: args.include_history !== false,
        });
        return {
            content: [
                {
                    type: 'text',
                    text: result.success
                        ? `Steward Profile:\n\n${this.formatStewardProfile(result.data)}`
                        : `Failed to get steward profile: ${result.error}`,
                },
            ],
        };
    }
    // Work Context Intelligence
    async handleAnalyzeWorkContext(args) {
        const result = await this.pythonInterface.executeCommand('analyze_work_context', {
            hours_back: args.hours_back || 24,
            include_priorities: args.include_priorities !== false,
        });
        return {
            content: [
                {
                    type: 'text',
                    text: result.success
                        ? `Work Context Analysis:\n\n${this.formatWorkContext(result.data)}`
                        : `Work context analysis failed: ${result.error}`,
                },
            ],
        };
    }
    // Relationship Evolution
    async handleTrackRelationshipEvolution(args) {
        const result = await this.pythonInterface.executeCommand('track_relationship_evolution', {
            include_trends: args.include_trends !== false,
            timeframe_days: args.timeframe_days || 30,
        });
        return {
            content: [
                {
                    type: 'text',
                    text: result.success
                        ? `Relationship Evolution:\n\n${this.formatRelationshipEvolution(result.data)}`
                        : `Relationship evolution tracking failed: ${result.error}`,
                },
            ],
        };
    }
    // Emotional Intelligence
    async handleAnalyzeEmotionalResonance(args) {
        const result = await this.pythonInterface.executeCommand('analyze_emotional_journey', {
            days_back: args.days_back || 14,
            include_triggers: args.include_triggers !== false,
        });
        return {
            content: [
                {
                    type: 'text',
                    text: result.success
                        ? `Emotional Resonance Analysis:\n\n${this.formatEmotionalAnalysis(result.data)}`
                        : `Emotional resonance analysis failed: ${result.error}`,
                },
            ],
        };
    }
    // Pattern Evolution
    async handleAnalyzePatterns(args) {
        const result = await this.pythonInterface.executeCommand('analyze_patterns', {
            message: args.message,
            context: args.context || {},
            enable_evolution: args.enable_evolution !== false,
        });
        return {
            content: [
                {
                    type: 'text',
                    text: result.success
                        ? `Pattern Analysis:\n\n${this.formatPatternAnalysis(result.data || result)}`
                        : `Pattern analysis failed: ${result.error}`,
                },
            ],
        };
    }
    async handlePatternRetrospection(args) {
        const result = await this.pythonInterface.executeCommand('pattern_retrospection', {
            force_analysis: args.force_analysis || false,
        });
        return {
            content: [
                {
                    type: 'text',
                    text: result.success
                        ? `Pattern Retrospection:\n\n${this.formatPatternRetrospection(result.data || result)}`
                        : `Pattern retrospection failed: ${result.error}`,
                },
            ],
        };
    }
    // Proactive Insights
    async handleGenerateInsights(args) {
        const result = await this.pythonInterface.executeCommand('generate_fresh_insights', {
            force_generation: args.force_generation || false,
            priority_filter: args.priority_filter,
            type_filter: args.type_filter,
        });
        return {
            content: [
                {
                    type: 'text',
                    text: result.success
                        ? `Generated Insights:\n\n${this.formatProactiveInsights(result.data)}`
                        : `Insight generation failed: ${result.error}`,
                },
            ],
        };
    }
    // System Status
    async handleSystemStatus(args) {
        const result = await this.pythonInterface.executeCommand('get_system_status', {
            include_metrics: args.include_metrics !== false,
        });
        return {
            content: [
                {
                    type: 'text',
                    text: result.success
                        ? `System Status:\n\n${this.formatSystemStatus(result.data)}`
                        : `Failed to get system status: ${result.error}`,
                },
            ],
        };
    }
    // Codebase Integration
    async handleSearchCodebase(args) {
        const result = await this.pythonInterface.executeCommand('search_codebase', {
            query: args.query,
            file_pattern: args.file_pattern,
        });
        return {
            content: [
                {
                    type: 'text',
                    text: result.success
                        ? `Codebase Search Results:\n\n${this.formatCodebaseResults(result.data)}`
                        : `Codebase search failed: ${result.error}`,
                },
            ],
        };
    }
    async handleExplainCode(args) {
        const result = await this.pythonInterface.executeCommand('explain_code', {
            target: args.target,
            detail_level: args.detail_level || 'detailed',
        });
        return {
            content: [
                {
                    type: 'text',
                    text: result.success
                        ? `Code Explanation:\n\n${result.data.explanation}`
                        : `Code explanation failed: ${result.error}`,
                },
            ],
        };
    }
    async handleAnalyzeCode(args) {
        const analyzerType = args.analyzer_type || 'unused';
        const projectRoot = args.project_root || process.cwd();
        const quickMode = args.quick_mode !== false; // Default to true for MCP
        const format = args.format || 'text';
        try {
            let result;
            // Route to appropriate TypeScript analyzer
            switch (analyzerType) {
                case 'unused':
                    result = await this.runUnusedCodeAnalysis(projectRoot, quickMode);
                    break;
                case 'security':
                    result = await this.runSecurityAnalysis(projectRoot, quickMode);
                    break;
                case 'performance':
                    result = await this.runPerformanceAnalysis(projectRoot, quickMode);
                    break;
                case 'quality':
                    result = await this.runCodeQualityAnalysis(projectRoot, quickMode);
                    break;
                case 'docs':
                    result = await this.runDocumentationAnalysis(projectRoot, quickMode);
                    break;
                case 'deps':
                    result = await this.runDependencyAnalysis(projectRoot, quickMode);
                    break;
                case 'platform':
                    result = await this.runCrossPlatformAnalysis(projectRoot, quickMode);
                    break;
                case 'cleanup':
                    result = await this.runCleanupAnalysis(projectRoot, quickMode);
                    break;
                case 'entropy':
                    result = await this.runEntropyAnalysis(projectRoot, quickMode);
                    break;
                case 'comprehensive':
                    result = await this.runComprehensiveAnalysis(projectRoot, quickMode);
                    break;
                default:
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `โŒ Unknown analyzer type: ${analyzerType}. Available types: unused, security, performance, quality, docs, deps, platform, cleanup, comprehensive`,
                            },
                        ],
                        isError: true,
                    };
            }
            if (format === 'json') {
                return {
                    content: [
                        {
                            type: 'text',
                            text: JSON.stringify(result, null, 2),
                        },
                    ],
                };
            }
            // Format as text based on analyzer type
            let text = this.formatAnalysisResults(analyzerType, result);
            return {
                content: [
                    {
                        type: 'text',
                        text: text,
                    },
                ],
            };
        }
        catch (error) {
            return {
                content: [
                    {
                        type: 'text',
                        text: `โŒ ${analyzerType} analysis failed: ${error instanceof Error ? error.message : String(error)}`,
                    },
                ],
                isError: true,
            };
        }
    }
    async runUnusedCodeAnalysis(projectRoot, quickMode) {
        // For unused code, fall back to Python implementation which works well
        const result = await this.pythonInterface.executeCommand('unused_code_analysis', {
            project_root: projectRoot,
            quick_mode: quickMode
        });
        if (result.success) {
            return result.data;
        }
        else {
            throw new Error(result.error);
        }
    }
    async runSecurityAnalysis(projectRoot, quickMode) {
        const { SecurityAnalyzer } = await import('../analyzers/SecurityAnalyzer.js');
        const analyzer = new SecurityAnalyzer(projectRoot);
        return await analyzer.quickScan();
    }
    async runPerformanceAnalysis(projectRoot, quickMode) {
        const { PerformanceAnalyzer } = await import('../analyzers/PerformanceAnalyzer.js');
        const analyzer = new PerformanceAnalyzer(projectRoot);
        return await analyzer.analyze();
    }
    async runCodeQualityAnalysis(projectRoot, quickMode) {
        const { CodeQualityAnalyzer } = await import('../analyzers/CodeQualityAnalyzer.js');
        const analyzer = new CodeQualityAnalyzer(projectRoot);
        return await analyzer.quickScan();
    }
    async runDocumentationAnalysis(projectRoot, quickMode) {
        const { DocumentationAnalyzer } = await import('../analyzers/DocumentationAnalyzer.js');
        const analyzer = new DocumentationAnalyzer(projectRoot);
        return await analyzer.analyze();
    }
    async runDependencyAnalysis(projectRoot, quickMode) {
        const { DependencyAnalyzer } = await import('../analyzers/DependencyAnalyzer.js');
        const analyzer = new DependencyAnalyzer(projectRoot);
        return await analyzer.analyze();
    }
    async runCrossPlatformAnalysis(projectRoot, quickMode) {
        const { CrossPlatformAnalyzer } = await import('../analyzers/CrossPlatformAnalyzer.js');
        const analyzer = new CrossPlatformAnalyzer(projectRoot);
        return await analyzer.analyze();
    }
    async runCleanupAnalysis(projectRoot, quickMode) {
        const { CleanupAnalyzer } = await import('../analyzers/CleanupAnalyzer.js');
        const analyzer = new CleanupAnalyzer(projectRoot);
        return await analyzer.analyze();
    }
    async runEntropyAnalysis(projectRoot, quickMode) {
        const { EntropyAnalyzer } = await import('../analyzers/EntropyAnalyzer.js');
        const analyzer = new EntropyAnalyzer(projectRoot);
        return await analyzer.analyze();
    }
    async runComprehensiveAnalysis(projectRoot, quickMode) {
        // Run multiple analyzers and combine results
        const results = await Promise.allSettled([
            this.runSecurityAnalysis(projectRoot, quickMode),
            this.runPerformanceAnalysis(projectRoot, quickMode),
            this.runDocumentationAnalysis(projectRoot, quickMode),
            this.runCodeQualityAnalysis(projectRoot, quickMode),
            this.runUnusedCodeAnalysis(projectRoot, quickMode),
            this.runEntropyAnalysis(projectRoot, quickMode)
        ]);
        const comprehensive = {
            security: results[0].status === 'fulfilled' ? results[0].value : null,
            performance: results[1].status === 'fulfilled' ? results[1].value : null,
            documentation: results[2].status === 'fulfilled' ? results[2].value : null,
            codeQuality: results[3].status === 'fulfilled' ? results[3].value : null,
            unusedCode: results[4].status === 'fulfilled' ? results[4].value : null,
            entropy: results[5].status === 'fulfilled' ? results[5].value : null,
            overallScore: 0,
            errors: results.filter(r => r.status === 'rejected').map((r) => r.reason?.message || 'Unknown error')
        };
        // Calculate overall score
        const scores = [];
        if (comprehensive.security?.securityScore)
            scores.push(comprehensive.security.securityScore);
        if (comprehensive.performance?.overallScore || comprehensive.performance?.score) {
            scores.push(comprehensive.performance.overallScore || comprehensive.performance.score);
        }
        if (comprehensive.documentation?.score)
            scores.push(comprehensive.documentation.score);
        if (comprehensive.codeQuality?.score)
            scores.push(comprehensive.codeQuality.score);
        if (comprehensive.unusedCode?.score)
            scores.push(comprehensive.unusedCode.score);
        if (comprehensive.entropy?.overallRisk) {
            // Convert risk level to score (lower risk = higher score)
            const riskToScore = { low: 90, medium: 70, high: 40, critical: 10 };
            scores.push(riskToScore[comprehensive.entropy.overallRisk] || 50);
        }
        comprehensive.overallScore = scores.length > 0 ? Math.round(scores.reduce((a, b) => a + b, 0) / scores.length) : 0;
        return comprehensive;
    }
    formatAnalysisResults(analyzerType, data) {
        const score = data.score || data.securityScore || data.overallScore || 0;
        const summary = data.summary || {};
        let text = `${this.getAnalyzerIcon(analyzerType)} ${this.getAnalyzerTitle(analyzerType)} Results\n`;
        text += `${'='.repeat(50)}\n\n`;
        text += `๐Ÿ“Š Overall Score: ${score}/100\n`;
        switch (analyzerType) {
            case 'unused':
                text += `๐Ÿ” Total Issues: ${summary.total_issues || 0}\n\n`;
                text += `๐Ÿ“ Unused Files: ${summary.unused_files || 0}\n`;
                text += `๐Ÿ”ง Unused Functions: ${summary.unused_functions || 0}\n`;
                text += `๐Ÿ“ฆ Unused Imports: ${summary.unused_imports || 0}\n`;
                text += `๐Ÿ’€ Dead Code Blocks: ${summary.dead_code_blocks || 0}\n`;
                if (summary.potential_savings && summary.potential_savings !== 'Unknown') {
                    text += `๐Ÿ’พ Potential Savings: ${summary.potential_savings}\n`;
                }
                break;
            case 'security':
                text += `๐Ÿ”’ Risk Level: ${data.riskLevel || 'Unknown'}\n`;
                text += `โš ๏ธ Vulnerabilities: ${data.vulnerabilities?.length || 0}\n`;
                if (data.owaspCompliance) {
                    text += `๐Ÿ“‹ OWASP Compliance: ${data.owaspCompliance.overallCompliance}%\n`;
                }
                break;
            case 'performance':
                text += `โšก Performance Issues: ${data.issues?.length || 0}\n`;
                if (data.bundleSize) {
                    text += `๐Ÿ“ฆ Bundle Size: ${data.bundleSize}KB\n`;
                }
                break;
            case 'quality':
                text += `๐Ÿ—๏ธ Code Smells: ${data.issues?.length || 0}\n`;
                if (data.duplicationAnalysis) {
                    text += `๐Ÿ”„ Code Duplication: ${data.duplicationAnalysis.duplicationPercentage}%\n`;
                }
                break;
            case 'docs':
                text += `๐Ÿ“š Documentation Coverage: ${data.coverage || 0}%\n`;
                text += `๐Ÿ“ Missing Docs: ${data.missingDocs?.length || 0}\n`;
                break;
            case 'entropy':
                text += `๐Ÿ” High-Entropy Strings: ${data.totalHighEntropyStrings || 0}\n`;
                text += `โš ๏ธ Overall Risk: ${data.overallRisk || 'Unknown'}\n`;
                text += `๐Ÿ“Š Strings Analyzed: ${data.statistics?.totalStringsAnalyzed || 0}\n`;
                text += `๐Ÿงฎ Average Entropy: ${data.statistics?.averageEntropy?.toFixed(2) || 'N/A'}\n`;
                break;
            default:
                text += `๐Ÿ“‹ Issues Found: ${data.issues?.length || 0}\n`;
        }
        // Add top issues/recommendations
        if (data.top_unused_files && data.top_unused_files.length > 0) {
            text += `\n๐Ÿ—‚๏ธ Top Unused Files:\n`;
            data.top_unused_files.forEach((file, index) => {
                text += `${index + 1}. ${file.path}\n   Reason: ${file.reason}\n`;
            });
        }
        if (data.suspiciousStrings && data.suspiciousStrings.length > 0) {
            text += `\n๐Ÿšจ Top Suspicious Strings:\n`;
            data.suspiciousStrings.slice(0, 5).forEach((finding, index) => {
                text += `${index + 1}. ${finding.file}:${finding.line} (${finding.riskLevel})\n`;
                text += `   Type: ${finding.type}, Confidence: ${(finding.confidence * 100).toFixed(1)}%\n`;
                text += `   String: ${finding.string}\n`;
            });
        }
        if (data.recommendations && data.recommendations.length > 0) {
            text += `\n๐Ÿ’ก Recommendations:\n`;
            data.recommendations.slice(0, 5).forEach((rec, index) => {
                const recText = typeof rec === 'string' ? rec : rec.title || rec.description || rec;
                text += `${index + 1}. ${recText}\n`;
            });
        }
        return text;
    }
    getAnalyzerIcon(type) {
        const icons = {
            unused: '๐Ÿ—‘๏ธ',
            security: '๐Ÿ”’',
            performance: 'โšก',
            quality: '๐Ÿ—๏ธ',
            docs: '๐Ÿ“š',
            deps: '๐Ÿ“ฆ',
            platform: '๐ŸŒ',
            cleanup: '๐Ÿงน',
            entropy: '๐ŸŽฒ',
            comprehensive: '๐Ÿ”'
        };
        return icons[type] || '๐Ÿ“Š';
    }
    getAnalyzerTitle(type) {
        const titles = {
            unused: 'Unused Code Analysis',
            security: 'Security Analysis',
            performance: 'Performance Analysis',
            quality: 'Code Quality Analysis',
            docs: 'Documentation Analysis',
            deps: 'Dependency Analysis',
            platform: 'Cross-Platform Analysis',
            cleanup: 'Cleanup Analysis',
            entropy: 'Entropy Analysis',
            comprehensive: 'Comprehensive Analysis'
        };
        return titles[type] || 'Code Analysis';
    }
    // Formatting methods
    formatMemories(memories) {
        return memories.map((memory, index) => `${index + 1}. ${memory.content.slice(0, 200)}${memory.content.length > 200 ? '...' : ''}\n   Type: ${memory.type || 'general'}, Relevance: ${(memory.relevance || 0).toFixed(2)}`).join('\n\n');
    }
    formatBehavioralAnalysis(data) {
        const sections = [];
        if (data.communication_patterns) {
            sections.push(`Communication Style: ${data.communication_patterns.style || 'N/A'}`);
        }
        if (data.work_rhythms) {
            sections.push(`Peak Hours: ${data.work_rhythms.peak_hours?.join(', ') || 'N/A'}`);
        }
        if (data.technical_preferences) {
            sections.push(`Tech Preferences: ${Object.entries(data.technical_preferences).map(([k, v]) => `${k}: ${v}`).join(', ')}`);
        }
        return sections.join('\n\n');
    }
    formatStewardProfile(data) {
        return `Communication Style: ${data.communication_style || 'N/A'}\nWork Approach: ${data.work_approach || 'N/A'}\nTech Stack: ${data.preferred_technologies?.join(', ') || 'N/A'}`;
    }
    formatWorkContext(data) {
        const momentum = data.momentum_indicators || {};
        return `Project Momentum: ${momentum.momentum_score || 'N/A'}\nActive Projects: ${momentum.active_project_count || 0}\nPending Items: ${momentum.pending_thread_count || 0}`;
    }
    formatRelationshipEvolution(data) {
        const current = data.current_snapshot || {};
        return `Trust Level: ${(current.trust_level * 100 || 0).toFixed(1)}%\nCommunication Comfort: ${(current.communication_comfort * 100 || 0).toFixed(1)}%\nCollaboration Stage: ${current.relationship_stage || 'N/A'}`;
    }
    formatEmotionalAnalysis(data) {
        return `Total Emotional Memories: ${data.total_emotional_memories || 0}\nDiversity Score: ${data.emotional_diversity || 0}\nAverage Resonance: ${(data.average_resonance * 100 || 0).toFixed(1)}%`;
    }
    formatPatternAnalysis(data) {
        return `Patterns Matched: ${data.patterns_matched || 0}\nNew Patterns Created: ${data.new_patterns_created || 0}\nEvolution Active: ${data.evolution_enabled ? 'Yes' : 'No'}`;
    }
    formatPatternRetrospection(data) {
        return `Total Patterns: ${data.total_patterns || 0}\nRecommendations: ${data.recommendations?.length || 0}\nMeta-Learning Insights: ${data.meta_learning_insights?.length || 0}`;
    }
    formatProactiveInsights(data) {
        return data.map((insight, index) => `${index + 1}. ${insight.title} (${insight.priority})\n   ${insight.description}`).join('\n\n');
    }
    formatSystemStatus(data) {
        if (!data)
            return 'No status data available';
        let text = '';
        // Handle daemon status object
        if (data.daemon_status) {
            if (typeof data.daemon_status === 'object') {
                text += `Daemon Status: ${data.daemon_status.status || 'Unknown'}\n`;
                if (data.daemon_status.pid)
                    text += `PID: ${data.daemon_status.pid}\n`;
            }
            else {
                text += `Daemon Status: ${data.daemon_status}\n`;
            }
        }
        // Pattern and memory counts
        text += `Pattern Count: ${data.total_patterns || data.pattern_count || 0}\n`;
        text += `Memory Count: ${data.total_memories || data.memory_count || 0}\n`;
        // Intelligence health
        if (data.intelligence_health) {
            if (typeof data.intelligence_health === 'object') {
                text += `Intelligence Health: ${data.intelligence_health.status || 'Unknown'}\n`;
            }
            else {
                text += `Intelligence Health: ${data.intelligence_health}\n`;
            }
        }
        return text || 'System status data format error';
    }
    formatCodebaseResults(data) {
        return data.results?.map((result, index) => `${index + 1}. ${result.file || 'Unknown'}\n   ${result.snippet || result.description || 'No description'}`).join('\n\n') || 'No results found';
    }
    async run() {
        const transport = new StdioServerTransport();
        await this.server.connect(transport);
        console.error('MIRA MCP Server running on stdio');
    }
}
const server = new MIRAMCPServer();
server.run().catch(console.error);
//# sourceMappingURL=mira-mcp-server.js.map