/**
* Centralized error handling system
*/
import { MCPError, ErrorCode } from '../types/core.js';
export class MCPException extends Error {
public readonly code: ErrorCode;
public readonly details?: any;
constructor(code: ErrorCode, message: string, details?: any) {
super(message);
this.name = 'MCPException';
this.code = code;
this.details = details;
}
toMCPError(): MCPError {
return {
code: this.code,
message: this.message,
details: this.details
};
}
}
export function createError(code: ErrorCode, message: string, details?: any): MCPError {
return {
code,
message,
details
};
}
export function wrapError(error: any, code: ErrorCode = 'UPSTREAM_ERROR'): MCPError {
if (error instanceof MCPException) {
return error.toMCPError();
}
if (error instanceof Error) {
return createError(code, error.message, {
stack: error.stack,
name: error.name
});
}
return createError(code, String(error));
}
export class ConfigMissingError extends MCPException {
constructor(key: string) {
super('CONFIG_MISSING', `Missing required environment variable: ${key}`, { key });
}
}
export class AuthFailedError extends MCPException {
constructor(service: string, reason?: string) {
super('AUTH_FAILED', `Authentication failed for ${service}${reason ? ': ' + reason : ''}`, { service });
}
}
export class InvalidArgError extends MCPException {
constructor(arg: string, reason: string) {
super('INVALID_ARG', `Invalid argument '${arg}': ${reason}`, { arg });
}
}
export class NotFoundError extends MCPException {
constructor(resource: string, id?: string) {
super('NOT_FOUND', `${resource}${id ? ' ' + id : ''} not found`, { resource, id });
}
}
export class SessionNotFoundError extends MCPException {
constructor(sessionId: string) {
super('SESSION_NOT_FOUND', `Session ${sessionId} not found or expired`, { sessionId });
}
}
export class ConflictError extends MCPException {
constructor(resource: string, reason: string) {
super('CONFLICT', `Conflict with ${resource}: ${reason}`, { resource });
}
}
export class RateLimitedError extends MCPException {
constructor(retryAfterMs?: number) {
super('RATE_LIMITED', 'Rate limit exceeded', { retry_after_ms: retryAfterMs });
}
}
export class TimeoutError extends MCPException {
constructor(operation: string, timeoutMs: number) {
super('TIMEOUT', `Operation '${operation}' timed out after ${timeoutMs}ms`, { operation, timeoutMs });
}
}
export class UnavailableError extends MCPException {
constructor(service: string, reason?: string) {
super('UNAVAILABLE', `Service ${service} is unavailable${reason ? ': ' + reason : ''}`, { service });
}
}