File size: 5,356 Bytes
529090e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
/**
 * MCP Integration with Autonomous System
 * 
 * Auto-registers MCP tools as data sources in the autonomous system
 * for intelligent routing and self-healing
 */

import { mcpRegistry } from '../mcpRegistry.js';
import { getSourceRegistry } from '../SourceRegistry.js';
import { DataSource } from './DecisionEngine.js';
import { OutlookJsonAdapter } from '../../services/external/OutlookJsonAdapter.js';
import { join } from 'path';
import { cwd } from 'process';

/**
 * Register all MCP tools as autonomous data sources
 */
export async function registerMCPToolsAsSources(): Promise<void> {
    const sourceRegistry = getSourceRegistry();
    const tools = mcpRegistry.getRegisteredTools();

    console.log(`๐Ÿ”— Registering ${tools.length} MCP tools as autonomous data sources...`);

    for (const toolName of tools) {
        try {
            // Parse tool name to extract domain
            const [domain, operation] = toolName.split('.');
            const capabilities = [
                toolName,
                `${domain}.*`,
                operation || '*'
            ];

            // Create base data source
            const baseSource: DataSource = {
                name: `mcp-${toolName}`,
                type: 'mcp-tool',
                capabilities,
                isHealthy: async () => {
                    // Check if tool is registered
                    return mcpRegistry.getRegisteredTools().includes(toolName);
                },
                estimatedLatency: 100, // MCP tools typically fast
                costPerQuery: 0, // MCP tools are free
                query: async (op: string, params: any) => {
                    // Route through MCP registry
                    // Include operation in payload so handlers can distinguish different operations
                    return await mcpRegistry.route({
                        id: `auton-${Date.now()}`,
                        createdAt: new Date().toISOString(),
                        sourceId: 'autonomous-agent',
                        targetId: 'mcp-registry',
                        tool: toolName,
                        payload: {
                            ...(params || {}),
                            operation: op // Include operation parameter for routing
                        }
                    });
                }
            };

            // Register as data source directly (self-healing is handled at the adapter level)
            sourceRegistry.registerSource(baseSource);

            console.log(`  โœ“ Registered: ${toolName} โ†’ mcp-${toolName}`);
        } catch (error: any) {
            console.warn(`  โš ๏ธ  Failed to register ${toolName}: ${error.message}`);
        }
    }

    console.log(`โœ… Registered ${tools.length} MCP tools as autonomous sources`);
}

/**
 * Register database as data source
 */
export async function registerDatabaseSource(): Promise<void> {
    const sourceRegistry = getSourceRegistry();
    const { getDatabase } = await import('../../database/index.js');

    sourceRegistry.registerSource({
        name: 'database-main',
        type: 'database',
        capabilities: ['*', 'database.*', 'agents.*', 'memory.*', 'srag.*', 'evolution.*', 'pal.*'],
        isHealthy: async () => {
            try {
                const db = getDatabase();
                const stmt = db.prepare('SELECT 1');
                stmt.get();
                stmt.free();
                return true;
            } catch {
                return false;
            }
        },
        estimatedLatency: 50,
        costPerQuery: 0,
        query: async (_operation: string, _params: any) => {
            // Database queries are handled by repositories
            // This is a placeholder - actual routing happens in repositories
            throw new Error('Database query routing handled by repositories');
        }
    });

    console.log('๐Ÿ“Œ Registered database as autonomous source');
}

/**
 * Register Outlook JSON source
 */
export async function registerOutlookSource(): Promise<void> {
    const sourceRegistry = getSourceRegistry();
    // Path to data file
    const dataPath = join(cwd(), 'apps', 'backend', 'data', 'outlook-mails.json');
    
    const adapter = new OutlookJsonAdapter(dataPath);
    
    sourceRegistry.registerSource({
        name: 'outlook-mail',
        type: 'email-adapter',
        capabilities: ['email.search', 'email.read', 'communication.history'],
        isHealthy: async () => true, // File adapter is always "healthy" if file exists or not (just returns empty)
        estimatedLatency: 20, // Fast local read
        costPerQuery: 0,
        query: async (operation: string, params: any) => {
            return await adapter.query(operation, params);
        }
    });

    console.log(`๐Ÿ“Œ Registered Outlook JSON source (path: ${dataPath})`);
}

/**
 * Initialize all autonomous data sources
 */
export async function initializeAutonomousSources(): Promise<void> {
    // Register database first (highest priority for most queries)
    await registerDatabaseSource();

    // Register Outlook source
    await registerOutlookSource();

    // Wait a bit for MCP tools to be registered
    await new Promise(resolve => setTimeout(resolve, 1000));

    // Register all MCP tools as sources
    await registerMCPToolsAsSources();
}