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 | 290x 290x 290x 290x 290x 102x 102x 102x 102x 179x 179x 179x 179x 108x 2x 106x 2x 104x 104x 71x 71x 29x 29x 29x 29x 29x 11x 11x 11x 11x 29x 29x 29x 29x 29x 11x 11x 11x 11x 11x 29x 29x 29x 29x 18x 18x 18x 18x 11x 11x 42x 11x 4x 4x 4x 4x 4x 52x 52x 52x 2x 50x 1x 49x 2x 2x 47x 47x 4x 4x 4x 4x 1x 3x 3x 5x 5x 5x 5x 1x 4x 3x 3x 3x 4x 4x 3x 5x 3x 2x 2x 2x 2x 3x 5x 2x 2x | // SPDX-FileCopyrightText: 2024-2026 Hack23 AB
// SPDX-License-Identifier: Apache-2.0
/**
* @module MCP/ep/client
* @description European Parliament MCP client — domain-specific tool wrappers
* built on top of the generic {@link MCPConnection} transport.
*
* The class skeleton (fields, constructor, core utility methods, and diagnostics)
* is defined here. Domain method groups are mixed into the prototype via
* side-effect imports of the `tools-*.ts` sibling modules.
*/
import { MCPConnection } from '../mcp-connection.js';
import type { MCPClientOptions, MCPToolResult } from '../../types/index.js';
import { classifyToolError, isFeedUnavailable } from './error-classifier.js';
import { FEED_UNAVAILABLE_REASON } from './fallbacks.js';
import { TOOL_RELIABILITY_TIMEOUT_MS, TOOL_RELIABILITY_TIMEOUT_RETRIES } from './reliability.js';
export class EuropeanParliamentMCPClient extends MCPConnection {
/** Tracks tools that returned fallback data in the current session */
protected readonly _failedTools = new Map<string, string>();
/** Tracks tools that have been called (attempted) in the current session */
protected readonly _calledTools = new Set<string>();
/**
* Tracks tools that experienced a timeout but the failure was downgraded to a warning.
* Unlike `_failedTools`, entries here are NOT counted against the reliability score.
*/
protected readonly _slowFeedWarnings = new Map<string, string>();
/**
* Path to the pending-documents sidecar file.
* Undefined means "use the module-level default (`<cwd>/data/pending-documents.json`)".
*/
protected readonly _pendingDocumentsStorePath: string | undefined;
/**
* Create a new EP MCP client.
*
* @param options - Connection and gateway options forwarded to {@link MCPConnection},
* plus an optional `pendingDocumentsStorePath` that overrides the
* default `<cwd>/data/pending-documents.json` sidecar location.
*/
constructor(options: MCPClientOptions = {}) {
super(options);
this._pendingDocumentsStorePath = options.pendingDocumentsStorePath;
}
/**
* Record a tool failure and log a warning.
*
* @param toolName - MCP tool name that failed
* @param errorText - Raw error text from the failure
* @param fallbackText - JSON text for the fallback result
* @returns Fallback MCPToolResult
*/
protected _recordToolFailure(
toolName: string,
errorText: string,
fallbackText: string
): MCPToolResult {
const errorType = classifyToolError(errorText);
this._failedTools.set(toolName, `${errorType}: ${errorText.slice(0, 200)}`);
console.warn(`\u26a0\ufe0f ${toolName} failed [${errorType}]:`, errorText.slice(0, 200));
return { content: [{ type: 'text', text: fallbackText }] };
}
/**
* Generic error-safe wrapper around {@link callToolWithRetry}.
* Catches any error thrown by the tool (or by the args factory), logs a warning,
* and returns a fallback payload.
*
* @param toolName - MCP tool name
* @param args - Tool arguments or a factory that builds them
* @param fallbackText - JSON text to return when the tool is unavailable
* @returns Tool result or fallback
*/
protected async safeCallTool(
toolName: string,
args: object | (() => object),
fallbackText: string
): Promise<MCPToolResult> {
this._calledTools.add(toolName);
try {
const resolvedArgs = typeof args === 'function' ? args() : args;
const result = await this.callToolWithRetry(toolName, resolvedArgs);
if (result.isError === true) {
return this._recordToolFailure(toolName, result.content?.[0]?.text ?? '', fallbackText);
}
if (isFeedUnavailable(result)) {
return this._recordToolFailure(
toolName,
`UPSTREAM_404: ${result.content?.[0]?.text?.slice(0, 200) ?? FEED_UNAVAILABLE_REASON}`,
fallbackText
);
}
this._failedTools.delete(toolName);
return result;
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
return this._recordToolFailure(toolName, message, fallbackText);
}
}
/**
* Build a standardized per-tool timeout error.
* @param toolName - MCP tool identifier
* @param timeoutMs - Timeout threshold in milliseconds
* @param cause - Optional underlying error
* @returns Formatted timeout error
*/
private _buildReliabilityTimeoutError(toolName: string, timeoutMs: number, cause?: Error): Error {
return new Error(`UPSTREAM_TIMEOUT: ${toolName} exceeded per-tool timeout (${timeoutMs}ms)`, {
cause,
});
}
/**
* Execute one MCP tool attempt with a per-tool timeout guard.
* @param toolName - MCP tool identifier
* @param args - Tool arguments
* @param timeoutMs - Timeout threshold in milliseconds
* @returns Tool result or throws on timeout
*/
private async _callToolOnceWithReliabilityTimeout(
toolName: string,
args: object,
timeoutMs: number
): Promise<MCPToolResult> {
let timer: NodeJS.Timeout | undefined;
const timeoutPromise = new Promise<MCPToolResult>((_, reject) => {
timer = setTimeout(
() => reject(this._buildReliabilityTimeoutError(toolName, timeoutMs)),
timeoutMs
);
});
try {
return await Promise.race([this.callToolWithRetry(toolName, args, 0), timeoutPromise]);
} finally {
Eif (timer) clearTimeout(timer);
}
}
/**
* Decide retry/throw behavior for a failed reliability-timed attempt.
* @param toolName - MCP tool identifier
* @param timeoutMs - Timeout threshold in milliseconds
* @param error - The error that occurred
* @param timeoutObserved - Whether a timeout was previously observed
* @param attempt - Current attempt number
* @param timeoutRetries - Maximum allowed timeout retries
* @returns Decision object with retry flag and error details
*/
private _decideReliabilityAttemptError(
toolName: string,
timeoutMs: number,
error: Error,
timeoutObserved: boolean,
attempt: number,
timeoutRetries: number
): { retry: boolean; timeoutObserved: boolean; error?: Error } {
const isTimeout = classifyToolError(error.message) === 'TIMEOUT';
Iif (isTimeout) {
if (attempt < timeoutRetries) {
return { retry: true, timeoutObserved: true };
}
return { retry: false, timeoutObserved: true, error };
}
Iif (timeoutObserved) {
return {
retry: false,
timeoutObserved: true,
error: this._buildReliabilityTimeoutError(toolName, timeoutMs, error),
};
}
return { retry: false, timeoutObserved, error };
}
/**
* Call a tool with per-tool timeout and one timeout-only retry budget.
* @param toolName - MCP tool identifier
* @param args - Tool arguments
* @param timeoutMs - Timeout threshold in milliseconds
* @param timeoutRetries - Maximum allowed timeout retries
* @returns Tool result
*/
private async callToolWithReliabilityTimeout(
toolName: string,
args: object,
timeoutMs: number = TOOL_RELIABILITY_TIMEOUT_MS,
timeoutRetries: number = TOOL_RELIABILITY_TIMEOUT_RETRIES
): Promise<MCPToolResult> {
let lastError: Error = new Error(`Timed out calling ${toolName}`);
let timeoutObserved = false;
for (let attempt = 0; attempt <= timeoutRetries; attempt++) {
try {
return await this._callToolOnceWithReliabilityTimeout(toolName, args, timeoutMs);
} catch (error) {
lastError = error instanceof Error ? error : new Error(String(error));
const decision = this._decideReliabilityAttemptError(
toolName,
timeoutMs,
lastError,
timeoutObserved,
attempt,
timeoutRetries
);
timeoutObserved = decision.timeoutObserved;
Iif (decision.retry) {
continue;
}
throw decision.error ?? lastError;
}
}
throw lastError;
}
/**
* Wrapper variant of {@link safeCallTool} that enforces per-tool timeout/retry policy.
*
* @param toolName - MCP tool name
* @param args - Tool arguments or arg factory
* @param fallbackText - JSON fallback payload
* @returns Tool result or fallback
*/
protected async safeCallToolWithReliabilityTimeout(
toolName: string,
args: object | (() => object),
fallbackText: string
): Promise<MCPToolResult> {
this._calledTools.add(toolName);
try {
const resolvedArgs = typeof args === 'function' ? args() : args;
const result = await this.callToolWithReliabilityTimeout(toolName, resolvedArgs);
Iif (result.isError === true) {
return this._recordToolFailure(toolName, result.content?.[0]?.text ?? '', fallbackText);
}
Iif (isFeedUnavailable(result)) {
return this._recordToolFailure(
toolName,
`UPSTREAM_404: ${result.content?.[0]?.text?.slice(0, 200) ?? FEED_UNAVAILABLE_REASON}`,
fallbackText
);
}
this._failedTools.delete(toolName);
return result;
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
return this._recordToolFailure(toolName, message, fallbackText);
}
}
// \u2500\u2500\u2500 Diagnostics \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
/**
* Get a summary of tools that returned fallback data in the current session.
*
* @returns Map of tool name to error description
*/
getFailedTools(): ReadonlyMap<string, string> {
return new Map(this._failedTools);
}
/**
* Get tools that experienced a timeout but the failure was downgraded to a warning.
*
* @returns Map of tool name to warning description
*/
getSlowFeedWarnings(): ReadonlyMap<string, string> {
return new Map(this._slowFeedWarnings);
}
/**
* Get a human-readable feed health summary for diagnostics.
*
* @returns Formatted summary of feed availability
*/
getFeedHealthSummary(): string {
const feedTools = [
'get_meps_feed',
'get_events_feed',
'get_procedures_feed',
'get_adopted_texts_feed',
'get_mep_declarations_feed',
'get_documents_feed',
'get_plenary_documents_feed',
'get_committee_documents_feed',
'get_plenary_session_documents_feed',
'get_external_documents_feed',
'get_parliamentary_questions_feed',
'get_corporate_bodies_feed',
'get_controlled_vocabularies_feed',
];
const lines: string[] = ['EP MCP Feed Health:'];
let operational = 0;
let unchecked = 0;
for (const tool of feedTools) {
const error = this._failedTools.get(tool);
const slowWarning = this._slowFeedWarnings.get(tool);
if (error) {
lines.push(` \u274c ${tool}: ${error}`);
} else if (slowWarning) {
lines.push(` \ud83d\udfe1 ${tool}: ${slowWarning}`);
} else if (this._calledTools.has(tool)) {
lines.push(` \u2705 ${tool}`);
operational++;
} else {
lines.push(` \u26aa ${tool} (not checked)`);
unchecked++;
}
}
const checked = feedTools.length - unchecked;
lines.push(
` Summary: ${operational}/${checked} checked feeds operational${unchecked > 0 ? `, ${unchecked} unchecked` : ''}`
);
return lines.join('\n');
}
/**
* Get a per-error-code breakdown of tool-level rejections.
*
* @returns Formatted summary of tool errors by code
*/
getToolErrorSummary(): string {
if (this._failedTools.size === 0) {
return `EP MCP Tool Errors: 0 (all ${this._calledTools.size} invoked tools operational)`;
}
const byCode = new Map<string, string[]>();
for (const [tool, entry] of this._failedTools.entries()) {
const sepIdx = entry.indexOf(':');
const code = sepIdx > 0 ? entry.slice(0, sepIdx) : 'UNKNOWN';
const existing = byCode.get(code);
if (existing) {
existing.push(tool);
} else {
byCode.set(code, [tool]);
}
}
const lines: string[] = [
`EP MCP Tool Errors: ${this._failedTools.size} of ${this._calledTools.size} invoked tools rejected`,
];
const sortedCodes = [...byCode.keys()].sort();
for (const code of sortedCodes) {
const tools = byCode.get(code) ?? [];
lines.push(` ${code} (${tools.length}): ${tools.sort().join(', ')}`);
}
return lines.join('\n');
}
}
// \u2500\u2500\u2500 Singleton factory \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
let clientInstance: EuropeanParliamentMCPClient | null = null;
/**
* Get or create singleton MCP client instance
*
* @param options - Client options
* @returns Connected MCP client
*/
export async function getEPMCPClient(
options: MCPClientOptions = {}
): Promise<EuropeanParliamentMCPClient> {
if (!clientInstance) {
const client = new EuropeanParliamentMCPClient(options);
try {
await client.connect();
clientInstance = client;
} catch (error) {
clientInstance = null;
throw error;
}
}
return clientInstance;
}
/**
* Close and cleanup singleton MCP client
*/
export async function closeEPMCPClient(): Promise<void> {
if (clientInstance) {
clientInstance.disconnect();
clientInstance = null;
}
}
// Side-effect mixin imports live in the barrel (ep-mcp-client.ts) to avoid
// circular-dependency issues. ES module static imports are hoisted, so
// importing tools-*.ts from here causes the class to be accessed before it
// is initialised. See ep-mcp-client.ts for the actual imports.
|