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 | 4x 13x 13x 13x 13x 24x 13x 24x 13x 13x 13x 13x 13x 24x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 1x 1x 13x 65x 13x 1x 1x 15x 15x 15x 13x 15x 15x 15x 13x 13x 13x 15x 15x 15x 15x 15x 65x 15x 15x 15x 15x 1x 1x 4x | /**
* MCP Tool: assess_mep_influence
*
* Compute MEP influence score from voting activity, committee roles,
* rapporteurships, questions filed, and coalition building metrics.
*
* **Intelligence Perspective:** Core OSINT scorecard tool computing composite MEP
* influence scores using CIA Political Scorecards methodology—enables comparative
* ranking, trend analysis, and political weight assessment across 5 dimensions.
*
* ISMS Policy: SC-002 (Input Validation), AC-003 (Least Privilege)
*/
import { AssessMepInfluenceSchema } from '../schemas/europeanParliament.js';
import { epClient } from '../clients/europeanParliamentClient.js';
import { auditLogger, toErrorMessage } from '../utils/auditLogger.js';
import { buildToolResponse } from './shared/responseBuilder.js';
import type { ToolResult } from './shared/types.js';
/**
* Dimension weight configuration for influence scoring
* Based on CIA Political Scorecards methodology from FUTURE_ARCHITECTURE.md
*/
const DIMENSION_WEIGHTS = {
votingActivity: 0.25,
legislativeOutput: 0.25,
committeeEngagement: 0.20,
parliamentaryOversight: 0.15,
coalitionBuilding: 0.15
} as const;
/**
* Influence dimension score
*/
interface DimensionScore {
dimension: string;
score: number;
weight: number;
weightedScore: number;
metrics: Record<string, number>;
}
/**
* MEP influence assessment result
*/
interface MepInfluenceAssessment {
mepId: string;
mepName: string;
country: string;
politicalGroup: string;
period: { from: string; to: string };
overallScore: number;
rank: string;
dimensions: DimensionScore[];
computedAttributes: {
participationRate: number;
loyaltyScore: number;
diversityIndex: number;
effectivenessRatio: number;
leadershipIndicator: number;
};
votingDataAvailable: boolean;
confidenceLevel: string;
dataFreshness: string;
sourceAttribution: string;
methodology: string;
}
/**
* Compute voting activity score (0-100)
*/
function computeVotingActivityScore(stats: { totalVotes: number; attendanceRate: number }): {
score: number;
metrics: Record<string, number>;
} {
const attendanceScore = stats.attendanceRate;
const participationVolume = Math.min(100, (stats.totalVotes / 1500) * 100);
const score = attendanceScore * 0.6 + participationVolume * 0.4;
return {
score: Math.round(score * 100) / 100,
metrics: {
attendanceRate: stats.attendanceRate,
totalVotes: stats.totalVotes,
participationVolume: Math.round(participationVolume * 100) / 100
}
};
}
/**
* Compute legislative output score (0-100)
*/
function computeLegislativeOutputScore(roles: string[], committees: string[]): {
score: number;
metrics: Record<string, number>;
} {
const rapporteurships = roles.filter(r => r.toLowerCase().includes('rapporteur')).length;
const committeeRoles = roles.filter(r =>
r.toLowerCase().includes('chair') || r.toLowerCase().includes('vice')
).length;
const roleScore = Math.min(100, rapporteurships * 15 + committeeRoles * 20);
const committeeDiversity = Math.min(100, committees.length * 20);
const score = roleScore * 0.6 + committeeDiversity * 0.4;
return {
score: Math.round(score * 100) / 100,
metrics: {
rapporteurships,
committeeRoles,
totalCommittees: committees.length
}
};
}
/**
* Compute committee engagement score (0-100)
*/
function computeCommitteeEngagementScore(committees: string[], roles: string[]): {
score: number;
metrics: Record<string, number>;
} {
const leadershipRoles = roles.filter(r =>
r.toLowerCase().includes('chair') ||
r.toLowerCase().includes('coordinator') ||
r.toLowerCase().includes('vice')
).length;
const membershipBreadth = Math.min(100, committees.length * 25);
const leadershipScore = Math.min(100, leadershipRoles * 30);
const score = membershipBreadth * 0.5 + leadershipScore * 0.5;
return {
score: Math.round(score * 100) / 100,
metrics: {
committeeMemberships: committees.length,
leadershipRoles,
membershipBreadth: Math.round(membershipBreadth * 100) / 100
}
};
}
/**
* Compute parliamentary oversight score (0-100) using real question data
*/
function computeOversightScore(questionCount: number): {
score: number;
metrics: Record<string, number>;
} {
const questionVolume = Math.min(100, questionCount * 2);
const topicDiversity = Math.min(100, questionCount * 10);
const score = questionVolume * 0.5 + topicDiversity * 0.5;
return {
score: Math.round(score * 100) / 100,
metrics: {
questionsFound: questionCount,
questionVolume: Math.round(questionVolume * 100) / 100,
topicDiversity: Math.round(topicDiversity * 100) / 100
}
};
}
/**
* Compute coalition building score (0-100)
*/
function computeCoalitionScore(stats: { votesFor: number; votesAgainst: number; abstentions: number; totalVotes: number }): {
score: number;
metrics: Record<string, number>;
} {
const totalDecisive = stats.votesFor + stats.votesAgainst;
const crossPartyRate = totalDecisive > 0
? Math.min(100, (stats.votesAgainst / totalDecisive) * 100 * 2)
: 0;
const engagementRate = stats.totalVotes > 0
? ((stats.totalVotes - stats.abstentions) / stats.totalVotes) * 100
: 0;
const score = crossPartyRate * 0.4 + engagementRate * 0.6;
return {
score: Math.round(score * 100) / 100,
metrics: {
crossPartyRate: Math.round(crossPartyRate * 100) / 100,
engagementRate: Math.round(engagementRate * 100) / 100,
decisiveVotes: totalDecisive
}
};
}
/**
* Determine influence rank label
*/
function getRankLabel(score: number): string {
Iif (score >= 80) return 'Very High Influence';
Iif (score >= 60) return 'High Influence';
if (score >= 40) return 'Moderate Influence';
Iif (score >= 20) return 'Low Influence';
return 'Minimal Influence';
}
/**
* Input for dimension building
*/
interface DimensionInputs {
votingDim: { score: number; metrics: Record<string, number> };
legislativeDim: { score: number; metrics: Record<string, number> };
committeeDim: { score: number; metrics: Record<string, number> };
oversightDim: { score: number; metrics: Record<string, number> };
coalitionDim: { score: number; metrics: Record<string, number> };
}
/**
* Build dimensions array from computed scores
*/
function buildDimensions(inputs: DimensionInputs, includeMetrics: boolean): DimensionScore[] {
const raw: { name: string; result: { score: number; metrics: Record<string, number> }; weight: number }[] = [
{ name: 'Voting Activity', result: inputs.votingDim, weight: DIMENSION_WEIGHTS.votingActivity },
{ name: 'Legislative Output', result: inputs.legislativeDim, weight: DIMENSION_WEIGHTS.legislativeOutput },
{ name: 'Committee Engagement', result: inputs.committeeDim, weight: DIMENSION_WEIGHTS.committeeEngagement },
{ name: 'Parliamentary Oversight', result: inputs.oversightDim, weight: DIMENSION_WEIGHTS.parliamentaryOversight },
{ name: 'Coalition Building', result: inputs.coalitionDim, weight: DIMENSION_WEIGHTS.coalitionBuilding }
];
return raw.map(d => ({
dimension: d.name,
score: d.result.score,
weight: d.weight,
weightedScore: Math.round(d.result.score * d.weight * 100) / 100,
metrics: includeMetrics ? d.result.metrics : {}
}));
}
/**
* Determine confidence level from vote count
*/
function getConfidenceLevel(totalVotes: number): string {
if (totalVotes > 500) return 'HIGH';
Iif (totalVotes > 100) return 'MEDIUM';
return 'LOW';
}
/**
* Handles the assess_mep_influence MCP tool request.
*
* Assesses an MEP's influence within the European Parliament by evaluating their
* voting activity, parliamentary questions, committee leadership roles, and
* seniority. Produces a multi-dimensional influence score with network centrality
* and impact rank computations.
*
* @param args - Raw tool arguments, validated against {@link AssessMepInfluenceSchema}
* @returns MCP tool result containing the MEP's influence scores, voting statistics,
* committee roles, question count, seniority metrics, and computed influence rank
* @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 handleAssessMepInfluence({
* mepId: '124810',
* includeVoting: true,
* includeCommittees: true
* });
* // Returns influence assessment with overall score, voting discipline,
* // committee leadership, and seniority breakdown
* ```
*
* @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 assessMepInfluenceToolMetadata} for MCP schema registration
* @see {@link handleTrackMepAttendance} for MEP attendance and participation tracking
* Assess MEP influence tool handler
*
* Computes a composite influence scorecard for a single MEP using a
* 5-dimension weighted model aligned with CIA Political Scorecards methodology.
* Fetches live MEP profile and parliamentary questions from the EP Open Data API
* to populate the scoring dimensions.
*
* **Dimensions (weighted):**
* - Voting Activity (25%) — attendance rate + participation volume
* - Legislative Output (25%) — rapporteurships + committee leadership roles
* - Committee Engagement (20%) — membership breadth + leadership positions
* - Parliamentary Oversight (15%) — parliamentary questions filed
* - Coalition Building (15%) — cross-party voting rate + engagement rate
*
* @param args - Tool arguments matching AssessMepInfluenceSchema
* @param args.mepId - MEP identifier (required)
* @param args.dateFrom - Analysis start date in YYYY-MM-DD format (optional)
* @param args.dateTo - Analysis end date in YYYY-MM-DD format (optional)
* @param args.includeDetails - When true, includes per-dimension metric breakdown (optional)
* @returns MCP ToolResult containing the `MepInfluenceAssessment` object as JSON
* @throws {Error} When MEP is not found or the EP API request fails
* @throws {ZodError} When input fails schema validation (missing mepId, invalid date format)
*
* @example
* ```typescript
* // Basic influence assessment
* const result = await handleAssessMepInfluence({ mepId: "197558" });
* const assessment = JSON.parse(result.content[0].text);
* console.log(`${assessment.mepName}: ${assessment.rank} (${assessment.overallScore}/100)`);
* ```
*
* @example
* ```typescript
* // Detailed assessment with dimension breakdown
* const result = await handleAssessMepInfluence({
* mepId: "197558",
* dateFrom: "2024-01-01",
* dateTo: "2024-12-31",
* includeDetails: true
* });
* ```
*
* @security Input validated by Zod. Errors sanitized (no stack traces exposed).
* Personal data (MEP profiles) access logged per GDPR Article 30.
* ISMS Policy: SC-002 (Input Validation), AC-003 (Least Privilege)
*/
export async function handleAssessMepInfluence(
args: unknown
): Promise<ToolResult> {
const params = AssessMepInfluenceSchema.parse(args);
try {
const mep = await epClient.getMEPDetails(params.mepId);
const stats = mep.votingStatistics ?? {
totalVotes: 0, votesFor: 0, votesAgainst: 0, abstentions: 0, attendanceRate: 0
};
// Fetch real parliamentary questions for this MEP
// Use data.length instead of total because total is a lower-bound estimate
let questionCount = 0;
try {
const questions = await epClient.getParliamentaryQuestions({
author: params.mepId,
limit: 100
});
questionCount = questions.data.length;
} catch (error: unknown) {
auditLogger.logError('assess_mep_influence.fetch_questions', { mepId: params.mepId }, toErrorMessage(error));
// Questions may not be available — report zero
}
const votingDim = computeVotingActivityScore(stats);
const legislativeDim = computeLegislativeOutputScore(mep.roles ?? [], mep.committees);
const committeeDim = computeCommitteeEngagementScore(mep.committees, mep.roles ?? []);
const oversightDim = computeOversightScore(questionCount);
const coalitionDim = computeCoalitionScore(stats);
const dimensions = buildDimensions(
{ votingDim, legislativeDim, committeeDim, oversightDim, coalitionDim },
params.includeDetails
);
const overallScore = Math.round(
dimensions.reduce((sum, d) => sum + d.weightedScore, 0) * 100
) / 100;
const totalDecisive = stats.votesFor + stats.votesAgainst;
const loyaltyScore = totalDecisive > 0
? Math.round((stats.votesFor / totalDecisive) * 100 * 100) / 100
: 0;
const assessment: MepInfluenceAssessment = {
mepId: params.mepId,
mepName: mep.name,
country: mep.country,
politicalGroup: mep.politicalGroup,
period: {
from: params.dateFrom ?? '2024-01-01',
to: params.dateTo ?? '2024-12-31'
},
overallScore,
rank: getRankLabel(overallScore),
dimensions,
computedAttributes: {
participationRate: stats.attendanceRate,
loyaltyScore,
diversityIndex: Math.min(100, Math.max(0, Math.round((mep.committees.length / 5) * 100 * 100) / 100)),
effectivenessRatio: Math.round((votingDim.score + legislativeDim.score) / 2 * 100) / 100,
leadershipIndicator: committeeDim.score
},
confidenceLevel: getConfidenceLevel(stats.totalVotes),
votingDataAvailable: stats.totalVotes > 0,
dataFreshness: 'Real-time EP API data — MEP voting statistics and committee memberships',
sourceAttribution: 'European Parliament Open Data Portal - data.europarl.europa.eu',
methodology: 'CIA Political Scorecards - 5-dimension weighted scoring model using real EP Open Data. '
+ 'Parliamentary questions fetched from /parliamentary-questions endpoint. '
+ 'Data source: European Parliament Open Data Portal.'
};
return buildToolResponse(assessment);
} catch (error) {
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
throw new Error(`Failed to assess MEP influence: ${errorMessage}`);
}
}
/**
* Tool metadata for MCP registration
*/
export const assessMepInfluenceToolMetadata = {
name: 'assess_mep_influence',
description: 'Compute MEP influence score using a 5-dimension weighted model: Voting Activity (25%), Legislative Output (25%), Committee Engagement (20%), Parliamentary Oversight (15%), Coalition Building (15%). Returns overall score, rank, dimension breakdowns, and computed attributes including participation rate, loyalty score, diversity index, and leadership indicator.',
inputSchema: {
type: 'object' as const,
properties: {
mepId: {
type: 'string',
description: 'MEP identifier',
minLength: 1,
maxLength: 100
},
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}$'
},
includeDetails: {
type: 'boolean',
description: 'Include detailed breakdown per dimension',
default: false
}
},
required: ['mepId']
}
};
|