mcp-adr-analysis-server 2.0.21 → 2.0.24

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 (119) hide show
  1. package/dist/.tsbuildinfo +1 -1
  2. package/dist/src/index.d.ts +9 -0
  3. package/dist/src/index.d.ts.map +1 -1
  4. package/dist/src/index.js +1380 -781
  5. package/dist/src/index.js.map +1 -1
  6. package/dist/src/tools/adr-suggestion-tool.d.ts.map +1 -1
  7. package/dist/src/tools/adr-suggestion-tool.js +32 -30
  8. package/dist/src/tools/adr-suggestion-tool.js.map +1 -1
  9. package/dist/src/tools/content-masking-tool.d.ts +4 -0
  10. package/dist/src/tools/content-masking-tool.d.ts.map +1 -1
  11. package/dist/src/tools/content-masking-tool.js +531 -28
  12. package/dist/src/tools/content-masking-tool.js.map +1 -1
  13. package/dist/src/tools/deployment-readiness-tool.d.ts +8 -5
  14. package/dist/src/tools/deployment-readiness-tool.d.ts.map +1 -1
  15. package/dist/src/tools/deployment-readiness-tool.js +741 -79
  16. package/dist/src/tools/deployment-readiness-tool.js.map +1 -1
  17. package/dist/src/tools/environment-analysis-tool.d.ts +4 -0
  18. package/dist/src/tools/environment-analysis-tool.d.ts.map +1 -1
  19. package/dist/src/tools/environment-analysis-tool.js +568 -24
  20. package/dist/src/tools/environment-analysis-tool.js.map +1 -1
  21. package/dist/src/tools/mcp-planning-tool.d.ts.map +1 -1
  22. package/dist/src/tools/mcp-planning-tool.js +298 -173
  23. package/dist/src/tools/mcp-planning-tool.js.map +1 -1
  24. package/dist/src/tools/memory-loading-tool.d.ts +60 -0
  25. package/dist/src/tools/memory-loading-tool.d.ts.map +1 -0
  26. package/dist/src/tools/memory-loading-tool.js +457 -0
  27. package/dist/src/tools/memory-loading-tool.js.map +1 -0
  28. package/dist/src/tools/smart-git-push-tool.d.ts +3 -0
  29. package/dist/src/tools/smart-git-push-tool.d.ts.map +1 -1
  30. package/dist/src/tools/smart-git-push-tool.js +177 -223
  31. package/dist/src/tools/smart-git-push-tool.js.map +1 -1
  32. package/dist/src/tools/troubleshoot-guided-workflow-tool.d.ts +20 -11
  33. package/dist/src/tools/troubleshoot-guided-workflow-tool.d.ts.map +1 -1
  34. package/dist/src/tools/troubleshoot-guided-workflow-tool.js +506 -22
  35. package/dist/src/tools/troubleshoot-guided-workflow-tool.js.map +1 -1
  36. package/dist/src/types/enhanced-errors.d.ts +173 -0
  37. package/dist/src/types/enhanced-errors.d.ts.map +1 -0
  38. package/dist/src/types/enhanced-errors.js +668 -0
  39. package/dist/src/types/enhanced-errors.js.map +1 -0
  40. package/dist/src/types/knowledge-graph-schemas.d.ts +92 -0
  41. package/dist/src/types/knowledge-graph-schemas.d.ts.map +1 -1
  42. package/dist/src/types/knowledge-graph-schemas.js +45 -17
  43. package/dist/src/types/knowledge-graph-schemas.js.map +1 -1
  44. package/dist/src/types/memory-entities.d.ts +7209 -0
  45. package/dist/src/types/memory-entities.d.ts.map +1 -0
  46. package/dist/src/types/memory-entities.js +395 -0
  47. package/dist/src/types/memory-entities.js.map +1 -0
  48. package/dist/src/types/todo-json-schemas.d.ts +7 -653
  49. package/dist/src/types/todo-json-schemas.d.ts.map +1 -1
  50. package/dist/src/types/todo-json-schemas.js +6 -110
  51. package/dist/src/types/todo-json-schemas.js.map +1 -1
  52. package/dist/src/utils/enhanced-logging.d.ts +195 -0
  53. package/dist/src/utils/enhanced-logging.d.ts.map +1 -0
  54. package/dist/src/utils/enhanced-logging.js +449 -0
  55. package/dist/src/utils/enhanced-logging.js.map +1 -0
  56. package/dist/src/utils/interactive-approval.d.ts +1 -1
  57. package/dist/src/utils/interactive-approval.d.ts.map +1 -1
  58. package/dist/src/utils/interactive-approval.js +20 -16
  59. package/dist/src/utils/interactive-approval.js.map +1 -1
  60. package/dist/src/utils/knowledge-graph-manager.d.ts +23 -1
  61. package/dist/src/utils/knowledge-graph-manager.d.ts.map +1 -1
  62. package/dist/src/utils/knowledge-graph-manager.js +297 -69
  63. package/dist/src/utils/knowledge-graph-manager.js.map +1 -1
  64. package/dist/src/utils/memory-entity-manager.d.ts +134 -0
  65. package/dist/src/utils/memory-entity-manager.d.ts.map +1 -0
  66. package/dist/src/utils/memory-entity-manager.js +848 -0
  67. package/dist/src/utils/memory-entity-manager.js.map +1 -0
  68. package/dist/src/utils/memory-health-scoring.d.ts +125 -0
  69. package/dist/src/utils/memory-health-scoring.d.ts.map +1 -0
  70. package/dist/src/utils/memory-health-scoring.js +277 -0
  71. package/dist/src/utils/memory-health-scoring.js.map +1 -0
  72. package/dist/src/utils/memory-migration-manager.d.ts +93 -0
  73. package/dist/src/utils/memory-migration-manager.d.ts.map +1 -0
  74. package/dist/src/utils/memory-migration-manager.js +834 -0
  75. package/dist/src/utils/memory-migration-manager.js.map +1 -0
  76. package/dist/src/utils/memory-relationship-mapper.d.ts +87 -0
  77. package/dist/src/utils/memory-relationship-mapper.d.ts.map +1 -0
  78. package/dist/src/utils/memory-relationship-mapper.js +481 -0
  79. package/dist/src/utils/memory-relationship-mapper.js.map +1 -0
  80. package/dist/src/utils/memory-rollback-manager.d.ts +93 -0
  81. package/dist/src/utils/memory-rollback-manager.d.ts.map +1 -0
  82. package/dist/src/utils/memory-rollback-manager.js +542 -0
  83. package/dist/src/utils/memory-rollback-manager.js.map +1 -0
  84. package/dist/src/utils/memory-transformation.d.ts +59 -0
  85. package/dist/src/utils/memory-transformation.d.ts.map +1 -0
  86. package/dist/src/utils/memory-transformation.js +742 -0
  87. package/dist/src/utils/memory-transformation.js.map +1 -0
  88. package/dist/src/utils/prompt-execution.d.ts.map +1 -1
  89. package/dist/src/utils/prompt-execution.js +72 -51
  90. package/dist/src/utils/prompt-execution.js.map +1 -1
  91. package/dist/src/utils/todo-file-watcher.d.ts +11 -23
  92. package/dist/src/utils/todo-file-watcher.d.ts.map +1 -1
  93. package/dist/src/utils/todo-file-watcher.js +18 -156
  94. package/dist/src/utils/todo-file-watcher.js.map +1 -1
  95. package/package.json +22 -6
  96. package/dist/src/tools/smart-score-tool.d.ts +0 -173
  97. package/dist/src/tools/smart-score-tool.d.ts.map +0 -1
  98. package/dist/src/tools/smart-score-tool.js +0 -681
  99. package/dist/src/tools/smart-score-tool.js.map +0 -1
  100. package/dist/src/tools/todo-management-tool-v2.d.ts +0 -368
  101. package/dist/src/tools/todo-management-tool-v2.d.ts.map +0 -1
  102. package/dist/src/tools/todo-management-tool-v2.js +0 -922
  103. package/dist/src/tools/todo-management-tool-v2.js.map +0 -1
  104. package/dist/src/utils/project-health-scoring.d.ts +0 -177
  105. package/dist/src/utils/project-health-scoring.d.ts.map +0 -1
  106. package/dist/src/utils/project-health-scoring.js +0 -370
  107. package/dist/src/utils/project-health-scoring.js.map +0 -1
  108. package/dist/src/utils/todo-json-manager.d.ts +0 -71
  109. package/dist/src/utils/todo-json-manager.d.ts.map +0 -1
  110. package/dist/src/utils/todo-json-manager.js +0 -396
  111. package/dist/src/utils/todo-json-manager.js.map +0 -1
  112. package/dist/src/utils/todo-markdown-converter.d.ts +0 -16
  113. package/dist/src/utils/todo-markdown-converter.d.ts.map +0 -1
  114. package/dist/src/utils/todo-markdown-converter.js +0 -362
  115. package/dist/src/utils/todo-markdown-converter.js.map +0 -1
  116. package/dist/src/utils/todo-migration.d.ts +0 -47
  117. package/dist/src/utils/todo-migration.d.ts.map +0 -1
  118. package/dist/src/utils/todo-migration.js +0 -261
  119. package/dist/src/utils/todo-migration.js.map +0 -1
@@ -2,21 +2,317 @@
2
2
  * MCP Tool for content masking and sensitive information detection
3
3
  * Implements prompt-driven security analysis
4
4
  * Enhanced with Generated Knowledge Prompting (GKP) for security and privacy expertise
5
+ * Now includes memory integration for security pattern learning and institutional knowledge building
5
6
  */
6
7
  import { McpAdrError } from '../types/index.js';
8
+ import { MemoryEntityManager } from '../utils/memory-entity-manager.js';
9
+ import { EnhancedLogger } from '../utils/enhanced-logging.js';
10
+ /**
11
+ * Security Memory Manager for tracking security patterns and masking effectiveness
12
+ */
13
+ class SecurityMemoryManager {
14
+ memoryManager;
15
+ logger;
16
+ constructor() {
17
+ this.memoryManager = new MemoryEntityManager();
18
+ this.logger = new EnhancedLogger();
19
+ }
20
+ async initialize() {
21
+ await this.memoryManager.initialize();
22
+ }
23
+ /**
24
+ * Store security pattern detection results as memory entity
25
+ */
26
+ async storeSecurityPattern(contentType, detectedPatterns, maskingResults, analysisMetadata) {
27
+ try {
28
+ const securityData = {
29
+ contentType: contentType,
30
+ detectedPatterns: detectedPatterns.map(pattern => ({
31
+ patternType: pattern.type || 'unknown',
32
+ severity: pattern.severity,
33
+ description: pattern.description || 'Detected sensitive pattern',
34
+ location: pattern.context || undefined,
35
+ recommendation: `Review and mask ${pattern.type || 'unknown'} patterns`,
36
+ })),
37
+ maskingResults: {
38
+ effectiveness: maskingResults?.securityScore || 0.8,
39
+ method: maskingResults?.strategy || 'analysis-only',
40
+ preservedUtility: maskingResults?.preservedContext || 0.7,
41
+ falsePositives: 0, // Simplified - could be enhanced with actual analysis
42
+ falseNegatives: 0, // Simplified - could be enhanced with actual analysis
43
+ },
44
+ riskAssessment: {
45
+ overallRisk: calculateOverallRisk(detectedPatterns),
46
+ specificRisks: detectedPatterns.map(p => `${p.type || 'unknown'} exposure risk`),
47
+ mitigationStrategies: [
48
+ 'Implement content masking',
49
+ 'Review data handling policies',
50
+ 'Enhance detection patterns',
51
+ 'Train team on security awareness',
52
+ ],
53
+ complianceImpact: assessComplianceImpact(detectedPatterns),
54
+ },
55
+ evolutionTracking: {
56
+ patternChanges: [
57
+ {
58
+ timestamp: new Date().toISOString(),
59
+ change: `Initial detection of ${detectedPatterns.length} patterns`,
60
+ impact: `Security analysis baseline established`,
61
+ },
62
+ ],
63
+ effectivenessHistory: [
64
+ {
65
+ timestamp: new Date().toISOString(),
66
+ effectiveness: maskingResults?.securityScore || 0.8,
67
+ method: maskingResults?.strategy || 'analysis-only',
68
+ },
69
+ ],
70
+ },
71
+ };
72
+ const entity = await this.memoryManager.upsertEntity({
73
+ type: 'security_pattern',
74
+ title: `Security Pattern Analysis: ${contentType} - ${detectedPatterns.length} patterns detected`,
75
+ description: `Security analysis for ${contentType} content with ${detectedPatterns.length} sensitive patterns detected and masking effectiveness of ${Math.round((maskingResults?.securityScore || 0.8) * 100)}%`,
76
+ tags: [
77
+ 'security',
78
+ 'content-masking',
79
+ contentType.toLowerCase(),
80
+ `patterns-${detectedPatterns.length}`,
81
+ `confidence-${this.getConfidenceCategory(detectedPatterns)}`,
82
+ `security-score-${Math.floor((maskingResults?.securityScore || 0.8) * 10) * 10}`,
83
+ ...(detectedPatterns.some(p => p.severity === 'critical') ? ['critical-patterns'] : []),
84
+ ...(detectedPatterns.length > 10 ? ['high-volume'] : []),
85
+ ],
86
+ securityData,
87
+ relationships: [],
88
+ context: {
89
+ projectPhase: 'security-analysis',
90
+ technicalStack: this.extractTechnicalStack(contentType, analysisMetadata),
91
+ environmentalFactors: [contentType, analysisMetadata?.environment || 'unknown'].filter(Boolean),
92
+ stakeholders: ['security-team', 'development-team', 'compliance-team'],
93
+ },
94
+ accessPattern: {
95
+ lastAccessed: new Date().toISOString(),
96
+ accessCount: 1,
97
+ accessContext: ['security-analysis'],
98
+ },
99
+ evolution: {
100
+ origin: 'created',
101
+ transformations: [
102
+ {
103
+ timestamp: new Date().toISOString(),
104
+ type: 'security_analysis',
105
+ description: `Security pattern analysis completed for ${contentType} content`,
106
+ agent: 'content-masking-tool',
107
+ },
108
+ ],
109
+ },
110
+ validation: {
111
+ isVerified: maskingResults?.securityScore > 0.7,
112
+ verificationMethod: 'automated-security-analysis',
113
+ verificationTimestamp: new Date().toISOString(),
114
+ },
115
+ });
116
+ this.logger.info(`Security pattern stored for ${contentType}`, 'SecurityMemoryManager', {
117
+ contentType,
118
+ entityId: entity.id,
119
+ patternsDetected: detectedPatterns.length,
120
+ securityScore: maskingResults?.securityScore,
121
+ criticalPatterns: detectedPatterns.filter(p => p.severity === 'critical').length,
122
+ });
123
+ return entity.id;
124
+ }
125
+ catch (error) {
126
+ this.logger.error('Failed to store security pattern', 'SecurityMemoryManager', error);
127
+ throw error;
128
+ }
129
+ }
130
+ /**
131
+ * Track masking evolution and effectiveness over time
132
+ */
133
+ async trackMaskingEvolution(previousPatternId, currentResults) {
134
+ try {
135
+ if (!previousPatternId || !currentResults) {
136
+ return {
137
+ improvements: [],
138
+ degradations: [],
139
+ recommendations: ['No previous patterns to compare with - establishing baseline'],
140
+ };
141
+ }
142
+ // Get recent security patterns for comparison
143
+ const recentPatterns = await this.memoryManager.queryEntities({
144
+ entityTypes: ['security_pattern'],
145
+ limit: 10,
146
+ sortBy: 'lastModified',
147
+ });
148
+ if (recentPatterns.entities.length === 0) {
149
+ return {
150
+ improvements: [],
151
+ degradations: [],
152
+ recommendations: ['No historical patterns found - establishing baseline'],
153
+ };
154
+ }
155
+ const analysis = this.compareSecurityPatterns(recentPatterns.entities, currentResults);
156
+ return {
157
+ improvements: analysis.improvements,
158
+ degradations: analysis.degradations,
159
+ recommendations: analysis.recommendations,
160
+ };
161
+ }
162
+ catch (error) {
163
+ this.logger.error('Failed to track masking evolution', 'SecurityMemoryManager', error);
164
+ return {
165
+ improvements: [],
166
+ degradations: [],
167
+ recommendations: ['Evolution tracking failed - continuing with current analysis'],
168
+ };
169
+ }
170
+ }
171
+ /**
172
+ * Analyze security patterns across all stored entities
173
+ */
174
+ async analyzeInstitutionalSecurity() {
175
+ try {
176
+ const allPatterns = await this.memoryManager.queryEntities({
177
+ entityTypes: ['security_pattern'],
178
+ limit: 100,
179
+ sortBy: 'lastModified',
180
+ });
181
+ if (allPatterns.entities.length === 0) {
182
+ return {
183
+ commonPatterns: [],
184
+ emergingThreats: [],
185
+ effectivenessMetrics: { overallScore: 0, totalAnalyses: 0 },
186
+ complianceStatus: { gdpr: 'unknown', hipaa: 'unknown', pci: 'unknown' },
187
+ recommendations: [
188
+ 'No security patterns in memory - start analyzing content to build knowledge',
189
+ ],
190
+ };
191
+ }
192
+ return this.performInstitutionalAnalysis(allPatterns.entities);
193
+ }
194
+ catch (error) {
195
+ this.logger.error('Failed to analyze institutional security', 'SecurityMemoryManager', error);
196
+ return {
197
+ commonPatterns: [],
198
+ emergingThreats: [],
199
+ effectivenessMetrics: { overallScore: 0, totalAnalyses: 0 },
200
+ complianceStatus: { gdpr: 'unknown', hipaa: 'unknown', pci: 'unknown' },
201
+ recommendations: ['Security analysis failed - review system configuration'],
202
+ };
203
+ }
204
+ }
205
+ // Private helper methods
206
+ getConfidenceCategory(detectedPatterns) {
207
+ const avgConfidence = detectedPatterns.reduce((sum, p) => sum + (p.confidence || 0.5), 0) / detectedPatterns.length;
208
+ if (avgConfidence >= 0.9)
209
+ return 'high';
210
+ if (avgConfidence >= 0.7)
211
+ return 'medium';
212
+ return 'low';
213
+ }
214
+ extractTechnicalStack(contentType, metadata) {
215
+ const stack = [contentType];
216
+ if (metadata?.language)
217
+ stack.push(metadata.language);
218
+ if (metadata?.framework)
219
+ stack.push(metadata.framework);
220
+ if (metadata?.environment)
221
+ stack.push(metadata.environment);
222
+ return stack;
223
+ }
224
+ compareSecurityPatterns(historicalPatterns, currentResults) {
225
+ // Simplified comparison - could be enhanced with more sophisticated analysis
226
+ const improvements = [];
227
+ const degradations = [];
228
+ const recommendations = [];
229
+ if (historicalPatterns.length > 0) {
230
+ const lastPattern = historicalPatterns[0];
231
+ const lastScore = lastPattern.securityData?.maskingEffectiveness?.securityScore || 0;
232
+ const currentScore = currentResults?.securityScore || 0;
233
+ if (currentScore > lastScore) {
234
+ improvements.push(`Security score improved from ${(lastScore * 100).toFixed(1)}% to ${(currentScore * 100).toFixed(1)}%`);
235
+ }
236
+ else if (currentScore < lastScore) {
237
+ degradations.push(`Security score decreased from ${(lastScore * 100).toFixed(1)}% to ${(currentScore * 100).toFixed(1)}%`);
238
+ }
239
+ recommendations.push('Continue monitoring security patterns for trends');
240
+ }
241
+ return { improvements, degradations, recommendations };
242
+ }
243
+ performInstitutionalAnalysis(patterns) {
244
+ // Simplified institutional analysis
245
+ const totalPatterns = patterns.length;
246
+ const avgScore = patterns.reduce((sum, p) => sum + (p.securityData?.maskingEffectiveness?.securityScore || 0), 0) / totalPatterns;
247
+ return {
248
+ commonPatterns: this.extractCommonPatterns(patterns),
249
+ emergingThreats: this.identifyEmergingThreats(patterns),
250
+ effectivenessMetrics: {
251
+ overallScore: avgScore,
252
+ totalAnalyses: totalPatterns,
253
+ averageConfidence: 0.8, // Simplified
254
+ },
255
+ complianceStatus: {
256
+ gdpr: avgScore > 0.8 ? 'likely-compliant' : 'needs-review',
257
+ hipaa: avgScore > 0.9 ? 'likely-compliant' : 'needs-review',
258
+ pci: avgScore > 0.95 ? 'likely-compliant' : 'needs-review',
259
+ },
260
+ recommendations: [
261
+ 'Continue building security knowledge through regular content analysis',
262
+ 'Monitor emerging threat patterns',
263
+ 'Maintain high masking effectiveness standards',
264
+ ],
265
+ };
266
+ }
267
+ extractCommonPatterns(patterns) {
268
+ // Extract most frequently occurring pattern types
269
+ const patternCounts = {};
270
+ patterns.forEach((p) => {
271
+ const detectedPatterns = p.securityData?.patternAnalysis?.detectedPatterns || [];
272
+ detectedPatterns.forEach((dp) => {
273
+ patternCounts[dp.type] = (patternCounts[dp.type] || 0) + 1;
274
+ });
275
+ });
276
+ return Object.entries(patternCounts)
277
+ .sort(([, a], [, b]) => b - a)
278
+ .slice(0, 5)
279
+ .map(([type, count]) => ({ type, frequency: count }));
280
+ }
281
+ identifyEmergingThreats(patterns) {
282
+ // Identify patterns that are appearing more frequently in recent analyses
283
+ const recentPatterns = patterns.slice(0, Math.min(10, patterns.length));
284
+ const threats = [];
285
+ // This is a simplified implementation
286
+ if (recentPatterns.length > 0) {
287
+ threats.push({
288
+ type: 'increasing-pattern-complexity',
289
+ description: 'Pattern detection complexity may be increasing',
290
+ trend: 'emerging',
291
+ });
292
+ }
293
+ return threats;
294
+ }
295
+ }
7
296
  /**
8
297
  * Analyze content for sensitive information
9
298
  * Enhanced with Generated Knowledge Prompting for security and privacy expertise
10
299
  */
11
300
  export async function analyzeContentSecurity(args) {
12
301
  const { content, contentType = 'general', userDefinedPatterns, knowledgeEnhancement = true, // Default to GKP enabled
13
- enhancedMode = true // Default to enhanced mode
302
+ enhancedMode = true, // Default to enhanced mode
303
+ enableMemoryIntegration = true, // Default to memory integration enabled
14
304
  } = args;
15
305
  try {
16
306
  const { analyzeSensitiveContent } = await import('../utils/content-masking.js');
17
307
  if (!content || content.trim().length === 0) {
18
308
  throw new McpAdrError('Content is required for security analysis', 'INVALID_INPUT');
19
309
  }
310
+ // Initialize memory manager if enabled
311
+ let securityMemoryManager = null;
312
+ if (enableMemoryIntegration) {
313
+ securityMemoryManager = new SecurityMemoryManager();
314
+ await securityMemoryManager.initialize();
315
+ }
20
316
  let enhancedPrompt = '';
21
317
  let knowledgeContext = '';
22
318
  // Generate security and privacy knowledge if enabled
@@ -27,11 +323,11 @@ export async function analyzeContentSecurity(args) {
27
323
  projectPath: process.cwd(),
28
324
  technologies: [],
29
325
  patterns: [],
30
- projectType: 'security-content-analysis'
326
+ projectType: 'security-content-analysis',
31
327
  }, {
32
328
  domains: ['security-patterns'],
33
329
  depth: 'intermediate',
34
- cacheEnabled: true
330
+ cacheEnabled: true,
35
331
  });
36
332
  knowledgeContext = `\n## Security & Privacy Knowledge Enhancement\n\n${knowledgeResult.prompt}\n\n---\n`;
37
333
  }
@@ -53,9 +349,90 @@ Leverage the provided cybersecurity and data privacy knowledge to create compreh
53
349
  Provide detailed findings with confidence scores and practical remediation recommendations.
54
350
  Consider regulatory compliance requirements, data classification standards, and modern security practices.
55
351
  Focus on actionable security insights that can prevent data exposure and ensure compliance.`,
56
- responseFormat: 'text'
352
+ responseFormat: 'text',
57
353
  });
58
354
  if (executionResult.isAIGenerated) {
355
+ // Memory integration: store security patterns and analysis results
356
+ let memoryIntegrationInfo = '';
357
+ if (securityMemoryManager) {
358
+ try {
359
+ // Extract patterns from AI analysis (simplified parsing)
360
+ const detectedPatterns = parseDetectedPatterns(executionResult.content, userDefinedPatterns);
361
+ const maskingResults = {
362
+ strategy: 'analysis-only',
363
+ securityScore: calculateSecurityScore(detectedPatterns, content),
364
+ successRate: 1.0,
365
+ preservedContext: 1.0, // Analysis doesn't mask, so context is preserved
366
+ complianceLevel: 'analysis-complete',
367
+ };
368
+ // Store security pattern
369
+ const patternId = await securityMemoryManager.storeSecurityPattern(contentType, detectedPatterns, maskingResults, {
370
+ contentLength: content.length,
371
+ method: 'ai-powered-analysis',
372
+ userDefinedPatterns: userDefinedPatterns?.length || 0,
373
+ });
374
+ // Track evolution
375
+ const evolution = await securityMemoryManager.trackMaskingEvolution(undefined, maskingResults);
376
+ // Get institutional insights
377
+ const institutionalAnalysis = await securityMemoryManager.analyzeInstitutionalSecurity();
378
+ memoryIntegrationInfo = `
379
+
380
+ ## 🧠 Security Memory Integration
381
+
382
+ - **Pattern Stored**: ✅ Security analysis saved (ID: ${patternId.substring(0, 8)}...)
383
+ - **Content Type**: ${contentType}
384
+ - **Patterns Detected**: ${detectedPatterns.length}
385
+ - **Security Score**: ${Math.round(maskingResults.securityScore * 100)}%
386
+
387
+ ${evolution.improvements.length > 0
388
+ ? `### Security Improvements
389
+ ${evolution.improvements.map(improvement => `- ${improvement}`).join('\n')}
390
+ `
391
+ : ''}
392
+
393
+ ${evolution.recommendations.length > 0
394
+ ? `### Evolution Recommendations
395
+ ${evolution.recommendations.map(rec => `- ${rec}`).join('\n')}
396
+ `
397
+ : ''}
398
+
399
+ ${institutionalAnalysis.commonPatterns.length > 0
400
+ ? `### Institutional Security Patterns
401
+ ${institutionalAnalysis.commonPatterns
402
+ .slice(0, 3)
403
+ .map(pattern => `- **${pattern.type}**: ${pattern.frequency} occurrences`)
404
+ .join('\n')}
405
+ `
406
+ : ''}
407
+
408
+ ${institutionalAnalysis.complianceStatus
409
+ ? `### Compliance Status
410
+ - **GDPR**: ${institutionalAnalysis.complianceStatus.gdpr}
411
+ - **HIPAA**: ${institutionalAnalysis.complianceStatus.hipaa}
412
+ - **PCI**: ${institutionalAnalysis.complianceStatus.pci}
413
+ `
414
+ : ''}
415
+
416
+ ${institutionalAnalysis.recommendations.length > 0
417
+ ? `### Security Recommendations
418
+ ${institutionalAnalysis.recommendations
419
+ .slice(0, 3)
420
+ .map(rec => `- ${rec}`)
421
+ .join('\n')}
422
+ `
423
+ : ''}
424
+ `;
425
+ }
426
+ catch (memoryError) {
427
+ memoryIntegrationInfo = `
428
+
429
+ ## 🧠 Security Memory Integration Status
430
+
431
+ - **Status**: ⚠️ Memory integration failed - analysis completed without persistence
432
+ - **Error**: ${memoryError instanceof Error ? memoryError.message : 'Unknown error'}
433
+ `;
434
+ }
435
+ }
59
436
  // AI execution successful - return actual security analysis results
60
437
  return formatMCPResponse({
61
438
  ...executionResult,
@@ -64,15 +441,18 @@ Focus on actionable security insights that can prevent data exposure and ensure
64
441
  ## Enhancement Features
65
442
  - **Generated Knowledge Prompting**: ${knowledgeEnhancement ? '✅ Enabled' : '❌ Disabled'}
66
443
  - **Enhanced Mode**: ${enhancedMode ? '✅ Enabled' : '❌ Disabled'}
444
+ - **Memory Integration**: ${enableMemoryIntegration ? '✅ Enabled' : '❌ Disabled'}
67
445
  - **Knowledge Domains**: Cybersecurity, data privacy, regulatory compliance, secret management
68
446
 
69
447
  ## Analysis Information
70
448
  - **Content Type**: ${contentType}
71
449
 
72
- ${knowledgeContext ? `## Applied Security Knowledge
450
+ ${knowledgeContext
451
+ ? `## Applied Security Knowledge
73
452
 
74
453
  ${knowledgeContext}
75
- ` : ''}
454
+ `
455
+ : ''}
76
456
  - **Content Length**: ${content.length} characters
77
457
  - **User-Defined Patterns**: ${userDefinedPatterns?.length || 0} patterns
78
458
 
@@ -80,6 +460,8 @@ ${knowledgeContext}
80
460
 
81
461
  ${executionResult.content}
82
462
 
463
+ ${memoryIntegrationInfo}
464
+
83
465
  ## Next Steps
84
466
 
85
467
  Based on the security analysis:
@@ -117,7 +499,9 @@ To apply masking to identified sensitive content, use the \`generate_content_mas
117
499
  * Enhanced with Generated Knowledge Prompting for security and privacy expertise
118
500
  */
119
501
  export async function generateContentMasking(args) {
120
- const { content, detectedItems, maskingStrategy = 'full' } = args;
502
+ const { content, detectedItems, maskingStrategy = 'full',
503
+ // enableMemoryIntegration and contentType can be used for future enhancements
504
+ } = args;
121
505
  try {
122
506
  const { generateMaskingInstructions } = await import('../utils/content-masking.js');
123
507
  if (!content || content.trim().length === 0) {
@@ -155,7 +539,7 @@ export async function generateContentMasking(args) {
155
539
  Apply appropriate masking to sensitive content while preserving functionality and readability.
156
540
  Focus on balancing security with usability, maintaining context where possible.
157
541
  Provide detailed explanations for masking decisions and security recommendations.`,
158
- responseFormat: 'text'
542
+ responseFormat: 'text',
159
543
  });
160
544
  if (executionResult.isAIGenerated) {
161
545
  // AI execution successful - return actual content masking results
@@ -218,7 +602,10 @@ export async function configureCustomPatterns(args) {
218
602
  // Use actual file operations to scan project structure
219
603
  const { scanProjectStructure } = await import('../utils/actual-file-operations.js');
220
604
  // Actually scan project structure
221
- const projectStructure = await scanProjectStructure(projectPath, { readContent: true, maxFileSize: 10000 });
605
+ const projectStructure = await scanProjectStructure(projectPath, {
606
+ readContent: true,
607
+ maxFileSize: 10000,
608
+ });
222
609
  const customPatternPrompt = `
223
610
  # Custom Pattern Configuration Generation
224
611
 
@@ -230,49 +617,65 @@ Based on actual project structure analysis, here are the findings:
230
617
  - **Directories**: ${projectStructure.directories.join(', ')}
231
618
 
232
619
  ## Package Management Files
233
- ${projectStructure.packageFiles.length > 0 ?
234
- projectStructure.packageFiles.map(f => `
620
+ ${projectStructure.packageFiles.length > 0
621
+ ? projectStructure.packageFiles
622
+ .map(f => `
235
623
  ### ${f.filename}
236
624
  \`\`\`
237
625
  ${f.content.slice(0, 500)}${f.content.length > 500 ? '\n... (truncated)' : ''}
238
626
  \`\`\`
239
- `).join('\n') : '- No package files found'}
627
+ `)
628
+ .join('\n')
629
+ : '- No package files found'}
240
630
 
241
631
  ## Environment Configuration Files
242
- ${projectStructure.environmentFiles.length > 0 ?
243
- projectStructure.environmentFiles.map(f => `
632
+ ${projectStructure.environmentFiles.length > 0
633
+ ? projectStructure.environmentFiles
634
+ .map(f => `
244
635
  ### ${f.filename}
245
636
  \`\`\`
246
637
  ${f.content.slice(0, 300)}${f.content.length > 300 ? '\n... (truncated)' : ''}
247
638
  \`\`\`
248
- `).join('\n') : '- No environment files found'}
639
+ `)
640
+ .join('\n')
641
+ : '- No environment files found'}
249
642
 
250
643
  ## Configuration Files
251
- ${projectStructure.configFiles.length > 0 ?
252
- projectStructure.configFiles.map(f => `
644
+ ${projectStructure.configFiles.length > 0
645
+ ? projectStructure.configFiles
646
+ .map(f => `
253
647
  ### ${f.filename}
254
648
  \`\`\`
255
649
  ${f.content.slice(0, 300)}${f.content.length > 300 ? '\n... (truncated)' : ''}
256
650
  \`\`\`
257
- `).join('\n') : '- No config files found'}
651
+ `)
652
+ .join('\n')
653
+ : '- No config files found'}
258
654
 
259
655
  ## Script Files
260
- ${projectStructure.scriptFiles.length > 0 ?
261
- projectStructure.scriptFiles.map(f => `
656
+ ${projectStructure.scriptFiles.length > 0
657
+ ? projectStructure.scriptFiles
658
+ .map(f => `
262
659
  ### ${f.filename}
263
660
  \`\`\`
264
661
  ${f.content.slice(0, 400)}${f.content.length > 400 ? '\n... (truncated)' : ''}
265
662
  \`\`\`
266
- `).join('\n') : '- No script files found'}
663
+ `)
664
+ .join('\n')
665
+ : '- No script files found'}
267
666
 
268
667
  ## Existing Patterns Context
269
668
 
270
- ${existingPatterns ? `
669
+ ${existingPatterns
670
+ ? `
271
671
  ### Current Patterns (${existingPatterns.length})
272
- ${existingPatterns.map((pattern, index) => `
672
+ ${existingPatterns
673
+ .map((pattern, index) => `
273
674
  #### ${index + 1}. ${pattern}
274
- `).join('')}
275
- ` : 'No existing patterns provided.'}
675
+ `)
676
+ .join('')}
677
+ `
678
+ : 'No existing patterns provided.'}
276
679
 
277
680
  ## Pattern Generation Requirements
278
681
 
@@ -345,9 +748,9 @@ const result = await configureCustomPatterns({ projectPath, existingPatterns });
345
748
  packageFiles: projectStructure.packageFiles.length,
346
749
  environmentFiles: projectStructure.environmentFiles.length,
347
750
  configFiles: projectStructure.configFiles.length,
348
- scriptFiles: projectStructure.scriptFiles.length
349
- }
350
- }
751
+ scriptFiles: projectStructure.scriptFiles.length,
752
+ },
753
+ },
351
754
  };
352
755
  return {
353
756
  content: [
@@ -466,4 +869,104 @@ ${validation.securityScore >= 0.9
466
869
  throw new McpAdrError(`Failed to validate masking: ${error instanceof Error ? error.message : String(error)}`, 'VALIDATION_ERROR');
467
870
  }
468
871
  }
872
+ /**
873
+ * Helper methods for SecurityMemoryManager
874
+ */
875
+ function calculateOverallRisk(detectedPatterns) {
876
+ if (detectedPatterns.length === 0)
877
+ return 'low';
878
+ const criticalCount = detectedPatterns.filter(p => p.severity === 'critical').length;
879
+ const highCount = detectedPatterns.filter(p => p.severity === 'high').length;
880
+ if (criticalCount > 0)
881
+ return 'critical';
882
+ if (highCount > 2)
883
+ return 'high';
884
+ if (detectedPatterns.length > 5)
885
+ return 'medium';
886
+ return 'low';
887
+ }
888
+ function assessComplianceImpact(detectedPatterns) {
889
+ const hasPersonalData = detectedPatterns.some(p => p.type === 'email' || p.type === 'name' || p.category === 'personal-data');
890
+ const hasFinancialData = detectedPatterns.some(p => p.type === 'credit-card' || p.type === 'bank-account' || p.category === 'payment-data');
891
+ const hasHealthData = detectedPatterns.some(p => p.type === 'medical-record' || p.category === 'health-data');
892
+ if (hasHealthData)
893
+ return 'HIPAA compliance required - high impact';
894
+ if (hasFinancialData)
895
+ return 'PCI DSS compliance required - high impact';
896
+ if (hasPersonalData)
897
+ return 'GDPR compliance required - medium impact';
898
+ return 'Standard security practices apply - low impact';
899
+ }
900
+ /**
901
+ * Helper function to parse detected patterns from AI analysis content
902
+ */
903
+ function parseDetectedPatterns(aiContent, userDefinedPatterns) {
904
+ // Simplified pattern parsing - in production, would use more sophisticated NLP
905
+ const patterns = [];
906
+ // Look for common security-related keywords
907
+ const securityKeywords = [
908
+ { keyword: 'password', type: 'password', severity: 'high' },
909
+ { keyword: 'secret', type: 'secret', severity: 'high' },
910
+ { keyword: 'api.key', type: 'api-key', severity: 'critical' },
911
+ { keyword: 'email', type: 'email', severity: 'medium' },
912
+ { keyword: 'token', type: 'token', severity: 'high' },
913
+ { keyword: 'credit.card', type: 'credit-card', severity: 'critical' },
914
+ { keyword: 'ssn', type: 'ssn', severity: 'critical' },
915
+ { keyword: 'phone', type: 'phone', severity: 'low' },
916
+ ];
917
+ const lowerContent = aiContent.toLowerCase();
918
+ securityKeywords.forEach(({ keyword, type, severity }) => {
919
+ if (lowerContent.includes(keyword.replace('.', ' '))) {
920
+ patterns.push({
921
+ type,
922
+ category: 'sensitive-data',
923
+ confidence: 0.7, // Simplified confidence
924
+ severity: severity,
925
+ description: `Detected potential ${type.replace('-', ' ')} pattern`,
926
+ context: `Found in AI analysis content`,
927
+ });
928
+ }
929
+ });
930
+ // Add user-defined patterns
931
+ if (userDefinedPatterns) {
932
+ userDefinedPatterns.forEach(pattern => {
933
+ if (lowerContent.includes(pattern.toLowerCase())) {
934
+ patterns.push({
935
+ type: 'user-defined',
936
+ category: 'custom-pattern',
937
+ confidence: 0.8,
938
+ severity: 'medium',
939
+ description: `User-defined pattern detected: ${pattern}`,
940
+ context: 'User-defined security pattern',
941
+ });
942
+ }
943
+ });
944
+ }
945
+ return patterns;
946
+ }
947
+ /**
948
+ * Helper function to calculate security score based on detected patterns
949
+ */
950
+ function calculateSecurityScore(detectedPatterns, content) {
951
+ if (detectedPatterns.length === 0) {
952
+ return 1.0; // No patterns detected = highest security score
953
+ }
954
+ const contentLength = content.length;
955
+ const patternDensity = detectedPatterns.length / Math.max(contentLength / 1000, 1); // patterns per 1000 chars
956
+ // Calculate base score based on pattern density and severity
957
+ let baseScore = 1.0;
958
+ detectedPatterns.forEach(pattern => {
959
+ const severityWeight = {
960
+ low: 0.05,
961
+ medium: 0.1,
962
+ high: 0.2,
963
+ critical: 0.3,
964
+ }[pattern.severity] || 0.1;
965
+ baseScore -= severityWeight * pattern.confidence;
966
+ });
967
+ // Apply density penalty
968
+ const densityPenalty = Math.min(patternDensity * 0.1, 0.3);
969
+ baseScore -= densityPenalty;
970
+ return Math.max(0, Math.min(1, baseScore));
971
+ }
469
972
  //# sourceMappingURL=content-masking-tool.js.map