@juspay/neurolink 1.2.4 → 1.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 (35) hide show
  1. package/CHANGELOG.md +170 -0
  2. package/README.md +96 -232
  3. package/dist/cli/commands/config.d.ts +403 -0
  4. package/dist/cli/commands/config.js +567 -0
  5. package/dist/cli/commands/mcp.d.ts +7 -0
  6. package/dist/cli/commands/mcp.js +434 -0
  7. package/dist/cli/index.d.ts +9 -0
  8. package/dist/cli/index.js +16 -9
  9. package/dist/core/factory.js +6 -2
  10. package/dist/core/types.d.ts +12 -2
  11. package/dist/core/types.js +11 -0
  12. package/dist/mcp/context-manager.d.ts +164 -0
  13. package/dist/mcp/context-manager.js +273 -0
  14. package/dist/mcp/factory.d.ts +144 -0
  15. package/dist/mcp/factory.js +141 -0
  16. package/dist/mcp/orchestrator.d.ts +170 -0
  17. package/dist/mcp/orchestrator.js +372 -0
  18. package/dist/mcp/registry.d.ts +188 -0
  19. package/dist/mcp/registry.js +373 -0
  20. package/dist/mcp/servers/ai-providers/ai-analysis-tools.d.ts +21 -0
  21. package/dist/mcp/servers/ai-providers/ai-analysis-tools.js +215 -0
  22. package/dist/mcp/servers/ai-providers/ai-core-server.d.ts +10 -0
  23. package/dist/mcp/servers/ai-providers/ai-core-server.js +302 -0
  24. package/dist/mcp/servers/ai-providers/ai-workflow-tools.d.ts +101 -0
  25. package/dist/mcp/servers/ai-providers/ai-workflow-tools.js +430 -0
  26. package/dist/neurolink.d.ts +4 -4
  27. package/dist/neurolink.js +109 -56
  28. package/dist/providers/googleAIStudio.d.ts +30 -0
  29. package/dist/providers/googleAIStudio.js +215 -0
  30. package/dist/providers/googleVertexAI.js +2 -2
  31. package/dist/providers/index.d.ts +2 -0
  32. package/dist/providers/index.js +3 -1
  33. package/dist/providers/openAI.js +2 -2
  34. package/dist/utils/providerUtils.js +11 -2
  35. package/package.json +78 -6
@@ -0,0 +1,141 @@
1
+ /**
2
+ * NeuroLink MCP Server Factory
3
+ * Factory-First Architecture: MCP servers create tools for internal orchestration
4
+ * Compatible with Lighthouse MCP patterns for seamless migration
5
+ */
6
+ import { z } from 'zod';
7
+ /**
8
+ * Input validation schemas
9
+ */
10
+ const ServerConfigSchema = z.object({
11
+ id: z.string().min(1, 'Server ID is required'),
12
+ title: z.string().min(1, 'Server title is required'),
13
+ description: z.string().optional(),
14
+ version: z.string().optional(),
15
+ category: z.enum([
16
+ 'ai-providers',
17
+ 'frameworks',
18
+ 'development',
19
+ 'business',
20
+ 'content',
21
+ 'data',
22
+ 'integrations',
23
+ 'automation',
24
+ 'analysis',
25
+ 'custom'
26
+ ]).optional(),
27
+ visibility: z.enum(['public', 'private', 'organization']).optional(),
28
+ metadata: z.record(z.any()).optional(),
29
+ dependencies: z.array(z.string()).optional(),
30
+ capabilities: z.array(z.string()).optional()
31
+ });
32
+ /**
33
+ * Create MCP Server Factory Function
34
+ *
35
+ * Core factory function for creating Lighthouse-compatible MCP servers.
36
+ * Follows Factory-First architecture where tools are internal implementation.
37
+ *
38
+ * @param config Server configuration with minimal required fields
39
+ * @returns Fully configured MCP server ready for tool registration
40
+ *
41
+ * @example
42
+ * ```typescript
43
+ * const aiCoreServer = createMCPServer({
44
+ * id: 'neurolink-ai-core',
45
+ * title: 'NeuroLink AI Core',
46
+ * description: 'Core AI provider tools',
47
+ * category: 'ai-providers'
48
+ * });
49
+ *
50
+ * aiCoreServer.registerTool({
51
+ * name: 'generate-text',
52
+ * description: 'Generate text using AI providers',
53
+ * execute: async (params, context) => {
54
+ * // Tool implementation
55
+ * return { success: true, data: result };
56
+ * }
57
+ * });
58
+ * ```
59
+ */
60
+ export function createMCPServer(config) {
61
+ // Validate configuration
62
+ const validatedConfig = ServerConfigSchema.parse(config);
63
+ // Create server with sensible defaults
64
+ const server = {
65
+ // Required fields
66
+ id: validatedConfig.id,
67
+ title: validatedConfig.title,
68
+ // Optional fields with defaults
69
+ description: validatedConfig.description,
70
+ version: validatedConfig.version || '1.0.0',
71
+ category: validatedConfig.category || 'custom',
72
+ visibility: validatedConfig.visibility || 'private',
73
+ // Tool management
74
+ tools: {},
75
+ // Tool registration method
76
+ registerTool(tool) {
77
+ // Validate tool has required fields
78
+ if (!tool.name || !tool.description || !tool.execute) {
79
+ throw new Error(`Invalid tool: name, description, and execute are required`);
80
+ }
81
+ // Check for duplicate tool names
82
+ if (this.tools[tool.name]) {
83
+ throw new Error(`Tool '${tool.name}' already exists in server '${this.id}'`);
84
+ }
85
+ // Register the tool
86
+ this.tools[tool.name] = {
87
+ ...tool,
88
+ // Add server metadata to tool
89
+ metadata: {
90
+ ...tool.metadata,
91
+ serverId: this.id,
92
+ serverCategory: this.category,
93
+ registeredAt: Date.now()
94
+ }
95
+ };
96
+ return this;
97
+ },
98
+ // Extension points
99
+ metadata: validatedConfig.metadata || {},
100
+ dependencies: validatedConfig.dependencies || [],
101
+ capabilities: validatedConfig.capabilities || []
102
+ };
103
+ return server;
104
+ }
105
+ /**
106
+ * Utility function to validate tool interface
107
+ */
108
+ export function validateTool(tool) {
109
+ try {
110
+ // Check required fields
111
+ if (!tool.name || typeof tool.name !== 'string')
112
+ return false;
113
+ if (!tool.description || typeof tool.description !== 'string')
114
+ return false;
115
+ if (!tool.execute || typeof tool.execute !== 'function')
116
+ return false;
117
+ // Validate optional schemas if present
118
+ if (tool.inputSchema && !(tool.inputSchema instanceof z.ZodSchema))
119
+ return false;
120
+ if (tool.outputSchema && !(tool.outputSchema instanceof z.ZodSchema))
121
+ return false;
122
+ return true;
123
+ }
124
+ catch (error) {
125
+ return false;
126
+ }
127
+ }
128
+ /**
129
+ * Utility function to get server info
130
+ */
131
+ export function getServerInfo(server) {
132
+ return {
133
+ id: server.id,
134
+ title: server.title,
135
+ description: server.description,
136
+ category: server.category,
137
+ toolCount: Object.keys(server.tools).length,
138
+ capabilities: server.capabilities || []
139
+ };
140
+ }
141
+ // Types are already exported above via export interface declarations
@@ -0,0 +1,170 @@
1
+ /**
2
+ * NeuroLink MCP Tool Orchestration Engine
3
+ * Central orchestrator for coordinated tool execution with pipeline management
4
+ * Coordinates factory, registry, context, and AI tools for seamless operation
5
+ */
6
+ import type { ToolResult } from './factory.js';
7
+ import { MCPToolRegistry, type ToolExecutionOptions } from './registry.js';
8
+ import { ContextManager, type ContextRequest } from './context-manager.js';
9
+ /**
10
+ * Pipeline execution options
11
+ */
12
+ export interface PipelineOptions {
13
+ stopOnError?: boolean;
14
+ parallel?: boolean;
15
+ timeout?: number;
16
+ trackMetrics?: boolean;
17
+ validateInputs?: boolean;
18
+ }
19
+ /**
20
+ * Tool execution step in a pipeline
21
+ */
22
+ export interface PipelineStep {
23
+ toolName: string;
24
+ params: any;
25
+ options?: ToolExecutionOptions;
26
+ dependsOn?: string[];
27
+ stepId?: string;
28
+ }
29
+ /**
30
+ * Pipeline execution result
31
+ */
32
+ export interface PipelineResult {
33
+ success: boolean;
34
+ results: Map<string, ToolResult>;
35
+ errors: Map<string, string>;
36
+ executionTime: number;
37
+ stepsExecuted: number;
38
+ stepsSkipped: number;
39
+ metadata: {
40
+ pipelineId: string;
41
+ sessionId: string;
42
+ timestamp: number;
43
+ parallel: boolean;
44
+ };
45
+ }
46
+ /**
47
+ * Text generation pipeline result
48
+ */
49
+ export interface TextPipelineResult {
50
+ success: boolean;
51
+ text?: string;
52
+ provider?: string;
53
+ model?: string;
54
+ executionTime: number;
55
+ usage?: {
56
+ tokens?: number;
57
+ cost?: number;
58
+ };
59
+ metadata: {
60
+ sessionId: string;
61
+ timestamp: number;
62
+ toolsUsed: string[];
63
+ };
64
+ }
65
+ /**
66
+ * NeuroLink MCP Tool Orchestrator
67
+ * Central coordination engine for tool execution, pipelines, and AI operations
68
+ */
69
+ export declare class MCPOrchestrator {
70
+ private registry;
71
+ private contextManager;
72
+ private pipelineCounter;
73
+ constructor(registry?: MCPToolRegistry, contextManager?: ContextManager);
74
+ /**
75
+ * Initialize with default servers (AI Core)
76
+ */
77
+ private initializeDefaultServers;
78
+ /**
79
+ * Execute a single tool with full orchestration
80
+ *
81
+ * @param toolName Tool name to execute
82
+ * @param params Tool parameters
83
+ * @param contextRequest Context creation request
84
+ * @param options Execution options
85
+ * @returns Tool execution result
86
+ */
87
+ executeTool(toolName: string, params: any, contextRequest?: ContextRequest, options?: ToolExecutionOptions): Promise<ToolResult>;
88
+ /**
89
+ * Execute a pipeline of tools with dependency management
90
+ *
91
+ * @param steps Pipeline steps to execute
92
+ * @param contextRequest Context creation request
93
+ * @param options Pipeline execution options
94
+ * @returns Pipeline execution result
95
+ */
96
+ executePipeline(steps: PipelineStep[], contextRequest?: ContextRequest, options?: PipelineOptions): Promise<PipelineResult>;
97
+ /**
98
+ * Execute AI text generation pipeline (high-level convenience method)
99
+ *
100
+ * @param prompt Text prompt for generation
101
+ * @param contextRequest Context creation request
102
+ * @param options Additional generation options
103
+ * @returns Text generation result
104
+ */
105
+ executeTextPipeline(prompt: string, contextRequest?: ContextRequest, options?: {
106
+ provider?: string;
107
+ model?: string;
108
+ temperature?: number;
109
+ maxTokens?: number;
110
+ systemPrompt?: string;
111
+ customTools?: string[];
112
+ }): Promise<TextPipelineResult>;
113
+ /**
114
+ * Get orchestrator statistics
115
+ *
116
+ * @returns Comprehensive orchestrator statistics
117
+ */
118
+ getStats(): {
119
+ registry: any;
120
+ context: any;
121
+ orchestrator: {
122
+ pipelinesExecuted: number;
123
+ };
124
+ };
125
+ /**
126
+ * Execute parallel pipeline with dependency management
127
+ *
128
+ * @private
129
+ */
130
+ private executeParallelPipeline;
131
+ /**
132
+ * Generate unique pipeline ID
133
+ *
134
+ * @private
135
+ */
136
+ private generatePipelineId;
137
+ }
138
+ /**
139
+ * Default orchestrator instance
140
+ * Ready-to-use orchestrator with pre-configured registry and context manager
141
+ */
142
+ export declare const defaultOrchestrator: MCPOrchestrator;
143
+ /**
144
+ * Utility function to execute tool with default orchestrator
145
+ *
146
+ * @param toolName Tool name to execute
147
+ * @param params Tool parameters
148
+ * @param contextRequest Context creation request
149
+ * @param options Execution options
150
+ * @returns Tool execution result
151
+ */
152
+ export declare function executeTool(toolName: string, params: any, contextRequest?: ContextRequest, options?: ToolExecutionOptions): Promise<ToolResult>;
153
+ /**
154
+ * Utility function to execute text generation pipeline
155
+ *
156
+ * @param prompt Text prompt for generation
157
+ * @param contextRequest Context creation request
158
+ * @param options Generation options
159
+ * @returns Text generation result
160
+ */
161
+ export declare function executeTextPipeline(prompt: string, contextRequest?: ContextRequest, options?: any): Promise<TextPipelineResult>;
162
+ /**
163
+ * Utility function to execute pipeline with default orchestrator
164
+ *
165
+ * @param steps Pipeline steps
166
+ * @param contextRequest Context creation request
167
+ * @param options Pipeline options
168
+ * @returns Pipeline execution result
169
+ */
170
+ export declare function executePipeline(steps: PipelineStep[], contextRequest?: ContextRequest, options?: PipelineOptions): Promise<PipelineResult>;
@@ -0,0 +1,372 @@
1
+ /**
2
+ * NeuroLink MCP Tool Orchestration Engine
3
+ * Central orchestrator for coordinated tool execution with pipeline management
4
+ * Coordinates factory, registry, context, and AI tools for seamless operation
5
+ */
6
+ import { MCPToolRegistry, defaultToolRegistry } from './registry.js';
7
+ import { ContextManager, defaultContextManager, createExecutionContext } from './context-manager.js';
8
+ import { aiCoreServer } from './servers/ai-providers/ai-core-server.js';
9
+ /**
10
+ * NeuroLink MCP Tool Orchestrator
11
+ * Central coordination engine for tool execution, pipelines, and AI operations
12
+ */
13
+ export class MCPOrchestrator {
14
+ registry;
15
+ contextManager;
16
+ pipelineCounter = 0;
17
+ constructor(registry, contextManager) {
18
+ this.registry = registry || defaultToolRegistry;
19
+ this.contextManager = contextManager || defaultContextManager;
20
+ // Initialize with AI Core Server
21
+ this.initializeDefaultServers();
22
+ }
23
+ /**
24
+ * Initialize with default servers (AI Core)
25
+ */
26
+ async initializeDefaultServers() {
27
+ try {
28
+ await this.registry.registerServer(aiCoreServer);
29
+ console.log('[Orchestrator] Initialized with AI Core Server');
30
+ }
31
+ catch (error) {
32
+ console.warn('[Orchestrator] Failed to register AI Core Server:', error);
33
+ }
34
+ }
35
+ /**
36
+ * Execute a single tool with full orchestration
37
+ *
38
+ * @param toolName Tool name to execute
39
+ * @param params Tool parameters
40
+ * @param contextRequest Context creation request
41
+ * @param options Execution options
42
+ * @returns Tool execution result
43
+ */
44
+ async executeTool(toolName, params, contextRequest = {}, options = {}) {
45
+ // Create execution context
46
+ const context = this.contextManager.createContext(contextRequest);
47
+ console.log(`[Orchestrator] Executing tool '${toolName}' in session ${context.sessionId}`);
48
+ // Execute tool through registry
49
+ const result = await this.registry.executeTool(toolName, params, context, options);
50
+ console.log(`[Orchestrator] Tool '${toolName}' execution ${result.success ? 'completed' : 'failed'}`);
51
+ return result;
52
+ }
53
+ /**
54
+ * Execute a pipeline of tools with dependency management
55
+ *
56
+ * @param steps Pipeline steps to execute
57
+ * @param contextRequest Context creation request
58
+ * @param options Pipeline execution options
59
+ * @returns Pipeline execution result
60
+ */
61
+ async executePipeline(steps, contextRequest = {}, options = {}) {
62
+ const startTime = Date.now();
63
+ const pipelineId = this.generatePipelineId();
64
+ const { stopOnError = true, parallel = false, timeout = 60000, trackMetrics = true, validateInputs = true } = options;
65
+ // Create shared execution context
66
+ const context = this.contextManager.createContext({
67
+ ...contextRequest,
68
+ sessionId: contextRequest.sessionId || pipelineId
69
+ });
70
+ const results = new Map();
71
+ const errors = new Map();
72
+ let stepsExecuted = 0;
73
+ let stepsSkipped = 0;
74
+ console.log(`[Orchestrator] Starting pipeline ${pipelineId} with ${steps.length} steps`);
75
+ try {
76
+ if (parallel) {
77
+ // Execute steps in parallel with dependency management
78
+ await this.executeParallelPipeline(steps, context, results, errors, {
79
+ timeout,
80
+ trackMetrics,
81
+ validateInputs,
82
+ stopOnError
83
+ });
84
+ }
85
+ else {
86
+ // Execute steps sequentially
87
+ for (const step of steps) {
88
+ const stepId = step.stepId || `step-${stepsExecuted + 1}`;
89
+ try {
90
+ console.log(`[Orchestrator] Executing step: ${stepId} (${step.toolName})`);
91
+ const stepResult = await this.registry.executeTool(step.toolName, step.params, context, {
92
+ ...step.options,
93
+ validateInput: validateInputs,
94
+ trackMetrics,
95
+ timeoutMs: timeout / steps.length // Distribute timeout across steps
96
+ });
97
+ results.set(stepId, stepResult);
98
+ stepsExecuted++;
99
+ if (!stepResult.success) {
100
+ errors.set(stepId, stepResult.error || 'Unknown error');
101
+ if (stopOnError) {
102
+ console.error(`[Orchestrator] Pipeline ${pipelineId} stopped due to error in step ${stepId}`);
103
+ break;
104
+ }
105
+ }
106
+ }
107
+ catch (error) {
108
+ const errorMessage = error instanceof Error ? error.message : String(error);
109
+ errors.set(stepId, errorMessage);
110
+ if (stopOnError) {
111
+ console.error(`[Orchestrator] Pipeline ${pipelineId} stopped due to exception in step ${stepId}: ${errorMessage}`);
112
+ break;
113
+ }
114
+ stepsSkipped++;
115
+ }
116
+ }
117
+ }
118
+ const executionTime = Date.now() - startTime;
119
+ const success = errors.size === 0 || !stopOnError;
120
+ console.log(`[Orchestrator] Pipeline ${pipelineId} completed in ${executionTime}ms - ${success ? 'SUCCESS' : 'FAILED'}`);
121
+ return {
122
+ success,
123
+ results,
124
+ errors,
125
+ executionTime,
126
+ stepsExecuted,
127
+ stepsSkipped,
128
+ metadata: {
129
+ pipelineId,
130
+ sessionId: context.sessionId,
131
+ timestamp: Date.now(),
132
+ parallel
133
+ }
134
+ };
135
+ }
136
+ catch (error) {
137
+ const executionTime = Date.now() - startTime;
138
+ const errorMessage = error instanceof Error ? error.message : String(error);
139
+ console.error(`[Orchestrator] Pipeline ${pipelineId} failed: ${errorMessage}`);
140
+ return {
141
+ success: false,
142
+ results,
143
+ errors: new Map([['pipeline', errorMessage]]),
144
+ executionTime,
145
+ stepsExecuted,
146
+ stepsSkipped,
147
+ metadata: {
148
+ pipelineId,
149
+ sessionId: context.sessionId,
150
+ timestamp: Date.now(),
151
+ parallel
152
+ }
153
+ };
154
+ }
155
+ }
156
+ /**
157
+ * Execute AI text generation pipeline (high-level convenience method)
158
+ *
159
+ * @param prompt Text prompt for generation
160
+ * @param contextRequest Context creation request
161
+ * @param options Additional generation options
162
+ * @returns Text generation result
163
+ */
164
+ async executeTextPipeline(prompt, contextRequest = {}, options = {}) {
165
+ const startTime = Date.now();
166
+ // Create execution context
167
+ const context = this.contextManager.createContext(contextRequest);
168
+ try {
169
+ console.log(`[Orchestrator] Starting text pipeline for prompt: "${prompt.substring(0, 50)}..."`);
170
+ // Build pipeline steps
171
+ const steps = [];
172
+ // Step 1: Provider selection (if not specified)
173
+ if (!options.provider) {
174
+ steps.push({
175
+ stepId: 'select-provider',
176
+ toolName: 'select-provider',
177
+ params: {
178
+ requirements: {
179
+ maxTokens: options.maxTokens,
180
+ costEfficient: true
181
+ }
182
+ }
183
+ });
184
+ }
185
+ // Step 2: Text generation
186
+ steps.push({
187
+ stepId: 'generate-text',
188
+ toolName: 'generate-text',
189
+ params: {
190
+ prompt,
191
+ provider: options.provider,
192
+ model: options.model,
193
+ temperature: options.temperature,
194
+ maxTokens: options.maxTokens,
195
+ systemPrompt: options.systemPrompt
196
+ },
197
+ dependsOn: options.provider ? [] : ['select-provider']
198
+ });
199
+ // Step 3: Custom tools (if specified)
200
+ if (options.customTools && options.customTools.length > 0) {
201
+ for (const toolName of options.customTools) {
202
+ steps.push({
203
+ stepId: `custom-${toolName}`,
204
+ toolName,
205
+ params: { /* tool-specific params */},
206
+ dependsOn: ['generate-text']
207
+ });
208
+ }
209
+ }
210
+ // Execute pipeline
211
+ const pipelineResult = await this.executePipeline(steps, contextRequest, {
212
+ stopOnError: true,
213
+ parallel: false,
214
+ trackMetrics: true
215
+ });
216
+ const executionTime = Date.now() - startTime;
217
+ // Extract text generation result
218
+ const textResult = pipelineResult.results.get('generate-text');
219
+ const providerResult = pipelineResult.results.get('select-provider');
220
+ if (!textResult || !textResult.success) {
221
+ throw new Error('Text generation failed');
222
+ }
223
+ const toolsUsed = Array.from(pipelineResult.results.keys());
224
+ console.log(`[Orchestrator] Text pipeline completed in ${executionTime}ms`);
225
+ return {
226
+ success: true,
227
+ text: textResult.data?.text,
228
+ provider: textResult.data?.provider || providerResult?.data?.provider,
229
+ model: textResult.data?.model,
230
+ executionTime,
231
+ usage: textResult.usage,
232
+ metadata: {
233
+ sessionId: context.sessionId,
234
+ timestamp: Date.now(),
235
+ toolsUsed
236
+ }
237
+ };
238
+ }
239
+ catch (error) {
240
+ const executionTime = Date.now() - startTime;
241
+ const errorMessage = error instanceof Error ? error.message : String(error);
242
+ console.error(`[Orchestrator] Text pipeline failed: ${errorMessage}`);
243
+ return {
244
+ success: false,
245
+ executionTime,
246
+ metadata: {
247
+ sessionId: context.sessionId,
248
+ timestamp: Date.now(),
249
+ toolsUsed: []
250
+ }
251
+ };
252
+ }
253
+ }
254
+ /**
255
+ * Get orchestrator statistics
256
+ *
257
+ * @returns Comprehensive orchestrator statistics
258
+ */
259
+ getStats() {
260
+ return {
261
+ registry: this.registry.getStats(),
262
+ context: this.contextManager.getStats(),
263
+ orchestrator: {
264
+ pipelinesExecuted: this.pipelineCounter
265
+ }
266
+ };
267
+ }
268
+ /**
269
+ * Execute parallel pipeline with dependency management
270
+ *
271
+ * @private
272
+ */
273
+ async executeParallelPipeline(steps, context, results, errors, options) {
274
+ // Build dependency graph
275
+ const stepMap = new Map();
276
+ const dependencyGraph = new Map();
277
+ for (const step of steps) {
278
+ const stepId = step.stepId || `step-${stepMap.size + 1}`;
279
+ stepMap.set(stepId, { ...step, stepId });
280
+ dependencyGraph.set(stepId, step.dependsOn || []);
281
+ }
282
+ // Execute steps in dependency order
283
+ const completed = new Set();
284
+ const executing = new Set();
285
+ while (completed.size < steps.length) {
286
+ const readySteps = Array.from(stepMap.keys()).filter(stepId => {
287
+ if (completed.has(stepId) || executing.has(stepId))
288
+ return false;
289
+ const dependencies = dependencyGraph.get(stepId) || [];
290
+ return dependencies.every(dep => completed.has(dep));
291
+ });
292
+ if (readySteps.length === 0) {
293
+ throw new Error('Circular dependency detected in pipeline');
294
+ }
295
+ // Execute ready steps in parallel
296
+ const executePromises = readySteps.map(async (stepId) => {
297
+ executing.add(stepId);
298
+ const step = stepMap.get(stepId);
299
+ try {
300
+ const result = await this.registry.executeTool(step.toolName, step.params, context, { ...step.options, ...options });
301
+ results.set(stepId, result);
302
+ if (!result.success) {
303
+ errors.set(stepId, result.error || 'Unknown error');
304
+ }
305
+ }
306
+ catch (error) {
307
+ const errorMessage = error instanceof Error ? error.message : String(error);
308
+ errors.set(stepId, errorMessage);
309
+ }
310
+ finally {
311
+ executing.delete(stepId);
312
+ completed.add(stepId);
313
+ }
314
+ });
315
+ await Promise.all(executePromises);
316
+ // Check for errors and stop if configured
317
+ if (options.stopOnError && errors.size > 0) {
318
+ break;
319
+ }
320
+ }
321
+ }
322
+ /**
323
+ * Generate unique pipeline ID
324
+ *
325
+ * @private
326
+ */
327
+ generatePipelineId() {
328
+ this.pipelineCounter++;
329
+ const timestamp = Date.now();
330
+ const random = Math.random().toString(36).substring(2, 8);
331
+ return `nlpipe-${timestamp}-${this.pipelineCounter}-${random}`;
332
+ }
333
+ }
334
+ /**
335
+ * Default orchestrator instance
336
+ * Ready-to-use orchestrator with pre-configured registry and context manager
337
+ */
338
+ export const defaultOrchestrator = new MCPOrchestrator();
339
+ /**
340
+ * Utility function to execute tool with default orchestrator
341
+ *
342
+ * @param toolName Tool name to execute
343
+ * @param params Tool parameters
344
+ * @param contextRequest Context creation request
345
+ * @param options Execution options
346
+ * @returns Tool execution result
347
+ */
348
+ export async function executeTool(toolName, params, contextRequest, options) {
349
+ return defaultOrchestrator.executeTool(toolName, params, contextRequest, options);
350
+ }
351
+ /**
352
+ * Utility function to execute text generation pipeline
353
+ *
354
+ * @param prompt Text prompt for generation
355
+ * @param contextRequest Context creation request
356
+ * @param options Generation options
357
+ * @returns Text generation result
358
+ */
359
+ export async function executeTextPipeline(prompt, contextRequest, options) {
360
+ return defaultOrchestrator.executeTextPipeline(prompt, contextRequest, options);
361
+ }
362
+ /**
363
+ * Utility function to execute pipeline with default orchestrator
364
+ *
365
+ * @param steps Pipeline steps
366
+ * @param contextRequest Context creation request
367
+ * @param options Pipeline options
368
+ * @returns Pipeline execution result
369
+ */
370
+ export async function executePipeline(steps, contextRequest, options) {
371
+ return defaultOrchestrator.executePipeline(steps, contextRequest, options);
372
+ }