All files / src/tools/shared errorClassifier.ts

98.14% Statements 53/54
96.07% Branches 49/51
100% Functions 8/8
98.11% Lines 52/53

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                                                            75x             30x   45x                                                         57x 8x 8x                 49x 49x 15x       34x 9x       25x                 49x 49x   49x 49x 60x 60x 15x     45x 3x   42x 1x   41x   41x       30x               9x 1x   8x 1x   7x                 25x 1x   24x 1x   23x               15x 3x             12x 2x             10x 1x             9x 6x             3x 2x             1x 1x                                       6x                     6x                     8x                     8x    
/**
 * Error classification utilities for MCP tool error responses.
 *
 * Extracted from `errorHandler.ts` so that both `errorHandler.ts` and
 * `responseBuilder.ts` can import classification logic without creating
 * a circular dependency.
 *
 * ISMS Policy: SC-002 (Input Validation), AC-003 (Least Privilege)
 */
 
import { z } from 'zod';
import { ToolError } from './errors.js';
import type { ErrorCode, ErrorCategory } from './errors.js';
 
/**
 * Structured error classification result for MCP responses.
 */
export interface ErrorClassification {
  errorCode: ErrorCode;
  errorCategory: ErrorCategory;
  httpStatus?: number;
  retryable: boolean;
}
 
/**
 * Extract an HTTP status code from an error via duck typing.
 * Works with both `APIError` (from `clients/ep/baseClient`) and any error
 * carrying a numeric `statusCode` property (avoids circular imports).
 */
export function extractHttpStatus(error: unknown): number | undefined {
  if (
    error !== null &&
    error !== undefined &&
    typeof error === 'object' &&
    'statusCode' in error &&
    typeof (error as { statusCode?: unknown }).statusCode === 'number'
  ) {
    return (error as { statusCode: number }).statusCode;
  }
  return undefined;
}
 
/**
 * Classify an error into a structured error code, category, and retryability.
 *
 * Priority:
 * 1. If the error is a `ToolError` with explicit `errorCode` already set, use it.
 *    Retryability is derived from the error code's standard meaning (via
 *    {@link retryableForCode}) rather than `ToolError.isRetryable`, ensuring
 *    consistency even when callers set `errorCode` without a matching
 *    `isRetryable`. **Note:** `ToolError.isRetryable` is ignored when
 *    `errorCode` is present.
 * 2. Inspect the error and its cause chain for HTTP status codes (for example
 *    from `APIError`) and classify from the resolved status.
 * 3. If the error is a `ToolError` without an explicit `errorCode`, apply
 *    heuristic classification, including operation-based mappings
 *    (`validateInput` → `INVALID_PARAMS`) and message-based timeout detection.
 * 4. If the error is a `ZodError` (validation failure), classify as
 *    `INVALID_PARAMS` / `CLIENT_ERROR`.
 * 5. If the error is a plain `Error`, apply message-based timeout detection
 *    (`timed out` → `UPSTREAM_TIMEOUT`).
 * 6. Default to `INTERNAL_ERROR`.
 *
 * @param error - The caught error value
 * @returns Structured classification with code, category, httpStatus, and retryable flag
 */
export function classifyError(error: unknown): ErrorClassification {
  // 1. ToolError with explicit classification
  if (error instanceof ToolError && error.errorCode !== undefined) {
    const code = error.errorCode;
    return {
      errorCode: code,
      errorCategory: error.errorCategory ?? categoryForCode(code),
      ...(error.httpStatus !== undefined ? { httpStatus: error.httpStatus } : {}),
      retryable: retryableForCode(code),
    };
  }
 
  // 2. Extract HTTP status from error or its cause chain
  const httpStatus = resolveHttpStatus(error);
  if (httpStatus !== undefined) {
    return classifyHttpStatus(httpStatus);
  }
 
  // 3. ToolError operation-based and message-based heuristics
  if (error instanceof ToolError) {
    return classifyToolErrorHeuristic(error);
  }
 
  // 4–6. Plain Error heuristics (ZodError, timeout, default)
  return classifyPlainErrorHeuristic(error);
}
 
/**
 * Resolve HTTP status by walking the error's cause chain (duck-typed).
 * Stops after 10 levels or on a cycle to prevent infinite loops.
 * @internal
 */
function resolveHttpStatus(error: unknown): number | undefined {
  const maxDepth = 10;
  const visited = new Set<object>();
 
  let current: unknown = error;
  for (let depth = 0; depth < maxDepth && current != null; depth += 1) {
    const status = extractHttpStatus(current);
    if (status !== undefined) {
      return status;
    }
 
    if (typeof current !== 'object') {
      return undefined;
    }
    if (visited.has(current)) {
      return undefined;
    }
    visited.add(current);
 
    current =
      current instanceof Error ? current.cause : undefined;
  }
 
  return undefined;
}
 
/**
 * Classify a ToolError using operation name and message heuristics.
 * @internal
 */
function classifyToolErrorHeuristic(error: ToolError): ErrorClassification {
  if (error.operation === 'validateInput') {
    return { errorCode: 'INVALID_PARAMS', errorCategory: 'CLIENT_ERROR', retryable: false };
  }
  if (error.message.includes('timed out')) {
    return { errorCode: 'UPSTREAM_TIMEOUT', errorCategory: 'TIMEOUT', retryable: true };
  }
  return { errorCode: 'INTERNAL_ERROR', errorCategory: 'INTERNAL', retryable: error.isRetryable };
}
 
/**
 * Classify a plain Error (non-ToolError) using name and message heuristics.
 * Detects ZodError (validation) and timeout patterns before falling back to INTERNAL_ERROR.
 * @internal
 */
function classifyPlainErrorHeuristic(error: unknown): ErrorClassification {
  if (error instanceof z.ZodError) {
    return { errorCode: 'INVALID_PARAMS', errorCategory: 'CLIENT_ERROR', retryable: false };
  }
  if (error instanceof Error && error.message.includes('timed out')) {
    return { errorCode: 'UPSTREAM_TIMEOUT', errorCategory: 'TIMEOUT', retryable: true };
  }
  return { errorCode: 'INTERNAL_ERROR', errorCategory: 'INTERNAL', retryable: false };
}
 
/**
 * Map an HTTP status code to a structured error classification.
 * @internal
 */
function classifyHttpStatus(status: number): ErrorClassification {
  if (status === 404) {
    return {
      errorCode: 'UPSTREAM_404',
      errorCategory: 'DATA_UNAVAILABLE',
      httpStatus: status,
      retryable: false,
    };
  }
  if (status === 429) {
    return {
      errorCode: 'RATE_LIMITED',
      errorCategory: 'RATE_LIMIT',
      httpStatus: status,
      retryable: true,
    };
  }
  if (status === 408) {
    return {
      errorCode: 'UPSTREAM_TIMEOUT',
      errorCategory: 'TIMEOUT',
      httpStatus: status,
      retryable: true,
    };
  }
  if (status === 503) {
    return {
      errorCode: 'UPSTREAM_503',
      errorCategory: 'SERVER_ERROR',
      httpStatus: status,
      retryable: true,
    };
  }
  if (status >= 500) {
    return {
      errorCode: 'UPSTREAM_500',
      errorCategory: 'SERVER_ERROR',
      httpStatus: status,
      retryable: true,
    };
  }
  Eif (status >= 400) {
    return {
      errorCode: 'INVALID_PARAMS',
      errorCategory: 'CLIENT_ERROR',
      httpStatus: status,
      retryable: false,
    };
  }
  return {
    errorCode: 'INTERNAL_ERROR',
    errorCategory: 'INTERNAL',
    httpStatus: status,
    retryable: false,
  };
}
 
/**
 * Derive default category from error code.
 * @internal
 */
function categoryForCode(code: ErrorCode): ErrorCategory {
  const map: Record<ErrorCode, ErrorCategory> = {
    UPSTREAM_404: 'DATA_UNAVAILABLE',
    UPSTREAM_500: 'SERVER_ERROR',
    UPSTREAM_503: 'SERVER_ERROR',
    UPSTREAM_TIMEOUT: 'TIMEOUT',
    RATE_LIMITED: 'RATE_LIMIT',
    INVALID_PARAMS: 'CLIENT_ERROR',
    FEED_FALLBACK: 'DATA_QUALITY',
    UNKNOWN_TOOL: 'CLIENT_ERROR',
    INTERNAL_ERROR: 'INTERNAL',
  };
  return map[code];
}
 
/**
 * Derive standard retryability from an error code.
 *
 * Ensures callers who set `errorCode` on a `ToolError` get consistent
 * retryable metadata without needing to also set `isRetryable`.
 * @internal
 */
function retryableForCode(code: ErrorCode): boolean {
  const map: Record<ErrorCode, boolean> = {
    UPSTREAM_404: false,
    UPSTREAM_500: true,
    UPSTREAM_503: true,
    UPSTREAM_TIMEOUT: true,
    RATE_LIMITED: true,
    INVALID_PARAMS: false,
    FEED_FALLBACK: false,
    UNKNOWN_TOOL: false,
    INTERNAL_ERROR: false,
  };
  return map[code];
}