All files / mcp mcp-connection.ts

84.86% Statements 258/304
72.98% Branches 154/211
92.68% Functions 38/41
84.74% Lines 250/295

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 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907                                                    12x     12x     12x           12x     12x     12x     12x     12x               9x 9x                       8x 8x 8x                         5x 5x 5x 5x 1x 1x 1x                                               91x 5x   86x       91x 3x   83x                                         13x 13x 2x   11x 11x 7x   4x 4x 1x   3x 3x 2x 2x   1x                             10x 10x 21x 21x 12x 12x 10x 10x             3x                                                                   251x   251x 251x 251x 251x 251x 251x 251x 251x 251x 251x 251x 251x   251x 251x 251x 251x                 10x                 4x                 1x                 2x                 2x                 8x                                 1x 1x                           3x 1x   2x 2x 1x         1x   1x             7x 1x     6x 4x 4x   2x     6x 6x 7x 7x 5x   2x   4x 4x   3x 3x     3x                       2x               2x       2x 2x 2x                                                 11x 11x 2x       9x 2x                 7x         7x 7x 4x 4x 4x         3x 11x   11x 1x     2x             5x 5x       5x       5x                     5x             4x 2x     2x 2x 1x       2x 5x 2x   2x 2x   3x 3x 3x               1x 1x 1x 1x   1x       1x 1x   1x                       1x 1x 1x 1x       1x 1x 1x   1x           1x         1x   1x       1x 1x                       197x 4x 4x   197x 197x                 5x 5x   5x 2x 2x   2x 1x   1x   2x 1x     1x 1x 1x                     12x 3x 3x 3x   9x   7x 7x 7x 5x 5x 5x 5x   2x 7x         2x                           10x 10x             10x       10x     10x 1x     10x             10x 10x                 10x                                                       4x 2x     2x       2x 2x             2x 2x   2x 2x   2x                             1x                     4x 1x       3x                     6x 1x   5x 5x 5x 5x 5x   5x                                   5x   5x 5x       5x 5x 5x 5x   1x                                         9x 7x 7x       2x   9x 1x   9x                                         160x 160x 2x   158x 158x 167x 167x   81x 81x 11x 9x     2x      
// SPDX-FileCopyrightText: 2024-2026 Hack23 AB
// SPDX-License-Identifier: Apache-2.0
 
/**
 * @module MCP/MCPConnection
 * @description Base MCP client — JSON-RPC 2.0 transport over stdio or HTTP gateway.
 * Supports two transport modes:
 * - **stdio**: Spawns the EP MCP server binary as a child process (default)
 * - **gateway**: Connects to an MCP Gateway via HTTP (for agentic workflow environments)
 *
 * Gateway mode is activated when `EP_MCP_GATEWAY_URL` env var is set or
 * `gatewayUrl` is provided in options.
 */
 
import { spawn, type ChildProcess } from 'child_process';
import { resolve, dirname } from 'path';
import { fileURLToPath } from 'url';
import type {
  MCPClientOptions,
  MCPToolResult,
  JSONRPCRequest,
  JSONRPCResponse,
  PendingRequest,
} from '../types/index.js';
 
/** npm binary name for the European Parliament MCP server */
const BINARY_NAME = 'european-parliament-mcp-server';
 
/** Platform-specific binary filename (Windows uses .cmd shim) */
const BINARY_FILE = process.platform === 'win32' ? `${BINARY_NAME}.cmd` : BINARY_NAME;
 
/** Default binary resolved from node_modules/.bin relative to this file's compiled location */
const DEFAULT_SERVER_BINARY = resolve(
  dirname(fileURLToPath(import.meta.url)),
  `../../node_modules/.bin/${BINARY_FILE}`
);
 
/** Request timeout in milliseconds — EU Parliament API responses commonly take 30+ seconds */
const REQUEST_TIMEOUT_MS = 60000;
 
/** Connection startup delay in milliseconds */
const CONNECTION_STARTUP_DELAY_MS = 500;
 
/** Maximum reconnect back-off delay in milliseconds */
const RECONNECT_MAX_DELAY_MS = 30000;
 
/** HTTP header for API rate-limit retry delay */
const RETRY_AFTER_HEADER = 'X-Retry-After';
 
/** Log prefix for rate-limit warnings */
const RATE_LIMIT_MSG = 'Rate limited. Retry after';
 
/**
 * Typed error thrown when the MCP gateway returns 401 (session expired).
 * Callers can detect this with `instanceof MCPSessionExpiredError` to trigger re-authentication.
 */
export class MCPSessionExpiredError extends Error {
  constructor(statusText: string) {
    super(`MCP session expired (401): ${statusText}`);
    this.name = 'MCPSessionExpiredError';
  }
}
 
/**
 * Typed error thrown when the MCP gateway returns 429 (rate limited).
 * Carries the parsed `retryAfterMs` delay so callers can honour the back-off period.
 * `retryAfterMs` is 0 when no Retry-After / X-Retry-After header was present.
 */
export class MCPRateLimitError extends Error {
  readonly retryAfterMs: number;
  constructor(retryAfterMs: number, message: string) {
    super(message);
    this.name = 'MCPRateLimitError';
    this.retryAfterMs = retryAfterMs;
  }
}
 
/**
 * Parse a `Retry-After` or `X-Retry-After` header value into milliseconds.
 * Accepts delta-seconds ("30"), numeric-with-suffix ("30s"), or an HTTP-date string.
 * Returns 0 when the value is empty or unparseable.
 *
 * @param retryAfter - Raw Retry-After / X-Retry-After header value
 * @returns Delay in milliseconds, or 0 if the value cannot be parsed
 */
function parseRetryAfterMs(retryAfter: string): number {
  const normalized = retryAfter.trim().replace(/s$/i, '');
  Iif (!normalized) return 0;
  const numericDelay = Number(normalized);
  if (!Number.isNaN(numericDelay)) return numericDelay * 1000;
  const retryDate = new Date(retryAfter);
  Eif (!Number.isNaN(retryDate.getTime())) {
    return Math.max(0, retryDate.getTime() - Date.now());
  }
  return 0;
}
 
/**
 * Returns true only for transient, retriable failures: request timeouts,
 * network-level connection-closed/reset errors, and "not connected" states.
 *
 * Uses an allow-list of known transient error patterns so that unknown or
 * server-level errors (e.g., tool runtime failures) are NOT retried:
 * - timeout — AbortSignal timeout or custom timeout message
 * - connection closed / reset / refused — network-level transport failures
 * - not connected — local "not yet connected" guard error
 * - socket hang up — Node.js HTTP socket-level disconnection
 *
 * Everything else (MCPSessionExpiredError, TypeError, rate-limit errors,
 * unknown errors) returns false so `callToolWithRetry` surfaces them immediately.
 *
 * @param error - The caught error to classify
 * @returns `true` if the error is safe to retry
 */
export function isRetriableError(error: Error): boolean {
  // Never retry session expiry or programmer errors — these require intervention
  if (error instanceof MCPSessionExpiredError || error instanceof TypeError) {
    return false;
  }
  const msg = error.message?.toLowerCase() ?? '';
  // Never retry rate-limit errors — callers must honour the Retry-After delay.
  // `instanceof MCPRateLimitError` is the primary guard for typed errors;
  // the string prefix fallback handles any legacy plain Error with a rate-limit message.
  if (error instanceof MCPRateLimitError || msg.startsWith(RATE_LIMIT_MSG.toLowerCase())) {
    return false;
  }
  return (
    msg.includes('timeout') ||
    msg.includes('connection closed') ||
    msg.includes('connection reset') ||
    msg.includes('not connected') ||
    msg.includes('econnreset') ||
    msg.includes('econnrefused') ||
    msg.includes('socket hang up')
  );
}
 
/**
 * Parse a `Retry-After` or `X-Retry-After` header value (which may be either a
 * delay-in-seconds number, a numeric string with an optional trailing "s" suffix
 * (e.g. "30s"), or an HTTP-date string) into a human-readable message.
 *
 * @param retryAfter - Raw header value
 * @returns Formatted string describing the delay (e.g. "30s" or "45s (until Thu, 01 Jan 2026 …)")
 */
export function formatRetryAfter(retryAfter: string): string {
  // Accept both bare numbers ("30") and numeric-with-suffix ("30s")
  const normalized = retryAfter.trim().replace(/s$/i, '');
  if (!normalized) {
    return retryAfter;
  }
  const numericDelay = Number(normalized);
  if (!Number.isNaN(numericDelay)) {
    return `${numericDelay}s`;
  }
  const retryDate = new Date(retryAfter);
  if (Number.isNaN(retryDate.getTime())) {
    return retryAfter;
  }
  const delayMs = retryDate.getTime() - Date.now();
  if (delayMs > 0) {
    const delaySeconds = Math.ceil(delayMs / 1000);
    return `${delaySeconds}s (until ${retryDate.toUTCString()})`;
  }
  return retryDate.toUTCString();
}
 
/**
 * Parse an SSE (Server-Sent Events) response body to extract the first valid JSON-RPC message.
 *
 * The MCP Streamable HTTP protocol sends JSON-RPC responses as SSE `data:` lines.
 * This function returns the **first** successfully parsed JSON-RPC message; any
 * subsequent `data:` lines are ignored. This matches the MCP protocol expectation
 * of one JSON-RPC response per HTTP request/response cycle.
 *
 * @param body - Raw SSE response text (may contain multiple lines including `event:` and `data:`)
 * @returns The first valid JSON-RPC response found, or null if no valid message exists
 */
export function parseSSEResponse(body: string): JSONRPCResponse | null {
  const lines = body.split('\n');
  for (const line of lines) {
    const trimmed = line.trim();
    if (trimmed.startsWith('data:')) {
      const jsonStr = trimmed.slice(5).trim();
      if (jsonStr) {
        try {
          return JSON.parse(jsonStr) as JSONRPCResponse;
        } catch {
          // Continue to next data line
        }
      }
    }
  }
  return null;
}
 
/**
 * Base MCP connection managing JSON-RPC 2.0 transport over stdio or HTTP gateway.
 * Extended by domain-specific clients to add tool wrapper methods.
 */
export class MCPConnection {
  private serverPath: string;
  private connected: boolean;
  private process: ChildProcess | null;
  private requestId: number;
  private pendingRequests: Map<number, PendingRequest>;
  private connectionAttempts: number;
  private maxConnectionAttempts: number;
  private connectionRetryDelay: number;
  private maxRetries: number;
  private reconnectingPromise: Promise<void> | null;
  private timeoutCount: number;
  private reconnectCount: number;
 
  /** Gateway URL for HTTP transport mode */
  private gatewayUrl: string | null;
 
  /** API key for gateway authentication */
  private gatewayApiKey: string | null;
 
  /** MCP session ID returned by the gateway */
  private mcpSessionId: string | null;
 
  /** Human-readable server name for log messages */
  protected serverLabel: string;
 
  constructor(options: MCPClientOptions = {}) {
    this.serverPath =
      options.serverPath ?? process.env['EP_MCP_SERVER_PATH'] ?? DEFAULT_SERVER_BINARY;
    this.connected = false;
    this.process = null;
    this.requestId = 0;
    this.pendingRequests = new Map();
    this.connectionAttempts = 0;
    this.maxConnectionAttempts = Math.max(1, options.maxConnectionAttempts ?? 3);
    this.connectionRetryDelay = options.connectionRetryDelay ?? 1000;
    this.maxRetries = options.maxRetries ?? 2;
    this.reconnectingPromise = null;
    this.timeoutCount = 0;
    this.reconnectCount = 0;
    this.serverLabel = options.serverLabel ?? 'European Parliament MCP Server';
 
    const rawGatewayUrl = (options.gatewayUrl ?? process.env['EP_MCP_GATEWAY_URL'] ?? '').trim();
    this.gatewayUrl = rawGatewayUrl || null;
    this.gatewayApiKey = options.gatewayApiKey ?? process.env['EP_MCP_GATEWAY_API_KEY'] ?? null;
    this.mcpSessionId = null;
  }
 
  /**
   * Check if client is connected
   *
   * @returns Connection status
   */
  isConnected(): boolean {
    return this.connected;
  }
 
  /**
   * Check if using gateway HTTP transport
   *
   * @returns True if gateway mode is active
   */
  isGatewayMode(): boolean {
    return Boolean(this.gatewayUrl);
  }
 
  /**
   * Get the configured gateway URL
   *
   * @returns Gateway URL or null if using stdio transport
   */
  getGatewayUrl(): string | null {
    return this.gatewayUrl;
  }
 
  /**
   * Get the configured gateway API key
   *
   * @returns Gateway API key or null if not set
   */
  getGatewayApiKey(): string | null {
    return this.gatewayApiKey;
  }
 
  /**
   * Get the current MCP session ID
   *
   * @returns Session ID returned by the gateway, or null if not yet connected
   */
  getMcpSessionId(): string | null {
    return this.mcpSessionId;
  }
 
  /**
   * Get connection health metrics for telemetry
   *
   * @returns Object with timeout count, reconnection count, and current connection status
   */
  getConnectionHealth(): { timeoutCount: number; reconnectCount: number; connected: boolean } {
    return {
      timeoutCount: this.timeoutCount,
      reconnectCount: this.reconnectCount,
      connected: this.connected,
    };
  }
 
  /**
   * Compute the delay before the next connection attempt.
   * Respects `Retry-After` carried by {@link MCPRateLimitError}; otherwise uses
   * exponential back-off (`connectionRetryDelay * 2^(attempt - 1)`).
   *
   * @param error - The error from the failed attempt
   * @param attempt - Number of attempts made so far (1-indexed)
   * @returns Delay in milliseconds
   */
  private _computeConnectionDelay(error: unknown, attempt: number): number {
    Eif (error instanceof MCPRateLimitError && error.retryAfterMs > 0) {
      return error.retryAfterMs;
    }
    return this.connectionRetryDelay * Math.pow(2, attempt - 1);
  }
 
  /**
   * Handle a single connection attempt error: re-throw immediately for non-retriable errors
   * (e.g. session expiry), increment the attempt counter, and return the delay to wait
   * before the next attempt. Throws when the maximum attempts have been exhausted.
   *
   * @param error - The error from the failed attempt
   * @returns Delay in milliseconds to wait before the next attempt
   */
  private _handleConnectionAttemptError(error: unknown): number {
    if (error instanceof MCPSessionExpiredError) {
      throw error;
    }
    this.connectionAttempts++;
    if (this.connectionAttempts >= this.maxConnectionAttempts) {
      console.error(
        '❌ Failed to connect to MCP server after',
        this.maxConnectionAttempts,
        'attempts'
      );
      throw error;
    }
    return this._computeConnectionDelay(error, this.connectionAttempts);
  }
 
  /**
   * Connect to the MCP server with retry logic
   */
  async connect(): Promise<void> {
    if (this.connected) {
      return;
    }
 
    if (this.gatewayUrl) {
      console.log(`🔌 Connecting to ${this.serverLabel} via gateway...`);
      console.log(`   Gateway URL: ${this.gatewayUrl}`);
    } else {
      console.log(`🔌 Connecting to ${this.serverLabel}...`);
    }
 
    this.connectionAttempts = 0;
    while (this.connectionAttempts < this.maxConnectionAttempts) {
      try {
        if (this.gatewayUrl) {
          await this._attemptGatewayConnection();
        } else {
          await this._attemptConnection();
        }
        this.connectionAttempts = 0; // Reset on success
        return;
      } catch (error) {
        const delay = this._handleConnectionAttemptError(error);
        console.warn(
          `⚠️ Connection attempt ${this.connectionAttempts} failed. Retrying in ${delay}ms...`
        );
        await new Promise((resolve) => setTimeout(resolve, delay));
      }
    }
  }
 
  /**
   * Validate a gateway response body, throwing on JSON-RPC errors.
   *
   * @param contentType - Response content-type header
   * @param body - Raw response body text
   */
  private _validateGatewayResponseBody(contentType: string, body: string): void {
    Iif (contentType.includes('text/event-stream')) {
      const parsed = parseSSEResponse(body);
      if (parsed?.error) {
        throw new Error(parsed.error.message ?? 'MCP gateway initialization error');
      }
      return;
    }
 
    Iif (!body) {
      return;
    }
 
    try {
      const jsonResponse = JSON.parse(body) as JSONRPCResponse;
      Iif (jsonResponse.error) {
        throw new Error(jsonResponse.error.message ?? 'MCP gateway initialization error');
      }
    } catch (e) {
      // Non-JSON body is acceptable for init — some gateways return empty/plain text
      if (e instanceof Error && e.message.includes('MCP gateway')) {
        throw e;
      }
    }
  }
 
  /**
   * Build the Authorization header value for gateway requests.
   * Keys that already contain a valid RFC 7235 scheme token followed by
   * whitespace (e.g. "Bearer …", "Token …", "AWS4-HMAC-SHA256 …") are passed
   * through unchanged. Otherwise the raw key is sent directly unless
   * EP_MCP_GATEWAY_AUTH_SCHEME is set to a valid token, in which case that
   * scheme prefix is prepended. The EP MCP gateway expects raw-token auth by
   * default (no "Bearer " prefix).
   *
   * @param apiKey - Raw or pre-prefixed gateway API key
   * @returns The full Authorization header value, or empty string for empty keys
   * @throws {Error} When the API key contains CR or LF characters (header injection risk)
   */
  private _buildAuthorizationHeader(apiKey: string): string {
    const trimmedKey = apiKey.trim();
    if (!trimmedKey) {
      return '';
    }
 
    // Reject CR/LF in the key to prevent HTTP header injection.
    if (/[\r\n]/.test(trimmedKey)) {
      throw new Error(
        'Invalid gateway API key: control characters (CR/LF) are not allowed in Authorization header values.'
      );
    }
 
    // RFC 7235 tchar token pattern for scheme validation.
    // This regex exclusively allows valid tchar characters, which by definition
    // excludes control characters — no separate control-char check is needed
    // for the scheme token itself.
    const tokenRegex = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
 
    // If the key already starts with a valid RFC 7235 scheme token followed
    // by whitespace, treat it as a fully formed Authorization value and pass
    // it through unchanged.
    const firstSpaceIndex = trimmedKey.indexOf(' ');
    if (firstSpaceIndex > 0) {
      const possibleScheme = trimmedKey.slice(0, firstSpaceIndex);
      Eif (tokenRegex.test(possibleScheme)) {
        return trimmedKey;
      }
    }
 
    const rawScheme =
      typeof process !== 'undefined' && process.env && process.env['EP_MCP_GATEWAY_AUTH_SCHEME'];
    const scheme = typeof rawScheme === 'string' ? rawScheme.trim() : '';
 
    if (scheme && tokenRegex.test(scheme)) {
      return `${scheme} ${trimmedKey}`;
    }
 
    return trimmedKey;
  }
 
  /**
   * Attempt a single connection via MCP Gateway (HTTP transport)
   */
  private async _attemptGatewayConnection(): Promise<void> {
    try {
      const headers: Record<string, string> = {
        'Content-Type': 'application/json',
        Accept: 'application/json, text/event-stream',
      };
      Iif (this.gatewayApiKey) {
        headers['Authorization'] = this._buildAuthorizationHeader(this.gatewayApiKey);
      }
 
      const initRequest: JSONRPCRequest = {
        jsonrpc: '2.0',
        id: ++this.requestId,
        method: 'initialize',
        params: {
          protocolVersion: '2024-11-05',
          capabilities: {},
          clientInfo: { name: 'ep-mcp-client', version: '1.0.0' },
        },
      };
 
      const response = await fetch(this.gatewayUrl!, {
        method: 'POST',
        headers,
        body: JSON.stringify(initRequest),
        signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
      });
 
      if (!response.ok) {
        this._throwGatewayResponseError(response);
      }
 
      const sessionId = response.headers.get('mcp-session-id');
      if (sessionId) {
        this.mcpSessionId = sessionId;
      }
 
      // Parse and validate the initialization response body
      const contentType = response.headers.get('content-type') ?? '';
      const body = await response.text();
      this._validateGatewayResponseBody(contentType, body);
 
      this.connected = true;
      console.log(`✅ Connected to ${this.serverLabel} via gateway`);
    } catch (error) {
      const message = error instanceof Error ? error.message : String(error);
      console.error('❌ Failed to connect to MCP gateway:', message);
      throw error;
    }
  }
 
  /**
   * Attempt a single connection via stdio (spawns server binary)
   */
  private async _attemptConnection(): Promise<void> {
    try {
      const isJavaScriptFile: boolean = this.serverPath.toLowerCase().endsWith('.js');
      const command: string = isJavaScriptFile ? process.execPath : this.serverPath;
      const args: string[] = isJavaScriptFile ? [this.serverPath] : [];
 
      this.process = spawn(command, args, {
        stdio: ['pipe', 'pipe', 'pipe'],
      });
 
      let buffer = '';
      let startupError: Error | null = null;
 
      this.process.stdout?.on('data', (data: Buffer) => {
        buffer += data.toString();
        const lines = buffer.split('\n');
        buffer = lines.pop() ?? '';
 
        for (const line of lines) {
          if (line.trim()) {
            this.handleMessage(line);
          }
        }
      });
 
      this.process.stderr?.on('data', (data: Buffer) => {
        const message = data.toString().trim();
        Eif (message) {
          console.error(`MCP Server: ${message}`);
        }
      });
 
      this.process.on('close', (code: number | null) => {
        console.log(`MCP Server exited with code ${code}`);
        this.connected = false;
 
        for (const [id, { reject }] of this.pendingRequests.entries()) {
          reject(new Error('MCP server connection closed'));
          this.pendingRequests.delete(id);
        }
      });
 
      this.process.on('error', (err: Error) => {
        startupError = err;
        this.connected = false;
      });
 
      await new Promise((resolve) => setTimeout(resolve, CONNECTION_STARTUP_DELAY_MS));
 
      Iif (startupError) {
        throw startupError;
      }
 
      this.connected = true;
      console.log(`✅ Connected to ${this.serverLabel}`);
    } catch (error) {
      const message = error instanceof Error ? error.message : String(error);
      console.error('❌ Failed to spawn MCP server:', message);
      throw error;
    }
  }
 
  /**
   * Disconnect from the MCP server
   */
  disconnect(): void {
    if (this.process) {
      this.process.kill();
      this.process = null;
    }
    this.connected = false;
    this.mcpSessionId = null;
  }
 
  /**
   * Handle incoming messages from MCP server (stdio mode only)
   *
   * @param line - JSON message line from server
   */
  handleMessage(line: string): void {
    try {
      const message = JSON.parse(line) as JSONRPCResponse;
 
      if (message.id && this.pendingRequests.has(message.id)) {
        const pending = this.pendingRequests.get(message.id)!;
        this.pendingRequests.delete(message.id);
 
        if (message.error) {
          pending.reject(new Error(message.error.message ?? 'MCP server error'));
        } else {
          pending.resolve(message.result);
        }
      } else if (!message.id && message.method) {
        console.log(`MCP Notification: ${message.method}`);
      }
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : String(error);
      console.error('Error parsing MCP message:', errorMessage);
      console.error('Problematic line:', line);
    }
  }
 
  /**
   * Throw an appropriate error for a non-OK gateway response.
   * Extracted to keep `_sendGatewayRequest` within cognitive-complexity limits.
   *
   * @param response - The non-OK fetch Response
   */
  private _throwGatewayResponseError(response: Response): never {
    if (response.status === 401) {
      this.mcpSessionId = null;
      this.connected = false;
      throw new MCPSessionExpiredError(response.statusText);
    }
    if (response.status === 429) {
      const rawRetryAfter =
        response.headers.get(RETRY_AFTER_HEADER) ?? response.headers.get('Retry-After');
      const retryAfter = (rawRetryAfter ?? '').trim();
      if (retryAfter !== '') {
        const retryMessage = formatRetryAfter(retryAfter);
        const retryAfterMs = parseRetryAfterMs(retryAfter);
        console.warn(`⏳ ${RATE_LIMIT_MSG} ${retryMessage}`);
        throw new MCPRateLimitError(retryAfterMs, `${RATE_LIMIT_MSG} ${retryMessage}`);
      }
      const statusText = response.statusText || 'Too Many Requests';
      throw new MCPRateLimitError(
        0,
        `${RATE_LIMIT_MSG} (status ${response.status} ${statusText}; ${RETRY_AFTER_HEADER}/Retry-After header missing)`
      );
    }
    throw new Error(`Gateway error ${response.status}: ${response.statusText}`);
  }
 
  /**
   * Send a request via MCP Gateway (HTTP transport)
   *
   * @param method - RPC method name
   * @param params - Method parameters
   * @returns Server response
   */
  private async _sendGatewayRequest(
    method: string,
    params: Record<string, unknown> = {}
  ): Promise<unknown> {
    const id = ++this.requestId;
    const request: JSONRPCRequest = {
      jsonrpc: '2.0',
      id,
      method,
      params,
    };
 
    const headers: Record<string, string> = {
      'Content-Type': 'application/json',
      Accept: 'application/json, text/event-stream',
    };
    Iif (this.gatewayApiKey) {
      headers['Authorization'] = this._buildAuthorizationHeader(this.gatewayApiKey);
    }
    if (this.mcpSessionId) {
      headers['Mcp-Session-Id'] = this.mcpSessionId;
    }
 
    const response = await fetch(this.gatewayUrl!, {
      method: 'POST',
      headers,
      body: JSON.stringify(request),
      signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
    });
 
    Eif (!response.ok) {
      this._throwGatewayResponseError(response);
    }
 
    const sessionId = response.headers.get('mcp-session-id');
    if (sessionId) {
      this.mcpSessionId = sessionId;
    }
 
    const contentType = response.headers.get('content-type') ?? '';
    const body = await response.text();
 
    if (contentType.includes('text/event-stream')) {
      const parsed = parseSSEResponse(body);
      if (!parsed) {
        throw new Error('Failed to parse SSE response from gateway');
      }
      if (parsed.error) {
        throw new Error(parsed.error.message ?? 'MCP gateway error');
      }
      return parsed.result;
    }
 
    const jsonResponse = JSON.parse(body) as JSONRPCResponse;
    if (jsonResponse.error) {
      throw new Error(jsonResponse.error.message ?? 'MCP gateway error');
    }
    return jsonResponse.result;
  }
 
  /**
   * Send a request to the MCP server
   *
   * @param method - RPC method name
   * @param params - Method parameters
   * @returns Server response
   */
  async sendRequest(method: string, params: Record<string, unknown> = {}): Promise<unknown> {
    if (!this.connected) {
      throw new Error('Not connected to MCP server');
    }
 
    Iif (this.gatewayUrl) {
      return await this._sendGatewayRequest(method, params);
    }
 
    const id = ++this.requestId;
    const request: JSONRPCRequest = {
      jsonrpc: '2.0',
      id,
      method,
      params,
    };
 
    return await new Promise((resolve, reject) => {
      this.pendingRequests.set(id, { resolve, reject });
 
      const message = JSON.stringify(request) + '\n';
      this.process?.stdin?.write(message);
 
      setTimeout(() => {
        if (this.pendingRequests.has(id)) {
          this.pendingRequests.delete(id);
          reject(new Error('Request timeout'));
        }
      }, REQUEST_TIMEOUT_MS);
    });
  }
 
  /**
   * List available MCP tools
   *
   * @returns List of available tools
   */
  async listTools(): Promise<unknown> {
    return await this.sendRequest('tools/list');
  }
 
  /**
   * Call an MCP tool
   *
   * @param name - Tool name
   * @param args - Tool arguments (must be a plain object, non-null, not an array)
   * @returns Tool execution result
   */
  async callTool(name: string, args: object = {}): Promise<MCPToolResult> {
    if (args === null || Array.isArray(args) || typeof args !== 'object') {
      throw new TypeError(
        'MCP tool arguments must be a plain object (non-null object, not an array or function)'
      );
    }
    return (await this.sendRequest('tools/call', { name, arguments: args })) as MCPToolResult;
  }
 
  /**
   * Attempt to reconnect to the MCP server with exponential back-off.
   * Concurrent callers await the same in-flight reconnect instead of no-oping,
   * ensuring the connection is re-established before all waiting callers continue.
   *
   * @returns Promise that resolves when reconnection succeeds or all attempts are exhausted
   */
  private async reconnect(): Promise<void> {
    if (this.reconnectingPromise !== null) {
      return this.reconnectingPromise;
    }
    this.reconnectCount++;
    console.log(`🔄 Reconnecting to ${this.serverLabel} (attempt ${this.reconnectCount})...`);
    this.reconnectingPromise = this._doReconnect();
    try {
      await this.reconnectingPromise;
    } finally {
      this.reconnectingPromise = null;
    }
  }
 
  /**
   * Internal reconnect helper.
   *
   * Waits for an exponential back-off delay derived from the current
   * `reconnectCount`, then delegates to `connect()` which handles its own
   * retry loop. This avoids composing N×N attempts.
   *
   * @returns Promise that resolves when reconnection succeeds or logs on failure
   */
  private async _doReconnect(): Promise<void> {
    // Derive a single outer back-off delay from reconnectCount so successive
    // reconnect bursts are spaced further apart, capped at RECONNECT_MAX_DELAY_MS.
    // Normalize maxConnectionAttempts to ≥1 to avoid a negative upper bound when
    // the user configures 0 attempts (which would give 2^-1 = 0.5 s backoff).
    const normalizedMaxAttempts = Math.max(1, this.maxConnectionAttempts);
    // Clamp to [0, normalizedMaxAttempts - 1]: first floor to ≥0, then ceil to ≤max.
    const attemptIndex = Math.min(Math.max(0, this.reconnectCount - 1), normalizedMaxAttempts - 1);
    const delay = Math.min(
      this.connectionRetryDelay * Math.pow(2, attemptIndex),
      RECONNECT_MAX_DELAY_MS
    );
    await new Promise((r) => setTimeout(r, delay));
    try {
      this.connected = false;
      await this.connect();
    } catch (error) {
      console.error(
        `❌ Reconnection to ${this.serverLabel} failed: ${
          error instanceof Error ? error.message : String(error)
        }`
      );
    }
  }
 
  /**
   * Log a retry warning and, if disconnected, attempt to reconnect before waiting.
   *
   * @param lastError - The error from the failed attempt
   * @param attempt - Zero-based current attempt index
   * @param retries - Total retry count
   * @returns Promise that resolves after logging, optional reconnect, and inter-retry delay
   */
  private async _handleRetryAttempt(
    lastError: Error,
    attempt: number,
    retries: number
  ): Promise<void> {
    if (lastError.message.toLowerCase().includes('timeout')) {
      this.timeoutCount++;
      console.warn(
        `⏱️ Request timeout (total: ${this.timeoutCount}), retrying ${attempt + 1}/${retries}...`
      );
    } else {
      console.warn(`⚠️ Request failed, retrying ${attempt + 1}/${retries}: ${lastError.message}`);
    }
    if (!this.connected) {
      await this.reconnect();
    }
    await new Promise((r) => setTimeout(r, this.connectionRetryDelay * (attempt + 1)));
  }
 
  /**
   * 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.
   *
   * @param name - Tool name
   * @param args - Tool arguments (plain object, non-null, not an array)
   * @param maxRetries - Override the default retry count from options
   * @returns Tool execution result
   */
  async callToolWithRetry(
    name: string,
    args: object = {},
    maxRetries?: number
  ): Promise<MCPToolResult> {
    const retries = maxRetries ?? this.maxRetries;
    if (retries < 0) {
      throw new RangeError(`maxRetries must be >= 0, received ${retries}`);
    }
    let lastError: Error = new Error(`Failed to call tool '${name}' after ${retries} retries`);
    for (let attempt = 0; attempt <= retries; attempt++) {
      try {
        return await this.callTool(name, args);
      } catch (error) {
        lastError = error instanceof Error ? error : new Error(String(error));
        if (!isRetriableError(lastError)) throw lastError;
        if (attempt === retries) break;
        await this._handleRetryAttempt(lastError, attempt, retries);
      }
    }
    throw lastError;
  }
}