|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +"""MCP Gateway Centralized for Pydantic validation error, SQL exception. |
| 3 | +
|
| 4 | +Copyright 2025 |
| 5 | +SPDX-License-Identifier: Apache-2.0 |
| 6 | +Authors: Mihai Criveti |
| 7 | +
|
| 8 | +
|
| 9 | +""" |
| 10 | + |
| 11 | +# Standard |
| 12 | +from typing import Dict, Any |
| 13 | +import logging |
| 14 | + |
| 15 | +# Third-Party |
| 16 | +from pydantic import ValidationError |
| 17 | +from sqlalchemy.exc import IntegrityError, DatabaseError |
| 18 | + |
| 19 | + |
| 20 | +logger = logging.getLogger(__name__) |
| 21 | + |
| 22 | + |
| 23 | +class ErrorFormatter: |
| 24 | + """ |
| 25 | + Transform technical errors into user-friendly messages. |
| 26 | + """ |
| 27 | + @staticmethod |
| 28 | + def format_validation_error(error: ValidationError) -> Dict[str, Any]: |
| 29 | + """ |
| 30 | + Convert Pydantic errors to user-friendly format. |
| 31 | +
|
| 32 | + Args: |
| 33 | + error (ValidationError): The Pydantic validation error. |
| 34 | +
|
| 35 | + Returns: |
| 36 | + Dict[str, Any]: A dictionary with formatted error details. |
| 37 | + """ |
| 38 | + errors = [] |
| 39 | + |
| 40 | + for err in error.errors(): |
| 41 | + field = err.get('loc', ['field'])[-1] |
| 42 | + msg = err.get('msg', 'Invalid value') |
| 43 | + |
| 44 | + # Map technical messages to user-friendly ones |
| 45 | + user_message = ErrorFormatter._get_user_message(field, msg) |
| 46 | + errors.append({ |
| 47 | + "field": field, |
| 48 | + "message": user_message |
| 49 | + }) |
| 50 | + |
| 51 | + # Log the full error for debugging |
| 52 | + logger.debug(f"Validation error: {error}") |
| 53 | + print(type(error)) |
| 54 | + |
| 55 | + return { |
| 56 | + "message": "Validation failed", |
| 57 | + "details": errors, |
| 58 | + "success": False |
| 59 | + } |
| 60 | + |
| 61 | + @staticmethod |
| 62 | + def _get_user_message(field: str, technical_msg: str) -> str: |
| 63 | + """ |
| 64 | + Map technical validation messages to user-friendly ones. |
| 65 | +
|
| 66 | + Args: |
| 67 | + field (str): The field name. |
| 68 | + technical_msg (str): The technical validation message. |
| 69 | +
|
| 70 | + Returns: |
| 71 | + str: User-friendly error message. |
| 72 | + """ |
| 73 | + mappings = { |
| 74 | + "Tool name must start with a letter": f"{field.title()} must start with a letter and contain only letters, numbers, and underscores", |
| 75 | + "Tool name exceeds maximum length": f"{field.title()} is too long (maximum 255 characters)", |
| 76 | + "Tool URL must start with": f"{field.title()} must be a valid HTTP or WebSocket URL", |
| 77 | + "cannot contain directory traversal": f"{field.title()} contains invalid characters", |
| 78 | + "contains HTML tags": f"{field.title()} cannot contain HTML or script tags", |
| 79 | + } |
| 80 | + |
| 81 | + for pattern, friendly_msg in mappings.items(): |
| 82 | + if pattern in technical_msg: |
| 83 | + return friendly_msg |
| 84 | + |
| 85 | + # Default fallback |
| 86 | + return f"Invalid {field}" |
| 87 | + |
| 88 | + @staticmethod |
| 89 | + def format_database_error(error: DatabaseError) -> Dict[str, Any]: |
| 90 | + """ |
| 91 | + Convert database errors to user-friendly format. |
| 92 | +
|
| 93 | + Args: |
| 94 | + error (DatabaseError): The database error. |
| 95 | +
|
| 96 | + Returns: |
| 97 | + Dict[str, Any]: A dictionary with formatted error details. |
| 98 | + """ |
| 99 | + error_str = str(error.orig) if hasattr(error, 'orig') else str(error) |
| 100 | + |
| 101 | + # Log full error |
| 102 | + logger.error(f"Database error: {error}") |
| 103 | + |
| 104 | + # Map common database errors |
| 105 | + if isinstance(error, IntegrityError): |
| 106 | + if "UNIQUE constraint failed" in error_str: |
| 107 | + if "gateways.url" in error_str: |
| 108 | + return {"message": "A gateway with this URL already exists", "success": False} |
| 109 | + elif "gateways.name" in error_str: |
| 110 | + return {"message": "A gateway with this name already exists", "success": False} |
| 111 | + elif "tools.name" in error_str: |
| 112 | + return {"message": "A tool with this name already exists", "success": False} |
| 113 | + elif "resources.uri" in error_str: |
| 114 | + return {"message": "A resource with this URI already exists", "success": False} |
| 115 | + elif "FOREIGN KEY constraint failed" in error_str: |
| 116 | + return {"message": "Referenced item not found", "success": False} |
| 117 | + elif "NOT NULL constraint failed" in error_str: |
| 118 | + return {"message": "Required field is missing", "success": False} |
| 119 | + elif "CHECK constraint failed:" in error_str: |
| 120 | + return {"message": "Gateway validation failed. Please check the input data.", "success": False} |
| 121 | + |
| 122 | + # Generic database error |
| 123 | + return {"message": "Unable to complete the operation. Please try again.", "success": False} |
0 commit comments