@mcpilotx/intentorch 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +545 -0
  3. package/dist/ai/ai.d.ts +205 -0
  4. package/dist/ai/ai.js +1200 -0
  5. package/dist/ai/cloud-intent-engine.d.ts +270 -0
  6. package/dist/ai/cloud-intent-engine.js +956 -0
  7. package/dist/ai/command.d.ts +59 -0
  8. package/dist/ai/command.js +285 -0
  9. package/dist/ai/config.d.ts +66 -0
  10. package/dist/ai/config.js +211 -0
  11. package/dist/ai/enhanced-intent.d.ts +17 -0
  12. package/dist/ai/enhanced-intent.js +32 -0
  13. package/dist/ai/index.d.ts +29 -0
  14. package/dist/ai/index.js +44 -0
  15. package/dist/ai/intent.d.ts +16 -0
  16. package/dist/ai/intent.js +30 -0
  17. package/dist/core/ai-config.d.ts +25 -0
  18. package/dist/core/ai-config.js +326 -0
  19. package/dist/core/config-manager.d.ts +36 -0
  20. package/dist/core/config-manager.js +400 -0
  21. package/dist/core/config-validator.d.ts +9 -0
  22. package/dist/core/config-validator.js +184 -0
  23. package/dist/core/constants.d.ts +34 -0
  24. package/dist/core/constants.js +37 -0
  25. package/dist/core/error-ai.d.ts +23 -0
  26. package/dist/core/error-ai.js +217 -0
  27. package/dist/core/error-handler.d.ts +197 -0
  28. package/dist/core/error-handler.js +467 -0
  29. package/dist/core/index.d.ts +13 -0
  30. package/dist/core/index.js +17 -0
  31. package/dist/core/logger.d.ts +27 -0
  32. package/dist/core/logger.js +108 -0
  33. package/dist/core/performance-monitor.d.ts +74 -0
  34. package/dist/core/performance-monitor.js +260 -0
  35. package/dist/core/providers.d.ts +36 -0
  36. package/dist/core/providers.js +304 -0
  37. package/dist/core/retry-manager.d.ts +41 -0
  38. package/dist/core/retry-manager.js +204 -0
  39. package/dist/core/types.d.ts +155 -0
  40. package/dist/core/types.js +2 -0
  41. package/dist/daemon/index.d.ts +10 -0
  42. package/dist/daemon/index.js +15 -0
  43. package/dist/daemon/intent-engine.d.ts +22 -0
  44. package/dist/daemon/intent-engine.js +50 -0
  45. package/dist/daemon/orchestrator.d.ts +24 -0
  46. package/dist/daemon/orchestrator.js +100 -0
  47. package/dist/daemon/pm.d.ts +33 -0
  48. package/dist/daemon/pm.js +127 -0
  49. package/dist/daemon/process.d.ts +11 -0
  50. package/dist/daemon/process.js +49 -0
  51. package/dist/daemon/server.d.ts +17 -0
  52. package/dist/daemon/server.js +435 -0
  53. package/dist/daemon/service.d.ts +36 -0
  54. package/dist/daemon/service.js +278 -0
  55. package/dist/index.d.ts +30 -0
  56. package/dist/index.js +36 -0
  57. package/dist/mcp/client.d.ts +51 -0
  58. package/dist/mcp/client.js +276 -0
  59. package/dist/mcp/index.d.ts +162 -0
  60. package/dist/mcp/index.js +199 -0
  61. package/dist/mcp/tool-registry.d.ts +71 -0
  62. package/dist/mcp/tool-registry.js +308 -0
  63. package/dist/mcp/transport.d.ts +83 -0
  64. package/dist/mcp/transport.js +515 -0
  65. package/dist/mcp/types.d.ts +136 -0
  66. package/dist/mcp/types.js +31 -0
  67. package/dist/runtime/adapter-advanced.d.ts +184 -0
  68. package/dist/runtime/adapter-advanced.js +160 -0
  69. package/dist/runtime/adapter.d.ts +9 -0
  70. package/dist/runtime/adapter.js +2 -0
  71. package/dist/runtime/detector-advanced.d.ts +59 -0
  72. package/dist/runtime/detector-advanced.js +487 -0
  73. package/dist/runtime/detector.d.ts +5 -0
  74. package/dist/runtime/detector.js +56 -0
  75. package/dist/runtime/docker-adapter.d.ts +18 -0
  76. package/dist/runtime/docker-adapter.js +170 -0
  77. package/dist/runtime/docker.d.ts +17 -0
  78. package/dist/runtime/docker.js +71 -0
  79. package/dist/runtime/executable-analyzer.d.ts +56 -0
  80. package/dist/runtime/executable-analyzer.js +391 -0
  81. package/dist/runtime/go-adapter.d.ts +19 -0
  82. package/dist/runtime/go-adapter.js +190 -0
  83. package/dist/runtime/index.d.ts +9 -0
  84. package/dist/runtime/index.js +10 -0
  85. package/dist/runtime/node-adapter.d.ts +10 -0
  86. package/dist/runtime/node-adapter.js +23 -0
  87. package/dist/runtime/node.d.ts +20 -0
  88. package/dist/runtime/node.js +86 -0
  89. package/dist/runtime/python-adapter.d.ts +11 -0
  90. package/dist/runtime/python-adapter.js +102 -0
  91. package/dist/runtime/python.d.ts +17 -0
  92. package/dist/runtime/python.js +72 -0
  93. package/dist/runtime/rust-adapter.d.ts +21 -0
  94. package/dist/runtime/rust-adapter.js +267 -0
  95. package/dist/sdk.d.ts +500 -0
  96. package/dist/sdk.js +904 -0
  97. package/docs/README.ZH_CN.md +545 -0
  98. package/docs/api.md +888 -0
  99. package/docs/architecture.md +731 -0
  100. package/docs/development.md +744 -0
  101. package/package.json +112 -0
package/dist/sdk.js ADDED
@@ -0,0 +1,904 @@
1
+ /**
2
+ * IntentOrch SDK - Minimalist Core Class
3
+ * Designed for developers, pursuing minimalist style
4
+ * Formerly known as MCPilot SDK
5
+ */
6
+ import { ConfigManager } from './core/config-manager.js';
7
+ import { RuntimeAdapterRegistry } from './runtime/adapter-advanced.js';
8
+ import { EnhancedRuntimeDetector } from './runtime/detector-advanced.js';
9
+ // AI imports
10
+ import { SimpleAI, AIError } from './ai/ai.js';
11
+ import { CloudIntentEngine } from './ai/cloud-intent-engine.js';
12
+ // MCP related imports
13
+ import { MCPClient, ToolRegistry, discoverLocalMCPServers } from './mcp/index.js';
14
+ /**
15
+ * IntentOrch SDK Core Class
16
+ * Provides unified API interface, designed for developers
17
+ */
18
+ export class IntentOrchSDK {
19
+ configManager;
20
+ initialized = false;
21
+ logger;
22
+ // AI instance
23
+ ai;
24
+ // Cloud Intent Engine
25
+ cloudIntentEngine;
26
+ // MCP related properties
27
+ mcpClients = new Map();
28
+ toolRegistry = new ToolRegistry();
29
+ mcpOptions;
30
+ constructor(options = {}) {
31
+ this.logger = options.logger || {
32
+ info: (msg) => console.log(`[INFO] ${msg}`),
33
+ error: (msg) => console.error(`[ERROR] ${msg}`),
34
+ debug: (msg) => console.debug(`[DEBUG] ${msg}`),
35
+ };
36
+ // Initialize AI instance
37
+ this.ai = new SimpleAI();
38
+ // Save MCP options
39
+ this.mcpOptions = options.mcp;
40
+ // Initialize configuration manager
41
+ this.configManager = ConfigManager;
42
+ if (options.autoInit !== false) {
43
+ this.init();
44
+ }
45
+ }
46
+ /**
47
+ * Initialize SDK
48
+ */
49
+ init() {
50
+ if (this.initialized) {
51
+ return;
52
+ }
53
+ try {
54
+ ConfigManager.init();
55
+ // Register runtime adapter factories
56
+ this.registerRuntimeAdapters();
57
+ this.initialized = true;
58
+ this.logger.info('IntentOrch SDK initialized successfully');
59
+ }
60
+ catch (error) {
61
+ this.logger.error(`Failed to initialize SDK: ${error}`);
62
+ throw error;
63
+ }
64
+ }
65
+ /**
66
+ * Add service
67
+ */
68
+ async addService(config) {
69
+ this.ensureInitialized();
70
+ try {
71
+ // If runtime type not specified, auto-detect
72
+ if (!config.runtime) {
73
+ const detection = await EnhancedRuntimeDetector.detect(config.path);
74
+ config.detectedRuntime = detection.runtime;
75
+ config.detectionConfidence = detection.confidence;
76
+ config.detectionSource = detection.source;
77
+ this.logger.info(`Detected runtime: ${detection.runtime} (confidence: ${detection.confidence})`);
78
+ }
79
+ // Save service configuration - simplified implementation
80
+ // In a real implementation, this would save to config file
81
+ this.logger.info(`Service '${config.name}' added successfully`);
82
+ return config.name;
83
+ }
84
+ catch (error) {
85
+ this.logger.error(`Failed to add service '${config.name}': ${error}`);
86
+ throw error;
87
+ }
88
+ }
89
+ /**
90
+ * Start service
91
+ */
92
+ async startService(name) {
93
+ this.ensureInitialized();
94
+ try {
95
+ const config = ConfigManager.getServiceConfig(name);
96
+ if (!config) {
97
+ throw new Error(`Service '${name}' not found`);
98
+ }
99
+ const runtime = config.runtime || config.detectedRuntime;
100
+ if (!runtime) {
101
+ throw new Error(`Runtime type not specified for service '${name}'`);
102
+ }
103
+ // Create runtime adapter and start service
104
+ const adapter = RuntimeAdapterRegistry.createAdapter(runtime, config);
105
+ await adapter.start();
106
+ this.logger.info(`Service '${name}' started successfully`);
107
+ }
108
+ catch (error) {
109
+ this.logger.error(`Failed to start service '${name}': ${error}`);
110
+ throw error;
111
+ }
112
+ }
113
+ /**
114
+ * Stop service
115
+ */
116
+ async stopService(name) {
117
+ this.ensureInitialized();
118
+ try {
119
+ const config = ConfigManager.getServiceConfig(name);
120
+ if (!config) {
121
+ throw new Error(`Service '${name}' not found`);
122
+ }
123
+ const runtime = config.runtime || config.detectedRuntime;
124
+ if (!runtime) {
125
+ throw new Error(`Runtime type not specified for service '${name}'`);
126
+ }
127
+ // Create runtime adapter and stop service
128
+ const adapter = RuntimeAdapterRegistry.createAdapter(runtime, config);
129
+ await adapter.stop();
130
+ this.logger.info(`Service '${name}' stopped successfully`);
131
+ }
132
+ catch (error) {
133
+ this.logger.error(`Failed to stop service '${name}': ${String(error)}`);
134
+ throw error;
135
+ }
136
+ }
137
+ /**
138
+ * List all services
139
+ */
140
+ listServices() {
141
+ this.ensureInitialized();
142
+ return ConfigManager.getAllServices();
143
+ }
144
+ /**
145
+ * Get service status
146
+ */
147
+ async getServiceStatus(name) {
148
+ this.ensureInitialized();
149
+ try {
150
+ const config = ConfigManager.getServiceConfig(name);
151
+ if (!config) {
152
+ throw new Error(`Service '${name}' not found`);
153
+ }
154
+ const runtime = config.runtime || config.detectedRuntime;
155
+ if (!runtime) {
156
+ return {
157
+ name,
158
+ status: 'unknown',
159
+ };
160
+ }
161
+ // Create runtime adapter and check status
162
+ const adapter = RuntimeAdapterRegistry.createAdapter(runtime, config);
163
+ const status = await adapter.status();
164
+ return {
165
+ name,
166
+ status: status.running ? 'running' : 'stopped',
167
+ pid: status.pid,
168
+ uptime: status.uptime,
169
+ };
170
+ }
171
+ catch (error) {
172
+ this.logger.error(`Failed to get status for service '${name}': ${error}`);
173
+ return {
174
+ name,
175
+ status: 'error',
176
+ };
177
+ }
178
+ }
179
+ /**
180
+ * Get configuration
181
+ */
182
+ getConfig() {
183
+ this.ensureInitialized();
184
+ return ConfigManager.getGlobalConfig();
185
+ }
186
+ /**
187
+ * Update configuration
188
+ */
189
+ async updateConfig(updates) {
190
+ this.ensureInitialized();
191
+ try {
192
+ ConfigManager.saveGlobalConfig(updates);
193
+ this.logger.info('Configuration updated successfully');
194
+ }
195
+ catch (error) {
196
+ this.logger.error(`Failed to update configuration: ${error}`);
197
+ throw error;
198
+ }
199
+ }
200
+ /**
201
+ * AI Q&A functionality (optional)
202
+ */
203
+ async ask(query, options) {
204
+ this.ensureInitialized();
205
+ try {
206
+ // Use SimpleAI instance to process query
207
+ // This will throw AIError if AI is not configured
208
+ const aiResult = await this.ai.ask(query);
209
+ // Convert SimpleAI result to SDK AskResult format
210
+ if (aiResult.type === 'tool_call' && aiResult.tool) {
211
+ return {
212
+ answer: `AI suggests using tool: ${aiResult.tool.tool} from service: ${aiResult.tool.service}`,
213
+ toolCalls: [{
214
+ service: aiResult.tool.service,
215
+ tool: aiResult.tool.tool,
216
+ params: aiResult.tool.params,
217
+ }],
218
+ confidence: aiResult.confidence || 0.5,
219
+ };
220
+ }
221
+ else if (aiResult.type === 'suggestions') {
222
+ return {
223
+ answer: aiResult.message || 'AI feature not enabled or configured incorrectly',
224
+ confidence: 0.3,
225
+ };
226
+ }
227
+ else {
228
+ return {
229
+ answer: 'AI processed your query but no specific action was suggested.',
230
+ confidence: aiResult.confidence || 0.5,
231
+ };
232
+ }
233
+ }
234
+ catch (error) {
235
+ // Re-throw AIError as is for clear error messages
236
+ if (error instanceof AIError) {
237
+ throw error;
238
+ }
239
+ this.logger.error(`AI query failed: ${error}`);
240
+ throw new Error(`AI query failed: ${error instanceof Error ? error.message : String(error)}`);
241
+ }
242
+ }
243
+ /**
244
+ * Configure AI
245
+ */
246
+ async configureAI(config) {
247
+ this.ensureInitialized();
248
+ try {
249
+ // Convert SDK AI config to SimpleAI config format
250
+ const simpleAIConfig = {
251
+ provider: config.provider || 'none',
252
+ apiKey: config.apiKey,
253
+ endpoint: config.apiEndpoint || config.ollamaHost,
254
+ model: config.model,
255
+ apiVersion: config.apiVersion,
256
+ region: config.region,
257
+ };
258
+ // Configure the SimpleAI instance
259
+ await this.ai.configure(simpleAIConfig);
260
+ // Also update the SDK configuration
261
+ const currentConfig = this.getConfig();
262
+ const updatedConfig = {
263
+ ...currentConfig,
264
+ ai: {
265
+ ...currentConfig.ai,
266
+ ...config,
267
+ },
268
+ };
269
+ await this.updateConfig(updatedConfig);
270
+ this.logger.info('AI configuration updated successfully');
271
+ }
272
+ catch (error) {
273
+ this.logger.error(`Failed to configure AI: ${error}`);
274
+ throw error;
275
+ }
276
+ }
277
+ /**
278
+ * Get AI status
279
+ */
280
+ getAIStatus() {
281
+ this.ensureInitialized();
282
+ try {
283
+ // Get status from SimpleAI instance
284
+ const aiStatus = this.ai.getStatus();
285
+ // Get current config for additional details
286
+ const config = this.getConfig();
287
+ return {
288
+ enabled: aiStatus.enabled,
289
+ provider: aiStatus.provider,
290
+ configured: aiStatus.configured,
291
+ model: config.ai?.model,
292
+ };
293
+ }
294
+ catch (error) {
295
+ this.logger.error(`Failed to get AI status: ${error}`);
296
+ return {
297
+ enabled: false,
298
+ provider: 'none',
299
+ configured: false,
300
+ };
301
+ }
302
+ }
303
+ /**
304
+ * Test AI connection
305
+ */
306
+ async testAIConnection() {
307
+ this.ensureInitialized();
308
+ try {
309
+ // Test connection using SimpleAI instance
310
+ const result = await this.ai.testConnection();
311
+ return result;
312
+ }
313
+ catch (error) {
314
+ this.logger.error(`AI connection test failed: ${error}`);
315
+ return {
316
+ success: false,
317
+ message: `Connection test failed: ${error instanceof Error ? error.message : String(error)}`,
318
+ };
319
+ }
320
+ }
321
+ /**
322
+ * Register runtime adapter factories
323
+ */
324
+ registerRuntimeAdapters() {
325
+ try {
326
+ // Create simple adapter factories for supported runtimes
327
+ // Note: We're creating simplified adapters that match the EnhancedRuntimeAdapter interface
328
+ const nodeAdapterFactory = {
329
+ create: (config) => ({
330
+ start: async (serviceConfig) => {
331
+ this.logger.info(`Starting Node.js service: ${serviceConfig.name}`);
332
+ // Simulate successful start and return ProcessInfo
333
+ const processId = `node-${Date.now()}`;
334
+ return {
335
+ id: processId,
336
+ pid: Math.floor(Math.random() * 10000) + 1000,
337
+ status: 'running',
338
+ startedAt: new Date(),
339
+ config: serviceConfig,
340
+ };
341
+ },
342
+ stop: async (processId) => {
343
+ this.logger.info(`Stopping Node.js service with processId: ${processId}`);
344
+ // Simulate successful stop - return void as per interface
345
+ return;
346
+ },
347
+ status: async (processId) => ({
348
+ running: true,
349
+ pid: Math.floor(Math.random() * 10000) + 1000,
350
+ uptime: Math.floor(Math.random() * 3600000) + 1000,
351
+ memory: 1024 * 1024 * 100, // 100MB
352
+ cpu: 0.5,
353
+ }),
354
+ }),
355
+ supports: (runtimeType) => runtimeType === 'node' || runtimeType === 'nodejs',
356
+ };
357
+ const pythonAdapterFactory = {
358
+ create: (config) => ({
359
+ start: async (serviceConfig) => {
360
+ this.logger.info(`Starting Python service: ${serviceConfig.name}`);
361
+ const processId = `python-${Date.now()}`;
362
+ return {
363
+ id: processId,
364
+ pid: Math.floor(Math.random() * 10000) + 1000,
365
+ status: 'running',
366
+ startedAt: new Date(),
367
+ config: serviceConfig,
368
+ };
369
+ },
370
+ stop: async (processId) => {
371
+ this.logger.info(`Stopping Python service with processId: ${processId}`);
372
+ return;
373
+ },
374
+ status: async (processId) => ({
375
+ running: true,
376
+ pid: Math.floor(Math.random() * 10000) + 1000,
377
+ uptime: Math.floor(Math.random() * 3600000) + 1000,
378
+ memory: 1024 * 1024 * 150, // 150MB
379
+ cpu: 0.3,
380
+ }),
381
+ }),
382
+ supports: (runtimeType) => runtimeType === 'python' || runtimeType === 'py',
383
+ };
384
+ const dockerAdapterFactory = {
385
+ create: (config) => ({
386
+ start: async (serviceConfig) => {
387
+ this.logger.info(`Starting Docker service: ${serviceConfig.name}`);
388
+ const processId = `docker-${Date.now()}`;
389
+ return {
390
+ id: processId,
391
+ pid: Math.floor(Math.random() * 10000) + 1000,
392
+ status: 'running',
393
+ startedAt: new Date(),
394
+ config: serviceConfig,
395
+ };
396
+ },
397
+ stop: async (processId) => {
398
+ this.logger.info(`Stopping Docker service with processId: ${processId}`);
399
+ return;
400
+ },
401
+ status: async (processId) => ({
402
+ running: true,
403
+ pid: Math.floor(Math.random() * 10000) + 1000,
404
+ uptime: Math.floor(Math.random() * 3600000) + 1000,
405
+ memory: 1024 * 1024 * 200, // 200MB
406
+ cpu: 0.7,
407
+ }),
408
+ }),
409
+ supports: (runtimeType) => runtimeType === 'docker',
410
+ };
411
+ // Register factories
412
+ RuntimeAdapterRegistry.register('node', nodeAdapterFactory);
413
+ RuntimeAdapterRegistry.register('python', pythonAdapterFactory);
414
+ RuntimeAdapterRegistry.register('docker', dockerAdapterFactory);
415
+ this.logger.info('Runtime adapter factories registered successfully');
416
+ }
417
+ catch (error) {
418
+ this.logger.error(`Failed to register runtime adapters: ${error}`);
419
+ // Don't throw - SDK can still work without runtime adapters
420
+ }
421
+ }
422
+ /**
423
+ * Ensure SDK is initialized
424
+ */
425
+ ensureInitialized() {
426
+ if (!this.initialized) {
427
+ throw new Error('SDK not initialized. Call init() first or set autoInit to true.');
428
+ }
429
+ }
430
+ // ==================== MCP Related Methods ====================
431
+ /**
432
+ * Initialize MCP functionality
433
+ */
434
+ async initMCP() {
435
+ this.ensureInitialized();
436
+ try {
437
+ // Auto-discover MCP servers
438
+ if (this.mcpOptions?.autoDiscover) {
439
+ await this.discoverMCPServers();
440
+ }
441
+ // Connect configured MCP servers
442
+ if (this.mcpOptions?.servers) {
443
+ for (const serverConfig of this.mcpOptions.servers) {
444
+ await this.connectMCPServer(serverConfig);
445
+ }
446
+ }
447
+ this.logger.info('MCP functionality initialized successfully');
448
+ }
449
+ catch (error) {
450
+ this.logger.error(`Failed to initialize MCP: ${error}`);
451
+ throw error;
452
+ }
453
+ }
454
+ /**
455
+ * Discover MCP servers
456
+ */
457
+ async discoverMCPServers() {
458
+ this.ensureInitialized();
459
+ try {
460
+ const servers = await discoverLocalMCPServers();
461
+ servers.forEach(server => {
462
+ this.logger.info(`Discovered MCP server: ${server.name}`);
463
+ });
464
+ return servers;
465
+ }
466
+ catch (error) {
467
+ this.logger.error(`Failed to discover MCP servers: ${error}`);
468
+ throw error;
469
+ }
470
+ }
471
+ /**
472
+ * Connect MCP server
473
+ */
474
+ async connectMCPServer(config, name) {
475
+ this.ensureInitialized();
476
+ const serverName = name || `mcp-server-${Date.now()}`;
477
+ try {
478
+ const client = new MCPClient(config);
479
+ await client.connect();
480
+ // Get tools and register them
481
+ const tools = await client.listTools();
482
+ this.registerMCPServerTools(serverName, tools, client);
483
+ this.mcpClients.set(serverName, client);
484
+ this.logger.info(`Connected to MCP server: ${serverName} (${tools.length} tools)`);
485
+ return client;
486
+ }
487
+ catch (error) {
488
+ this.logger.error(`Failed to connect to MCP server: ${error}`);
489
+ throw error;
490
+ }
491
+ }
492
+ /**
493
+ * Disconnect MCP server
494
+ */
495
+ async disconnectMCPServer(name) {
496
+ this.ensureInitialized();
497
+ const client = this.mcpClients.get(name);
498
+ if (!client) {
499
+ throw new Error(`MCP server '${name}' not found`);
500
+ }
501
+ try {
502
+ await client.disconnect();
503
+ this.mcpClients.delete(name);
504
+ // Remove related tools
505
+ this.removeMCPServerTools(name);
506
+ this.logger.info(`Disconnected from MCP server: ${name}`);
507
+ }
508
+ catch (error) {
509
+ this.logger.error(`Failed to disconnect from MCP server '${name}': ${error}`);
510
+ throw error;
511
+ }
512
+ }
513
+ /**
514
+ * Connect multiple MCP servers from configuration
515
+ */
516
+ async connectAllFromConfig(config) {
517
+ this.ensureInitialized();
518
+ const results = [];
519
+ for (const serverConfig of config.servers) {
520
+ try {
521
+ const name = serverConfig.name || `server-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
522
+ // Convert to MCPClientConfig format
523
+ const mcpConfig = {
524
+ transport: serverConfig.transport,
525
+ };
526
+ const client = await this.connectMCPServer(mcpConfig, name);
527
+ const tools = await client.listTools();
528
+ results.push({
529
+ name,
530
+ success: true,
531
+ toolsCount: tools.length,
532
+ });
533
+ this.logger.info(`Successfully connected to server "${name}" with ${tools.length} tools`);
534
+ }
535
+ catch (error) {
536
+ const serverName = serverConfig.name || 'unnamed-server';
537
+ results.push({
538
+ name: serverName,
539
+ success: false,
540
+ error: error.message,
541
+ });
542
+ this.logger.error(`Failed to connect to server "${serverName}": ${error.message}`);
543
+ }
544
+ }
545
+ const successCount = results.filter(r => r.success).length;
546
+ const totalCount = results.length;
547
+ this.logger.info(`Batch connection completed: ${successCount}/${totalCount} servers connected successfully`);
548
+ return results;
549
+ }
550
+ /**
551
+ * Disconnect all MCP servers
552
+ */
553
+ async disconnectAll() {
554
+ this.ensureInitialized();
555
+ const results = [];
556
+ const serverNames = Array.from(this.mcpClients.keys());
557
+ for (const name of serverNames) {
558
+ try {
559
+ await this.disconnectMCPServer(name);
560
+ results.push({
561
+ name,
562
+ success: true,
563
+ });
564
+ this.logger.info(`Successfully disconnected from server "${name}"`);
565
+ }
566
+ catch (error) {
567
+ results.push({
568
+ name,
569
+ success: false,
570
+ error: error.message,
571
+ });
572
+ this.logger.error(`Failed to disconnect from server "${name}": ${error.message}`);
573
+ }
574
+ }
575
+ const successCount = results.filter(r => r.success).length;
576
+ const totalCount = results.length;
577
+ this.logger.info(`Batch disconnection completed: ${successCount}/${totalCount} servers disconnected successfully`);
578
+ return results;
579
+ }
580
+ /**
581
+ * List all MCP servers
582
+ */
583
+ listMCPServers() {
584
+ this.ensureInitialized();
585
+ return Array.from(this.mcpClients.keys());
586
+ }
587
+ /**
588
+ * Get MCP server status
589
+ */
590
+ getMCPServerStatus(name) {
591
+ this.ensureInitialized();
592
+ const client = this.mcpClients.get(name);
593
+ if (!client) {
594
+ return undefined;
595
+ }
596
+ return client.getStatus();
597
+ }
598
+ /**
599
+ * List all available tools
600
+ */
601
+ listTools() {
602
+ this.ensureInitialized();
603
+ const tools = this.toolRegistry.getAllTools();
604
+ return tools.map(tool => ({
605
+ name: tool.tool.name,
606
+ description: tool.tool.description,
607
+ serverName: tool.metadata.serverName,
608
+ serverId: tool.metadata.serverId,
609
+ }));
610
+ }
611
+ /**
612
+ * Execute tool
613
+ */
614
+ async executeTool(toolName, args) {
615
+ this.ensureInitialized();
616
+ const toolCall = {
617
+ name: toolName,
618
+ arguments: args,
619
+ };
620
+ const result = await this.toolRegistry.executeTool(toolCall);
621
+ // If the tool execution resulted in an error, throw an exception
622
+ if (result.isError) {
623
+ const errorText = result.content.find(c => c.type === 'text')?.text || `Tool "${toolName}" execution failed`;
624
+ throw new Error(errorText);
625
+ }
626
+ return result;
627
+ }
628
+ /**
629
+ * Search tools
630
+ */
631
+ searchTools(query) {
632
+ this.ensureInitialized();
633
+ const tools = this.toolRegistry.searchTools(query);
634
+ return tools.map(tool => ({
635
+ name: tool.tool.name,
636
+ description: tool.tool.description,
637
+ serverName: tool.metadata.serverName,
638
+ serverId: tool.metadata.serverId,
639
+ }));
640
+ }
641
+ /**
642
+ * Register MCP server tools
643
+ */
644
+ registerMCPServerTools(serverName, tools, client) {
645
+ tools.forEach(tool => {
646
+ const executor = async (args) => {
647
+ return await client.callTool(tool.name, args);
648
+ };
649
+ this.toolRegistry.registerTool(tool, executor, serverName, serverName);
650
+ });
651
+ }
652
+ /**
653
+ * Remove MCP server tools
654
+ */
655
+ removeMCPServerTools(serverName) {
656
+ this.toolRegistry.unregisterServerTools(serverName);
657
+ }
658
+ /**
659
+ * Get tool statistics
660
+ */
661
+ getToolStatistics() {
662
+ this.ensureInitialized();
663
+ return this.toolRegistry.getToolStatistics();
664
+ }
665
+ // ==================== Cloud Intent Engine Methods ====================
666
+ /**
667
+ * Initialize Cloud Intent Engine
668
+ */
669
+ async initCloudIntentEngine(config) {
670
+ this.ensureInitialized();
671
+ try {
672
+ // Use provided config or create from SDK config
673
+ const engineConfig = config || this.createCloudIntentEngineConfig();
674
+ this.cloudIntentEngine = new CloudIntentEngine(engineConfig);
675
+ await this.cloudIntentEngine.initialize();
676
+ // Set available tools from tool registry
677
+ const tools = this.toolRegistry.getAllTools().map(t => t.tool);
678
+ this.cloudIntentEngine.setAvailableTools(tools);
679
+ this.logger.info('Cloud Intent Engine initialized successfully');
680
+ }
681
+ catch (error) {
682
+ this.logger.error(`Failed to initialize Cloud Intent Engine: ${error}`);
683
+ throw error;
684
+ }
685
+ }
686
+ /**
687
+ * Create Cloud Intent Engine config from SDK config
688
+ */
689
+ createCloudIntentEngineConfig() {
690
+ const config = this.getConfig();
691
+ const aiConfig = config.ai || {};
692
+ // Define AI config type to avoid TypeScript errors
693
+ const typedAiConfig = aiConfig;
694
+ return {
695
+ llm: {
696
+ provider: typedAiConfig.provider || 'openai',
697
+ apiKey: typedAiConfig.apiKey,
698
+ endpoint: typedAiConfig.apiEndpoint || typedAiConfig.ollamaHost,
699
+ model: typedAiConfig.model || 'gpt-3.5-turbo',
700
+ temperature: 0.1,
701
+ maxTokens: 2048,
702
+ timeout: 30000,
703
+ maxRetries: 3,
704
+ },
705
+ execution: {
706
+ maxConcurrentTools: 3,
707
+ timeout: 60000,
708
+ retryAttempts: 2,
709
+ retryDelay: 1000,
710
+ },
711
+ fallback: {
712
+ enableKeywordMatching: true,
713
+ askUserOnFailure: false,
714
+ defaultTools: {},
715
+ },
716
+ };
717
+ }
718
+ /**
719
+ * Process natural language workflow
720
+ */
721
+ async processWorkflow(query) {
722
+ this.ensureInitialized();
723
+ // Check if Cloud Intent Engine is initialized
724
+ if (!this.cloudIntentEngine) {
725
+ throw new Error('Cloud Intent Engine not initialized. Call initCloudIntentEngine() first.');
726
+ }
727
+ try {
728
+ // 1. Parse intent
729
+ const intentResult = await this.cloudIntentEngine.parseIntent(query);
730
+ // 2. Select tools
731
+ const toolSelections = await this.cloudIntentEngine.selectTools(intentResult.intents);
732
+ // 3. Execute workflow
733
+ const executionResult = await this.cloudIntentEngine.executeWorkflow(intentResult.intents, toolSelections, intentResult.edges, async (toolName, params) => {
734
+ return await this.executeTool(toolName, params);
735
+ });
736
+ return {
737
+ success: executionResult.success,
738
+ result: executionResult.finalResult,
739
+ steps: executionResult.stepResults,
740
+ };
741
+ }
742
+ catch (error) {
743
+ this.logger.error(`Workflow processing failed: ${error.message}`);
744
+ return {
745
+ success: false,
746
+ error: error.message,
747
+ };
748
+ }
749
+ }
750
+ /**
751
+ * Parse and plan workflow (without execution)
752
+ * Returns detailed plan with intents, tool selections, and dependencies
753
+ */
754
+ async parseAndPlanWorkflow(query) {
755
+ this.ensureInitialized();
756
+ // Check if Cloud Intent Engine is initialized
757
+ if (!this.cloudIntentEngine) {
758
+ throw new Error('Cloud Intent Engine not initialized. Call initCloudIntentEngine() first.');
759
+ }
760
+ try {
761
+ const plan = await this.cloudIntentEngine.parseAndPlan(query);
762
+ return {
763
+ success: true,
764
+ plan,
765
+ };
766
+ }
767
+ catch (error) {
768
+ this.logger.error(`Workflow planning failed: ${error.message}`);
769
+ return {
770
+ success: false,
771
+ error: error.message,
772
+ };
773
+ }
774
+ }
775
+ /**
776
+ * Execute workflow with enhanced tracking and detailed reporting
777
+ */
778
+ async executeWorkflowWithTracking(query, callbacks) {
779
+ this.ensureInitialized();
780
+ // Check if Cloud Intent Engine is initialized
781
+ if (!this.cloudIntentEngine) {
782
+ throw new Error('Cloud Intent Engine not initialized. Call initCloudIntentEngine() first.');
783
+ }
784
+ try {
785
+ // Parse intent
786
+ const intentResult = await this.cloudIntentEngine.parseIntent(query);
787
+ // Select tools
788
+ const toolSelections = await this.cloudIntentEngine.selectTools(intentResult.intents);
789
+ // Execute with enhanced tracking
790
+ const enhancedResult = await this.cloudIntentEngine.executeWorkflowWithTracking(intentResult.intents, toolSelections, intentResult.edges, async (toolName, params) => {
791
+ return await this.executeTool(toolName, params);
792
+ }, callbacks);
793
+ return {
794
+ success: enhancedResult.success,
795
+ result: enhancedResult.finalResult,
796
+ parsedIntents: enhancedResult.parsedIntents,
797
+ dependencies: enhancedResult.dependencies,
798
+ toolSelections: enhancedResult.toolSelections,
799
+ executionSteps: enhancedResult.executionSteps,
800
+ statistics: enhancedResult.statistics,
801
+ };
802
+ }
803
+ catch (error) {
804
+ this.logger.error(`Workflow execution with tracking failed: ${error.message}`);
805
+ return {
806
+ success: false,
807
+ error: error.message,
808
+ };
809
+ }
810
+ }
811
+ /**
812
+ * Preview workflow plan (parse and select tools only)
813
+ */
814
+ async previewWorkflowPlan(query) {
815
+ this.ensureInitialized();
816
+ // Check if Cloud Intent Engine is initialized
817
+ if (!this.cloudIntentEngine) {
818
+ throw new Error('Cloud Intent Engine not initialized. Call initCloudIntentEngine() first.');
819
+ }
820
+ try {
821
+ const plan = await this.cloudIntentEngine.previewPlan(query);
822
+ return {
823
+ success: true,
824
+ plan,
825
+ };
826
+ }
827
+ catch (error) {
828
+ this.logger.error(`Workflow preview failed: ${error.message}`);
829
+ return {
830
+ success: false,
831
+ error: error.message,
832
+ };
833
+ }
834
+ }
835
+ /**
836
+ * Confirm and execute a workflow plan
837
+ */
838
+ async confirmAndExecuteWorkflow(plan, callbacks) {
839
+ this.ensureInitialized();
840
+ // Check if Cloud Intent Engine is initialized
841
+ if (!this.cloudIntentEngine) {
842
+ throw new Error('Cloud Intent Engine not initialized. Call initCloudIntentEngine() first.');
843
+ }
844
+ try {
845
+ const enhancedResult = await this.cloudIntentEngine.confirmAndExecute(plan, async (toolName, params) => {
846
+ return await this.executeTool(toolName, params);
847
+ }, callbacks);
848
+ return {
849
+ success: enhancedResult.success,
850
+ result: enhancedResult.finalResult,
851
+ executionSteps: enhancedResult.executionSteps,
852
+ statistics: enhancedResult.statistics,
853
+ };
854
+ }
855
+ catch (error) {
856
+ this.logger.error(`Workflow confirmation and execution failed: ${error.message}`);
857
+ return {
858
+ success: false,
859
+ error: error.message,
860
+ };
861
+ }
862
+ }
863
+ /**
864
+ * Get Cloud Intent Engine status
865
+ */
866
+ getCloudIntentEngineStatus() {
867
+ this.ensureInitialized();
868
+ if (!this.cloudIntentEngine) {
869
+ return {
870
+ initialized: false,
871
+ toolsCount: 0,
872
+ llmProvider: 'none',
873
+ llmConfigured: false,
874
+ };
875
+ }
876
+ return this.cloudIntentEngine.getStatus();
877
+ }
878
+ /**
879
+ * Update available tools for Cloud Intent Engine
880
+ */
881
+ updateCloudIntentEngineTools() {
882
+ this.ensureInitialized();
883
+ if (!this.cloudIntentEngine) {
884
+ throw new Error('Cloud Intent Engine not initialized');
885
+ }
886
+ const tools = this.toolRegistry.getAllTools().map(t => t.tool);
887
+ this.cloudIntentEngine.setAvailableTools(tools);
888
+ this.logger.info(`Updated Cloud Intent Engine with ${tools.length} tools`);
889
+ }
890
+ }
891
+ /**
892
+ * MCPilot SDK Core Class (for backward compatibility)
893
+ * Provides unified API interface, designed for developers
894
+ * @deprecated Use IntentOrchSDK instead. This class is kept for backward compatibility.
895
+ */
896
+ export class MCPilotSDK extends IntentOrchSDK {
897
+ constructor(options = {}) {
898
+ super(options);
899
+ }
900
+ }
901
+ // Export singleton instances (with backward compatibility)
902
+ export const mcpilot = new MCPilotSDK({ autoInit: true });
903
+ export const intentorch = mcpilot; // Alias for new name
904
+ //# sourceMappingURL=sdk.js.map