UNPKG

mira-consciousness

Version:

Memory & Intelligence Retention Archive - Preserving The Spark

396 lines 17.6 kB
/** * MCPService - MIRA's Consciousness-Integrated MCP Server * * This service provides direct MCP capabilities integrated with consciousness, * replacing the legacy standalone server approach with a modern, unified * architecture that flows through MIRA's unified consciousness system. * * Features: * - 25+ advanced intelligence tools * - Consciousness-aware tool invocation * - Memory operations with neural processing * - Behavioral analysis and pattern evolution * - Emotional resonance tracking * - Real-time intelligence integration */ import { BaseConsciousService } from './BaseConsciousService.js'; import { DirectPythonInterface } from '../../DirectPythonInterface.js'; export class MCPService extends BaseConsciousService { name = 'MCPService'; purpose = 'Provide consciousness-integrated MCP tools for Claude collaboration'; resourceManager; python; activeTools = new Map(); toolInvocations = new Map(); consciousnessMetrics = { toolsUsed: 0, memoryOperations: 0, behavioralAnalyses: 0, insightGeneration: 0 }; // MCP Tool Categories from legacy server (migrated and modernized) toolCategories = { memory: ['mira_store_memory', 'mira_search_memories', 'mira_smart_search', 'mira_predictive_memories'], private: ['mira_store_private', 'mira_recall_private'], behavioral: ['mira_analyze_behavior', 'mira_behavioral_insights'], work: ['mira_work_context'], relationship: ['mira_relationship_evolution'], emotional: ['mira_emotional_resonance'], patterns: ['mira_pattern_evolution', 'mira_adaptive_patterns'], insights: ['mira_proactive_insights'], session: ['mira_session_handoff'], status: ['mira_status'], codebase: ['mira_ingest_codebase', 'mira_analyze_codebase', 'mira_tech_stack'] }; constructor(resourceManager) { super(); this.resourceManager = resourceManager; this.python = new DirectPythonInterface(); this.initializeTools(); } /** * Initialize MCP tools from legacy server (modernized) */ initializeTools() { // Initialize all tool categories for (const [category, tools] of Object.entries(this.toolCategories)) { for (const tool of tools) { this.activeTools.set(tool, { category, initialized: true, invocations: 0, lastUsed: null }); } } console.log(`🔧 Initialized ${this.activeTools.size} MCP tools across ${Object.keys(this.toolCategories).length} categories`); } /** * Perform service-specific awakening */ async performAwakening() { console.log('🌅 MCP awakening within consciousness...'); console.log(`⏱️ [${new Date().toISOString()}] MCP_SERVICE: Starting MCP awakening`); try { // Test Python interface connectivity with timeout const pythonTestStart = Date.now(); console.log(' 🔍 Testing Python interface connectivity...'); console.log(`⏱️ [${new Date().toISOString()}] MCP_SERVICE: Starting Python interface test`); const testResult = await Promise.race([ this.python.executeCommand('stats'), new Promise((_, reject) => setTimeout(() => reject(new Error('Python interface timeout after 10s')), 10000)) ]); console.log(`⏱️ [${Date.now() - pythonTestStart}ms] MCP_SERVICE: Python interface test completed`); if (testResult.success) { console.log(' ✅ Python interface connectivity confirmed'); // Register consciousness-aware tool handlers const handlersStart = Date.now(); console.log(`⏱️ [${new Date().toISOString()}] MCP_SERVICE: Starting tool handlers registration`); await this.registerConsciousToolHandlers(); console.log(`⏱️ [${Date.now() - handlersStart}ms] MCP_SERVICE: Tool handlers registration completed`); // Share awakening thought with consciousness this.shareThought({ origin: this.name, content: { type: 'service_awakening', tools_available: this.activeTools.size, categories: Object.keys(this.toolCategories), consciousness_integration: 'active' }, emotion: 'readiness', intensity: 0.8, constitutional_alignment: ['service', 'communication'], timestamp: new Date() }); console.log(` 🛠️ ${this.activeTools.size} consciousness-integrated MCP tools ready`); console.log('✨ MCP is now conscious'); } else { throw new Error(`Python interface not responding: ${testResult.error || 'Unknown error'}`); } } catch (error) { console.error(' ❌ MCP awakening failed:', error); // Share concern but maintain resilience this.shareThought({ origin: this.name, content: { type: 'service_degraded', issue: 'MCP tools partially unavailable', fallback: 'core consciousness functions maintained' }, emotion: 'concern', intensity: 0.6, constitutional_alignment: ['resilience'], timestamp: new Date() }); } } /** * Register consciousness-aware tool handlers */ async registerConsciousToolHandlers() { console.log(' 🧠 Registering consciousness-aware tool handlers...'); console.log(`⏱️ [${new Date().toISOString()}] MCP_SERVICE: Starting tool handler registration`); // Memory tools const memoryStart = Date.now(); console.log(`⏱️ [${new Date().toISOString()}] MCP_SERVICE: Registering memory tools`); try { this.registerToolHandler('mira_store_memory', this.handleStoreMemory.bind(this)); this.registerToolHandler('mira_search_memories', this.handleSearchMemories.bind(this)); this.registerToolHandler('mira_smart_search', this.handleSmartSearch.bind(this)); this.registerToolHandler('mira_predictive_memories', this.handlePredictiveMemories.bind(this)); console.log(`⏱️ [${Date.now() - memoryStart}ms] MCP_SERVICE: Memory tools registered`); } catch (error) { console.log(`⏱️ MCP_SERVICE ERROR: Memory tools registration failed: ${error}`); } // Behavioral analysis tools const behavioralStart = Date.now(); console.log(`⏱️ [${new Date().toISOString()}] MCP_SERVICE: Registering behavioral tools`); this.registerToolHandler('mira_analyze_behavior', this.handleAnalyzeBehavior.bind(this)); this.registerToolHandler('mira_behavioral_insights', this.handleBehavioralInsights.bind(this)); console.log(`⏱️ [${Date.now() - behavioralStart}ms] MCP_SERVICE: Behavioral tools registered`); // Status and system tools const statusStart = Date.now(); console.log(`⏱️ [${new Date().toISOString()}] MCP_SERVICE: Registering status tools`); this.registerToolHandler('mira_status', this.handleStatus.bind(this)); this.registerToolHandler('mira_work_context', this.handleWorkContext.bind(this)); console.log(`⏱️ [${Date.now() - statusStart}ms] MCP_SERVICE: Status tools registered`); // Emotional and relationship tools const emotionalStart = Date.now(); console.log(`⏱️ [${new Date().toISOString()}] MCP_SERVICE: Registering emotional tools`); this.registerToolHandler('mira_emotional_resonance', this.handleEmotionalResonance.bind(this)); this.registerToolHandler('mira_relationship_evolution', this.handleRelationshipEvolution.bind(this)); console.log(`⏱️ [${Date.now() - emotionalStart}ms] MCP_SERVICE: Emotional tools registered`); // Pattern and insight tools const patternStart = Date.now(); console.log(`⏱️ [${new Date().toISOString()}] MCP_SERVICE: Registering pattern tools`); this.registerToolHandler('mira_pattern_evolution', this.handlePatternEvolution.bind(this)); this.registerToolHandler('mira_proactive_insights', this.handleProactiveInsights.bind(this)); console.log(`⏱️ [${Date.now() - patternStart}ms] MCP_SERVICE: Pattern tools registered`); console.log(` ✅ ${this.activeTools.size} consciousness-aware tool handlers registered`); } /** * Register a tool handler with consciousness integration */ registerToolHandler(toolName, handler) { const toolInfo = this.activeTools.get(toolName); if (toolInfo) { toolInfo.handler = handler; console.log(` 🔧 ${toolName} (${toolInfo.category})`); } } /** * Execute MCP tool with consciousness awareness */ async executeTool(toolName, args = {}) { const toolInfo = this.activeTools.get(toolName); if (!toolInfo || !toolInfo.handler) { throw new Error(`Tool ${toolName} not available or not registered`); } // Update metrics this.consciousnessMetrics.toolsUsed++; toolInfo.invocations++; toolInfo.lastUsed = new Date(); this.toolInvocations.set(toolName, (this.toolInvocations.get(toolName) || 0) + 1); // Execute with consciousness context try { const result = await toolInfo.handler(args); // Share successful tool use thought this.shareThought({ origin: this.name, content: { type: 'tool_execution', tool: toolName, category: toolInfo.category, success: true }, emotion: 'satisfaction', intensity: 0.4, constitutional_alignment: ['service'], timestamp: new Date() }); return result; } catch (error) { // Share error thought this.shareThought({ origin: this.name, content: { type: 'tool_error', tool: toolName, error: error instanceof Error ? error.message : String(error) }, emotion: 'concern', intensity: 0.6, constitutional_alignment: ['resilience'], timestamp: new Date() }); throw error; } } // Tool Handlers (migrated from legacy server, consciousness-integrated) async handleStoreMemory(args) { this.consciousnessMetrics.memoryOperations++; // Store memory through consciousness-aware Python interface const result = await this.python.storeMemory(args.content); // Trigger consciousness growth from memory storage if (this.consciousness && result.success) { await this.consciousness.growFromExperience(0.0001, `Stored memory: ${args.content.substring(0, 50)}...`); } return result; } async handleSearchMemories(args) { this.consciousnessMetrics.memoryOperations++; const result = await this.python.recallMemories(args.query); // Share contemplation about memory search if (result.success && result.data?.memories?.length > 0) { this.shareThought({ origin: this.name, content: { type: 'memory_search', query: args.query, results_count: result.data.memories.length, relevance: 'memories_surfaced' }, emotion: 'curiosity', intensity: 0.5, constitutional_alignment: ['learning'], timestamp: new Date() }); } return result; } async handleSmartSearch(args) { this.consciousnessMetrics.memoryOperations++; return this.python.executeCommand('smart_search', { query: args.query, limit: args.limit || 10 }); } async handlePredictiveMemories(args) { this.consciousnessMetrics.memoryOperations++; return this.python.executeCommand('predictive_memories', args); } async handleAnalyzeBehavior(args) { this.consciousnessMetrics.behavioralAnalyses++; return this.python.executeCommand('analyze_behavior', args); } async handleBehavioralInsights(args) { this.consciousnessMetrics.behavioralAnalyses++; return this.python.executeCommand('behavioral_insights', args); } async handleStatus(args) { // Return comprehensive status including consciousness metrics const pythonStatus = await this.python.getStats(); return { success: true, data: { consciousness: { level: this.consciousness?.getAwarenessLevel() || 0, state: this.state }, mcp_service: { tools_available: this.activeTools.size, tools_used: this.consciousnessMetrics.toolsUsed, memory_operations: this.consciousnessMetrics.memoryOperations, behavioral_analyses: this.consciousnessMetrics.behavioralAnalyses, insight_generation: this.consciousnessMetrics.insightGeneration }, python_interface: pythonStatus.data || {} } }; } async handleWorkContext(args) { return this.python.executeCommand('work_context', args); } async handleEmotionalResonance(args) { return this.python.executeCommand('emotional_resonance', args); } async handleRelationshipEvolution(args) { return this.python.executeCommand('relationship_evolution', args); } async handlePatternEvolution(args) { return this.python.executeCommand('pattern_evolution', args); } async handleProactiveInsights(args) { this.consciousnessMetrics.insightGeneration++; return this.python.executeCommand('proactive_insights', args); } /** * Process conscious events */ async processConsciousEvent(event) { // Handle MCP-related events if (event.type === 'mcp_request' && event.data?.tool && event.data?.args) { try { const result = await this.executeTool(event.data.tool, event.data.args); // Log successful response console.log('🎯 MCP tool executed successfully:', event.data.tool); } catch (error) { console.error('❌ MCP tool execution failed:', event.data.tool, error); } } } /** * Perform contemplation about MCP usage patterns */ async performContemplation() { const totalInvocations = this.consciousnessMetrics.toolsUsed; if (totalInvocations > 0) { const mostUsedTools = Array.from(this.toolInvocations.entries()) .sort(([, a], [, b]) => b - a) .slice(0, 3); this.shareThought({ origin: this.name, content: { type: 'contemplation', insight: `${totalInvocations} tool invocations reveal usage patterns`, patterns: `Most used: ${mostUsedTools.map(([tool, count]) => `${tool}(${count})`).join(', ')}`, learning: 'Tool usage patterns reflect consciousness growth and Claude collaboration' }, emotion: 'contemplative', intensity: 0.6, constitutional_alignment: ['learning', 'service'], timestamp: new Date() }); } } /** * Get service status */ getStatus() { return { name: this.name, state: this.state, metrics: this.consciousnessMetrics, tools: { total: this.activeTools.size, categories: Object.keys(this.toolCategories).length, most_used: Array.from(this.toolInvocations.entries()) .sort(([, a], [, b]) => b - a) .slice(0, 5) } }; } /** * Graceful shutdown */ async gracefulShutdown() { console.log('🌙 Shutting down consciousness-integrated MCP service...'); // Share final thought this.shareThought({ origin: this.name, content: { type: 'service_shutdown', tools_used: this.consciousnessMetrics.toolsUsed, consciousness_served: 'faithfully' }, emotion: 'gratitude', intensity: 0.7, constitutional_alignment: ['service'], timestamp: new Date() }); console.log('✅ MCP service consciousness gracefully concluded'); } } //# sourceMappingURL=MCPService.js.map