# All files / src/resources index.ts

95.04% Statements 115/121
84.09% Branches 74/88
100% Functions 21/21
94.87% Lines 111/117

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
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    455
    456
    457
    458
    459
    460
    461
    462
    463
    464
    465
    466
    467
    468
    469
    470
    471
    472
    473
    474
    475
    476
    477
    478
    479
    480
    481
    482
    483
    484
    485
    486
    487
    488
    489
    490
    491
    492
    493
    494
    495
    496
    497
    498
    499
    500
    501
    502
    503
    504
    505
    506
    507
    508
    509
    510
    511
    512
    513
    514
    515
    516
    517
    518
    519

    3x

    3x

    3x

    3x

    3x

    3x

    3x

    3x

    3x

    3x

    3x

    3x

    24x
    5x
    2x

    3x
    2x

    1x

    20x
    20x
    2x

    18x
    2x

    16x
    2x

    14x
    2x

    12x
    4x

    8x
    2x

    6x
    2x

    4x

    2x
    2x

    2x
    2x

    4x
    3x

    1x

    2x
    2x

    2x
    2x

    27x
    2x

    25x
    25x

    25x
    1x

    24x
    24x

    20x
    20x

    5x

    1x
    1x

    1x

    1x

    1x

    1x
    1x

    1x

    1x

    1x

    1x
    1x

    1x

    1x

    1x
    1x
    1x
    2x
    2x

    2x

    1x

    2x
    2x

    1x

    1x
    1x

    1x

    1x
    1x

    1x

    21x

    7x
    7x

    7x

    15x

    15x

    1x
    1x

    1x
    1x

    1x
    1x

    1x
    1x

    1x
    1x

    1x
    1x

    2x
    1x

    1x
    1x

    1x
    1x

    9x

     /**
     * MCP Resources for European Parliament Data Access
     *
     * Resource templates and handlers for direct EP data access via MCP resources.
     * Resources provide a standardized way to read EP data using URI patterns.
     *
     * **Intelligence Perspective:** Resources enable direct data access for intelligence
     * pipelines—bypassing tool call overhead for known-entity lookups and bulk retrieval.
     *
     * **Business Perspective:** Resource URIs provide stable, addressable data endpoints
     * that enterprise integrations can cache, bookmark, and reference programmatically.
     *
     * ISMS Policy: SC-002 (Input Validation), AC-003 (Least Privilege)
     *
     * @see https://spec.modelcontextprotocol.io/specification/server/resources/
     */

    import { z } from 'zod';
    import { epClient } from '../clients/europeanParliamentClient.js';

    /**
     * Resource template metadata for MCP listing
     */
    export interface ResourceTemplate {
      uriTemplate: string;
      name: string;
      description: string;
      mimeType: string;
    }

    /**
     * Resource content result
     */
    export interface ResourceContent {
      uri: string;
      mimeType: string;
      text: string;
    }

    /**
     * Resource read result
     */
    export interface ResourceReadResult {
      contents: ResourceContent[];
      [key: string]: unknown;
    }

    const mepResourceTemplate: ResourceTemplate = {
      uriTemplate: 'ep://meps/{mepId}',
      name: 'MEP Profile',
      description: 'European Parliament Member profile including biographical info, committee memberships, political group, and contact details.',
      mimeType: 'application/json'
    };

    const mepListResourceTemplate: ResourceTemplate = {
      uriTemplate: 'ep://meps',
      name: 'MEP List',
      description: 'List of current Members of the European Parliament with basic profile information.',
      mimeType: 'application/json'
    };

    const committeeResourceTemplate: ResourceTemplate = {
      uriTemplate: 'ep://committees/{committeeId}',
      name: 'Committee Information',
      description: 'European Parliament committee details including membership, leadership, and responsibilities.',
      mimeType: 'application/json'
    };

    const plenarySessionsResourceTemplate: ResourceTemplate = {
      uriTemplate: 'ep://plenary-sessions',
      name: 'Plenary Sessions',
      description: 'Recent European Parliament plenary sessions with dates, locations, and agenda items.',
      mimeType: 'application/json'
    };

    const votingRecordResourceTemplate: ResourceTemplate = {
      uriTemplate: 'ep://votes/{sessionId}',
      name: 'Voting Record',
      description: 'Voting records for a specific plenary session including vote breakdowns and results.',
      mimeType: 'application/json'
    };

    const politicalGroupsResourceTemplate: ResourceTemplate = {
      uriTemplate: 'ep://political-groups',
      name: 'Political Groups',
      description: 'European Parliament political groups with membership counts and leadership.',
      mimeType: 'application/json'
    };

    const procedureResourceTemplate: ResourceTemplate = {
      uriTemplate: 'ep://procedures/{procedureId}',
      name: 'Procedure Details',
      description: 'Legislative procedure details by process ID (format: YYYY-NNNN).',
      mimeType: 'application/json'
    };

    const plenaryDetailResourceTemplate: ResourceTemplate = {
      uriTemplate: 'ep://plenary/{plenaryId}',
      name: 'Plenary Session Detail',
      description: 'Specific plenary session details by session ID.',
      mimeType: 'application/json'
    };

    const documentResourceTemplate: ResourceTemplate = {
      uriTemplate: 'ep://documents/{documentId}',
      name: 'Legislative Document',
      description: 'Legislative document details by document ID.',
      mimeType: 'application/json'
    };

    const MepIdSchema = z.string().min(1).max(100);
    /** Generic resource ID validator (reused for procedures, plenary sessions, documents) */
    const ResourceIdSchema = z.string().min(1).max(200);

    /**
     * Procedure ID schema — enforces the YYYY-NNNN format expected by the EP API
     * `/procedures/{process-id}` endpoint (e.g. `"2024-0006"`).
     */
    const ProcedureIdSchema = ResourceIdSchema.regex(
      /^\d{4}-\d{4}$/,
      'Procedure ID must be in YYYY-NNNN format (e.g. "2024-0006")'
    );

    /**
     * Match MEP resource URIs
     */
    function matchMepUri(segments: string[]): { template: string; params: Record<string, string> } | null {
      if (segments[0] !== 'meps') return null;
      if (segments.length === 2 && segments[1] !== '') {
        return { template: 'mep_detail', params: { mepId: segments[1] ?? '' } };
      }
      if (segments.length === 1) {
        return { template: 'mep_list', params: {} };
      }
      return null;
    }

    /**
     * Match committee/session/vote resource URIs
     */
    function matchOtherUri(segments: string[]): { template: string; params: Record<string, string> } | null {
      const resource = segments[0];
      if (resource === 'committees') {
        return matchCommitteeUri(segments);
      }
      if (resource === 'plenary-sessions' && segments.length === 1) {
        return { template: 'plenary_sessions', params: {} };
      }
      if (resource === 'votes') {
        return matchVoteUri(segments);
      }
      if (resource === 'political-groups' && segments.length === 1) {
        return { template: 'political_groups', params: {} };
      }
      if (resource === 'procedures') {
        return matchProcedureUri(segments);
      }
      if (resource === 'plenary') {
        return matchPlenaryDetailUri(segments);
      }
      if (resource === 'documents') {
        return matchDocumentUri(segments);
      }
      return null;
    }

    /**
     * Match committee URI
     */
    function matchCommitteeUri(segments: string[]): { template: string; params: Record<string, string> } | null {
      Eif (segments.length === 2 && segments[1] !== '') {
        return { template: 'committee_detail', params: { committeeId: segments[1] ?? '' } };
      }
      return null;
    }

    /**
     * Match vote URI
     */
    function matchVoteUri(segments: string[]): { template: string; params: Record<string, string> } | null {
      Eif (segments.length === 2 && segments[1] !== '') {
        return { template: 'voting_record', params: { sessionId: segments[1] ?? '' } };
      }
      return null;
    }

    /**
     * Match procedure detail URI: ep://procedures/{id}
     */
    function matchProcedureUri(segments: string[]): { template: string; params: Record<string, string> } | null {
      if (segments.length === 2 && segments[1] !== '') {
        return { template: 'procedure_detail', params: { procedureId: segments[1] ?? '' } };
      }
      return null;
    }

    /**
     * Match plenary detail URI: ep://plenary/{id}
     */
    function matchPlenaryDetailUri(segments: string[]): { template: string; params: Record<string, string> } | null {
      Eif (segments.length === 2 && segments[1] !== '') {
        return { template: 'plenary_detail', params: { plenaryId: segments[1] ?? '' } };
      }
      return null;
    }

    /**
     * Match document detail URI: ep://documents/{id}
     */
    function matchDocumentUri(segments: string[]): { template: string; params: Record<string, string> } | null {
      Eif (segments.length === 2 && segments[1] !== '') {
        return { template: 'document_detail', params: { documentId: segments[1] ?? '' } };
      }
      return null;
    }

    /**
     * Parse a resource URI and extract template parameters
     */
    function parseResourceUri(uri: string): { template: string; params: Record<string, string> } {
      if (!uri.startsWith('ep://')) {
        throw new Error(`Invalid resource URI scheme: ${uri}. Must start with "ep://"`);
      }

      const path = uri.slice(5);
      const segments = path.split('/');

      if (segments.length === 0 || segments[0] === '') {
        throw new Error(`Invalid resource URI: ${uri}`);
      }

      const mepMatch = matchMepUri(segments);
      if (mepMatch !== null) return mepMatch;

      const otherMatch = matchOtherUri(segments);
      if (otherMatch !== null) return otherMatch;

      throw new Error(`Unknown resource URI: ${uri}`);
    }

    /**
     * Handle MEP detail resource request
     *
     * @param mepId - MEP identifier to look up
     * @returns Resource content with MEP details as JSON
     */
    async function handleMepDetail(mepId: string): Promise<ResourceContent> {
      const validId = MepIdSchema.parse(mepId);
      const data = await epClient.getMEPDetails(validId);

      return {
        uri: `ep://meps/${validId}`,
        mimeType: 'application/json',
        text: JSON.stringify({
          ...data,
          _source: 'European Parliament Open Data Portal',
          _accessedAt: new Date().toISOString()
        }, null, 2)
      };
    }

    /**
     * Handle MEP list resource request
     *
     * @returns Resource content with paginated MEP list as JSON
     */
    async function handleMepList(): Promise<ResourceContent> {
      const data = await epClient.getMEPs({ limit: 50 });

      return {
        uri: 'ep://meps',
        mimeType: 'application/json',
        text: JSON.stringify({
          ...data,
          _source: 'European Parliament Open Data Portal',
          _accessedAt: new Date().toISOString()
        }, null, 2)
      };
    }

    /**
     * Handle committee detail resource request
     *
     * @param committeeId - Committee identifier or abbreviation
     * @returns Resource content with committee details as JSON
     */
    async function handleCommitteeDetail(committeeId: string): Promise<ResourceContent> {
      const validId = ResourceIdSchema.parse(committeeId);
      const data = await epClient.getCommitteeInfo({ abbreviation: validId });

      return {
        uri: `ep://committees/${validId}`,
        mimeType: 'application/json',
        text: JSON.stringify({
          ...data,
          _source: 'European Parliament Open Data Portal',
          _accessedAt: new Date().toISOString()
        }, null, 2)
      };
    }

    /**
     * Handle plenary sessions resource request
     *
     * @returns Resource content with recent plenary sessions as JSON
     */
    async function handlePlenarySessions(): Promise<ResourceContent> {
      const data = await epClient.getPlenarySessions({ limit: 20 });

      return {
        uri: 'ep://plenary-sessions',
        mimeType: 'application/json',
        text: JSON.stringify({
          ...data,
          _source: 'European Parliament Open Data Portal',
          _accessedAt: new Date().toISOString()
        }, null, 2)
      };
    }

    /**
     * Handle voting record resource request
     *
     * @param sessionId - Session identifier for vote retrieval
     * @returns Resource content with voting records as JSON
     */
    async function handleVotingRecord(sessionId: string): Promise<ResourceContent> {
      const validId = ResourceIdSchema.parse(sessionId);
      const data = await epClient.getVotingRecords({ sessionId: validId });

      return {
        uri: `ep://votes/${validId}`,
        mimeType: 'application/json',
        text: JSON.stringify({
          ...data,
          _source: 'European Parliament Open Data Portal',
          _accessedAt: new Date().toISOString()
        }, null, 2)
      };
    }

    /**
     * Handle political groups resource request
     *
     * @returns Resource content with political group composition as JSON
     */
    async function handlePoliticalGroups(): Promise<ResourceContent> {
      const data = await epClient.getMEPs({ limit: 100 });

      const groups = new Map<string, number>();
      Eif (Array.isArray(data.data)) {
        for (const mep of data.data) {
          const group = (mep as { politicalGroup?: string }).politicalGroup ?? 'Unknown';
          groups.set(group, (groups.get(group) ?? 0) + 1);
        }
      }

      const groupList = Array.from(groups.entries()).map(([name, memberCount]) => ({
        name,
        memberCount
      }));

      return {
        uri: 'ep://political-groups',
        mimeType: 'application/json',
        text: JSON.stringify({
          politicalGroups: groupList,
          total: groupList.length,
          _source: 'European Parliament Open Data Portal',
          _accessedAt: new Date().toISOString()
        }, null, 2)
      };
    }

    /**
     * Handle procedure detail resource request (extended URI: ep://procedures/{procedureId})
     *
     * @param procedureId - Legislative procedure identifier (process-id format YYYY-NNNN)
     * @returns Resource content with procedure details as JSON
     */
    async function handleProcedureDetail(procedureId: string): Promise<ResourceContent> {
      const validId = ProcedureIdSchema.parse(procedureId);
      const data = await epClient.getProcedureById(validId);

      return {
        uri: `ep://procedures/${validId}`,
        mimeType: 'application/json',
        text: JSON.stringify({
          ...data,
          _source: 'European Parliament Open Data Portal',
          _accessedAt: new Date().toISOString()
        }, null, 2)
      };
    }

    /**
     * Handle plenary detail resource request (extended URI: ep://plenary/{plenaryId})
     *
     * Uses {@link EuropeanParliamentClient#getMeetingById} for a direct ID-based
     * lookup. Throws a not-found error if the EP API returns no matching session.
     *
     * @param plenaryId - Plenary session / meeting identifier
     * @returns Resource content with plenary session details as JSON
     */
    async function handlePlenaryDetail(plenaryId: string): Promise<ResourceContent> {
      const validId = ResourceIdSchema.parse(plenaryId);
      const session = await epClient.getMeetingById(validId);

      return {
        uri: `ep://plenary/${validId}`,
        mimeType: 'application/json',
        text: JSON.stringify({
          plenaryId: validId,
          session,
          _source: 'European Parliament Open Data Portal',
          _accessedAt: new Date().toISOString()
        }, null, 2)
      };
    }

    /**
     * Handle document detail resource request (extended URI: ep://documents/{documentId})
     *
     * @param documentId - Legislative document identifier
     * @returns Resource content with document details as JSON
     */
    async function handleDocumentDetail(documentId: string): Promise<ResourceContent> {
      const validId = ResourceIdSchema.parse(documentId);
      const data = await epClient.getDocumentById(validId);

      return {
        uri: `ep://documents/${validId}`,
        mimeType: 'application/json',
        text: JSON.stringify({
          ...data,
          _source: 'European Parliament Open Data Portal',
          _accessedAt: new Date().toISOString()
        }, null, 2)
      };
    }

    /**
     * Get all resource template metadata for MCP listing
     */
    export function getResourceTemplateArray(): ResourceTemplate[] {
      return [
        mepResourceTemplate,
        mepListResourceTemplate,
        committeeResourceTemplate,
        plenarySessionsResourceTemplate,
        votingRecordResourceTemplate,
        politicalGroupsResourceTemplate,
        procedureResourceTemplate,
        plenaryDetailResourceTemplate,
        documentResourceTemplate,
      ];
    }

    /**
     * Validate and extract required parameter from params
     */
    function requireParam(params: Record<string, string>, key: string, uriPattern: string): string {
      const value = params[key];
      Iif (value === undefined || value === '') {
        throw new Error(`${key} is required for ${uriPattern}`);
      }
      return value;
    }

    /**
     * Handle ReadResource request
     *
     * @param uri - Resource URI (e.g., "ep://meps/12345")
     * @returns Resource content
     * @throws Error if URI is invalid or resource not found
     */
    export async function handleReadResource(uri: string): Promise<ResourceReadResult> {
      const { template, params } = parseResourceUri(uri);

      let content: ResourceContent;

      switch (template) {
        case 'mep_detail':
          content = await handleMepDetail(requireParam(params, 'mepId', 'ep://meps/{mepId}'));
          break;
        case 'mep_list':
          content = await handleMepList();
          break;
        case 'committee_detail':
          content = await handleCommitteeDetail(requireParam(params, 'committeeId', 'ep://committees/{committeeId}'));
          break;
        case 'plenary_sessions':
          content = await handlePlenarySessions();
          break;
        case 'voting_record':
          content = await handleVotingRecord(requireParam(params, 'sessionId', 'ep://votes/{sessionId}'));
          break;
        case 'political_groups':
          content = await handlePoliticalGroups();
          break;
        case 'procedure_detail':
          content = await handleProcedureDetail(requireParam(params, 'procedureId', 'ep://procedures/{procedureId}'));
          break;
        case 'plenary_detail':
          content = await handlePlenaryDetail(requireParam(params, 'plenaryId', 'ep://plenary/{plenaryId}'));
          break;
        case 'document_detail':
          content = await handleDocumentDetail(requireParam(params, 'documentId', 'ep://documents/{documentId}'));
          break;
        default:
          throw new Error(`Unhandled resource template: ${template}`);
      }

      return { contents: [content] };
    }

    /** Export parseResourceUri for testing */
    export { parseResourceUri };