# All files / src/tools searchDocuments.ts

73.91% Statements 17/23
62.5% Branches 5/8
66.66% Functions 2/3
76.19% Lines 16/21

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

    26x
    26x

    10x
    12x
    10x

    16x
    16x
    1x

    15x

    26x

    14x
    14x

    14x

    2x

    2x

    4x

     /**
     * MCP Tool: search_documents
     *
     * Search European Parliament legislative documents or retrieve a single document by ID.
     *
     * **Intelligence Perspective:** Essential for legislative monitoring, policy tracking,
     * amendment analysis, and building intelligence products around EU regulatory developments.
     *
     * **Business Perspective:** Enables document search products for legal firms, compliance
     * teams, and regulatory intelligence services requiring legislative text access.
     *
     * **Marketing Perspective:** Demonstrates comprehensive document search capability—
     * key for attracting legal tech, RegTech, and policy research customer segments.
     *
     * **EP API Endpoints:**
     * - `GET /documents` (list/search)
     * - `GET /documents/{doc-id}` (single)
     *
     * ISMS Policy: SC-002 (Input Validation), AC-003 (Least Privilege)
     */

    import { SearchDocumentsSchema, LegislativeDocumentSchema, PaginatedResponseSchema } from '../schemas/europeanParliament.js';
    import { epClient } from '../clients/europeanParliamentClient.js';
    import { buildToolResponse } from './shared/responseBuilder.js';
    import { buildApiParams } from './shared/paramBuilder.js';
    import { ToolError } from './shared/errors.js';
    import { z } from 'zod';
    import type { ToolResult } from './shared/types.js';

    /**
     * Handles the search_documents MCP tool request.
     *
     * Searches European Parliament legislative documents by keyword and optional filters, or
     * retrieves a single document by `docId`. Supports filtering by document type, date range,
     * and responsible committee. Returned document metadata includes titles, authors, status,
     * and links to PDF/XML versions.
     *
     * @param args - Raw tool arguments, validated against {@link SearchDocumentsSchema}
     * @returns MCP tool result containing matching legislative documents or a single document
     * @throws - If `args` fails schema validation (e.g., keyword exceeds 200 chars, bad date format)
     * - If the European Parliament API is unreachable or returns an error response
     *
     * @example
     * ```typescript
     * // Full-text keyword search with filters
     * const result = await handleSearchDocuments({
     *   keyword: 'climate change',
     *   documentType: 'REPORT',
     *   dateFrom: '2024-01-01',
     *   limit: 20
     * });
     * // Returns up to 20 EP reports matching "climate change" from 2024 onwards
     *
     * // Single document lookup by ID
     * const doc = await handleSearchDocuments({ docId: 'A9-0234/2024' });
     * // Returns the full metadata for document A9-0234/2024
     * ```
     *
     * @security Input is validated with Zod before any API call.
     *   Keyword pattern is restricted to alphanumeric characters, spaces, hyphens, and underscores
     *   to prevent injection. 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 searchDocumentsToolMetadata} for MCP schema registration
     * @see {@link handleGetExternalDocuments} for non-EP (external) document retrieval
     */
    export async function handleSearchDocuments(
      args: unknown
    ): Promise<ToolResult> {
      let params: ReturnType<typeof SearchDocumentsSchema.parse>;
      try {
        params = SearchDocumentsSchema.parse(args);
      } catch (error: unknown) {
        Eif (error instanceof z.ZodError) {
          const fieldErrors = error.issues.map(e => `${e.path.join('.')}: ${e.message}`).join('; ');
          throw new ToolError({
            toolName: 'search_documents',
            operation: 'validateInput',
            message: `Invalid parameters: ${fieldErrors}`,
            isRetryable: false,
            cause: error,
          });
        }
        throw error;
      }

      try {
        if (params.docId !== undefined) {
          const result = await epClient.getDocumentById(params.docId);
          const validated = LegislativeDocumentSchema.parse(result);
          return buildToolResponse(validated);
        }

        const apiParams = {
          keyword: params.keyword ?? '',
          limit: params.limit,
          offset: params.offset,
          ...buildApiParams(params, [
            { from: 'documentType', to: 'documentType' },
            { from: 'dateFrom', to: 'dateFrom' },
            { from: 'dateTo', to: 'dateTo' },
            { from: 'committee', to: 'committee' },
          ]),
        };

        const result = await epClient.searchDocuments(apiParams);

        const outputSchema = PaginatedResponseSchema(LegislativeDocumentSchema);
        const validated = outputSchema.parse(result);

        return buildToolResponse(validated);
      } catch (error: unknown) {
        Iif (error instanceof z.ZodError) {
          const fieldErrors = error.issues.map(e => `${e.path.join('.')}: ${e.message}`).join('; ');
          throw new ToolError({
            toolName: 'search_documents',
            operation: 'validateOutput',
            message: `Unexpected EP API response format: ${fieldErrors}`,
            isRetryable: false,
            cause: error,
          });
        }
        throw new ToolError({
          toolName: 'search_documents',
          operation: 'fetchData',
          message: 'Failed to search documents',
          isRetryable: true,
          cause: error,
        });
      }
    }

    /**
     * Tool metadata for MCP registration
     */
    export const searchDocumentsToolMetadata = {
      name: 'search_documents',
      description: 'Search European Parliament legislative documents by keyword, or retrieve a single document by docId. Filter by document type (REPORT, RESOLUTION, DECISION, DIRECTIVE, REGULATION, OPINION), date range, and committee. Returns document metadata including title, authors, status, and PDF/XML links.',
      inputSchema: {
        type: 'object' as const,
        properties: {
          docId: {
            type: 'string',
            description: 'Document ID for single document lookup (bypasses keyword search)'
          },
          keyword: {
            type: 'string',
            description: 'Search keyword or phrase (alphanumeric, spaces, hyphens, underscores only)',
            minLength: 1,
            maxLength: 200,
            pattern: '^[a-zA-Z0-9\\s\\-_]+$'
          },
          documentType: {
            type: 'string',
            description: 'Filter by document type',
            enum: ['REPORT', 'RESOLUTION', 'DECISION', 'DIRECTIVE', 'REGULATION', 'OPINION', 'AMENDMENT']
          },
          dateFrom: {
            type: 'string',
            description: 'Start date filter (YYYY-MM-DD format)',
            pattern: '^\\d{4}-\\d{2}-\\d{2}$'
          },
          dateTo: {
            type: 'string',
            description: 'End date filter (YYYY-MM-DD format)',
            pattern: '^\\d{4}-\\d{2}-\\d{2}$'
          },
          committee: {
            type: 'string',
            description: 'Committee identifier',
            minLength: 1,
            maxLength: 100
          },
          limit: {
            type: 'number',
            description: 'Maximum number of results to return (1-100)',
            minimum: 1,
            maximum: 100,
            default: 20
          },
          offset: {
            type: 'number',
            description: 'Pagination offset',
            minimum: 0,
            default: 0
          }
        }
      }
    };