All files / mcp mcp-retry.ts

100% Statements 49/49
100% Branches 26/26
100% Functions 8/8
100% Lines 45/45

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                                                                        41x 41x 41x 41x         41x 41x                       91x 29x 27x 11x 11x     16x       13x 11x 11x         86x 86x 86x                   66x 66x   1x 1x 1x 1x   65x 65x 25x 25x 25x                       37x                 7x                                       10x 10x 10x                           6x 6x 6x   6x 18x 18x   16x 16x 12x 12x       16x    
// SPDX-FileCopyrightText: 2024-2026 Hack23 AB
// SPDX-License-Identifier: Apache-2.0
 
/**
 * @module MCP/MCPRetry
 * @description Circuit breaker and retry logic for MCP operations.
 *
 * Provides the {@link CircuitBreaker} class for preventing cascading MCP
 * failures, the {@link MCPRetryPolicy} interface for configurable retry
 * strategies, and the {@link withRetry} wrapper for automatic retries
 * with exponential backoff.
 *
 * @see {@link https://github.com/Hack23/ISMS-PUBLIC/blob/main/Secure_Development_Policy.md | Secure Development Policy}
 */
 
// ─── Circuit Breaker ─────────────────────────────────────────────────────────
 
/** Possible circuit breaker states */
export type CircuitState = 'CLOSED' | 'OPEN' | 'HALF_OPEN';
 
/** Constructor options for {@link CircuitBreaker} */
export interface CircuitBreakerOptions {
  /** Consecutive failures before opening the circuit (default: 3) */
  failureThreshold?: number | undefined;
  /** Milliseconds to wait before probing recovery (default: 60 000) */
  resetTimeoutMs?: number | undefined;
}
 
/**
 * Circuit breaker preventing cascading MCP failures.
 *
 * - **CLOSED** — normal operation; all requests pass through.
 * - **OPEN** — fast-fail; requests are rejected for `resetTimeoutMs` ms.
 * - **HALF_OPEN** — probe state; one request is allowed to test recovery.
 */
export class CircuitBreaker {
  private state: CircuitState = 'CLOSED';
  private consecutiveFailures = 0;
  private nextAttemptAt = 0;
  private halfOpenProbeInFlight = false;
  private readonly failureThreshold: number;
  private readonly resetTimeoutMs: number;
 
  constructor(options: CircuitBreakerOptions = {}) {
    this.failureThreshold = options.failureThreshold ?? 3;
    this.resetTimeoutMs = options.resetTimeoutMs ?? 60_000;
  }
 
  /**
   * Whether a request may proceed given the current circuit state.
   *
   * In HALF_OPEN state only a single probe is allowed at a time; subsequent
   * calls return `false` until the in-flight probe records success or failure.
   *
   * @returns `true` when the circuit is CLOSED, or HALF_OPEN with no probe in flight
   */
  canRequest(): boolean {
    if (this.state === 'CLOSED') return true;
    if (this.state === 'OPEN') {
      if (Date.now() >= this.nextAttemptAt) {
        this.state = 'HALF_OPEN';
        this.halfOpenProbeInFlight = false;
        // Fall through to HALF_OPEN probe logic below
      } else {
        return false;
      }
    }
    // HALF_OPEN: allow exactly one probe in flight at a time
    if (this.halfOpenProbeInFlight) return false;
    this.halfOpenProbeInFlight = true;
    return true;
  }
 
  /** Record a successful request and close the circuit */
  recordSuccess(): void {
    this.consecutiveFailures = 0;
    this.halfOpenProbeInFlight = false;
    this.state = 'CLOSED';
  }
 
  /**
   * Record a failed request.
   *
   * - When in **HALF_OPEN** the circuit re-opens immediately (the probe failed).
   * - When in **CLOSED** the circuit opens only once the failure threshold is reached.
   */
  recordFailure(): void {
    this.halfOpenProbeInFlight = false;
    if (this.state === 'HALF_OPEN') {
      // Probe failed — immediately re-open and back off again
      this.state = 'OPEN';
      this.nextAttemptAt = Date.now() + this.resetTimeoutMs;
      console.warn('⚡ Circuit breaker re-OPEN after HALF_OPEN probe failure');
      return;
    }
    this.consecutiveFailures++;
    if (this.consecutiveFailures >= this.failureThreshold) {
      this.state = 'OPEN';
      this.nextAttemptAt = Date.now() + this.resetTimeoutMs;
      console.warn(
        `⚡ Circuit breaker OPEN after ${this.consecutiveFailures} consecutive failures`
      );
    }
  }
 
  /**
   * Return the current circuit state.
   *
   * @returns Current circuit state
   */
  getState(): CircuitState {
    return this.state;
  }
 
  /**
   * Return current statistics for observability.
   *
   * @returns Snapshot of state and consecutive failure count
   */
  getStats(): Readonly<{ state: CircuitState; consecutiveFailures: number }> {
    return { state: this.state, consecutiveFailures: this.consecutiveFailures };
  }
}
 
// ─── Retry Policy ────────────────────────────────────────────────────────────
 
/**
 * Configuration for {@link withRetry} controlling how failed async operations
 * are retried with exponential backoff.
 */
export interface MCPRetryPolicy {
  /** Maximum number of retry attempts (default: 3) */
  maxRetries?: number | undefined;
  /** Base delay in milliseconds before the first retry (default: 1000) */
  baseDelayMs?: number | undefined;
  /** Maximum delay cap in milliseconds (default: 30 000) */
  maxDelayMs?: number | undefined;
}
 
/** Default retry policy values */
const DEFAULT_MAX_RETRIES = 3;
const DEFAULT_BASE_DELAY_MS = 1_000;
const DEFAULT_MAX_DELAY_MS = 30_000;
 
/**
 * Execute an async function with retry and exponential backoff.
 *
 * Retries up to `policy.maxRetries` times with capped exponential delay:
 * `min(baseDelayMs * 2^attempt, maxDelayMs)`.
 *
 * @param fn - Async factory that performs the operation
 * @param policy - Retry configuration (merged with defaults)
 * @returns Result of `fn` on first success
 * @throws The last error when all retries are exhausted
 */
export async function withRetry<T>(fn: () => Promise<T>, policy: MCPRetryPolicy = {}): Promise<T> {
  const maxRetries = policy.maxRetries ?? DEFAULT_MAX_RETRIES;
  const baseDelayMs = policy.baseDelayMs ?? DEFAULT_BASE_DELAY_MS;
  const maxDelayMs = policy.maxDelayMs ?? DEFAULT_MAX_DELAY_MS;
  let lastError: unknown;
  for (let attempt = 0; attempt <= maxRetries; attempt++) {
    try {
      return await fn();
    } catch (error) {
      lastError = error;
      if (attempt < maxRetries) {
        const delay = Math.min(baseDelayMs * Math.pow(2, attempt), maxDelayMs);
        await new Promise((resolve) => setTimeout(resolve, delay));
      }
    }
  }
  throw lastError;
}