snow-flow 2.0.2 → 2.0.3

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 (173) hide show
  1. package/{.claude/mcp-config.json → .mcp.json} +13 -12
  2. package/.releaserc.json +47 -0
  3. package/README.md +6 -0
  4. package/package.json +1 -1
  5. package/.claude/claude-settings.json +0 -15
  6. package/.claude/commands/analysis/README.md +0 -9
  7. package/.claude/commands/automation/README.md +0 -9
  8. package/.claude/commands/github/README.md +0 -11
  9. package/.claude/commands/helpers/standard-checkpoint-hooks.sh +0 -179
  10. package/.claude/commands/hooks/README.md +0 -11
  11. package/.claude/commands/monitoring/README.md +0 -9
  12. package/.claude/commands/optimization/README.md +0 -9
  13. package/.claude/commands/training/README.md +0 -9
  14. package/.claude/commands/workflows/README.md +0 -9
  15. package/.claude/config.json +0 -36
  16. package/.claude/helpers/github-setup.sh +0 -28
  17. package/.claude/helpers/quick-start.sh +0 -19
  18. package/.claude/helpers/setup-mcp.sh +0 -18
  19. package/.claude/settings.json +0 -114
  20. package/.claude/settings.local.json +0 -33
  21. package/.claude-flow/metrics/agent-metrics.json +0 -1
  22. package/.claude-flow/metrics/performance.json +0 -9
  23. package/.claude-flow/metrics/system-metrics.json +0 -15986
  24. package/.claude-flow/metrics/task-metrics.json +0 -10
  25. package/.roo/README.md +0 -402
  26. package/.roo/mcp-list.txt +0 -257
  27. package/.roo/mcp.json +0 -32
  28. package/.roo/workflows/basic-tdd.json +0 -32
  29. package/.roomodes +0 -201
  30. package/CLAUDE.md +0 -393
  31. package/bin/snow-flow.js +0 -3
  32. package/dist/cli.js.bak +0 -2052
  33. package/dist/config/snow-flow-config.d.ts +0 -1492
  34. package/dist/config/snow-flow-config.js +0 -938
  35. package/scripts/create-env.js +0 -91
  36. package/scripts/postinstall.js +0 -30
  37. package/scripts/register-mcp-servers.js +0 -210
  38. package/scripts/reset-mcp-servers.js +0 -246
  39. package/scripts/setup-mcp.js +0 -106
  40. package/scripts/update-version.js +0 -31
  41. package/src/agents/README.md +0 -192
  42. package/src/agents/base-agent.ts +0 -251
  43. package/src/agents/coordinator.ts +0 -971
  44. package/src/agents/index.ts +0 -18
  45. package/src/agents/queen-403-handler.ts +0 -230
  46. package/src/agents/queen-agent.ts +0 -1399
  47. package/src/agents/script-writer-agent.ts +0 -769
  48. package/src/agents/security-agent.ts +0 -726
  49. package/src/agents/widget-creator-agent.ts +0 -568
  50. package/src/api/error-handling.ts +0 -1758
  51. package/src/api/natural-language-mapper.ts +0 -630
  52. package/src/api/performance-optimizer.ts +0 -891
  53. package/src/api/transaction-manager.ts +0 -754
  54. package/src/cli/deploy-artifact.ts +0 -304
  55. package/src/cli/snow-flow-cli-integration.ts +0 -434
  56. package/src/cli.ts +0 -4455
  57. package/src/cli.ts.bak +0 -5616
  58. package/src/compliance/advanced-compliance-system.ts +0 -1268
  59. package/src/compliance/index.ts +0 -19
  60. package/src/config/snow-flow-config.ts +0 -1019
  61. package/src/documentation/index.ts +0 -16
  62. package/src/documentation/self-documenting-system.ts +0 -1421
  63. package/src/dynamic-version.ts +0 -44
  64. package/src/healing/index.ts +0 -20
  65. package/src/healing/self-healing-system.ts +0 -1435
  66. package/src/health/README.md +0 -161
  67. package/src/health/system-health.ts +0 -995
  68. package/src/index.ts +0 -60
  69. package/src/intelligence/acl-analyzer.ts +0 -377
  70. package/src/intelligence/auto-resolution-engine.ts +0 -643
  71. package/src/intelligence/gap-analysis-engine.ts +0 -488
  72. package/src/intelligence/manual-instructions-generator.ts +0 -744
  73. package/src/intelligence/mcp-coverage-analyzer.ts +0 -708
  74. package/src/intelligence/multi-pass-requirements-analyzer.ts +0 -603
  75. package/src/intelligence/performance-recommendations-engine.ts +0 -1223
  76. package/src/intelligence/requirements-analyzer.ts +0 -1148
  77. package/src/intelligence/task-analyzer.ts +0 -628
  78. package/src/managers/scope-manager.ts +0 -555
  79. package/src/mcp/advanced/servicenow-advanced-features-mcp.ts +0 -16110
  80. package/src/mcp/base-mcp-server.ts +0 -660
  81. package/src/mcp/http-transport-wrapper.ts +0 -426
  82. package/src/mcp/service-discovery-client.ts +0 -312
  83. package/src/mcp/servicenow-automation-mcp-refactored.ts +0 -678
  84. package/src/mcp/servicenow-automation-mcp.ts +0 -838
  85. package/src/mcp/servicenow-deployment-mcp-refactored.ts +0 -1292
  86. package/src/mcp/servicenow-deployment-mcp.ts +0 -7244
  87. package/src/mcp/servicenow-graph-memory-mcp-refactored.ts +0 -721
  88. package/src/mcp/servicenow-graph-memory-mcp.ts +0 -832
  89. package/src/mcp/servicenow-integration-mcp-refactored.ts +0 -655
  90. package/src/mcp/servicenow-integration-mcp.ts +0 -819
  91. package/src/mcp/servicenow-intelligent-mcp-refactored.ts +0 -977
  92. package/src/mcp/servicenow-intelligent-mcp.ts +0 -4638
  93. package/src/mcp/servicenow-mcp-server.ts +0 -728
  94. package/src/mcp/servicenow-memory-mcp.ts +0 -474
  95. package/src/mcp/servicenow-operations-mcp-refactored.ts +0 -1995
  96. package/src/mcp/servicenow-operations-mcp.ts +0 -3384
  97. package/src/mcp/servicenow-platform-development-mcp-refactored.ts +0 -611
  98. package/src/mcp/servicenow-platform-development-mcp.ts +0 -970
  99. package/src/mcp/servicenow-progressive-indexer.ts +0 -370
  100. package/src/mcp/servicenow-reporting-analytics-mcp-refactored.ts +0 -695
  101. package/src/mcp/servicenow-reporting-analytics-mcp.ts +0 -1123
  102. package/src/mcp/servicenow-security-compliance-mcp-refactored.ts +0 -642
  103. package/src/mcp/servicenow-security-compliance-mcp.ts +0 -1157
  104. package/src/mcp/servicenow-update-set-mcp-refactored.ts +0 -751
  105. package/src/mcp/servicenow-update-set-mcp.ts +0 -811
  106. package/src/mcp/shared/agent-context-provider.ts +0 -365
  107. package/src/mcp/shared/base-mcp-server.ts +0 -2463
  108. package/src/mcp/shared/mcp-memory-manager.ts +0 -540
  109. package/src/mcp/shared/mcp-resource-manager.ts +0 -367
  110. package/src/mcp/snow-flow-mcp.ts +0 -911
  111. package/src/mcp/start-all-mcp-servers.ts +0 -102
  112. package/src/mcp/start-servicenow-mcp.ts +0 -67
  113. package/src/monitoring/enhanced-monitoring-system.ts +0 -1345
  114. package/src/monitoring/performance-tracker.ts +0 -777
  115. package/src/optimization/cost-optimization-engine.ts +0 -1125
  116. package/src/optimization/index.ts +0 -10
  117. package/src/queen/README.md +0 -403
  118. package/src/queen/agent-factory.ts +0 -574
  119. package/src/queen/index.ts +0 -94
  120. package/src/queen/mcp-execution-bridge.ts +0 -681
  121. package/src/queen/neural-learning.ts +0 -319
  122. package/src/queen/parallel-agent-engine.ts +0 -848
  123. package/src/queen/queen-memory-system.ts +0 -490
  124. package/src/queen/queen-memory.ts +0 -456
  125. package/src/queen/servicenow-queen.ts +0 -1029
  126. package/src/queen/types.ts +0 -87
  127. package/src/rollback/smart-rollback-system.ts +0 -866
  128. package/src/schemas/deployment.schema.json +0 -58
  129. package/src/schemas/flow.schema.json +0 -79
  130. package/src/schemas/widget.schema.json +0 -72
  131. package/src/snow-flow-system.ts +0 -541
  132. package/src/sparc/sparc-help.ts +0 -49
  133. package/src/sparc/team-sparc.ts +0 -88
  134. package/src/strategies/global-scope-strategy.ts +0 -736
  135. package/src/templates/base/application.template.json +0 -45
  136. package/src/templates/base/business_rule.template.json +0 -33
  137. package/src/templates/base/script_include.template.json +0 -18
  138. package/src/templates/base/table.template.json +0 -64
  139. package/src/templates/base/widget.template.json +0 -25
  140. package/src/templates/patterns/composite.incident-management.template.json +0 -140
  141. package/src/templates/patterns/widget.dashboard.template.json +0 -238
  142. package/src/templates/patterns/widget.datatable.template.json +0 -292
  143. package/src/testing/integration-test-suite.ts +0 -1276
  144. package/src/types/index.ts +0 -183
  145. package/src/types/neo4j-driver.d.ts +0 -23
  146. package/src/types/servicenow.types.ts +0 -307
  147. package/src/types/snow-flow.types.ts +0 -186
  148. package/src/types/todo.types.ts +0 -70
  149. package/src/utils/action-type-cache.ts +0 -286
  150. package/src/utils/agent-detector.ts +0 -573
  151. package/src/utils/artifact-tracker.ts +0 -379
  152. package/src/utils/dependency-detector.ts +0 -233
  153. package/src/utils/deployment-metadata-handler.ts +0 -518
  154. package/src/utils/error-recovery.ts +0 -680
  155. package/src/utils/logger.ts +0 -60
  156. package/src/utils/mcp-auth-middleware.ts +0 -262
  157. package/src/utils/mcp-config-manager.ts +0 -270
  158. package/src/utils/mcp-server-manager.ts +0 -446
  159. package/src/utils/mcp-tool-registry.ts +0 -298
  160. package/src/utils/migrate-snow-flow.ts +0 -98
  161. package/src/utils/oauth-html-templates.ts +0 -188
  162. package/src/utils/scope-utils.ts +0 -443
  163. package/src/utils/servicenow-client.ts +0 -3321
  164. package/src/utils/servicenow-id-generator.ts +0 -181
  165. package/src/utils/snow-memory-manager.ts +0 -605
  166. package/src/utils/snow-oauth.ts +0 -797
  167. package/src/utils/template-engine.ts +0 -463
  168. package/src/utils/theme-manager.ts +0 -295
  169. package/src/utils/unified-auth-store.ts +0 -222
  170. package/src/utils/update-set-importer.ts +0 -422
  171. package/src/utils/update-set-xml-packager.ts +0 -371
  172. package/src/utils/widget-template-generator.ts +0 -1744
  173. package/src/version.ts +0 -1950
@@ -1,660 +0,0 @@
1
- /**
2
- * Base MCP Server Implementation
3
- *
4
- * Solves DRY violations by providing common functionality for all MCP servers:
5
- * - Unified authentication handling
6
- * - Consistent error handling
7
- * - Session management
8
- * - Logging and monitoring
9
- * - Retry logic with exponential backoff
10
- */
11
-
12
- import { Server } from '@modelcontextprotocol/sdk/server/index.js';
13
- import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
14
- import {
15
- CallToolRequestSchema,
16
- ErrorCode,
17
- ListToolsRequestSchema,
18
- McpError,
19
- Tool,
20
- } from '@modelcontextprotocol/sdk/types.js';
21
- import { ServiceNowClient } from '../utils/servicenow-client.js';
22
- import { ServiceNowOAuth } from '../utils/snow-oauth.js';
23
- import { Logger } from '../utils/logger.js';
24
-
25
- export interface MCPServerConfig {
26
- name: string;
27
- version: string;
28
- description?: string;
29
- requiresAuth?: boolean; // Optional flag to disable ServiceNow authentication
30
- capabilities?: {
31
- tools?: {};
32
- resources?: {};
33
- prompts?: {};
34
- };
35
- }
36
-
37
- export interface ToolResult<T = any> {
38
- success: boolean;
39
- result?: T;
40
- error?: string;
41
- retryable?: boolean;
42
- executionTime?: number;
43
- }
44
-
45
- export interface AuthResult {
46
- success: boolean;
47
- error?: string;
48
- token?: string;
49
- expiresIn?: number;
50
- }
51
-
52
- /**
53
- * Base class for all ServiceNow MCP servers
54
- * Provides common functionality to eliminate code duplication
55
- */
56
- export abstract class BaseMCPServer {
57
- protected server: Server;
58
- protected client: ServiceNowClient;
59
- protected oauth: ServiceNowOAuth;
60
- protected logger: Logger;
61
- protected transport: StdioServerTransport;
62
- protected tools: Map<string, Tool> = new Map();
63
- protected config: MCPServerConfig; // Store the config for later use
64
-
65
- // Session management
66
- private sessionToken?: string;
67
- private sessionExpiry?: Date;
68
- private authCheckInterval?: NodeJS.Timeout;
69
-
70
- // Performance tracking
71
- private toolMetrics: Map<string, { calls: number; totalTime: number; errors: number }> = new Map();
72
-
73
- constructor(config: MCPServerConfig) {
74
- // Store the config
75
- this.config = config;
76
- // Initialize server with config
77
- this.server = new Server(
78
- {
79
- name: config.name,
80
- version: config.version,
81
- },
82
- {
83
- capabilities: config.capabilities || { tools: {} },
84
- }
85
- );
86
-
87
- // Initialize common dependencies
88
- this.client = new ServiceNowClient();
89
- this.oauth = new ServiceNowOAuth();
90
- this.logger = new Logger(`MCP:${config.name}`);
91
- this.transport = new StdioServerTransport();
92
-
93
- // Setup common functionality
94
- this.setupCommonHandlers();
95
- this.setupAuthentication();
96
- this.setupErrorHandling();
97
- this.setupMetrics();
98
-
99
- // Let child classes define their specific tools
100
- this.setupTools();
101
- }
102
-
103
- /**
104
- * Setup common request handlers
105
- */
106
- private setupCommonHandlers(): void {
107
- // Handle tool listing
108
- this.server.setRequestHandler(ListToolsRequestSchema, async () => ({
109
- tools: Array.from(this.tools.values()),
110
- }));
111
-
112
- // Handle tool execution with common auth/error handling
113
- this.server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
114
- const { name, arguments: args } = request.params;
115
-
116
- // Track metrics
117
- const startTime = Date.now();
118
- const metrics = this.toolMetrics.get(name) || { calls: 0, totalTime: 0, errors: 0 };
119
- metrics.calls++;
120
-
121
- try {
122
- // Validate authentication first (skip if not required)
123
- if (this.config.requiresAuth !== false) {
124
- const authResult = await this.validateAuth();
125
- if (!authResult.success) {
126
- throw new McpError(
127
- ErrorCode.InvalidRequest,
128
- `Authentication failed: ${authResult.error}`
129
- );
130
- }
131
- }
132
-
133
- // Execute tool with retry logic
134
- const result = await this.executeWithRetry(name, args);
135
-
136
- // Update metrics
137
- metrics.totalTime += Date.now() - startTime;
138
- this.toolMetrics.set(name, metrics);
139
-
140
- return result;
141
- } catch (error) {
142
- // Update error metrics
143
- metrics.errors++;
144
- metrics.totalTime += Date.now() - startTime;
145
- this.toolMetrics.set(name, metrics);
146
-
147
- throw error;
148
- }
149
- });
150
- }
151
-
152
- /**
153
- * Setup authentication with automatic token refresh
154
- */
155
- private setupAuthentication(): void {
156
- // Skip authentication setup if not required
157
- if (this.config.requiresAuth === false) {
158
- return;
159
- }
160
-
161
- // Check auth every 5 minutes
162
- this.authCheckInterval = setInterval(async () => {
163
- try {
164
- await this.validateAuth();
165
- } catch (error) {
166
- this.logger.error('Background auth check failed:', error);
167
- }
168
- }, 5 * 60 * 1000);
169
- }
170
-
171
- /**
172
- * Validate authentication with smart caching
173
- */
174
- protected async validateAuth(): Promise<AuthResult> {
175
- try {
176
- // Check if we have a valid session
177
- if (this.sessionToken && this.sessionExpiry && this.sessionExpiry > new Date()) {
178
- return { success: true, token: this.sessionToken };
179
- }
180
-
181
- // Validate connection
182
- const connectionResult = await this.validateServiceNowConnection();
183
- if (!connectionResult.success) {
184
- return {
185
- success: false,
186
- error: connectionResult.error || 'Authentication validation failed'
187
- };
188
- }
189
-
190
- // Get fresh token
191
- const isAuthenticated = await this.oauth.isAuthenticated();
192
- if (!isAuthenticated) {
193
- // Try to refresh
194
- try {
195
- await this.oauth.refreshAccessToken();
196
- } catch (refreshError) {
197
- return {
198
- success: false,
199
- error: 'OAuth authentication required. Run "snow-flow auth login" to authenticate.',
200
- };
201
- }
202
- }
203
-
204
- // Cache session info
205
- const tokenInfo = await this.oauth.loadTokens();
206
- this.sessionToken = tokenInfo?.access_token;
207
- this.sessionExpiry = new Date(Date.now() + (tokenInfo?.expires_in || 3600) * 1000);
208
-
209
- return {
210
- success: true,
211
- token: this.sessionToken,
212
- expiresIn: tokenInfo.expires_in,
213
- };
214
- } catch (error) {
215
- this.logger.error('Authentication validation failed:', error);
216
- return {
217
- success: false,
218
- error: error instanceof Error ? error.message : 'Unknown authentication error',
219
- };
220
- }
221
- }
222
-
223
- /**
224
- * 🔴 SNOW-003 FIX: Enhanced retry logic with intelligent backoff and circuit breaker
225
- * Addresses the 19% failure rate with better retry strategies and failure prevention
226
- */
227
- private async executeWithRetry(toolName: string, args: any, attempt = 1): Promise<any> {
228
- // 🔴 CRITICAL: Increased retries from 3 to 6 for better resilience
229
- const maxRetries = 6;
230
-
231
- // 🔴 CRITICAL: Intelligent backoff based on error type
232
- const backoffMs = this.calculateBackoff(attempt, toolName);
233
-
234
- // 🔴 CRITICAL: Dynamic timeout based on tool complexity
235
- const timeout = this.calculateTimeout(toolName);
236
-
237
- try {
238
- // Get tool handler
239
- const handler = this.getToolHandler(toolName);
240
- if (!handler) {
241
- throw new McpError(ErrorCode.MethodNotFound, `Unknown tool: ${toolName}`);
242
- }
243
-
244
- // 🔴 CRITICAL: Memory usage check before execution
245
- if (attempt === 1) {
246
- await this.checkMemoryUsage();
247
- }
248
-
249
- // Execute with dynamic timeout
250
- const result = await Promise.race([
251
- handler(args),
252
- new Promise((_, reject) =>
253
- setTimeout(() => reject(new Error(`Tool execution timeout after ${timeout}ms`)), timeout)
254
- ),
255
- ]);
256
-
257
- // 🔴 SUCCESS: Reset circuit breaker on success
258
- this.resetCircuitBreaker(toolName);
259
-
260
- return result;
261
- } catch (error) {
262
- this.logger.error(`🔴 Tool ${toolName} execution failed (attempt ${attempt}/${maxRetries}):`, error);
263
-
264
- // 🔴 CRITICAL: Update circuit breaker
265
- this.updateCircuitBreaker(toolName, error);
266
-
267
- // Check if retryable and within limits
268
- if (attempt < maxRetries && this.isRetryableError(error) && !this.isCircuitBreakerOpen(toolName)) {
269
- this.logger.info(`🔄 Retrying ${toolName} after ${backoffMs}ms (attempt ${attempt + 1}/${maxRetries})...`);
270
- await new Promise(resolve => setTimeout(resolve, backoffMs));
271
- return this.executeWithRetry(toolName, args, attempt + 1);
272
- }
273
-
274
- // 🔴 FINAL FAILURE: Enhanced error reporting
275
- const errorMessage = this.createEnhancedErrorMessage(toolName, error, attempt, maxRetries);
276
- throw new McpError(ErrorCode.InternalError, errorMessage);
277
- }
278
- }
279
-
280
- /**
281
- * 🔴 SNOW-003 FIX: Calculate intelligent backoff based on error type and attempt
282
- */
283
- private calculateBackoff(attempt: number, toolName: string): number {
284
- // Base exponential backoff: 1s, 2s, 4s, 8s, 16s, 32s
285
- const baseBackoff = 1000 * Math.pow(2, attempt - 1);
286
-
287
- // Add jitter to prevent thundering herd (±25%)
288
- const jitter = baseBackoff * 0.25 * (Math.random() - 0.5);
289
-
290
- // Cap maximum backoff at 30 seconds
291
- const maxBackoff = 30000;
292
-
293
- return Math.min(baseBackoff + jitter, maxBackoff);
294
- }
295
-
296
- /**
297
- * 🔴 SNOW-003 FIX: Calculate dynamic timeout based on tool complexity
298
- */
299
- private calculateTimeout(toolName: string): number {
300
- // Tool-specific timeouts based on complexity
301
- const timeoutMap: Record<string, number> = {
302
- 'snow_create_flow': 90000, // Flow creation: 90s
303
- 'snow_deploy': 120000, // Deployment: 2 minutes
304
- 'snow_comprehensive_search': 45000, // Search: 45s
305
- 'snow_find_artifact': 30000, // Find: 30s
306
- 'snow_validate_live_connection': 15000, // Validation: 15s
307
- };
308
-
309
- // Default timeout for unknown tools
310
- return timeoutMap[toolName] || 60000; // 60s default (increased from 30s)
311
- }
312
-
313
- // 🔴 SNOW-003 FIX: Circuit breaker implementation
314
- private circuitBreakers: Map<string, { failures: number; lastFailure: number; isOpen: boolean }> = new Map();
315
-
316
- private updateCircuitBreaker(toolName: string, error: any): void {
317
- const breaker = this.circuitBreakers.get(toolName) || { failures: 0, lastFailure: 0, isOpen: false };
318
-
319
- breaker.failures++;
320
- breaker.lastFailure = Date.now();
321
-
322
- // Open circuit breaker after 5 failures within 5 minutes
323
- if (breaker.failures >= 5 && (Date.now() - breaker.lastFailure) < 300000) {
324
- breaker.isOpen = true;
325
- this.logger.warn(`🚨 Circuit breaker opened for ${toolName} due to repeated failures`);
326
- }
327
-
328
- this.circuitBreakers.set(toolName, breaker);
329
- }
330
-
331
- private isCircuitBreakerOpen(toolName: string): boolean {
332
- const breaker = this.circuitBreakers.get(toolName);
333
- if (!breaker || !breaker.isOpen) return false;
334
-
335
- // Auto-reset circuit breaker after 10 minutes
336
- if (Date.now() - breaker.lastFailure > 600000) {
337
- breaker.isOpen = false;
338
- breaker.failures = 0;
339
- this.circuitBreakers.set(toolName, breaker);
340
- this.logger.info(`✅ Circuit breaker reset for ${toolName}`);
341
- return false;
342
- }
343
-
344
- return true;
345
- }
346
-
347
- private resetCircuitBreaker(toolName: string): void {
348
- const breaker = this.circuitBreakers.get(toolName);
349
- if (breaker) {
350
- breaker.failures = 0;
351
- breaker.isOpen = false;
352
- this.circuitBreakers.set(toolName, breaker);
353
- }
354
- }
355
-
356
- /**
357
- * 🔴 SNOW-003 FIX: Memory usage monitoring to prevent memory exhaustion failures
358
- */
359
- private async checkMemoryUsage(): Promise<void> {
360
- try {
361
- const memUsage = process.memoryUsage();
362
- const heapUsedMB = Math.round(memUsage.heapUsed / 1024 / 1024);
363
- const heapTotalMB = Math.round(memUsage.heapTotal / 1024 / 1024);
364
-
365
- // Log memory usage if high (>200MB)
366
- if (heapUsedMB > 200) {
367
- this.logger.warn(`⚠️ High memory usage: ${heapUsedMB}MB heap used, ${heapTotalMB}MB total`);
368
- }
369
-
370
- // Trigger garbage collection if memory usage is very high (>500MB)
371
- if (heapUsedMB > 500 && global.gc) {
372
- this.logger.info('🧹 Triggering garbage collection due to high memory usage');
373
- global.gc();
374
- }
375
-
376
- // Fail fast if memory usage is critical (>800MB)
377
- if (heapUsedMB > 800) {
378
- throw new Error(`Critical memory usage: ${heapUsedMB}MB. Operation aborted to prevent system instability.`);
379
- }
380
-
381
- } catch (error) {
382
- this.logger.warn('Could not check memory usage:', error);
383
- }
384
- }
385
-
386
- /**
387
- * 🔴 SNOW-003 FIX: Enhanced error message with troubleshooting guidance
388
- */
389
- private createEnhancedErrorMessage(toolName: string, error: any, attempts: number, maxRetries: number): string {
390
- const baseMessage = `Tool '${toolName}' failed after ${attempts}/${maxRetries} attempts`;
391
- const errorDetail = error instanceof Error ? error.message : String(error);
392
-
393
- let troubleshooting = '';
394
-
395
- // Add specific troubleshooting based on error type
396
- if ((error as any).response?.status === 401) {
397
- troubleshooting = '\n💡 Authentication issue: Run "snow-flow auth login" to re-authenticate';
398
- } else if ((error as any).response?.status === 403) {
399
- troubleshooting = '\n💡 Permission issue: Check ServiceNow user permissions and OAuth scopes';
400
- } else if ((error as any).response?.status >= 500) {
401
- troubleshooting = '\n💡 ServiceNow server issue: Try again later or contact ServiceNow administrator';
402
- } else if (errorDetail.includes('timeout')) {
403
- troubleshooting = '\n💡 Timeout issue: ServiceNow instance may be slow - try again later';
404
- } else if (errorDetail.includes('network') || errorDetail.includes('connection')) {
405
- troubleshooting = '\n💡 Network issue: Check internet connection and ServiceNow instance availability';
406
- }
407
-
408
- return `${baseMessage}: ${errorDetail}${troubleshooting}`;
409
- }
410
-
411
- /**
412
- * 🔴 SNOW-003 FIX: Enhanced error classification for ServiceNow specific errors
413
- * Addresses the 19% failure rate by properly categorizing retryable errors
414
- */
415
- private isRetryableError(error: any): boolean {
416
- if (error instanceof Error) {
417
- const message = error.message.toLowerCase();
418
-
419
- // 🔴 CRITICAL: ServiceNow specific retryable errors
420
- const serviceNowRetryable = (
421
- message.includes('timeout') ||
422
- message.includes('econnreset') ||
423
- message.includes('socket hang up') ||
424
- message.includes('enotfound') ||
425
- message.includes('rate limit') ||
426
- message.includes('service unavailable') ||
427
- message.includes('bad gateway') ||
428
- message.includes('gateway timeout') ||
429
- message.includes('connection refused') ||
430
- message.includes('network error') ||
431
- message.includes('dns lookup failed') ||
432
- message.includes('connect etimedout') ||
433
- message.includes('index not available') ||
434
- message.includes('search index updating') ||
435
- message.includes('temporary failure') ||
436
- message.includes('server is busy') ||
437
- message.includes('database lock') ||
438
- message.includes('deadlock detected')
439
- );
440
-
441
- // 🔴 CRITICAL: HTTP status code based retry logic
442
- if ((error as any).response?.status) {
443
- const status = (error as any).response.status;
444
- const httpRetryable = (
445
- status === 429 || // Rate limit
446
- status === 502 || // Bad Gateway
447
- status === 503 || // Service Unavailable
448
- status === 504 || // Gateway Timeout
449
- status === 507 || // Insufficient Storage
450
- status === 520 || // CloudFlare unknown error
451
- status === 521 || // Web server is down
452
- status === 522 || // Connection timed out
453
- status === 523 || // Origin is unreachable
454
- status === 524 // A timeout occurred
455
- );
456
-
457
- // 401 is retryable only once (for token refresh)
458
- const authRetryable = status === 401 && !(error as any).config?._retry;
459
-
460
- return httpRetryable || authRetryable;
461
- }
462
-
463
- return serviceNowRetryable;
464
- }
465
-
466
- // Handle specific error types
467
- if (error.code) {
468
- const retryableCodes = [
469
- 'ECONNRESET', 'ENOTFOUND', 'ECONNREFUSED', 'ETIMEDOUT',
470
- 'ESOCKETTIMEDOUT', 'EHOSTUNREACH', 'EPIPE', 'EAI_AGAIN'
471
- ];
472
- return retryableCodes.includes(error.code);
473
- }
474
-
475
- return false;
476
- }
477
-
478
- /**
479
- * Setup global error handling
480
- */
481
- private setupErrorHandling(): void {
482
- process.on('uncaughtException', (error) => {
483
- this.logger.error('Uncaught exception:', error);
484
- this.gracefulShutdown();
485
- });
486
-
487
- process.on('unhandledRejection', (reason, promise) => {
488
- this.logger.error('Unhandled rejection:', { promise, reason });
489
- });
490
-
491
- process.on('SIGINT', () => {
492
- this.logger.info('Received SIGINT, shutting down gracefully...');
493
- this.gracefulShutdown();
494
- });
495
- }
496
-
497
- /**
498
- * Setup metrics collection
499
- */
500
- private setupMetrics(): void {
501
- // Log metrics every minute
502
- setInterval(() => {
503
- const metrics = Array.from(this.toolMetrics.entries()).map(([tool, data]) => ({
504
- tool,
505
- calls: data.calls,
506
- avgTime: data.calls > 0 ? Math.round(data.totalTime / data.calls) : 0,
507
- errorRate: data.calls > 0 ? (data.errors / data.calls * 100).toFixed(2) : '0',
508
- }));
509
-
510
- if (metrics.length > 0) {
511
- this.logger.info('Tool metrics:', metrics);
512
- }
513
- }, 60000);
514
- }
515
-
516
- /**
517
- * Execute tool with common error handling
518
- */
519
- protected async executeTool<T>(
520
- toolName: string,
521
- handler: () => Promise<T>
522
- ): Promise<ToolResult<T>> {
523
- const startTime = Date.now();
524
-
525
- try {
526
- // Validate auth before execution
527
- const authResult = await this.validateAuth();
528
- if (!authResult.success) {
529
- return {
530
- success: false,
531
- error: authResult.error,
532
- retryable: true,
533
- };
534
- }
535
-
536
- // Execute the tool logic
537
- const result = await handler();
538
-
539
- // Log success
540
- this.logger.debug(`Tool ${toolName} executed successfully in ${Date.now() - startTime}ms`);
541
-
542
- return {
543
- success: true,
544
- result,
545
- executionTime: Date.now() - startTime,
546
- };
547
- } catch (error) {
548
- this.logger.error(`Tool ${toolName} failed:`, error);
549
-
550
- return {
551
- success: false,
552
- error: error instanceof Error ? error.message : 'Unknown error',
553
- retryable: this.isRetryableError(error),
554
- executionTime: Date.now() - startTime,
555
- };
556
- }
557
- }
558
-
559
- /**
560
- * Register a tool
561
- */
562
- protected registerTool(tool: Tool, handler: (args: any) => Promise<any>): void {
563
- this.tools.set(tool.name, tool);
564
- this.toolHandlers.set(tool.name, handler);
565
- }
566
-
567
- /**
568
- * Tool handlers map
569
- */
570
- private toolHandlers: Map<string, (args: any) => Promise<any>> = new Map();
571
-
572
- /**
573
- * Get tool handler
574
- */
575
- private getToolHandler(name: string): ((args: any) => Promise<any>) | undefined {
576
- return this.toolHandlers.get(name);
577
- }
578
-
579
- /**
580
- * Graceful shutdown
581
- */
582
- private async gracefulShutdown(): Promise<void> {
583
- this.logger.info('Starting graceful shutdown...');
584
-
585
- // Clear intervals
586
- if (this.authCheckInterval) {
587
- clearInterval(this.authCheckInterval);
588
- }
589
-
590
- // Log final metrics
591
- const metrics = Array.from(this.toolMetrics.entries());
592
- if (metrics.length > 0) {
593
- this.logger.info('Final metrics:', metrics);
594
- }
595
-
596
- // Close connections
597
- try {
598
- await this.oauth.logout();
599
- } catch (error) {
600
- this.logger.error('Error during logout:', error);
601
- }
602
-
603
- process.exit(0);
604
- }
605
-
606
- /**
607
- * Start the server
608
- */
609
- async start(): Promise<void> {
610
- this.logger.info(`Starting ${this.config.name} v${this.config.version}`);
611
-
612
- // Validate initial connection (skip if not required)
613
- if (this.config.requiresAuth !== false) {
614
- const authResult = await this.validateAuth();
615
- if (!authResult.success) {
616
- this.logger.warn('Starting without authentication - some features may be limited');
617
- }
618
- }
619
-
620
- await this.server.connect(this.transport);
621
- this.logger.info('MCP server started successfully');
622
- }
623
-
624
- /**
625
- * Abstract method for child classes to implement their specific tools
626
- */
627
- /**
628
- * Validate ServiceNow connection
629
- */
630
- protected async validateServiceNowConnection(): Promise<AuthResult> {
631
- try {
632
- const isAuthenticated = await this.oauth.isAuthenticated();
633
- if (!isAuthenticated) {
634
- return {
635
- success: false,
636
- error: 'Not authenticated with ServiceNow'
637
- };
638
- }
639
-
640
- // Test connection with a simple request
641
- const response = await this.client.makeRequest({
642
- method: 'GET',
643
- url: '/api/now/table/sys_properties',
644
- params: { sysparm_limit: 1 }
645
- });
646
-
647
- return {
648
- success: response.success,
649
- token: 'valid'
650
- };
651
- } catch (error) {
652
- return {
653
- success: false,
654
- error: error instanceof Error ? error.message : 'Connection validation failed'
655
- };
656
- }
657
- }
658
-
659
- protected abstract setupTools(): void;
660
- }