@gohcltech/bitbucket-mcp
Version:
Bitbucket integration for Claude via Model Context Protocol
269 lines • 10.5 kB
TypeScript
/**
* @fileoverview Centralized error handling system for the Bitbucket MCP Server.
*
* This module provides comprehensive error handling capabilities including:
* - Automatic retry logic with exponential backoff
* - API error classification and transformation
* - Validation error handling with detailed feedback
* - Rate limiting error management
* - MCP-compatible error response formatting
*
* The error handler centralizes all error management to ensure consistent
* behavior across the entire application and provides robust resilience
* for network and API operations.
*/
import { ValidationError } from './types.js';
/**
* Configuration interface for retry behavior.
*
* Controls how operations are retried when encountering retryable errors,
* including timing, backoff strategy, and which error types should trigger retries.
*/
export interface RetryConfig {
/** Maximum number of retry attempts before giving up */
maxRetries: number;
/** Initial delay in milliseconds before first retry */
baseDelay: number;
/** Maximum delay in milliseconds to prevent excessive wait times */
maxDelay: number;
/** Exponential backoff multiplier for calculating delays */
backoffFactor: number;
/** List of error codes/types that should trigger retries */
retryableErrors: string[];
}
/**
* Context information for retry operations.
*
* Tracks the current state of a retry sequence for logging and decision making.
*/
export interface RetryContext {
/** Current attempt number (starting from 1) */
attempt: number;
/** The most recent error that triggered the retry */
lastError: Error;
/** Total time elapsed since the first attempt */
totalDuration: number;
}
/**
* Centralized error handling class with retry logic and error classification.
*
* This class provides comprehensive error handling capabilities for the Bitbucket MCP server:
* - Automatic retry logic with exponential backoff for transient failures
* - API error classification and transformation into appropriate error types
* - Validation error handling with detailed feedback
* - Rate limiting awareness and management
* - MCP-compatible error response formatting
*
* The error handler integrates with the logging system to provide detailed
* error tracking and debugging information while maintaining security by
* sanitizing sensitive data in error messages.
*
* @example
* ```typescript
* const errorHandler = new ErrorHandler({
* maxRetries: 5,
* baseDelay: 2000
* });
*
* // Retry an operation with automatic error handling
* const result = await errorHandler.withRetry(
* () => apiCall(),
* { operationName: 'fetch_repositories', toolName: 'list_repositories' }
* );
* ```
*/
export declare class ErrorHandler {
/** Logger instance for error tracking and debugging */
private logger;
/** Retry configuration with defaults and custom overrides */
private retryConfig;
/**
* Creates a new ErrorHandler instance.
*
* @param retryConfig - Optional partial configuration to override defaults
*/
constructor(retryConfig?: Partial<RetryConfig>);
/**
* Execute a function with retry logic and exponential backoff.
*
* Automatically retries failed operations using exponential backoff strategy.
* Only retries operations that fail with retryable errors (network issues,
* rate limits, server errors). Non-retryable errors (authentication,
* validation) are thrown immediately.
*
* @param operation - Async function to execute with retry logic
* @param context - Context information for logging and error messages
* @param context.operationName - Human-readable name of the operation
* @param context.toolName - Optional tool name for categorized logging
* @param customRetryConfig - Optional configuration overrides for this operation
* @returns Promise that resolves to the operation result
* @throws {Error} The final error if all retry attempts are exhausted
*
* @example
* ```typescript
* const result = await errorHandler.withRetry(
* () => fetch('/api/repos'),
* { operationName: 'fetch_repositories', toolName: 'list_repositories' },
* { maxRetries: 5, baseDelay: 2000 }
* );
* ```
*/
withRetry<T>(operation: () => Promise<T>, context: {
operationName: string;
toolName?: string;
}, customRetryConfig?: Partial<RetryConfig>): Promise<T>;
/**
* Handle and classify errors from API responses.
*
* Transforms raw API errors into appropriate typed errors based on HTTP status codes
* and error content. This method ensures consistent error handling across all API
* operations and provides meaningful error messages to users.
*
* @param error - Raw error from HTTP client (axios, fetch, etc.)
* @param context - Context information about the failed request
* @param context.method - HTTP method that failed
* @param context.url - URL that was requested
* @param context.toolName - Optional tool name for error categorization
* @throws {AuthenticationError} For 401/403 status codes
* @throws {RateLimitError} For 429 status codes with retry information
* @throws {BitbucketApiError} For other HTTP errors with status codes
* @throws {Error} For network errors without status codes
*
* @example
* ```typescript
* try {
* await apiCall();
* } catch (error) {
* errorHandler.handleApiError(error, {
* method: 'GET',
* url: '/repositories',
* toolName: 'list_repositories'
* });
* }
* ```
*/
handleApiError(error: any, context: {
method: string;
url: string;
toolName?: string;
}): never;
/**
* Handle validation errors with detailed feedback.
*
* Processes validation errors to provide detailed feedback about what
* went wrong and how to fix it. Integrates with the logging system
* to track validation issues for debugging.
*
* @param error - The validation error to handle
* @param toolName - Name of the tool where validation failed
* @throws {ValidationError} Always throws a ValidationError with enhanced context
*/
handleValidationError(error: ValidationError, toolName: string): never;
/**
* Create error response for MCP tools.
*
* Formats errors into the standard MCP response format expected by Claude.
* Ensures consistent error presentation and includes appropriate context
* while maintaining security by not exposing sensitive information.
*
* @param error - The error to format
* @param toolName - Name of the tool that encountered the error
* @returns MCP-compatible error response object
*/
createErrorResponse(error: Error, toolName: string): {
isError: true;
content: [{
type: 'text';
text: string;
}];
};
/**
* Normalizes various error types into standard Error objects.
*
* Handles different error formats that might be thrown by various libraries
* and APIs, ensuring consistent error handling throughout the application.
*
* @private
* @param error - Error of any type to normalize
* @returns Normalized Error object
*/
private normalizeError;
/**
* Determines if an error should trigger a retry attempt.
*
* Evaluates errors against retry criteria to decide whether the operation
* should be retried. Authentication and validation errors are never retried,
* while network errors and server errors are typically retryable.
*
* @private
* @param error - Error to evaluate for retry eligibility
* @param config - Retry configuration with retryable error patterns
* @returns True if the error should trigger a retry attempt
*/
private isRetryableError;
/**
* Calculates the delay before the next retry attempt using exponential backoff.
*
* Implements exponential backoff with a maximum delay cap to prevent
* excessive wait times while providing increasing delays for subsequent retries.
*
* @private
* @param attempt - Current attempt number (0-based)
* @param config - Retry configuration with delay parameters
* @returns Delay in milliseconds before the next retry
*/
private calculateDelay;
/**
* Creates a promise that resolves after the specified delay.
*
* @private
* @param ms - Delay in milliseconds
* @returns Promise that resolves after the delay
*/
private sleep;
/**
* Extracts retry-after information from HTTP response headers.
*
* Parses rate limit headers to determine when the next request can be made.
* Supports both standard 'Retry-After' and Bitbucket-specific headers.
*
* @private
* @param headers - HTTP response headers
* @returns Retry delay in milliseconds, or undefined if not specified
*/
private extractRetryAfter;
/**
* Formats error messages for consistent presentation to users.
*
* Creates user-friendly error messages based on error type while maintaining
* security by not exposing sensitive information. Provides context about
* the operation that failed and any relevant recovery information.
*
* @private
* @param error - Error to format
* @param toolName - Name of the tool where the error occurred
* @returns Formatted error message string
*/
private formatErrorMessage;
}
/**
* Creates and configures the global error handler instance.
*
* Initializes the singleton error handler with the provided configuration.
* This should be called once during application startup.
*
* @param config - Optional configuration overrides for retry behavior
* @returns The configured ErrorHandler instance
*/
export declare function createErrorHandler(config?: Partial<RetryConfig>): ErrorHandler;
/**
* Gets the global error handler instance.
*
* Returns the singleton error handler, creating a default instance if none
* has been explicitly created. For production use, prefer calling
* createErrorHandler() first to ensure proper configuration.
*
* @returns The global ErrorHandler instance
*/
export declare function getErrorHandler(): ErrorHandler;
//# sourceMappingURL=error-handler.d.ts.map