# All files / src/tools correlateIntelligence.ts

91.48% Statements 172/188
81.96% Branches 100/122
97.36% Functions 37/38
91.92% Lines 148/161

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
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    455
    456
    457
    458
    459
    460
    461
    462
    463
    464
    465
    466
    467
    468
    469
    470
    471
    472
    473
    474
    475
    476
    477
    478
    479
    480
    481
    482
    483
    484
    485
    486
    487
    488
    489
    490
    491
    492
    493
    494
    495
    496
    497
    498
    499
    500
    501
    502
    503
    504
    505
    506
    507
    508
    509
    510
    511
    512
    513
    514
    515
    516
    517
    518
    519
    520
    521
    522
    523
    524
    525
    526
    527
    528
    529
    530
    531
    532
    533
    534
    535
    536
    537
    538
    539
    540
    541
    542
    543
    544
    545
    546
    547
    548
    549
    550
    551
    552
    553
    554
    555
    556
    557
    558
    559
    560
    561
    562
    563
    564
    565
    566
    567
    568
    569
    570
    571
    572
    573
    574
    575
    576
    577
    578
    579
    580
    581
    582
    583
    584
    585
    586
    587
    588
    589
    590
    591
    592
    593
    594
    595
    596
    597
    598
    599
    600
    601
    602
    603
    604
    605
    606
    607
    608
    609
    610
    611
    612
    613
    614
    615
    616
    617
    618
    619
    620
    621
    622
    623
    624
    625
    626
    627
    628
    629
    630
    631
    632
    633
    634
    635
    636
    637
    638
    639
    640
    641
    642
    643
    644
    645
    646
    647
    648
    649
    650
    651
    652
    653
    654
    655
    656
    657
    658
    659
    660
    661
    662
    663
    664
    665
    666
    667
    668
    669
    670
    671
    672
    673
    674
    675
    676
    677
    678
    679
    680
    681
    682
    683
    684
    685
    686
    687
    688
    689
    690
    691
    692
    693
    694
    695
    696
    697
    698
    699
    700
    701
    702
    703
    704
    705
    706
    707
    708
    709
    710
    711
    712
    713
    714
    715
    716
    717
    718
    719
    720
    721
    722
    723
    724
    725
    726
    727
    728
    729
    730
    731
    732
    733
    734
    735
    736
    737
    738
    739
    740
    741
    742
    743
    744
    745
    746
    747
    748
    749
    750
    751
    752
    753
    754
    755
    756
    757
    758
    759
    760
    761
    762
    763
    764
    765
    766
    767
    768
    769
    770
    771
    772
    773
    774
    775
    776
    777
    778
    779
    780
    781
    782
    783
    784
    785
    786
    787
    788
    789
    790
    791
    792
    793
    794
    795
    796
    797
    798
    799
    800
    801
    802
    803
    804
    805
    806
    807
    808
    809
    810
    811
    812
    813
    814
    815
    816
    817
    818
    819
    820
    821
    822
    823
    824
    825
    826
    827
    828
    829
    830
    831
    832
    833
    834
    835
    836
    837
    838
    839
    840
    841
    842
    843
    844
    845
    846
    847
    848
    849
    850
    851
    852
    853
    854
    855
    856
    857
    858
    859
    860
    861
    862
    863
    864
    865
    866
    867
    868
    869
    870
    871
    872
    873
    874
    875
    876
    877
    878
    879
    880
    881
    882
    883
    884
    885
    886
    887
    888
    889
    890
    891
    892
    893
    894
    895
    896
    897
    898
    899
    900
    901
    902
    903
    904
    905
    906
    907
    908
    909
    910
    911
    912
    913
    914
    915
    916
    917
    918
    919
    920
    921
    922
    923
    924
    925
    926
    927
    928
    929
    930
    931
    932
    933
    934
    935
    936
    937
    938
    939
    940
    941
    942
    943
    944
    945
    946
    947
    948
    949
    950
    951
    952
    953

    4x

    4x

    169x
    169x

    169x
    169x

    44x
    32x
    32x

    12x
    11x

    49x
    49x
    46x

    3x
    3x

    46x
    46x
    46x

    49x
    49x

    46x
    46x

    46x
    46x

    46x

    44x

    44x

    44x
    44x
    12x
    12x

    44x

    38x
    34x
    32x

    1x
    1x

    1x

    38x

    38x
    38x
    35x

    3x
    3x

    35x
    35x
    35x

    35x

    35x

    35x
    70x
    1x

    35x
    1x

    35x
    38x

    38x

    1x

    1x

    1x

    1x
    1x
    1x

    1x

    6x
    3x
    3x

    6x

    6x
    6x
    6x
    6x
    6x

    6x

    6x

    6x

    9x

    5x
    5x
    4x

    1x
    1x

    4x

    3x
    3x
    3x

    3x

    3x

    5x

    5x
    6x

    6x
    6x

    5x

    38x
    28x
    26x

    38x
    5x
    3x

    38x

    38x
    2x
    36x
    3x

    168x
    38x
    26x

    38x
    33x

    38x

    38x
    2x

    36x

    38x

    16x
    16x
    16x
    16x

    38x
    38x

    42x
    42x

    42x
    42x
    42x
    42x

    42x
    49x

    38x
    38x
    38x

    38x
    49x
    49x
    49x

    38x

    38x

    42x

    42x

    42x

    42x

    42x

    42x
    42x

    38x

    4x

     /**
     * MCP Tool: correlate_intelligence
     *
     * Cross-tool OSINT intelligence correlation engine that combines outputs from
     * multiple intelligence tools to generate consolidated alerts and insights.
     *
     * **Intelligence Perspective:** Combines influence assessment, voting anomaly
     * detection, coalition dynamics, network analysis, and early warning signals
     * into unified intelligence assessments — surfacing patterns that are invisible
     * when each tool operates independently. Implements three core correlation
     * scenarios: (1) High-influence MEP × voting anomalies → elevated attention
     * flag; (2) Coalition fracture warning × declining cohesion → consolidated
     * alert; (3) Network centrality × cross-committee activity → comprehensive
     * profile.
     *
     * **Business Perspective:** Enables policy analysts, government affairs teams,
     * and intelligence practitioners to identify high-risk MEPs and coalition
     * instability through automated cross-tool correlation — saving hours of
     * manual intelligence synthesis and reducing missed signals.
     *
     * **Marketing Perspective:** Demonstrates the advanced OSINT capability of
     * combining multiple intelligence tools into actionable assessments for policy
     * professionals, researchers, and advocacy organisations tracking EU
     * legislative dynamics.
     *
     * ISMS Policy: SC-002 (Input Validation), AC-003 (Least Privilege), AU-002 (Audit Logging)
     */

    import { randomUUID } from 'node:crypto';
    import { CorrelateIntelligenceSchema, OsintStandardOutputSchema } from '../schemas/europeanParliament.js';
    import { buildToolResponse, buildErrorResponse } from './shared/responseBuilder.js';
    import type { ToolResult, OsintStandardOutput, ConfidenceLevel } from './shared/types.js';
    import type { DataAvailability } from '../types/index.js';
    import { auditLogger, toErrorMessage } from '../utils/auditLogger.js';

    import { handleAssessMepInfluence } from './assessMepInfluence.js';
    import { handleDetectVotingAnomalies } from './detectVotingAnomalies.js';
    import { handleEarlyWarningSystem } from './earlyWarningSystem.js';
    import { handleAnalyzeCoalitionDynamics } from './analyzeCoalitionDynamics.js';
    import { handleNetworkAnalysis } from './networkAnalysis.js';
    import { handleComparativeIntelligence } from './comparativeIntelligence.js';
    import { ToolError } from './shared/errors.js';

    interface InfluenceResult {
      mepId: string;
      mepName: string;
      overallScore: number;
      rank: string;
      confidenceLevel: 'HIGH' | 'MEDIUM' | 'LOW';
    }

    interface AnomalyResult {
      anomalies: { type: string; severity: string; mepId: string; mepName: string }[];
      summary: { totalAnomalies: number; highSeverity: number };
      confidenceLevel: 'HIGH' | 'MEDIUM' | 'LOW';
    }

    interface EarlyWarningResult {
      warnings: { type: string; severity: string; description: string; affectedEntities: string[] }[];
      riskLevel: string;
      stabilityScore: number;
      computedAttributes: { criticalWarnings: number; highWarnings: number; keyRiskFactor: string };
      confidenceLevel: 'HIGH' | 'MEDIUM' | 'LOW';
    }

    interface CoalitionResult {
      groupMetrics: { groupId: string; stressIndicator: { value: number | null; availability: string; confidence: string }; computedAttributes: { unityTrend: string } }[];
      stressIndicators: { indicator: string; severity: string; affectedGroups: string[] }[];
      confidenceLevel: 'HIGH' | 'MEDIUM' | 'LOW';
    }

    interface NetworkResult {
      centralMEPs: { mepId: string; mepName: string; centralityScore: number }[];
      bridgingMEPs: { mepId: string; mepName: string }[];
      networkNodes?: { mepId: string; centralityScore: number }[];
      confidenceLevel: 'HIGH' | 'MEDIUM' | 'LOW';
    }

    interface ComparativeResult {
      profiles: { mepId: string; name: string; scores: Record<string, number>; overallScore: number }[];
      outlierMEPs: { mepId: string; name: string; outlierDimension: string; zScore: number }[];
      confidenceLevel: 'HIGH' | 'MEDIUM' | 'LOW';
    }

    /** A single correlated intelligence alert */
    export interface CorrelationAlert {
      alertType: 'ELEVATED_ATTENTION' | 'COALITION_FRACTURE' | 'COMPREHENSIVE_PROFILE';
      severity: 'CRITICAL' | 'HIGH' | 'MEDIUM' | 'LOW';
      mepId?: string;
      mepName?: string;
      groups?: string[];
      evidence: string[];
      recommendation: string;
    }

    /** Detail record for an influence × anomaly correlation */
    export interface InfluenceAnomalyCorrelation {
      mepId: string;
      mepName: string;
      influenceScore: number;
      influenceRank: string;
      anomalyCount: number;
      highSeverityAnomalies: number;
      correlationSignificance: 'HIGH' | 'MEDIUM' | 'LOW';
    }

    /** Detail record for a coalition fracture correlation */
    export interface CoalitionFractureCorrelation {
      affectedGroups: string[];
      warningSignals: string[];
      decliningCohesionGroups: string[];
      fractureRisk: 'HIGH' | 'MEDIUM' | 'LOW';
      stabilityScore: number;
    }

    /** Detail record for a network × committee comprehensive profile */
    export interface NetworkProfileCorrelation {
      mepId: string;
      mepName: string;
      centralityScore: number;
      committeeActivityScore: number;
      isBridgingMep: boolean;
      profileSignificance: 'HIGH' | 'MEDIUM' | 'LOW';
    }

    /** Full correlated intelligence report */
    export interface CorrelatedIntelligenceReport extends OsintStandardOutput {
      correlationId: string;
      analysisTime: string;
      scope: {
        mepIds: string[];
        groups: string[];
        sensitivityLevel: string;
        networkAnalysisIncluded: boolean;
      };
      alerts: CorrelationAlert[];
      correlations: {
        influenceAnomaly: InfluenceAnomalyCorrelation[];
        coalitionFracture: CoalitionFractureCorrelation | null;
        networkProfiles: NetworkProfileCorrelation[];
      };
      summary: {
        totalAlerts: number;
        criticalAlerts: number;
        highAlerts: number;
        mediumAlerts: number;
        lowAlerts: number;
        correlationsFound: number;
      };
      /** Explicit marker indicating whether correlation data was available from dependent tools */
      dataAvailability: DataAvailability;
    }

    const INFLUENCE_THRESHOLDS: Record<'HIGH' | 'MEDIUM' | 'LOW', number> = {
      HIGH: 50,
      MEDIUM: 70,
      LOW: 85,
    };

    const DEFAULT_COALITION_GROUPS = ['EPP', 'S&D', 'Renew', 'Greens/EFA', 'ECR', 'ID'];

    /**
     * Safely parses the JSON payload from a {@link ToolResult} returned by a dependent tool.
     *
     * Throws descriptive errors for explicit tool errors (`isError: true`) and for
     * unparseable JSON. When `result.content[0]?.text` is missing or `undefined`,
     * the implementation falls back to parsing `'{}'` (an empty object), so callers
     * will receive an empty object rather than an error for missing content.
     *
     * @param result - MCP tool result from a dependent tool call
     * @returns Parsed JSON value — an empty object `{}` if content is absent
     * @throws {Error} If the result's `isError` flag is `true`
     * @throws {Error} If the result content is present but cannot be parsed as JSON
     *
     * @security Content is parsed as JSON only — no `eval`/`Function` usage.
     *   Note: when a dependent tool sets `isError: true`, the raw `text` payload is
     *   embedded in the thrown error message. Callers should ensure error messages
     *   are sanitised before surfacing them to end users.
     */
    function parseToolResult(result: ToolResult): unknown {
      const text = result.content[0]?.text;
      Iif (result.isError === true) {
        const message =
          typeof text === 'string' && text.trim().length > 0
            ? `Dependent tool returned an error result: ${text}`
            : 'Dependent tool returned an error result with no message';
        throw new Error(message);
      }
      try {
        return JSON.parse(text ?? '{}');
      } catch (error: unknown) {
        throw new Error(
          `Failed to parse dependent tool result as JSON: ${toErrorMessage(error)}`
        );
      }
    }

    /**
     * Determines the significance level of an influence × anomaly correlation.
     *
     * Significance escalates when both high influence and anomalies are present:
     * - **`HIGH`** — high-influence MEP with at least one high-severity anomaly
     * - **`MEDIUM`** — high-influence MEP with anomalies (but none high-severity)
     * - **`LOW`** — no meaningful combined signal
     *
     * @param isHighInfluence - Whether the MEP's influence score exceeds the threshold
     * @param hasAnomalies - Whether any voting anomalies were detected
     * @param highSeverityAnomalies - Count of high-severity anomalies
     * @returns Correlation significance level
     */
    function getCorrelationSignificance(
      isHighInfluence: boolean,
      hasAnomalies: boolean,
      highSeverityAnomalies: number
    ): 'HIGH' | 'MEDIUM' | 'LOW' {
      if (isHighInfluence && highSeverityAnomalies > 0) return 'HIGH';
      Iif (isHighInfluence && hasAnomalies) return 'MEDIUM';
      return 'LOW';
    }

    /**
     * Determines the severity level for an `ELEVATED_ATTENTION` alert based on anomaly counts.
     *
     * - **`CRITICAL`** — more than one high-severity anomaly (pattern, not isolated)
     * - **`HIGH`** — exactly one high-severity anomaly
     * - **`MEDIUM`** — anomalies exist but none are high-severity
     *
     * @param highSeverity - Number of high-severity voting anomalies detected
     * @returns Severity level (CRITICAL / HIGH / MEDIUM) for the ELEVATED_ATTENTION alert type
     */
    function getAlertSeverityForAnomalies(highSeverity: number): 'CRITICAL' | 'HIGH' | 'MEDIUM' {
      if (highSeverity > 1) return 'CRITICAL';
      Eif (highSeverity > 0) return 'HIGH';
      return 'MEDIUM';
    }

    /**
     * Fetches influence assessment data for a single MEP.
     *
     * Delegates to {@link handleAssessMepInfluence} and returns `null` on any
     * failure (network error, unknown MEP, tool error) to allow the correlation
     * pipeline to continue with remaining MEPs.
     *
     * @param mepId - MEP identifier string
     * @returns Parsed {@link InfluenceResult} or `null` if the call fails
     */
    async function fetchInfluenceData(mepId: string): Promise<InfluenceResult | null> {
      try {
        const ir = await handleAssessMepInfluence({ mepId });
        return parseToolResult(ir) as InfluenceResult;
      } catch (error: unknown) {
        auditLogger.logError('correlate_intelligence.fetch_influence_data', { mepId }, toErrorMessage(error));
        return null;
      }
    }

    /**
     * Fetches voting anomaly data for a single MEP.
     *
     * On tool or network failure, returns a zero-anomaly fallback with
     * `confidenceLevel: 'LOW'` to keep the correlation pipeline running and
     * avoid hard failures. This graceful degradation prioritizes pipeline
     * continuity over strict detection guarantees and may under-report
     * anomalies if failures are interpreted as "no anomalies" by callers.
     *
     * @param mepId - MEP identifier string
     * @returns Parsed {@link AnomalyResult}, or a zeroed result with LOW confidence on failure
     */
    async function fetchAnomalyData(mepId: string): Promise<AnomalyResult> {
      try {
        const ar = await handleDetectVotingAnomalies({ mepId });
        return parseToolResult(ar) as AnomalyResult;
      } catch (error: unknown) {
        auditLogger.logError('correlate_intelligence.fetch_anomaly_data', { mepId }, toErrorMessage(error));
        return { anomalies: [], summary: { totalAnomalies: 0, highSeverity: 0 }, confidenceLevel: 'LOW' };
      }
    }

    /**
     * Executes **Correlation Scenario 1**: Influence × Anomaly for a single MEP.
     *
     * Fetches influence and anomaly data in sequence (anomaly call is skipped if
     * influence fetch fails). An `ELEVATED_ATTENTION` alert is generated only when
     * the MEP's influence score meets or exceeds `influenceThreshold` *and* voting
     * anomalies are detected simultaneously — combining both risk signals into one
     * actionable alert.
     *
     * @param mepId - MEP identifier to analyse
     * @param influenceThreshold - Minimum influence score required to trigger the alert
     * @returns Object containing the optional correlation record, optional alert, and
     *   confidence-level strings from both underlying tools
     */
    async function correlateInfluenceAnomaly(
      mepId: string,
      influenceThreshold: number
    ): Promise<{
      correlation: InfluenceAnomalyCorrelation | null;
      alert: CorrelationAlert | null;
      toolConfidenceLevels: ConfidenceLevel[];
    }> {
      const influenceData = await fetchInfluenceData(mepId);
      if (influenceData === null) return { correlation: null, alert: null, toolConfidenceLevels: [] };

      const anomalyData = await fetchAnomalyData(mepId);
      const toolConfidenceLevels = [influenceData.confidenceLevel, anomalyData.confidenceLevel];

      const isHighInfluence = influenceData.overallScore >= influenceThreshold;
      const hasAnomalies = anomalyData.summary.totalAnomalies > 0;

      if (!isHighInfluence && !hasAnomalies) return { correlation: null, alert: null, toolConfidenceLevels };

      const significance = getCorrelationSignificance(isHighInfluence, hasAnomalies, anomalyData.summary.highSeverity);

      const correlation: InfluenceAnomalyCorrelation = {
        mepId,
        mepName: influenceData.mepName,
        influenceScore: influenceData.overallScore,
        influenceRank: influenceData.rank,
        anomalyCount: anomalyData.summary.totalAnomalies,
        highSeverityAnomalies: anomalyData.summary.highSeverity,
        correlationSignificance: significance,
      };

      let alert: CorrelationAlert | null = null;
      if (isHighInfluence && hasAnomalies) {
        const severity = getAlertSeverityForAnomalies(anomalyData.summary.highSeverity);
        alert = {
          alertType: 'ELEVATED_ATTENTION',
          severity,
          mepId,
          mepName: influenceData.mepName,
          evidence: [
            `Influence score ${String(influenceData.overallScore)}/100 (rank: ${influenceData.rank}) meets threshold of ${String(influenceThreshold)}`,
            `${String(anomalyData.summary.totalAnomalies)} voting ${anomalyData.summary.totalAnomalies === 1 ? 'anomaly' : 'anomalies'} detected (${String(anomalyData.summary.highSeverity)} HIGH severity)`,
          ],
          recommendation:
            'Flag this MEP for elevated monitoring. High-influence actors exhibiting anomalous voting patterns may indicate a political realignment, external pressure, or coalition strategy shift.',
        };
      }

      return { correlation, alert, toolConfidenceLevels };
    }

    /**
     * Maps the caller-facing `sensitivityLevel` enum to the EWS tool's `sensitivity` parameter.
     *
     * The EWS tool uses lowercase strings (`'low'`, `'medium'`, `'high'`) while the
     * correlate-intelligence schema uses uppercase. This function bridges the two conventions.
     *
     * @param sensitivityLevel - Caller-supplied sensitivity level
     * @returns Equivalent lowercase EWS sensitivity string
     */
    function mapSensitivityToEws(sensitivityLevel: 'HIGH' | 'MEDIUM' | 'LOW'): 'low' | 'medium' | 'high' {
      if (sensitivityLevel === 'HIGH') return 'high';
      if (sensitivityLevel === 'LOW') return 'low';
      return 'medium';
    }

    /**
     * Classifies the fracture risk level based on warning signal counts and stress indicators.
     *
     * Escalation logic:
     * - **`HIGH`** — critical EWS warnings present, or more than one high-stress indicator
     *   (multiple converging risk signals)
     * - **`MEDIUM`** — fracture signals exist but below the high-risk threshold
     * - **`LOW`** — no meaningful fracture signals detected
     *
     * @param criticalWarnings - Count of CRITICAL-level EWS warnings
     * @param highStressCount - Count of HIGH/CRITICAL coalition stress indicators
     * @param hasFractureSignals - Whether any coalition or fragmentation warnings are present
     * @returns Fracture risk classification
     */
    function getFractureRisk(
      criticalWarnings: number,
      highStressCount: number,
      hasFractureSignals: boolean
    ): 'HIGH' | 'MEDIUM' | 'LOW' {
      Iif (criticalWarnings > 0 || highStressCount > 1) return 'HIGH';
      Eif (hasFractureSignals) return 'MEDIUM';
      return 'LOW';
    }

    /**
     * Predicate that identifies whether an EWS warning is coalition-related.
     *
     * A warning is considered coalition-related if its type contains `'COALITION'`
     * or `'FRAGMENTATION'`, or if its severity is `'CRITICAL'` or `'HIGH'`
     * (high-severity warnings of any type warrant coalition-fracture scrutiny).
     *
     * @param w - Warning object with `type` and `severity` string fields
     * @returns `true` if the warning should be included in coalition fracture analysis
     */
    function isCoalitionWarning(w: { type: string; severity: string }): boolean {
      return w.type.includes('COALITION') || w.type.includes('FRAGMENTATION') ||
        w.severity === 'CRITICAL' || w.severity === 'HIGH';
    }

    /**
     * Executes **Correlation Scenario 2**: Early Warning × Coalition Dynamics.
     *
     * Fetches EWS warnings (filtered to `'coalitions'` focus area) and coalition
     * dynamics data in sequence. A `COALITION_FRACTURE` alert is generated when
     * at least one coalition-related warning is detected, combining EWS signals
     * with declining-cohesion evidence from the coalition dynamics tool.
     *
     * Either tool failing causes the entire scenario to return an empty result
     * (fail-safe: no false-positive coalition-fracture alerts from incomplete data).
     *
     * @param groups - Political group identifiers to include in the coalition analysis
     * @param sensitivityLevel - Sensitivity level passed to the EWS tool
     * @returns Object containing the optional fracture correlation, optional alert,
     *   and confidence-level strings from both underlying tools
     */
    async function correlateCoalitionFracture(
      groups: string[],
      sensitivityLevel: 'HIGH' | 'MEDIUM' | 'LOW'
    ): Promise<{
      correlation: CoalitionFractureCorrelation | null;
      alert: CorrelationAlert | null;
      toolConfidenceLevels: ConfidenceLevel[];
    }> {
      const ewsSensitivity = mapSensitivityToEws(sensitivityLevel);

      let ewsData: EarlyWarningResult;
      let coalitionData: CoalitionResult;

      try {
        const er = await handleEarlyWarningSystem({ sensitivity: ewsSensitivity, focusArea: 'coalitions' });
        ewsData = parseToolResult(er) as EarlyWarningResult;
      } catch (error: unknown) {
        auditLogger.logError('correlate_intelligence.fetch_early_warning_data', { sensitivity: ewsSensitivity }, toErrorMessage(error));
        return { correlation: null, alert: null, toolConfidenceLevels: [] };
      }

      try {
        const cr = await handleAnalyzeCoalitionDynamics({ groupIds: groups });
        coalitionData = parseToolResult(cr) as CoalitionResult;
      } catch (error: unknown) {
        auditLogger.logError('correlate_intelligence.fetch_coalition_data', { groups }, toErrorMessage(error));
        return { correlation: null, alert: null, toolConfidenceLevels: [] };
      }

      const toolConfidenceLevels = [ewsData.confidenceLevel, coalitionData.confidenceLevel];

      const coalitionWarnings = ewsData.warnings.filter(isCoalitionWarning);

      const decliningGroups = coalitionData.groupMetrics
        .filter(gm => gm.computedAttributes.unityTrend === 'WEAKENING' || (gm.stressIndicator.value !== null && gm.stressIndicator.value > 0.5))
        .map(gm => gm.groupId);

      const highStressIndicators = coalitionData.stressIndicators.filter(
        si => si.severity === 'CRITICAL' || si.severity === 'HIGH'
      );

      const hasFractureSignals = coalitionWarnings.length > 0 || highStressIndicators.length > 0;
      const hasDecliningCohesion = decliningGroups.length > 0;

      if (!hasFractureSignals && !hasDecliningCohesion) return { correlation: null, alert: null, toolConfidenceLevels };

      const fractureRisk = getFractureRisk(
        ewsData.computedAttributes.criticalWarnings,
        highStressIndicators.length,
        hasFractureSignals
      );

      const correlation: CoalitionFractureCorrelation = {
        affectedGroups: groups,
        warningSignals: coalitionWarnings.map(w => w.description),
        decliningCohesionGroups: decliningGroups,
        fractureRisk,
        stabilityScore: ewsData.stabilityScore,
      };

      let alert: CorrelationAlert | null = null;
      Eif (hasFractureSignals) {
        alert = {
          alertType: 'COALITION_FRACTURE',
          severity: fractureRisk,
          groups: decliningGroups.length > 0 ? decliningGroups : groups,
          evidence: [
            `Early Warning System: ${String(coalitionWarnings.length)} coalition warning(s) at ${ewsData.riskLevel} risk level`,
            hasDecliningCohesion
              ? `Coalition Dynamics: ${String(decliningGroups.length)} group(s) showing declining cohesion (${decliningGroups.join(', ')})`
              : `Coalition Dynamics: no declining cohesion detected (EP API per-group voting data limited)`,
            `Stability score: ${String(ewsData.stabilityScore)}/100 — key risk: ${ewsData.computedAttributes.keyRiskFactor}`,
          ],
          recommendation:
            'Monitor coalition stability closely. Converging fracture signals from both early warning and coalition dynamics indicate elevated risk of realignment or fragmentation.',
        };
      }

      return { correlation, alert, toolConfidenceLevels };
    }

    /**
     * Determines the profile significance level for Scenario 3 (Network × Profiles).
     *
     * Significance is high only when all three signals converge: high centrality,
     * high committee activity, *and* bridging status. This reduces false positives
     * compared to triggering on any single signal alone.
     *
     * @param isHighCentrality - Whether the MEP is classified as high centrality by the network analysis
     * @param isHighCommitteeActivity - Whether the MEP's committee activity score exceeds 60
     * @param isBridging - Whether the MEP appears in the network's bridging MEP list
     * @returns Profile significance level
     */
    function getProfileSignificance(
      isHighCentrality: boolean,
      isHighCommitteeActivity: boolean,
      isBridging: boolean
    ): 'HIGH' | 'MEDIUM' | 'LOW' {
      if (isHighCentrality && isHighCommitteeActivity && isBridging) return 'HIGH';
      Iif (isHighCentrality && (isHighCommitteeActivity || isBridging)) return 'MEDIUM';
      return 'LOW';
    }

    /**
     * Builds a {@link NetworkProfileCorrelation} record and optional
     * {@link CorrelationAlert} for a single MEP profile.
     *
     * Centrality is looked up first from the full `networkNodes` map (all MEPs in
     * the network), falling back to the truncated `centralMEPs` top-10 list so
     * that MEPs outside the top-10 are not silently scored as 0.
     */
    function buildProfileAndAlert(
      profile: ComparativeResult['profiles'][number],
      networkNodesMap: Map<string, number>,
      centralMEPs: NetworkResult['centralMEPs'],
      bridgingIds: Set<string>
    ): { correlation: NetworkProfileCorrelation; alert: CorrelationAlert | null } {
      const centralityScore =
        networkNodesMap.get(profile.mepId) ??
        centralMEPs.find(c => c.mepId === profile.mepId)?.centralityScore ??
        0;
      const committeeScore = profile.scores['committee'] ?? 0;
      const isHighCentrality = centralityScore > 0.5;
      const isHighCommitteeActivity = committeeScore > 60;
      const isBridging = bridgingIds.has(profile.mepId);
      const significance = getProfileSignificance(isHighCentrality, isHighCommitteeActivity, isBridging);

      const correlation: NetworkProfileCorrelation = {
        mepId: profile.mepId,
        mepName: profile.name,
        centralityScore,
        committeeActivityScore: committeeScore,
        isBridgingMep: isBridging,
        profileSignificance: significance,
      };

      const alert: CorrelationAlert | null =
        significance === 'HIGH'
          ? {
              alertType: 'COMPREHENSIVE_PROFILE',
              severity: 'HIGH',
              mepId: profile.mepId,
              mepName: profile.name,
              evidence: [
                `Network centrality score: ${String(centralityScore)} (> 0.5 threshold)`,
                `Committee activity score: ${String(committeeScore)}/100 (cross-committee active)`,
                `Bridging MEP: ${String(isBridging)} — connects multiple political clusters`,
              ],
              recommendation:
                'Generate a comprehensive intelligence profile. High network centrality combined with cross-committee activity indicates a key informal power broker warranting deeper analysis.',
            }
          : null;

      return { correlation, alert };
    }

    /**
     * Executes **Correlation Scenario 3**: Network Centrality × Comparative Intelligence.
     *
     * Fetches global network analysis and comparative intelligence profiles for the given
     * MEP IDs in sequence. For each MEP, centrality is looked up from the full
     * `networkNodes` map before falling back to the truncated `centralMEPs` top-10 list,
     * so MEPs outside the top-10 are not silently scored as 0.
     *
     * If fewer than 2 valid numeric MEP IDs are provided, or either tool call fails,
     * an empty result is returned (fail-safe).
     *
     * @param mepIds - String MEP IDs; non-numeric values are filtered out
     * @returns Object containing correlation records, alerts, and confidence-level strings
     */
    async function correlateNetworkProfiles(
      mepIds: string[]
    ): Promise<{
      correlations: NetworkProfileCorrelation[];
      alerts: CorrelationAlert[];
      toolConfidenceLevels: ConfidenceLevel[];
    }> {
      const numericIds = mepIds.map(id => parseInt(id, 10)).filter(n => !isNaN(n));

      let networkData: NetworkResult;
      try {
        const nr = await handleNetworkAnalysis({});
        networkData = parseToolResult(nr) as NetworkResult;
      } catch (error: unknown) {
        auditLogger.logError('correlate_intelligence.fetch_network_data', { mepIds: numericIds, mepIdCount: numericIds.length }, toErrorMessage(error));
        return { correlations: [], alerts: [], toolConfidenceLevels: [] };
      }

      if (numericIds.length < 2) return { correlations: [], alerts: [], toolConfidenceLevels: [] };

      let comparativeData: ComparativeResult;
      try {
        const cr = await handleComparativeIntelligence({ mepIds: numericIds });
        comparativeData = parseToolResult(cr) as ComparativeResult;
      } catch (error: unknown) {
        auditLogger.logError('correlate_intelligence.fetch_comparative_data', { mepIds: numericIds }, toErrorMessage(error));
        return { correlations: [], alerts: [], toolConfidenceLevels: [] };
      }

      const toolConfidenceLevels = [networkData.confidenceLevel, comparativeData.confidenceLevel];

      const networkNodesMap = new Map<string, number>(
        (networkData.networkNodes ?? []).map(n => [n.mepId, n.centralityScore])
      );
      const bridgingIds = new Set(networkData.bridgingMEPs.map(b => b.mepId));

      const profileResults = comparativeData.profiles.map(
        profile => buildProfileAndAlert(profile, networkNodesMap, networkData.centralMEPs, bridgingIds)
      );
      const correlations = profileResults.map(r => r.correlation);
      const alerts = profileResults.flatMap(r => (r.alert !== null ? [r.alert] : []));

      return { correlations, alerts, toolConfidenceLevels };
    }

    /**
     * Derives the aggregate confidence level from across all tool results in the pipeline.
     *
     * - **`'HIGH'`** — at least one level is `'HIGH'` and no level is `'LOW'`
     * - **`'LOW'`** — every level is `'LOW'` (no useful high/medium signal)
     * - **`'MEDIUM'`** — any other combination (mixed or all `'MEDIUM'`)
     *
     * @param levels - Array of confidence-level strings from individual tool results
     * @returns Aggregated confidence level
     */
    function aggregateConfidence(levels: ConfidenceLevel[]): ConfidenceLevel {
      if (levels.includes('HIGH') && !levels.includes('LOW')) return 'HIGH';
      if (levels.every(l => l === 'LOW')) return 'LOW';
      return 'MEDIUM';
    }

    /**
     * Derive an explicit DataAvailability marker from correlation results.
     * - `'AVAILABLE'`   — at least one correlation was produced from a successful tool response.
     * - `'UNAVAILABLE'` — all dependent tool calls failed; no confidence levels were collected,
     *                     meaning there is no data whatsoever to base correlations on.
     * - `'PARTIAL'`     — dependent tools responded (confidence levels collected) but the
     *                     responses contained no actionable correlation signals.
     */
    function computeDataAvailability(
      correlationsFound: number,
      confidenceLevels: ConfidenceLevel[]
    ): DataAvailability {
      if (correlationsFound > 0) return 'AVAILABLE';
      if (confidenceLevels.length === 0) return 'UNAVAILABLE';
      return 'PARTIAL';
    }

    /**
     * Aggregate data-quality warnings based on the correlation run context.
     *
     * Warnings are generated when:
     * - Data availability is `PARTIAL` or `UNAVAILABLE` (downstream tools failed or had no signals)
     * - Any collected confidence level is `LOW` (indicating proxy/heuristic data in a sub-tool)
     * - Network analysis was excluded (consumer may expect it)
     */
    function buildCorrelationWarnings(
      dataAvailability: DataAvailability,
      confidenceLevels: ConfidenceLevel[],
      includeNetworkAnalysis: boolean
    ): string[] {
      const warnings: string[] = [];

      if (dataAvailability === 'UNAVAILABLE') {
        warnings.push('All downstream tool calls failed — no data available for correlation analysis');
      } else if (dataAvailability === 'PARTIAL') {
        warnings.push('Downstream tools responded but produced no actionable correlations — results may be incomplete');
      }

      const lowCount = confidenceLevels.filter(c => c === 'LOW').length;
      if (lowCount > 0) {
        warnings.push(`${String(lowCount)} of ${String(confidenceLevels.length)} sub-tool results have LOW confidence — underlying data is proxy or heuristic`);
      }

      if (!includeNetworkAnalysis) {
        warnings.push('Network analysis was not included — committee co-membership correlations are absent');
      }

      return warnings;
    }

    /**
     * Build the final tool response, returning an error when data is unavailable.
     *
     * When `dataAvailability` is `'UNAVAILABLE'` (all downstream tools failed),
     * the function returns `buildErrorResponse` with `isError: true` so AI agents
     * do not confuse "no data fetched" with "no anomalies found".
     */
    function buildCorrelationResponse(
      report: CorrelatedIntelligenceReport
    ): ToolResult {
      if (report.dataAvailability === 'UNAVAILABLE') {
        return buildErrorResponse(
          new ToolError({
            toolName: 'correlate_intelligence',
            operation: 'correlateIntelligence',
            message: 'All downstream intelligence tools failed — no data available for correlation analysis. ' +
              'The result should not be interpreted as "no anomalies found".',
            errorCode: 'UPSTREAM_503',
            httpStatus: 503,
          }),
          'correlate_intelligence',
        );
      }
      return buildToolResponse(report);
    }

    /**
     * Builds the summary block of the {@link CorrelatedIntelligenceReport}.
     *
     * Counts alerts by severity and records the total number of cross-tool
     * correlations that were detected (including those below alert threshold).
     *
     * @param allAlerts - Flat list of all generated correlation alerts
     * @param correlationsFound - Total count of correlations detected across all scenarios
     * @returns Report summary object
     */
    function buildAlertSummary(allAlerts: CorrelationAlert[], correlationsFound: number): CorrelatedIntelligenceReport['summary'] {
      return {
        totalAlerts: allAlerts.length,
        criticalAlerts: allAlerts.filter(a => a.severity === 'CRITICAL').length,
        highAlerts: allAlerts.filter(a => a.severity === 'HIGH').length,
        mediumAlerts: allAlerts.filter(a => a.severity === 'MEDIUM').length,
        lowAlerts: allAlerts.filter(a => a.severity === 'LOW').length,
        correlationsFound,
      };
    }

    /**
     * Builds the methodology description string for the correlation report.
     *
     * Describes the tools orchestrated and the numeric thresholds applied so that
     * downstream consumers can reproduce or audit the analysis.
     *
     * @param influenceThreshold - Minimum influence score for Scenario 1 alerts
     * @param sensitivityLevel - EWS sensitivity level used for Scenario 2 alerts
     * @param includeNetworkAnalysis - Whether Scenario 3 (network × profiles) was enabled
     * @returns Human-readable methodology string
     */
    function buildMethodology(influenceThreshold: number, sensitivityLevel: string, includeNetworkAnalysis: boolean): string {
      const networkTools = includeNetworkAnalysis ? ', network_analysis, comparative_intelligence' : '';
      return `Cross-tool OSINT correlation engine — orchestrates assess_mep_influence, detect_voting_anomalies, early_warning_system, analyze_coalition_dynamics${networkTools}. Correlation thresholds: influence ≥ ${String(influenceThreshold)} (sensitivity: ${sensitivityLevel}). Data source: European Parliament Open Data Portal (data.europarl.europa.eu).`;
    }

    /**
     * Handles the `correlate_intelligence` MCP tool request.
     *
     * Orchestrates six OSINT tools — `assess_mep_influence`,
     * `detect_voting_anomalies`, `early_warning_system`,
     * `analyze_coalition_dynamics`, `network_analysis`, and
     * `comparative_intelligence` — and cross-correlates their outputs to produce
     * consolidated intelligence alerts.
     *
     * Three correlation scenarios are evaluated:
     * 1. **Influence × Anomaly** — When an MEP's influence score exceeds the
     *    sensitivity threshold and voting anomalies are detected simultaneously,
     *    an `ELEVATED_ATTENTION` alert is raised.
     * 2. **Coalition Fracture** — When the early warning system flags coalition
     *    instability and coalition dynamics shows declining cohesion for the same
     *    groups, a `COALITION_FRACTURE` alert is generated.
     * 3. **Comprehensive Profile** — When network analysis reveals high centrality
     *    and comparative intelligence confirms cross-committee activity for the
     *    same MEP, a `COMPREHENSIVE_PROFILE` alert is issued.
     *
     * @param args - Raw tool arguments, validated against
     *   {@link CorrelateIntelligenceSchema}
     * @returns MCP tool result containing a {@link CorrelatedIntelligenceReport}
     *   with alerts, correlations, and standard OSINT output fields
     * @throws If `args` fails schema validation
     * @throws If all underlying EP API calls fail simultaneously
     *
     * @example
     * ```typescript
     * // Correlate two MEPs with default MEDIUM sensitivity
     * const result = await handleCorrelateIntelligence({
     *   mepIds: ['197558', '124810'],
     * });
     * const report = JSON.parse(result.content[0].text);
     * console.log(`Alerts: ${report.summary.totalAlerts}`);
     * ```
     *
     * @example
     * ```typescript
     * // High-sensitivity scan with network analysis and explicit group scope
     * const result = await handleCorrelateIntelligence({
     *   mepIds: ['197558', '124810', '23456'],
     *   groups: ['EPP', 'S&D', 'Renew'],
     *   sensitivityLevel: 'HIGH',
     *   includeNetworkAnalysis: true,
     * });
     * ```
     *
     * @security Input validated by Zod. Cross-tool access to MEP personal data
     *   is minimised per GDPR Article 5(1)(c). EP data-access operations are
     *   logged through the underlying EP API client per ISMS Policy AU-002.
     * @since 1.0.0
     * @see {@link correlateIntelligenceToolMetadata} for MCP schema registration
     * @see {@link handleAssessMepInfluence} for the influence dimension
     * @see {@link handleDetectVotingAnomalies} for the anomaly dimension
     * @see {@link handleEarlyWarningSystem} for coalition risk signals
     */
    export async function handleCorrelateIntelligence(
      args: unknown
    ): Promise<ToolResult> {
      const params = CorrelateIntelligenceSchema.parse(args);
      const { mepIds, groups, sensitivityLevel, includeNetworkAnalysis } = params;

      const resolvedGroups = groups ?? DEFAULT_COALITION_GROUPS;
      const influenceThreshold = INFLUENCE_THRESHOLDS[sensitivityLevel];
      const analysisTime = new Date().toISOString();
      const correlationId = `CORR-${randomUUID().replace(/-/g, '').toUpperCase().slice(0, 12)}`;

      const influenceAnomalyResults = await Promise.all(
        mepIds.map((mepId) => correlateInfluenceAnomaly(mepId, influenceThreshold)),
      );
      const influenceAnomalyCorrelations: InfluenceAnomalyCorrelation[] = [];
      const influenceAnomalyAlerts: CorrelationAlert[] = [];
      const influenceToolConfidenceLevels: ConfidenceLevel[] = [];

      for (const { correlation, alert, toolConfidenceLevels } of influenceAnomalyResults) {
        if (correlation !== null) influenceAnomalyCorrelations.push(correlation);
        if (alert !== null) influenceAnomalyAlerts.push(alert);
        influenceToolConfidenceLevels.push(...toolConfidenceLevels);
      }

      const { correlation: coalitionCorrelation, alert: coalitionAlert, toolConfidenceLevels: coalitionConfidenceLevels } =
        await correlateCoalitionFracture(resolvedGroups, sensitivityLevel);

      const { correlations: networkCorrelations, alerts: networkAlerts, toolConfidenceLevels: networkConfidenceLevels } =
        includeNetworkAnalysis
          ? await correlateNetworkProfiles(mepIds)
          : { correlations: [], alerts: [], toolConfidenceLevels: [] };

      const allAlerts: CorrelationAlert[] = [
        ...influenceAnomalyAlerts,
        ...(coalitionAlert !== null ? [coalitionAlert] : []),
        ...networkAlerts,
      ];

      const correlationsFound =
        influenceAnomalyCorrelations.length +
        (coalitionCorrelation !== null ? 1 : 0) +
        networkCorrelations.length;

      const confidenceLevels: ConfidenceLevel[] = [
        ...influenceToolConfidenceLevels,
        ...coalitionConfidenceLevels,
        ...networkConfidenceLevels,
      ];

      const dataAvailability = computeDataAvailability(correlationsFound, confidenceLevels);

      const report: CorrelatedIntelligenceReport = {
        correlationId,
        analysisTime,
        scope: {
          mepIds,
          groups: resolvedGroups,
          sensitivityLevel,
          networkAnalysisIncluded: includeNetworkAnalysis,
        },
        alerts: allAlerts,
        correlations: {
          influenceAnomaly: influenceAnomalyCorrelations,
          coalitionFracture: coalitionCorrelation,
          networkProfiles: networkCorrelations,
        },
        summary: buildAlertSummary(allAlerts, correlationsFound),
        confidenceLevel: aggregateConfidence(confidenceLevels.length > 0 ? confidenceLevels : ['LOW']),
        dataAvailability,
        methodology: buildMethodology(influenceThreshold, sensitivityLevel, includeNetworkAnalysis),
        dataFreshness: `Real-time EP API data — correlated at ${analysisTime}`,
        sourceAttribution: 'European Parliament Open Data Portal - data.europarl.europa.eu',
        dataQualityWarnings: buildCorrelationWarnings(dataAvailability, confidenceLevels, includeNetworkAnalysis),
      };

      try {
        OsintStandardOutputSchema.parse({
          confidenceLevel: report.confidenceLevel,
          methodology: report.methodology,
          dataFreshness: report.dataFreshness,
          sourceAttribution: report.sourceAttribution,
          dataQualityWarnings: report.dataQualityWarnings,
        });
      } catch (validationError: unknown) {
        throw new ToolError({
          toolName: 'correlate_intelligence',
          operation: 'validateOsintOutput',
          message: 'Report failed OSINT standard output schema validation',
          isRetryable: false,
          cause: validationError,
        });
      }

      return buildCorrelationResponse(report);
    }

    /**
     * MCP tool metadata for `correlate_intelligence` registration.
     */
    export const correlateIntelligenceToolMetadata = {
      name: 'correlate_intelligence',
      description:
        'Cross-tool OSINT intelligence correlation engine. Combines outputs from ' +
        'assess_mep_influence + detect_voting_anomalies (ELEVATED_ATTENTION alerts), ' +
        'early_warning_system + analyze_coalition_dynamics (COALITION_FRACTURE alerts), ' +
        'and optionally network_analysis + comparative_intelligence (COMPREHENSIVE_PROFILE alerts). ' +
        'Returns consolidated intelligence alerts with evidence chains and recommendations.',
      inputSchema: {
        type: 'object' as const,
        properties: {
          mepIds: {
            type: 'array',
            items: { type: 'string', minLength: 1, maxLength: 100 },
            minItems: 1,
            maxItems: 5,
            description: 'MEP identifiers to cross-correlate (1–5 MEPs)',
          },
          groups: {
            type: 'array',
            items: { type: 'string', minLength: 1, maxLength: 50 },
            maxItems: 8,
            description: 'Political groups for coalition fracture analysis (omit to use all major groups)',
          },
          sensitivityLevel: {
            type: 'string',
            enum: ['HIGH', 'MEDIUM', 'LOW'],
            default: 'MEDIUM',
            description: 'Alert sensitivity — HIGH surfaces more signals, LOW reduces noise',
          },
          includeNetworkAnalysis: {
            type: 'boolean',
            default: false,
            description: 'Run network centrality analysis (increases response time)',
          },
        },
        required: ['mepIds'],
      },
    };