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 | 4x 63x 63x 28x 35x 17x 18x 19x 18x 18x 19x 17x 14x 19x 19x 7x 2x 19x 19x 19x 19x 19x 19x 19x 1048x 1048x 1048x 1048x 985x 985x 63x 19x 63x 57x 19x 19x 19x 19x 19x 19x 19x 63x 63x 63x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 1x 18x 1x 17x 1x 16x 19x 19x 1x 1x 19x 20x 20x 20x 20x 20x 19x 4x | /**
* MCP Tool: generate_political_landscape
*
* Generate a comprehensive political landscape overview of the
* European Parliament — group sizes, power dynamics, coalition
* patterns, and activity metrics in a single intelligence product.
*
* **Intelligence Perspective:** The political landscape tool provides a
* strategic-level overview combining group composition, voting cohesion,
* coalition patterns, and activity intensity—the go-to tool for
* situational awareness across the entire Parliament.
*
* **Business Perspective:** Single-call comprehensive overview enables
* quick onboarding for policy teams and provides context for all
* subsequent analysis queries.
*
* ISMS Policy: SC-002 (Input Validation), AC-003 (Least Privilege)
*/
import { z } from 'zod';
import { epClient } from '../clients/europeanParliamentClient.js';
import { auditLogger, toErrorMessage } from '../utils/auditLogger.js';
import { fetchAllCurrentMEPs } from '../utils/mepFetcher.js';
import { normalizePoliticalGroup } from '../utils/politicalGroupNormalization.js';
import type { ToolResult } from './shared/types.js';
/**
* Schema for generate_political_landscape tool input
*/
export const GeneratePoliticalLandscapeSchema = z.object({
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 summary
*/
interface GroupSummary {
name: string;
memberCount: number;
seatShare: number;
countries: number;
}
/**
* Political landscape overview
*/
interface PoliticalLandscape {
period: { from: string; to: string };
parliament: {
totalMEPs: number;
politicalGroups: number;
countriesRepresented: number;
};
groups: GroupSummary[];
powerDynamics: {
largestGroup: string;
majorityThreshold: number;
grandCoalitionSize: number;
progressiveBloc: number;
conservativeBloc: number;
};
activityMetrics: {
averageAttendance: number;
recentSessionCount: number;
};
computedAttributes: {
fragmentationIndex: string;
majorityType: string;
politicalBalance: string;
overallEngagement: string;
};
confidenceLevel: 'HIGH' | 'MEDIUM' | 'LOW';
dataFreshness: string;
sourceAttribution: string;
methodology: string;
dataQualityWarnings: string[];
}
/**
* Classify political group into bloc.
* Based on European Parliament's traditional left-right spectrum:
* - Progressive: Greens/EFA, GUE/NGL (The Left), S&D — left-of-centre families
* - Conservative: ECR, ID/PfE — right-of-centre and eurosceptic families
* - Centre: EPP, Renew, and others — centrist or cross-spectrum
* - NI (Non-Inscrits) default to 'center' as they have no formal bloc alignment
*/
function classifyBloc(group: string): 'progressive' | 'conservative' | 'center' {
const normalised = group.toUpperCase();
if (normalised.includes('GREEN') || normalised.includes('LEFT') || normalised.includes('S&D')) {
return 'progressive';
}
if (normalised.includes('ECR') || normalised.includes('ID') || normalised.includes('PFE')) {
return 'conservative';
}
return 'center';
}
/**
* Compute fragmentation index label
*/
function computeFragmentation(groupCount: number): string {
if (groupCount >= 8) return 'HIGH';
Iif (groupCount >= 5) return 'MODERATE';
return 'LOW';
}
/**
* Compute majority type
*/
function computeMajorityType(largestShare: number, grandShare: number): string {
if (largestShare > 50) return 'SINGLE_GROUP_MAJORITY';
if (grandShare > 60) return 'GRAND_COALITION_DOMINANT';
return 'MULTI_COALITION_REQUIRED';
}
/**
* Compute political balance label
*/
function computePoliticalBalance(
progressive: number,
conservative: number
): string {
const ratio = progressive / Math.max(1, conservative);
if (ratio > 1.3) return 'PROGRESSIVE_LEANING';
if (ratio < 0.77) return 'CONSERVATIVE_LEANING';
return 'BALANCED';
}
/**
* Compute engagement label
*/
function computeEngagement(avgAttendance: number): string {
Iif (avgAttendance >= 80) return 'HIGH';
Iif (avgAttendance >= 65) return 'MODERATE';
return 'LOW';
}
/**
* Aggregate MEPs by political group
*/
function aggregateByGroup(
meps: { politicalGroup: string; country: string }[]
): { groups: GroupSummary[]; countriesRepresented: number; totalMEPs: number } {
const groupMap = new Map<string, { count: number; countries: Set<string> }>();
const allCountries = new Set<string>();
const totalMEPs = meps.length;
for (const mep of meps) {
allCountries.add(mep.country);
// Normalize political-group label so EP API native-language acronyms
// (e.g. French `PPE` / `Verts-ALE`) and legacy successor names
// (e.g. EP9 `ID` → EP10 `PfE`) collapse onto their canonical short codes
// before aggregation. Without this, the same group can appear twice with
// split member counts. See `analyze_coalition_dynamics` Defect #1 / D-01
// (Hack23/euparliamentmonitor 2026-04-26 reliability audits) for the
// root-cause analysis of the equivalent issue in coalition dynamics.
const groupKey = normalizePoliticalGroup(mep.politicalGroup);
const existing = groupMap.get(groupKey);
if (existing !== undefined) {
existing.count++;
existing.countries.add(mep.country);
} else {
groupMap.set(groupKey, {
count: 1,
countries: new Set([mep.country])
});
}
}
const groups: GroupSummary[] = Array.from(groupMap.entries())
.map(([name, data]) => ({
name,
memberCount: data.count,
seatShare: Math.round((data.count / Math.max(1, totalMEPs)) * 10000) / 100,
countries: data.countries.size
}))
.sort((a, b) => b.memberCount - a.memberCount);
return { groups, countriesRepresented: allCountries.size, totalMEPs };
}
/**
* Compute power dynamics from group summaries
*/
function computePowerDynamics(
groups: GroupSummary[],
totalMEPs: number
): PoliticalLandscape['powerDynamics'] {
const largestGroup = groups[0]?.name ?? 'Unknown';
const majorityThreshold = Math.ceil(totalMEPs / 2) + 1;
const grandSize = (groups[0]?.memberCount ?? 0) + (groups[1]?.memberCount ?? 0);
let progressive = 0;
let conservative = 0;
for (const g of groups) {
const bloc = classifyBloc(g.name);
if (bloc === 'progressive') progressive += g.memberCount;
if (bloc === 'conservative') conservative += g.memberCount;
}
return {
largestGroup,
majorityThreshold,
grandCoalitionSize: grandSize,
progressiveBloc: progressive,
conservativeBloc: conservative
};
}
/**
* Build political landscape from EP data
*/
async function buildLandscape(
dateFrom: string,
dateTo: string
): Promise<PoliticalLandscape> {
// Fetch ALL active MEPs via paginated batches (typically ~720 for EP10)
// rather than a single 100-MEP page. The previous `getCurrentMEPs({ limit: 100 })`
// call produced ~14% sample-based seat shares and triggered Defect #3 / D-08
// in the Hack23/euparliamentmonitor 2026-04-26 reliability audits, where
// `totalMEPs: 100` was reported instead of the full Parliament composition.
const mepResult = await fetchAllCurrentMEPs();
const meps = mepResult.meps;
const { groups, countriesRepresented, totalMEPs } = aggregateByGroup(
meps
);
const powerDynamics = computePowerDynamics(groups, totalMEPs);
const largestShare = groups[0]?.seatShare ?? 0;
const grandShare = Math.round(
(powerDynamics.grandCoalitionSize / Math.max(1, totalMEPs)) * 10000
) / 100;
// Fetch real plenary session data from EP API
// Use data.length instead of total because total is a lower-bound estimate
// capped by the page size at offset 0
let recentSessionCount = 0;
try {
const year = parseInt(dateFrom.substring(0, 4), 10);
const sessions = await epClient.getPlenarySessions({
year,
limit: 100
});
recentSessionCount = sessions.data.length;
} catch (error: unknown) {
auditLogger.logError('generate_political_landscape.fetch_sessions', { dateFrom, dateTo }, toErrorMessage(error));
// API may not return sessions for this date range — report zero
}
// Confidence reflects (a) whether the MEP pagination completed and (b)
// whether the resulting roster is large enough to be representative of
// the full Parliament (~720 MEPs in EP10). A partial fetch (pagination
// failure) or a small roster (<200 MEPs) downgrades confidence so
// downstream consumers can flag the snapshot accordingly.
let confidenceLevel: 'HIGH' | 'MEDIUM' | 'LOW';
if (!mepResult.complete) {
confidenceLevel = 'LOW';
} else if (totalMEPs >= 600) {
confidenceLevel = 'HIGH';
} else if (totalMEPs >= 200) {
confidenceLevel = 'MEDIUM';
} else {
confidenceLevel = 'LOW';
}
const dataQualityWarnings: string[] = [
'Bloc classification (progressive/conservative/centre) uses hardcoded group mapping — NI members classified as centre by default',
'Attendance data unavailable from EP API — average attendance reported as zero',
];
if (!mepResult.complete) {
const offsetLabel = mepResult.failureOffset !== undefined
? `offset ${String(mepResult.failureOffset)}`
: 'an unknown offset';
dataQualityWarnings.push(
`MEP pagination failed at ${offsetLabel}; seat shares are computed from the partial roster collected before the failure.`
);
}
return {
period: { from: dateFrom, to: dateTo },
parliament: {
totalMEPs,
politicalGroups: groups.length,
countriesRepresented
},
groups,
powerDynamics,
// Activity metrics from real EP API data
activityMetrics: {
averageAttendance: 0, // EP API does not provide attendance data
recentSessionCount
},
computedAttributes: {
fragmentationIndex: computeFragmentation(groups.length),
majorityType: computeMajorityType(largestShare, grandShare),
politicalBalance: computePoliticalBalance(
powerDynamics.progressiveBloc,
powerDynamics.conservativeBloc
),
overallEngagement: computeEngagement(0)
},
confidenceLevel,
dataFreshness: 'Real-time EP API data — MEP records and plenary sessions from EP Open Data',
sourceAttribution: 'European Parliament Open Data Portal - data.europarl.europa.eu',
methodology: 'Political landscape analysis using real EP Open Data: full paginated MEP '
+ 'roster (typically ~720 MEPs in EP10), group composition mapping with native-language '
+ 'acronym normalisation (e.g. PPE → EPP, Verts-ALE → Greens/EFA, ID → PfE), bloc '
+ 'classification, coalition threshold calculation, fragmentation indexing, and plenary '
+ 'session counts (fetched page count, lower bound). Attendance data is not available '
+ 'from the EP API and is reported as zero. Data source: European Parliament Open Data Portal.',
dataQualityWarnings,
};
}
/**
* Handles the generate_political_landscape MCP tool request.
*
* Generates a comprehensive snapshot of the current European Parliament political
* landscape including group seat shares, bloc analysis (progressive vs. conservative),
* coalition viability, and power-balance metrics. Provides single-call situational
* awareness for strategic intelligence briefings.
*
* @param args - Raw tool arguments, validated against {@link GeneratePoliticalLandscapeSchema}
* @returns MCP tool result containing group seat distributions, power dynamics,
* activity metrics, fragmentation index, majority type, and political balance score
* @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 handleGeneratePoliticalLandscape({
* dateFrom: '2024-01-01',
* dateTo: '2024-12-31'
* });
* // Returns full landscape with group sizes, bloc analysis,
* // fragmentation index, and majority-type classification
* ```
*
* @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 generatePoliticalLandscapeToolMetadata} for MCP schema registration
* @see {@link handleComparePoliticalGroups} for detailed per-group dimension comparison
*/
export async function handleGeneratePoliticalLandscape(
args: unknown
): Promise<ToolResult> {
const params = GeneratePoliticalLandscapeSchema.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 landscape = await buildLandscape(dateFrom, dateTo);
return {
content: [
{
type: 'text',
text: JSON.stringify(landscape, null, 2)
}
]
};
}
/**
* Tool metadata for MCP listing
*/
export const generatePoliticalLandscapeToolMetadata = {
name: 'generate_political_landscape',
description: 'Generate a comprehensive political landscape overview of the European Parliament — group sizes, seat shares, coalition dynamics, bloc analysis, and power balance. Single-call situational awareness for strategic intelligence.',
inputSchema: {
type: 'object' as const,
properties: {
dateFrom: {
type: 'string',
description: 'Start date (YYYY-MM-DD)'
},
dateTo: {
type: 'string',
description: 'End date (YYYY-MM-DD)'
}
},
required: []
}
};
|