snow-flow 3.4.11 → 3.4.14

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.
package/dist/cli.js CHANGED
@@ -813,7 +813,7 @@ All agents MUST use this simple memory coordination:
813
813
 
814
814
  \`\`\`javascript
815
815
  // Agent initialization
816
- const agentId = \`agent_\${agentType}_${sessionId}\`;
816
+ const agentId = \`agent_\${agentType}_\${sessionId}\`;
817
817
 
818
818
  // Agent stores progress
819
819
  Memory.store(\`\${agentId}_progress\`, JSON.stringify({
@@ -824,7 +824,7 @@ Memory.store(\`\${agentId}_progress\`, JSON.stringify({
824
824
  }));
825
825
 
826
826
  // Agent reads other agent's work when needed
827
- const primaryWork = Memory.get("agent_${taskAnalysis.primaryAgent}_output");
827
+ const primaryWork = Memory.get("agent_\${taskAnalysis.primaryAgent}_output");
828
828
 
829
829
  // Agent signals completion
830
830
  Memory.store(\`\${agentId}_complete\`, JSON.stringify({
@@ -852,6 +852,20 @@ ${hasIntelligentFeatures ? `✅ **INTELLIGENT MODE ACTIVE** - The following feat
852
852
 
853
853
  **CRITICAL RULE**: All agents MUST attempt to use ServiceNow MCP tools first, regardless of authentication status.
854
854
 
855
+ ### 🚨 MANDATORY: ES5 JavaScript Only for ALL ServiceNow Scripts
856
+ **⚠️ SERVICENOW RHINO ENGINE = ES5 ONLY - NO MODERN SYNTAX!**
857
+
858
+ **CRITICAL ES5 RULES:**
859
+ - NO const/let (use var)
860
+ - NO arrow functions (use function())
861
+ - NO template literals (use string concatenation)
862
+ - NO destructuring (use explicit property access)
863
+ - NO for...of loops (use traditional for loops)
864
+ - NO default parameters (use typeof checks)
865
+
866
+ **🔥 If you use ES6+ syntax, the script WILL FAIL with SyntaxError!**
867
+ **See CLAUDE.md for complete ES5 examples and common mistake fixes.**
868
+
855
869
  ### 📝 Background Script Execution Settings
856
870
  ${options.autoConfirm ? '⚠️ **AUTO-CONFIRM MODE ENABLED**: When calling snow_execute_background_script, ALWAYS add autoConfirm: true parameter to skip user confirmation.\n```javascript\nsnow_execute_background_script({\n script: "your ES5 script here",\n description: "Clear description",\n autoConfirm: true // ⚠️ User enabled auto-confirm mode\n})\n```' : options.autoConfirm === false ? '🔒 **FORCE CONFIRM MODE**: All background scripts will require user confirmation, even simple ones.' : '🤚 **DEFAULT MODE**: Background scripts will ask for user confirmation based on risk level.'}
857
871
 
@@ -12,7 +12,7 @@ const types_js_1 = require("@modelcontextprotocol/sdk/types.js");
12
12
  const servicenow_client_js_1 = require("../utils/servicenow-client.js");
13
13
  const mcp_auth_middleware_js_1 = require("../utils/mcp-auth-middleware.js");
14
14
  const mcp_config_manager_js_1 = require("../utils/mcp-config-manager.js");
15
- const logger_js_1 = require("../utils/logger.js");
15
+ const mcp_logger_js_1 = require("./shared/mcp-logger.js");
16
16
  class ServiceNowAutomationMCP {
17
17
  constructor() {
18
18
  this.server = new index_js_1.Server({
@@ -24,7 +24,7 @@ class ServiceNowAutomationMCP {
24
24
  },
25
25
  });
26
26
  this.client = new servicenow_client_js_1.ServiceNowClient();
27
- this.logger = new logger_js_1.Logger('ServiceNowAutomationMCP');
27
+ this.logger = new mcp_logger_js_1.MCPLogger('ServiceNowAutomationMCP');
28
28
  this.config = mcp_config_manager_js_1.mcpConfig.getConfig();
29
29
  this.setupHandlers();
30
30
  }
@@ -38,7 +38,7 @@ class ServiceNowAutomationMCP {
38
38
  type: 'object',
39
39
  properties: {
40
40
  name: { type: 'string', description: 'Scheduled Job name' },
41
- script: { type: 'string', description: 'JavaScript code to execute' },
41
+ script: { type: 'string', description: '🚨 ES5 ONLY! JavaScript code to execute (no const/let/arrows/templates - Rhino engine)' },
42
42
  description: { type: 'string', description: 'Job description' },
43
43
  schedule: { type: 'string', description: 'Schedule pattern (daily, weekly, monthly, or cron)' },
44
44
  active: { type: 'boolean', description: 'Job active status' },
@@ -56,8 +56,8 @@ class ServiceNowAutomationMCP {
56
56
  properties: {
57
57
  name: { type: 'string', description: 'Event Rule name' },
58
58
  eventName: { type: 'string', description: 'Event name to listen for' },
59
- condition: { type: 'string', description: 'Event condition script' },
60
- script: { type: 'string', description: 'Action script to execute' },
59
+ condition: { type: 'string', description: 'Event condition script (ES5 only!)' },
60
+ script: { type: 'string', description: '🚨 ES5 ONLY! Action script to execute (no const/let/arrows/templates - Rhino engine)' },
61
61
  description: { type: 'string', description: 'Rule description' },
62
62
  active: { type: 'boolean', description: 'Rule active status' },
63
63
  order: { type: 'number', description: 'Execution order' }
@@ -179,13 +179,13 @@ class ServiceNowAutomationMCP {
179
179
  },
180
180
  {
181
181
  name: 'snow_execute_background_script',
182
- description: '🚨 REQUIRES USER CONFIRMATION (unless autoConfirm=true): Executes a JavaScript background script in ServiceNow. Script runs in server-side context with full API access. By default asks for user approval.',
182
+ description: '🚨 REQUIRES USER CONFIRMATION (unless autoConfirm=true): Executes JavaScript background script in ServiceNow. ⚠️ CRITICAL: Script MUST be ES5-only (no const/let/arrow functions/template literals) - ES6+ will cause SyntaxError on Rhino engine!',
183
183
  inputSchema: {
184
184
  type: 'object',
185
185
  properties: {
186
186
  script: {
187
187
  type: 'string',
188
- description: 'JavaScript code to execute in background. Has access to GlideRecord, GlideAggregate, gs, etc.'
188
+ description: '🚨 ES5 JAVASCRIPT ONLY! Use var (not const/let), function(){} (not arrows), string concatenation (not templates). Has access to GlideRecord, GlideAggregate, gs, etc.'
189
189
  },
190
190
  description: {
191
191
  type: 'string',
@@ -308,11 +308,11 @@ class ServiceNowAutomationMCP {
308
308
  },
309
309
  {
310
310
  name: 'snow_execute_script_with_output',
311
- description: 'Executes a background script and retrieves the actual output. Waits for execution to complete and returns the results.',
311
+ description: 'Executes a background script and retrieves the actual output. ⚠️ CRITICAL: Script MUST be ES5-only (Rhino engine) - no const/let/arrows/templates!',
312
312
  inputSchema: {
313
313
  type: 'object',
314
314
  properties: {
315
- script: { type: 'string', description: 'JavaScript code to execute' },
315
+ script: { type: 'string', description: '🚨 ES5 ONLY! Use var, function(){}, string+concatenation. JavaScript code to execute on ServiceNow server.' },
316
316
  return_output: { type: 'boolean', description: 'Return script output', default: true },
317
317
  max_wait: { type: 'number', description: 'Maximum wait time in milliseconds', default: 5000 },
318
318
  capture_logs: { type: 'boolean', description: 'Capture system logs during execution', default: true }
@@ -333,11 +333,11 @@ class ServiceNowAutomationMCP {
333
333
  },
334
334
  {
335
335
  name: 'snow_execute_script_sync',
336
- description: 'Synchronously executes a script and waits for the result. Returns output immediately.',
336
+ description: 'Synchronously executes a script and waits for the result. ⚠️ CRITICAL: Script MUST be ES5-only (Rhino engine)!',
337
337
  inputSchema: {
338
338
  type: 'object',
339
339
  properties: {
340
- script: { type: 'string', description: 'JavaScript code to execute' },
340
+ script: { type: 'string', description: '🚨 ES5 ONLY! No const/let/arrows/templates. JavaScript code to execute synchronously.' },
341
341
  timeout: { type: 'number', description: 'Timeout in milliseconds', default: 3000 },
342
342
  capture_output: { type: 'boolean', description: 'Capture and return output', default: true }
343
343
  },
@@ -423,68 +423,100 @@ class ServiceNowAutomationMCP {
423
423
  ]
424
424
  }));
425
425
  this.server.setRequestHandler(types_js_1.CallToolRequestSchema, async (request) => {
426
+ const { name, arguments: args } = request.params;
426
427
  try {
427
- const { name, arguments: args } = request.params;
428
+ // Start operation with token tracking
429
+ this.logger.operationStart(name, args);
428
430
  const authResult = await mcp_auth_middleware_js_1.mcpAuth.ensureAuthenticated();
429
431
  if (!authResult.success) {
430
432
  throw new types_js_1.McpError(types_js_1.ErrorCode.InternalError, authResult.error || 'Authentication required');
431
433
  }
434
+ let result;
432
435
  switch (name) {
433
436
  case 'snow_create_scheduled_job':
434
- return await this.createScheduledJob(args);
437
+ result = await this.createScheduledJob(args);
438
+ break;
435
439
  case 'snow_create_event_rule':
436
- return await this.createEventRule(args);
440
+ result = await this.createEventRule(args);
441
+ break;
437
442
  case 'snow_create_notification':
438
- return await this.createNotification(args);
443
+ result = await this.createNotification(args);
444
+ break;
439
445
  case 'snow_create_sla_definition':
440
- return await this.createSLADefinition(args);
446
+ result = await this.createSLADefinition(args);
447
+ break;
441
448
  case 'snow_create_escalation_rule':
442
- return await this.createEscalationRule(args);
449
+ result = await this.createEscalationRule(args);
450
+ break;
443
451
  case 'snow_create_workflow_activity':
444
- return await this.createWorkflowActivity(args);
452
+ result = await this.createWorkflowActivity(args);
453
+ break;
445
454
  case 'snow_discover_schedules':
446
- return await this.discoverSchedules(args);
455
+ result = await this.discoverSchedules(args);
456
+ break;
447
457
  case 'snow_discover_events':
448
- return await this.discoverEvents(args);
458
+ result = await this.discoverEvents(args);
459
+ break;
449
460
  case 'snow_discover_automation_jobs':
450
- return await this.discoverAutomationJobs(args);
461
+ result = await this.discoverAutomationJobs(args);
462
+ break;
451
463
  case 'snow_test_scheduled_job':
452
- return await this.testScheduledJob(args);
464
+ result = await this.testScheduledJob(args);
465
+ break;
453
466
  case 'snow_execute_background_script':
454
- return await this.executeBackgroundScript(args);
467
+ result = await this.executeBackgroundScript(args);
468
+ break;
455
469
  case 'snow_confirm_script_execution':
456
- return await this.confirmScriptExecution(args);
470
+ result = await this.confirmScriptExecution(args);
471
+ break;
457
472
  case 'snow_create_atf_test':
458
- return await this.createATFTest(args);
473
+ result = await this.createATFTest(args);
474
+ break;
459
475
  case 'snow_create_atf_test_step':
460
- return await this.createATFTestStep(args);
476
+ result = await this.createATFTestStep(args);
477
+ break;
461
478
  case 'snow_execute_atf_test':
462
- return await this.executeATFTest(args);
479
+ result = await this.executeATFTest(args);
480
+ break;
463
481
  case 'snow_get_atf_results':
464
- return await this.getATFResults(args);
482
+ result = await this.getATFResults(args);
483
+ break;
465
484
  case 'snow_create_atf_test_suite':
466
- return await this.createATFTestSuite(args);
485
+ result = await this.createATFTestSuite(args);
486
+ break;
467
487
  case 'snow_discover_atf_tests':
468
- return await this.discoverATFTests(args);
488
+ result = await this.discoverATFTests(args);
489
+ break;
469
490
  case 'snow_execute_script_with_output':
470
- return await this.executeScriptWithOutput(args);
491
+ result = await this.executeScriptWithOutput(args);
492
+ break;
471
493
  case 'snow_get_script_output':
472
- return await this.getScriptOutput(args);
494
+ result = await this.getScriptOutput(args);
495
+ break;
473
496
  case 'snow_execute_script_sync':
474
- return await this.executeScriptSync(args);
497
+ result = await this.executeScriptSync(args);
498
+ break;
475
499
  case 'snow_get_logs':
476
- return await this.getLogs(args);
500
+ result = await this.getLogs(args);
501
+ break;
477
502
  case 'snow_test_rest_connection':
478
- return await this.testRESTConnection(args);
503
+ result = await this.testRESTConnection(args);
504
+ break;
479
505
  case 'snow_rest_message_test_suite':
480
- return await this.restMessageTestSuite(args);
506
+ result = await this.restMessageTestSuite(args);
507
+ break;
481
508
  case 'snow_property_manager':
482
- return await this.propertyManager(args);
509
+ result = await this.propertyManager(args);
510
+ break;
483
511
  case 'snow_trace_execution':
484
- return await this.traceExecution(args);
512
+ result = await this.traceExecution(args);
513
+ break;
485
514
  default:
486
515
  throw new types_js_1.McpError(types_js_1.ErrorCode.MethodNotFound, `Unknown tool: ${name}`);
487
516
  }
517
+ // Complete operation with token tracking
518
+ this.logger.operationComplete(name, result);
519
+ return result;
488
520
  }
489
521
  catch (error) {
490
522
  this.logger.error(`Error in ${request.params.name}:`, error);
@@ -513,6 +545,7 @@ class ServiceNowAutomationMCP {
513
545
  ...schedulePattern
514
546
  };
515
547
  const updateSetResult = await this.client.ensureUpdateSet();
548
+ this.logger.trackAPICall('CREATE', 'sysauto_script', 1);
516
549
  const response = await this.client.createRecord('sysauto_script', jobData);
517
550
  if (!response.success) {
518
551
  throw new Error(`Failed to create Scheduled Job: ${response.error}`);
@@ -1210,6 +1243,7 @@ Reply with:
1210
1243
  description: `Background script executed via Snow-Flow MCP - Execution ID: ${executionId}`
1211
1244
  };
1212
1245
  // Execute script using sys_script table (Background Scripts)
1246
+ this.logger.trackAPICall('CREATE', 'sys_script', 1);
1213
1247
  const scriptResponse = await this.client.createRecord('sys_script', executionRecord);
1214
1248
  if (!scriptResponse.success) {
1215
1249
  throw new Error(`Failed to create background script execution record: ${scriptResponse.error}`);
@@ -1971,6 +2005,7 @@ ${groupedResults.suites.slice(0, 10).map(suite => `- ${suite.name} ${suite.activ
1971
2005
  }
1972
2006
  // Remove trailing ^
1973
2007
  query = query.replace(/\^$/, '');
2008
+ this.logger.trackAPICall('SEARCH', 'syslog_transaction', limit);
1974
2009
  const logsResponse = await this.client.searchRecords('syslog_transaction', query, limit);
1975
2010
  if (logsResponse.success && logsResponse.data?.result?.length > 0) {
1976
2011
  const logs = logsResponse.data.result.map((log) => ({
@@ -2171,6 +2206,7 @@ ${groupedResults.suites.slice(0, 10).map(suite => `- ${suite.name} ${suite.activ
2171
2206
  const action = args.action || 'list';
2172
2207
  switch (action) {
2173
2208
  case 'get':
2209
+ this.logger.trackAPICall('SEARCH', 'sys_properties', 1);
2174
2210
  const getPropResponse = await this.client.searchRecords('sys_properties', `name=${args.name}`, 1);
2175
2211
  if (getPropResponse.success && getPropResponse.data?.result?.length > 0) {
2176
2212
  const prop = getPropResponse.data.result[0];
@@ -12,7 +12,7 @@ const types_js_1 = require("@modelcontextprotocol/sdk/types.js");
12
12
  const servicenow_client_js_1 = require("../utils/servicenow-client.js");
13
13
  const mcp_auth_middleware_js_1 = require("../utils/mcp-auth-middleware.js");
14
14
  const mcp_config_manager_js_1 = require("../utils/mcp-config-manager.js");
15
- const logger_js_1 = require("../utils/logger.js");
15
+ const mcp_logger_js_1 = require("../shared/mcp-logger.js");
16
16
  class ServiceNowChangeVirtualAgentPAMCP {
17
17
  constructor() {
18
18
  this.server = new index_js_1.Server({
@@ -24,7 +24,7 @@ class ServiceNowChangeVirtualAgentPAMCP {
24
24
  },
25
25
  });
26
26
  this.client = new servicenow_client_js_1.ServiceNowClient();
27
- this.logger = new logger_js_1.Logger('ServiceNowChangeVirtualAgentPAMCP');
27
+ this.logger = new mcp_logger_js_1.MCPLogger('ServiceNowChangeVirtualAgentPAMCP');
28
28
  this.config = mcp_config_manager_js_1.mcpConfig.getConfig();
29
29
  this.setupHandlers();
30
30
  }
@@ -337,55 +337,80 @@ class ServiceNowChangeVirtualAgentPAMCP {
337
337
  this.server.setRequestHandler(types_js_1.CallToolRequestSchema, async (request) => {
338
338
  try {
339
339
  const { name, arguments: args } = request.params;
340
+ // Start operation with token tracking
341
+ this.logger.operationStart(name, args);
340
342
  const authResult = await mcp_auth_middleware_js_1.mcpAuth.ensureAuthenticated();
341
343
  if (!authResult.success) {
342
344
  throw new types_js_1.McpError(types_js_1.ErrorCode.InternalError, authResult.error || 'Authentication required');
343
345
  }
346
+ let result;
344
347
  switch (name) {
345
348
  // Change Management
346
349
  case 'snow_create_change_request':
347
- return await this.createChangeRequest(args);
350
+ result = await this.createChangeRequest(args);
351
+ break;
348
352
  case 'snow_create_change_task':
349
- return await this.createChangeTask(args);
353
+ result = await this.createChangeTask(args);
354
+ break;
350
355
  case 'snow_get_change_request':
351
- return await this.getChangeRequest(args);
356
+ result = await this.getChangeRequest(args);
357
+ break;
352
358
  case 'snow_update_change_state':
353
- return await this.updateChangeState(args);
359
+ result = await this.updateChangeState(args);
360
+ break;
354
361
  case 'snow_schedule_cab_meeting':
355
- return await this.scheduleCABMeeting(args);
362
+ result = await this.scheduleCABMeeting(args);
363
+ break;
356
364
  case 'snow_search_change_requests':
357
- return await this.searchChangeRequests(args);
365
+ result = await this.searchChangeRequests(args);
366
+ break;
358
367
  // Virtual Agent
359
368
  case 'snow_create_va_topic':
360
- return await this.createVATopic(args);
369
+ result = await this.createVATopic(args);
370
+ break;
361
371
  case 'snow_create_va_topic_block':
362
- return await this.createVATopicBlock(args);
372
+ result = await this.createVATopicBlock(args);
373
+ break;
363
374
  case 'snow_get_va_conversation':
364
- return await this.getVAConversation(args);
375
+ result = await this.getVAConversation(args);
376
+ break;
365
377
  case 'snow_send_va_message':
366
- return await this.sendVAMessage(args);
378
+ result = await this.sendVAMessage(args);
379
+ break;
367
380
  case 'snow_handoff_to_agent':
368
- return await this.handoffToAgent(args);
381
+ result = await this.handoffToAgent(args);
382
+ break;
369
383
  case 'snow_discover_va_topics':
370
- return await this.discoverVATopics(args);
384
+ result = await this.discoverVATopics(args);
385
+ break;
371
386
  // Performance Analytics
372
387
  case 'snow_create_pa_indicator':
373
- return await this.createPAIndicator(args);
388
+ result = await this.createPAIndicator(args);
389
+ break;
374
390
  case 'snow_create_pa_widget':
375
- return await this.createPAWidget(args);
391
+ result = await this.createPAWidget(args);
392
+ break;
376
393
  case 'snow_create_pa_breakdown':
377
- return await this.createPABreakdown(args);
394
+ result = await this.createPABreakdown(args);
395
+ break;
378
396
  case 'snow_get_pa_scores':
379
- return await this.getPAScores(args);
397
+ result = await this.getPAScores(args);
398
+ break;
380
399
  case 'snow_create_pa_threshold':
381
- return await this.createPAThreshold(args);
400
+ result = await this.createPAThreshold(args);
401
+ break;
382
402
  case 'snow_collect_pa_data':
383
- return await this.collectPAData(args);
403
+ result = await this.collectPAData(args);
404
+ break;
384
405
  case 'snow_discover_pa_indicators':
385
- return await this.discoverPAIndicators(args);
406
+ result = await this.discoverPAIndicators(args);
407
+ break;
386
408
  default:
387
409
  throw new types_js_1.McpError(types_js_1.ErrorCode.MethodNotFound, `Unknown tool: ${name}`);
388
410
  }
411
+ // Complete operation with token tracking
412
+ this.logger.operationComplete(name, result);
413
+ return result;
389
414
  }
390
415
  catch (error) {
391
416
  this.logger.error(`Error in ${request.params.name}:`, error);
@@ -416,6 +441,7 @@ class ServiceNowChangeVirtualAgentPAMCP {
416
441
  state: '-5' // New state
417
442
  };
418
443
  const updateSetResult = await this.client.ensureUpdateSet();
444
+ this.logger.trackAPICall('CREATE', 'change_request', 1);
419
445
  const response = await this.client.createRecord('change_request', changeData);
420
446
  if (!response.success) {
421
447
  throw new Error(`Failed to create change request: ${response.error}`);
@@ -464,6 +490,7 @@ class ServiceNowChangeVirtualAgentPAMCP {
464
490
  planned_end_date: args.planned_end_date || '',
465
491
  order: args.order || 100
466
492
  };
493
+ this.logger.trackAPICall('CREATE', 'change_task', 1);
467
494
  const response = await this.client.createRecord('change_task', taskData);
468
495
  if (!response.success) {
469
496
  throw new Error(`Failed to create change task: ${response.error}`);
@@ -654,6 +681,7 @@ ${args.close_code ? `✅ Close Code: ${args.close_code}` : ''}
654
681
  query += `assigned_to=${args.assigned_to}`;
655
682
  }
656
683
  const limit = args.limit || 20;
684
+ this.logger.trackAPICall('SEARCH', 'change_request', limit);
657
685
  const response = await this.client.searchRecords('change_request', query, limit);
658
686
  if (!response.success) {
659
687
  throw new Error('Failed to search change requests');
@@ -699,6 +727,7 @@ ${changeList}
699
727
  active: args.active !== false,
700
728
  live_agent_enabled: args.live_agent_enabled || false
701
729
  };
730
+ this.logger.trackAPICall('CREATE', 'sys_cs_topic', 1);
702
731
  const response = await this.client.createRecord('sys_cs_topic', topicData);
703
732
  if (!response.success) {
704
733
  throw new Error(`Failed to create VA topic: ${response.error}`);
@@ -951,6 +980,7 @@ ${topicList}
951
980
  target: args.target || 0,
952
981
  thresholds: args.thresholds ? JSON.stringify(args.thresholds) : ''
953
982
  };
983
+ this.logger.trackAPICall('CREATE', 'pa_indicators', 1);
954
984
  const response = await this.client.createRecord('pa_indicators', indicatorData);
955
985
  if (!response.success) {
956
986
  throw new Error(`Failed to create PA indicator: ${response.error}`);
@@ -12,7 +12,7 @@ const types_js_1 = require("@modelcontextprotocol/sdk/types.js");
12
12
  const servicenow_client_js_1 = require("../utils/servicenow-client.js");
13
13
  const mcp_auth_middleware_js_1 = require("../utils/mcp-auth-middleware.js");
14
14
  const mcp_config_manager_js_1 = require("../utils/mcp-config-manager.js");
15
- const logger_js_1 = require("../utils/logger.js");
15
+ const mcp_logger_js_1 = require("../shared/mcp-logger.js");
16
16
  class ServiceNowCMDBEventHRCSMDevOpsMCP {
17
17
  constructor() {
18
18
  this.server = new index_js_1.Server({
@@ -24,7 +24,7 @@ class ServiceNowCMDBEventHRCSMDevOpsMCP {
24
24
  },
25
25
  });
26
26
  this.client = new servicenow_client_js_1.ServiceNowClient();
27
- this.logger = new logger_js_1.Logger('ServiceNowCMDBEventHRCSMDevOpsMCP');
27
+ this.logger = new mcp_logger_js_1.MCPLogger('ServiceNowCMDBEventHRCSMDevOpsMCP');
28
28
  this.config = mcp_config_manager_js_1.mcpConfig.getConfig();
29
29
  this.setupHandlers();
30
30
  }
@@ -406,65 +406,94 @@ class ServiceNowCMDBEventHRCSMDevOpsMCP {
406
406
  this.server.setRequestHandler(types_js_1.CallToolRequestSchema, async (request) => {
407
407
  try {
408
408
  const { name, arguments: args } = request.params;
409
+ // Start operation with token tracking
410
+ this.logger.operationStart(name, args);
409
411
  const authResult = await mcp_auth_middleware_js_1.mcpAuth.ensureAuthenticated();
410
412
  if (!authResult.success) {
411
413
  throw new types_js_1.McpError(types_js_1.ErrorCode.InternalError, authResult.error || 'Authentication required');
412
414
  }
415
+ let result;
413
416
  switch (name) {
414
417
  // CMDB & Discovery
415
418
  case 'snow_create_ci':
416
- return await this.createCI(args);
419
+ result = await this.createCI(args);
420
+ break;
417
421
  case 'snow_create_ci_relationship':
418
- return await this.createCIRelationship(args);
422
+ result = await this.createCIRelationship(args);
423
+ break;
419
424
  case 'snow_run_discovery':
420
- return await this.runDiscovery(args);
425
+ result = await this.runDiscovery(args);
426
+ break;
421
427
  case 'snow_get_ci_details':
422
- return await this.getCIDetails(args);
428
+ result = await this.getCIDetails(args);
429
+ break;
423
430
  case 'snow_search_cmdb':
424
- return await this.searchCMDB(args);
431
+ result = await this.searchCMDB(args);
432
+ break;
425
433
  case 'snow_impact_analysis':
426
- return await this.impactAnalysis(args);
434
+ result = await this.impactAnalysis(args);
435
+ break;
427
436
  // Event Management
428
437
  case 'snow_create_event':
429
- return await this.createEvent(args);
438
+ result = await this.createEvent(args);
439
+ break;
430
440
  case 'snow_create_alert':
431
- return await this.createAlert(args);
441
+ result = await this.createAlert(args);
442
+ break;
432
443
  case 'snow_create_alert_rule':
433
- return await this.createAlertRule(args);
444
+ result = await this.createAlertRule(args);
445
+ break;
434
446
  case 'snow_get_event_correlation':
435
- return await this.getEventCorrelation(args);
447
+ result = await this.getEventCorrelation(args);
448
+ break;
436
449
  // HR Service Delivery
437
450
  case 'snow_create_hr_case':
438
- return await this.createHRCase(args);
451
+ result = await this.createHRCase(args);
452
+ break;
439
453
  case 'snow_create_hr_task':
440
- return await this.createHRTask(args);
454
+ result = await this.createHRTask(args);
455
+ break;
441
456
  case 'snow_employee_onboarding':
442
- return await this.employeeOnboarding(args);
457
+ result = await this.employeeOnboarding(args);
458
+ break;
443
459
  case 'snow_employee_offboarding':
444
- return await this.employeeOffboarding(args);
460
+ result = await this.employeeOffboarding(args);
461
+ break;
445
462
  // Customer Service Management
446
463
  case 'snow_create_customer_case':
447
- return await this.createCustomerCase(args);
464
+ result = await this.createCustomerCase(args);
465
+ break;
448
466
  case 'snow_create_customer_account':
449
- return await this.createCustomerAccount(args);
467
+ result = await this.createCustomerAccount(args);
468
+ break;
450
469
  case 'snow_create_entitlement':
451
- return await this.createEntitlement(args);
470
+ result = await this.createEntitlement(args);
471
+ break;
452
472
  case 'snow_get_customer_history':
453
- return await this.getCustomerHistory(args);
473
+ result = await this.getCustomerHistory(args);
474
+ break;
454
475
  // DevOps
455
476
  case 'snow_create_devops_pipeline':
456
- return await this.createDevOpsPipeline(args);
477
+ result = await this.createDevOpsPipeline(args);
478
+ break;
457
479
  case 'snow_track_deployment':
458
- return await this.trackDeployment(args);
480
+ result = await this.trackDeployment(args);
481
+ break;
459
482
  case 'snow_create_devops_change':
460
- return await this.createDevOpsChange(args);
483
+ result = await this.createDevOpsChange(args);
484
+ break;
461
485
  case 'snow_get_devops_insights':
462
- return await this.getDevOpsInsights(args);
486
+ result = await this.getDevOpsInsights(args);
487
+ break;
463
488
  case 'snow_velocity_tracking':
464
- return await this.velocityTracking(args);
489
+ result = await this.velocityTracking(args);
490
+ break;
465
491
  default:
466
492
  throw new types_js_1.McpError(types_js_1.ErrorCode.MethodNotFound, `Unknown tool: ${name}`);
467
493
  }
494
+ // Complete operation with token tracking
495
+ this.logger.operationComplete(name, result);
496
+ return result;
468
497
  }
469
498
  catch (error) {
470
499
  this.logger.error(`Error in ${request.params.name}:`, error);
@@ -489,6 +518,7 @@ class ServiceNowCMDBEventHRCSMDevOpsMCP {
489
518
  ...args.attributes
490
519
  };
491
520
  const updateSetResult = await this.client.ensureUpdateSet();
521
+ this.logger.trackAPICall('CREATE', ciTable, 1);
492
522
  const response = await this.client.createRecord(ciTable, ciData);
493
523
  if (!response.success) {
494
524
  throw new Error(`Failed to create CI: ${response.error}`);
@@ -524,6 +554,7 @@ ${args.asset_tag ? `🏷️ Asset Tag: ${args.asset_tag}` : ''}
524
554
  type: args.type,
525
555
  description: args.description || ''
526
556
  };
557
+ this.logger.trackAPICall('CREATE', 'cmdb_rel_ci', 1);
527
558
  const response = await this.client.createRecord('cmdb_rel_ci', relationshipData);
528
559
  if (!response.success) {
529
560
  throw new Error(`Failed to create CI relationship: ${response.error}`);
@@ -645,6 +676,7 @@ ${args.patterns ? `📋 Patterns: ${args.patterns.join(', ')}` : ''}
645
676
  query += `location=${args.location}`;
646
677
  }
647
678
  const limit = args.limit || 50;
679
+ this.logger.trackAPICall('SEARCH', 'cmdb_ci', limit);
648
680
  const response = await this.client.searchRecords('cmdb_ci', query, limit);
649
681
  if (!response.success) {
650
682
  throw new Error('Failed to search CMDB');
@@ -736,6 +768,7 @@ ${mockImpact.recommendations.map(r => ` ✓ ${r}`).join('\n')}
736
768
  time_of_event: args.time_of_event || new Date().toISOString(),
737
769
  resolution_state: args.resolution_state || 'New'
738
770
  };
771
+ this.logger.trackAPICall('CREATE', 'em_event', 1);
739
772
  const response = await this.client.createRecord('em_event', eventData);
740
773
  if (!response.success) {
741
774
  throw new Error(`Failed to create event: ${response.error}`);
@@ -887,6 +920,7 @@ ${mockCorrelation.correlation_rules_applied.map(r => ` - ${r}`).join('\n')}
887
920
  subcategory: args.subcategory || '',
888
921
  confidential: args.confidential || false
889
922
  };
923
+ this.logger.trackAPICall('CREATE', 'sn_hr_core_case', 1);
890
924
  const response = await this.client.createRecord('sn_hr_core_case', caseData);
891
925
  if (!response.success) {
892
926
  throw new Error(`Failed to create HR case: ${response.error}`);