EU Parliament Monitor โ€” API Documentation - v0.8.49
    Preparing search index...

    Class EuropeanParliamentMCPClient

    MCP Client for European Parliament data access. Extends MCPConnection with EP-specific tool wrapper methods.

    Hierarchy (View Summary)

    Index

    Constructors

    Methods

    _recordToolFailure safeCallTool getFailedTools getSlowFeedWarnings getFeedHealthSummary getToolErrorSummary getMEPs getPlenarySessions searchDocuments getParliamentaryQuestions getCommitteeInfo monitorLegislativePipeline analyzeLegislativeEffectiveness assessMEPInfluence analyzeCoalitionDynamics detectVotingAnomalies comparePoliticalGroups getMEPDetails getVotingRecords analyzeVotingPatterns trackLegislation generateReport analyzeCommitteeActivity trackMEPAttendance analyzeCountryDelegation generatePoliticalLandscape getCurrentMEPs getSpeeches getProcedures getFreshProcedures getAdoptedTexts _fetchAdoptedTextByDocId getDueAdoptedTextsForReprobe resolveAdoptedText escalateStalePendingDocuments getPendingDocumentsSummary getEvents getMeetingActivities getMeetingDecisions getMEPDeclarations getIncomingMEPs getOutgoingMEPs getHomonymMEPs getPlenaryDocuments getCommitteeDocuments getPlenarySessionDocuments getPlenarySessionDocumentItems getControlledVocabularies getExternalDocuments getMeetingForeseenActivities getProcedureEvents getMeetingPlenarySessionDocuments getMeetingPlenarySessionDocumentItems networkAnalysis sentimentTracker earlyWarningSystem comparativeIntelligence correlateIntelligence getAllGeneratedStats getMEPsFeed getEventsFeed getProceduresFeed getAdoptedTextsFeed getMEPDeclarationsFeed getDocumentsFeed getPlenaryDocumentsFeed getCommitteeDocumentsFeed getPlenarySessionDocumentsFeed getExternalDocumentsFeed getParliamentaryQuestionsFeed getCorporateBodiesFeed getControlledVocabulariesFeed getProcedureEventById getServerHealth isConnected isGatewayMode getGatewayUrl getGatewayApiKey getMcpSessionId getConnectionHealth connect disconnect handleMessage sendRequest listTools callTool callToolWithRetry

    Properties

    Constructors

    Methods

    • Record a tool failure and log a warning.

      Parameters

      • toolName: string

        MCP tool name that failed

      • errorText: string

        Raw error text from the failure

      • fallbackText: string

        JSON text for the fallback result

      Returns MCPToolResult

      Fallback MCPToolResult

    • Generic error-safe wrapper around callToolWithRetry. Retries transient failures (timeouts, connection drops) with a bounded back-off delay before falling back. Non-retriable errors (session expiry, rate limits, programmer errors) are caught immediately without additional delay. Catches any error thrown by the tool (or by the args factory), logs a warning, and returns a fallback payload.

      Also inspects the tool result for the MCP protocol isError flag. When isError === true, the first content item's text is passed through classifyToolError for diagnostic categorization, and the tool is recorded as failed via _recordToolFailure. This handles EP MCP Server error responses that are returned (not thrown) as structured results.

      Accepts either a plain args object or a factory function () => object. Using a factory ensures that options normalization/destructuring runs inside the try/catch so invalid runtime inputs fall back gracefully.

      Parameters

      • toolName: string

        MCP tool name

      • args: object | (() => object)

        Tool arguments or a factory that builds them

      • fallbackText: string

        JSON text to return when the tool is unavailable

      Returns Promise<MCPToolResult>

      Tool result or fallback

    • Get a summary of tools that returned fallback data in the current session. Useful for diagnosing feed availability and data quality issues.

      Returns ReadonlyMap<string, string>

      Map of tool name to error description

    • Get tools that experienced a timeout but the failure was downgraded to a warning. Unlike getFailedTools, entries here are not counted against the reliability score โ€” they represent expected-slow tools whose timeouts are classified as ๐ŸŸข LIMITATION (see .github/prompts/07-mcp-reference.md ยง11 row #8).

      Returns ReadonlyMap<string, string>

      Map of tool name to "SLOW_FEED: <message>" warning description

    • Get a human-readable feed health summary for diagnostics.

      Returns string

      Formatted summary of feed availability

    • Get a per-error-code breakdown of tool-level rejections recorded during the current session. Designed for end-of-run observability so regressions like Hack23/European-Parliament-MCP-Server#378 (raw upstream 404 leaking through as "successful" feed calls) surface in agent-stdio without needing to hand-comb the MCP gateway logs.

      Each entry in _failedTools is stored as "${errorCode}: ${message}" by _recordToolFailure. This method splits on the first colon to group tool names by error code.

      Returns string

      Formatted summary: one line per error code, with affected tools, terminated by a final counts line. Returns a single "all operational" line when no failures have been recorded.

    • Get plenary sessions

      Parameters

      Returns Promise<MCPToolResult>

      Plenary sessions data

      This repository is currently documented/configured against european-parliament-mcp-server@1.2.15.

      Upstream date-filter contract (v1.2.14+, active on the pinned v1.2.15 server): the upstream server applies a server-side post-filter on dateFrom/dateTo before serialisation, because the EP Open Data Portal /meetings endpoint silently ignores its date-from/date-to query parameters (Defect #5). Under this contract:

      • data[] contains only sessions within the requested window.
      • total reflects the filtered count, not the raw upstream count.
      • Per-window session counts are reproducible because the EP-side regression is masked by the upstream post-filter.

      No local post-filter is applied here. The repository is pinned to v1.2.15, so the date-filter guarantees above apply; consumers running against an older server image (pre-v1.2.14) must not assume them.

    • Get detailed information about a specific MEP

      Parameters

      • id: string

        MEP identifier (must be non-empty)

      Returns Promise<MCPToolResult>

      Detailed MEP information including biography, contact, and activities

    • Track a legislative procedure by its identifier

      Parameters

      • procedureId: string

        Legislative procedure identifier (must be non-empty)

      Returns Promise<MCPToolResult>

      Procedure status and timeline

    • Get fresh legislative procedures using client-side date filtering as a workaround for the broken EP /procedures/feed timeframe filter.

      Background: the EP Open Data Portal /procedures/feed endpoint stopped honouring the timeframe parameter on or around 2026-04-19 and began returning historical-tail pagination (oldest records first, all metadata empty). This regression is tracked as Defect #3 in analysis/daily/2026-04-24/propositions/intelligence/mcp-reliability-audit.md and has been reported to open-data-helpdesk@europarl.europa.eu.

      Strategy:

      1. Call get_procedures(limit=100, offset=0) โ€” the stable non-feed endpoint.
      2. Sort results client-side by dateLastActivity DESC, falling back to dateInitiated when dateLastActivity is empty.
      3. Keep procedures where the effective date >= today minus windowDays (default 30 days). Apply optional topN cap.
      4. Persist (procedureId, dateLastActivity) pairs to the seen-cache so subsequent runs can detect new/updated IDs without re-paginating.

      Parameters

      Returns Promise<MCPToolResult>

      Sorted, filtered procedure list in {"procedures": [...]} envelope

    • Get adopted texts (legislative resolutions, positions, non-legislative resolutions)

      When called with options.docId this method delegates to _fetchAdoptedTextByDocId which handles two CONTENT_PENDING conditions with the correct classification from the first log entry:

      1. UPSTREAM_404 indexing lag (primary, v1.2.13+): The EP MCP Server throws UPSTREAM_404: document indexed but content not yet available when the EP Open Data Portal has indexed a document identifier but the content body has not yet been populated (typically 5โ€“15-day lag). The docId is recorded in the pending-documents sidecar with exponential back-off scheduling so subsequent runs can re-probe without over-reporting the lag as a reliability defect.

      2. Empty-string sentinel (secondary, pre-v1.2.13 defence-in-depth): Every string field is "" โ€” upstream issue Hack23/European-Parliament-MCP-Server#369.

      In both cases the method returns the empty {"texts": []} fallback so downstream consumers do not render blank title/reference/date fields.

      Year-range list queries (no docId) use the standard safeCallTool wrapper and are not affected by content-availability detection.

      Parameters

      Returns Promise<MCPToolResult>

      Adopted texts data

    • Contextual fetcher for single-document get_adopted_texts lookups.

      Wraps callToolWithRetry directly so content-availability lag is classified as CONTENT_PENDING from the first log entry โ€” not reclassified from NOT_FOUND after the fact. Two conditions are handled:

      1. UPSTREAM_404 indexing lag (thrown exception or isError:true body): message contains CONTENT_NOT_YET_AVAILABLE_SUBSTRING.

      2. Empty-string sentinel (isError:false, pre-v1.2.13 defence-in-depth): every string field is "".

      Parameters

      • docId: string

        Trimmed document identifier

      Returns Promise<MCPToolResult>

      Adopted texts data or ADOPTED_TEXTS_FALLBACK

    • Return the docIds of pending adopted texts that are due for a re-probe according to their exponential back-off schedule.

      Call this at the start of each Stage B deep-fetch run to obtain the list of identifiers to re-probe. For each returned docId, call getAdoptedTexts with { docId }. If the fetch succeeds (real content returned), call resolveAdoptedText to mark it resolved.

      Returns Promise<string[]>

      Array of docIds due for reprobe (may be empty)

    • Mark a previously-pending adopted text as resolved (content is now available and has been successfully retrieved).

      Parameters

      • docId: string

        Adopted-text identifier (e.g., "TA-10-2026-0104")

      Returns Promise<void>

    • Escalate PENDING adopted texts that have exceeded the 14-day maximum tracking age. Escalated documents are excluded from future reprobes and should be handled by the wildcards-blackswans family.

      Returns Promise<string[]>

      Array of docIds that were escalated

    • Return a human-readable summary of the pending-documents sidecar for Stage B observability logging.

      Returns Promise<string>

      Formatted summary string

    • Retrieve precomputed European Parliament activity statistics (EP6โ€“EP10, 2004โ€“2025). Includes yearly stats, category rankings, political landscape history, and average-based predictions for 2026โ€“2030. Static data refreshed weekly โ€” no live API calls.

      Parameters

      Returns Promise<MCPToolResult>

      Precomputed EP statistics data

    • Get events feed (most recent updates via EP API v2)

      Implements special timeout-downgrade handling: when the call throws a timeout error, the failure is recorded in _slowFeedWarnings (not _failedTools) so it does not reduce the session reliability score. The events feed is documented as significantly slower than other feeds (30โ€“120 s+); timeouts during heavy EP API load are expected behaviour, classified as ๐ŸŸข LIMITATION in .github/prompts/07-mcp-reference.md ยง11 row #8.

      A fallback result with slowFeedWarning: true is returned so Stage A consumers can detect the condition and fall back to get_plenary_sessions({ year }).

      Non-timeout errors (404, 5xx, rate-limit, etc.) are still recorded as failures.

      Parameters

      Returns Promise<MCPToolResult>

      Events feed data, or { "feed": [], "slowFeedWarning": true } on timeout

    • Get procedures feed (most recent updates via EP API v2)

      Post-processes the response to detect "recess mode" โ€” when the EP procedures feed returns historical archive data (all items dated โ‰ค 1995) instead of current procedures. This happens during parliamentary recesses when the EP API serves its historical archive in ID order.

      When recess mode is detected:

      • recessMode: true is added to the payload
      • A RECESS_MODE: โ€ฆ entry is appended to dataQualityWarnings[]
      • A ๐ŸŸก procedures-feed: recess mode console warning is emitted

      The tool is not recorded as failed โ€” this is documented EP API behaviour classified as ๐ŸŸข LIMITATION in .github/prompts/07-mcp-reference.md ยง11 row #5. Downstream Stage A consumers should fall back to get_adopted_texts({ year: $YEAR }) or track_legislation({ procedureId }).

      Parameters

      Returns Promise<MCPToolResult>

      Procedures feed data, possibly with recessMode: true added to the payload

    • Get adopted texts feed (most recent updates via EP API v2)

      Post-processes the response to honour upstream freshness-fallback warnings added by Hack23/European-Parliament-MCP-Server when the feed payload contains no items from the current calendar year:

      • FRESHNESS_FALLBACK: โ€ฆ in dataQualityWarnings[] indicates the server augmented the response with GET /adopted-texts?year={currentYear}. The result is kept (do NOT downgrade to C4 โ€” the augmented items are confirmable, current-year, EP-published documents) and two fields are added to the payload:

        • freshness: "augmented" โ€” callers can detect the augmentation
        • dataFreshnessWarnings: string[] โ€” the subset of dataQualityWarnings that starts with FRESHNESS_FALLBACK, forwarded for Stage-A consumers
      • FRESHNESS_FALLBACK_FAILED: โ€ฆ indicates the feed was stale AND the fallback GET /adopted-texts?year=โ€ฆ also returned no items. The tool is recorded as failed (escalated to ANALYSIS_ONLY) so downstream consumers do not treat an empty-year dataset as fresh evidence.

      Parameters

      Returns Promise<MCPToolResult>

      Adopted texts feed data, possibly with augmented freshness fields

    • Check server health and feed availability status. Returns server version, uptime, per-feed health status, and overall availability. Does not make upstream API calls โ€” reports cached status from recent tool invocations.

      Returns Promise<MCPToolResult>

      Server health and feed availability data

    • Get connection health metrics for telemetry

      Returns { timeoutCount: number; reconnectCount: number; connected: boolean }

      Object with timeout count, reconnection count, and current connection status

    • Send a request to the MCP server

      Type Parameters

      • T = unknown

      Parameters

      • method: string

        RPC method name

      • params: Record<string, unknown> = {}

        Method parameters

      Returns Promise<T>

      Server response

    • Call an MCP tool with automatic retry on timeout or connection loss. Reconnects automatically if the connection was lost between attempts.

      Only transient failures are retried (see isRetriableError). Non-retriable errors โ€” rate-limit (429), session-expired (401), and programmer errors such as TypeError โ€” are re-thrown immediately without consuming any retry budget.

      Parameters

      • name: string

        Tool name

      • args: object = {}

        Tool arguments (plain object, non-null, not an array)

      • OptionalmaxRetries: number

        Override the default retry count from options

      Returns Promise<MCPToolResult>

      Tool execution result

    Properties

    _failedTools: Map<string, string> = ...

    Tracks tools that returned fallback data in the current session

    _calledTools: Set<string> = ...

    Tracks tools that have been called (attempted) in the current session

    _slowFeedWarnings: Map<string, 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. Currently used by getEventsFeed whose documented latency is 30โ€“120 s+.

    _pendingDocumentsStorePath: string | undefined

    Path to the pending-documents sidecar file. Undefined means "use the module-level default (<cwd>/data/pending-documents.json)".

    FEED_FALLBACK: "{\"feed\": []}" = '{"feed": []}'

    Fallback payload for feed tools

    serverLabel: string

    Human-readable server name for log messages