All files / src/server cli.ts

100% Statements 31/31
85% Branches 17/20
100% Functions 7/7
100% Lines 29/29

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                                                            37x 37x 37x 37x 37x 37x 37x   7x 7x 7x               12x 564x 12x     12x                                                               4x                   16x 752x 16x 16x 16x   16x 16x 16x 16x 16x 16x   16x                                                                 16x                                     14x            
/**
 * CLI command handlers for the MCP server.
 *
 * Provides `--help`, `--version`, and `--health` output for
 * standalone execution. These functions write directly to stdout
 * and exit the process.
 *
 * @module server/cli
 */
 
import { SERVER_NAME, SERVER_VERSION, DEFAULT_RATE_LIMIT_PER_MINUTE, DEFAULT_API_URL } from '../config.js';
import { getToolMetadataArray } from './toolRegistry.js';
import { getPromptMetadataArray } from '../prompts/index.js';
import { getResourceTemplateArray } from '../resources/index.js';
import { RateLimiter } from '../utils/rateLimiter.js';
import { MetricsService } from '../services/MetricsService.js';
import { HealthService } from '../services/HealthService.js';
import type { CLIOptions } from './types.js';
 
/** Re-export CLIOptions for consumers */
export type { CLIOptions };
 
/**
 * Sanitize URL to remove credentials.
 *
 * @param urlString - URL to sanitize
 * @returns Sanitized URL without credentials
 * @internal
 */
export function sanitizeUrl(urlString: string): string {
  try {
    const url = new URL(urlString);
    url.username = '';
    url.password = '';
    url.search = '';
    url.hash = '';
    return url.toString();
  } catch {
    const withoutQuery = urlString.split('?')[0] ?? urlString;
    const withoutFragment = withoutQuery.split('#')[0] ?? withoutQuery;
    return withoutFragment;
  }
}
 
/**
 * Display help text.
 */
export function showHelp(): void {
  const tools = getToolMetadataArray();
  const coreToolCount = tools.filter(t => t.category === 'core').length;
  const nonCoreToolCount = tools.length - coreToolCount;
 
  // eslint-disable-next-line no-console
  console.log(`
${SERVER_NAME} v${SERVER_VERSION}
 
European Parliament MCP Server - Access EU parliamentary data via Model Context Protocol
 
USAGE:
  npx european-parliament-mcp-server [OPTIONS]
 
OPTIONS:
  --help      Show this help message
  --version   Show version information
  --health    Show health check / diagnostics
 
CAPABILITIES:
  Tools:     ${String(tools.length)} (${String(coreToolCount)} core + ${String(nonCoreToolCount)} additional)
  Protocol:  Model Context Protocol (MCP) via stdio
 
ENVIRONMENT VARIABLES:
  EP_API_URL              Override EP API base URL
  EP_REQUEST_TIMEOUT_MS   Override request timeout (default: 10000ms)
  EP_CACHE_TTL            Cache TTL in ms (default: 900000)
  EP_RATE_LIMIT           Rate limit requests/min (default: ${String(DEFAULT_RATE_LIMIT_PER_MINUTE)})
 
For more information: https://github.com/Hack23/European-Parliament-MCP-Server
  `.trim());
}
 
/**
 * Display version information.
 */
export function showVersion(): void {
  // eslint-disable-next-line no-console
  console.log(`${SERVER_NAME} v${SERVER_VERSION}`);
}
 
/**
 * Display health check / diagnostics.
 *
 * Combines a static capability report with a dynamic health snapshot
 * produced by {@link HealthService}.
 */
export function showHealth(): void {
  const tools = getToolMetadataArray();
  const coreToolCount = tools.filter(t => t.category === 'core').length;
  const nonCoreToolCount = tools.length - coreToolCount;
  const prompts = getPromptMetadataArray();
  const resourceTemplates = getResourceTemplateArray();
 
  const rateLimitEnv = parseInt(process.env['EP_RATE_LIMIT'] ?? String(DEFAULT_RATE_LIMIT_PER_MINUTE), 10);
  const tokensPerInterval = Number.isFinite(rateLimitEnv) && rateLimitEnv > 0 ? rateLimitEnv : DEFAULT_RATE_LIMIT_PER_MINUTE;
  const rateLimiter = new RateLimiter({ tokensPerInterval, interval: 'minute' });
  const metricsService = new MetricsService();
  const healthService = new HealthService(rateLimiter, metricsService);
  const dynamicHealth = healthService.checkHealth();
 
  const health = {
    name: SERVER_NAME,
    version: SERVER_VERSION,
    status: dynamicHealth.status,
    capabilities: ['tools', 'resources', 'prompts'],
    tools: {
      total: tools.length,
      core: coreToolCount,
      nonCore: nonCoreToolCount,
    },
    prompts: {
      total: prompts.length,
    },
    resources: {
      templates: resourceTemplates.length,
    },
    epApiReachable: dynamicHealth.epApiReachable,
    cache: dynamicHealth.cache,
    rateLimiter: dynamicHealth.rateLimiter,
    uptimeMs: dynamicHealth.uptimeMs,
    environment: {
      nodeVersion: process.version,
      platform: process.platform,
      arch: process.arch,
    },
    configuration: {
      apiUrl: sanitizeUrl(process.env['EP_API_URL'] ?? DEFAULT_API_URL),
      cacheTTL: process.env['EP_CACHE_TTL'] ?? '900000',
      rateLimit: process.env['EP_RATE_LIMIT'] ?? String(DEFAULT_RATE_LIMIT_PER_MINUTE),
    },
  };
 
  // eslint-disable-next-line no-console
  console.log(JSON.stringify(health, null, 2));
}
 
/**
 * Parse an array of CLI argument strings into a typed {@link CLIOptions} object.
 *
 * Supports the canonical flags `--help` / `-h`, `--version` / `-v`,
 * and `--health`.
 *
 * @param argv - Array of raw argument strings (typically `process.argv.slice(2)`)
 * @returns Typed CLI options with boolean flags
 *
 * @example
 * ```typescript
 * const opts = parseCLIArgs(['--health']);
 * if (opts.health) showHealth();
 * ```
 */
export function parseCLIArgs(argv: string[]): CLIOptions {
  return {
    help: argv.includes('--help') || argv.includes('-h'),
    version: argv.includes('--version') || argv.includes('-v'),
    health: argv.includes('--health'),
  };
}