snow-flow 2.0.2 → 2.0.4

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