All files / scripts/mcp-client/transport jsonrpc.ts

87.3% Statements 55/63
95.12% Branches 39/41
80% Functions 8/10
88.33% Lines 53/60

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                                                                                                              130x 2x 2x 2x 2x 2x   128x 128x 128x 128x 128x     130x 130x 130x         1x                         130x   130x 112x     122x 122x   122x 122x   122x 1x 1x           122x   122x             108x 4x 4x 4x         104x 104x   104x               104x 3x     101x 130x   21x   21x 10x 10x     10x 10x 10x     11x 11x   122x                 1x               1x               15x                     3x 3x      
/**
 * @module mcp-client/transport/jsonrpc
 * @description JSON-RPC 2.0 transport base class for the MCP client stack.
 *
 * `MCPTransportClient` owns the wire-level orchestration:
 *   - HTTP POST via `performPost` (fetch + Node.js fallback)
 *   - JSON-RPC 2.0 `tools/call` envelope (built in `./request-builder.ts`)
 *   - Response parsing + gateway payload dereferencing (`./response-parser.ts`)
 *   - JSON-RPC error envelope classification (`./error-envelope.ts`)
 *   - Exponential-backoff retry on transient transport errors (`./retry.ts`)
 *   - Lazy session re-init on session-init / rate-limit errors (`./session.ts`)
 *   - Statistics tracking (`requests`, `errors`, `successRate`)
 *
 * The orchestrating `MCPClient` in `../client.ts` extends this base and wires
 * per-domain method wrappers on top.
 *
 * @author Hack23 AB
 * @license Apache-2.0
 */
 
import type {
  MCPClientConfig,
  MCPStats,
  JsonRpcResponse,
} from '../../types/mcp.js';
import { performPost } from '../transport.js';
import { DEFAULT_MAX_RETRIES, DEFAULT_MCP_SERVER_URL, getDefaultTimeout } from '../config/defaults.js';
import { DEFAULT_MCP_AUTH_TOKEN } from '../config/auth.js';
import { calculateRetryDelay, isRetryableNetworkError } from './retry.js';
import { initializeSession, parseSSEResponse, type SessionInitContext } from './session.js';
import {
  assertValidToolName,
  buildJsonRpcRequest,
  buildRequestHeaders,
  nextJsonRpcId,
} from './request-builder.js';
import { parseJsonRpcEnvelope, resolveResultContent } from './response-parser.js';
import { classifyJsonRpcError, formatRequestFailure } from './error-envelope.js';
 
/**
 * Wire-level MCP transport. Domain-agnostic JSON-RPC 2.0 client with
 * retry, SSE parsing, and lazy session bootstrap.
 */
export class MCPTransportClient implements SessionInitContext {
  readonly baseURL: string;
  readonly timeout: number;
  readonly maxRetries: number;
  readonly customHeaders: Readonly<Record<string, string>>;
  readonly authToken: string;
 
  requestCount: number;
  errorCount: number;
  sessionId: string | null;
 
  constructor(config: MCPClientConfig | string = {}) {
    if (typeof config === 'string') {
      this.baseURL = config;
      this.timeout = getDefaultTimeout();
      this.maxRetries = DEFAULT_MAX_RETRIES;
      this.customHeaders = {};
      this.authToken = DEFAULT_MCP_AUTH_TOKEN;
    } else {
      this.baseURL = config.baseURL ?? config.serverUrl ?? DEFAULT_MCP_SERVER_URL;
      this.timeout = config.timeout ?? getDefaultTimeout();
      this.maxRetries = config.maxRetries ?? DEFAULT_MAX_RETRIES;
      this.customHeaders = config.headers ?? {};
      this.authToken = config.authToken ?? DEFAULT_MCP_AUTH_TOKEN;
    }
 
    this.requestCount = 0;
    this.errorCount = 0;
    this.sessionId = null;
  }
 
  /** SessionInitContext glue — returns the next monotonic JSON-RPC id. */
  nextJsonRpcId(): number {
    return nextJsonRpcId();
  }
 
  // -----------------------------------------------------------------------
  // Core request
  // -----------------------------------------------------------------------
 
  async request(
    tool: string,
    params: Record<string, unknown> = {},
    retryCount = 0,
    _skipPrefix = false,
  ): Promise<Record<string, unknown>> {
    assertValidToolName(tool);
 
    if (retryCount === 0) {
      this.requestCount++;
    }
 
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), this.timeout);
 
    try {
      const jsonRpcRequest = buildJsonRpcRequest(tool, params);
 
      if (this.authToken && !this.sessionId) {
        try {
          await this.initializeSession();
        } catch {
          // Session init is optional
        }
      }
 
      const headers = buildRequestHeaders(this.customHeaders, this.authToken, this.sessionId);
 
      const response = await performPost(
        this.baseURL,
        headers,
        JSON.stringify(jsonRpcRequest),
        controller.signal,
      );
 
      if (!response.ok) {
        let errorBody = '';
        try { errorBody = await response.text(); } catch { /* ignore */ }
        throw new Error(
          `MCP server error: ${response.status} ${response.statusText}${errorBody ? ' - ' + errorBody : ''}`,
        );
      }
 
      const jsonRpcResponse: JsonRpcResponse = await parseJsonRpcEnvelope(response);
      const errorOutcome = classifyJsonRpcError(jsonRpcResponse);
 
      Iif (errorOutcome.kind === 'session_init' && retryCount < 2) {
        this.sessionId = null;
        const delay = (retryCount + 1) * 2000;
        console.warn(`⚠️ Session error, re-initializing after ${delay}ms...`);
        await this.sleep(delay);
        await this.initializeSession();
        return this.request(tool, params, retryCount + 1);
      }
      if (errorOutcome.kind !== 'none') {
        throw new Error(errorOutcome.message);
      }
 
      const result = (jsonRpcResponse.result ?? {}) as Record<string, unknown>;
      return resolveResultContent(result);
    } catch (error: unknown) {
      const err = error as Error;
 
      if (retryCount < this.maxRetries - 1 && isRetryableNetworkError(err)) {
        const delay = calculateRetryDelay(retryCount);
        console.warn(
          `⚠️ Request failed (${err.message.substring(0, 60)}), retrying after ${delay}ms (${retryCount + 1}/${this.maxRetries - 1})...`,
        );
        this.sessionId = null;
        await this.sleep(delay);
        return this.request(tool, params, retryCount + 1);
      }
 
      this.errorCount++;
      throw new Error(formatRequestFailure(err, this.baseURL), { cause: error });
    } finally {
      clearTimeout(timeoutId);
    }
  }
 
  // -----------------------------------------------------------------------
  // Session / utility delegators
  // -----------------------------------------------------------------------
 
  async sleep(ms: number): Promise<void> {
    return new Promise((resolve) => setTimeout(resolve, ms));
  }
 
  parseSSEResponse(text: string): JsonRpcResponse {
    return parseSSEResponse(text);
  }
 
  async initializeSession(): Promise<void> {
    return initializeSession(this);
  }
 
  // -----------------------------------------------------------------------
  // Statistics
  // -----------------------------------------------------------------------
 
  getStats(): MCPStats {
    return {
      requests: this.requestCount,
      errors: this.errorCount,
      successRate:
        this.requestCount > 0
          ? Math.round(((this.requestCount - this.errorCount) / this.requestCount) * 100) + '%'
          : '0%',
    };
  }
 
  resetStats(): void {
    this.requestCount = 0;
    this.errorCount = 0;
  }
}