from typing import Dict, Any, Optional
from enum import Enum
class JSONRPCErrorCode(Enum):
"""Standard JSON-RPC 2.0 error codes"""
PARSE_ERROR = -32700
INVALID_REQUEST = -32600
METHOD_NOT_FOUND = -32601
INVALID_PARAMS = -32602
INTERNAL_ERROR = -32603
SERVER_ERROR = -32000
class MCPError(Exception):
"""Base MCP protocol error"""
def __init__(self, message: str, code: JSONRPCErrorCode = JSONRPCErrorCode.INTERNAL_ERROR, data: Optional[Dict[str, Any]] = None):
self.message = message
self.code = code
self.data = data
super().__init__(message)
def to_dict(self) -> Dict[str, Any]:
"""Convert error to JSON-RPC error format"""
error_dict = {
"code": self.code.value,
"message": self.message
}
if self.data:
error_dict["data"] = self.data
return error_dict
class InvalidRequestError(MCPError):
def __init__(self, message: str = "Invalid request"):
super().__init__(message, JSONRPCErrorCode.INVALID_REQUEST)
class MethodNotFoundError(MCPError):
def __init__(self, method: str):
super().__init__(f"Method '{method}' not found", JSONRPCErrorCode.METHOD_NOT_FOUND)
class InvalidParamsError(MCPError):
def __init__(self, message: str = "Invalid parameters"):
super().__init__(message, JSONRPCErrorCode.INVALID_PARAMS)
class ResourceNotFoundError(MCPError):
def __init__(self, uri: str):
super().__init__(f"Resource not found: {uri}", JSONRPCErrorCode.SERVER_ERROR)
class ToolExecutionError(MCPError):
def __init__(self, tool_name: str, error: str):
super().__init__(f"Tool '{tool_name}' execution failed: {error}", JSONRPCErrorCode.SERVER_ERROR)