|
@@ -0,0 +1,204 @@
|
|
|
|
|
+"""
|
|
|
|
|
+-----------------------------------------------------------------------------------------
|
|
|
|
|
+INTERSEL - 4 cité d'Hauteville - 75010 PARIS
|
|
|
|
|
+RCS PARIS 488 379 660 - NAF 721Z
|
|
|
|
|
+
|
|
|
|
|
+File : api/modx_client.py
|
|
|
|
|
+Object : HTTP client to interact with the MODX REST API
|
|
|
|
|
+-----------------------------------------------------------------------------------------
|
|
|
|
|
+Modifications :
|
|
|
|
|
+- 2026/01/27 - Damien Lugagne-Delpon - V1.0.0- Creation
|
|
|
|
|
+
|
|
|
|
|
+-----------------------------------------------------------------------------------------
|
|
|
|
|
+@copyright : Intersel 2026
|
|
|
|
|
+@author : Damien Lugagne-Delpon - damien.lugagne-delpon@livinweb.fr
|
|
|
|
|
+@version : 1.0.0 (to be updated to the current_version of the developed software if file is touched)
|
|
|
|
|
+-----------------------------------------------------------------------------------------
|
|
|
|
|
+
|
|
|
|
|
+"""
|
|
|
|
|
+
|
|
|
|
|
+import httpx
|
|
|
|
|
+import logging
|
|
|
|
|
+from typing import Dict, Any, Optional
|
|
|
|
|
+from mcp_server.config import settings
|
|
|
|
|
+from mcp_server.core.errors import (
|
|
|
|
|
+ AuthenticationError,
|
|
|
|
|
+ MODXAPIError,
|
|
|
|
|
+ InternalError,
|
|
|
|
|
+)
|
|
|
|
|
+
|
|
|
|
|
+logger = logging.getLogger(__name__)
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+class ModxClient:
|
|
|
|
|
+ """Client HTTP pour communiquer avec l'API REST MODX."""
|
|
|
|
|
+
|
|
|
|
|
+ def __init__(self):
|
|
|
|
|
+ """Initialiser le client MODX."""
|
|
|
|
|
+ self.base_url = settings.MODX_API_BASE_URL
|
|
|
|
|
+ self.timeout = settings.MODX_API_TIMEOUT
|
|
|
|
|
+ self.auth_type = settings.AUTH_TYPE
|
|
|
|
|
+ self.auth_token = settings.AUTH_TOKEN
|
|
|
|
|
+ self.client = httpx.Client(timeout=self.timeout)
|
|
|
|
|
+
|
|
|
|
|
+ def _get_headers(self) -> Dict[str, str]:
|
|
|
|
|
+ """
|
|
|
|
|
+ Construire les headers pour les requêtes.
|
|
|
|
|
+
|
|
|
|
|
+ Returns:
|
|
|
|
|
+ Dict contenant les headers d'authentification
|
|
|
|
|
+ """
|
|
|
|
|
+ headers = {
|
|
|
|
|
+ "Content-Type": "application/json",
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ # Ajouter l'authentification
|
|
|
|
|
+ if self.auth_type == "bearer" and self.auth_token:
|
|
|
|
|
+ headers["Authorization"] = f"Bearer {self.auth_token}"
|
|
|
|
|
+ elif self.auth_type == "api_key" and self.auth_token:
|
|
|
|
|
+ headers["X-API-Key"] = self.auth_token
|
|
|
|
|
+
|
|
|
|
|
+ return headers
|
|
|
|
|
+
|
|
|
|
|
+ def _handle_response(self, response: httpx.Response) -> Dict[str, Any]:
|
|
|
|
|
+ """
|
|
|
|
|
+ Traiter la réponse HTTP et lever les exceptions appropriées.
|
|
|
|
|
+
|
|
|
|
|
+ Args:
|
|
|
|
|
+ response: Réponse httpx
|
|
|
|
|
+
|
|
|
|
|
+ Returns:
|
|
|
|
|
+ Données JSON de la réponse
|
|
|
|
|
+
|
|
|
|
|
+ Raises:
|
|
|
|
|
+ AuthenticationError: Si authentification échouée
|
|
|
|
|
+ MODXAPIError: Si erreur API MODX
|
|
|
|
|
+ InternalError: Si erreur serveur
|
|
|
|
|
+ """
|
|
|
|
|
+ try:
|
|
|
|
|
+ data = response.json()
|
|
|
|
|
+ except Exception as e:
|
|
|
|
|
+ logger.error(f"Erreur décodage JSON: {e}")
|
|
|
|
|
+ raise InternalError(f"Invalid JSON response from MODX API: {str(e)}")
|
|
|
|
|
+
|
|
|
|
|
+ # Vérifier statut HTTP
|
|
|
|
|
+ if response.status_code == 401:
|
|
|
|
|
+ raise AuthenticationError(
|
|
|
|
|
+ "Authentication failed with MODX API",
|
|
|
|
|
+ details={"status_code": 401, "response": data}
|
|
|
|
|
+ )
|
|
|
|
|
+ elif response.status_code == 403:
|
|
|
|
|
+ raise AuthenticationError(
|
|
|
|
|
+ "Access denied to MODX resource",
|
|
|
|
|
+ details={"status_code": 403, "response": data}
|
|
|
|
|
+ )
|
|
|
|
|
+ elif response.status_code >= 400:
|
|
|
|
|
+ error_msg = data.get("message", f"HTTP {response.status_code}")
|
|
|
|
|
+ raise MODXAPIError(
|
|
|
|
|
+ f"MODX API error: {error_msg}",
|
|
|
|
|
+ code=response.status_code,
|
|
|
|
|
+ details={"response": data}
|
|
|
|
|
+ )
|
|
|
|
|
+
|
|
|
|
|
+ return data
|
|
|
|
|
+
|
|
|
|
|
+ def get(self, endpoint: str, params: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
|
|
|
|
|
+ """
|
|
|
|
|
+ Effectuer une requête GET.
|
|
|
|
|
+
|
|
|
|
|
+ Args:
|
|
|
|
|
+ endpoint: Chemin de l'endpoint (ex: "/resource/1")
|
|
|
|
|
+ params: Paramètres query optionnels
|
|
|
|
|
+
|
|
|
|
|
+ Returns:
|
|
|
|
|
+ Réponse JSON
|
|
|
|
|
+ """
|
|
|
|
|
+ url = f"{self.base_url}{endpoint}"
|
|
|
|
|
+ headers = self._get_headers()
|
|
|
|
|
+
|
|
|
|
|
+ try:
|
|
|
|
|
+ logger.debug(f"GET {url}")
|
|
|
|
|
+ response = self.client.get(url, headers=headers, params=params)
|
|
|
|
|
+ return self._handle_response(response)
|
|
|
|
|
+ except (AuthenticationError, MODXAPIError, InternalError):
|
|
|
|
|
+ raise
|
|
|
|
|
+ except Exception as e:
|
|
|
|
|
+ logger.error(f"Erreur requête GET {url}: {e}")
|
|
|
|
|
+ raise InternalError(f"Request failed: {str(e)}")
|
|
|
|
|
+
|
|
|
|
|
+ def post(self, endpoint: str, data: Dict[str, Any]) -> Dict[str, Any]:
|
|
|
|
|
+ """
|
|
|
|
|
+ Effectuer une requête POST.
|
|
|
|
|
+
|
|
|
|
|
+ Args:
|
|
|
|
|
+ endpoint: Chemin de l'endpoint (ex: "/resource")
|
|
|
|
|
+ data: Données à envoyer
|
|
|
|
|
+
|
|
|
|
|
+ Returns:
|
|
|
|
|
+ Réponse JSON
|
|
|
|
|
+ """
|
|
|
|
|
+ url = f"{self.base_url}{endpoint}"
|
|
|
|
|
+ headers = self._get_headers()
|
|
|
|
|
+
|
|
|
|
|
+ try:
|
|
|
|
|
+ logger.debug(f"POST {url} with data: {data}")
|
|
|
|
|
+ response = self.client.post(url, headers=headers, json=data)
|
|
|
|
|
+ return self._handle_response(response)
|
|
|
|
|
+ except (AuthenticationError, MODXAPIError, InternalError):
|
|
|
|
|
+ raise
|
|
|
|
|
+ except Exception as e:
|
|
|
|
|
+ logger.error(f"Erreur requête POST {url}: {e}")
|
|
|
|
|
+ raise InternalError(f"Request failed: {str(e)}")
|
|
|
|
|
+
|
|
|
|
|
+ def put(self, endpoint: str, data: Dict[str, Any]) -> Dict[str, Any]:
|
|
|
|
|
+ """
|
|
|
|
|
+ Effectuer une requête PUT.
|
|
|
|
|
+
|
|
|
|
|
+ Args:
|
|
|
|
|
+ endpoint: Chemin de l'endpoint (ex: "/resource/1")
|
|
|
|
|
+ data: Données à envoyer
|
|
|
|
|
+
|
|
|
|
|
+ Returns:
|
|
|
|
|
+ Réponse JSON
|
|
|
|
|
+ """
|
|
|
|
|
+ url = f"{self.base_url}{endpoint}"
|
|
|
|
|
+ headers = self._get_headers()
|
|
|
|
|
+
|
|
|
|
|
+ try:
|
|
|
|
|
+ logger.debug(f"PUT {url} with data: {data}")
|
|
|
|
|
+ response = self.client.put(url, headers=headers, json=data)
|
|
|
|
|
+ return self._handle_response(response)
|
|
|
|
|
+ except (AuthenticationError, MODXAPIError, InternalError):
|
|
|
|
|
+ raise
|
|
|
|
|
+ except Exception as e:
|
|
|
|
|
+ logger.error(f"Erreur requête PUT {url}: {e}")
|
|
|
|
|
+ raise InternalError(f"Request failed: {str(e)}")
|
|
|
|
|
+
|
|
|
|
|
+ def close(self):
|
|
|
|
|
+ """Fermer la connexion du client."""
|
|
|
|
|
+ self.client.close()
|
|
|
|
|
+
|
|
|
|
|
+ def __enter__(self):
|
|
|
|
|
+ """Support du context manager."""
|
|
|
|
|
+ return self
|
|
|
|
|
+
|
|
|
|
|
+ def __exit__(self, exc_type, exc_val, exc_tb):
|
|
|
|
|
+ """Support du context manager."""
|
|
|
|
|
+ self.close()
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+# Instance globale du client
|
|
|
|
|
+_modx_client: Optional[ModxClient] = None
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def get_modx_client() -> ModxClient:
|
|
|
|
|
+ """
|
|
|
|
|
+ Obtenir l'instance globale du client MODX.
|
|
|
|
|
+
|
|
|
|
|
+ Returns:
|
|
|
|
|
+ Instance de ModxClient
|
|
|
|
|
+ """
|
|
|
|
|
+ global _modx_client
|
|
|
|
|
+ if _modx_client is None:
|
|
|
|
|
+ _modx_client = ModxClient()
|
|
|
|
|
+ return _modx_client
|