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,782 +0,0 @@
1
- #!/usr/bin/env node
2
- "use strict";
3
- /**
4
- * ServiceNow Intelligent MCP Server - Agent-Integrated Version
5
- * Smart discovery and memory-aware operations for the agent ecosystem
6
- */
7
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
8
- if (k2 === undefined) k2 = k;
9
- var desc = Object.getOwnPropertyDescriptor(m, k);
10
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
11
- desc = { enumerable: true, get: function() { return m[k]; } };
12
- }
13
- Object.defineProperty(o, k2, desc);
14
- }) : (function(o, m, k, k2) {
15
- if (k2 === undefined) k2 = k;
16
- o[k2] = m[k];
17
- }));
18
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
19
- Object.defineProperty(o, "default", { enumerable: true, value: v });
20
- }) : function(o, v) {
21
- o["default"] = v;
22
- });
23
- var __importStar = (this && this.__importStar) || (function () {
24
- var ownKeys = function(o) {
25
- ownKeys = Object.getOwnPropertyNames || function (o) {
26
- var ar = [];
27
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
28
- return ar;
29
- };
30
- return ownKeys(o);
31
- };
32
- return function (mod) {
33
- if (mod && mod.__esModule) return mod;
34
- var result = {};
35
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
36
- __setModuleDefault(result, mod);
37
- return result;
38
- };
39
- })();
40
- Object.defineProperty(exports, "__esModule", { value: true });
41
- exports.ServiceNowIntelligentMCP = void 0;
42
- const types_js_1 = require("@modelcontextprotocol/sdk/types.js");
43
- const base_mcp_server_js_1 = require("./shared/base-mcp-server.js");
44
- const crypto = __importStar(require("crypto"));
45
- class ServiceNowIntelligentMCP extends base_mcp_server_js_1.BaseMCPServer {
46
- constructor() {
47
- super('servicenow-intelligent', '2.0.0');
48
- this.cacheTimeout = 5 * 60 * 1000; // 5 minutes
49
- this.searchCache = new Map();
50
- this.setupHandlers();
51
- }
52
- setupHandlers() {
53
- this.server.setRequestHandler(types_js_1.ListToolsRequestSchema, async () => ({
54
- tools: [
55
- {
56
- name: 'snow_find_artifact',
57
- description: 'AUTONOMOUS artifact discovery - finds ServiceNow artifacts using natural language, searches memory first, then ServiceNow. NO MANUAL SEARCH NEEDED.',
58
- inputSchema: {
59
- type: 'object',
60
- properties: {
61
- query: {
62
- type: 'string',
63
- description: 'Natural language query (e.g., "the widget that shows incidents on homepage")'
64
- },
65
- type: {
66
- type: 'string',
67
- enum: ['widget', 'flow', 'script', 'application', 'any'],
68
- description: 'Artifact type filter'
69
- },
70
- // Agent context
71
- session_id: { type: 'string', description: 'Agent session ID' },
72
- agent_id: { type: 'string', description: 'Searching agent ID' },
73
- agent_type: { type: 'string', description: 'Type of agent' },
74
- use_cache: { type: 'boolean', default: true, description: 'Use cached results if available' }
75
- },
76
- required: ['query']
77
- }
78
- },
79
- {
80
- name: 'snow_analyze_artifact',
81
- description: 'AUTONOMOUS deep _analysis - intelligently indexes artifacts for optimal Claude understanding, stores in memory for future use. SELF-LEARNING SYSTEM.',
82
- inputSchema: {
83
- type: 'object',
84
- properties: {
85
- sys_id: { type: 'string', description: 'System ID of the artifact' },
86
- table: { type: 'string', description: 'ServiceNow table name' },
87
- session_id: { type: 'string' },
88
- agent_id: { type: 'string' },
89
- agent_type: { type: 'string' },
90
- deep__analysis: { type: 'boolean', default: true, description: 'Perform deep _analysis' }
91
- },
92
- required: ['sys_id', 'table']
93
- }
94
- },
95
- {
96
- name: 'snow_memory_search',
97
- description: 'Search indexed ServiceNow artifacts in memory',
98
- inputSchema: {
99
- type: 'object',
100
- properties: {
101
- query: { type: 'string', description: 'Search query' },
102
- type: {
103
- type: 'string',
104
- enum: ['widget', 'flow', 'script', 'application'],
105
- description: 'Artifact type'
106
- },
107
- session_id: { type: 'string' },
108
- agent_id: { type: 'string' }
109
- },
110
- required: ['query']
111
- }
112
- },
113
- {
114
- name: 'snow_comprehensive_search',
115
- description: 'COMPREHENSIVE multi-table search - searches across all relevant ServiceNow tables for artifacts. Perfect for finding hard-to-locate items.',
116
- inputSchema: {
117
- type: 'object',
118
- properties: {
119
- query: { type: 'string', description: 'Natural language search query' },
120
- include_inactive: { type: 'boolean', default: false, description: 'Include inactive records' },
121
- session_id: { type: 'string' },
122
- agent_id: { type: 'string' },
123
- agent_type: { type: 'string' },
124
- max_results: { type: 'number', default: 50, description: 'Maximum results to return' }
125
- },
126
- required: ['query']
127
- }
128
- },
129
- {
130
- name: 'memory_store',
131
- description: 'Store data in persistent memory for multi-agent coordination',
132
- inputSchema: {
133
- type: 'object',
134
- properties: {
135
- key: { type: 'string', description: 'Unique key for the data' },
136
- value: { description: 'Data to store (any JSON-serializable value)' },
137
- ttl: { type: 'number', description: 'Time to live in milliseconds (optional)' },
138
- namespace: { type: 'string', description: 'Namespace for organizing data (optional)', default: 'default' }
139
- },
140
- required: ['key', 'value']
141
- }
142
- },
143
- {
144
- name: 'memory_get',
145
- description: 'Retrieve data from persistent memory',
146
- inputSchema: {
147
- type: 'object',
148
- properties: {
149
- key: { type: 'string', description: 'Key to retrieve' },
150
- namespace: { type: 'string', description: 'Namespace to search in (optional)', default: 'default' }
151
- },
152
- required: ['key']
153
- }
154
- },
155
- {
156
- name: 'memory_list',
157
- description: 'List all keys in memory',
158
- inputSchema: {
159
- type: 'object',
160
- properties: {
161
- namespace: { type: 'string', description: 'Namespace to list (optional)', default: 'default' },
162
- pattern: { type: 'string', description: 'Pattern to filter keys (optional)' }
163
- }
164
- }
165
- },
166
- {
167
- name: 'todo_write',
168
- description: 'Create or update todo items for task coordination',
169
- inputSchema: {
170
- type: 'object',
171
- properties: {
172
- todos: {
173
- type: 'array',
174
- description: 'Array of todo items',
175
- items: {
176
- type: 'object',
177
- properties: {
178
- id: { type: 'string', description: 'Unique ID for the todo' },
179
- content: { type: 'string', description: 'Todo description' },
180
- status: { type: 'string', enum: ['pending', 'in_progress', 'completed'], description: 'Todo status' },
181
- priority: { type: 'string', enum: ['high', 'medium', 'low'], description: 'Todo priority' }
182
- },
183
- required: ['id', 'content', 'status', 'priority']
184
- }
185
- }
186
- },
187
- required: ['todos']
188
- }
189
- },
190
- {
191
- name: 'todo_read',
192
- description: 'Read current todo list',
193
- inputSchema: {
194
- type: 'object',
195
- properties: {
196
- status: { type: 'string', enum: ['all', 'pending', 'in_progress', 'completed'], description: 'Filter by status', default: 'all' }
197
- }
198
- }
199
- }
200
- ]
201
- }));
202
- this.server.setRequestHandler(types_js_1.CallToolRequestSchema, async (request, extra) => {
203
- const { name, arguments: args } = request.params;
204
- try {
205
- switch (name) {
206
- case 'snow_find_artifact':
207
- return await this.findArtifactWithMemory(args);
208
- case 'snow_analyze_artifact':
209
- return await this.analyzeArtifactWithMemory(args);
210
- case 'snow_memory_search':
211
- return await this.searchMemory(args);
212
- case 'snow_comprehensive_search':
213
- return await this.comprehensiveSearch(args);
214
- case 'memory_store':
215
- return await this.handleMemoryStore(args);
216
- case 'memory_get':
217
- return await this.handleMemoryGet(args);
218
- case 'memory_list':
219
- return await this.handleMemoryList(args);
220
- case 'todo_write':
221
- return await this.handleTodoWrite(args);
222
- case 'todo_read':
223
- return await this.handleTodoRead(args);
224
- default:
225
- throw new Error(`Unknown tool: ${name}`);
226
- }
227
- }
228
- catch (error) {
229
- return this.createErrorResponse(`Tool execution failed: ${name}`, error);
230
- }
231
- });
232
- }
233
- /**
234
- * Find artifact with memory-first approach
235
- */
236
- async findArtifactWithMemory(args) {
237
- return await this.executeWithAgentContext('snow_find_artifact', args, async (context) => {
238
- const { query, type, use_cache } = args;
239
- // Check authentication
240
- // 🔧 MANDATORY ServiceNow connection validation
241
- const connectionResult = await this.validateServiceNowConnection();
242
- if (!connectionResult.success) {
243
- return this.createAuthenticationError(connectionResult.error);
244
- }
245
- this.assertNoMockData('artifact search');
246
- // Progress: Starting search
247
- await this.reportProgress(context, 10, 'Starting artifact search');
248
- // Step 1: Check memory first
249
- const memoryResults = await this.searchMemoryForArtifacts(query, type, context);
250
- if (memoryResults.length > 0) {
251
- await this.reportProgress(context, 30, 'Found artifacts in memory');
252
- // Store search in context for other agents
253
- await this.updateSearchContext(context, query, memoryResults);
254
- return this.createSuccessResponse(`Found ${memoryResults.length} artifacts in memory`, { results: memoryResults, source: 'memory' });
255
- }
256
- // Step 2: Check cache if enabled
257
- if (use_cache) {
258
- const cachedResults = this.getCachedResults(query, type);
259
- if (cachedResults) {
260
- await this.reportProgress(context, 40, 'Using cached results');
261
- return this.createSuccessResponse(`Found ${cachedResults.length} artifacts (cached)`, { results: cachedResults, source: 'cache' });
262
- }
263
- }
264
- // Step 3: Search ServiceNow
265
- await this.reportProgress(context, 50, 'Searching ServiceNow instance');
266
- const searchResults = await this.searchServiceNow(query, type, context);
267
- // Step 4: Store results in memory and cache
268
- await this.reportProgress(context, 80, 'Indexing results');
269
- for (const result of searchResults) {
270
- await this.storeArtifact(context, {
271
- sys_id: result.sys_id,
272
- type: result.type,
273
- name: result.name,
274
- description: result.description
275
- });
276
- }
277
- // Cache results
278
- this.cacheResults(query, type, searchResults);
279
- // Update search context
280
- await this.updateSearchContext(context, query, searchResults);
281
- await this.reportProgress(context, 100, 'Search complete');
282
- return this.createSuccessResponse(`Found ${searchResults.length} artifacts in ServiceNow`, {
283
- results: searchResults,
284
- source: 'servicenow',
285
- indexed: true
286
- });
287
- });
288
- }
289
- /**
290
- * Analyze artifact with deep learning
291
- */
292
- async analyzeArtifactWithMemory(args) {
293
- return await this.executeWithAgentContext('snow_analyze_artifact', args, async (context) => {
294
- const { sys_id, table, deep__analysis } = args;
295
- // 🔧 MANDATORY ServiceNow connection validation
296
- const connectionResult = await this.validateServiceNowConnection();
297
- if (!connectionResult.success) {
298
- return this.createAuthenticationError(connectionResult.error);
299
- }
300
- this.assertNoMockData('artifact _analysis');
301
- await this.reportProgress(context, 10, 'Fetching artifact details');
302
- // Fetch artifact from ServiceNow
303
- const artifact = await this.client.getRecord(table, sys_id);
304
- if (!artifact.success || !artifact.result) {
305
- throw new Error(`Artifact ${sys_id} not found in table ${table}`);
306
- }
307
- await this.reportProgress(context, 30, 'Analyzing artifact structure');
308
- // Perform deep analysis
309
- const _analysis = await this.performDeepAnalysis(artifact.result, table, deep__analysis);
310
- // Store _analysis in memory
311
- await this.memory.updateSharedContext({
312
- session_id: context.session_id,
313
- context_key: `artifact_analysis_${sys_id}`,
314
- context_value: JSON.stringify(_analysis),
315
- created_by_agent: context.agent_id
316
- });
317
- // Store enhanced artifact info
318
- await this.storeArtifact(context, {
319
- sys_id: sys_id,
320
- type: this.getArtifactType(table),
321
- name: artifact.result.name || artifact.result.id || sys_id,
322
- description: artifact.result.description,
323
- config: _analysis.config
324
- });
325
- await this.reportProgress(context, 70, 'Identifying relationships');
326
- // Find related artifacts
327
- const relationships = await this.findRelationships(artifact.result, table, context);
328
- // Notify relevant agents based on artifact type
329
- if (_analysis.requires_ui_work && this.getArtifactType(table) === 'widget') {
330
- await this.notifyHandoff(context, 'ui_specialist', {
331
- type: 'widget',
332
- sys_id: sys_id,
333
- next_steps: _analysis.suggested_improvements || []
334
- });
335
- }
336
- await this.reportProgress(context, 100, 'Analysis complete');
337
- return this.createSuccessResponse(`Deep _analysis completed for ${artifact.result.name || sys_id}`, {
338
- artifact: {
339
- sys_id: sys_id,
340
- name: artifact.result.name,
341
- type: this.getArtifactType(table),
342
- table: table
343
- },
344
- _analysis: _analysis,
345
- relationships: relationships,
346
- indexed: true
347
- });
348
- });
349
- }
350
- /**
351
- * Search memory for artifacts
352
- */
353
- async searchMemory(args) {
354
- return await this.executeWithAgentContext('snow_memory_search', args, async (context) => {
355
- const { query, type } = args;
356
- const artifacts = await this.memory.getSessionArtifacts(context.session_id);
357
- const results = artifacts.filter(artifact => {
358
- const matchesType = !type || artifact.artifact_type === type;
359
- const matchesQuery = artifact.name.toLowerCase().includes(query.toLowerCase()) ||
360
- (artifact.description && artifact.description.toLowerCase().includes(query.toLowerCase()));
361
- return matchesType && matchesQuery;
362
- });
363
- return this.createSuccessResponse(`Found ${results.length} artifacts in memory`, { results });
364
- });
365
- }
366
- /**
367
- * Comprehensive search across all tables
368
- */
369
- async comprehensiveSearch(args) {
370
- return await this.executeWithAgentContext('snow_comprehensive_search', args, async (context) => {
371
- const { query, include_inactive, max_results } = args;
372
- // 🔧 MANDATORY ServiceNow connection validation
373
- const connectionResult = await this.validateServiceNowConnection();
374
- if (!connectionResult.success) {
375
- return this.createAuthenticationError(connectionResult.error);
376
- }
377
- this.assertNoMockData('comprehensive search');
378
- // Define tables to search
379
- const searchTables = [
380
- { table: 'sp_widget', type: 'widget', nameField: 'name' },
381
- { table: 'sys_hub_flow', type: 'flow', nameField: 'name' },
382
- { table: 'sys_script_include', type: 'script', nameField: 'name' },
383
- { table: 'sys_app', type: 'application', nameField: 'name' },
384
- { table: 'sc_cat_item', type: 'catalog_item', nameField: 'name' },
385
- { table: 'sys_script', type: 'business_rule', nameField: 'name' }
386
- ];
387
- const allResults = [];
388
- let tablesSearched = 0;
389
- for (const searchConfig of searchTables) {
390
- await this.reportProgress(context, 10 + (80 * tablesSearched / searchTables.length), `Searching ${searchConfig.type} records`);
391
- try {
392
- const results = await this.searchTable(searchConfig.table, searchConfig.nameField, query, searchConfig.type, include_inactive, Math.floor(max_results / searchTables.length));
393
- allResults.push(...results);
394
- tablesSearched++;
395
- // Store found artifacts
396
- for (const result of results) {
397
- await this.storeArtifact(context, {
398
- sys_id: result.sys_id,
399
- type: result.type,
400
- name: result.name,
401
- description: result.description
402
- });
403
- }
404
- }
405
- catch (error) {
406
- this.logger.warn(`Failed to search ${searchConfig.table}`, error);
407
- }
408
- }
409
- // Sort by relevance
410
- allResults.sort((a, b) => (b.relevance_score || 0) - (a.relevance_score || 0));
411
- // Limit results
412
- const finalResults = allResults.slice(0, max_results);
413
- await this.reportProgress(context, 100, 'Search complete');
414
- return this.createSuccessResponse(`Comprehensive search found ${finalResults.length} artifacts across ${tablesSearched} tables`, {
415
- results: finalResults,
416
- tables_searched: tablesSearched,
417
- total_found: allResults.length,
418
- limited_to: max_results
419
- });
420
- });
421
- }
422
- // Helper methods
423
- async searchMemoryForArtifacts(query, type, context) {
424
- const artifacts = await this.memory.getSessionArtifacts(context.session_id);
425
- return artifacts
426
- .filter(artifact => {
427
- const matchesType = !type || type === 'any' || artifact.artifact_type === type;
428
- const queryLower = query.toLowerCase();
429
- const matchesQuery = artifact.name.toLowerCase().includes(queryLower) ||
430
- (artifact.description && artifact.description.toLowerCase().includes(queryLower));
431
- return matchesType && matchesQuery;
432
- })
433
- .map(artifact => ({
434
- sys_id: artifact.sys_id,
435
- name: artifact.name,
436
- type: artifact.artifact_type,
437
- table: this.getTableForType(artifact.artifact_type),
438
- description: artifact.description,
439
- relevance_score: this.calculateRelevance(artifact.name, query)
440
- }));
441
- }
442
- async searchServiceNow(query, type, context) {
443
- const results = [];
444
- // Determine which tables to search
445
- const tablesToSearch = type && type !== 'any'
446
- ? [this.getSearchConfigForType(type)]
447
- : this.getAllSearchConfigs();
448
- for (const config of tablesToSearch) {
449
- try {
450
- const tableResults = await this.searchTable(config.table, config.nameField, query, config.type, false, 10);
451
- results.push(...tableResults);
452
- }
453
- catch (error) {
454
- this.logger.warn(`Search failed for table ${config.table}`, error);
455
- }
456
- }
457
- return results;
458
- }
459
- async searchTable(table, nameField, query, type, includeInactive, limit) {
460
- const encodedQuery = `${nameField}LIKE${query}${includeInactive ? '' : '^active=true'}`;
461
- const response = await this.client.getRecords(table, {
462
- sysparm_query: encodedQuery,
463
- sysparm_limit: limit,
464
- sysparm_fields: `sys_id,${nameField},description,active`
465
- });
466
- if (!response.success || !response.result) {
467
- return [];
468
- }
469
- return response.result.map((record) => ({
470
- sys_id: record.sys_id,
471
- name: record[nameField] || 'Unnamed',
472
- type: type,
473
- table: table,
474
- description: record.description,
475
- relevance_score: this.calculateRelevance(record[nameField] || '', query)
476
- }));
477
- }
478
- async performDeepAnalysis(artifact, table, deep) {
479
- const _analysis = {
480
- structure: {},
481
- dependencies: [],
482
- config: {},
483
- suggested_improvements: []
484
- };
485
- // Analyze based on artifact type
486
- const artifactType = this.getArtifactType(table);
487
- switch (artifactType) {
488
- case 'widget':
489
- _analysis.structure = {
490
- has_template: !!artifact.template,
491
- has_css: !!artifact.css,
492
- has_client_script: !!artifact.client_script,
493
- has_server_script: !!artifact.server_script,
494
- uses_options: !!artifact.option_schema
495
- };
496
- if (deep) {
497
- // Check for common patterns
498
- if (artifact.template && !artifact.template.includes('ng-')) {
499
- _analysis.suggested_improvements.push('Consider using Angular directives');
500
- }
501
- if (!artifact.css || artifact.css.length < 50) {
502
- _analysis.suggested_improvements.push('Add responsive CSS styling');
503
- _analysis.requires_ui_work = true;
504
- }
505
- }
506
- _analysis.config = {
507
- name: artifact.name,
508
- template_size: artifact.template?.length || 0,
509
- css_size: artifact.css?.length || 0,
510
- requires_data: artifact.server_script?.includes('data.') || false
511
- };
512
- break;
513
- case 'flow':
514
- _analysis.structure = {
515
- trigger_type: artifact.trigger_type,
516
- table: artifact.table_name,
517
- active: artifact.active,
518
- has_conditions: !!artifact.condition
519
- };
520
- _analysis.config = {
521
- name: artifact.name,
522
- complexity: 'medium' // Would need to analyze flow definition
523
- };
524
- break;
525
- case 'script':
526
- _analysis.structure = {
527
- api_name: artifact.api_name,
528
- client_callable: artifact.client_callable,
529
- active: artifact.active
530
- };
531
- if (deep && artifact.script) {
532
- // Simple dependency detection
533
- const scriptDeps = [];
534
- if (artifact.script.includes('GlideRecord'))
535
- scriptDeps.push('GlideRecord API');
536
- if (artifact.script.includes('GlideAjax'))
537
- scriptDeps.push('GlideAjax');
538
- if (artifact.script.includes('gs.'))
539
- scriptDeps.push('GlideSystem API');
540
- _analysis.dependencies = scriptDeps;
541
- }
542
- break;
543
- }
544
- return _analysis;
545
- }
546
- async findRelationships(artifact, table, context) {
547
- const relationships = [];
548
- // Find references in the artifact
549
- if (table === 'sp_widget' && artifact.server_script) {
550
- // Look for script includes
551
- const scriptMatches = artifact.server_script.match(/new\s+(\w+)\(/g);
552
- if (scriptMatches) {
553
- for (const match of scriptMatches) {
554
- const scriptName = match.replace(/new\s+/, '').replace(/\(/, '');
555
- relationships.push({
556
- type: 'uses_script',
557
- name: scriptName,
558
- table: 'sys_script_include'
559
- });
560
- }
561
- }
562
- }
563
- return relationships;
564
- }
565
- async updateSearchContext(context, query, results) {
566
- await this.memory.updateSharedContext({
567
- session_id: context.session_id,
568
- context_key: `search_${this.hashQuery(query)}`,
569
- context_value: JSON.stringify({
570
- query,
571
- results: results.map(r => ({
572
- sys_id: r.sys_id,
573
- name: r.name,
574
- type: r.type
575
- })),
576
- timestamp: new Date().toISOString(),
577
- found_count: results.length
578
- }),
579
- created_by_agent: context.agent_id
580
- });
581
- }
582
- getCachedResults(query, type) {
583
- const cacheKey = `${query}_${type || 'any'}`;
584
- const cached = this.searchCache.get(cacheKey);
585
- if (cached && Date.now() - cached.timestamp < this.cacheTimeout) {
586
- return cached.results;
587
- }
588
- return null;
589
- }
590
- cacheResults(query, type, results) {
591
- const cacheKey = `${query}_${type || 'any'}`;
592
- this.searchCache.set(cacheKey, {
593
- results,
594
- timestamp: Date.now()
595
- });
596
- }
597
- calculateRelevance(name, query) {
598
- const nameLower = name.toLowerCase();
599
- const queryLower = query.toLowerCase();
600
- // Exact match
601
- if (nameLower === queryLower)
602
- return 1.0;
603
- // Starts with query
604
- if (nameLower.startsWith(queryLower))
605
- return 0.9;
606
- // Contains query
607
- if (nameLower.includes(queryLower))
608
- return 0.7;
609
- // Fuzzy match (simple)
610
- const queryWords = queryLower.split(/\s+/);
611
- const matchedWords = queryWords.filter(word => nameLower.includes(word));
612
- return matchedWords.length / queryWords.length * 0.5;
613
- }
614
- getArtifactType(table) {
615
- const typeMap = {
616
- 'sp_widget': 'widget',
617
- 'sys_hub_flow': 'flow',
618
- 'sys_script_include': 'script',
619
- 'sys_app': 'application',
620
- 'sc_cat_item': 'catalog_item',
621
- 'sys_script': 'business_rule'
622
- };
623
- return typeMap[table] || 'unknown';
624
- }
625
- getTableForType(type) {
626
- const tableMap = {
627
- 'widget': 'sp_widget',
628
- 'flow': 'sys_hub_flow',
629
- 'script': 'sys_script_include',
630
- 'application': 'sys_app',
631
- 'catalog_item': 'sc_cat_item',
632
- 'business_rule': 'sys_script'
633
- };
634
- return tableMap[type] || 'sys_metadata';
635
- }
636
- getSearchConfigForType(type) {
637
- const configs = {
638
- 'widget': { table: 'sp_widget', type: 'widget', nameField: 'name' },
639
- 'flow': { table: 'sys_hub_flow', type: 'flow', nameField: 'name' },
640
- 'script': { table: 'sys_script_include', type: 'script', nameField: 'name' },
641
- 'application': { table: 'sys_app', type: 'application', nameField: 'name' }
642
- };
643
- return configs[type] || configs['widget'];
644
- }
645
- getAllSearchConfigs() {
646
- return [
647
- { table: 'sp_widget', type: 'widget', nameField: 'name' },
648
- { table: 'sys_hub_flow', type: 'flow', nameField: 'name' },
649
- { table: 'sys_script_include', type: 'script', nameField: 'name' },
650
- { table: 'sys_app', type: 'application', nameField: 'name' }
651
- ];
652
- }
653
- hashQuery(query) {
654
- return crypto.createHash('md5').update(query).digest('hex').substring(0, 8);
655
- }
656
- /**
657
- * Memory store handler
658
- */
659
- async handleMemoryStore(args) {
660
- const { key, value, ttl, namespace = 'default' } = args;
661
- try {
662
- // Store in shared context
663
- await this.memory.updateSharedContext({
664
- session_id: 'global',
665
- context_key: `${namespace}:${key}`,
666
- context_value: JSON.stringify(value),
667
- created_by_agent: 'intelligent_mcp'
668
- });
669
- return this.createSuccessResponse(`Data stored successfully with key: ${namespace}:${key}`, { key: `${namespace}:${key}`, namespace });
670
- }
671
- catch (error) {
672
- return this.createErrorResponse('Failed to store in memory', error);
673
- }
674
- }
675
- /**
676
- * Memory get handler
677
- */
678
- async handleMemoryGet(args) {
679
- const { key, namespace = 'default' } = args;
680
- try {
681
- // Get from session context
682
- const sessionContext = await this.memory.getSessionContext('global');
683
- const fullKey = `${namespace}:${key}`;
684
- if (!sessionContext || !sessionContext[fullKey]) {
685
- return this.createSuccessResponse(`Key not found: ${namespace}:${key}`, { value: null, found: false });
686
- }
687
- return this.createSuccessResponse(`Data retrieved successfully`, {
688
- key: `${namespace}:${key}`,
689
- namespace,
690
- value: JSON.parse(sessionContext[fullKey]),
691
- found: true
692
- });
693
- }
694
- catch (error) {
695
- return this.createErrorResponse('Failed to retrieve from memory', error);
696
- }
697
- }
698
- /**
699
- * Memory list handler
700
- */
701
- async handleMemoryList(args) {
702
- const { namespace = 'default', pattern } = args;
703
- try {
704
- // Get all contexts for global session
705
- const sessionContext = await this.memory.getSessionContext('global');
706
- if (!sessionContext) {
707
- return this.createSuccessResponse(`No keys found in namespace ${namespace}`, { namespace, count: 0, keys: [] });
708
- }
709
- // Filter by namespace
710
- let keys = Object.keys(sessionContext)
711
- .filter(k => k.startsWith(`${namespace}:`))
712
- .map(k => k.replace(`${namespace}:`, ''));
713
- // Apply pattern filter if provided
714
- if (pattern) {
715
- const regex = new RegExp(pattern);
716
- keys = keys.filter(k => regex.test(k));
717
- }
718
- return this.createSuccessResponse(`Found ${keys.length} keys in namespace ${namespace}`, { namespace, count: keys.length, keys });
719
- }
720
- catch (error) {
721
- return this.createErrorResponse('Failed to list memory keys', error);
722
- }
723
- }
724
- /**
725
- * Todo write handler
726
- */
727
- async handleTodoWrite(args) {
728
- const { todos } = args;
729
- try {
730
- // Store todos in shared context
731
- await this.memory.updateSharedContext({
732
- session_id: 'global',
733
- context_key: 'todos:current',
734
- context_value: JSON.stringify(todos),
735
- created_by_agent: 'intelligent_mcp'
736
- });
737
- // Update individual todo items for quick access
738
- for (const todo of todos) {
739
- await this.memory.updateSharedContext({
740
- session_id: 'global',
741
- context_key: `todos:item:${todo.id}`,
742
- context_value: JSON.stringify(todo),
743
- created_by_agent: 'intelligent_mcp'
744
- });
745
- }
746
- return this.createSuccessResponse(`Updated ${todos.length} todo items`, { todos, count: todos.length });
747
- }
748
- catch (error) {
749
- return this.createErrorResponse('Failed to write todos', error);
750
- }
751
- }
752
- /**
753
- * Todo read handler
754
- */
755
- async handleTodoRead(args) {
756
- const { status = 'all' } = args;
757
- try {
758
- // Get current todos from session context
759
- const sessionContext = await this.memory.getSessionContext('global');
760
- const todosKey = 'todos:current';
761
- if (!sessionContext || !sessionContext[todosKey]) {
762
- return this.createSuccessResponse('No todos found', { todos: [], count: 0 });
763
- }
764
- let todos = JSON.parse(sessionContext[todosKey]);
765
- // Filter by status if not 'all'
766
- if (status !== 'all') {
767
- todos = todos.filter((t) => t.status === status);
768
- }
769
- return this.createSuccessResponse(`Found ${todos.length} todos`, { todos, count: todos.length });
770
- }
771
- catch (error) {
772
- return this.createErrorResponse('Failed to read todos', error);
773
- }
774
- }
775
- }
776
- exports.ServiceNowIntelligentMCP = ServiceNowIntelligentMCP;
777
- // Start the server
778
- // if (import.meta.url === `file://${process.argv[1]}`) {
779
- // const server = new ServiceNowIntelligentMCP();
780
- // server.start().catch(console.error);
781
- // }
782
- //# sourceMappingURL=servicenow-intelligent-mcp-refactored.js.map