# All files / src/tools earlyWarningSystem.ts

90.44% Statements 123/136
74.35% Branches 58/78
97.43% Functions 38/39
96.11% Lines 99/103

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
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440

    4x

    4x

    19x
    19x
    19x
    3x

    19x
    19x

    17x
    17x

    136x

    112x
    16x
    16x
    16x

    19x

    17x
    136x
    136x
    17x
    17x
    17x

    19x
    19x

    17x
    16x
    16x

    136x
    17x

    17x

    19x

    122x
    16x

    1x

    1x

    19x
    1x
    1x

    19x
    1x
    1x

    19x
    146x
    146x

    19x
    19x
    19x

    19x
    18x

    127x
    38x
    19x
    19x
    19x

    19x
    19x
    19x

    19x
    146x
    1x
    19x
    19x
    19x
    19x

    19x

    19x

    1x

    34x
    19x
    34x
    19x
    3x

    22x
    22x
    20x

    20x
    1x

    19x
    19x
    11875x
    11875x

    19x
    146x
    235x

    19x
    19x
    19x
    19x

    19x

    34x
    34x
    34x
    19x

    19x

    22x

    2x

    4x

    24x
    24x

     /**
     * MCP Tool: early_warning_system
     *
     * Detect emerging political shifts, unusual voting changes, and coalition
     * fracture signals. Combines anomaly detection and coalition dynamics
     * concepts to surface actionable risk warnings.
     *
     * **Intelligence Perspective:** Early warning identifies weak signals before
     * they manifest as major political disruptions—enabling proactive positioning
     * and risk mitigation for EU affairs practitioners.
     *
     * **Business Perspective:** Critical for B2G/B2B clients—including policy
     * risk consultancies, lobbying firms, and institutional investors—who need
     * advance notice of coalition fractures or fragmentation shifts that could
     * alter the legislative majority and affect regulatory outcomes.
     *
     * **Marketing Perspective:** Showcases real-time political intelligence
     * capabilities to journalists, think-tank researchers, and civic-tech
     * developers who monitor EU governance and democratic accountability.
     *
     * ISMS Policy: SC-002 (Input Validation), AC-003 (Least Privilege)
     */

    import { z } from 'zod';
    import { epClient } from '../clients/europeanParliamentClient.js';
    import { buildToolResponse, buildErrorResponse } from './shared/responseBuilder.js';
    import type { ToolResult } from './shared/types.js';

    /**
     * Zod input schema for the `early_warning_system` MCP tool. Configures
     * detection sensitivity (low / medium / high) and the focus area
     * (coalitions / attendance / all).
     */
    export const EarlyWarningSystemSchema = z.object({
      sensitivity: z.enum(['low', 'medium', 'high'])
        .optional()
        .default('medium')
        .describe('Detection sensitivity — higher = more warnings surfaced'),
      focusArea: z.enum(['coalitions', 'attendance', 'all'])
        .optional()
        .default('all')
        .describe('Area of political activity to monitor')
    });

    /**
     * Validated parameter type for the `early_warning_system` tool, inferred
     * from {@link EarlyWarningSystemSchema}.
     */
    export type EarlyWarningSystemParams = z.infer<typeof EarlyWarningSystemSchema>;

    type SeverityLevel = 'CRITICAL' | 'HIGH' | 'MEDIUM' | 'LOW';

    interface Warning {
      type: string;
      severity: SeverityLevel;
      description: string;
      affectedEntities: string[];
      recommendedAction: string;
    }

    interface TrendIndicator {
      indicator: string;
      direction: 'POSITIVE' | 'NEGATIVE' | 'NEUTRAL';
      confidence: number;
      description: string;
    }

    interface EarlyWarningResult {
      assessmentTime: string;
      sensitivity: string;
      focusArea: string;
      warnings: Warning[];
      riskLevel: SeverityLevel;
      stabilityScore: number;
      trendIndicators: TrendIndicator[];
      lastAssessmentTime: string;
      computedAttributes: {
        criticalWarnings: number;
        highWarnings: number;
        totalWarnings: number;
        overallStabilityTrend: 'STABLE' | 'DETERIORATING';
        keyRiskFactor: string;
      };
      dataAvailable: boolean;
      confidenceLevel: 'HIGH' | 'MEDIUM' | 'LOW';
      dataFreshness: string;
      sourceAttribution: string;
      methodology: string;
      dataQualityWarnings: string[];
    }

    interface GroupSize {
      groupId: string;
      memberCount: number;
    }

    interface SensitivityThresholds {
      attendance: number;
      fragmentation: number;
      sizeImbalance: number;
    }

    const SENSITIVITY_THRESHOLDS: Record<'low' | 'medium' | 'high', SensitivityThresholds> = {
      low: { attendance: 50, fragmentation: 8, sizeImbalance: 5 },
      medium: { attendance: 60, fragmentation: 6, sizeImbalance: 3 },
      high: { attendance: 70, fragmentation: 4, sizeImbalance: 2 }
    };

    function deriveRiskLevel(critical: number, high: number, medium: number): SeverityLevel {
      Iif (critical > 0) return 'CRITICAL';
      Iif (high > 2) return 'HIGH';
      if (high > 0 || medium > 3) return 'MEDIUM';
      return 'LOW';
    }

    function computeStabilityScore(totalWarnings: number, critical: number, high: number): number {
      const penalty = critical * 25 + high * 10 + (totalWarnings - critical - high) * 3;
      return Math.max(0, Math.min(100, Math.round(100 - penalty)));
    }

    function buildFragmentationWarning(groupSizes: GroupSize[], threshold: number): Warning | undefined {
      Iif (groupSizes.length < threshold) return undefined;
      return {
        type: 'HIGH_FRAGMENTATION',
        severity: 'MEDIUM',
        description: `Parliament fragmented across ${String(groupSizes.length)} political groups — coalition building more complex`,
        affectedEntities: groupSizes.map(g => g.groupId),
        recommendedAction: 'Monitor cross-group voting patterns for emerging grand coalitions or blocking minorities'
      };
    }

    function buildDominanceWarning(groupSizes: GroupSize[], imbalanceRatio: number): Warning | undefined {
      const sorted = [...groupSizes].sort((a, b) => b.memberCount - a.memberCount);
      const largest = sorted[0];
      Iif (largest === undefined) return undefined;
      return {
        type: 'DOMINANT_GROUP_RISK',
        severity: 'HIGH',
        description: `Largest group (${largest.groupId}) is ${imbalanceRatio.toFixed(1)}x the size of the smallest group — potential dominance risk`,
        affectedEntities: [largest.groupId],
        recommendedAction: 'Track minority group coalition formation to counter dominant group influence'
      };
    }

    function buildMajorityWarning(majorityGroup: GroupSize, total: number): Warning {
      return {
        type: 'ABSOLUTE_MAJORITY_RISK',
        severity: 'CRITICAL',
        description: `Group ${majorityGroup.groupId} holds absolute majority (${String(majorityGroup.memberCount)}/${String(total)} MEPs)`,
        affectedEntities: [majorityGroup.groupId],
        recommendedAction: 'Verify inter-group checks and balances; monitor for procedural overreach'
      };
    }

    function buildCoalitionWarnings(groupSizes: GroupSize[], thresholds: SensitivityThresholds, focusArea: string): Warning[] {
      if (focusArea !== 'coalitions' && focusArea !== 'all') return [];

      const warnings: Warning[] = [];
      const totalMembers = groupSizes.reduce((s, g) => s + g.memberCount, 0);
      const sizes = groupSizes.map(g => g.memberCount);
      const maxSize = Math.max(...sizes);
      const minSize = Math.min(...sizes);
      const imbalanceRatio = minSize > 0 ? maxSize / minSize : maxSize;

      const fragWarning = buildFragmentationWarning(groupSizes, thresholds.fragmentation);
      if (fragWarning !== undefined) warnings.push(fragWarning);

      if (imbalanceRatio > thresholds.sizeImbalance) {
        const domWarning = buildDominanceWarning(groupSizes, imbalanceRatio);
        Eif (domWarning !== undefined) warnings.push(domWarning);
      }

      const majorityGroup = groupSizes.find(g => totalMembers > 0 && g.memberCount > totalMembers / 2);
      Iif (majorityGroup !== undefined) {
        warnings.push(buildMajorityWarning(majorityGroup, totalMembers));
      }

      return warnings;
    }

    function buildAttendanceWarnings(groupSizes: GroupSize[], focusArea: string): Warning[] {
      if (focusArea !== 'attendance' && focusArea !== 'all') return [];

      const smallGroups = groupSizes.filter(g => g.memberCount <= 5);
      if (smallGroups.length === 0) return [];

      return [{
        type: 'SMALL_GROUP_QUORUM_RISK',
        severity: 'LOW',
        description: `${String(smallGroups.length)} political group(s) with ≤5 members may struggle to maintain quorum`,
        affectedEntities: smallGroups.map(g => g.groupId),
        recommendedAction: 'Monitor small group participation rates to ensure quorum requirements are met'
      }];
    }

    function classifyFragmentationDirection(effectiveParties: number): TrendIndicator['direction'] {
      if (effectiveParties > 5) return 'NEGATIVE';
      Iif (effectiveParties > 3) return 'NEUTRAL';
      return 'POSITIVE';
    }

    function describeFragmentation(direction: TrendIndicator['direction']): string {
      if (direction === 'NEGATIVE') return 'high';
      Iif (direction === 'NEUTRAL') return 'moderate';
      return 'low';
    }

    function buildFragmentationIndicator(groupSizes: GroupSize[], totalMembers: number): TrendIndicator {
      const herfindahl = groupSizes.reduce((s, g) => {
        const share = totalMembers > 0 ? g.memberCount / totalMembers : 0;
        return s + share * share;
      }, 0);
      const effectiveParties = herfindahl > 0 ? 1 / herfindahl : 1;
      const direction = classifyFragmentationDirection(effectiveParties);
      return {
        indicator: 'parliamentary_fragmentation',
        direction,
        confidence: 0.7,
        description: `Effective number of parties: ${effectiveParties.toFixed(1)} (${describeFragmentation(direction)} fragmentation)`
      };
    }

    function classifyCoalitionDirection(top2Share: number): TrendIndicator['direction'] {
      if (top2Share > 0.5) return 'POSITIVE';
      Eif (top2Share > 0.35) return 'NEUTRAL';
      return 'NEGATIVE';
    }

    function buildCoalitionViabilityIndicator(groupSizes: GroupSize[], totalMembers: number): TrendIndicator {
      const sorted = [...groupSizes].sort((a, b) => b.memberCount - a.memberCount);
      const top2Share = sorted.slice(0, 2).reduce((s, g) => s + (totalMembers > 0 ? g.memberCount / totalMembers : 0), 0);
      const direction = classifyCoalitionDirection(top2Share);
      const viabilityText = top2Share > 0.5 ? 'viable' : 'uncertain';
      return {
        indicator: 'grand_coalition_viability',
        direction,
        confidence: 0.65,
        description: `Top-2 groups hold ${(top2Share * 100).toFixed(1)}% of seats — grand coalition ${viabilityText}`
      };
    }

    function classifyMinorityDirection(minorityShare: number): TrendIndicator['direction'] {
      Iif (minorityShare > 0.15) return 'NEGATIVE';
      Iif (minorityShare > 0.08) return 'NEUTRAL';
      return 'POSITIVE';
    }

    function buildMinorityIndicator(groupSizes: GroupSize[], totalMembers: number): TrendIndicator {
      const smallGroupCount = groupSizes
        .filter(g => totalMembers > 0 && g.memberCount / totalMembers < 0.05)
        .reduce((s, g) => s + g.memberCount, 0);
      const minorityShare = totalMembers > 0 ? smallGroupCount / totalMembers : 0;
      const direction = classifyMinorityDirection(minorityShare);
      const minorityText = minorityShare > 0.15 ? 'fragmentation concern' : 'healthy distribution';
      return {
        indicator: 'minority_representation',
        direction,
        confidence: 0.6,
        description: `${(minorityShare * 100).toFixed(1)}% of MEPs in minority groups (<5% seat share) — ${minorityText}`
      };
    }

    function buildTrendIndicators(groupSizes: GroupSize[], totalMembers: number): TrendIndicator[] {
      return [
        buildFragmentationIndicator(groupSizes, totalMembers),
        buildCoalitionViabilityIndicator(groupSizes, totalMembers),
        buildMinorityIndicator(groupSizes, totalMembers)
      ];
    }

    function classifyStabilityTrend(stabilityScore: number): 'STABLE' | 'DETERIORATING' {
      Eif (stabilityScore >= 50) return 'STABLE';
      return 'DETERIORATING';
    }

    function buildEmptyResult(params: EarlyWarningSystemParams, assessmentTime: string): EarlyWarningResult {
      return {
        assessmentTime,
        sensitivity: params.sensitivity,
        focusArea: params.focusArea,
        warnings: [],
        riskLevel: 'LOW',
        stabilityScore: 50,
        trendIndicators: [],
        lastAssessmentTime: assessmentTime,
        computedAttributes: {
          criticalWarnings: 0,
          highWarnings: 0,
          totalWarnings: 0,
          overallStabilityTrend: 'STABLE',
          keyRiskFactor: 'Insufficient data'
        },
        dataAvailable: false,
        confidenceLevel: 'LOW',
        dataFreshness: 'No data available from EP API',
        sourceAttribution: 'European Parliament Open Data Portal - data.europarl.europa.eu',
        methodology: 'Early warning assessment could not be performed — no MEP data returned.',
        dataQualityWarnings: ['No MEP data returned from EP API — early warning analysis could not be performed'],
      };
    }

    function resolveKeyRiskFactor(warnings: Warning[]): string {
      const critical = warnings.find(w => w.severity === 'CRITICAL');
      Iif (critical !== undefined) return critical.type;
      const high = warnings.find(w => w.severity === 'HIGH');
      if (high !== undefined) return high.type;
      return 'NONE';
    }

    /**
     * Compute an early-warning assessment of EP political stability.
     *
     * Implementation of the MCP `early_warning_system` tool. Analyses current
     * group composition for fragmentation, dominant-group risks, minority
     * quorum risks and coalition viability, derives severity-tagged warnings,
     * and produces an overall stability score (0-100) and risk level.
     *
     * @param params - Validated tool parameters
     *   (see {@link EarlyWarningSystemSchema})
     * @returns A {@link ToolResult} containing the warning report or a
     *   structured error response on failure
     */
    export async function earlyWarningSystem(params: EarlyWarningSystemParams): Promise<ToolResult> {
      try {
        const mepResult = await epClient.getCurrentMEPs({ limit: 100 });
        const assessmentTime = new Date().toISOString();

        if (mepResult.data.length === 0) {
          return buildToolResponse(buildEmptyResult(params, assessmentTime));
        }

        const groupSizeMap = new Map<string, number>();
        for (const mep of mepResult.data as { politicalGroup: string }[]) {
          const g = mep.politicalGroup;
          groupSizeMap.set(g, (groupSizeMap.get(g) ?? 0) + 1);
        }

        const groupSizes: GroupSize[] = Array.from(groupSizeMap.entries())
          .map(([groupId, memberCount]) => ({ groupId, memberCount }))
          .sort((a, b) => b.memberCount - a.memberCount);

        const totalMembers = mepResult.data.length;
        const sensitivity = params.sensitivity;
        const focusArea = params.focusArea;
        const thresholds = SENSITIVITY_THRESHOLDS[sensitivity];

        const warnings: Warning[] = [
          ...buildCoalitionWarnings(groupSizes, thresholds, focusArea),
          ...buildAttendanceWarnings(groupSizes, focusArea)
        ];

        const criticalWarnings = warnings.filter(w => w.severity === 'CRITICAL').length;
        const highWarnings = warnings.filter(w => w.severity === 'HIGH').length;
        const mediumWarnings = warnings.filter(w => w.severity === 'MEDIUM').length;
        const stabilityScore = computeStabilityScore(warnings.length, criticalWarnings, highWarnings);

        const result: EarlyWarningResult = {
          assessmentTime,
          sensitivity,
          focusArea,
          warnings,
          riskLevel: deriveRiskLevel(criticalWarnings, highWarnings, mediumWarnings),
          stabilityScore,
          trendIndicators: buildTrendIndicators(groupSizes, totalMembers),
          lastAssessmentTime: assessmentTime,
          computedAttributes: {
            criticalWarnings,
            highWarnings,
            totalWarnings: warnings.length,
            overallStabilityTrend: classifyStabilityTrend(stabilityScore),
            keyRiskFactor: resolveKeyRiskFactor(warnings)
          },
          dataAvailable: true,
          confidenceLevel: totalMembers >= 50 ? 'MEDIUM' : 'LOW',
          dataFreshness: 'Real-time EP API data — group composition from current MEP records',
          sourceAttribution: 'European Parliament Open Data Portal - data.europarl.europa.eu',
          methodology: 'Early warning assessment combining fragmentation analysis and coalition stability metrics. '
            + 'Warnings generated from: group size distribution (fragmentation), dominant group detection, '
            + 'minority group quorum risk, and coalition viability thresholds. '
            + 'Stability score = 100 - (25*critical + 10*high + 3*medium warnings). '
            + 'NOTE: Voting cohesion and attendance data not available from EP API — '
            + 'warnings are derived from structural group composition only. '
            + 'Data source: https://data.europarl.europa.eu/api/v2/meps',
          dataQualityWarnings: [
            'Warnings based on group size composition only — voting cohesion and attendance data unavailable from EP API',
          ],
        };

        return buildToolResponse(result);
      } catch (error: unknown) {
        return buildErrorResponse(
          error instanceof Error ? error : new Error(String(error)),
          'early_warning_system'
        );
      }
    }

    /**
     * MCP tool metadata for `early_warning_system` (name, description, and
     * JSON Schema for the tool's input). Consumed by the server's tool
     * registry to advertise this tool in `ListTools` responses.
     */
    export const earlyWarningSystemToolMetadata = {
      name: 'early_warning_system',
      description: 'Detect emerging political shifts, coalition fracture signals, and unusual patterns. Generates warnings with severity levels (CRITICAL/HIGH/MEDIUM/LOW), computes stability score (0-100), trend indicators, and overall risk level. Configurable sensitivity and focus area.',
      inputSchema: {
        type: 'object' as const,
        properties: {
          sensitivity: {
            type: 'string',
            enum: ['low', 'medium', 'high'],
            description: 'Detection sensitivity — higher surfaces more warnings',
            default: 'medium'
          },
          focusArea: {
            type: 'string',
            enum: ['coalitions', 'attendance', 'all'],
            description: 'Area of political activity to monitor',
            default: 'all'
          }
        }
      }
    };

    /**
     * MCP `CallTool` handler entry point for `early_warning_system`.
     *
     * Validates the raw input arguments against
     * {@link EarlyWarningSystemSchema} and delegates execution to
     * {@link earlyWarningSystem}.
     *
     * @param args - Raw, untrusted MCP `CallTool` arguments
     * @returns The same {@link ToolResult} produced by
     *   {@link earlyWarningSystem}
     */
    export async function handleEarlyWarningSystem(args: unknown): Promise<ToolResult> {
      const params = EarlyWarningSystemSchema.parse(args);
      return earlyWarningSystem(params);
    }