snow-flow 2.6.3 → 2.6.5

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 (26) hide show
  1. package/dist/mcp/servicenow-development-assistant-mcp.js +38 -18
  2. package/package.json +1 -1
  3. package/dist/mcp/example-refactored-server.d.ts +0 -18
  4. package/dist/mcp/example-refactored-server.js +0 -57
  5. package/dist/mcp/servicenow-automation-mcp-refactored.d.ts +0 -26
  6. package/dist/mcp/servicenow-automation-mcp-refactored.js +0 -632
  7. package/dist/mcp/servicenow-deployment-mcp-refactored.d.ts +0 -74
  8. package/dist/mcp/servicenow-deployment-mcp-refactored.js +0 -1044
  9. package/dist/mcp/servicenow-flow-composer-mcp-refactored.d.ts +0 -25
  10. package/dist/mcp/servicenow-flow-composer-mcp-refactored.js +0 -565
  11. package/dist/mcp/servicenow-graph-memory-mcp-refactored.d.ts +0 -32
  12. package/dist/mcp/servicenow-graph-memory-mcp-refactored.js +0 -642
  13. package/dist/mcp/servicenow-integration-mcp-refactored.d.ts +0 -24
  14. package/dist/mcp/servicenow-integration-mcp-refactored.js +0 -612
  15. package/dist/mcp/servicenow-intelligent-mcp-refactored.d.ts +0 -63
  16. package/dist/mcp/servicenow-intelligent-mcp-refactored.js +0 -782
  17. package/dist/mcp/servicenow-operations-mcp-refactored.d.ts +0 -63
  18. package/dist/mcp/servicenow-operations-mcp-refactored.js +0 -1770
  19. package/dist/mcp/servicenow-platform-development-mcp-refactored.d.ts +0 -25
  20. package/dist/mcp/servicenow-platform-development-mcp-refactored.js +0 -542
  21. package/dist/mcp/servicenow-reporting-analytics-mcp-refactored.d.ts +0 -26
  22. package/dist/mcp/servicenow-reporting-analytics-mcp-refactored.js +0 -648
  23. package/dist/mcp/servicenow-security-compliance-mcp-refactored.d.ts +0 -25
  24. package/dist/mcp/servicenow-security-compliance-mcp-refactored.js +0 -600
  25. package/dist/mcp/servicenow-update-set-mcp-refactored.d.ts +0 -31
  26. package/dist/mcp/servicenow-update-set-mcp-refactored.js +0 -662
@@ -1,1770 +0,0 @@
1
- #!/usr/bin/env node
2
- "use strict";
3
- /**
4
- * ServiceNow Operations MCP Server - REFACTORED
5
- * Uses BaseMCPServer to eliminate code duplication
6
- *
7
- * Handles operational data queries, incident management, and intelligent analysis
8
- * Features:
9
- * - Incident, Request, Problem, Change management
10
- * - CMDB and User management
11
- * - Intelligent incident _analysis and auto-resolution
12
- * - Pattern recognition and root cause analysis
13
- * - Knowledge base integration
14
- * - Predictive analytics
15
- */
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.ServiceNowOperationsMCP = void 0;
18
- const base_mcp_server_js_1 = require("./base-mcp-server.js");
19
- // Operational table mappings for ServiceNow
20
- const operationalTableMapping = {
21
- // ITIL Core Processes
22
- incident: 'incident',
23
- request: 'sc_request',
24
- request_item: 'sc_req_item',
25
- problem: 'problem',
26
- change_request: 'change_request',
27
- // Service Catalog
28
- catalog: 'sc_catalog',
29
- catalog_item: 'sc_cat_item',
30
- catalog_category: 'sc_category',
31
- catalog_variable: 'item_option_new',
32
- catalog_variable_set: 'io_set_item',
33
- catalog_ui_policy: 'catalog_ui_policy',
34
- catalog_client_script: 'catalog_script_client',
35
- catalog_template: 'sc_template',
36
- // Task Management
37
- task: 'task',
38
- incident_task: 'incident_task',
39
- problem_task: 'problem_task',
40
- change_task: 'change_task',
41
- approval: 'sysapproval_approver',
42
- // User & Group Management
43
- user: 'sys_user',
44
- user_group: 'sys_user_group',
45
- user_role: 'sys_user_has_role',
46
- // CMDB (Configuration Management Database)
47
- configuration_item: 'cmdb_ci',
48
- server: 'cmdb_ci_server',
49
- application: 'cmdb_ci_application',
50
- database: 'cmdb_ci_database',
51
- network_device: 'cmdb_ci_network_device',
52
- service: 'cmdb_ci_service',
53
- // Knowledge Management
54
- knowledge_base: 'kb_knowledge_base',
55
- knowledge: 'kb_knowledge',
56
- // Metrics & Analytics
57
- metric: 'sys_metric',
58
- metric_instance: 'sys_metric_instance',
59
- // Notifications
60
- notification: 'sysevent_email_action',
61
- email_log: 'sys_email'
62
- };
63
- class ServiceNowOperationsMCP extends base_mcp_server_js_1.BaseMCPServer {
64
- constructor() {
65
- super({
66
- name: 'servicenow-operations',
67
- version: '2.0.0',
68
- description: 'Operations management server with BaseMCPServer pattern'
69
- });
70
- }
71
- setupTools() {
72
- // Tools are set up via getTools() method
73
- }
74
- getTools() {
75
- return [
76
- {
77
- name: 'snow_query_incidents',
78
- description: 'Advanced incident querying with filters and _analysis',
79
- inputSchema: {
80
- type: 'object',
81
- properties: {
82
- query: { type: 'string', description: 'ServiceNow encoded query or natural language description' },
83
- fields: { type: 'array', items: { type: 'string' }, description: 'Specific fields to return' },
84
- limit: { type: 'number', default: 10, description: 'Maximum number of results (default: 10)' },
85
- include__analysis: { type: 'boolean', default: false, description: 'Include intelligent _analysis of incidents' }
86
- },
87
- required: ['query']
88
- }
89
- },
90
- {
91
- name: 'snow_analyze_incident',
92
- description: 'Intelligent _analysis of a specific incident with auto-resolution suggestions',
93
- inputSchema: {
94
- type: 'object',
95
- properties: {
96
- incident_id: { type: 'string', description: 'Incident number or sys_id' },
97
- include_similar: { type: 'boolean', default: true, description: 'Include similar incidents in _analysis' },
98
- suggest_resolution: { type: 'boolean', default: true, description: 'Generate automated resolution suggestions' }
99
- },
100
- required: ['incident_id']
101
- }
102
- },
103
- {
104
- name: 'snow_auto_resolve_incident',
105
- description: 'Attempt automated resolution of technical incidents',
106
- inputSchema: {
107
- type: 'object',
108
- properties: {
109
- incident_id: { type: 'string', description: 'Incident number or sys_id' },
110
- dry_run: { type: 'boolean', default: true, description: 'Preview actions without executing' }
111
- },
112
- required: ['incident_id']
113
- }
114
- },
115
- {
116
- name: 'snow_query_requests',
117
- description: 'Query and analyze service requests',
118
- inputSchema: {
119
- type: 'object',
120
- properties: {
121
- query: { type: 'string', description: 'ServiceNow encoded query or natural language' },
122
- include_items: { type: 'boolean', default: false, description: 'Include request items' },
123
- limit: { type: 'number', default: 10, description: 'Maximum number of results' }
124
- },
125
- required: ['query']
126
- }
127
- },
128
- {
129
- name: 'snow_query_problems',
130
- description: 'Query and analyze problems with root cause _analysis',
131
- inputSchema: {
132
- type: 'object',
133
- properties: {
134
- query: { type: 'string', description: 'ServiceNow encoded query or natural language' },
135
- include_incidents: { type: 'boolean', default: false, description: 'Include related incidents' },
136
- limit: { type: 'number', default: 10, description: 'Maximum number of results' }
137
- },
138
- required: ['query']
139
- }
140
- },
141
- {
142
- name: 'snow_cmdb_search',
143
- description: 'Search and analyze Configuration Items (CMDB)',
144
- inputSchema: {
145
- type: 'object',
146
- properties: {
147
- query: { type: 'string', description: 'Search query for configuration items' },
148
- ci_type: {
149
- type: 'string',
150
- enum: ['server', 'application', 'database', 'network_device', 'service', 'any'],
151
- description: 'Type of CI (server, application, service, etc.)'
152
- },
153
- include_relationships: { type: 'boolean', default: false, description: 'Include CI relationships' },
154
- limit: { type: 'number', default: 10, description: 'Maximum number of results' }
155
- },
156
- required: ['query']
157
- }
158
- },
159
- {
160
- name: 'snow_user_lookup',
161
- description: 'Lookup and analyze user information',
162
- inputSchema: {
163
- type: 'object',
164
- properties: {
165
- identifier: { type: 'string', description: 'User ID, email, or name' },
166
- include_groups: { type: 'boolean', default: true, description: 'Include user groups' },
167
- include_roles: { type: 'boolean', default: true, description: 'Include user roles' }
168
- },
169
- required: ['identifier']
170
- }
171
- },
172
- {
173
- name: 'snow_operational_metrics',
174
- description: 'Get operational metrics and analytics',
175
- inputSchema: {
176
- type: 'object',
177
- properties: {
178
- timeframe: {
179
- type: 'string',
180
- enum: ['today', 'week', 'month', 'quarter'],
181
- default: 'week',
182
- description: 'Time period for metrics'
183
- },
184
- metric_types: { type: 'array', items: { type: 'string' }, description: 'Types of metrics to include' }
185
- }
186
- }
187
- },
188
- {
189
- name: 'snow_pattern__analysis',
190
- description: 'Analyze patterns in incidents, requests, and problems',
191
- inputSchema: {
192
- type: 'object',
193
- properties: {
194
- analysis_type: {
195
- type: 'string',
196
- enum: ['incident_patterns', 'request_trends', 'problem_root_causes', 'user_behavior'],
197
- description: 'Type of pattern _analysis'
198
- },
199
- timeframe: {
200
- type: 'string',
201
- enum: ['day', 'week', 'month', 'quarter'],
202
- default: 'week',
203
- description: 'Time period for _analysis'
204
- }
205
- },
206
- required: ['analysis_type']
207
- }
208
- },
209
- {
210
- name: 'snow_knowledge_search',
211
- description: 'Search knowledge base articles with intelligent matching',
212
- inputSchema: {
213
- type: 'object',
214
- properties: {
215
- query: { type: 'string', description: 'Search query or incident description' },
216
- match_incident: { type: 'string', description: 'Match knowledge to specific incident' },
217
- limit: { type: 'number', default: 5, description: 'Maximum number of results' }
218
- },
219
- required: ['query']
220
- }
221
- },
222
- {
223
- name: 'snow_predictive__analysis',
224
- description: 'Predictive _analysis for potential issues and trends',
225
- inputSchema: {
226
- type: 'object',
227
- properties: {
228
- prediction_type: {
229
- type: 'string',
230
- enum: ['incident_volume', 'system_failure', 'resource_exhaustion', 'user_impact'],
231
- description: 'Type of prediction'
232
- },
233
- timeframe: {
234
- type: 'string',
235
- enum: ['day', 'week', 'month'],
236
- default: 'week',
237
- description: 'Prediction timeframe'
238
- }
239
- },
240
- required: ['prediction_type']
241
- }
242
- },
243
- {
244
- name: 'snow_catalog_item_manager',
245
- description: 'Manage service catalog items - create, update, configure variables and workflows',
246
- inputSchema: {
247
- type: 'object',
248
- properties: {
249
- action: {
250
- type: 'string',
251
- enum: ['create', 'update', 'list', 'get', 'add_variable', 'set_workflow', 'publish', 'retire'],
252
- description: 'Action to perform'
253
- },
254
- item_id: { type: 'string', description: 'Catalog item sys_id (for update/get actions)' },
255
- name: { type: 'string', description: 'Catalog item name' },
256
- short_description: { type: 'string', description: 'Short description' },
257
- description: { type: 'string', description: 'Full description' },
258
- category_id: { type: 'string', description: 'Category sys_id' },
259
- price: { type: 'string', description: 'Item price (e.g., "100.00")' },
260
- recurring_price: { type: 'string', description: 'Recurring price if applicable' },
261
- active: { type: 'boolean', default: true, description: 'Whether the item is active' },
262
- variables: {
263
- type: 'array',
264
- items: {
265
- type: 'object',
266
- properties: {
267
- name: { type: 'string' },
268
- label: { type: 'string' },
269
- type: {
270
- type: 'string',
271
- enum: ['single_line_text', 'multi_line_text', 'select_box', 'checkbox', 'reference', 'date', 'datetime']
272
- },
273
- mandatory: { type: 'boolean' },
274
- default_value: { type: 'string' },
275
- choices: { type: 'array', items: { type: 'string' } }
276
- }
277
- },
278
- description: 'Variables to add'
279
- }
280
- },
281
- required: ['action']
282
- }
283
- },
284
- {
285
- name: 'snow_catalog_item_search',
286
- description: 'Search for catalog items with intelligent matching and discovery',
287
- inputSchema: {
288
- type: 'object',
289
- properties: {
290
- query: { type: 'string', description: 'Search query (e.g., "iPhone", "laptop", "mobile device")' },
291
- category_filter: { type: 'string', description: 'Filter by category name or sys_id' },
292
- include_variables: { type: 'boolean', default: false, description: 'Include catalog item variables in results' },
293
- include_inactive: { type: 'boolean', default: false, description: 'Include inactive catalog items' },
294
- fuzzy_match: { type: 'boolean', default: true, description: 'Enable fuzzy matching for similar items' },
295
- limit: { type: 'number', default: 50, description: 'Maximum results to return' }
296
- },
297
- required: ['query']
298
- }
299
- },
300
- {
301
- name: 'snow_cleanup_test_artifacts',
302
- description: 'Clean up test artifacts while preserving Update Set audit trail',
303
- inputSchema: {
304
- type: 'object',
305
- properties: {
306
- artifact_types: {
307
- type: 'array',
308
- items: {
309
- type: 'string',
310
- enum: ['catalog_items', 'flows', 'users', 'requests', 'all']
311
- },
312
- default: ['catalog_items', 'flows', 'users'],
313
- description: 'Types of artifacts to clean up'
314
- },
315
- dry_run: { type: 'boolean', default: false, description: 'Preview what would be deleted without actually deleting' },
316
- max_age_hours: { type: 'number', default: 1, description: 'Only clean artifacts older than this (hours)' }
317
- }
318
- }
319
- },
320
- {
321
- name: 'snow_create_user_group',
322
- description: 'Create a new user group in ServiceNow',
323
- inputSchema: {
324
- type: 'object',
325
- properties: {
326
- name: { type: 'string', description: 'Group name (e.g., "Need Approval")' },
327
- description: { type: 'string', description: 'Group description' },
328
- email: { type: 'string', description: 'Group email address (optional)' },
329
- manager: { type: 'string', description: 'Group manager sys_id or user_name (optional)' },
330
- parent: { type: 'string', description: 'Parent group sys_id (optional)' },
331
- active: { type: 'boolean', default: true, description: 'Is group active' }
332
- },
333
- required: ['name']
334
- }
335
- },
336
- {
337
- name: 'snow_create_user',
338
- description: 'Create a new user in ServiceNow',
339
- inputSchema: {
340
- type: 'object',
341
- properties: {
342
- user_name: { type: 'string', description: 'Unique username for login' },
343
- first_name: { type: 'string', description: 'User first name' },
344
- last_name: { type: 'string', description: 'User last name' },
345
- email: { type: 'string', description: 'User email address' },
346
- title: { type: 'string', description: 'Job title (optional)' },
347
- department: { type: 'string', description: 'Department name or sys_id (optional)' },
348
- manager: { type: 'string', description: 'Manager sys_id or user_name (optional)' },
349
- phone: { type: 'string', description: 'Phone number (optional)' },
350
- location: { type: 'string', description: 'Location name or sys_id (optional)' },
351
- active: { type: 'boolean', default: true, description: 'Is user active' }
352
- },
353
- required: ['user_name', 'first_name', 'last_name', 'email']
354
- }
355
- },
356
- {
357
- name: 'snow_assign_user_to_group',
358
- description: 'Add a user to a group in ServiceNow',
359
- inputSchema: {
360
- type: 'object',
361
- properties: {
362
- user: { type: 'string', description: 'User sys_id or user_name' },
363
- group: { type: 'string', description: 'Group sys_id or name' }
364
- },
365
- required: ['user', 'group']
366
- }
367
- },
368
- {
369
- name: 'snow_remove_user_from_group',
370
- description: 'Remove a user from a group in ServiceNow',
371
- inputSchema: {
372
- type: 'object',
373
- properties: {
374
- user: { type: 'string', description: 'User sys_id or user_name' },
375
- group: { type: 'string', description: 'Group sys_id or name' }
376
- },
377
- required: ['user', 'group']
378
- }
379
- },
380
- {
381
- name: 'snow_list_group_members',
382
- description: 'List all members of a group',
383
- inputSchema: {
384
- type: 'object',
385
- properties: {
386
- group: { type: 'string', description: 'Group sys_id or name' },
387
- active_only: { type: 'boolean', default: true, description: 'Only show active users' }
388
- },
389
- required: ['group']
390
- }
391
- }
392
- ];
393
- }
394
- async executeTool(name, args) {
395
- const startTime = Date.now();
396
- try {
397
- switch (name) {
398
- case 'snow_query_incidents':
399
- return await this.handleQueryIncidents(args);
400
- case 'snow_analyze_incident':
401
- return await this.handleAnalyzeIncident(args);
402
- case 'snow_auto_resolve_incident':
403
- return await this.handleAutoResolveIncident(args);
404
- case 'snow_query_requests':
405
- return await this.handleQueryRequests(args);
406
- case 'snow_query_problems':
407
- return await this.handleQueryProblems(args);
408
- case 'snow_cmdb_search':
409
- return await this.handleCmdbSearch(args);
410
- case 'snow_user_lookup':
411
- return await this.handleUserLookup(args);
412
- case 'snow_operational_metrics':
413
- return await this.handleOperationalMetrics(args);
414
- case 'snow_pattern__analysis':
415
- return await this.handlePatternAnalysis(args);
416
- case 'snow_knowledge_search':
417
- return await this.handleKnowledgeSearch(args);
418
- case 'snow_predictive__analysis':
419
- return await this.handlePredictiveAnalysis(args);
420
- case 'snow_catalog_item_manager':
421
- return await this.handleCatalogItemManager(args);
422
- case 'snow_catalog_item_search':
423
- return await this.handleCatalogItemSearch(args);
424
- case 'snow_cleanup_test_artifacts':
425
- return await this.handleCleanupTestArtifacts(args);
426
- case 'snow_create_user_group':
427
- return await this.handleCreateUserGroup(args);
428
- case 'snow_create_user':
429
- return await this.handleCreateUser(args);
430
- case 'snow_assign_user_to_group':
431
- return await this.handleAssignUserToGroup(args);
432
- case 'snow_remove_user_from_group':
433
- return await this.handleRemoveUserFromGroup(args);
434
- case 'snow_list_group_members':
435
- return await this.handleListGroupMembers(args);
436
- default:
437
- return {
438
- success: false,
439
- error: `Unknown tool: ${name}`
440
- };
441
- }
442
- }
443
- catch (error) {
444
- this.logger.error(`Tool execution failed: ${name}`, error);
445
- return {
446
- success: false,
447
- error: error instanceof Error ? error.message : 'Tool execution failed',
448
- executionTime: Date.now() - startTime
449
- };
450
- }
451
- }
452
- // Tool implementations
453
- async handleQueryIncidents(args) {
454
- const { query, fields, limit = 10, include__analysis } = args;
455
- const queryParams = {
456
- sysparm_query: this.parseQuery(query),
457
- sysparm_limit: limit
458
- };
459
- if (fields && fields.length > 0) {
460
- queryParams.sysparm_fields = fields.join(',');
461
- }
462
- const response = await this.client.makeRequest({
463
- method: 'GET',
464
- url: '/api/now/table/incident',
465
- params: queryParams
466
- });
467
- if (!response.success) {
468
- return {
469
- success: false,
470
- error: response.error || 'Failed to query incidents'
471
- };
472
- }
473
- let result = {
474
- incidents: response.result,
475
- total: response.result.length
476
- };
477
- if (include__analysis && response.result.length > 0) {
478
- // Add basic analysis
479
- const _analysis = this.analyzeIncidentPatterns(response.result);
480
- result = { ...result, ..._analysis };
481
- }
482
- return {
483
- success: true,
484
- result
485
- };
486
- }
487
- async handleAnalyzeIncident(args) {
488
- const { incident_id, include_similar, suggest_resolution } = args;
489
- // Get incident details
490
- const response = await this.client.makeRequest({
491
- method: 'GET',
492
- url: `/api/now/table/incident/${incident_id}`
493
- });
494
- if (!response.success || !response.result) {
495
- return {
496
- success: false,
497
- error: 'Incident not found'
498
- };
499
- }
500
- const incident = response.result;
501
- const _analysis = {
502
- incident_id: incident.sys_id,
503
- patterns_found: this.detectPatterns(incident.short_description + ' ' + incident.description),
504
- root_cause__analysis: 'Automated _analysis based on patterns',
505
- suggested_resolution: [],
506
- confidence_score: 0.75,
507
- similar_incidents: [],
508
- knowledge_articles: [],
509
- automated_actions: []
510
- };
511
- if (include_similar) {
512
- // Find similar incidents
513
- const similarQuery = this.buildSimilarQuery(incident);
514
- const similarResponse = await this.client.makeRequest({
515
- method: 'GET',
516
- url: '/api/now/table/incident',
517
- params: {
518
- sysparm_query: similarQuery,
519
- sysparm_limit: 5
520
- }
521
- });
522
- if (similarResponse.success) {
523
- _analysis.similar_incidents = similarResponse.result;
524
- }
525
- }
526
- if (suggest_resolution) {
527
- _analysis.suggested_resolution = this.generateResolutionSuggestions(incident, _analysis.patterns_found);
528
- }
529
- return {
530
- success: true,
531
- result: _analysis
532
- };
533
- }
534
- async handleAutoResolveIncident(args) {
535
- const { incident_id, dry_run = true } = args;
536
- // Get incident details
537
- const response = await this.client.makeRequest({
538
- method: 'GET',
539
- url: `/api/now/table/incident/${incident_id}`
540
- });
541
- if (!response.success || !response.result) {
542
- return {
543
- success: false,
544
- error: 'Incident not found'
545
- };
546
- }
547
- const incident = response.result;
548
- const patterns = this.detectPatterns(incident.short_description + ' ' + incident.description);
549
- const actions = this.determineAutomatedActions(patterns);
550
- if (dry_run) {
551
- return {
552
- success: true,
553
- result: {
554
- incident_id,
555
- proposed_actions: actions,
556
- dry_run: true,
557
- message: 'These actions would be performed in a real run'
558
- }
559
- };
560
- }
561
- // Execute actions (simplified)
562
- const executedActions = [];
563
- for (const action of actions) {
564
- executedActions.push({
565
- action: action,
566
- status: 'would_execute',
567
- timestamp: new Date().toISOString()
568
- });
569
- }
570
- return {
571
- success: true,
572
- result: {
573
- incident_id,
574
- executed_actions: executedActions,
575
- dry_run: false,
576
- resolution_notes: 'Automated resolution attempted'
577
- }
578
- };
579
- }
580
- async handleQueryRequests(args) {
581
- const { query, include_items, limit = 10 } = args;
582
- const queryParams = {
583
- sysparm_query: this.parseQuery(query),
584
- sysparm_limit: limit
585
- };
586
- const response = await this.client.makeRequest({
587
- method: 'GET',
588
- url: '/api/now/table/sc_request',
589
- params: queryParams
590
- });
591
- if (!response.success) {
592
- return {
593
- success: false,
594
- error: response.error || 'Failed to query requests'
595
- };
596
- }
597
- const result = {
598
- requests: response.result,
599
- total: response.result.length
600
- };
601
- if (include_items && response.result.length > 0) {
602
- // Get request items for each request
603
- for (const request of response.result) {
604
- const itemsResponse = await this.client.makeRequest({
605
- method: 'GET',
606
- url: '/api/now/table/sc_req_item',
607
- params: {
608
- sysparm_query: `request=${request.sys_id}`,
609
- sysparm_limit: 10
610
- }
611
- });
612
- if (itemsResponse.success) {
613
- request.items = itemsResponse.result;
614
- }
615
- }
616
- }
617
- return {
618
- success: true,
619
- result
620
- };
621
- }
622
- async handleQueryProblems(args) {
623
- const { query, include_incidents, limit = 10 } = args;
624
- const queryParams = {
625
- sysparm_query: this.parseQuery(query),
626
- sysparm_limit: limit
627
- };
628
- const response = await this.client.makeRequest({
629
- method: 'GET',
630
- url: '/api/now/table/problem',
631
- params: queryParams
632
- });
633
- if (!response.success) {
634
- return {
635
- success: false,
636
- error: response.error || 'Failed to query problems'
637
- };
638
- }
639
- const result = {
640
- problems: response.result,
641
- total: response.result.length
642
- };
643
- if (include_incidents && response.result.length > 0) {
644
- // Get related incidents for each problem
645
- for (const problem of response.result) {
646
- const incidentsResponse = await this.client.makeRequest({
647
- method: 'GET',
648
- url: '/api/now/table/incident',
649
- params: {
650
- sysparm_query: `problem_id=${problem.sys_id}`,
651
- sysparm_limit: 10
652
- }
653
- });
654
- if (incidentsResponse.success) {
655
- problem.related_incidents = incidentsResponse.result;
656
- }
657
- }
658
- }
659
- return {
660
- success: true,
661
- result
662
- };
663
- }
664
- async handleCmdbSearch(args) {
665
- const { query, ci_type, include_relationships, limit = 10 } = args;
666
- let table = 'cmdb_ci';
667
- if (ci_type && ci_type !== 'any') {
668
- table = operationalTableMapping[ci_type] || `cmdb_ci_${ci_type}`;
669
- }
670
- const queryParams = {
671
- sysparm_query: this.parseQuery(query),
672
- sysparm_limit: limit
673
- };
674
- const response = await this.client.makeRequest({
675
- method: 'GET',
676
- url: `/api/now/table/${table}`,
677
- params: queryParams
678
- });
679
- if (!response.success) {
680
- return {
681
- success: false,
682
- error: response.error || 'Failed to search CMDB'
683
- };
684
- }
685
- const result = {
686
- configuration_items: response.result,
687
- total: response.result.length,
688
- ci_type: ci_type || 'any'
689
- };
690
- if (include_relationships && response.result.length > 0) {
691
- // Get relationships for each CI
692
- for (const ci of response.result) {
693
- const relResponse = await this.client.makeRequest({
694
- method: 'GET',
695
- url: '/api/now/table/cmdb_rel_ci',
696
- params: {
697
- sysparm_query: `parent=${ci.sys_id}^ORchild=${ci.sys_id}`,
698
- sysparm_limit: 10
699
- }
700
- });
701
- if (relResponse.success) {
702
- ci.relationships = relResponse.result;
703
- }
704
- }
705
- }
706
- return {
707
- success: true,
708
- result
709
- };
710
- }
711
- async handleUserLookup(args) {
712
- const { identifier, include_groups, include_roles } = args;
713
- // Build query based on identifier type
714
- let query = '';
715
- if (identifier.includes('@')) {
716
- query = `email=${identifier}`;
717
- }
718
- else if (identifier.match(/^[a-f0-9]{32}$/)) {
719
- query = `sys_id=${identifier}`;
720
- }
721
- else {
722
- query = `user_name=${identifier}^ORname=${identifier}`;
723
- }
724
- const response = await this.client.makeRequest({
725
- method: 'GET',
726
- url: '/api/now/table/sys_user',
727
- params: {
728
- sysparm_query: query,
729
- sysparm_limit: 1
730
- }
731
- });
732
- if (!response.success || response.result.length === 0) {
733
- return {
734
- success: false,
735
- error: 'User not found'
736
- };
737
- }
738
- const user = response.result[0];
739
- const result = { user };
740
- if (include_groups) {
741
- const groupsResponse = await this.client.makeRequest({
742
- method: 'GET',
743
- url: '/api/now/table/sys_user_grmember',
744
- params: {
745
- sysparm_query: `user=${user.sys_id}`,
746
- sysparm_fields: 'group.name,group.sys_id'
747
- }
748
- });
749
- if (groupsResponse.success) {
750
- result.groups = groupsResponse.result.map((g) => g.group);
751
- }
752
- }
753
- if (include_roles) {
754
- const rolesResponse = await this.client.makeRequest({
755
- method: 'GET',
756
- url: '/api/now/table/sys_user_has_role',
757
- params: {
758
- sysparm_query: `user=${user.sys_id}`,
759
- sysparm_fields: 'role.name,role.sys_id'
760
- }
761
- });
762
- if (rolesResponse.success) {
763
- result.roles = rolesResponse.result.map((r) => r.role);
764
- }
765
- }
766
- return {
767
- success: true,
768
- result
769
- };
770
- }
771
- async handleOperationalMetrics(args) {
772
- const { timeframe = 'week', metric_types } = args;
773
- // Calculate date range
774
- const endDate = new Date();
775
- const startDate = new Date();
776
- switch (timeframe) {
777
- case 'today':
778
- startDate.setHours(0, 0, 0, 0);
779
- break;
780
- case 'week':
781
- startDate.setDate(startDate.getDate() - 7);
782
- break;
783
- case 'month':
784
- startDate.setMonth(startDate.getMonth() - 1);
785
- break;
786
- case 'quarter':
787
- startDate.setMonth(startDate.getMonth() - 3);
788
- break;
789
- }
790
- const dateQuery = `sys_created_on>=${startDate.toISOString()}^sys_created_on<=${endDate.toISOString()}`;
791
- // Get incident metrics
792
- const incidentResponse = await this.client.makeRequest({
793
- method: 'GET',
794
- url: '/api/now/stats/incident',
795
- params: {
796
- sysparm_query: dateQuery,
797
- sysparm_group_by: 'state,priority,category',
798
- sysparm_count: true
799
- }
800
- });
801
- const metrics = {
802
- timeframe,
803
- period: {
804
- start: startDate.toISOString(),
805
- end: endDate.toISOString()
806
- },
807
- incidents: {}
808
- };
809
- if (incidentResponse.success) {
810
- metrics.incidents = this.processIncidentMetrics(incidentResponse.result);
811
- }
812
- // Add more metrics based on metric_types if specified
813
- if (metric_types && metric_types.includes('requests')) {
814
- const requestResponse = await this.client.makeRequest({
815
- method: 'GET',
816
- url: '/api/now/stats/sc_request',
817
- params: {
818
- sysparm_query: dateQuery,
819
- sysparm_count: true
820
- }
821
- });
822
- if (requestResponse.success) {
823
- metrics.requests = {
824
- total: requestResponse.result.length || 0
825
- };
826
- }
827
- }
828
- return {
829
- success: true,
830
- result: metrics
831
- };
832
- }
833
- async handlePatternAnalysis(args) {
834
- const { analysis_type, timeframe = 'week' } = args;
835
- // This would normally do sophisticated pattern analysis
836
- // For now, return a simplified analysis
837
- const patterns = {
838
- analysis_type,
839
- timeframe,
840
- patterns_detected: [],
841
- insights: [],
842
- recommendations: []
843
- };
844
- switch (analysis_type) {
845
- case 'incident_patterns':
846
- patterns.patterns_detected = [
847
- 'Increased network-related incidents on Monday mornings',
848
- 'Database timeout issues correlate with backup schedules',
849
- 'User authentication failures spike after password policy changes'
850
- ];
851
- patterns.insights = [
852
- 'Network capacity may be insufficient for Monday morning load',
853
- 'Backup process may be impacting database performance'
854
- ];
855
- patterns.recommendations = [
856
- 'Consider network capacity upgrade',
857
- 'Review backup scheduling and database optimization'
858
- ];
859
- break;
860
- case 'request_trends':
861
- patterns.patterns_detected = [
862
- 'Mobile device requests increase 40% quarter-over-quarter',
863
- 'Software requests peak at month-end',
864
- 'VPN access requests correlate with remote work announcements'
865
- ];
866
- patterns.insights = [
867
- 'Mobile-first strategy appears to be driving device requests',
868
- 'Budget cycles may be driving month-end software requests'
869
- ];
870
- break;
871
- }
872
- return {
873
- success: true,
874
- result: patterns
875
- };
876
- }
877
- async handleKnowledgeSearch(args) {
878
- const { query, match_incident, limit = 5 } = args;
879
- let searchQuery = query;
880
- // If matching to specific incident, get incident details first
881
- if (match_incident) {
882
- const incidentResponse = await this.client.makeRequest({
883
- method: 'GET',
884
- url: `/api/now/table/incident/${match_incident}`,
885
- params: {
886
- sysparm_fields: 'short_description,description,category'
887
- }
888
- });
889
- if (incidentResponse.success && incidentResponse.result) {
890
- const incident = incidentResponse.result;
891
- searchQuery = `${incident.short_description} ${incident.description} ${incident.category}`;
892
- }
893
- }
894
- // Search knowledge base
895
- const response = await this.client.makeRequest({
896
- method: 'GET',
897
- url: '/api/now/table/kb_knowledge',
898
- params: {
899
- sysparm_query: `workflow_state=published^short_descriptionLIKE${searchQuery}^ORtextLIKE${searchQuery}`,
900
- sysparm_limit: limit,
901
- sysparm_fields: 'number,short_description,wiki,sys_id,kb_category'
902
- }
903
- });
904
- if (!response.success) {
905
- return {
906
- success: false,
907
- error: response.error || 'Failed to search knowledge base'
908
- };
909
- }
910
- return {
911
- success: true,
912
- result: {
913
- query: searchQuery,
914
- articles: response.result,
915
- total: response.result.length,
916
- matched_incident: match_incident || null
917
- }
918
- };
919
- }
920
- async handlePredictiveAnalysis(args) {
921
- const { prediction_type, timeframe = 'week' } = args;
922
- // Simplified predictive analysis
923
- const predictions = {
924
- prediction_type,
925
- timeframe,
926
- predictions: [],
927
- confidence: 0.7,
928
- based_on: 'Historical patterns and current trends'
929
- };
930
- switch (prediction_type) {
931
- case 'incident_volume':
932
- predictions.predictions = [
933
- {
934
- metric: 'incident_volume',
935
- current_rate: '45/day',
936
- predicted_rate: '52/day',
937
- change: '+15%',
938
- factors: ['Seasonal increase', 'New system deployments']
939
- }
940
- ];
941
- break;
942
- case 'system_failure':
943
- predictions.predictions = [
944
- {
945
- system: 'Database Server DB01',
946
- failure_probability: 0.23,
947
- timeframe: 'next 7 days',
948
- indicators: ['Increasing response times', 'Memory usage trending up']
949
- }
950
- ];
951
- break;
952
- }
953
- return {
954
- success: true,
955
- result: predictions
956
- };
957
- }
958
- async handleCatalogItemManager(args) {
959
- const { action, item_id, ...itemData } = args;
960
- switch (action) {
961
- case 'create':
962
- return await this.createCatalogItem(itemData);
963
- case 'update':
964
- return await this.updateCatalogItem(item_id, itemData);
965
- case 'list':
966
- return await this.listCatalogItems();
967
- case 'get':
968
- return await this.getCatalogItem(item_id);
969
- case 'publish':
970
- return await this.publishCatalogItem(item_id);
971
- case 'retire':
972
- return await this.retireCatalogItem(item_id);
973
- default:
974
- return {
975
- success: false,
976
- error: `Unknown action: ${action}`
977
- };
978
- }
979
- }
980
- async handleCatalogItemSearch(args) {
981
- const { query, category_filter, include_variables, include_inactive, fuzzy_match, limit = 50 } = args;
982
- let searchQuery = `nameLIKE${query}^ORshort_descriptionLIKE${query}`;
983
- if (!include_inactive) {
984
- searchQuery += '^active=true';
985
- }
986
- if (category_filter) {
987
- searchQuery += `^category=${category_filter}`;
988
- }
989
- const response = await this.client.makeRequest({
990
- method: 'GET',
991
- url: '/api/now/table/sc_cat_item',
992
- params: {
993
- sysparm_query: searchQuery,
994
- sysparm_limit: limit
995
- }
996
- });
997
- if (!response.success) {
998
- return {
999
- success: false,
1000
- error: response.error || 'Failed to search catalog items'
1001
- };
1002
- }
1003
- let items = response.result;
1004
- // Apply fuzzy matching if enabled
1005
- if (fuzzy_match && items.length === 0) {
1006
- // Try alternative searches
1007
- const fuzzyQueries = this.generateFuzzyQueries(query);
1008
- for (const fuzzyQuery of fuzzyQueries) {
1009
- const fuzzyResponse = await this.client.makeRequest({
1010
- method: 'GET',
1011
- url: '/api/now/table/sc_cat_item',
1012
- params: {
1013
- sysparm_query: `nameLIKE${fuzzyQuery}^ORshort_descriptionLIKE${fuzzyQuery}`,
1014
- sysparm_limit: limit
1015
- }
1016
- });
1017
- if (fuzzyResponse.success && fuzzyResponse.result.length > 0) {
1018
- items = fuzzyResponse.result;
1019
- break;
1020
- }
1021
- }
1022
- }
1023
- if (include_variables && items.length > 0) {
1024
- // Get variables for each item
1025
- for (const item of items) {
1026
- const varResponse = await this.client.makeRequest({
1027
- method: 'GET',
1028
- url: '/api/now/table/item_option_new',
1029
- params: {
1030
- sysparm_query: `cat_item=${item.sys_id}`,
1031
- sysparm_fields: 'name,question_text,type,order,mandatory'
1032
- }
1033
- });
1034
- if (varResponse.success) {
1035
- item.variables = varResponse.result;
1036
- }
1037
- }
1038
- }
1039
- return {
1040
- success: true,
1041
- result: {
1042
- catalog_items: items,
1043
- total: items.length,
1044
- query,
1045
- fuzzy_match_used: fuzzy_match && items.length > 0
1046
- }
1047
- };
1048
- }
1049
- async handleCleanupTestArtifacts(args) {
1050
- const { artifact_types, dry_run, max_age_hours } = args;
1051
- const cutoffTime = new Date();
1052
- cutoffTime.setHours(cutoffTime.getHours() - max_age_hours);
1053
- const cleanupResults = {
1054
- dry_run,
1055
- artifacts_found: 0,
1056
- artifacts_deleted: 0,
1057
- by_type: {}
1058
- };
1059
- for (const type of artifact_types) {
1060
- let table = '';
1061
- let query = '';
1062
- switch (type) {
1063
- case 'catalog_items':
1064
- table = 'sc_cat_item';
1065
- query = `nameLIKETest^ORnameLIKEMock^sys_created_on>${cutoffTime.toISOString()}`;
1066
- break;
1067
- case 'flows':
1068
- table = 'sys_hub_flow';
1069
- query = `nameLIKETest^ORnameLIKEMock^sys_created_on>${cutoffTime.toISOString()}`;
1070
- break;
1071
- case 'users':
1072
- table = 'sys_user';
1073
- query = `user_nameLIKEtest^sys_created_on>${cutoffTime.toISOString()}`;
1074
- break;
1075
- case 'requests':
1076
- table = 'sc_request';
1077
- query = `numberLIKETest^sys_created_on>${cutoffTime.toISOString()}`;
1078
- break;
1079
- }
1080
- if (table) {
1081
- const response = await this.client.makeRequest({
1082
- method: 'GET',
1083
- url: `/api/now/table/${table}`,
1084
- params: {
1085
- sysparm_query: query,
1086
- sysparm_fields: 'sys_id,name,number'
1087
- }
1088
- });
1089
- if (response.success) {
1090
- cleanupResults.artifacts_found += response.result.length;
1091
- cleanupResults.by_type[type] = response.result.length;
1092
- if (!dry_run && response.result.length > 0) {
1093
- // Delete artifacts
1094
- for (const artifact of response.result) {
1095
- try {
1096
- await this.client.makeRequest({
1097
- method: 'DELETE',
1098
- url: `/api/now/table/${table}/${artifact.sys_id}`
1099
- });
1100
- cleanupResults.artifacts_deleted++;
1101
- }
1102
- catch (error) {
1103
- this.logger.error(`Failed to delete ${type} artifact`, error);
1104
- }
1105
- }
1106
- }
1107
- }
1108
- }
1109
- }
1110
- return {
1111
- success: true,
1112
- result: cleanupResults
1113
- };
1114
- }
1115
- async handleCreateUserGroup(args) {
1116
- const groupData = {
1117
- name: args.name,
1118
- description: args.description || '',
1119
- email: args.email || '',
1120
- manager: args.manager || '',
1121
- parent: args.parent || '',
1122
- active: args.active !== false
1123
- };
1124
- const response = await this.client.makeRequest({
1125
- method: 'POST',
1126
- url: '/api/now/table/sys_user_group',
1127
- data: groupData
1128
- });
1129
- if (!response.success) {
1130
- return {
1131
- success: false,
1132
- error: response.error || 'Failed to create user group'
1133
- };
1134
- }
1135
- return {
1136
- success: true,
1137
- result: {
1138
- sys_id: response.result.sys_id,
1139
- name: response.result.name,
1140
- created: true
1141
- }
1142
- };
1143
- }
1144
- async handleCreateUser(args) {
1145
- const userData = {
1146
- user_name: args.user_name,
1147
- first_name: args.first_name,
1148
- last_name: args.last_name,
1149
- email: args.email,
1150
- title: args.title || '',
1151
- department: args.department || '',
1152
- manager: args.manager || '',
1153
- phone: args.phone || '',
1154
- location: args.location || '',
1155
- active: args.active !== false
1156
- };
1157
- const response = await this.client.makeRequest({
1158
- method: 'POST',
1159
- url: '/api/now/table/sys_user',
1160
- data: userData
1161
- });
1162
- if (!response.success) {
1163
- return {
1164
- success: false,
1165
- error: response.error || 'Failed to create user'
1166
- };
1167
- }
1168
- return {
1169
- success: true,
1170
- result: {
1171
- sys_id: response.result.sys_id,
1172
- user_name: response.result.user_name,
1173
- created: true
1174
- }
1175
- };
1176
- }
1177
- async handleAssignUserToGroup(args) {
1178
- const { user, group } = args;
1179
- // Get user sys_id
1180
- const userResponse = await this.resolveUserIdentifier(user);
1181
- if (!userResponse.success) {
1182
- return userResponse;
1183
- }
1184
- // Get group sys_id
1185
- const groupResponse = await this.resolveGroupIdentifier(group);
1186
- if (!groupResponse.success) {
1187
- return groupResponse;
1188
- }
1189
- // Create group membership
1190
- const membershipData = {
1191
- user: userResponse.result.sys_id,
1192
- group: groupResponse.result.sys_id
1193
- };
1194
- const response = await this.client.makeRequest({
1195
- method: 'POST',
1196
- url: '/api/now/table/sys_user_grmember',
1197
- data: membershipData
1198
- });
1199
- if (!response.success) {
1200
- return {
1201
- success: false,
1202
- error: response.error || 'Failed to add user to group'
1203
- };
1204
- }
1205
- return {
1206
- success: true,
1207
- result: {
1208
- user: userResponse.result.user_name,
1209
- group: groupResponse.result.name,
1210
- membership_created: true
1211
- }
1212
- };
1213
- }
1214
- async handleRemoveUserFromGroup(args) {
1215
- const { user, group } = args;
1216
- // Get user sys_id
1217
- const userResponse = await this.resolveUserIdentifier(user);
1218
- if (!userResponse.success) {
1219
- return userResponse;
1220
- }
1221
- // Get group sys_id
1222
- const groupResponse = await this.resolveGroupIdentifier(group);
1223
- if (!groupResponse.success) {
1224
- return groupResponse;
1225
- }
1226
- // Find membership record
1227
- const membershipResponse = await this.client.makeRequest({
1228
- method: 'GET',
1229
- url: '/api/now/table/sys_user_grmember',
1230
- params: {
1231
- sysparm_query: `user=${userResponse.result.sys_id}^group=${groupResponse.result.sys_id}`,
1232
- sysparm_limit: 1
1233
- }
1234
- });
1235
- if (!membershipResponse.success || membershipResponse.result.length === 0) {
1236
- return {
1237
- success: false,
1238
- error: 'User is not a member of this group'
1239
- };
1240
- }
1241
- // Delete membership
1242
- const deleteResponse = await this.client.makeRequest({
1243
- method: 'DELETE',
1244
- url: `/api/now/table/sys_user_grmember/${membershipResponse.result[0].sys_id}`
1245
- });
1246
- if (!deleteResponse.success) {
1247
- return {
1248
- success: false,
1249
- error: deleteResponse.error || 'Failed to remove user from group'
1250
- };
1251
- }
1252
- return {
1253
- success: true,
1254
- result: {
1255
- user: userResponse.result.user_name,
1256
- group: groupResponse.result.name,
1257
- membership_removed: true
1258
- }
1259
- };
1260
- }
1261
- async handleListGroupMembers(args) {
1262
- const { group, active_only } = args;
1263
- // Get group sys_id
1264
- const groupResponse = await this.resolveGroupIdentifier(group);
1265
- if (!groupResponse.success) {
1266
- return groupResponse;
1267
- }
1268
- // Get group members
1269
- let query = `group=${groupResponse.result.sys_id}`;
1270
- if (active_only) {
1271
- query += '^user.active=true';
1272
- }
1273
- const response = await this.client.makeRequest({
1274
- method: 'GET',
1275
- url: '/api/now/table/sys_user_grmember',
1276
- params: {
1277
- sysparm_query: query,
1278
- sysparm_fields: 'user.user_name,user.name,user.email,user.active'
1279
- }
1280
- });
1281
- if (!response.success) {
1282
- return {
1283
- success: false,
1284
- error: response.error || 'Failed to list group members'
1285
- };
1286
- }
1287
- return {
1288
- success: true,
1289
- result: {
1290
- group: groupResponse.result.name,
1291
- members: response.result.map((m) => m.user),
1292
- total: response.result.length
1293
- }
1294
- };
1295
- }
1296
- // Helper methods
1297
- parseQuery(query) {
1298
- // Simple natural language to encoded query conversion
1299
- // In a real implementation, this would be more sophisticated
1300
- // If it's already an encoded query, return as-is
1301
- if (query.includes('=') || query.includes('^')) {
1302
- return query;
1303
- }
1304
- // Convert natural language to basic queries
1305
- const lowerQuery = query.toLowerCase();
1306
- if (lowerQuery.includes('open')) {
1307
- return 'state=1^ORstate=2';
1308
- }
1309
- if (lowerQuery.includes('critical') || lowerQuery.includes('high priority')) {
1310
- return 'priority=1';
1311
- }
1312
- if (lowerQuery.includes('today')) {
1313
- const today = new Date();
1314
- today.setHours(0, 0, 0, 0);
1315
- return `sys_created_on>=${today.toISOString()}`;
1316
- }
1317
- // Default: search in short description
1318
- return `short_descriptionLIKE${query}`;
1319
- }
1320
- detectPatterns(text) {
1321
- const patterns = [];
1322
- const lowerText = text.toLowerCase();
1323
- // Check against common patterns
1324
- for (const [patternName, patternData] of Object.entries(commonPatterns)) {
1325
- for (const keyword of patternData.keywords) {
1326
- if (lowerText.includes(keyword)) {
1327
- patterns.push(patternName);
1328
- break;
1329
- }
1330
- }
1331
- }
1332
- return patterns;
1333
- }
1334
- buildSimilarQuery(incident) {
1335
- // Build query to find similar incidents
1336
- const terms = [];
1337
- if (incident.category) {
1338
- terms.push(`category=${incident.category}`);
1339
- }
1340
- if (incident.subcategory) {
1341
- terms.push(`subcategory=${incident.subcategory}`);
1342
- }
1343
- // Extract keywords from short description
1344
- const keywords = incident.short_description.split(' ')
1345
- .filter((word) => word.length > 3)
1346
- .slice(0, 3);
1347
- if (keywords.length > 0) {
1348
- terms.push(`short_descriptionLIKE${keywords.join(' ')}`);
1349
- }
1350
- return terms.join('^');
1351
- }
1352
- generateResolutionSuggestions(incident, patterns) {
1353
- const suggestions = [];
1354
- // Add suggestions based on patterns
1355
- for (const pattern of patterns) {
1356
- const patternData = commonPatterns[pattern];
1357
- if (patternData && patternData.common_solutions) {
1358
- suggestions.push(...patternData.common_solutions);
1359
- }
1360
- }
1361
- // Add generic suggestions based on incident properties
1362
- if (incident.priority === '1') {
1363
- suggestions.push('Escalate to senior support team');
1364
- suggestions.push('Consider emergency change if needed');
1365
- }
1366
- return [...new Set(suggestions)]; // Remove duplicates
1367
- }
1368
- determineAutomatedActions(patterns) {
1369
- const actions = [];
1370
- if (patterns.includes('network_issues')) {
1371
- actions.push('Run network diagnostic script');
1372
- actions.push('Check network device status');
1373
- }
1374
- if (patterns.includes('database_issues')) {
1375
- actions.push('Check database connection pool');
1376
- actions.push('Run database performance _analysis');
1377
- }
1378
- if (patterns.includes('auth_issues')) {
1379
- actions.push('Verify LDAP connectivity');
1380
- actions.push('Check user account status');
1381
- }
1382
- return actions;
1383
- }
1384
- analyzeIncidentPatterns(incidents) {
1385
- const _analysis = {
1386
- common_categories: {},
1387
- priority_distribution: {},
1388
- state_distribution: {},
1389
- avg_age_hours: 0
1390
- };
1391
- let totalAge = 0;
1392
- for (const incident of incidents) {
1393
- // Category analysis
1394
- const category = incident.category || 'uncategorized';
1395
- _analysis.common_categories[category] = (_analysis.common_categories[category] || 0) + 1;
1396
- // Priority analysis
1397
- const priority = incident.priority || 'unset';
1398
- _analysis.priority_distribution[priority] = (_analysis.priority_distribution[priority] || 0) + 1;
1399
- // State analysis
1400
- const state = incident.state || 'unknown';
1401
- _analysis.state_distribution[state] = (_analysis.state_distribution[state] || 0) + 1;
1402
- // Age calculation
1403
- if (incident.sys_created_on) {
1404
- const created = new Date(incident.sys_created_on);
1405
- const age = Date.now() - created.getTime();
1406
- totalAge += age;
1407
- }
1408
- }
1409
- if (incidents.length > 0) {
1410
- _analysis.avg_age_hours = Math.round(totalAge / incidents.length / (1000 * 60 * 60));
1411
- }
1412
- return { _analysis };
1413
- }
1414
- processIncidentMetrics(data) {
1415
- // Process raw metrics data into useful format
1416
- return {
1417
- total: data.length,
1418
- by_state: this.groupBy(data, 'state'),
1419
- by_priority: this.groupBy(data, 'priority'),
1420
- by_category: this.groupBy(data, 'category')
1421
- };
1422
- }
1423
- groupBy(data, field) {
1424
- return data.reduce((acc, item) => {
1425
- const key = item[field] || 'unknown';
1426
- acc[key] = (acc[key] || 0) + 1;
1427
- return acc;
1428
- }, {});
1429
- }
1430
- generateFuzzyQueries(query) {
1431
- const queries = [];
1432
- // Common variations
1433
- if (query.toLowerCase().includes('iphone')) {
1434
- queries.push('iPhone', 'Apple iPhone', 'iOS device', 'mobile phone');
1435
- }
1436
- else if (query.toLowerCase().includes('laptop')) {
1437
- queries.push('notebook', 'portable computer', 'MacBook', 'ThinkPad');
1438
- }
1439
- else if (query.toLowerCase().includes('software')) {
1440
- queries.push('application', 'program', 'license');
1441
- }
1442
- // Generic variations
1443
- queries.push(query.replace(/\s+/g, '%')); // Replace spaces with wildcards
1444
- queries.push(query.split(' ')[0]); // First word only
1445
- return queries;
1446
- }
1447
- async createTestUser() {
1448
- const testUserData = {
1449
- user_name: `test_user_${Date.now()}`,
1450
- first_name: 'Test',
1451
- last_name: 'User',
1452
- email: `test${Date.now()}@example.com`,
1453
- active: true
1454
- };
1455
- const response = await this.client.makeRequest({
1456
- method: 'POST',
1457
- url: '/api/now/table/sys_user',
1458
- data: testUserData
1459
- });
1460
- if (!response.success) {
1461
- throw new Error('Failed to create test user');
1462
- }
1463
- return response.result;
1464
- }
1465
- async createMockCatalogItems() {
1466
- const mockItems = [
1467
- {
1468
- name: `Mock iPhone ${Date.now()}`,
1469
- short_description: 'Test iPhone for flow testing',
1470
- category: 'hardware',
1471
- price: '999.00'
1472
- },
1473
- {
1474
- name: `Mock Software ${Date.now()}`,
1475
- short_description: 'Test software license',
1476
- category: 'software',
1477
- price: '299.00'
1478
- }
1479
- ];
1480
- const created = [];
1481
- for (const item of mockItems) {
1482
- const response = await this.client.makeRequest({
1483
- method: 'POST',
1484
- url: '/api/now/table/sc_cat_item',
1485
- data: item
1486
- });
1487
- if (response.success) {
1488
- created.push({
1489
- type: 'catalog_item',
1490
- sys_id: response.result.sys_id,
1491
- name: response.result.name
1492
- });
1493
- }
1494
- }
1495
- return created;
1496
- }
1497
- async cleanupTestData(testData) {
1498
- for (const item of testData) {
1499
- let table = '';
1500
- switch (item.type) {
1501
- case 'user':
1502
- table = 'sys_user';
1503
- break;
1504
- case 'catalog_item':
1505
- table = 'sc_cat_item';
1506
- break;
1507
- }
1508
- if (table) {
1509
- try {
1510
- await this.client.makeRequest({
1511
- method: 'DELETE',
1512
- url: `/api/now/table/${table}/${item.sys_id}`
1513
- });
1514
- }
1515
- catch (error) {
1516
- this.logger.error(`Failed to cleanup ${item.type}`, error);
1517
- }
1518
- }
1519
- }
1520
- }
1521
- async createCatalogItem(itemData) {
1522
- const catalogItemData = {
1523
- name: itemData.name,
1524
- short_description: itemData.short_description,
1525
- description: itemData.description || '',
1526
- category: itemData.category_id || '',
1527
- price: itemData.price || '0',
1528
- recurring_price: itemData.recurring_price || '',
1529
- active: itemData.active !== false
1530
- };
1531
- const response = await this.client.makeRequest({
1532
- method: 'POST',
1533
- url: '/api/now/table/sc_cat_item',
1534
- data: catalogItemData
1535
- });
1536
- if (!response.success) {
1537
- return {
1538
- success: false,
1539
- error: response.error || 'Failed to create catalog item'
1540
- };
1541
- }
1542
- // Add variables if provided
1543
- if (itemData.variables && itemData.variables.length > 0) {
1544
- await this.addVariablesToCatalogItem(response.result.sys_id, itemData.variables);
1545
- }
1546
- return {
1547
- success: true,
1548
- result: {
1549
- sys_id: response.result.sys_id,
1550
- name: response.result.name,
1551
- created: true
1552
- }
1553
- };
1554
- }
1555
- async updateCatalogItem(itemId, itemData) {
1556
- const updateData = {};
1557
- if (itemData.name)
1558
- updateData.name = itemData.name;
1559
- if (itemData.short_description)
1560
- updateData.short_description = itemData.short_description;
1561
- if (itemData.description)
1562
- updateData.description = itemData.description;
1563
- if (itemData.category_id)
1564
- updateData.category = itemData.category_id;
1565
- if (itemData.price)
1566
- updateData.price = itemData.price;
1567
- if (itemData.recurring_price)
1568
- updateData.recurring_price = itemData.recurring_price;
1569
- if (itemData.active !== undefined)
1570
- updateData.active = itemData.active;
1571
- const response = await this.client.makeRequest({
1572
- method: 'PATCH',
1573
- url: `/api/now/table/sc_cat_item/${itemId}`,
1574
- data: updateData
1575
- });
1576
- if (!response.success) {
1577
- return {
1578
- success: false,
1579
- error: response.error || 'Failed to update catalog item'
1580
- };
1581
- }
1582
- return {
1583
- success: true,
1584
- result: {
1585
- sys_id: response.result.sys_id,
1586
- updated: true
1587
- }
1588
- };
1589
- }
1590
- async listCatalogItems() {
1591
- const response = await this.client.makeRequest({
1592
- method: 'GET',
1593
- url: '/api/now/table/sc_cat_item',
1594
- params: {
1595
- sysparm_limit: 100,
1596
- sysparm_fields: 'sys_id,name,short_description,category,active,price'
1597
- }
1598
- });
1599
- if (!response.success) {
1600
- return {
1601
- success: false,
1602
- error: response.error || 'Failed to list catalog items'
1603
- };
1604
- }
1605
- return {
1606
- success: true,
1607
- result: {
1608
- catalog_items: response.result,
1609
- total: response.result.length
1610
- }
1611
- };
1612
- }
1613
- async getCatalogItem(itemId) {
1614
- const response = await this.client.makeRequest({
1615
- method: 'GET',
1616
- url: `/api/now/table/sc_cat_item/${itemId}`
1617
- });
1618
- if (!response.success || !response.result) {
1619
- return {
1620
- success: false,
1621
- error: 'Catalog item not found'
1622
- };
1623
- }
1624
- // Get variables
1625
- const varResponse = await this.client.makeRequest({
1626
- method: 'GET',
1627
- url: '/api/now/table/item_option_new',
1628
- params: {
1629
- sysparm_query: `cat_item=${itemId}`,
1630
- sysparm_fields: 'name,question_text,type,order,mandatory'
1631
- }
1632
- });
1633
- if (varResponse.success) {
1634
- response.result.variables = varResponse.result;
1635
- }
1636
- return {
1637
- success: true,
1638
- result: response.result
1639
- };
1640
- }
1641
- async publishCatalogItem(itemId) {
1642
- return await this.updateCatalogItem(itemId, { active: true });
1643
- }
1644
- async retireCatalogItem(itemId) {
1645
- return await this.updateCatalogItem(itemId, { active: false });
1646
- }
1647
- async addVariablesToCatalogItem(itemId, variables) {
1648
- for (const variable of variables) {
1649
- const varData = {
1650
- cat_item: itemId,
1651
- name: variable.name,
1652
- question_text: variable.label,
1653
- type: variable.type,
1654
- mandatory: variable.mandatory || false,
1655
- default_value: variable.default_value || '',
1656
- order: variable.order || 100
1657
- };
1658
- try {
1659
- await this.client.makeRequest({
1660
- method: 'POST',
1661
- url: '/api/now/table/item_option_new',
1662
- data: varData
1663
- });
1664
- }
1665
- catch (error) {
1666
- this.logger.error(`Failed to add variable ${variable.name}`, error);
1667
- }
1668
- }
1669
- }
1670
- async resolveUserIdentifier(identifier) {
1671
- let query = '';
1672
- if (identifier.match(/^[a-f0-9]{32}$/)) {
1673
- query = `sys_id=${identifier}`;
1674
- }
1675
- else {
1676
- query = `user_name=${identifier}`;
1677
- }
1678
- const response = await this.client.makeRequest({
1679
- method: 'GET',
1680
- url: '/api/now/table/sys_user',
1681
- params: {
1682
- sysparm_query: query,
1683
- sysparm_limit: 1
1684
- }
1685
- });
1686
- if (!response.success || response.result.length === 0) {
1687
- return {
1688
- success: false,
1689
- error: 'User not found'
1690
- };
1691
- }
1692
- return {
1693
- success: true,
1694
- result: response.result[0]
1695
- };
1696
- }
1697
- async resolveGroupIdentifier(identifier) {
1698
- let query = '';
1699
- if (identifier.match(/^[a-f0-9]{32}$/)) {
1700
- query = `sys_id=${identifier}`;
1701
- }
1702
- else {
1703
- query = `name=${identifier}`;
1704
- }
1705
- const response = await this.client.makeRequest({
1706
- method: 'GET',
1707
- url: '/api/now/table/sys_user_group',
1708
- params: {
1709
- sysparm_query: query,
1710
- sysparm_limit: 1
1711
- }
1712
- });
1713
- if (!response.success || response.result.length === 0) {
1714
- return {
1715
- success: false,
1716
- error: 'Group not found'
1717
- };
1718
- }
1719
- return {
1720
- success: true,
1721
- result: response.result[0]
1722
- };
1723
- }
1724
- }
1725
- exports.ServiceNowOperationsMCP = ServiceNowOperationsMCP;
1726
- // Simplified common patterns for intelligent _analysis (moved from top to avoid duplication)
1727
- const commonPatterns = {
1728
- network_issues: {
1729
- keywords: ['network', 'connectivity', 'ping', 'dns', 'timeout', 'unreachable'],
1730
- common_solutions: [
1731
- 'Check network connectivity',
1732
- 'Verify DNS resolution',
1733
- 'Test ping to server',
1734
- 'Review firewall rules'
1735
- ]
1736
- },
1737
- database_issues: {
1738
- keywords: ['database', 'connection', 'sql', 'timeout', 'deadlock', 'performance'],
1739
- common_solutions: [
1740
- 'Check database connection',
1741
- 'Review connection pool settings',
1742
- 'Analyze query performance',
1743
- 'Check for blocking processes'
1744
- ]
1745
- },
1746
- application_errors: {
1747
- keywords: ['application', 'error', 'exception', 'crash', 'memory', 'cpu'],
1748
- common_solutions: [
1749
- 'Check application logs',
1750
- 'Review memory usage',
1751
- 'Analyze CPU utilization',
1752
- 'Restart application service'
1753
- ]
1754
- },
1755
- auth_issues: {
1756
- keywords: ['authentication', 'login', 'password', 'ldap', 'sso', 'unauthorized'],
1757
- common_solutions: [
1758
- 'Reset user password',
1759
- 'Check LDAP connectivity',
1760
- 'Verify SSO configuration',
1761
- 'Review user permissions'
1762
- ]
1763
- }
1764
- };
1765
- // Create and run the server
1766
- if (require.main === module) {
1767
- const server = new ServiceNowOperationsMCP();
1768
- server.start().catch(console.error);
1769
- }
1770
- //# sourceMappingURL=servicenow-operations-mcp-refactored.js.map