All files / src/tools analyzeCountryDelegation.ts

96.51% Statements 83/86
86.95% Branches 40/46
100% Functions 17/17
100% Lines 73/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                                                  4x                                                                                                                             16x 16x 139x 139x     16x 16x 30x         17x             30x 16x   15x 15x 30x 30x   15x   15x 14x 3x             16x 16x 15x 15x             16x 4x 3x             16x 2x 2x             16x 2x 2x                 16x 16x 16x   16x 24x 24x 93x   24x 93x 91x       24x                 16x 16x 16x 91x 141x   91x 50x     16x                     17x         16x 17x   17x   16x         16x 91x 91x   16x 88x     17x         17x 17x     17x   17x                                                                                                                                           21x   21x 21x         21x   21x           16x                         4x                                            
/**
 * MCP Tool: analyze_country_delegation
 *
 * Analyze how a country's MEP delegation votes, collaborates, and
 * distributes across political groups—revealing national voting patterns
 * and cross-group alignment within a member state's EP representation.
 *
 * **Intelligence Perspective:** Country delegation analysis uncovers national
 * interest patterns that cut across political group lines—essential for
 * identifying when national priorities override party discipline.
 *
 * **Business Perspective:** Enables government affairs teams to understand
 * a country's collective position on policy domains for targeted advocacy.
 *
 * ISMS Policy: SC-002 (Input Validation), AC-003 (Least Privilege)
 */
 
import { z } from 'zod';
import { epClient } from '../clients/europeanParliamentClient.js';
import type { MEPDetails } from '../types/europeanParliament.js';
import type { ToolResult } from './shared/types.js';
 
/**
 * Schema for analyze_country_delegation tool input
 */
export const AnalyzeCountryDelegationSchema = z.object({
  country: z.string()
    .length(2)
    .regex(/^[A-Z]{2}$/, 'Country code must be 2 uppercase letters')
    .describe('ISO 3166-1 alpha-2 country code (e.g., "SE", "DE", "FR")'),
  dateFrom: z.string()
    .regex(/^\d{4}-\d{2}-\d{2}$/, 'Date must be in YYYY-MM-DD format')
    .optional()
    .describe('Start date for analysis period'),
  dateTo: z.string()
    .regex(/^\d{4}-\d{2}-\d{2}$/, 'Date must be in YYYY-MM-DD format')
    .optional()
    .describe('End date for analysis period')
});
 
/**
 * Political group distribution entry
 */
interface GroupDistribution {
  group: string;
  count: number;
  percentage: number;
}
 
/**
 * Country delegation analysis result
 */
interface CountryDelegationAnalysis {
  country: string;
  period: { from: string; to: string };
  delegation: {
    totalMEPs: number;
    activeMEPs: number;
    groupDistribution: GroupDistribution[];
  };
  votingBehavior: {
    averageAttendance: number;
    averageLoyalty: number;
    nationalCohesion: number;
  };
  committeePresence: {
    committeesRepresented: number;
    leadershipRoles: number;
  };
  computedAttributes: {
    delegationInfluence: string;
    nationalCohesionLevel: string;
    groupFragmentation: string;
    engagementLevel: string;
  };
  confidenceLevel: 'HIGH' | 'MEDIUM' | 'LOW';
  dataFreshness: string;
  sourceAttribution: string;
  methodology: string;
  dataQualityWarnings: string[];
}
 
/**
 * Compute group distribution from MEP list
 */
function computeGroupDistribution(
  meps: { politicalGroup: string }[]
): GroupDistribution[] {
  const counts = new Map<string, number>();
  for (const mep of meps) {
    const group = mep.politicalGroup;
    counts.set(group, (counts.get(group) ?? 0) + 1);
  }
 
  const total = meps.length;
  return Array.from(counts.entries())
    .map(([group, count]) => ({
      group,
      count,
      percentage: Math.round((count / Math.max(1, total)) * 10000) / 100
    }))
    .sort((a, b) => b.count - a.count);
}
 
/**
 * Compute group fragmentation index (Simpson's diversity)
 */
function computeFragmentation(distribution: GroupDistribution[]): string {
  const total = distribution.reduce((s, d) => s + d.count, 0);
  if (total === 0) return 'UNKNOWN';
 
  let sumSquares = 0;
  for (const d of distribution) {
    const p = d.count / total;
    sumSquares += p * p;
  }
  const diversity = 1 - sumSquares;
 
  if (diversity > 0.7) return 'HIGH';
  if (diversity > 0.4) return 'MODERATE';
  return 'LOW';
}
 
/**
 * Compute delegation influence level
 */
function computeInfluence(totalMEPs: number, leadershipRoles: number): string {
  const score = totalMEPs * 0.3 + leadershipRoles * 5;
  if (score > 30) return 'HIGH';
  Iif (score > 15) return 'MODERATE';
  return 'LOW';
}
 
/**
 * Compute confidence level from data coverage ratio
 */
function computeDataConfidence(dataCoverage: number): 'HIGH' | 'MEDIUM' | 'LOW' {
  if (dataCoverage > 0.8) return 'HIGH';
  if (dataCoverage > 0.4) return 'MEDIUM';
  return 'LOW';
}
 
/**
 * Compute engagement level from attendance
 */
function computeEngagement(avgAttendance: number): string {
  if (avgAttendance >= 80) return 'HIGH';
  Iif (avgAttendance >= 60) return 'MODERATE';
  return 'LOW';
}
 
/**
 * Compute national cohesion level
 */
function computeCohesionLevel(cohesion: number): string {
  if (cohesion >= 70) return 'HIGH';
  Iif (cohesion >= 50) return 'MODERATE';
  return 'LOW';
}
 
/**
 * Fetch MEP details, collecting fulfilled results
 */
async function fetchMepDetails(
  meps: { id: string }[]
): Promise<MEPDetails[]> {
  const details: MEPDetails[] = [];
  const batch = meps.slice(0, 50);
  const batchSize = 5;
 
  for (let i = 0; i < batch.length; i += batchSize) {
    const chunk = batch.slice(i, i + batchSize);
    const results = await Promise.allSettled(
      chunk.map((mep: { id: string }) => epClient.getMEPDetails(mep.id))
    );
    for (const r of results) {
      if (r.status === 'fulfilled') {
        details.push(r.value);
      }
    }
  }
  return details;
}
 
/**
 * Compute committee presence from MEP details
 */
function computeCommitteePresence(
  details: MEPDetails[]
): { committeesRepresented: number; leadershipRoles: number } {
  const allCommittees = new Set<string>();
  let leadershipRoles = 0;
  for (const mep of details) {
    for (const c of mep.committees) {
      allCommittees.add(c);
    }
    if (Array.isArray(mep.roles)) {
      leadershipRoles += mep.roles.length;
    }
  }
  return { committeesRepresented: allCommittees.size, leadershipRoles };
}
 
/**
 * Build delegation analysis from MEP details
 */
async function buildDelegationAnalysis(
  country: string,
  dateFrom: string,
  dateTo: string
): Promise<CountryDelegationAnalysis> {
  const mepResult = await epClient.getCurrentMEPs({
    country,
    limit: 100
  });
 
  const meps = Array.isArray(mepResult.data) ? mepResult.data : [];
  const totalMEPs = meps.length;
 
  const details = await fetchMepDetails(meps as { id: string }[]);
 
  const distribution = computeGroupDistribution(
    meps as { politicalGroup: string }[]
  );
 
  // Compute attendance averages
  const attendances = details
    .map(d => d.votingStatistics?.attendanceRate)
    .filter((a): a is number => a !== undefined);
 
  const avgAttendance = attendances.length > 0
    ? Math.round(attendances.reduce((s, a) => s + a, 0) / attendances.length * 100) / 100
    : 0;
 
  const committeePresence = computeCommitteePresence(details);
 
  // National cohesion - approximated from group concentration.
  // The +10 baseline accounts for empirical national-interest cohesion (e.g., structural funds,
  // CAP allocations) that cross-cuts political group lines even in fragmented delegations.
  const topGroupShare = distribution[0]?.percentage ?? 0;
  const nationalCohesion = Math.min(100, topGroupShare + 10);
 
  // Confidence based on data coverage, not just delegation size
  const dataCoverage = totalMEPs > 0 ? attendances.length / totalMEPs : 0;
 
  return {
    country,
    period: { from: dateFrom, to: dateTo },
    delegation: {
      totalMEPs,
      activeMEPs: totalMEPs,
      groupDistribution: distribution
    },
    votingBehavior: {
      averageAttendance: avgAttendance,
      // Loyalty approximated from group fragmentation; detailed roll-call analysis not yet available
      averageLoyalty: Math.round(Math.max(60, 95 - distribution.length * 5) * 100) / 100,
      nationalCohesion: Math.round(nationalCohesion * 100) / 100
    },
    committeePresence,
    computedAttributes: {
      delegationInfluence: computeInfluence(totalMEPs, committeePresence.leadershipRoles),
      nationalCohesionLevel: computeCohesionLevel(nationalCohesion),
      groupFragmentation: computeFragmentation(distribution),
      engagementLevel: computeEngagement(avgAttendance)
    },
    confidenceLevel: computeDataConfidence(dataCoverage),
    dataFreshness: 'Real-time EP API data — country delegation composition from current MEP records',
    sourceAttribution: 'European Parliament Open Data Portal - data.europarl.europa.eu',
    methodology: 'Country delegation analysis using EP Open Data: political group distribution, '
      + 'voting behavior aggregation, committee representation mapping, and national cohesion scoring. '
      + 'Data source: European Parliament Open Data Portal.',
    dataQualityWarnings: [
      ...(dataCoverage < 1 ? [`Voting statistics available for ${String(Math.round(dataCoverage * 100))}% of delegation MEPs`] : []),
      'National cohesion includes +10 baseline offset (proxy for national-interest voting beyond group lines)',
      ...(attendances.length === 0 ? ['No MEP voting statistics available — attendance is unavailable and loyalty is a proxy-derived estimate based on group fragmentation'] : []),
    ],
  };
}
 
/**
 * Handles the analyze_country_delegation MCP tool request.
 *
 * Analyses an EU member state's MEP delegation in the European Parliament, covering
 * political group distribution, aggregate voting behaviour, committee presence, and a
 * national cohesion score. Reveals national interest patterns that can cut across
 * political group lines, supporting targeted government-affairs advocacy.
 *
 * @param args - Raw tool arguments, validated against {@link AnalyzeCountryDelegationSchema}
 * @returns MCP tool result containing a {@link CountryDelegationAnalysis} object with
 *   delegation breakdown, computed attributes, confidence level, and methodology note
 * @throws - If `args` fails schema validation (e.g., missing required `country`, non-uppercase code)
 * - If the European Parliament API is unreachable or returns an error response
 *
 * @example
 * ```typescript
 * const result = await handleAnalyzeCountryDelegation({
 *   country: 'SE',
 *   dateFrom: '2024-01-01',
 *   dateTo: '2024-12-31'
 * });
 * // Returns political group distribution, voting behaviour, and cohesion score for Sweden's MEPs
 * ```
 *
 * @security Input is validated with Zod before any API call.
 *   Country code is validated against a strict regex to prevent injection.
 *   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 analyzeCountryDelegationToolMetadata} for MCP schema registration
 * @see {@link handleAnalyzeCommitteeActivity} for per-committee workload analysis
 */
export async function handleAnalyzeCountryDelegation(
  args: unknown
): Promise<ToolResult> {
  const params = AnalyzeCountryDelegationSchema.parse(args);
 
  const now = new Date();
  const dateFrom = params.dateFrom ?? new Date(
    now.getFullYear() - 1,
    now.getMonth(),
    now.getDate()
  ).toISOString().split('T')[0] ?? '';
  const dateTo = params.dateTo ?? now.toISOString().split('T')[0] ?? '';
 
  const analysis = await buildDelegationAnalysis(
    params.country,
    dateFrom,
    dateTo
  );
 
  return {
    content: [
      {
        type: 'text',
        text: JSON.stringify(analysis, null, 2)
      }
    ]
  };
}
 
/**
 * Tool metadata for MCP listing
 */
export const analyzeCountryDelegationToolMetadata = {
  name: 'analyze_country_delegation',
  description: 'Analyze a country\'s MEP delegation in the European Parliament — political group distribution, voting behavior, committee presence, and national cohesion. Reveals national interest patterns that cut across party lines.',
  inputSchema: {
    type: 'object' as const,
    properties: {
      country: {
        type: 'string',
        description: 'ISO 3166-1 alpha-2 country code (e.g., "SE", "DE", "FR")'
      },
      dateFrom: {
        type: 'string',
        description: 'Start date (YYYY-MM-DD)'
      },
      dateTo: {
        type: 'string',
        description: 'End date (YYYY-MM-DD)'
      }
    },
    required: ['country']
  }
};