All files / src/tools detectVotingAnomalies.ts

83.33% Statements 75/90
72.46% Branches 50/69
94.44% Functions 17/18
90.41% Lines 66/73

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                                                                                                    7x                           7x                 14x 14x 7x             14x 14x 14x 7x             7x                           8x   8x 7x                   1x                       8x 8x 8x                     8x                       8x 8x 8x 7x                   1x                       8x   8x 8x 8x 8x 8x 8x 8x 8x                 9x 8x 8x 9x           9x                       6x 6x 1x   6x 6x     6x                 14x 14x 14x   14x       14x     14x               14x 7x   7x                                                                             17x   17x 17x 17x 17x   17x         6x                                             14x 14x   14x                                           14x   1x 1x             4x                                                                            
/**
 * MCP Tool: detect_voting_anomalies
 * 
 * Flag unusual voting patterns — party defections, sudden alignment shifts,
 * abstention spikes, and behavioral anomalies.
 * 
 * **Intelligence Perspective:** Anomaly detection tool identifying deviations from
 * expected voting behavior—enables early warning for party splits, political
 * realignments, and emerging cross-party movements.
 * 
 * ISMS Policy: SC-002 (Input Validation), AC-003 (Least Privilege)
 */
 
import { DetectVotingAnomaliesSchema } from '../schemas/europeanParliament.js';
import { epClient } from '../clients/europeanParliamentClient.js';
import { buildToolResponse } from './shared/responseBuilder.js';
import type { ToolResult } from './shared/types.js';
 
interface VotingAnomaly {
  type: string;
  severity: string;
  mepId: string;
  mepName: string;
  description: string;
  metrics: { expectedValue: number; actualValue: number; deviation: number };
  detectedDate: string;
}
 
interface VotingAnomalyAnalysis {
  period: { from: string; to: string };
  targetScope: string;
  anomalies: VotingAnomaly[];
  summary: { totalAnomalies: number; highSeverity: number; mediumSeverity: number; lowSeverity: number };
  computedAttributes: {
    anomalyRate: number;
    severityIndex: number;
    groupStabilityScore: number;
    defectionTrend: string;
    riskLevel: string;
  };
  confidenceLevel: string;
  dataFreshness: string;
  sourceAttribution: string;
  methodology: string;
}
 
/**
 * Classify attendance severity
 */
function classifyAttendanceSeverity(rate: number): string {
  return rate < 50 ? 'HIGH' : 'MEDIUM';
}
 
/**
 * Classify abstention severity
 */
function classifyAbstentionSeverity(rate: number): string {
  return rate > 30 ? 'HIGH' : 'MEDIUM';
}
 
/**
 * Classify defection severity
 */
function classifyDefectionSeverity(rate: number): string {
  Eif (rate > 40) return 'HIGH';
  if (rate > 25) return 'MEDIUM';
  return 'LOW';
}
 
/**
 * Classify defection trend
 */
function classifyDefectionTrend(highCount: number): string {
  Iif (highCount > 2) return 'INCREASING';
  if (highCount > 0) return 'STABLE';
  return 'DECREASING';
}
 
/**
 * Classify risk level
 */
function classifyRiskLevel(highCount: number): string {
  Iif (highCount > 3) return 'CRITICAL';
  Iif (highCount > 1) return 'ELEVATED';
  if (highCount > 0) return 'MODERATE';
  return 'LOW';
}
 
/**
 * Determine confidence based on data volume, not anomaly count
 */
function getDataVolumeConfidence(scope: string, isSingleMep: boolean): string {
  Eif (isSingleMep) return 'MEDIUM';
  if (scope === 'All MEPs') return 'HIGH';
  return 'MEDIUM';
}
 
/**
 * Check for low attendance anomaly
 */
function checkAttendanceAnomaly(
  mep: { id: string; name: string; politicalGroup: string },
  stats: { attendanceRate: number },
  threshold: number,
  detectedDate: string
): VotingAnomaly | undefined {
  const expectedAttendance = Math.round((1 - threshold) * 100 * 100) / 100;
 
  if (stats.attendanceRate < expectedAttendance) {
    return {
      type: 'LOW_ATTENDANCE',
      severity: classifyAttendanceSeverity(stats.attendanceRate),
      mepId: mep.id,
      mepName: mep.name,
      description: `Attendance rate ${String(stats.attendanceRate)}% below expected threshold of ${String(expectedAttendance)}% for ${mep.politicalGroup}`,
      metrics: { expectedValue: expectedAttendance, actualValue: stats.attendanceRate, deviation: Math.round((expectedAttendance - stats.attendanceRate) * 100) / 100 },
      detectedDate
    };
  }
  return undefined;
}
 
/**
 * Check for high abstention anomaly
 */
function checkAbstentionAnomaly(
  mep: { id: string; name: string },
  stats: { abstentions: number; totalVotes: number },
  threshold: number,
  detectedDate: string
): VotingAnomaly | undefined {
  Iif (stats.totalVotes === 0) return undefined;
  const rate = (stats.abstentions / stats.totalVotes) * 100;
  Iif (rate > threshold * 50) {
    return {
      type: 'ABSTENTION_SPIKE',
      severity: classifyAbstentionSeverity(rate),
      mepId: mep.id,
      mepName: mep.name,
      description: `Abstention rate of ${String(Math.round(rate))}% significantly above group average`,
      metrics: { expectedValue: 10, actualValue: Math.round(rate * 100) / 100, deviation: Math.round((rate - 10) * 100) / 100 },
      detectedDate
    };
  }
  return undefined;
}
 
/**
 * Check for party defection anomaly
 */
function checkDefectionAnomaly(
  mep: { id: string; name: string; politicalGroup: string },
  stats: { votesFor: number; votesAgainst: number },
  threshold: number,
  detectedDate: string
): VotingAnomaly | undefined {
  const decisive = stats.votesFor + stats.votesAgainst;
  const rate = decisive > 0 ? (stats.votesAgainst / decisive) * 100 : 0;
  if (rate > threshold * 60) {
    return {
      type: 'PARTY_DEFECTION',
      severity: classifyDefectionSeverity(rate),
      mepId: mep.id,
      mepName: mep.name,
      description: `Defection rate of ${String(Math.round(rate))}% — voting against ${mep.politicalGroup} party line`,
      metrics: { expectedValue: 10, actualValue: Math.round(rate * 100) / 100, deviation: Math.round((rate - 10) * 100) / 100 },
      detectedDate
    };
  }
  return undefined;
}
 
/**
 * Detect anomalies from voting statistics
 */
function detectMepAnomalies(
  mep: { id: string; name: string; politicalGroup: string },
  stats: { totalVotes: number; votesFor: number; votesAgainst: number; abstentions: number; attendanceRate: number } | undefined,
  threshold: number,
  detectedDate: string
): VotingAnomaly[] {
  Iif (stats === undefined || stats.totalVotes === 0) return [];
 
  const anomalies: VotingAnomaly[] = [];
  const att = checkAttendanceAnomaly(mep, stats, threshold, detectedDate);
  if (att !== undefined) anomalies.push(att);
  const abs = checkAbstentionAnomaly(mep, stats, threshold, detectedDate);
  Iif (abs !== undefined) anomalies.push(abs);
  const def = checkDefectionAnomaly(mep, stats, threshold, detectedDate);
  if (def !== undefined) anomalies.push(def);
  return anomalies;
}
 
/**
 * Detect anomalies for a single MEP
 */
async function detectSingleMepAnomalies(
  mepId: string, threshold: number, period: { from: string; to: string }
): Promise<{ scope: string; anomalies: VotingAnomaly[]; dataAvailable: boolean }> {
  const mep = await epClient.getMEPDetails(mepId);
  const mepStats = mep.votingStatistics;
  const dataAvailable = mepStats !== undefined && mepStats.totalVotes > 0;
  const anomalies = detectMepAnomalies(
    { id: mep.id, name: mep.name, politicalGroup: mep.politicalGroup },
    mepStats,
    threshold,
    period.to
  );
  return { scope: `MEP: ${mepId}`, anomalies, dataAvailable };
}
 
/**
 * Detect anomalies for a group or all MEPs.
 * Note: The EP API /meps/{id} endpoint does not provide per-MEP voting
 * statistics, so group-level anomaly detection reports data unavailability
 * with LOW confidence rather than fabricating values.
 */
async function detectGroupAnomalies(
  groupId: string | undefined, _threshold: number, _period: { from: string; to: string }
): Promise<{ scope: string; anomalies: VotingAnomaly[]; mepCount: number }> {
  const groupFilter: { group?: string } = {};
  if (groupId !== undefined) {
    groupFilter.group = groupId;
  }
  const scope = groupId !== undefined ? `Group: ${groupId}` : 'All MEPs';
  const mepsResult = await epClient.getMEPs({ ...groupFilter, limit: 50 });
  // Per-MEP voting statistics are not available from the EP API /meps/{id}
  // endpoint, so we cannot detect group-wide anomalies from individual stats.
  return { scope, anomalies: [], mepCount: mepsResult.data.length };
}
 
/**
 * Build the anomaly analysis result object from anomaly detection results.
 */
function buildAnomalySummary(
  anomalies: VotingAnomaly[]
): { highSeverity: number; mediumSeverity: number; lowSeverity: number; anomalyRate: number; severityIndex: number } {
  const highSeverity = anomalies.filter(a => a.severity === 'HIGH').length;
  const mediumSeverity = anomalies.filter(a => a.severity === 'MEDIUM').length;
  const lowSeverity = anomalies.filter(a => a.severity === 'LOW').length;
  // anomalyRate: true proportion of HIGH-severity anomalies in [0, 1]
  const anomalyRate = anomalies.length > 0
    ? Math.round((highSeverity / anomalies.length) * 100) / 100
    : 0;
  // severityIndex: weighted-average severity on ~1–3 scale
  const severityIndex = anomalies.length > 0
    ? Math.round((highSeverity * 3 + mediumSeverity * 2 + lowSeverity) / anomalies.length * 100) / 100
    : 0;
  return { highSeverity, mediumSeverity, lowSeverity, anomalyRate, severityIndex };
}
 
/**
 * Resolve confidence level: MEDIUM when a single MEP has detectable anomalies
 * (indicating voting data was available and yielded results); LOW otherwise.
 */
function resolveConfidence(isSingleMep: boolean, scope: string, anomalyCount: number): string {
  if (isSingleMep && anomalyCount > 0) {
    return getDataVolumeConfidence(scope, true);
  }
  return 'LOW';
}
 
/**
 * Handles the detect_voting_anomalies MCP tool request.
 *
 * Detects statistically unusual voting patterns for individual MEPs or entire
 * political groups, including cross-party defections, unusual abstention clusters,
 * and discipline breakdowns. Returns anomaly records graded by severity with a
 * group stability score and defection trend assessment.
 *
 * @param args - Raw tool arguments, validated against {@link DetectVotingAnomaliesSchema}
 * @returns MCP tool result containing detected anomalies with severity ratings,
 *   summary statistics, anomaly rate, severity index, and risk level classification
 * @throws - If `args` fails schema validation (e.g., missing required fields or invalid format)
 * - If the European Parliament API is unreachable or returns an error response
 *
 * @example
 * ```typescript
 * const result = await handleDetectVotingAnomalies({
 *   mepId: '124810',
 *   sensitivityThreshold: 0.7,
 *   dateFrom: '2024-01-01',
 *   dateTo: '2024-12-31'
 * });
 * // Returns anomaly list with severity ratings (HIGH/MEDIUM/LOW),
 * // anomaly rate, severity index, and group stability score
 * ```
 *
 * @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 detectVotingAnomaliesToolMetadata} for MCP schema registration
 * @see {@link handleAnalyzeCoalitionDynamics} for coalition-level cohesion and stress analysis
 */
export async function handleDetectVotingAnomalies(
  args: unknown
): Promise<ToolResult> {
  const params = DetectVotingAnomaliesSchema.parse(args);
 
  try {
    const period = { from: params.dateFrom ?? '2024-01-01', to: params.dateTo ?? '2024-12-31' };
    const mepId = params.mepId;
    const isSingleMep = mepId !== undefined;
 
    const result = mepId !== undefined
      ? await detectSingleMepAnomalies(mepId, params.sensitivityThreshold, period)
      : await detectGroupAnomalies(params.groupId, params.sensitivityThreshold, period);
 
    // When single MEP has no voting data, report unavailability with same shape as normal path
    Iif (isSingleMep && 'dataAvailable' in result && !result.dataAvailable) {
      return buildToolResponse({
        period,
        targetScope: mepId,
        anomalies: [],
        summary: { totalAnomalies: 0, highSeverity: 0, mediumSeverity: 0, lowSeverity: 0 },
        computedAttributes: {
          anomalyRate: 0,
          severityIndex: 0,
          groupStabilityScore: 0,
          defectionTrend: 'UNKNOWN',
          riskLevel: 'UNKNOWN'
        },
        dataAvailable: false,
        confidenceLevel: 'LOW',
        dataFreshness: 'EP API data — voting statistics unavailable for this MEP',
        sourceAttribution: 'European Parliament Open Data Portal - data.europarl.europa.eu',
        methodology: 'The EP API /meps/{id} endpoint does not return voting statistics. '
          + 'Anomaly detection requires voting data which is unavailable for this MEP. '
          + 'Data source: European Parliament Open Data Portal.'
      });
    }
 
    const { highSeverity, mediumSeverity, lowSeverity, anomalyRate, severityIndex } = buildAnomalySummary(result.anomalies);
    const confidence = resolveConfidence(isSingleMep, result.scope, result.anomalies.length);
 
    const analysis: VotingAnomalyAnalysis = {
      period,
      targetScope: result.scope,
      anomalies: result.anomalies,
      summary: { totalAnomalies: result.anomalies.length, highSeverity, mediumSeverity, lowSeverity },
      computedAttributes: {
        anomalyRate,
        severityIndex,
        groupStabilityScore: Math.round((1 - severityIndex / 3) * 100 * 100) / 100,
        defectionTrend: classifyDefectionTrend(highSeverity),
        riskLevel: classifyRiskLevel(highSeverity)
      },
      confidenceLevel: confidence,
      dataFreshness: 'Real-time EP API data — voting statistics from MEP records',
      sourceAttribution: 'European Parliament Open Data Portal - data.europarl.europa.eu',
      methodology: 'Heuristic statistical analysis using aggregated voting statistics and MEP metadata '
        + 'from /meps/{id} on the European Parliament Open Data API. Vote-level records are not fetched; '
        + 'many voting statistic fields may be zero or unavailable from the EP API. Group-level analysis '
        + 'reflects data availability — detected anomalies are approximate and indicative only. '
        + 'Data source: European Parliament Open Data Portal (MEP metadata endpoints).'
    };
 
    return buildToolResponse(analysis);
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : 'Unknown error';
    throw new Error(`Failed to detect voting anomalies: ${errorMessage}`);
  }
}
 
/**
 * Tool metadata for MCP registration
 */
export const detectVotingAnomaliesToolMetadata = {
  name: 'detect_voting_anomalies',
  description: 'Detect unusual voting patterns including party defections, abstention spikes, and low attendance anomalies. Configurable sensitivity threshold with severity classification (HIGH/MEDIUM/LOW). Returns anomaly details, group stability score, defection trend, and risk level assessment.',
  inputSchema: {
    type: 'object' as const,
    properties: {
      mepId: {
        type: 'string',
        description: 'MEP identifier (omit for broad analysis)',
        minLength: 1,
        maxLength: 100
      },
      groupId: {
        type: 'string',
        description: 'Political group to analyze',
        minLength: 1,
        maxLength: 50
      },
      dateFrom: {
        type: 'string',
        description: 'Analysis start date (YYYY-MM-DD format)',
        pattern: '^\\d{4}-\\d{2}-\\d{2}$'
      },
      dateTo: {
        type: 'string',
        description: 'Analysis end date (YYYY-MM-DD format)',
        pattern: '^\\d{4}-\\d{2}-\\d{2}$'
      },
      sensitivityThreshold: {
        type: 'number',
        description: 'Anomaly sensitivity (0-1, lower = more anomalies detected)',
        minimum: 0,
        maximum: 1,
        default: 0.3
      }
    }
  }
};