framework-mcp 1.3.5 → 1.3.6

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.
package/src/index.ts CHANGED
@@ -16,1601 +16,3 @@ export { SafeguardManager } from './core/safeguard-manager.js';
16
16
 
17
17
  // Clean architecture - all safeguards data moved to SafeguardManager
18
18
 
19
- import { Server } from '@modelcontextprotocol/sdk/server/index.js';
20
- import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
21
- import {
22
- CallToolRequestSchema,
23
- ListToolsRequestSchema,
24
- Tool,
25
- } from '@modelcontextprotocol/sdk/types.js';
26
- import * as fs from 'fs/promises';
27
- import * as path from 'path';
28
- import { SafeguardManager } from './core/safeguard-manager.js';
29
-
30
- interface SafeguardElement {
31
- id: string;
32
- title: string;
33
- description: string;
34
- implementationGroup: 'IG1' | 'IG2' | 'IG3';
35
- assetType: string[];
36
- securityFunction: string[];
37
- // Color-coded elements from the CIS visualizations
38
- governanceElements: string[]; // Orange - MUST be met
39
- coreRequirements: string[]; // Green - The "what" of the safeguard
40
- subTaxonomicalElements: string[]; // Yellow - Sub-taxonomical elements
41
- implementationSuggestions: string[]; // Gray - Suggestions for implementation
42
- relatedSafeguards: string[];
43
- keywords: string[];
44
- }
45
-
46
- interface VendorAnalysis {
47
- vendor: string;
48
- safeguardId: string;
49
- safeguardTitle: string;
50
- // Primary capability categorization - what role does this tool play?
51
- capability: 'full' | 'partial' | 'facilitates' | 'governance' | 'validates';
52
- // Detailed capability breakdown
53
- capabilities: {
54
- full: boolean; // Directly implements the core safeguard functionality
55
- partial: boolean; // Implements limited aspects of the safeguard
56
- facilitates: boolean; // Enhances or enables safeguard implementation by others
57
- governance: boolean; // Provides policy, process, and oversight capabilities
58
- validates: boolean; // Provides evidence, audit, and validation reporting
59
- };
60
- confidence: number;
61
- reasoning: string;
62
- evidence: string[];
63
- // Capability-focused descriptions (replaces element coverage scoring)
64
- toolCapabilityDescription: string; // What type of tool this is and its role
65
- recommendedUse: string; // How practitioners should use this tool
66
- }
67
-
68
- interface AnalysisResult {
69
- summary: {
70
- totalVendors: number;
71
- safeguardId: string;
72
- safeguardTitle: string;
73
- byCapability: {
74
- full: number; // Count of vendors doing full safeguard
75
- partial: number; // Count of vendors doing partial safeguard
76
- facilitates: number; // Count of vendors facilitating safeguard
77
- governance: number; // Count of vendors providing governance
78
- validates: number; // Count of vendors providing validation
79
- none: number; // Count of vendors with no relevant capability
80
- };
81
- elementCoverage: {
82
- coreRequirements: {
83
- total: number;
84
- coveredByAtLeastOne: number;
85
- };
86
- subTaxonomicalElements: {
87
- total: number;
88
- coveredByAtLeastOne: number;
89
- };
90
- };
91
- };
92
- vendors: VendorAnalysis[];
93
- recommendations: string[];
94
- }
95
-
96
- interface ValidationResult {
97
- vendor: string;
98
- safeguard_id: string;
99
- safeguard_title: string;
100
- claimed_capability: string;
101
- validation_status: 'SUPPORTED' | 'QUESTIONABLE' | 'UNSUPPORTED';
102
- confidence_score: number; // 0-100
103
- actual_capability_detected: string; // What capability the tool actually provides
104
- capability_confidence: number; // Confidence in the detected capability
105
- tool_capability_description: string; // Description of what type of tool this is
106
- recommended_use: string; // How practitioners should use this tool
107
- domain_validation: {
108
- required_tool_type: string;
109
- detected_tool_type: string;
110
- domain_match: boolean;
111
- capability_adjusted: boolean;
112
- original_claim?: string;
113
- };
114
- gaps_identified: string[];
115
- strengths_identified: string[];
116
- recommendations: string[];
117
- detailed_feedback: string;
118
- }
119
-
120
- // Domain-specific validation mapping
121
- const SAFEGUARD_DOMAIN_REQUIREMENTS: Record<string, {
122
- domain: string;
123
- required_tool_types: string[];
124
- description: string;
125
- }> = {
126
- "1.1": {
127
- domain: "Asset Inventory",
128
- required_tool_types: ["inventory", "asset_management", "cmdb", "discovery"],
129
- description: "Only asset inventory and discovery tools can provide FULL/PARTIAL implementation capability"
130
- },
131
- "1.2": {
132
- domain: "Asset Management",
133
- required_tool_types: ["inventory", "asset_management", "network_security", "nac"],
134
- description: "Asset management or network access control tools required for FULL/PARTIAL implementation capability"
135
- },
136
- "5.1": {
137
- domain: "Account Management",
138
- required_tool_types: ["identity_management", "iam", "directory", "account_management"],
139
- description: "Identity and account management tools required for FULL/PARTIAL implementation capability"
140
- },
141
- "6.3": {
142
- domain: "Authentication",
143
- required_tool_types: ["mfa", "authentication", "identity_management", "iam"],
144
- description: "Multi-factor authentication and identity tools required for FULL/PARTIAL implementation capability"
145
- },
146
- "7.1": {
147
- domain: "Vulnerability Management",
148
- required_tool_types: ["vulnerability_management", "vulnerability_scanner", "patch_management"],
149
- description: "Vulnerability management and scanning tools required for FULL/PARTIAL implementation capability"
150
- }
151
- };
152
-
153
- // CIS_SAFEGUARDS removed - data now managed by SafeguardManager class
154
- // Legacy data removed to eliminate duplication and ensure single source of truth
155
-
156
- export class GRCAnalysisServer {
157
- private server: Server;
158
- private safeguardManager: SafeguardManager;
159
-
160
- constructor() {
161
- this.server = new Server(
162
- {
163
- name: 'framework-mcp',
164
- version: '1.0.0',
165
- }
166
- );
167
-
168
- this.safeguardManager = new SafeguardManager();
169
-
170
- this.setupToolHandlers();
171
- }
172
-
173
- private setupToolHandlers() {
174
- this.server.setRequestHandler(ListToolsRequestSchema, async () => ({
175
- tools: [
176
- {
177
- name: 'analyze_vendor_response',
178
- description: 'Analyze a vendor response to determine their tool capability role (Full Implementation, Partial Implementation, Facilitates, Governance, or Validates) for a specific CIS Control safeguard',
179
- inputSchema: {
180
- type: 'object',
181
- properties: {
182
- vendor_name: {
183
- type: 'string',
184
- description: 'Name of the vendor'
185
- },
186
- safeguard_id: {
187
- type: 'string',
188
- description: 'CIS Control safeguard ID (e.g., "5.1", "1.1", "6.3")',
189
- pattern: '^[0-9]+\\.[0-9]+$'
190
- },
191
- response_text: {
192
- type: 'string',
193
- description: 'Vendor response text describing their tool capabilities for the safeguard'
194
- }
195
- },
196
- required: ['vendor_name', 'safeguard_id', 'response_text']
197
- }
198
- } as Tool,
199
- {
200
- name: 'get_safeguard_details',
201
- description: 'Get detailed information about a CIS Control safeguard including governance requirements, core elements, and sub-taxonomical breakdown',
202
- inputSchema: {
203
- type: 'object',
204
- properties: {
205
- safeguard_id: {
206
- type: 'string',
207
- description: 'CIS Control safeguard ID (e.g., "5.1", "1.1")',
208
- pattern: '^[0-9]+\\.[0-9]+$'
209
- },
210
- include_examples: {
211
- type: 'boolean',
212
- description: 'Include implementation examples and suggestions',
213
- default: true
214
- }
215
- },
216
- required: ['safeguard_id']
217
- }
218
- } as Tool,
219
- {
220
- name: 'list_available_safeguards',
221
- description: 'List all available CIS Control safeguards with their categorization',
222
- inputSchema: {
223
- type: 'object',
224
- properties: {
225
- implementation_group: {
226
- type: 'string',
227
- enum: ['IG1', 'IG2', 'IG3'],
228
- description: 'Filter by implementation group (optional)'
229
- },
230
- security_function: {
231
- type: 'string',
232
- enum: ['Identify', 'Protect', 'Detect', 'Respond', 'Recover', 'Govern'],
233
- description: 'Filter by security function (optional)'
234
- }
235
- }
236
- }
237
- } as Tool,
238
- {
239
- name: 'validate_vendor_mapping',
240
- description: 'Validate whether a vendor\'s claimed capability role (Full Implementation/Partial Implementation/Facilitates/Governance/Validates) is actually supported by their supporting evidence for a specific CIS safeguard',
241
- inputSchema: {
242
- type: 'object',
243
- properties: {
244
- vendor_name: {
245
- type: 'string',
246
- description: 'Name of the vendor (optional)',
247
- default: 'Unknown Vendor'
248
- },
249
- safeguard_id: {
250
- type: 'string',
251
- description: 'CIS Control safeguard ID (e.g., "5.1", "1.1", "6.3")',
252
- pattern: '^[0-9]+\\.[0-9]+$'
253
- },
254
- claimed_capability: {
255
- type: 'string',
256
- enum: ['full', 'partial', 'facilitates', 'governance', 'validates'],
257
- description: 'Vendor\'s claimed capability role: full (complete implementation), partial (limited implementation), facilitates (enables/enhances), governance (policies/processes), validates (evidence/reporting)'
258
- },
259
- supporting_text: {
260
- type: 'string',
261
- description: 'Vendor\'s supporting evidence explaining how their tool fulfills the claimed capability role'
262
- }
263
- },
264
- required: ['safeguard_id', 'claimed_capability', 'supporting_text']
265
- }
266
- } as Tool
267
- ],
268
- }));
269
-
270
- this.server.setRequestHandler(CallToolRequestSchema, async (request) => {
271
- const { name, arguments: args } = request.params;
272
- const startTime = Date.now();
273
-
274
- try {
275
- let result;
276
- switch (name) {
277
- case 'analyze_vendor_response':
278
- result = await this.analyzeVendorResponse(args);
279
- break;
280
- case 'get_safeguard_details':
281
- result = await this.getSafeguardDetails(args);
282
- break;
283
- case 'list_available_safeguards':
284
- result = await this.listAvailableSafeguards(args);
285
- break;
286
- case 'validate_vendor_mapping':
287
- result = await this.validateVendorMapping(args);
288
- break;
289
- default:
290
- throw new Error(`Unknown tool: ${name}`);
291
- }
292
-
293
- // Record successful execution time
294
- const executionTime = Date.now() - startTime;
295
- this.recordToolExecution(name, executionTime);
296
-
297
- return result;
298
- } catch (error) {
299
- // Record error and performance metrics
300
- this.performanceMetrics.errorCount++;
301
- const executionTime = Date.now() - startTime;
302
- this.recordToolExecution(`${name}_error`, executionTime);
303
-
304
- const errorMessage = this.formatErrorMessage(error, name);
305
- console.error(`[FrameworkMCP] Tool execution error: ${name}`, error);
306
-
307
- return {
308
- content: [
309
- {
310
- type: 'text',
311
- text: errorMessage,
312
- },
313
- ],
314
- };
315
- }
316
- });
317
- }
318
-
319
- private async getSafeguardDetails(args: any) {
320
- const { safeguard_id, include_examples = true } = args;
321
-
322
- // Input validation
323
- this.validateSafeguardId(safeguard_id);
324
-
325
- // Check cache first
326
- const cached = this.getCachedSafeguardDetails(safeguard_id, include_examples);
327
- if (cached) {
328
- return cached;
329
- }
330
-
331
- const safeguard = this.safeguardManager.getSafeguardDetails(safeguard_id);
332
- if (!safeguard) {
333
- throw new Error(`Safeguard ${safeguard_id} not found`);
334
- }
335
-
336
- const result = {
337
- ...safeguard,
338
- elementBreakdown: {
339
- governanceElements: {
340
- count: safeguard.governanceElements.length,
341
- description: "Orange elements - MUST be met for compliance",
342
- elements: safeguard.governanceElements
343
- },
344
- coreRequirements: {
345
- count: safeguard.coreRequirements.length,
346
- description: "Green elements - The 'what' of the safeguard",
347
- elements: safeguard.coreRequirements
348
- },
349
- subTaxonomicalElements: {
350
- count: safeguard.subTaxonomicalElements.length,
351
- description: "Yellow elements - Detailed sub-taxonomical components",
352
- elements: safeguard.subTaxonomicalElements
353
- },
354
- ...(include_examples && {
355
- implementationSuggestions: {
356
- count: safeguard.implementationSuggestions.length,
357
- description: "Gray elements - Implementation suggestions and methods",
358
- elements: safeguard.implementationSuggestions
359
- }
360
- })
361
- }
362
- };
363
-
364
- const response = {
365
- content: [
366
- {
367
- type: 'text',
368
- text: JSON.stringify(result, null, 2),
369
- },
370
- ],
371
- };
372
-
373
- // Cache the result for future requests
374
- this.setCachedSafeguardDetails(safeguard_id, include_examples, response);
375
-
376
- return response;
377
- }
378
-
379
- private async listAvailableSafeguards(args: any) {
380
- const { implementation_group, security_function } = args;
381
-
382
- // Check cache for complete safeguard list (only if no filters applied)
383
- if (!implementation_group && !security_function && this.cache.safeguardList) {
384
- const cacheAge = Date.now() - this.cache.safeguardList.timestamp;
385
- if (cacheAge < 10 * 60 * 1000) { // 10 minute cache for safeguard list
386
- return this.cache.safeguardList.data;
387
- }
388
- }
389
-
390
- let safeguards = Object.values(this.safeguardManager.getAllSafeguards());
391
-
392
- if (implementation_group) {
393
- safeguards = safeguards.filter(s => s.implementationGroup === implementation_group);
394
- }
395
-
396
- if (security_function) {
397
- safeguards = safeguards.filter(s => s.securityFunction.includes(security_function));
398
- }
399
-
400
- const summary = {
401
- totalSafeguards: safeguards.length,
402
- byImplementationGroup: {
403
- IG1: safeguards.filter(s => s.implementationGroup === 'IG1').length,
404
- IG2: safeguards.filter(s => s.implementationGroup === 'IG2').length,
405
- IG3: safeguards.filter(s => s.implementationGroup === 'IG3').length,
406
- },
407
- safeguards: safeguards.map(s => ({
408
- id: s.id,
409
- title: s.title,
410
- implementationGroup: s.implementationGroup,
411
- assetType: s.assetType,
412
- securityFunction: s.securityFunction
413
- }))
414
- };
415
-
416
- const response = {
417
- content: [
418
- {
419
- type: 'text',
420
- text: JSON.stringify(summary, null, 2),
421
- },
422
- ],
423
- };
424
-
425
- // Cache the complete list if no filters were applied
426
- if (!implementation_group && !security_function) {
427
- this.cache.safeguardList = {
428
- data: response,
429
- timestamp: Date.now()
430
- };
431
- }
432
-
433
- return response;
434
- }
435
-
436
- private async analyzeVendorResponse(args: any) {
437
- const { vendor_name, safeguard_id, response_text } = args;
438
-
439
- // Input validation
440
- this.validateSafeguardId(safeguard_id);
441
- this.validateTextInput(response_text, 'Response text');
442
-
443
- if (!vendor_name || typeof vendor_name !== 'string' || vendor_name.trim().length === 0) {
444
- throw new Error('Vendor name is required');
445
- }
446
-
447
- const safeguard = this.safeguardManager.getSafeguardDetails(safeguard_id);
448
- if (!safeguard) {
449
- throw new Error(`Safeguard ${safeguard_id} not found`);
450
- }
451
-
452
- const analysis = this.performCapabilityAnalysis(vendor_name, safeguard, response_text);
453
-
454
- return {
455
- content: [
456
- {
457
- type: 'text',
458
- text: JSON.stringify(analysis, null, 2),
459
- },
460
- ],
461
- };
462
- }
463
-
464
-
465
- private performCapabilityAnalysis(vendorName: string, safeguard: SafeguardElement, responseText: string): VendorAnalysis {
466
- const text = responseText.toLowerCase();
467
-
468
- // Step 1: Determine what type of capability this tool is claiming
469
- const claimedCapability = this.determineClaimedCapability(text, safeguard);
470
-
471
- // Step 2: Assess how well the tool executes that specific capability type
472
- const qualityAssessment = this.assessCapabilityQuality(text, safeguard, claimedCapability);
473
-
474
- // Step 3: Generate capability-focused analysis
475
- return this.generateCapabilityAnalysis(vendorName, safeguard, responseText, claimedCapability, qualityAssessment);
476
- }
477
-
478
- private determineClaimedCapability(text: string, safeguard: SafeguardElement): 'full' | 'partial' | 'facilitates' | 'governance' | 'validates' {
479
- // Capability detection keywords - focused on what the tool DOES, not what elements it covers
480
- const governanceIndicators = [
481
- 'policy', 'policies', 'manage', 'process', 'workflow', 'governance', 'grc',
482
- 'compliance management', 'documented', 'establish', 'maintain', 'procedure',
483
- 'control', 'controls', 'framework', 'standard', 'enterprise risk management',
484
- 'centralized management', 'oversight'
485
- ];
486
-
487
- const facilitatesIndicators = [
488
- 'improve', 'enhance', 'optimize', 'faster', 'better', 'stronger', 'automate',
489
- 'streamline', 'efficiency', 'facilitate', 'support', 'enable', 'accelerate',
490
- 'api', 'integration', 'data', 'export', 'import', 'sync', 'feed',
491
- 'provides data', 'data source', 'data feeds', 'enrichment', 'data enrichment',
492
- 'supplemental data', 'additional data', 'contextual data', 'threat data',
493
- 'intelligence feeds', 'data aggregation', 'data collection', 'data gathering',
494
- 'feeds data', 'populates', 'informs', 'enriches', 'supplements',
495
- 'enables compliance', 'facilitates implementation', 'supports compliance',
496
- 'creates framework', 'enables organizations', 'infrastructure', 'foundation',
497
- 'template', 'templates', 'workflow automation', 'orchestration'
498
- ];
499
-
500
- const validatesIndicators = [
501
- 'audit', 'report', 'evidence', 'verify', 'validate', 'check', 'monitor',
502
- 'compliance', 'compliance report', 'assessment', 'logging', 'tracking', 'review', 'attest',
503
- 'dashboard', 'metrics', 'analytics', 'visibility', 'alert', 'attestation',
504
- 'compliance tracking', 'audit trail', 'reporting capabilities', 'audit capabilities'
505
- ];
506
-
507
- // Direct implementation indicators (tools that actually perform the safeguard)
508
- const implementationIndicators = this.getImplementationIndicators(safeguard.id);
509
-
510
- // Calculate keyword presence scores
511
- const governanceScore = this.calculateKeywordScore(text, governanceIndicators);
512
- const facilitatesScore = this.calculateKeywordScore(text, facilitatesIndicators);
513
- const validatesScore = this.calculateKeywordScore(text, validatesIndicators);
514
- const implementationScore = this.calculateKeywordScore(text, implementationIndicators);
515
-
516
- // Determine claimed capability based on strongest indicators and patterns
517
- if (implementationScore > 0.2 && implementationScore >= Math.max(facilitatesScore, governanceScore, validatesScore)) {
518
- // Tool claims to directly implement the safeguard
519
- return implementationScore > 0.5 ? 'full' : 'partial';
520
- } else if (governanceScore > 0.2 && governanceScore >= Math.max(facilitatesScore, validatesScore)) {
521
- return 'governance';
522
- } else if (validatesScore > 0.2 && validatesScore >= facilitatesScore) {
523
- return 'validates';
524
- } else {
525
- return 'facilitates';
526
- }
527
- }
528
-
529
- private getImplementationIndicators(safeguardId: string): string[] {
530
- // Return specific indicators for what constitutes direct implementation for each safeguard
531
- const implementationMap: Record<string, string[]> = {
532
- "1.1": ['inventory', 'discovery', 'asset management', 'catalog', 'enumerate', 'scan devices', 'device database'],
533
- "1.2": ['unauthorized', 'rogue', 'detect', 'identify unauthorized', 'quarantine', 'block unauthorized'],
534
- "5.1": ['account inventory', 'user management', 'identity management', 'account lifecycle', 'user provisioning'],
535
- "6.3": ['multi-factor', 'mfa', '2fa', 'authentication', 'two-factor', 'multi-factor authentication'],
536
- "7.1": ['vulnerability', 'vuln', 'scanning', 'vulnerability management', 'security testing', 'penetration testing']
537
- };
538
-
539
- return implementationMap[safeguardId] || [];
540
- }
541
-
542
- private assessCapabilityQuality(text: string, safeguard: SafeguardElement, claimedCapability: string): {
543
- quality: 'excellent' | 'good' | 'fair' | 'poor',
544
- confidence: number,
545
- evidence: string[],
546
- gaps: string[]
547
- } {
548
- // Assess how well the tool executes the claimed capability type
549
- const evidence: string[] = [];
550
- const gaps: string[] = [];
551
-
552
- // Quality assessment based on capability type
553
- let qualityScore = 0;
554
-
555
- switch (claimedCapability) {
556
- case 'full':
557
- case 'partial':
558
- qualityScore = this.assessImplementationQuality(text, safeguard, evidence, gaps);
559
- break;
560
- case 'governance':
561
- qualityScore = this.assessGovernanceQuality(text, safeguard, evidence, gaps);
562
- break;
563
- case 'facilitates':
564
- qualityScore = this.assessFacilitationQuality(text, safeguard, evidence, gaps);
565
- break;
566
- case 'validates':
567
- qualityScore = this.assessValidationQuality(text, safeguard, evidence, gaps);
568
- break;
569
- }
570
-
571
- // Convert score to quality rating
572
- let quality: 'excellent' | 'good' | 'fair' | 'poor';
573
- if (qualityScore >= 0.8) quality = 'excellent';
574
- else if (qualityScore >= 0.6) quality = 'good';
575
- else if (qualityScore >= 0.4) quality = 'fair';
576
- else quality = 'poor';
577
-
578
- return {
579
- quality,
580
- confidence: Math.round(qualityScore * 100),
581
- evidence: evidence.slice(0, 5), // Top 5 pieces of evidence
582
- gaps: gaps.slice(0, 3) // Top 3 gaps identified
583
- };
584
- }
585
-
586
- private assessImplementationQuality(text: string, safeguard: SafeguardElement, evidence: string[], gaps: string[]): number {
587
- // Assess quality of direct implementation capability
588
- const implementationIndicators = this.getImplementationIndicators(safeguard.id);
589
- let score = 0;
590
-
591
- // Check for strong implementation language
592
- const strongIndicators = implementationIndicators.filter(indicator => text.includes(indicator.toLowerCase()));
593
- if (strongIndicators.length > 0) {
594
- score += 0.4;
595
- evidence.push(`Strong implementation indicators: ${strongIndicators.join(', ')}`);
596
- }
597
-
598
- // Check for comprehensive functionality description
599
- if (text.includes('comprehensive') || text.includes('complete') || text.includes('full')) {
600
- score += 0.2;
601
- evidence.push('Claims comprehensive functionality');
602
- }
603
-
604
- // Check for automated vs manual implementation
605
- if (text.includes('automat') || text.includes('real-time') || text.includes('continuous')) {
606
- score += 0.2;
607
- evidence.push('Automated implementation capability');
608
- }
609
-
610
- // Identify potential gaps
611
- if (strongIndicators.length === 0) {
612
- gaps.push('No clear implementation indicators found');
613
- }
614
-
615
- return Math.min(score, 1.0);
616
- }
617
-
618
- private assessGovernanceQuality(text: string, safeguard: SafeguardElement, evidence: string[], gaps: string[]): number {
619
- const governanceIndicators = ['policy', 'process', 'governance', 'compliance', 'documentation', 'oversight'];
620
- let score = 0;
621
-
622
- const foundIndicators = governanceIndicators.filter(indicator => text.includes(indicator));
623
- if (foundIndicators.length >= 3) {
624
- score += 0.5;
625
- evidence.push(`Strong governance capability: ${foundIndicators.join(', ')}`);
626
- }
627
-
628
- if (text.includes('documented') && text.includes('process')) {
629
- score += 0.3;
630
- evidence.push('Documented process management');
631
- }
632
-
633
- return Math.min(score, 1.0);
634
- }
635
-
636
- private assessFacilitationQuality(text: string, safeguard: SafeguardElement, evidence: string[], gaps: string[]): number {
637
- const facilitationIndicators = ['enhance', 'enable', 'support', 'facilitate', 'improve', 'optimize'];
638
- let score = 0;
639
-
640
- const foundIndicators = facilitationIndicators.filter(indicator => text.includes(indicator));
641
- if (foundIndicators.length >= 2) {
642
- score += 0.4;
643
- evidence.push(`Clear facilitation capability: ${foundIndicators.join(', ')}`);
644
- }
645
-
646
- return Math.min(score, 1.0);
647
- }
648
-
649
- private assessValidationQuality(text: string, safeguard: SafeguardElement, evidence: string[], gaps: string[]): number {
650
- const validationIndicators = ['audit', 'report', 'monitor', 'track', 'verify', 'validate'];
651
- let score = 0;
652
-
653
- const foundIndicators = validationIndicators.filter(indicator => text.includes(indicator));
654
- if (foundIndicators.length >= 2) {
655
- score += 0.4;
656
- evidence.push(`Strong validation capability: ${foundIndicators.join(', ')}`);
657
- }
658
-
659
- return Math.min(score, 1.0);
660
- }
661
-
662
- private generateCapabilityAnalysis(vendorName: string, safeguard: SafeguardElement, responseText: string,
663
- claimedCapability: string, qualityAssessment: any): VendorAnalysis {
664
- // Generate the new capability-focused analysis result
665
- return {
666
- vendor: vendorName,
667
- safeguardId: safeguard.id,
668
- safeguardTitle: safeguard.title,
669
- capability: claimedCapability as 'full' | 'partial' | 'facilitates' | 'governance' | 'validates',
670
- capabilities: {
671
- full: claimedCapability === 'full',
672
- partial: claimedCapability === 'partial',
673
- facilitates: claimedCapability === 'facilitates',
674
- governance: claimedCapability === 'governance',
675
- validates: claimedCapability === 'validates'
676
- },
677
- confidence: qualityAssessment.confidence,
678
- reasoning: this.generateCapabilityReasoning(claimedCapability, qualityAssessment, safeguard),
679
- evidence: qualityAssessment.evidence,
680
- // Note: elementsCovered is now less relevant in capability-focused analysis
681
- // We focus on tool capability rather than element coverage
682
- toolCapabilityDescription: this.generateToolCapabilityDescription(claimedCapability, qualityAssessment),
683
- recommendedUse: this.generateRecommendedUse(claimedCapability, safeguard)
684
- };
685
- }
686
-
687
- private generateCapabilityReasoning(claimedCapability: string, qualityAssessment: any, safeguard: SafeguardElement): string {
688
- const capabilityDescriptions = {
689
- full: "directly implements the core functionality of this safeguard",
690
- partial: "implements limited aspects of this safeguard with clear scope boundaries",
691
- facilitates: "enhances or enables the implementation of this safeguard by others",
692
- governance: "provides governance, policy, and oversight capabilities for this safeguard",
693
- validates: "provides evidence, audit, and compliance validation for this safeguard"
694
- };
695
-
696
- const qualityDescriptor = qualityAssessment.quality;
697
- const description = capabilityDescriptions[claimedCapability as keyof typeof capabilityDescriptions];
698
-
699
- return `This tool ${description} with ${qualityDescriptor} capability quality. ${qualityAssessment.evidence.length > 0 ? 'Evidence: ' + qualityAssessment.evidence.join('; ') : ''}`;
700
- }
701
-
702
- private generateToolCapabilityDescription(claimedCapability: string, qualityAssessment: any): string {
703
- const roleDescriptions = {
704
- full: "Core Implementation Tool - Directly performs the safeguard functionality",
705
- partial: "Focused Implementation Tool - Performs specific aspects of the safeguard",
706
- facilitates: "Enablement Tool - Helps organizations implement the safeguard more effectively",
707
- governance: "Governance Tool - Manages policies, processes, and oversight for the safeguard",
708
- validates: "Compliance Tool - Provides audit, evidence, and validation capabilities"
709
- };
710
-
711
- return roleDescriptions[claimedCapability as keyof typeof roleDescriptions] || "Support Tool";
712
- }
713
-
714
- private generateRecommendedUse(claimedCapability: string, safeguard: SafeguardElement): string {
715
- const recommendations = {
716
- full: `Use as primary implementation tool for ${safeguard.title}. Ensure proper configuration and integration.`,
717
- partial: `Use as part of a multi-tool strategy for ${safeguard.title}. Supplement with additional capabilities as needed.`,
718
- facilitates: `Use to enhance existing safeguard implementation. Combine with direct implementation tools.`,
719
- governance: `Use for policy management and governance oversight. Pair with implementation and validation tools.`,
720
- validates: `Use for compliance monitoring and evidence collection. Combine with implementation tools for complete coverage.`
721
- };
722
-
723
- return recommendations[claimedCapability as keyof typeof recommendations] || "Evaluate specific use case alignment.";
724
- }
725
-
726
- private calculateKeywordScore(text: string, keywords: string[]): number {
727
- let matchedKeywords = 0;
728
- let totalMatches = 0;
729
-
730
- keywords.forEach(keyword => {
731
- const regex = new RegExp(keyword.replace(/\s+/g, '\\s+'), 'gi');
732
- const keywordMatches = (text.match(regex) || []).length;
733
- if (keywordMatches > 0) {
734
- matchedKeywords++;
735
- totalMatches += keywordMatches;
736
- }
737
- });
738
-
739
- // Return percentage of keywords that were found, with bonus for multiple matches
740
- const baseScore = matchedKeywords / keywords.length;
741
- const matchBonus = Math.min(totalMatches * 0.1, 0.5); // Up to 50% bonus for multiple matches
742
- return Math.min(baseScore + matchBonus, 1.0);
743
- }
744
-
745
- private analyzeElementCoverage(text: string, elements: string[]): {
746
- percentage: number;
747
- coveredElements: string[];
748
- uncoveredElements: string[];
749
- } {
750
- const coveredElements: string[] = [];
751
- const uncoveredElements: string[] = [];
752
-
753
- elements.forEach(element => {
754
- const elementKeywords = element.toLowerCase().split(/[\s\-\(\)\/]+/).filter(w => w.length > 2);
755
- let elementFound = false;
756
-
757
- // Check for keyword matches
758
- for (const keyword of elementKeywords) {
759
- if (text.includes(keyword)) {
760
- elementFound = true;
761
- break;
762
- }
763
- }
764
-
765
- // Check for semantic matches
766
- if (!elementFound) {
767
- const regex = new RegExp(element.replace(/[()]/g, '').replace(/\s+/g, '\\s*'), 'gi');
768
- if (regex.test(text)) {
769
- elementFound = true;
770
- }
771
- }
772
-
773
- if (elementFound) {
774
- coveredElements.push(element);
775
- } else {
776
- uncoveredElements.push(element);
777
- }
778
- });
779
-
780
- return {
781
- percentage: elements.length > 0 ? (coveredElements.length / elements.length) * 100 : 0,
782
- coveredElements,
783
- uncoveredElements
784
- };
785
- }
786
-
787
- private analyzeBinaryElementCoverage(text: string, elements: string[]): {
788
- coveredElements: string[];
789
- uncoveredElements: string[];
790
- } {
791
- const coveredElements: string[] = [];
792
- const uncoveredElements: string[] = [];
793
-
794
- elements.forEach(element => {
795
- const elementKeywords = element.toLowerCase().split(/[\s\-\(\)\/]+/).filter(w => w.length > 2);
796
- let elementFound = false;
797
-
798
- // Check for keyword matches
799
- for (const keyword of elementKeywords) {
800
- if (text.includes(keyword)) {
801
- elementFound = true;
802
- break;
803
- }
804
- }
805
-
806
- // Check for semantic matches
807
- if (!elementFound) {
808
- const regex = new RegExp(element.replace(/[()]/g, '').replace(/\s+/g, '\\s*'), 'gi');
809
- if (regex.test(text)) {
810
- elementFound = true;
811
- }
812
- }
813
-
814
- if (elementFound) {
815
- coveredElements.push(element);
816
- } else {
817
- uncoveredElements.push(element);
818
- }
819
- });
820
-
821
- return {
822
- coveredElements,
823
- uncoveredElements
824
- };
825
- }
826
-
827
- private extractEnhancedEvidence(text: string, safeguard: SafeguardElement): string[] {
828
- const sentences = text.split(/[.!?]+/).filter(s => s.trim().length > 15);
829
- const evidence: string[] = [];
830
-
831
- // Collect all keywords from all categories
832
- const allKeywords = [
833
- ...safeguard.keywords,
834
- ...safeguard.governanceElements,
835
- ...safeguard.coreRequirements,
836
- ...safeguard.subTaxonomicalElements
837
- ];
838
-
839
- // Extract relevant sentences
840
- allKeywords.forEach(keyword => {
841
- sentences.forEach(sentence => {
842
- const lowerSentence = sentence.toLowerCase();
843
- const lowerKeyword = keyword.toLowerCase();
844
-
845
- if (lowerSentence.includes(lowerKeyword) &&
846
- !evidence.includes(sentence.trim()) &&
847
- evidence.length < 8) {
848
- evidence.push(sentence.trim());
849
- }
850
- });
851
- });
852
-
853
- return evidence;
854
- }
855
-
856
- private generateEnhancedReasoning(
857
- governance: number,
858
- facilitates: number,
859
- validates: number,
860
- coverageBreakdown: any,
861
- safeguard: SafeguardElement
862
- ): string {
863
- const reasons = [];
864
-
865
- // GRC attribute analysis
866
- if (governance > 0.3) reasons.push(`Strong governance capabilities for ${safeguard.title}`);
867
- if (facilitates > 0.3) reasons.push(`Enhancement features that facilitate ${safeguard.id} implementation`);
868
- if (validates > 0.3) reasons.push(`Validation capabilities for ${safeguard.id} compliance verification`);
869
-
870
- // Coverage breakdown analysis
871
- reasons.push(`Coverage breakdown: ${coverageBreakdown.governance}% governance, ${coverageBreakdown.core}% core requirements, ${coverageBreakdown.subElements}% sub-elements`);
872
-
873
- if (coverageBreakdown.governance < 50) {
874
- reasons.push(`Limited governance element coverage may impact compliance`);
875
- }
876
-
877
- if (coverageBreakdown.core < 50) {
878
- reasons.push(`Core requirements coverage needs improvement`);
879
- }
880
-
881
- return reasons.join('. ');
882
- }
883
-
884
-
885
- private validateClaim(claim: string, analysis: VendorAnalysis, capabilities: string[], safeguard: SafeguardElement) {
886
- const validation = {
887
- coverageClaimValid: false,
888
- capabilityClaimsValid: {} as Record<string, boolean>,
889
- gaps: [] as string[],
890
- recommendations: [] as string[]
891
- };
892
-
893
- // Validate coverage claims
894
- if (claim === 'FULL') {
895
- const meetsFullCriteria = analysis.capabilities.full;
896
- validation.coverageClaimValid = meetsFullCriteria;
897
-
898
- if (!meetsFullCriteria) {
899
- validation.gaps.push(`FULL implementation capability claim not supported: Tool does not demonstrate direct implementation of core safeguard functionality`);
900
- }
901
- } else if (claim === 'PARTIAL') {
902
- const meetsPartialCriteria = analysis.capabilities.partial || analysis.capabilities.full;
903
- validation.coverageClaimValid = meetsPartialCriteria;
904
-
905
- if (!meetsPartialCriteria) {
906
- validation.gaps.push(`PARTIAL implementation capability claim questionable: No core or sub-taxonomical elements clearly addressed`);
907
- }
908
- }
909
-
910
- // Validate capability claims
911
- capabilities.forEach(capability => {
912
- switch (capability.toLowerCase()) {
913
- case 'governance':
914
- validation.capabilityClaimsValid[capability] = analysis.capabilities.governance;
915
- if (!analysis.capabilities.governance) {
916
- validation.gaps.push(`Governance capability not evidenced in response`);
917
- }
918
- break;
919
- case 'facilitates':
920
- validation.capabilityClaimsValid[capability] = analysis.capabilities.facilitates;
921
- if (!analysis.capabilities.facilitates) {
922
- validation.gaps.push(`Facilitates capability not evidenced in response`);
923
- }
924
- break;
925
- case 'validates':
926
- validation.capabilityClaimsValid[capability] = analysis.capabilities.validates;
927
- if (!analysis.capabilities.validates) {
928
- validation.gaps.push(`Validates capability not evidenced in response`);
929
- }
930
- break;
931
- case 'full':
932
- validation.capabilityClaimsValid[capability] = analysis.capabilities.full;
933
- if (!analysis.capabilities.full) {
934
- validation.gaps.push(`Full coverage capability not evidenced in response`);
935
- }
936
- break;
937
- case 'partial':
938
- validation.capabilityClaimsValid[capability] = analysis.capabilities.partial;
939
- if (!analysis.capabilities.partial) {
940
- validation.gaps.push(`Partial coverage capability not evidenced in response`);
941
- }
942
- break;
943
- }
944
- });
945
-
946
- // Generate recommendations
947
- if (validation.gaps.length === 0) {
948
- validation.recommendations.push(`Claims appear to be well-supported by the vendor response`);
949
- } else {
950
- validation.recommendations.push(`Consider requesting additional information about: ${validation.gaps.join(', ')}`);
951
-
952
- // Capability-based recommendations
953
- if (analysis.capability === 'facilitates') {
954
- validation.recommendations.push('Consider pairing with direct implementation tools for complete safeguard coverage');
955
- } else if (analysis.capability === 'partial') {
956
- validation.recommendations.push('Evaluate scope limitations and identify complementary tools for full coverage');
957
- } else if (analysis.capability === 'governance') {
958
- validation.recommendations.push('Combine with technical implementation tools for complete safeguard execution');
959
- } else if (analysis.capability === 'validates') {
960
- validation.recommendations.push('Pair with implementation tools to ensure both execution and validation coverage');
961
- }
962
-
963
- if (!analysis.capabilities.validates && capabilities.includes('Validates')) {
964
- validation.recommendations.push(`Request examples of audit trails, reporting capabilities, and compliance evidence`);
965
- }
966
- }
967
-
968
- return validation;
969
- }
970
-
971
- private async validateVendorMapping(args: any) {
972
- const { vendor_name = 'Unknown Vendor', safeguard_id, claimed_capability, supporting_text } = args;
973
-
974
- // Input validation
975
- this.validateSafeguardId(safeguard_id);
976
- this.validateTextInput(supporting_text, 'Supporting text');
977
- this.validateCapability(claimed_capability);
978
-
979
- const safeguard = this.safeguardManager.getSafeguardDetails(safeguard_id);
980
- if (!safeguard) {
981
- throw new Error(`Safeguard ${safeguard_id} not found`);
982
- }
983
-
984
- const validation = this.validateCapabilityClaim(
985
- vendor_name,
986
- safeguard,
987
- claimed_capability,
988
- supporting_text
989
- );
990
-
991
- return {
992
- content: [
993
- {
994
- type: 'text',
995
- text: JSON.stringify(validation, null, 2),
996
- },
997
- ],
998
- };
999
- }
1000
-
1001
- private validateCapabilityClaim(
1002
- vendorName: string,
1003
- safeguard: SafeguardElement,
1004
- claimedCapability: string,
1005
- supportingText: string
1006
- ): ValidationResult {
1007
- const text = supportingText.toLowerCase();
1008
-
1009
- // Detect tool type and validate domain match
1010
- const detectedToolType = this.detectToolType(supportingText, safeguard.id);
1011
- const domainValidation = this.validateDomainMatch(safeguard.id, claimedCapability, detectedToolType);
1012
-
1013
- // Adjust capability if domain mismatch detected
1014
- let effectiveCapability = claimedCapability;
1015
- let originalClaim: string | undefined;
1016
-
1017
- if (domainValidation.should_adjust_capability) {
1018
- originalClaim = claimedCapability;
1019
- effectiveCapability = domainValidation.adjusted_capability!;
1020
- }
1021
-
1022
- // Perform capability-focused analysis of the supporting text
1023
- const actualAnalysis = this.performCapabilityAnalysis(vendorName, safeguard, supportingText);
1024
-
1025
- // Validate claimed capability against actual capability analysis and domain requirements
1026
- const validation = this.assessCapabilityClaimAlignment(
1027
- claimedCapability,
1028
- effectiveCapability,
1029
- actualAnalysis,
1030
- domainValidation,
1031
- text
1032
- );
1033
-
1034
- // Add domain validation gaps if capability was adjusted
1035
- if (domainValidation.should_adjust_capability) {
1036
- validation.gaps.unshift(`Domain mismatch: ${domainValidation.reasoning}`);
1037
- validation.recommendations.unshift(`Correct capability mapping should be '${effectiveCapability.toUpperCase()}' for ${detectedToolType} tools`);
1038
- // Reduce confidence for domain mismatches
1039
- validation.confidence = Math.max(validation.confidence - 20, 0);
1040
- }
1041
-
1042
- return {
1043
- vendor: vendorName,
1044
- safeguard_id: safeguard.id,
1045
- safeguard_title: safeguard.title,
1046
- claimed_capability: claimedCapability,
1047
- validation_status: validation.status,
1048
- confidence_score: validation.confidence,
1049
- actual_capability_detected: actualAnalysis.capability,
1050
- capability_confidence: actualAnalysis.confidence,
1051
- tool_capability_description: actualAnalysis.toolCapabilityDescription,
1052
- recommended_use: actualAnalysis.recommendedUse,
1053
- domain_validation: {
1054
- required_tool_type: domainValidation.required_tool_types.join('/'),
1055
- detected_tool_type: detectedToolType,
1056
- domain_match: domainValidation.domain_match,
1057
- capability_adjusted: domainValidation.should_adjust_capability,
1058
- original_claim: originalClaim
1059
- },
1060
- gaps_identified: validation.gaps,
1061
- strengths_identified: validation.strengths,
1062
- recommendations: validation.recommendations,
1063
- detailed_feedback: validation.feedback
1064
- };
1065
- }
1066
-
1067
- private assessCapabilityClaimAlignment(
1068
- claimedCapability: string,
1069
- effectiveCapability: string,
1070
- actualAnalysis: VendorAnalysis,
1071
- domainValidation: any,
1072
- text: string
1073
- ): {
1074
- status: 'SUPPORTED' | 'QUESTIONABLE' | 'UNSUPPORTED';
1075
- confidence: number;
1076
- gaps: string[];
1077
- strengths: string[];
1078
- recommendations: string[];
1079
- feedback: string;
1080
- } {
1081
- const gaps: string[] = [];
1082
- const strengths: string[] = [];
1083
- const recommendations: string[] = [];
1084
-
1085
- // Compare claimed capability with what we actually detected
1086
- const claimedLower = claimedCapability.toLowerCase();
1087
- const effectiveLower = effectiveCapability.toLowerCase();
1088
- const actualCapability = actualAnalysis.capability;
1089
-
1090
- let alignmentScore = 0;
1091
-
1092
- // Check if claim aligns with actual analysis
1093
- if (claimedLower === actualCapability) {
1094
- alignmentScore = actualAnalysis.confidence;
1095
- strengths.push(`Claimed capability '${claimedCapability}' aligns with detected capability`);
1096
- strengths.push(`Tool demonstrates appropriate ${actualAnalysis.toolCapabilityDescription.toLowerCase()}`);
1097
- } else if (effectiveLower === actualCapability) {
1098
- // Domain validation adjusted the capability and it matches the analysis
1099
- alignmentScore = Math.max(actualAnalysis.confidence - 20, 30);
1100
- gaps.push(`Original claim '${claimedCapability}' doesn't match tool type, adjusted to '${effectiveCapability}'`);
1101
- strengths.push(`Adjusted capability '${effectiveCapability}' aligns with tool analysis`);
1102
- } else {
1103
- // Neither claimed nor effective capability matches the analysis
1104
- alignmentScore = Math.max(actualAnalysis.confidence - 40, 10);
1105
- gaps.push(`Claimed capability '${claimedCapability}' doesn't align with detected capability '${actualCapability}'`);
1106
- gaps.push(`Tool appears to be: ${actualAnalysis.toolCapabilityDescription}`);
1107
- }
1108
-
1109
- // Add evidence from the capability analysis
1110
- if (actualAnalysis.evidence && actualAnalysis.evidence.length > 0) {
1111
- strengths.push(`Supporting evidence: ${actualAnalysis.evidence.slice(0, 2).join('; ')}`);
1112
- }
1113
-
1114
- // Domain validation feedback
1115
- if (!domainValidation.domain_match) {
1116
- gaps.push(`Tool type '${domainValidation.detected_tool_type}' not appropriate for this safeguard domain`);
1117
- }
1118
-
1119
- // Determine overall status based on alignment score
1120
- let status: 'SUPPORTED' | 'QUESTIONABLE' | 'UNSUPPORTED';
1121
- if (alignmentScore >= 70) {
1122
- status = 'SUPPORTED';
1123
- } else if (alignmentScore >= 40) {
1124
- status = 'QUESTIONABLE';
1125
- } else {
1126
- status = 'UNSUPPORTED';
1127
- }
1128
-
1129
- // Generate capability-focused recommendations
1130
- recommendations.push(actualAnalysis.recommendedUse);
1131
-
1132
- if (status === 'QUESTIONABLE') {
1133
- recommendations.push('Consider clarifying tool capabilities or adjusting capability claim');
1134
- }
1135
-
1136
- if (!domainValidation.domain_match) {
1137
- recommendations.push(`For ${actualCapability.toUpperCase()} capability, focus on how the tool ${actualCapability === 'facilitates' ? 'enables and enhances' : actualCapability === 'governance' ? 'manages policies and processes for' : actualCapability === 'validates' ? 'provides evidence and reporting on' : 'directly implements'} this safeguard`);
1138
- }
1139
-
1140
- const feedback = this.generateCapabilityValidationFeedback(claimedCapability, effectiveCapability, actualCapability, status, alignmentScore, domainValidation);
1141
-
1142
- return {
1143
- status,
1144
- confidence: Math.round(alignmentScore),
1145
- gaps,
1146
- strengths,
1147
- recommendations,
1148
- feedback
1149
- };
1150
- }
1151
-
1152
- private hasFacilitationLanguage(text: string): boolean {
1153
- const facilitationPatterns = [
1154
- 'enables', 'facilitates', 'supports', 'helps', 'provides framework',
1155
- 'creates infrastructure', 'enables organizations', 'supports compliance',
1156
- 'provides data', 'enriches', 'supplements', 'feeds data'
1157
- ];
1158
- return facilitationPatterns.some(pattern => text.includes(pattern));
1159
- }
1160
-
1161
- private hasScopeBoundaries(text: string): boolean {
1162
- const boundaryPatterns = [
1163
- 'covers', 'but not', 'limited to', 'specifically', 'only', 'excludes',
1164
- 'scope includes', 'scope excludes', 'within', 'applies to'
1165
- ];
1166
- return boundaryPatterns.some(pattern => text.includes(pattern));
1167
- }
1168
-
1169
- private hasDirectImplementationLanguage(text: string): boolean {
1170
- const implementationPatterns = [
1171
- 'directly implements', 'performs', 'executes', 'scans', 'catalogs',
1172
- 'inventories', 'manages assets', 'controls access', 'blocks threats'
1173
- ];
1174
- return implementationPatterns.some(pattern => text.includes(pattern));
1175
- }
1176
-
1177
- private assessImplementationLanguage(text: string): number {
1178
- const implementationKeywords = [
1179
- 'implements', 'performs', 'executes', 'manages', 'controls', 'maintains',
1180
- 'establishes', 'configures', 'monitors', 'tracks', 'inventories'
1181
- ];
1182
- return this.calculateKeywordScore(text, implementationKeywords) * 100;
1183
- }
1184
-
1185
- private assessFacilitationLanguage(text: string): number {
1186
- const facilitationKeywords = [
1187
- 'enables', 'facilitates', 'supports', 'helps', 'enhances', 'improves',
1188
- 'streamlines', 'automates', 'optimizes', 'provides framework'
1189
- ];
1190
- return this.calculateKeywordScore(text, facilitationKeywords) * 100;
1191
- }
1192
-
1193
- private assessGovernanceLanguage(text: string): number {
1194
- const governanceKeywords = [
1195
- 'policy', 'governance', 'compliance', 'oversight', 'management',
1196
- 'framework', 'procedures', 'processes', 'controls', 'standards'
1197
- ];
1198
- return this.calculateKeywordScore(text, governanceKeywords) * 100;
1199
- }
1200
-
1201
- private assessValidationLanguage(text: string): number {
1202
- const validationKeywords = [
1203
- 'audit', 'validate', 'verify', 'report', 'evidence', 'monitor',
1204
- 'assess', 'check', 'review', 'attest', 'compliance', 'compliance tracking',
1205
- 'compliance reports', 'audit capabilities', 'audit trail', 'reporting capabilities'
1206
- ];
1207
- return this.calculateKeywordScore(text, validationKeywords) * 100;
1208
- }
1209
-
1210
- private detectToolType(text: string, safeguardId?: string): string {
1211
- const lowerText = text.toLowerCase();
1212
-
1213
- // Enhanced keyword definitions with scoring weights and context
1214
- const toolTypePatterns = {
1215
- 'inventory': {
1216
- primary: [
1217
- 'asset management', 'inventory management', 'cmdb', 'configuration management database',
1218
- 'asset discovery', 'hardware inventory', 'software inventory', 'device inventory',
1219
- 'asset tracking', 'it asset management', 'endpoint discovery', 'asset lifecycle'
1220
- ],
1221
- secondary: [
1222
- 'inventory', 'discovery', 'device management', 'endpoint management',
1223
- 'configuration management', 'asset database', 'equipment tracking'
1224
- ],
1225
- weight: { primary: 3, secondary: 1 }
1226
- },
1227
- 'identity_management': {
1228
- primary: [
1229
- 'identity management', 'iam', 'active directory', 'identity provider',
1230
- 'single sign-on', 'sso', 'multi-factor authentication', 'mfa',
1231
- 'user management', 'account management', 'directory service'
1232
- ],
1233
- secondary: [
1234
- 'ldap', 'authentication', 'access management', 'identity access management',
1235
- 'user directory', 'account lifecycle', 'privileged access'
1236
- ],
1237
- weight: { primary: 3, secondary: 1 }
1238
- },
1239
- 'vulnerability_management': {
1240
- primary: [
1241
- 'vulnerability management', 'vulnerability scanner', 'patch management',
1242
- 'security scanning', 'vulnerability assessment', 'penetration testing'
1243
- ],
1244
- secondary: [
1245
- 'vuln scan', 'security scanner', 'network scanner', 'scanning capabilities',
1246
- 'security assessment', 'vulnerability scanning', 'patch deployment'
1247
- ],
1248
- weight: { primary: 3, secondary: 1 }
1249
- },
1250
- 'threat_intelligence': {
1251
- primary: [
1252
- 'threat intelligence', 'cyber threat intelligence', 'threat intel',
1253
- 'threat feed', 'ioc feed', 'security intelligence', 'threat data'
1254
- ],
1255
- secondary: [
1256
- 'enrichment', 'data feed', 'contextual data', 'risk intelligence',
1257
- 'threat indicators', 'intelligence platform', 'threat correlation'
1258
- ],
1259
- weight: { primary: 3, secondary: 1 }
1260
- },
1261
- 'network_security': {
1262
- primary: [
1263
- 'firewall', 'network access control', 'nac', 'intrusion detection',
1264
- 'network security', 'network segmentation'
1265
- ],
1266
- secondary: [
1267
- 'network monitoring', 'traffic analysis', 'perimeter security',
1268
- 'network protection', 'network filtering'
1269
- ],
1270
- weight: { primary: 3, secondary: 1 }
1271
- },
1272
- 'governance': {
1273
- primary: [
1274
- 'grc', 'governance risk compliance', 'compliance management',
1275
- 'policy management', 'risk management', 'audit management'
1276
- ],
1277
- secondary: [
1278
- 'governance', 'compliance platform', 'policy enforcement',
1279
- 'regulatory compliance', 'framework management'
1280
- ],
1281
- weight: { primary: 3, secondary: 1 }
1282
- },
1283
- 'security_analytics': {
1284
- primary: [
1285
- 'siem', 'security information event management', 'security analytics',
1286
- 'soar', 'security orchestration', 'log management'
1287
- ],
1288
- secondary: [
1289
- 'security monitoring', 'event correlation', 'log analysis',
1290
- 'security intelligence', 'incident response platform'
1291
- ],
1292
- weight: { primary: 3, secondary: 1 }
1293
- }
1294
- };
1295
-
1296
- // Calculate scores for each tool type
1297
- const toolScores: Record<string, number> = {};
1298
-
1299
- for (const [toolType, patterns] of Object.entries(toolTypePatterns)) {
1300
- let score = 0;
1301
-
1302
- // Check primary keywords
1303
- for (const keyword of patterns.primary) {
1304
- if (lowerText.includes(keyword)) {
1305
- score += patterns.weight.primary;
1306
- }
1307
- }
1308
-
1309
- // Check secondary keywords
1310
- for (const keyword of patterns.secondary) {
1311
- if (lowerText.includes(keyword)) {
1312
- score += patterns.weight.secondary;
1313
- }
1314
- }
1315
-
1316
- toolScores[toolType] = score;
1317
- }
1318
-
1319
- // Apply safeguard-specific context weighting if provided
1320
- if (safeguardId && toolScores) {
1321
- const contextBonus = 1; // Small bonus for domain alignment
1322
-
1323
- // Asset inventory safeguards (1.1, 1.2) favor inventory tools
1324
- if (['1.1', '1.2'].includes(safeguardId) && toolScores['inventory'] > 0) {
1325
- toolScores['inventory'] += contextBonus;
1326
- }
1327
-
1328
- // Account inventory safeguards (5.1, 5.2, 5.3) favor identity tools
1329
- if (['5.1', '5.2', '5.3'].includes(safeguardId) && toolScores['identity_management'] > 0) {
1330
- toolScores['identity_management'] += contextBonus;
1331
- }
1332
-
1333
- // Authentication safeguards (6.1, 6.2, 6.3) favor identity tools
1334
- if (['6.1', '6.2', '6.3'].includes(safeguardId) && toolScores['identity_management'] > 0) {
1335
- toolScores['identity_management'] += contextBonus;
1336
- }
1337
-
1338
- // Vulnerability safeguards (7.1-7.7) favor vulnerability management tools
1339
- if (['7.1', '7.2', '7.3', '7.4', '7.5', '7.6', '7.7'].includes(safeguardId) && toolScores['vulnerability_management'] > 0) {
1340
- toolScores['vulnerability_management'] += contextBonus;
1341
- }
1342
- }
1343
-
1344
- // Find the tool type with highest score
1345
- let maxScore = 0;
1346
- let detectedType = 'unknown';
1347
-
1348
- for (const [toolType, score] of Object.entries(toolScores)) {
1349
- if (score > maxScore) {
1350
- maxScore = score;
1351
- detectedType = toolType;
1352
- }
1353
- }
1354
-
1355
- // Require minimum score threshold to avoid false positives
1356
- return maxScore >= 2 ? detectedType : 'unknown';
1357
- }
1358
-
1359
- private validateDomainMatch(
1360
- safeguardId: string,
1361
- claimedCapability: string,
1362
- detectedToolType: string
1363
- ): {
1364
- domain_match: boolean;
1365
- required_tool_types: string[];
1366
- should_adjust_capability: boolean;
1367
- adjusted_capability?: string;
1368
- reasoning: string;
1369
- } {
1370
- const domainReq = SAFEGUARD_DOMAIN_REQUIREMENTS[safeguardId];
1371
-
1372
- if (!domainReq) {
1373
- return {
1374
- domain_match: true,
1375
- required_tool_types: [],
1376
- should_adjust_capability: false,
1377
- reasoning: 'No domain restrictions defined for this safeguard'
1378
- };
1379
- }
1380
-
1381
- const isFullOrPartial = ['full', 'partial'].includes(claimedCapability.toLowerCase());
1382
- const toolTypeMatches = domainReq.required_tool_types.includes(detectedToolType);
1383
-
1384
- if (isFullOrPartial && !toolTypeMatches) {
1385
- return {
1386
- domain_match: false,
1387
- required_tool_types: domainReq.required_tool_types,
1388
- should_adjust_capability: true,
1389
- adjusted_capability: 'facilitates',
1390
- reasoning: `${domainReq.domain} safeguard requires ${domainReq.required_tool_types.join('/')} tool types for FULL/PARTIAL implementation capability. Detected tool type '${detectedToolType}' can only facilitate implementation.`
1391
- };
1392
- }
1393
-
1394
- return {
1395
- domain_match: true,
1396
- required_tool_types: domainReq.required_tool_types,
1397
- should_adjust_capability: false,
1398
- reasoning: toolTypeMatches ?
1399
- `Tool type '${detectedToolType}' is appropriate for ${domainReq.domain} safeguard` :
1400
- 'No domain validation required for this capability type'
1401
- };
1402
- }
1403
-
1404
- private generateCapabilityValidationFeedback(
1405
- claimedCapability: string,
1406
- effectiveCapability: string,
1407
- actualCapability: string,
1408
- status: string,
1409
- score: number,
1410
- domainValidation: any
1411
- ): string {
1412
- let feedback = `Capability Validation: ${claimedCapability.toUpperCase()} claim is ${status} (${Math.round(score)}% confidence)\n\n`;
1413
-
1414
- // Analysis summary
1415
- feedback += `ANALYSIS:\n`;
1416
- feedback += `• Claimed: ${claimedCapability.toUpperCase()}\n`;
1417
- if (effectiveCapability !== claimedCapability) {
1418
- feedback += `• Domain Adjusted: ${effectiveCapability.toUpperCase()} (${domainValidation.reasoning})\n`;
1419
- }
1420
- feedback += `• Detected: ${actualCapability.toUpperCase()}\n`;
1421
- feedback += `• Tool Type: ${domainValidation.detected_tool_type}\n\n`;
1422
-
1423
- // Assessment
1424
- feedback += `ASSESSMENT: `;
1425
- if (claimedCapability.toLowerCase() === actualCapability) {
1426
- feedback += 'Claimed capability aligns perfectly with tool analysis.';
1427
- } else if (effectiveCapability.toLowerCase() === actualCapability) {
1428
- feedback += 'After domain validation adjustment, capability aligns with tool analysis.';
1429
- } else {
1430
- feedback += `Capability mismatch detected. Tool functions as ${actualCapability.toUpperCase()} rather than claimed ${claimedCapability.toUpperCase()}.`;
1431
- }
1432
-
1433
- return feedback;
1434
- }
1435
-
1436
- private generateValidationFeedback(
1437
- claimedCapability: string,
1438
- status: string,
1439
- gaps: string[],
1440
- strengths: string[],
1441
- score: number
1442
- ): string {
1443
- let feedback = `Validation of ${claimedCapability.toUpperCase()} capability role claim: ${status} (${Math.round(score)}% alignment)\n\n`;
1444
-
1445
- if (strengths.length > 0) {
1446
- feedback += `STRENGTHS:\n${strengths.map(s => `• ${s}`).join('\n')}\n\n`;
1447
- }
1448
-
1449
- if (gaps.length > 0) {
1450
- feedback += `GAPS IDENTIFIED:\n${gaps.map(g => `• ${g}`).join('\n')}\n\n`;
1451
- }
1452
-
1453
- feedback += `ASSESSMENT: `;
1454
- switch (status) {
1455
- case 'SUPPORTED':
1456
- feedback += 'The vendor\'s supporting evidence strongly aligns with their claimed capability role.';
1457
- break;
1458
- case 'QUESTIONABLE':
1459
- feedback += 'The vendor\'s evidence partially supports their claim but has notable gaps or inconsistencies.';
1460
- break;
1461
- case 'UNSUPPORTED':
1462
- feedback += 'The vendor\'s evidence does not adequately support their claimed capability role.';
1463
- break;
1464
- }
1465
-
1466
- return feedback;
1467
- }
1468
-
1469
- // Enhanced error handling and formatting
1470
- private formatErrorMessage(error: unknown, toolName: string): string {
1471
- if (error instanceof Error) {
1472
- // Production-friendly error messages
1473
- switch (error.message) {
1474
- case /^Safeguard .+ not found/.test(error.message) ? error.message : '':
1475
- return `❌ Invalid safeguard ID. Use 'list_available_safeguards' to see available CIS Control safeguards.`;
1476
- case /^Unknown tool/.test(error.message) ? error.message : '':
1477
- return `❌ Tool '${toolName}' is not available. Available tools: analyze_vendor_response, validate_vendor_mapping, get_safeguard_details, list_available_safeguards.`;
1478
- default:
1479
- return `❌ Error in ${toolName}: ${error.message}`;
1480
- }
1481
- }
1482
- return `❌ Unexpected error in ${toolName}: ${String(error)}`;
1483
- }
1484
-
1485
- // Performance monitoring and caching
1486
- private performanceMetrics = {
1487
- toolExecutionTimes: new Map<string, number[]>(),
1488
- startTime: Date.now(),
1489
- totalRequests: 0,
1490
- errorCount: 0
1491
- };
1492
-
1493
- // Simple cache for safeguard details (most commonly requested data)
1494
- private cache = {
1495
- safeguardDetails: new Map<string, any>(),
1496
- safeguardList: null as any,
1497
- lastCacheCleanup: Date.now()
1498
- };
1499
-
1500
- private getCachedSafeguardDetails(safeguardId: string, includeExamples: boolean): any | null {
1501
- const cacheKey = `${safeguardId}_${includeExamples}`;
1502
- const cached = this.cache.safeguardDetails.get(cacheKey);
1503
-
1504
- if (cached && (Date.now() - cached.timestamp < 5 * 60 * 1000)) { // 5 minute cache
1505
- return cached.data;
1506
- }
1507
-
1508
- return null;
1509
- }
1510
-
1511
- private setCachedSafeguardDetails(safeguardId: string, includeExamples: boolean, data: any): void {
1512
- const cacheKey = `${safeguardId}_${includeExamples}`;
1513
- this.cache.safeguardDetails.set(cacheKey, {
1514
- data,
1515
- timestamp: Date.now()
1516
- });
1517
-
1518
- // Periodic cache cleanup to prevent memory leaks
1519
- if (Date.now() - this.cache.lastCacheCleanup > 10 * 60 * 1000) { // 10 minutes
1520
- this.cleanupCache();
1521
- }
1522
- }
1523
-
1524
- private cleanupCache(): void {
1525
- const now = Date.now();
1526
- const maxAge = 10 * 60 * 1000; // 10 minutes
1527
-
1528
- // Clean up safeguard details cache
1529
- for (const [key, value] of this.cache.safeguardDetails.entries()) {
1530
- if (now - value.timestamp > maxAge) {
1531
- this.cache.safeguardDetails.delete(key);
1532
- }
1533
- }
1534
-
1535
- this.cache.lastCacheCleanup = now;
1536
- }
1537
-
1538
- private recordToolExecution(toolName: string, executionTime: number) {
1539
- this.performanceMetrics.totalRequests++;
1540
-
1541
- if (!this.performanceMetrics.toolExecutionTimes.has(toolName)) {
1542
- this.performanceMetrics.toolExecutionTimes.set(toolName, []);
1543
- }
1544
-
1545
- const times = this.performanceMetrics.toolExecutionTimes.get(toolName)!;
1546
- times.push(executionTime);
1547
-
1548
- // Keep only last 100 measurements for memory efficiency
1549
- if (times.length > 100) {
1550
- times.shift();
1551
- }
1552
- }
1553
-
1554
- private getPerformanceStats(): string {
1555
- const uptime = Date.now() - this.performanceMetrics.startTime;
1556
- const avgTimes = Array.from(this.performanceMetrics.toolExecutionTimes.entries())
1557
- .map(([tool, times]) => {
1558
- const avg = times.reduce((a, b) => a + b, 0) / times.length;
1559
- return `${tool}: ${avg.toFixed(2)}ms`;
1560
- });
1561
-
1562
- return `Performance Stats (Uptime: ${(uptime / 1000).toFixed(1)}s, Requests: ${this.performanceMetrics.totalRequests}, Errors: ${this.performanceMetrics.errorCount})\n${avgTimes.join(', ')}`;
1563
- }
1564
-
1565
- // Input validation and sanitization
1566
- private validateSafeguardId(safeguardId: string): void {
1567
- if (!safeguardId || typeof safeguardId !== 'string') {
1568
- throw new Error('Safeguard ID is required and must be a string');
1569
- }
1570
-
1571
- if (!/^[0-9]+\.[0-9]+$/.test(safeguardId)) {
1572
- throw new Error('Safeguard ID must be in format "X.Y" (e.g., "1.1", "5.1")');
1573
- }
1574
-
1575
- if (!this.safeguardManager.getSafeguardDetails(safeguardId)) {
1576
- throw new Error(`Safeguard ${safeguardId} not found`);
1577
- }
1578
- }
1579
-
1580
- private validateTextInput(text: string, fieldName: string): void {
1581
- if (!text || typeof text !== 'string') {
1582
- throw new Error(`${fieldName} is required and must be a string`);
1583
- }
1584
-
1585
- if (text.length > 10000) {
1586
- throw new Error(`${fieldName} must be less than 10,000 characters`);
1587
- }
1588
-
1589
- if (text.trim().length < 10) {
1590
- throw new Error(`${fieldName} must contain at least 10 meaningful characters`);
1591
- }
1592
- }
1593
-
1594
- private validateCapability(capability: string): void {
1595
- const validCapabilities = ['full', 'partial', 'facilitates', 'governance', 'validates'];
1596
- if (!validCapabilities.includes(capability.toLowerCase())) {
1597
- throw new Error(`Invalid capability. Must be one of: ${validCapabilities.join(', ')}`);
1598
- }
1599
- }
1600
-
1601
- async run() {
1602
- const transport = new StdioServerTransport();
1603
- await this.server.connect(transport);
1604
- console.error('FrameworkMCP server running on stdio');
1605
-
1606
- // Log performance stats every 5 minutes in production
1607
- if (process.env.NODE_ENV === 'production') {
1608
- setInterval(() => {
1609
- console.error(`[FrameworkMCP] ${this.getPerformanceStats()}`);
1610
- }, 5 * 60 * 1000);
1611
- }
1612
- }
1613
- }
1614
-
1615
- const server = new GRCAnalysisServer();
1616
- server.run().catch(console.error);