All files / src/mcp/ep-open-data client.ts

98.85% Statements 86/87
87.95% Branches 73/83
93.75% Functions 15/16
100% Lines 84/84

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                                                      25x                         25x 25x   25x     25x   25x 25x 3x   25x   25x             25x                 3x                 4x                   11x 11x 11x   3x 3x                       6x         8x                                               13x 13x 2x 2x   11x 11x             13x 7x 13x                 13x           4x 4x 4x                                 17x 17x 17x 15x 15x   1x                                     6x                                                 11x 11x 11x 11x 11x         9x 1x   8x   11x                           11x 8x 8x   1x 1x               2x                                                                               8x   8x 1x   7x 1x     6x 1x             5x   5x 5x   1x           4x 4x             4x 2x             2x           4x             2x                         5x 4x 4x 4x 3x   1x 1x     4x         7x 3x 3x      
// SPDX-FileCopyrightText: 2024-2026 Hack23 AB
// SPDX-License-Identifier: Apache-2.0
 
/**
 * @module MCP/ep-open-data/client
 * @description EPOpenDataClient class, getVotingRecordsWithFallback, and singleton lifecycle.
 */
 
import type { MCPToolResult } from '../../types/index.js';
import type {
  EPDecisionResponse,
  VotingRecordsFallbackResult,
  VotingRecordsFallbackOptions,
} from './types.js';
import {
  DEFAULT_EP_OPEN_DATA_BASE_URL,
  DEFAULT_EP_OPEN_DATA_TIMEOUT_MS,
  EP_OPEN_DATA_ATTRIBUTION,
  EMPTY_VOTES_FALLBACK,
  EP_GET_VOTING_RECORDS_TOOL,
} from './config.js';
import { unwrapLabel, wrapAsMCPResult, extractIdentifier } from './utils.js';
 
export class EPOpenDataClient {
  private readonly _apiBaseUrl: string;
  private readonly _timeoutMs: number;
  private readonly _fetchImpl: typeof fetch;
  private _connected = false;
 
  /**
   * Create a new EP Open Data REST fallback client.
   *
   * Resolves the API base URL and request timeout from (in order)
   * the explicit `options`, the `EP_OPEN_DATA_BASE_URL` /
   * `EP_OPEN_DATA_TIMEOUT_MS` environment variables, and finally the
   * module-level defaults.
   *
   * @param options - Optional overrides for base URL, timeout, and `fetch` impl.
   */
  constructor(options: VotingRecordsFallbackOptions = { dateFrom: '', dateTo: '' }) {
    const envBase = process.env['EP_OPEN_DATA_BASE_URL'];
    const envTimeout = process.env['EP_OPEN_DATA_TIMEOUT_MS'];
    const parsedEnvTimeout =
      envTimeout !== undefined && envTimeout !== '' ? Number.parseInt(envTimeout, 10) : Number.NaN;
 
    const base =
      options.apiBaseUrl ?? (envBase && envBase !== '' ? envBase : DEFAULT_EP_OPEN_DATA_BASE_URL);
 
    let end = base.length;
    while (end > 0 && base.charCodeAt(end - 1) === 47) {
      end -= 1;
    }
    this._apiBaseUrl = end === base.length ? base : base.slice(0, end);
 
    this._timeoutMs =
      options.timeoutMs !== undefined && Number.isFinite(options.timeoutMs) && options.timeoutMs > 0
        ? options.timeoutMs
        : Number.isFinite(parsedEnvTimeout) && parsedEnvTimeout > 0
          ? parsedEnvTimeout
          : DEFAULT_EP_OPEN_DATA_TIMEOUT_MS;
 
    this._fetchImpl = options.fetchImpl ?? globalThis.fetch.bind(globalThis);
  }
 
  /**
   * Base URL currently in use (set at construction time).
   *
   * @returns The fully-qualified EP Open Data Portal base URL (no trailing slash).
   */
  getApiBaseUrl(): string {
    return this._apiBaseUrl;
  }
 
  /**
   * Per-request timeout in milliseconds.
   *
   * @returns The timeout applied to every `fetch()` call.
   */
  getTimeoutMs(): number {
    return this._timeoutMs;
  }
 
  /**
   * Mark the client as ready (HTTP is stateless; validates URL shape only).
   *
   * @returns A resolved promise; never throws for valid URLs.
   * @throws When the base URL is malformed (e.g. missing protocol).
   */
  async connect(): Promise<void> {
    try {
      new URL(this._apiBaseUrl);
      this._connected = true;
    } catch (error) {
      const message = error instanceof Error ? error.message : String(error);
      throw new Error(`Invalid EP_OPEN_DATA_BASE_URL "${this._apiBaseUrl}": ${message}`, {
        cause: error,
      });
    }
  }
 
  /**
   * Whether {@link connect} has been called successfully.
   *
   * @returns `true` after a successful {@link connect}.
   */
  isConnected(): boolean {
    return this._connected;
  }
 
  /** Reset the connected flag. No real socket to close. */
  disconnect(): void {
    this._connected = false;
  }
 
  /**
   * Fetch roll-call voting records from the EP Open Data Portal.
   *
   * Virtual tool: `ep-get-voting-records` (see `EP_GET_VOTING_RECORDS_TOOL`).
   *
   * Queries `/decision?date-of-vote-start=<dateFrom>&date-of-vote-end=<dateTo>`
   * and normalises the JSON-LD response to a `{ votes: VoteEntry[] }`
   * envelope whose shape mirrors `get_voting_records` from the EP MCP server,
   * augmented with `_source` and `_attribution` metadata.
   *
   * Returns the EMPTY_VOTES_FALLBACK envelope on any error so callers can
   * safely chain the result through {@link EPOpenDataClient.isVotingDataEmpty}
   * without defensive try/catch.
   *
   * @param options - Query options. `dateFrom` and `dateTo` are required and
   *   must be non-empty YYYY-MM-DD strings.
   * @returns MCP-shaped result with `votes[]` array (possibly empty on error).
   */
  async getVotingRecords(
    options: Pick<VotingRecordsFallbackOptions, 'dateFrom' | 'dateTo' | 'limit' | 'offset'>
  ): Promise<MCPToolResult> {
    const { dateFrom, dateTo } = options;
    if (!dateFrom || !dateTo) {
      console.warn(`${EP_GET_VOTING_RECORDS_TOOL}: dateFrom and dateTo are required`);
      return EMPTY_VOTES_FALLBACK;
    }
    try {
      const qs = new URLSearchParams({
        'date-of-vote-start': dateFrom,
        'date-of-vote-end': dateTo,
        limit: String(options.limit ?? 50),
        offset: String(options.offset ?? 0),
        format: 'application/ld+json',
      });
      const json = await this._getJSON<EPDecisionResponse>(`/decision?${qs.toString()}`);
      const records = json?.data ?? [];
      const votes = records.map((r) => ({
        identifier: extractIdentifier(r),
        date: r.date ?? '',
        title: unwrapLabel(r.prefLabel),
        activityType: r.activityType ?? '',
        for: r.favorable ?? 0,
        against: r.against ?? 0,
        abstain: r.abstention ?? 0,
      }));
      return wrapAsMCPResult({
        votes,
        _source: 'ep-open-data-portal',
        _attribution: EP_OPEN_DATA_ATTRIBUTION,
      });
    } catch (error) {
      const message = error instanceof Error ? error.message : String(error);
      console.warn(`${EP_GET_VOTING_RECORDS_TOOL} not available:`, message);
      return EMPTY_VOTES_FALLBACK;
    }
  }
 
  // ─── Static helpers ──────────────────────────────────────────────────────
 
  /**
   * Return `true` when a `get_voting_records` (or fallback) result carries
   * zero votes. Used to decide whether to proceed to the next fallback tier.
   *
   * Handles both the `{"votes":[]}` MCP empty shape and the plain
   * `{"votes":null}` edge case.
   *
   * @param result - MCP tool result to inspect.
   * @returns `true` when the votes array is absent or empty.
   */
  static isVotingDataEmpty(result: MCPToolResult): boolean {
    try {
      const text = result.content?.[0]?.text ?? '';
      if (!text) return true;
      const parsed = JSON.parse(text) as { votes?: unknown[] | null };
      return !Array.isArray(parsed.votes) || parsed.votes.length === 0;
    } catch {
      return true;
    }
  }
 
  /**
   * Build the canonical `🔴 voting data unavailable` marker emitted when
   * both MCP and the EP Open Data Portal fallback return empty.
   *
   * The returned payload remains a normal MCP JSON envelope containing an
   * empty `votes` array plus human-readable marker metadata (`_marker`,
   * `_reason`, `_unavailable`). This preserves compatibility with consumers
   * that parse `response.content[0]?.text` as JSON, while still exposing a
   * clear alert message for downstream display or diagnostics.
   *
   * @param dateFrom - Analysis period start (YYYY-MM-DD).
   * @param dateTo   - Analysis period end (YYYY-MM-DD).
   * @returns MCP-shaped result containing the 🔴 unavailability marker.
   */
  static buildVotingUnavailableMarker(dateFrom: string, dateTo: string): MCPToolResult {
    return wrapAsMCPResult({
      votes: [],
      _unavailable: true,
      _marker: `🔴 voting data unavailable for window ${dateFrom} → ${dateTo}`,
      _reason:
        'EP MCP server returned no roll-call votes and EP Open Data Portal returned no decisions ' +
        'for the requested window. This is expected when the window lies within the 4–6 week EP ' +
        'publication delay AND no older data has been published. Do not substitute with ' +
        'structural-proxy cohesion scores without an explicit LOW-confidence flag per ' +
        'osint-tradecraft-standards.md §3.1.',
    });
  }
 
  // ─── Private transport helpers ────────────────────────────────────────────
 
  /**
   * Build a full URL and GET it as text, enforcing the client-wide timeout.
   *
   * @param path - Path (already URL-encoded) to append to the base URL.
   * @returns Response body as a string.
   * @throws When the HTTP status is not 2xx, the request times out, or
   *   the network layer raises.
   * @internal
   */
  private async _getText(path: string): Promise<string> {
    const url = `${this._apiBaseUrl}${path.startsWith('/') ? path : `/${path}`}`;
    const controller = new AbortController();
    const timer = setTimeout(() => controller.abort(), this._timeoutMs);
    try {
      const response = await this._fetchImpl(url, {
        method: 'GET',
        headers: { Accept: 'application/ld+json, application/json;q=0.9' },
        signal: controller.signal,
      });
      if (!response.ok) {
        throw new Error(`HTTP ${response.status} ${response.statusText} for ${url}`);
      }
      return await response.text();
    } finally {
      clearTimeout(timer);
    }
  }
 
  /**
   * GET a URL and parse the response body as JSON.
   *
   * @template T - Narrow response type declared by the caller.
   * @param path - Path to append to the base URL.
   * @returns Parsed JSON value.
   * @throws When the response is not JSON, not 2xx, or the request fails.
   * @internal
   */
  private async _getJSON<T>(path: string): Promise<T> {
    const raw = await this._getText(path);
    try {
      return JSON.parse(raw) as T;
    } catch (error) {
      const message = error instanceof Error ? error.message : String(error);
      throw new Error(`Failed to parse EP Open Data response as JSON: ${message}`, {
        cause: error,
      });
    }
  }
}
 
/** Forward-looking alias (preferred for new code). */
export const EPOpenDataPortalClient = EPOpenDataClient;
 
// ─── Top-level three-state fallback helper ────────────────────────────────────
 
/**
 * Execute the three-state voting-data fallback decision tree.
 *
 * Given an already-retrieved MCP result and fallback options (dateFrom /
 * dateTo / fetchImpl / …), returns a {@link VotingRecordsFallbackResult}
 * that records both the data and the provenance label consumed by the
 * `voting-patterns.md` §"Voting Data Freshness" section.
 *
 * Decision tree:
 * ```
 * (a) mcpResult has votes  → source: "mcp",                freshness: 🟢
 * (b) MCP empty, portal ok → source: "ep-open-data-portal", freshness: 🟡
 * (c) both empty           → source: "unavailable",          freshness: 🔴
 * ```
 *
 * @param mcpResult - Result of `get_voting_records` from the EP MCP server.
 * @param options   - Fallback options; `dateFrom` and `dateTo` are required
 *   non-empty YYYY-MM-DD strings.
 * @returns Fallback result with source tag and human-readable freshness label.
 * @throws When `dateFrom` or `dateTo` is missing/blank, or when the EP Open
 *   Data Portal base URL is malformed (configuration error — distinct from
 *   the 🔴 `unavailable` data-empty path).
 *
 * @example
 * ```ts
 * const mcp = await epClient.getVotingRecords({ dateFrom, dateTo, limit: 50 });
 * const { result, source, freshnessLabel } = await getVotingRecordsWithFallback(mcp, {
 *   dateFrom, dateTo,
 * });
 * // Write freshnessLabel into voting-patterns.md §"Voting Data Freshness"
 * ```
 */
export async function getVotingRecordsWithFallback(
  mcpResult: MCPToolResult,
  options: VotingRecordsFallbackOptions
): Promise<VotingRecordsFallbackResult> {
  const { dateFrom, dateTo } = options;
 
  if (typeof dateFrom !== 'string' || dateFrom.trim() === '') {
    throw new Error('getVotingRecordsWithFallback: dateFrom is required (non-empty YYYY-MM-DD)');
  }
  if (typeof dateTo !== 'string' || dateTo.trim() === '') {
    throw new Error('getVotingRecordsWithFallback: dateTo is required (non-empty YYYY-MM-DD)');
  }
 
  if (!EPOpenDataClient.isVotingDataEmpty(mcpResult)) {
    return {
      result: mcpResult,
      source: 'mcp',
      freshnessLabel: `🟢 MCP (${dateFrom} → ${dateTo})`,
    };
  }
 
  const portalClient = new EPOpenDataClient(options);
 
  try {
    await portalClient.connect();
  } catch (error) {
    throw new Error(
      'Invalid EP Open Data Portal configuration: unable to validate EP_OPEN_DATA_BASE_URL',
      { cause: error }
    );
  }
 
  try {
    const portalResult = await portalClient.getVotingRecords({
      dateFrom,
      dateTo,
      ...(options.limit !== undefined ? { limit: options.limit } : {}),
      ...(options.offset !== undefined ? { offset: options.offset } : {}),
    });
 
    if (!EPOpenDataClient.isVotingDataEmpty(portalResult)) {
      return {
        result: portalResult,
        source: 'ep-open-data-portal',
        freshnessLabel: `🟡 EP Open Data Portal fallback (${dateFrom} → ${dateTo}) — attribution: ${EP_OPEN_DATA_ATTRIBUTION}`,
      };
    }
 
    return {
      result: EPOpenDataClient.buildVotingUnavailableMarker(dateFrom, dateTo),
      source: 'unavailable',
      freshnessLabel: `🔴 voting data unavailable for window ${dateFrom} → ${dateTo}`,
    };
  } finally {
    portalClient.disconnect();
  }
}
 
// ─── Singleton lifecycle ──────────────────────────────────────────────────────
 
/** Singleton instance, created lazily by {@link getEPOpenDataClient}. */
let epOpenDataClientInstance: EPOpenDataClient | null = null;
 
/**
 * Get or create the singleton EP Open Data client, validating the base URL
 * on first use. Subsequent calls return the cached instance.
 *
 * @param options - Client options (override env vars and defaults).
 * @returns Connected singleton client.
 * @throws When the base URL is malformed.
 */
export async function getEPOpenDataClient(
  options: VotingRecordsFallbackOptions = { dateFrom: '', dateTo: '' }
): Promise<EPOpenDataClient> {
  if (!epOpenDataClientInstance) {
    const client = new EPOpenDataClient(options);
    try {
      await client.connect();
      epOpenDataClientInstance = client;
    } catch (error) {
      epOpenDataClientInstance = null;
      throw error;
    }
  }
  return epOpenDataClientInstance;
}
 
/** Close and clear the singleton instance (idempotent). */
export async function closeEPOpenDataClient(): Promise<void> {
  if (epOpenDataClientInstance) {
    epOpenDataClientInstance.disconnect();
    epOpenDataClientInstance = null;
  }
}