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 | 84x 84x 84x 84x 84x 42x 42x 14x 16x 16x 16x 14x 8x 8x 8x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 21x 3x 23x 14x 14x 23x 16x 16x 16x 16x 14x 16x 8x 23x 23x 23x 23x 14x 14x 14x 14x 14x 14x 16x 16x 16x 14x 14x 14x 42x 42x 42x 42x 42x 14x 42x 42x 23x 14x 14x 14x 14x 14x 16x 1x 1x 4x | /**
* MCP Tool: monitor_legislative_pipeline
*
* Real-time legislative pipeline status with bottleneck detection
* and timeline forecasting.
*
* **Intelligence Perspective:** Pipeline monitoring tool providing situational
* awareness of legislative progress—enables early warning for stalled procedures,
* bottleneck identification, and timeline forecasting.
*
* ISMS Policy: SC-002 (Input Validation), AC-003 (Least Privilege)
*/
import { MonitorLegislativePipelineSchema } from '../schemas/europeanParliament.js';
import { epClient } from '../clients/europeanParliamentClient.js';
import type { Procedure } from '../types/europeanParliament.js';
import type { ToolResult } from './shared/types.js';
/** Computed attributes for a single pipeline item */
interface PipelineItemComputedAttrs {
progressPercentage: number;
velocityScore: number;
complexityIndicator: string;
estimatedCompletionDays: number;
bottleneckRisk: string;
}
/** A single procedure in the pipeline */
interface PipelineItem {
procedureId: string;
title: string;
type: string;
currentStage: string;
committee: string;
daysInCurrentStage: number;
isStalled: boolean;
nextExpectedAction: string;
computedAttributes: PipelineItemComputedAttrs;
}
/** Bottleneck analysis */
interface BottleneckInfo {
stage: string;
procedureCount: number;
avgDaysStuck: number;
severity: string;
}
/** Full pipeline analysis result */
interface LegislativePipelineAnalysis {
period: { from: string; to: string };
filter: { committee?: string; status: string };
pipeline: PipelineItem[];
summary: {
totalProcedures: number;
activeCount: number;
stalledCount: number;
completedCount: number;
avgDaysInPipeline: number;
};
bottlenecks: BottleneckInfo[];
computedAttributes: {
pipelineHealthScore: number;
throughputRate: number;
bottleneckIndex: number;
stalledProcedureRate: number;
estimatedClearanceTime: number;
legislativeMomentum: string;
};
confidenceLevel: string;
dataFreshness: string;
sourceAttribution: string;
methodology: string;
}
/**
* Calculate days between two date strings (or since a date).
*/
function daysBetween(dateStr: string, endStr?: string): number {
const start = new Date(dateStr);
const end = endStr !== undefined && endStr !== '' ? new Date(endStr) : new Date();
Iif (isNaN(start.getTime())) return 0;
Iif (isNaN(end.getTime())) return 0;
return Math.max(0, Math.round((end.getTime() - start.getTime()) / (1000 * 60 * 60 * 24)));
}
/** Classify complexity from days in stage */
function classifyComplexity(days: number): string {
Eif (days > 60) return 'HIGH';
if (days > 30) return 'MEDIUM';
return 'LOW';
}
/** Classify bottleneck risk */
function classifyBottleneckRisk(isStalled: boolean, days: number): string {
if (isStalled) return 'HIGH';
Eif (days > 45) return 'MEDIUM';
return 'LOW';
}
/** Classify bottleneck severity */
function classifyBottleneckSeverity(count: number): string {
Iif (count > 3) return 'CRITICAL';
Iif (count > 1) return 'HIGH';
return 'MODERATE';
}
/** Classify legislative momentum */
function classifyMomentum(healthScore: number): string {
if (healthScore > 80) return 'STRONG';
Iif (healthScore > 60) return 'MODERATE';
Iif (healthScore > 40) return 'SLOW';
return 'STALLED';
}
/**
* Check if a procedure status indicates completion.
*/
function isStatusCompleted(status: string): boolean {
const lower = status.toLowerCase();
return lower.includes('adopted') || lower.includes('completed');
}
/**
* Compute progress metrics for a procedure.
*/
function computePipelineMetrics(proc: Procedure): {
daysInStage: number; isCompleted: boolean; isStalled: boolean;
totalDays: number; progressEstimate: number; velocityScore: number; estimatedDays: number;
} {
const lastActivity = proc.dateLastActivity !== '' ? proc.dateLastActivity : proc.dateInitiated;
const daysInStage = daysBetween(lastActivity);
const isCompleted = isStatusCompleted(proc.status);
const isStalled = !isCompleted && daysInStage > 60;
const initiated = proc.dateInitiated !== '' ? proc.dateInitiated : '';
const lastAct = proc.dateLastActivity !== '' ? proc.dateLastActivity : undefined;
const totalDays = daysBetween(initiated, lastAct);
const progressEstimate = isCompleted ? 100 : Math.min(90, Math.max(5, Math.round(totalDays / 10)));
const velocityScore = isStalled ? 20 : Math.min(100, 100 - Math.min(80, daysInStage));
const estimatedDays = isCompleted ? 0 : Math.max(30, daysInStage * 2);
return { daysInStage, isCompleted, isStalled, totalDays, progressEstimate, velocityScore, estimatedDays };
}
/**
* Transform a real EP API Procedure into a PipelineItem.
* All data is derived from the real procedure fields.
*/
function procedureToPipelineItem(proc: Procedure): PipelineItem {
const m = computePipelineMetrics(proc);
let currentStage = 'Unknown';
if (proc.stage !== '') {
currentStage = proc.stage;
E} else if (proc.status !== '') {
currentStage = proc.status;
}
const committee = proc.responsibleCommittee !== '' ? proc.responsibleCommittee : 'Unknown';
const stageLabel = proc.stage !== '' ? proc.stage : 'processing';
const nextAction = m.isCompleted ? 'COMPLETED' : `Continue ${stageLabel}`;
return {
procedureId: proc.id,
title: proc.title,
type: proc.type,
currentStage,
committee,
daysInCurrentStage: m.daysInStage,
isStalled: m.isStalled,
nextExpectedAction: nextAction,
computedAttributes: {
progressPercentage: m.progressEstimate,
velocityScore: m.velocityScore,
complexityIndicator: classifyComplexity(m.daysInStage),
estimatedCompletionDays: m.estimatedDays,
bottleneckRisk: classifyBottleneckRisk(m.isStalled, m.daysInStage),
},
};
}
/** Check if item matches status filter */
function matchesStatusFilter(item: PipelineItem, status: string): boolean {
if (status === 'ALL') return true;
if (status === 'ACTIVE') return !item.isStalled && item.computedAttributes.progressPercentage < 100;
Eif (status === 'STALLED') return item.isStalled;
if (status === 'COMPLETED') return item.computedAttributes.progressPercentage >= 100;
return true;
}
/** Check if item matches committee filter */
function matchesCommitteeFilter(item: PipelineItem, committee: string | undefined): boolean {
Eif (committee === undefined) return true;
return item.committee === committee;
}
/** Detect bottlenecks from stalled pipeline items */
function detectBottlenecks(pipeline: PipelineItem[]): BottleneckInfo[] {
const stageCounts: Record<string, { count: number; totalDays: number }> = {};
for (const item of pipeline) {
if (item.isStalled) {
const entry = stageCounts[item.currentStage] ?? { count: 0, totalDays: 0 };
entry.count++;
entry.totalDays += item.daysInCurrentStage;
stageCounts[item.currentStage] = entry;
}
}
return Object.entries(stageCounts)
.map(([stage, data]) => ({
stage,
procedureCount: data.count,
avgDaysStuck: Math.round(data.totalDays / data.count),
severity: classifyBottleneckSeverity(data.count),
}))
.sort((a, b) => b.procedureCount - a.procedureCount);
}
/** Compute pipeline summary statistics */
function computePipelineSummary(pipeline: PipelineItem[]): {
activeCount: number; stalledCount: number; completedCount: number; avgDays: number;
} {
const activeCount = pipeline.filter(p => !p.isStalled && p.computedAttributes.progressPercentage < 100).length;
const stalledCount = pipeline.filter(p => p.isStalled).length;
const completedCount = pipeline.filter(p => p.computedAttributes.progressPercentage >= 100).length;
const totalDays = pipeline.reduce((sum, p) => sum + p.daysInCurrentStage, 0);
const avgDays = pipeline.length > 0 ? Math.round(totalDays / pipeline.length) : 0;
return { activeCount, stalledCount, completedCount, avgDays };
}
/** Compute pipeline health metrics */
function computeHealthMetrics(pipeline: PipelineItem[], summary: ReturnType<typeof computePipelineSummary>): {
healthScore: number; throughputRate: number; stalledRate: number;
} {
const stalledRate = pipeline.length > 0 ? summary.stalledCount / pipeline.length : 0;
const healthScore = Math.round((1 - stalledRate) * 100 * 100) / 100;
const throughputRate = pipeline.length > 0
? Math.round((summary.completedCount / pipeline.length) * 100 * 100) / 100
: 0;
return { healthScore, throughputRate, stalledRate };
}
/**
* Handles the monitor_legislative_pipeline MCP tool request.
*
* Monitors the European Parliament's active legislative pipeline by fetching real
* procedures from the EP API and computing health metrics including bottleneck
* detection, stalled-procedure rate, throughput rate, and legislative momentum.
* All procedure data (title, type, stage, status, dates, committee) is sourced
* directly from the EP API; computed attributes are derived from real dates and stages.
*
* @param args - Raw tool arguments, validated against {@link MonitorLegislativePipelineSchema}
* @returns MCP tool result containing pipeline items with stage and status,
* summary counts (active/stalled/completed), detected bottlenecks, pipeline health
* score, throughput rate, bottleneck index, and legislative momentum 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 handleMonitorLegislativePipeline({
* status: 'ACTIVE',
* committee: 'ENVI',
* dateFrom: '2024-01-01',
* dateTo: '2024-12-31',
* limit: 20
* });
* // Returns pipeline health score, stalled/active/completed counts,
* // bottleneck list, and legislative momentum assessment
* ```
*
* @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 monitorLegislativePipelineToolMetadata} for MCP schema registration
* @see {@link handleTrackLegislation} for individual procedure stage and timeline tracking
*/
export async function handleMonitorLegislativePipeline(
args: unknown
): Promise<ToolResult> {
const params = MonitorLegislativePipelineSchema.parse(args);
try {
const procedures = await epClient.getProcedures({ limit: params.limit });
const dateFrom = params.dateFrom;
const dateTo = params.dateTo;
const filteredProcs = procedures.data.filter(proc => {
const lastActivity = proc.dateLastActivity !== '' ? proc.dateLastActivity : proc.dateInitiated;
const initiated = proc.dateInitiated !== '' ? proc.dateInitiated : undefined;
Iif (dateFrom !== undefined && lastActivity !== '' && lastActivity < dateFrom) return false;
Iif (dateTo !== undefined && initiated !== undefined && initiated > dateTo) return false;
return true;
});
const allItems = filteredProcs
.map(proc => procedureToPipelineItem(proc))
.filter(item => matchesStatusFilter(item, params.status))
.filter(item => matchesCommitteeFilter(item, params.committee));
const pipeline = allItems.slice(0, params.limit);
const summary = computePipelineSummary(pipeline);
const bottlenecks = detectBottlenecks(pipeline);
const health = computeHealthMetrics(pipeline, summary);
const analysis: LegislativePipelineAnalysis = {
period: { from: params.dateFrom ?? '2024-01-01', to: params.dateTo ?? '2024-12-31' },
filter: { ...(params.committee !== undefined ? { committee: params.committee } : {}), status: params.status },
pipeline,
summary: {
totalProcedures: pipeline.length,
activeCount: summary.activeCount,
stalledCount: summary.stalledCount,
completedCount: summary.completedCount,
avgDaysInPipeline: summary.avgDays,
},
bottlenecks,
computedAttributes: {
pipelineHealthScore: health.healthScore,
throughputRate: health.throughputRate,
bottleneckIndex: Math.round(health.stalledRate * summary.avgDays * 100) / 100,
stalledProcedureRate: Math.round(health.stalledRate * 100 * 100) / 100,
estimatedClearanceTime: summary.avgDays * Math.max(1, summary.activeCount),
legislativeMomentum: classifyMomentum(health.healthScore),
},
confidenceLevel: pipeline.length >= 10 ? 'MEDIUM' : 'LOW',
dataFreshness: 'Real-time EP API data — procedures from EP Open Data /procedures endpoint',
sourceAttribution: 'European Parliament Open Data Portal - data.europarl.europa.eu',
methodology: 'Real-time pipeline analysis using EP API /procedures endpoint. '
+ 'All procedure data (title, type, stage, status, dates, committee) sourced from '
+ 'European Parliament open data. Computed attributes (health score, velocity, '
+ 'bottleneck risk, momentum) are derived from real procedure dates and stages. '
+ 'Data source: https://data.europarl.europa.eu/api/v2/procedures',
};
return { content: [{ type: 'text', text: JSON.stringify(analysis, null, 2) }] };
} catch (error) {
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
throw new Error(`Failed to monitor legislative pipeline: ${errorMessage}`);
}
}
/**
* Tool metadata for MCP registration
*/
export const monitorLegislativePipelineToolMetadata = {
name: 'monitor_legislative_pipeline',
description: 'Monitor legislative pipeline status with bottleneck detection and timeline forecasting. Tracks procedures through stages (proposal → committee → plenary → trilogue → adoption). Returns pipeline health score, throughput rate, bottleneck index, stalled procedure rate, and legislative momentum assessment.',
inputSchema: {
type: 'object' as const,
properties: {
committee: {
type: 'string',
description: 'Filter by committee',
minLength: 1,
maxLength: 100
},
status: {
type: 'string',
enum: ['ALL', 'ACTIVE', 'STALLED', 'COMPLETED'],
description: 'Pipeline status filter',
default: 'ACTIVE'
},
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}$'
},
limit: {
type: 'number',
description: 'Maximum results to return (1-100)',
minimum: 1,
maximum: 100,
default: 20
}
}
}
};
|