All files / src/tools/generateReport index.ts

100% Statements 9/9
50% Branches 1/2
100% Functions 1/1
100% Lines 9/9

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140                                                                                4x                                                                                       16x   16x   16x 16x     11x               2x 2x             4x                                                              
/**
 * MCP Tool: generate_report
 * 
 * Generate analytical reports on European Parliament data
 * 
 * **Intelligence Perspective:** Produces structured intelligence products including MEP
 * activity scorecards, committee effectiveness assessments, voting pattern reports, and
 * legislative progress tracking aligned with intelligence analysis best practices.
 * 
 * **Business Perspective:** Premium report generation capability enabling consulting
 * deliverables, automated briefings, and white-label reporting for enterprise customers.
 * 
 * **Marketing Perspective:** Flagship feature demonstrating automated parliamentary
 * intelligence—key for content marketing, case studies, and product demonstrations.
 * 
 * ISMS Policy: SC-002 (Input Validation), AC-003 (Least Privilege)
 */
 
import type { z } from 'zod';
import { GenerateReportSchema } from '../../schemas/europeanParliament.js';
import {
  generateMEPActivityReport,
  generateCommitteePerformanceReport,
  generateVotingStatisticsReport,
  generateLegislationProgressReport
} from './reportGenerators.js';
import type { Report, ReportType } from './types.js';
import type { ToolResult } from '../shared/types.js';
 
/**
 * Report parameters type inferred from schema
 */
type ReportParams = z.infer<typeof GenerateReportSchema>;
 
/**
 * Report generator map for O(1) lookup
 */
const reportGenerators: Record<
  ReportType,
  (params: ReportParams) => Promise<Report>
> = {
  MEP_ACTIVITY: generateMEPActivityReport,
  COMMITTEE_PERFORMANCE: generateCommitteePerformanceReport,
  VOTING_STATISTICS: generateVotingStatisticsReport,
  LEGISLATION_PROGRESS: generateLegislationProgressReport
};
 
/**
 * Handles the generate_report MCP tool request.
 *
 * Generates structured analytical intelligence reports on European Parliament data.
 * Supports four report types: MEP activity scorecards, committee performance
 * assessments, voting statistics summaries, and legislation progress reports.
 * Delegates to a type-keyed generator map for O(1) dispatch.
 *
 * @param args - Raw tool arguments, validated against {@link GenerateReportSchema}
 * @returns MCP tool result containing a structured report with summary, sections,
 *   statistics, and recommendations appropriate to the requested report type
 * @throws {ZodError} If `args` fails schema validation (e.g., missing required fields or invalid format)
 * @throws {Error} If the European Parliament API is unreachable or returns an error response
 *
 * @example
 * ```typescript
 * const result = await handleGenerateReport({
 *   reportType: 'MEP_ACTIVITY',
 *   subjectId: 'MEP-124810',
 *   dateFrom: '2024-01-01',
 *   dateTo: '2024-12-31'
 * });
 * // Returns MEP activity scorecard with voting discipline, attendance,
 * // committee contributions, and performance recommendations
 * ```
 *
 * @security Input is validated with Zod before any API call.
 *   Personal data in responses is minimised per GDPR Article 5(1)(c).
 *   All requests are rate-limited and audit-logged per ISMS Policy AU-002.
 * @since 0.8.0
 * @see {@link generateReportToolMetadata} for MCP schema registration
 * @see {@link handleTrackLegislation} for per-procedure legislative progress tracking
 */
export async function handleGenerateReport(
  args: unknown
): Promise<ToolResult> {
  // Validate input
  const params = GenerateReportSchema.parse(args);
  
  try {
    // Use map lookup instead of switch for O(1) access
    const generator = reportGenerators[params.reportType];
    const report = await generator(params);
    
    // Return MCP-compliant response
    return {
      content: [{
        type: 'text',
        text: JSON.stringify(report, null, 2)
      }]
    };
  } catch (error) {
    // Handle errors without exposing internal details
    const errorMessage = error instanceof Error ? error.message : 'Unknown error';
    throw new Error(`Failed to generate report: ${errorMessage}`);
  }
}
 
/**
 * Tool metadata for MCP registration
 */
export const generateReportToolMetadata = {
  name: 'generate_report',
  description: 'Generate comprehensive analytical reports on European Parliament data. Supports MEP activity reports, committee performance reports, voting statistics, and legislation progress reports. Returns structured report with summary, sections, statistics, and recommendations.',
  inputSchema: {
    type: 'object' as const,
    properties: {
      reportType: {
        type: 'string',
        description: 'Type of report to generate',
        enum: ['MEP_ACTIVITY', 'COMMITTEE_PERFORMANCE', 'VOTING_STATISTICS', 'LEGISLATION_PROGRESS']
      },
      subjectId: {
        type: 'string',
        description: 'Subject identifier (MEP ID, Committee ID, etc.) - optional for aggregate reports',
        minLength: 1,
        maxLength: 100
      },
      dateFrom: {
        type: 'string',
        description: 'Report period start date (YYYY-MM-DD format)',
        pattern: '^\\d{4}-\\d{2}-\\d{2}$'
      },
      dateTo: {
        type: 'string',
        description: 'Report period end date (YYYY-MM-DD format)',
        pattern: '^\\d{4}-\\d{2}-\\d{2}$'
      }
    },
    required: ['reportType']
  }
};