All files / mcp mcp-connection.ts

68.47% Statements 126/184
53.22% Branches 66/124
80% Functions 20/25
68.68% Lines 125/182

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                                                    11x     11x     11x           11x     11x                           10x 10x 21x 21x 12x 12x 10x 10x             3x                                                           177x   177x 177x 177x 177x 177x 177x 177x 177x   177x 177x 177x 177x                 10x                 4x                 1x                 2x                 2x             5x 1x     4x 2x 2x   2x     4x 4x 4x 4x 2x   2x   3x 3x   1x 1x             1x         1x                         1x               1x       1x 1x 1x                             2x 2x       2x       2x                     2x             1x       1x 1x 1x       1x 2x 1x   1x 1x   1x 1x 1x               1x 1x 1x 1x   1x       1x 1x   1x                       1x 1x 1x 1x       1x 1x 1x   1x           1x         1x   1x       1x 1x                       138x 4x 4x   138x 138x                 5x 5x   5x 2x 2x   2x 1x   1x   2x 1x     1x 1x 1x                                                                                                                                                             4x 2x     2x       2x 2x             2x 2x   2x 2x   2x                             1x                     4x 1x       3x      
// 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;
 
/**
 * 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;
 
  /** 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 = options.maxConnectionAttempts ?? 3;
    this.connectionRetryDelay = options.connectionRetryDelay ?? 1000;
    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;
  }
 
  /**
   * 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) {
        this.connectionAttempts++;
        Iif (this.connectionAttempts < this.maxConnectionAttempts) {
          const delay = this.connectionRetryDelay * Math.pow(2, this.connectionAttempts - 1);
          console.warn(
            `⚠️ Connection attempt ${this.connectionAttempts} failed. Retrying in ${delay}ms...`
          );
          await new Promise((resolve) => setTimeout(resolve, delay));
        } else {
          console.error(
            '❌ Failed to connect to MCP server after',
            this.maxConnectionAttempts,
            'attempts'
          );
          throw error;
        }
      }
    }
  }
 
  /**
   * 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;
      }
    }
  }
 
  /**
   * 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'] = `Bearer ${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),
      });
 
      Iif (!response.ok) {
        throw new Error(`Gateway returned ${response.status}: ${response.statusText}`);
      }
 
      const sessionId = response.headers.get('mcp-session-id');
      Eif (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);
    }
  }
 
  /**
   * 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',
    };
    if (this.gatewayApiKey) {
      headers['Authorization'] = `Bearer ${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),
    });
 
    if (!response.ok) {
      throw new Error(`Gateway error ${response.status}: ${response.statusText}`);
    }
 
    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;
  }
}