snow-flow 2.9.9 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/.mcp.json +13 -141
  2. package/.mcp.json.template +11 -25
  3. package/README.md +18 -0
  4. package/claude-flow +81 -0
  5. package/claude-flow.bat +18 -0
  6. package/claude-flow.config.json +20 -0
  7. package/claude-flow.ps1 +24 -0
  8. package/dist/agents/index.d.ts +3 -10
  9. package/dist/agents/index.js +10 -50
  10. package/dist/agents/queen-agent.d.ts +0 -2
  11. package/dist/agents/queen-agent.js +25 -42
  12. package/dist/cli.js +1 -1
  13. package/dist/mcp/servicenow-automation-mcp.js +10 -10
  14. package/dist/mcp/servicenow-deployment-mcp.js +1050 -169
  15. package/dist/mcp/servicenow-development-assistant-mcp.js +13 -65
  16. package/dist/mcp/servicenow-integration-mcp.js +10 -10
  17. package/dist/mcp/servicenow-machine-learning-mcp.js +15 -15
  18. package/dist/mcp/servicenow-operations-mcp.js +23 -23
  19. package/dist/mcp/servicenow-platform-development-mcp.js +9 -9
  20. package/dist/mcp/servicenow-reporting-analytics-mcp.js +11 -11
  21. package/dist/mcp/servicenow-security-compliance-mcp.js +11 -11
  22. package/dist/mcp/servicenow-update-set-mcp.js +9 -9
  23. package/dist/mcp/shared/reliable-memory-manager.d.ts +78 -0
  24. package/dist/mcp/shared/reliable-memory-manager.js +268 -0
  25. package/dist/mcp/snow-flow-mcp.js +341 -87
  26. package/dist/queen/agent-factory.d.ts +4 -2
  27. package/dist/queen/agent-factory.js +72 -25
  28. package/dist/services/tensorflow-ml-service.d.ts +105 -0
  29. package/dist/services/tensorflow-ml-service.js +456 -0
  30. package/dist/services/widget-deployment-service.d.ts +107 -0
  31. package/dist/services/widget-deployment-service.js +332 -0
  32. package/dist/utils/file-storage-fallback.d.ts +62 -0
  33. package/dist/utils/file-storage-fallback.js +289 -0
  34. package/dist/utils/mcp-singleton-enforcer.d.ts +36 -0
  35. package/dist/utils/mcp-singleton-enforcer.js +201 -0
  36. package/dist/utils/mcp-timeout-fix.d.ts +53 -0
  37. package/dist/utils/mcp-timeout-fix.js +221 -0
  38. package/memory/agents/README.md +31 -0
  39. package/memory/claude-flow-data.json +1 -1
  40. package/memory/sessions/README.md +1 -1
  41. package/package.json +4 -2
  42. package/src/agents/README.md +192 -0
  43. package/src/health/README.md +161 -0
  44. package/src/memory/README.md +240 -0
  45. package/src/queen/README.md +403 -0
  46. package/src/schemas/deployment.schema.json +58 -0
  47. package/src/schemas/flow.schema.json +79 -0
  48. package/src/schemas/widget.schema.json +72 -0
  49. package/src/templates/base/application.template.json +45 -0
  50. package/src/templates/base/business_rule.template.json +33 -0
  51. package/src/templates/base/script_include.template.json +18 -0
  52. package/src/templates/base/table.template.json +64 -0
  53. package/src/templates/base/widget.template.json +25 -0
  54. package/src/templates/patterns/composite.incident-management.template.json +140 -0
  55. package/src/templates/patterns/widget.dashboard.template.json +238 -0
  56. package/src/templates/patterns/widget.datatable.template.json +292 -0
  57. package/dist/mcp/servicenow-graph-memory-mcp.js +0 -728
  58. package/servicenow/widgets/openai_incident_classifier/client_controller.js +0 -284
  59. package/servicenow/widgets/openai_incident_classifier/server_script.js +0 -314
  60. package/servicenow/widgets/openai_incident_classifier/style.css +0 -354
  61. package/servicenow/widgets/openai_incident_classifier/template.html +0 -167
  62. package/servicenow/widgets/openai_incident_classifier/widget.json +0 -86
  63. package/test-ml-improvements.sh +0 -76
@@ -1,728 +0,0 @@
1
- #!/usr/bin/env node
2
- "use strict";
3
- /**
4
- * ServiceNow Graph Memory MCP Server
5
- * Neo4j-based intelligent memory system for ServiceNow artifacts
6
- */
7
- var __importDefault = (this && this.__importDefault) || function (mod) {
8
- return (mod && mod.__esModule) ? mod : { "default": mod };
9
- };
10
- Object.defineProperty(exports, "__esModule", { value: true });
11
- const index_js_1 = require("@modelcontextprotocol/sdk/server/index.js");
12
- const stdio_js_1 = require("@modelcontextprotocol/sdk/server/stdio.js");
13
- const types_js_1 = require("@modelcontextprotocol/sdk/types.js");
14
- const logger_js_1 = require("../utils/logger.js");
15
- const mcp_config_manager_js_1 = require("../utils/mcp-config-manager.js");
16
- const neo4j_driver_1 = __importDefault(require("neo4j-driver"));
17
- class ServiceNowGraphMemoryMCP {
18
- constructor() {
19
- this.driver = null;
20
- this.config = null;
21
- this.neo4jAvailable = false;
22
- this.server = new index_js_1.Server({
23
- name: 'servicenow-graph-memory',
24
- version: '1.0.0',
25
- }, {
26
- capabilities: {
27
- tools: {},
28
- },
29
- });
30
- this.logger = new logger_js_1.Logger('ServiceNowGraphMemoryMCP');
31
- const rawConfig = mcp_config_manager_js_1.mcpConfig.getNeo4jConfig();
32
- // Validate Neo4j configuration - but don't fail if missing
33
- if (!rawConfig?.uri || !rawConfig?.username || !rawConfig?.password) {
34
- this.logger.warn('Neo4j configuration missing. Graph Memory MCP will run in fallback mode without Neo4j functionality.');
35
- this.logger.info('To enable Neo4j: set NEO4J_URI, NEO4J_USERNAME, and NEO4J_PASSWORD environment variables.');
36
- this.neo4jAvailable = false;
37
- }
38
- else {
39
- // After validation, we know these are defined
40
- this.config = {
41
- uri: rawConfig.uri,
42
- username: rawConfig.username,
43
- password: rawConfig.password,
44
- database: rawConfig.database
45
- };
46
- this.neo4jAvailable = true;
47
- }
48
- this.setupHandlers();
49
- }
50
- createFallbackResponse(toolName) {
51
- return {
52
- success: false,
53
- message: `${toolName} requires Neo4j database. Please install and configure Neo4j to use graph memory features.`,
54
- fallback_mode: true,
55
- instructions: [
56
- '1. Install Neo4j Community Edition',
57
- '2. Start Neo4j service',
58
- '3. Set environment variables: NEO4J_URI, NEO4J_USERNAME, NEO4J_PASSWORD',
59
- '4. Restart the MCP server'
60
- ]
61
- };
62
- }
63
- async connectToNeo4j() {
64
- if (!this.neo4jAvailable || !this.config) {
65
- this.logger.warn('Neo4j not available - using fallback mode');
66
- return;
67
- }
68
- if (!this.driver) {
69
- try {
70
- this.driver = neo4j_driver_1.default.driver(this.config.uri, neo4j_driver_1.default.auth.basic(this.config.username, this.config.password));
71
- await this.driver.verifyConnectivity();
72
- this.logger.info('Connected to Neo4j');
73
- // Create indexes for better performance
74
- const session = this.driver.session();
75
- try {
76
- await session.run('CREATE INDEX artifact_id IF NOT EXISTS FOR (a:Artifact) ON (a.id)');
77
- await session.run('CREATE INDEX artifact_type IF NOT EXISTS FOR (a:Artifact) ON (a.type)');
78
- await session.run('CREATE INDEX artifact_name IF NOT EXISTS FOR (a:Artifact) ON (a.name)');
79
- }
80
- finally {
81
- await session.close();
82
- }
83
- }
84
- catch (error) {
85
- this.logger.error('Failed to connect to Neo4j', error);
86
- this.neo4jAvailable = false;
87
- if (this.driver) {
88
- await this.driver.close();
89
- this.driver = null;
90
- }
91
- throw error;
92
- }
93
- }
94
- return this.driver;
95
- }
96
- setupHandlers() {
97
- this.server.setRequestHandler(types_js_1.ListToolsRequestSchema, async () => ({
98
- tools: [
99
- {
100
- name: 'snow_graph_index_artifact',
101
- description: 'AUTONOMOUS graph indexing - stores ServiceNow artifacts in Neo4j with relationships, enables instant understanding of dependencies and connections',
102
- inputSchema: {
103
- type: 'object',
104
- properties: {
105
- artifact: {
106
- type: 'object',
107
- properties: {
108
- id: { type: 'string', description: 'Unique identifier for the artifact' },
109
- name: { type: 'string', description: 'Artifact name' },
110
- type: { type: 'string', enum: ['widget', 'flow', 'script_include', 'business_rule', 'table', 'client_script', 'ui_script'] },
111
- content: { type: 'string', description: 'Full content/code of the artifact' },
112
- purpose: { type: 'string', description: 'What this artifact does' },
113
- },
114
- required: ['id', 'name', 'type'],
115
- },
116
- relationships: {
117
- type: 'array',
118
- description: 'Relationships to other artifacts',
119
- items: {
120
- type: 'object',
121
- properties: {
122
- to: { type: 'string', description: 'Target artifact ID' },
123
- type: { type: 'string', enum: ['USES', 'REQUIRES', 'TRIGGERS', 'CREATES', 'MODIFIES', 'CALLS', 'EXTENDS'] },
124
- data_flow: { type: 'string', description: 'How data flows between artifacts' },
125
- },
126
- },
127
- },
128
- },
129
- required: ['artifact'],
130
- },
131
- },
132
- {
133
- name: 'snow_graph_find_related',
134
- description: 'INTELLIGENT relationship discovery - finds all artifacts related to a given artifact, understands dependencies, data flows, and impact _analysis',
135
- inputSchema: {
136
- type: 'object',
137
- properties: {
138
- artifact_id: { type: 'string', description: 'Artifact ID to find relationships for' },
139
- depth: { type: 'number', description: 'How many levels of relationships to traverse', default: 2 },
140
- relationship_types: {
141
- type: 'array',
142
- description: 'Filter by relationship types',
143
- items: { type: 'string', enum: ['USES', 'REQUIRES', 'TRIGGERS', 'CREATES', 'MODIFIES', 'CALLS', 'EXTENDS'] },
144
- },
145
- },
146
- required: ['artifact_id'],
147
- },
148
- },
149
- {
150
- name: 'snow_graph_analyze_impact',
151
- description: 'IMPACT ANALYSIS - shows what will be affected if an artifact is modified, critical for safe deployments',
152
- inputSchema: {
153
- type: 'object',
154
- properties: {
155
- artifact_id: { type: 'string', description: 'Artifact to analyze impact for' },
156
- change_type: { type: 'string', enum: ['modify', 'delete', 'upgrade'], description: 'Type of change planned' },
157
- },
158
- required: ['artifact_id'],
159
- },
160
- },
161
- {
162
- name: 'snow_graph_suggest_artifacts',
163
- description: 'AI-POWERED suggestions - recommends artifacts based on current context and past successful patterns',
164
- inputSchema: {
165
- type: 'object',
166
- properties: {
167
- context: { type: 'string', description: 'Current development context' },
168
- artifact_type: { type: 'string', description: 'Type of artifact needed' },
169
- requirements: { type: 'array', items: { type: 'string' }, description: 'Specific requirements' },
170
- },
171
- required: ['context'],
172
- },
173
- },
174
- {
175
- name: 'snow_graph_pattern__analysis',
176
- description: 'PATTERN RECOGNITION - identifies common patterns, best practices, and reusable components across all artifacts',
177
- inputSchema: {
178
- type: 'object',
179
- properties: {
180
- pattern_type: { type: 'string', enum: ['architectural', 'coding', 'integration', 'error_handling'], description: 'Type of pattern to analyze' },
181
- min_occurrences: { type: 'number', description: 'Minimum times pattern must appear', default: 3 },
182
- },
183
- },
184
- },
185
- {
186
- name: 'snow_graph_visualize',
187
- description: 'GRAPH VISUALIZATION - generates Cypher queries for visualizing artifact relationships in Neo4j Browser',
188
- inputSchema: {
189
- type: 'object',
190
- properties: {
191
- focus_artifact: { type: 'string', description: 'Central artifact to visualize around' },
192
- include_types: { type: 'array', items: { type: 'string' }, description: 'Artifact types to include' },
193
- max_nodes: { type: 'number', description: 'Maximum nodes to display', default: 50 },
194
- },
195
- },
196
- },
197
- {
198
- name: 'snow_graph_export_knowledge',
199
- description: 'KNOWLEDGE EXPORT - exports learned patterns and relationships for backup or sharing',
200
- inputSchema: {
201
- type: 'object',
202
- properties: {
203
- format: { type: 'string', enum: ['cypher', 'json', 'graphml'], description: 'Export format' },
204
- include_content: { type: 'boolean', description: 'Include full artifact content', default: false },
205
- },
206
- },
207
- },
208
- ],
209
- }));
210
- this.server.setRequestHandler(types_js_1.CallToolRequestSchema, async (request) => {
211
- const { name, arguments: args } = request.params;
212
- try {
213
- await this.connectToNeo4j();
214
- switch (name) {
215
- case 'snow_graph_index_artifact':
216
- return await this.indexArtifact(args);
217
- case 'snow_graph_find_related':
218
- return await this.findRelatedArtifacts(args);
219
- case 'snow_graph_analyze_impact':
220
- return await this.analyzeImpact(args);
221
- case 'snow_graph_suggest_artifacts':
222
- return await this.suggestArtifacts(args);
223
- case 'snow_graph_pattern__analysis':
224
- return await this.analyzePatterns(args);
225
- case 'snow_graph_visualize':
226
- return await this.generateVisualization(args);
227
- case 'snow_graph_export_knowledge':
228
- return await this.exportKnowledge(args);
229
- default:
230
- throw new types_js_1.McpError(types_js_1.ErrorCode.MethodNotFound, `Unknown tool: ${name}`);
231
- }
232
- }
233
- catch (error) {
234
- this.logger.error(`Tool execution failed: ${name}`, error);
235
- throw new types_js_1.McpError(types_js_1.ErrorCode.InternalError, error instanceof Error ? error.message : String(error));
236
- }
237
- });
238
- }
239
- async indexArtifact(args) {
240
- if (!this.neo4jAvailable || !this.driver) {
241
- return this.createFallbackResponse('snow_graph_index_artifact');
242
- }
243
- const session = this.driver.session();
244
- try {
245
- const { artifact, relationships = [] } = args;
246
- // Create or update the artifact node
247
- await session.run(`
248
- MERGE (a:Artifact {id: $id})
249
- SET a.name = $name,
250
- a.type = $type,
251
- a.content = $content,
252
- a.purpose = $purpose,
253
- a.last_updated = datetime(),
254
- a.indexed_at = datetime()
255
- RETURN a
256
- `, artifact);
257
- // Create relationships
258
- for (const rel of relationships) {
259
- await session.run(`
260
- MATCH (a:Artifact {id: $fromId})
261
- MERGE (b:Artifact {id: $toId})
262
- MERGE (a)-[r:${rel.type}]->(b)
263
- SET r.data_flow = $dataFlow,
264
- r.created_at = datetime()
265
- `, {
266
- fromId: artifact.id,
267
- toId: rel.to,
268
- dataFlow: rel.data_flow || ''
269
- });
270
- }
271
- // Analyze artifact content for automatic relationship discovery
272
- const discoveredRelations = await this.discoverRelationships(artifact);
273
- return {
274
- content: [{
275
- type: 'text',
276
- text: `✅ Artifact indexed successfully!
277
-
278
- 📊 **Artifact Details:**
279
- - ID: ${artifact.id}
280
- - Name: ${artifact.name}
281
- - Type: ${artifact.type}
282
- - Relationships: ${relationships.length} explicit, ${discoveredRelations} discovered
283
-
284
- 🔗 **Graph Impact:**
285
- - Node created/updated in Neo4j
286
- - Relationships established
287
- - Available for pattern analysis
288
- - Ready for impact assessment
289
-
290
- 💡 **Next Steps:**
291
- - Use snow_graph_find_related to explore connections
292
- - Use snow_graph_analyze_impact before modifications
293
- - Use snow_graph_pattern__analysis to find similar artifacts`
294
- }]
295
- };
296
- }
297
- finally {
298
- await session.close();
299
- }
300
- }
301
- async discoverRelationships(artifact) {
302
- // Analyze artifact content to discover implicit relationships
303
- const content = artifact.content || '';
304
- const discoveries = [];
305
- // Find script includes used
306
- const scriptIncludeMatches = content.match(/new\s+(\w+)\(/g) || [];
307
- for (const match of scriptIncludeMatches) {
308
- const className = match.match(/new\s+(\w+)\(/)?.[1];
309
- if (className)
310
- discoveries.push(className);
311
- }
312
- // Find table references
313
- const tableMatches = content.match(/GlideRecord\(['"](\w+)['"]\)/g) || [];
314
- for (const match of tableMatches) {
315
- const tableName = match.match(/GlideRecord\(['"](\w+)['"]\)/)?.[1];
316
- if (tableName)
317
- discoveries.push(tableName);
318
- }
319
- return discoveries.length;
320
- }
321
- async findRelatedArtifacts(args) {
322
- if (!this.neo4jAvailable || !this.driver) {
323
- return this.createFallbackResponse('snow_graph_find_related');
324
- }
325
- const session = this.driver.session();
326
- try {
327
- const { artifact_id, depth = 2, relationship_types = [] } = args;
328
- const relFilter = relationship_types.length > 0
329
- ? `WHERE type(r) IN [${relationship_types.map((t) => `'${t}'`).join(', ')}]`
330
- : '';
331
- const result = await session.run(`
332
- MATCH (start:Artifact {id: $artifactId})
333
- CALL apoc.path.subgraphAll(start, {
334
- maxLevel: $depth,
335
- relationshipFilter: "${relFilter}"
336
- })
337
- YIELD nodes, relationships
338
- RETURN nodes, relationships
339
- `, { artifactId: artifact_id, depth });
340
- const nodes = result.records[0]?.get('nodes') || [];
341
- const relationships = result.records[0]?.get('relationships') || [];
342
- return {
343
- content: [{
344
- type: 'text',
345
- text: `🔗 Related Artifacts Found:
346
-
347
- 📊 **Summary:**
348
- - Total artifacts: ${nodes.length}
349
- - Total relationships: ${relationships.length}
350
- - Search depth: ${depth} levels
351
-
352
- 🗂️ **Artifacts:**
353
- ${nodes.map((n) => `- ${n.properties.type}: ${n.properties.name} (${n.properties.id})`).join('\n')}
354
-
355
- 🔀 **Relationships:**
356
- ${relationships.map((r) => `- ${r.type}: ${r.start} → ${r.end}`).join('\n')}
357
-
358
- 💡 **Insights:**
359
- - This artifact is part of a ${nodes.length > 10 ? 'complex' : 'simple'} dependency network
360
- - ${relationships.filter((r) => r.type === 'REQUIRES').length} required dependencies
361
- - ${relationships.filter((r) => r.type === 'USES').length} usage relationships`
362
- }]
363
- };
364
- }
365
- finally {
366
- await session.close();
367
- }
368
- }
369
- async analyzeImpact(args) {
370
- if (!this.neo4jAvailable || !this.driver) {
371
- return this.createFallbackResponse('snow_graph_analyze_impact');
372
- }
373
- const session = this.driver.session();
374
- try {
375
- const { artifact_id, change_type = 'modify' } = args;
376
- // Find all artifacts that depend on this one
377
- const result = await session.run(`
378
- MATCH (target:Artifact {id: $artifactId})
379
- MATCH (dependent:Artifact)-[:USES|REQUIRES|CALLS]->(target)
380
- RETURN dependent, count(*) as impact_count
381
- ORDER BY impact_count DESC
382
- `, { artifactId: artifact_id });
383
- const impactedArtifacts = result.records.map((r) => ({
384
- artifact: r.get('dependent').properties,
385
- impact: r.get('impact_count').toNumber()
386
- }));
387
- const riskLevel = impactedArtifacts.length > 5 ? 'HIGH' :
388
- impactedArtifacts.length > 2 ? 'MEDIUM' : 'LOW';
389
- return {
390
- content: [{
391
- type: 'text',
392
- text: `⚠️ Impact Analysis for ${change_type} operation:
393
-
394
- 🎯 **Target Artifact:** ${artifact_id}
395
-
396
- 📊 **Impact Summary:**
397
- - Affected artifacts: ${impactedArtifacts.length}
398
- - Risk level: ${riskLevel}
399
- - Change type: ${change_type}
400
-
401
- 🔗 **Affected Artifacts:**
402
- ${impactedArtifacts.map((a) => `- ${a.artifact.type}: ${a.artifact.name} (Impact: ${a.impact})`).join('\n')}
403
-
404
- ⚡ **Recommendations:**
405
- ${riskLevel === 'HIGH' ? '- Create comprehensive test plan\n- Consider phased deployment\n- Notify all stakeholders' :
406
- riskLevel === 'MEDIUM' ? '- Test affected components\n- Review integration points' :
407
- '- Safe to proceed with standard testing'}
408
-
409
- 🛡️ **Safety Measures:**
410
- - ${change_type === 'delete' ? 'Archive artifact before deletion' : 'Create backup before modification'}
411
- - Update all dependent artifacts
412
- - Run integration tests`
413
- }]
414
- };
415
- }
416
- finally {
417
- await session.close();
418
- }
419
- }
420
- async suggestArtifacts(args) {
421
- if (!this.neo4jAvailable || !this.driver) {
422
- return this.createFallbackResponse('snow_graph_suggest_artifacts');
423
- }
424
- const session = this.driver.session();
425
- try {
426
- const { context, artifact_type, requirements = [] } = args;
427
- // Find similar contexts and successful patterns
428
- const result = await session.run(`
429
- MATCH (a:Artifact)
430
- WHERE a.purpose CONTAINS $context
431
- ${artifact_type ? 'AND a.type = $artifactType' : ''}
432
- WITH a
433
- MATCH (a)-[r]-(related:Artifact)
434
- RETURN a, collect(related) as related_artifacts
435
- ORDER BY a.deployment_count DESC, a.success_rate DESC
436
- LIMIT 10
437
- `, { context, artifactType: artifact_type });
438
- const suggestions = result.records.map((r) => ({
439
- artifact: r.get('a').properties,
440
- related: r.get('related_artifacts').map((n) => n.properties)
441
- }));
442
- return {
443
- content: [{
444
- type: 'text',
445
- text: `🤖 AI-Powered Artifact Suggestions:
446
-
447
- 📋 **Context:** ${context}
448
- ${artifact_type ? `📦 **Type:** ${artifact_type}` : ''}
449
-
450
- ✨ **Recommended Artifacts:**
451
- ${suggestions.map((s, i) => `
452
- ${i + 1}. **${s.artifact.name}** (${s.artifact.type})
453
- - Purpose: ${s.artifact.purpose || 'General purpose'}
454
- - Success rate: ${s.artifact.success_rate || 'Not measured'}%
455
- - Used with: ${s.related.map((r) => r.name).join(', ')}
456
- `).join('\n')}
457
-
458
- 🎯 **Pattern Analysis:**
459
- - Most successful pattern: ${suggestions[0]?.artifact.name || 'No patterns found'}
460
- - Common dependencies: ${this.findCommonDependencies(suggestions)}
461
- - Recommended architecture: ${this.suggestArchitecture(suggestions)}
462
-
463
- 💡 **Implementation Tips:**
464
- - Start with the highest success rate artifact
465
- - Check compatibility with existing components
466
- - Consider the related artifacts for complete solution`
467
- }]
468
- };
469
- }
470
- finally {
471
- await session.close();
472
- }
473
- }
474
- findCommonDependencies(suggestions) {
475
- const deps = new Map();
476
- suggestions.forEach((s) => {
477
- s.related.forEach((r) => {
478
- deps.set(r.name, (deps.get(r.name) || 0) + 1);
479
- });
480
- });
481
- const sorted = Array.from(deps.entries())
482
- .sort((a, b) => b[1] - a[1])
483
- .slice(0, 3)
484
- .map(([name]) => name);
485
- return sorted.join(', ') || 'None identified';
486
- }
487
- suggestArchitecture(suggestions) {
488
- const types = suggestions.map(s => s.artifact.type);
489
- if (types.includes('flow') && types.includes('script_include')) {
490
- return 'Flow-based with script include utilities';
491
- }
492
- else if (types.includes('widget') && types.includes('client_script')) {
493
- return 'UI-centric with client-side logic';
494
- }
495
- else if (types.includes('business_rule')) {
496
- return 'Event-driven with business rules';
497
- }
498
- return 'Standard ServiceNow pattern';
499
- }
500
- async analyzePatterns(args) {
501
- if (!this.neo4jAvailable || !this.driver) {
502
- return this.createFallbackResponse('snow_graph_pattern__analysis');
503
- }
504
- const session = this.driver.session();
505
- try {
506
- const { pattern_type = 'architectural', min_occurrences = 3 } = args;
507
- // This would be more sophisticated in production
508
- const query = pattern_type === 'architectural' ? `
509
- MATCH (a:Artifact)-[r]->(b:Artifact)
510
- WITH type(r) as relType, a.type as sourceType, b.type as targetType, count(*) as occurrences
511
- WHERE occurrences >= $minOccurrences
512
- RETURN sourceType, relType, targetType, occurrences
513
- ORDER BY occurrences DESC
514
- ` : `
515
- MATCH (a:Artifact)
516
- WHERE a.content IS NOT NULL
517
- RETURN a.type, count(*) as count
518
- ORDER BY count DESC
519
- `;
520
- const result = await session.run(query, { minOccurrences: min_occurrences });
521
- return {
522
- content: [{
523
- type: 'text',
524
- text: `🔍 Pattern Analysis Results:
525
-
526
- 📊 **Pattern Type:** ${pattern_type}
527
- 🔢 **Minimum Occurrences:** ${min_occurrences}
528
-
529
- 📈 **Discovered Patterns:**
530
- ${result.records.map((r) => {
531
- if (pattern_type === 'architectural') {
532
- return `- ${r.get('sourceType')} → ${r.get('relType')} → ${r.get('targetType')} (${r.get('occurrences')} times)`;
533
- }
534
- else {
535
- return `- ${r.get('type')}: ${r.get('count')} artifacts`;
536
- }
537
- }).join('\n')}
538
-
539
- 💡 **Insights:**
540
- - Most common pattern: ${result.records[0] ? this.describePattern(result.records[0], pattern_type) : 'No patterns found'}
541
- - Recommended approach: Follow the established patterns for consistency
542
- - Optimization opportunity: Reuse common patterns as templates`
543
- }]
544
- };
545
- }
546
- finally {
547
- await session.close();
548
- }
549
- }
550
- describePattern(record, patternType) {
551
- if (patternType === 'architectural') {
552
- return `${record.get('sourceType')} components typically ${record.get('relType').toLowerCase()} ${record.get('targetType')} components`;
553
- }
554
- return `${record.get('type')} is the most common artifact type`;
555
- }
556
- async generateVisualization(args) {
557
- if (!this.neo4jAvailable || !this.driver) {
558
- return this.createFallbackResponse('snow_graph_visualize');
559
- }
560
- const { focus_artifact, include_types = [], max_nodes = 50 } = args;
561
- const typeFilter = include_types.length > 0
562
- ? `WHERE n.type IN [${include_types.map((t) => `'${t}'`).join(', ')}]`
563
- : '';
564
- const cypherQuery = focus_artifact ? `
565
- MATCH (center:Artifact {id: '${focus_artifact}'})
566
- CALL apoc.path.subgraphAll(center, {
567
- maxLevel: 3,
568
- limit: ${max_nodes}
569
- })
570
- YIELD nodes, relationships
571
- ${typeFilter}
572
- RETURN nodes, relationships
573
- ` : `
574
- MATCH (n:Artifact)
575
- ${typeFilter}
576
- WITH n LIMIT ${max_nodes}
577
- MATCH (n)-[r]-(m:Artifact)
578
- RETURN n, r, m
579
- `;
580
- return {
581
- content: [{
582
- type: 'text',
583
- text: `🎨 Graph Visualization Query:
584
-
585
- \`\`\`cypher
586
- ${cypherQuery}
587
- \`\`\`
588
-
589
- 📊 **Visualization Settings:**
590
- - Focus: ${focus_artifact || 'All artifacts'}
591
- - Types: ${include_types.join(', ') || 'All types'}
592
- - Max nodes: ${max_nodes}
593
-
594
- 🖥️ **To Visualize:**
595
- 1. Open Neo4j Browser
596
- 2. Paste the query above
597
- 3. Click Run
598
- 4. Use the graph view for interactive exploration
599
-
600
- 🎯 **Visualization Tips:**
601
- - Click nodes to see properties
602
- - Drag nodes to rearrange
603
- - Double-click to expand connections
604
- - Use filters to focus on specific relationships`
605
- }]
606
- };
607
- }
608
- async exportKnowledge(args) {
609
- if (!this.neo4jAvailable || !this.driver) {
610
- return this.createFallbackResponse('snow_graph_export_knowledge');
611
- }
612
- const session = this.driver.session();
613
- try {
614
- const { format = 'json', include_content = false } = args;
615
- if (format === 'cypher') {
616
- return {
617
- content: [{
618
- type: 'text',
619
- text: `📤 Export Script (Cypher):
620
-
621
- \`\`\`cypher
622
- // Create indexes
623
- CREATE INDEX artifact_id IF NOT EXISTS FOR (a:Artifact) ON (a.id);
624
- CREATE INDEX artifact_type IF NOT EXISTS FOR (a:Artifact) ON (a.type);
625
-
626
- // Export all artifacts
627
- MATCH (a:Artifact)
628
- RETURN a.id, a.name, a.type, a.purpose${include_content ? ', a.content' : ''};
629
-
630
- // Export all relationships
631
- MATCH (a:Artifact)-[r]->(b:Artifact)
632
- RETURN a.id, type(r), b.id, r.data_flow;
633
- \`\`\`
634
-
635
- 💾 **Usage:**
636
- 1. Run in target Neo4j instance
637
- 2. Import will recreate the knowledge graph
638
- 3. All patterns and relationships preserved`
639
- }]
640
- };
641
- }
642
- else {
643
- const artifacts = await session.run('MATCH (a:Artifact) RETURN a');
644
- const relationships = await session.run('MATCH (a:Artifact)-[r]->(b:Artifact) RETURN a.id as from, type(r) as type, b.id as to');
645
- const exportData = {
646
- artifacts: artifacts.records.map((r) => r.get('a').properties),
647
- relationships: relationships.records.map((r) => ({
648
- from: r.get('from'),
649
- type: r.get('type'),
650
- to: r.get('to')
651
- })),
652
- metadata: {
653
- exported_at: new Date().toISOString(),
654
- total_artifacts: artifacts.records.length,
655
- total_relationships: relationships.records.length
656
- }
657
- };
658
- return {
659
- content: [{
660
- type: 'text',
661
- text: `📤 Knowledge Export Complete:
662
-
663
- \`\`\`json
664
- ${JSON.stringify(exportData, null, 2).substring(0, 1000)}...
665
- \`\`\`
666
-
667
- 📊 **Export Summary:**
668
- - Format: ${format}
669
- - Artifacts: ${exportData.metadata.total_artifacts}
670
- - Relationships: ${exportData.metadata.total_relationships}
671
- - Content included: ${include_content ? 'Yes' : 'No'}
672
-
673
- 💾 **Next Steps:**
674
- 1. Save the export to a file
675
- 2. Use for backup or migration
676
- 3. Share with team members
677
- 4. Import into another instance`
678
- }]
679
- };
680
- }
681
- }
682
- finally {
683
- await session.close();
684
- }
685
- }
686
- async start() {
687
- try {
688
- // Try to connect to Neo4j if configured
689
- if (this.neo4jAvailable && this.config) {
690
- try {
691
- await this.connectToNeo4j();
692
- this.logger.info('Neo4j connection established');
693
- }
694
- catch (error) {
695
- this.logger.warn('Neo4j connection failed - running in fallback mode', error);
696
- this.neo4jAvailable = false;
697
- }
698
- }
699
- const transport = new stdio_js_1.StdioServerTransport();
700
- await this.server.connect(transport);
701
- this.logger.info('ServiceNow Graph Memory MCP Server started');
702
- if (!this.neo4jAvailable) {
703
- this.logger.info('Running without Neo4j - all operations will return fallback responses');
704
- }
705
- }
706
- catch (error) {
707
- this.logger.error('Failed to start server', error);
708
- throw error;
709
- }
710
- }
711
- async stop() {
712
- if (this.driver) {
713
- await this.driver.close();
714
- }
715
- }
716
- }
717
- // Start the server
718
- const server = new ServiceNowGraphMemoryMCP();
719
- server.start().catch((error) => {
720
- console.error('Failed to start ServiceNow Graph Memory MCP:', error);
721
- process.exit(1);
722
- });
723
- // Graceful shutdown
724
- process.on('SIGINT', async () => {
725
- await server.stop();
726
- process.exit(0);
727
- });
728
- //# sourceMappingURL=servicenow-graph-memory-mcp.js.map