Преглед изворни кода

feat: Implement MODX API client and resource management tools

- Created ModxClient for interacting with the MODX REST API, including methods for GET, POST, and PUT requests.
- Added error handling for authentication and API errors.
- Introduced settings for MODX API configuration, including base URL and authentication tokens.
- Developed permissions management functions to check access rights for resources.
- Implemented request validation for tool calls, ensuring proper structure and parameter types.
- Added response formatting for success and error responses in the MCP server.
- Created tools for resource management: create_resource, get_resource, and update_resource, with appropriate validation and error handling.
- Enhanced logging for better traceability of operations and errors.
Damien Lugagne-Delpon пре 9 месеци
родитељ
комит
e2c84ff5cb

+ 204 - 0
mcp_server/api/modx_client.py

@@ -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

+ 34 - 8
mcp_server/config/settings.py

@@ -17,13 +17,39 @@ Modifications :
 
 """
 
+import os
+from enum import Enum
+
+# ============================================================================
+# MODX API Configuration
+# ============================================================================
+MODX_API_BASE_URL = os.getenv("MODX_API_BASE_URL", "")
+# MODX_API_KEY = os.getenv("MODX_API_KEY", "")
+MODX_API_TIMEOUT = int(os.getenv("MODX_API_TIMEOUT", "30"))
+
+# ============================================================================
+# Authentification
+# ============================================================================
+AUTH_TYPE = os.getenv("AUTH_TYPE", "")
+AUTH_TOKEN = os.getenv("AUTH_TOKEN", "")
+
+# ============================================================================
 # Application
-APP_NAME = "LW Copilot"
-
-MODX_BASE_URL = ""
-MOXDX_API_PATH = ""
-
-
-# Logging
-LOG_LEVEL = "DEBUG"
+# ============================================================================
+APP_NAME = "LW-Copilot"
+APP_VERSION = "1.0.0"
+LOG_LEVEL = os.getenv("LOG_LEVEL", "DEBUG")
+
+
+# ============================================================================
+# Chemins des endpoints MODX
+# ============================================================================
+MODX_ENDPOINTS = {
+    "resource": {
+        "create": "/tools/resource",  # POST /tools/resource
+        "read": "/tools/resource/{id}",  # GET /tools/resource/{id}
+        "update": "/tools/resource/{id}",  # PUT /tools/resource/{id}
+        "list": "/tools/resources",  # GET /tools/resources
+    }
+}
 

+ 92 - 0
mcp_server/core/errors.py

@@ -0,0 +1,92 @@
+"""
+-----------------------------------------------------------------------------------------
+INTERSEL - 4 cité d'Hauteville - 75010 PARIS
+RCS PARIS 488 379 660 - NAF 721Z
+
+File : core/errors.py
+Object : Error classes definitions for the MCP server
+
+-----------------------------------------------------------------------------------------
+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)
+-----------------------------------------------------------------------------------------
+
+"""
+
+
+class LWCopilotError(Exception):
+    """Exception de base pour LW-Copilot."""
+    
+    def __init__(self, message: str, code: int = 500, details: dict = None):
+        super().__init__(message)
+        self.message = message
+        self.code = code
+        self.details = details or {}
+
+
+class AuthenticationError(LWCopilotError):
+    """Erreur d'authentification avec l'API MODX."""
+    
+    def __init__(self, message: str = "Authentication failed", details: dict = None):
+        super().__init__(message, code=401, details=details)
+
+
+class PermissionError(LWCopilotError):
+    """Droits insuffisants pour accéder à une ressource."""
+    
+    def __init__(self, message: str = "Permission denied", details: dict = None):
+        super().__init__(message, code=403, details=details)
+
+
+class ResourceNotFoundError(LWCopilotError):
+    """Ressource non trouvée."""
+    
+    def __init__(self, message: str = "Resource not found", details: dict = None):
+        super().__init__(message, code=404, details=details)
+
+
+class TemplateNotFoundError(LWCopilotError):
+    """Template non trouvée."""
+    
+    def __init__(self, message: str = "Template not found", details: dict = None):
+        super().__init__(message, code=404, details=details)
+
+
+class ValidationError(LWCopilotError):
+    """Erreur de validation des paramètres."""
+    
+    def __init__(self, message: str = "Validation error", details: dict = None):
+        super().__init__(message, code=400, details=details)
+
+
+class InvalidToolCallError(LWCopilotError):
+    """Schéma d'appel d'outil invalide."""
+    
+    def __init__(self, message: str = "Invalid tool call", details: dict = None):
+        super().__init__(message, code=400, details=details)
+
+
+class ContextError(LWCopilotError):
+    """Erreur de gestion du contexte."""
+    
+    def __init__(self, message: str = "Context error", details: dict = None):
+        super().__init__(message, code=400, details=details)
+
+
+class MODXAPIError(LWCopilotError):
+    """Erreur générique de l'API MODX."""
+    
+    def __init__(self, message: str = "MODX API error", code: int = 500, details: dict = None):
+        super().__init__(message, code=code, details=details)
+
+
+class InternalError(LWCopilotError):
+    """Erreur interne du serveur."""
+    
+    def __init__(self, message: str = "Internal server error", details: dict = None):
+        super().__init__(message, code=500, details=details)

+ 81 - 0
mcp_server/core/permissions.py

@@ -0,0 +1,81 @@
+"""
+-----------------------------------------------------------------------------------------
+INTERSEL - 4 cité d'Hauteville - 75010 PARIS
+RCS PARIS 488 379 660 - NAF 721Z
+
+File : core/permissions.py
+Object : Permissions management functions for the MCP server
+-----------------------------------------------------------------------------------------
+Modifications :
+- 2026/01/16 - 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)
+-----------------------------------------------------------------------------------------
+
+"""
+
+
+from typing import Optional
+from mcp_server.core.constants import ModxType, actionType
+from mcp_server.core.context.context_manager import ContextManager
+from mcp_server.core.errors import PermissionError
+
+
+def check_permission(
+    context_manager: ContextManager,
+    modx_type: ModxType,
+    resource_id: int,
+    action: actionType
+) -> bool:
+    """
+    Vérifier si une action est autorisée sur une ressource.
+    
+    Args:
+        context_manager: Gestionnaire de contexte
+        modx_type: Type MODX (resource, template, tv, chunk)
+        resource_id: ID de la ressource
+        action: Action demandée (read ou update)
+        
+    Returns:
+        True si l'action est autorisée
+        
+    Raises:
+        PermissionError: Si l'action n'est pas autorisée
+    """
+    # Récupérer le contexte
+    context = context_manager.get_context()
+    
+    # Vérifier que le type de ressource existe dans le contexte
+    if modx_type.value not in context:
+        raise PermissionError(
+            f"Resource type '{modx_type.value}' not found in context",
+            details={"resource_type": modx_type.value, "resource_id": resource_id}
+        )
+    
+    resource_type_context = context[modx_type.value]
+    
+    # Vérifier que la ressource existe dans le contexte
+    if resource_id not in resource_type_context:
+        raise PermissionError(
+            f"Access denied: {modx_type.value} {resource_id} not in context",
+            details={"resource_type": modx_type.value, "resource_id": resource_id}
+        )
+    
+    permissions = resource_type_context[resource_id]
+    
+    # Vérifier que l'action est autorisée
+    if not permissions.get(action.value, False):
+        raise PermissionError(
+            f"Access denied: {action.value} permission not granted for {modx_type.value} {resource_id}",
+            details={
+                "resource_type": modx_type.value,
+                "resource_id": resource_id,
+                "action": action.value,
+                "permissions": permissions
+            }
+        )
+    
+    return True

+ 88 - 5
mcp_server/main.py

@@ -4,10 +4,12 @@ INTERSEL - 4 cité d'Hauteville - 75010 PARIS
 RCS PARIS 488 379 660 - NAF 721Z
 
 File : main.py
-Object : MCP server main entry point
+Object : MCP server main entry point. Initialize configuration, context, and start the MCP server.
+
 -----------------------------------------------------------------------------------------
 Modifications :
-- 2026/01/16 - Damien Lugagne-Delpon - V1.0.0- Creation
+- 2026/01/16 - Damien Lugagne-Delpon - V1.0.0 - Creation
+- 2026/01/27 - Damien Lugagne-Delpon - V1.1.0 - Started implementing main server logic
 
 -----------------------------------------------------------------------------------------
 @copyright : Intersel 2026
@@ -16,13 +18,94 @@ Modifications :
 -----------------------------------------------------------------------------------------
 
 """
+import asyncio
+import json
+import logging
+from mcp_server.config.logger import init_logger, LOGGER
+from mcp_server.config import settings
+from mcp_server.core.context.context_manager import ContextManager
+from mcp_server.mcp.tool_exposure import get_tool_exposure
+from mcp_server.mcp.request_validator import RequestValidator
+from mcp_server.mcp.response_formatter import ResponseFormatter
+from mcp_server.core.errors import InvalidToolCallError, LWCopilotError
 
 
-from mcp_server.config.logger import init_logger, LOGGER
+def initialize_server():
+    """
+    Initialiser le serveur MCP.
+    
+    Returns:
+        Tuple (context_manager, tool_exposure)
+    """
+    # Initialiser le logger
+    init_logger()
+    LOGGER.info(f"Initializing {settings.APP_NAME} v{settings.APP_VERSION}")
+
+    # Initialiser le contexte
+    context_manager = ContextManager()
+    LOGGER.info("Context manager initialized")
+
+    # Initialiser l'exposition des outils
+    tool_exposure = get_tool_exposure()
+    LOGGER.info(f"Tool exposure initialized with {len(tool_exposure.tools)} tools")
+
+    return context_manager, tool_exposure
+
+
+async def handle_tool_call(tool_exposure: get_tool_exposure, request_data: dict) -> dict:
+    """
+    Traiter un appel d'outil.
+    
+    Args:
+        tool_exposure: Gestionnaire d'exposition des outils
+        request_data: Données de la requête
+        
+    Returns:
+        Réponse formatée
+    """
+    try:
+        # Valider la requête
+        is_valid, error_msg = RequestValidator.validate_request(request_data)
+        if not is_valid:
+            LOGGER.error(f"Invalid request: {error_msg}")
+            return ResponseFormatter.format_validation_error("request", error_msg)
+
+        tool_name = request_data.get("tool")
+        parameters = request_data.get("parameters", {})
+
+        # Appeler l'outil
+        response = await tool_exposure.call_tool(tool_name, parameters)
+        return response
+
+    except InvalidToolCallError as e:
+        LOGGER.error(f"Invalid tool call: {e.message}")
+        return ResponseFormatter.format_error_response(e.code, e.message)
+    except LWCopilotError as e:
+        LOGGER.error(f"LW-Copilot error: {e.message}")
+        return ResponseFormatter.format_error_response(e.code, e.message)
+    except Exception as e:
+        LOGGER.error(f"Unexpected error: {str(e)}")
+        return ResponseFormatter.format_error_response(500, f"Internal error: {str(e)}")
+
 
 def main():
-    """MCP server main entry point."""
+    """Point d'entrée du serveur MCP."""
     init_logger()
     LOGGER.debug("main - Starting MCP server...")
 
-    pass
+    # Initialiser le serveur
+    context_manager, tool_exposure = initialize_server()
+
+    # Afficher les outils disponibles
+    tools_schema = tool_exposure.get_tools_schema()
+    LOGGER.info(f"Available tools:")
+    for tool in tools_schema:
+        LOGGER.info(f"  - {tool['name']}: {tool['description']}")
+
+    # Exemple d'utilisation (pour test)
+    # Dans un vrai serveur MCP, cela serait géré par le protocole MCP
+    LOGGER.info(f"Server is ready. Listening on {settings.MCP_HOST}:{settings.MCP_PORT}")
+
+
+if __name__ == "__main__":
+    main()

+ 106 - 16
mcp_server/mcp/request_validator.py

@@ -17,27 +17,117 @@ Modifications :
 
 """
 
-class RequestValidator:
-    """Request validator for the MCP server."""
-    def __init__(self):
-        """Initialize the request validator."""
-        self.schema = REQUEST_SCHEMA
+"""
+Validateur de requêtes pour le serveur MCP.
+"""
+import logging
+from typing import Dict, Any, List, Tuple
+from mcp_server.core.errors import InvalidToolCallError
 
-    def validate(self, request_data: dict) -> bool:
-        """Validate the incoming request data.
+logger = logging.getLogger(__name__)
 
-        Args:
-            request_data (dict): The incoming request data.
 
+class RequestValidator:
+    """Validateur de requêtes MCP."""
+
+    @staticmethod
+    def validate_tool_call(request_data: Dict[str, Any], available_tools: Dict[str, Any]) -> Tuple[bool, str]:
+        """
+        Valider un appel d'outil.
+        
+        Args:
+            request_data: Données de la requête {tool: "name", parameters: {...}}
+            available_tools: Dict des outils disponibles {tool_name: {parameters: {...}}}
+            
         Returns:
-            bool: If the request is valid.
+            Tuple (is_valid, error_message)
         """
-        tool = request_data.get("tool")
+        # Vérifier structure basique
+        if not isinstance(request_data, dict):
+            return False, "Request must be a dictionary"
+
+        if "tool" not in request_data:
+            return False, "Missing 'tool' field"
+
+        if "parameters" not in request_data:
+            return False, "Missing 'parameters' field"
+
+        tool_name = request_data.get("tool")
         parameters = request_data.get("parameters")
-        return True
 
+        # Vérifier que l'outil existe
+        if tool_name not in available_tools:
+            return False, f"Unknown tool: {tool_name}"
+
+        # Vérifier que parameters est un dict
+        if not isinstance(parameters, dict):
+            return False, "Parameters must be a dictionary"
+
+        # Obtenir le schéma de l'outil
+        tool_schema = available_tools[tool_name]
+        tool_parameters = tool_schema.get("parameters", {})
+
+        # Vérifier les paramètres requis
+        missing_required = []
+        for param_name, param_info in tool_parameters.items():
+            if param_info.get("required", False) and param_name not in parameters:
+                missing_required.append(param_name)
+
+        if missing_required:
+            return False, f"Missing required parameters: {', '.join(missing_required)}"
+
+        # Vérifier les paramètres inconnus
+        unknown_params = []
+        for param_name in parameters:
+            if param_name not in tool_parameters:
+                unknown_params.append(param_name)
+
+        if unknown_params:
+            return False, f"Unknown parameters: {', '.join(unknown_params)}"
+
+        # Vérifier les types (validation basique)
+        for param_name, param_value in parameters.items():
+            param_info = tool_parameters[param_name]
+            expected_type = param_info.get("type")
+
+            # Mapper les types JSON aux types Python
+            type_mapping = {
+                "string": str,
+                "integer": int,
+                "boolean": bool,
+                "object": dict,
+                "array": list,
+                "number": (int, float),
+            }
+
+            if expected_type in type_mapping:
+                expected_python_type = type_mapping[expected_type]
+                if not isinstance(param_value, expected_python_type):
+                    return False, f"Parameter '{param_name}' must be of type {expected_type}, got {type(param_value).__name__}"
+
+        return True, ""
+
+    @staticmethod
+    def validate_request(request_data: Dict[str, Any]) -> Tuple[bool, str]:
+        """
+        Valider la structure générale d'une requête.
+        
+        Args:
+            request_data: Données de la requête
+            
+        Returns:
+            Tuple (is_valid, error_message)
+        """
+        if not isinstance(request_data, dict):
+            return False, "Request must be a dictionary"
+
+        if "tool" not in request_data:
+            return False, "Missing 'tool' field"
+
+        if "parameters" not in request_data:
+            return False, "Missing 'parameters' field"
+
+        if not isinstance(request_data.get("parameters"), dict):
+            return False, "Parameters must be a dictionary"
 
-REQUEST_SCHEMA = {
-    "tool": str,
-    "parameters": dict
-}
+        return True, ""

+ 121 - 5
mcp_server/mcp/response_formatter.py

@@ -17,9 +17,125 @@ Modifications :
 
 """
 
+"""
+Formateur de réponses pour le serveur MCP.
+Transforme les réponses des outils au format attendu par le protocole MCP.
+"""
+import logging
+import json
+from typing import Dict, Any, Union, List
+
+logger = logging.getLogger(__name__)
+
+
 class ResponseFormatter:
-    """Response formatter for the MCP server."""
-    def format_response(self, response: dict) -> str:
-        """Format the response into a string."""
-        formatted_response = dict()
-        return formatted_response
+    """Formateur de réponses MCP."""
+
+    @staticmethod
+    def format_tool_response(tool_response: Dict[str, Any]) -> Dict[str, Any]:
+        """
+        Formater la réponse d'un outil au format MCP.
+        
+        Args:
+            tool_response: Réponse brute de l'outil
+            
+        Returns:
+            Réponse formatée pour MCP
+        """
+        # Valider que la réponse a la structure attendue
+        if not isinstance(tool_response, dict):
+            return {
+                "success": False,
+                "code": 500,
+                "data": [],
+                "message": "Invalid tool response format"
+            }
+
+        # Assurer que les champs obligatoires sont présents
+        formatted = {
+            "success": tool_response.get("success", False),
+            "code": tool_response.get("code", 500),
+            "data": tool_response.get("data", []),
+            "message": tool_response.get("message", "No message provided")
+        }
+
+        # Valider les types
+        if not isinstance(formatted["success"], bool):
+            formatted["success"] = bool(formatted["success"])
+
+        if not isinstance(formatted["code"], int):
+            try:
+                formatted["code"] = int(formatted["code"])
+            except (ValueError, TypeError):
+                formatted["code"] = 500
+
+        if not isinstance(formatted["data"], list):
+            formatted["data"] = [formatted["data"]]
+
+        if not isinstance(formatted["message"], str):
+            formatted["message"] = str(formatted["message"])
+
+        return formatted
+
+    @staticmethod
+    def format_error_response(error_code: int, error_message: str, details: Dict[str, Any] = None) -> Dict[str, Any]:
+        """
+        Formater une réponse d'erreur.
+        
+        Args:
+            error_code: Code d'erreur HTTP
+            error_message: Message d'erreur
+            details: Détails additionnels de l'erreur
+            
+        Returns:
+            Réponse formatée d'erreur
+        """
+        return {
+            "success": False,
+            "code": error_code,
+            "data": [details] if details else [],
+            "message": error_message
+        }
+
+    @staticmethod
+    def format_success_response(data: Union[Dict, List], message: str = "Success") -> Dict[str, Any]:
+        """
+        Formater une réponse de succès.
+        
+        Args:
+            data: Données de succès
+            message: Message de succès
+            
+        Returns:
+            Réponse formatée de succès
+        """
+        if isinstance(data, dict):
+            data = [data]
+        elif not isinstance(data, list):
+            data = [data]
+
+        return {
+            "success": True,
+            "code": 200,
+            "data": data,
+            "message": message
+        }
+
+    @staticmethod
+    def format_validation_error(field: str, reason: str) -> Dict[str, Any]:
+        """
+        Formater une erreur de validation.
+        
+        Args:
+            field: Champ en erreur
+            reason: Raison de l'erreur
+            
+        Returns:
+            Réponse formatée d'erreur de validation
+        """
+        return {
+            "success": False,
+            "code": 400,
+            "data": [{"field": field, "reason": reason}],
+            "message": f"Validation error: {reason}"
+        }

+ 149 - 0
mcp_server/mcp/tool_exposure.py

@@ -0,0 +1,149 @@
+"""
+Exposition des outils au protocole MCP.
+Génère la liste des outils disponibles au format MCP et les mappe aux handlers.
+"""
+import logging
+from typing import Dict, Any, List, Callable
+import asyncio
+from mcp_server.tools.tool_class import Tool
+from mcp_server.tools.resource.create_resource import create_resource_tool
+from mcp_server.tools.resource.get_resource import get_resource_tool
+from mcp_server.tools.resource.update_resource import update_resource_tool
+from mcp_server.mcp.request_validator import RequestValidator
+from mcp_server.mcp.response_formatter import ResponseFormatter
+from mcp_server.core.errors import InvalidToolCallError
+
+logger = logging.getLogger(__name__)
+
+
+class ToolExposure:
+    """Gestionnaire d'exposition des outils MCP."""
+
+    def __init__(self):
+        """Initialiser l'exposition des outils."""
+        self.tools = {
+            "create_resource": create_resource_tool,
+            "get_resource": get_resource_tool,
+            "update_resource": update_resource_tool,
+        }
+        self.tools_schema = self._generate_tools_schema()
+
+    def _generate_tools_schema(self) -> List[Dict[str, Any]]:
+        """
+        Générer le schéma JSON des outils pour le protocole MCP.
+        
+        Returns:
+            Liste des outils au format MCP
+        """
+        tools_schema = []
+
+        for tool_name, tool in self.tools.items():
+            # Convertir les paramètres du format Tool au format MCP
+            parameters_schema = {}
+            for param_name, param in tool.parameters.items():
+                parameters_schema[param_name] = {
+                    "type": param.type,
+                    "description": param.description,
+                    "required": param.required,
+                }
+                if param.default is not None:
+                    parameters_schema[param_name]["default"] = param.default
+
+            tool_schema = {
+                "name": tool.name,
+                "description": tool.description,
+                "parameters": parameters_schema,
+                "remarks": tool.remarks,
+            }
+
+            tools_schema.append(tool_schema)
+
+        logger.info(f"Exposed {len(tools_schema)} tools to MCP")
+        return tools_schema
+
+    def get_tools_schema(self) -> List[Dict[str, Any]]:
+        """
+        Obtenir le schéma de tous les outils.
+        
+        Returns:
+            Liste des outils
+        """
+        return self.tools_schema
+
+    def get_tools_dict(self) -> Dict[str, Dict[str, Any]]:
+        """
+        Obtenir un dictionnaire des outils pour validation.
+        
+        Returns:
+            Dict {tool_name: {parameters: {...}}}
+        """
+        tools_dict = {}
+        for schema in self.tools_schema:
+            tools_dict[schema["name"]] = {
+                "parameters": schema["parameters"]
+            }
+        return tools_dict
+
+    async def call_tool(self, tool_name: str, parameters: Dict[str, Any]) -> Dict[str, Any]:
+        """
+        Appeler un outil avec ses paramètres.
+        
+        Args:
+            tool_name: Nom de l'outil
+            parameters: Paramètres de l'appel
+            
+        Returns:
+            Réponse de l'outil
+            
+        Raises:
+            InvalidToolCallError: Si l'appel d'outil est invalide
+        """
+        # Valider l'appel d'outil
+        is_valid, error_msg = RequestValidator.validate_tool_call(
+            {"tool": tool_name, "parameters": parameters},
+            self.get_tools_dict()
+        )
+
+        if not is_valid:
+            logger.error(f"Invalid tool call: {error_msg}")
+            raise InvalidToolCallError(error_msg)
+
+        # Obtenir l'outil
+        if tool_name not in self.tools:
+            raise InvalidToolCallError(f"Unknown tool: {tool_name}")
+
+        tool = self.tools[tool_name]
+
+        # Appeler le handler
+        try:
+            logger.info(f"Calling tool: {tool_name} with parameters: {parameters}")
+            response = await tool.handler(**parameters)
+            
+            # Formater la réponse
+            formatted_response = ResponseFormatter.format_tool_response(response)
+            logger.debug(f"Tool response: {formatted_response}")
+            return formatted_response
+
+        except Exception as e:
+            logger.error(f"Error calling tool {tool_name}: {str(e)}")
+            return ResponseFormatter.format_error_response(
+                500,
+                f"Error executing tool: {str(e)}"
+            )
+
+
+# Instance globale du gestionnaire d'exposition
+_tool_exposure: ToolExposure = None
+
+
+def get_tool_exposure() -> ToolExposure:
+    """
+    Obtenir l'instance globale du gestionnaire d'exposition.
+    
+    Returns:
+        Instance de ToolExposure
+    """
+    global _tool_exposure
+    if _tool_exposure is None:
+        _tool_exposure = ToolExposure()
+    return _tool_exposure

+ 181 - 0
mcp_server/tools/resource/create_resource.py

@@ -0,0 +1,181 @@
+"""
+Outil pour créer une ressource MODX.
+"""
+import logging
+from typing import Dict, Any
+import asyncio
+from mcp_server.tools.tool_class import Tool, ToolParameter
+from mcp_server.api.modx_client import get_modx_client
+from mcp_server.config import settings
+from mcp_server.core.constants import ModxType, actionType
+from mcp_server.core.permissions import check_permission
+from mcp_server.core.errors import (
+    ValidationError,
+    PermissionError,
+    MODXAPIError,
+    InternalError,
+)
+
+logger = logging.getLogger(__name__)
+
+
+class CreateResourceTool(Tool):
+    """Outil pour créer une ressource MODX."""
+
+    def __init__(self):
+        """Initialiser l'outil CreateResource."""
+        super().__init__(
+            name="create_resource",
+            description="Create a new resource in MODX with specified template and properties.",
+            remarks="The template must be available in the context with read permission. "
+                   "Use get_template to understand template structure before creation.",
+            parameters={
+                "pagetitle": ToolParameter(
+                    required=True,
+                    type="string",
+                    description="Page title of the resource"
+                ),
+                "template": ToolParameter(
+                    required=True,
+                    type="integer",
+                    description="Template ID to use for the resource"
+                ),
+                "content": ToolParameter(
+                    required=False,
+                    type="string",
+                    description="Main content of the resource",
+                    default=""
+                ),
+                "parent": ToolParameter(
+                    required=False,
+                    type="integer",
+                    description="Parent resource ID (0 for root)",
+                    default=0
+                ),
+                "published": ToolParameter(
+                    required=False,
+                    type="boolean",
+                    description="Publish the resource",
+                    default=False
+                ),
+                "tvs": ToolParameter(
+                    required=False,
+                    type="object",
+                    description="Template variable values as {tv_name: value}",
+                    default={}
+                ),
+                "alias": ToolParameter(
+                    required=False,
+                    type="string",
+                    description="URL alias for the resource",
+                    default=""
+                ),
+            }
+        )
+
+    async def handler(self, **kwargs) -> Dict[str, Any]:
+        """
+        Créer une ressource MODX.
+        
+        Returns:
+            Dict avec structure {success, code, data, message}
+        """
+        try:
+            # Extraire les paramètres
+            pagetitle = kwargs.get("pagetitle")
+            template_id = kwargs.get("template")
+            content = kwargs.get("content", "")
+            parent = kwargs.get("parent", 0)
+            published = kwargs.get("published", False)
+            tvs = kwargs.get("tvs", {})
+            alias = kwargs.get("alias", "")
+
+            # Validation basique
+            if not pagetitle or not isinstance(pagetitle, str):
+                return {
+                    "success": False,
+                    "code": 400,
+                    "data": [],
+                    "message": "pagetitle is required and must be a string"
+                }
+
+            if not isinstance(template_id, int) or template_id <= 0:
+                return {
+                    "success": False,
+                    "code": 400,
+                    "data": [],
+                    "message": "template must be a positive integer"
+                }
+
+            # Préparer les données pour l'API
+            resource_data = {
+                "pagetitle": pagetitle,
+                "template": template_id,
+                "content": content,
+                "parent": parent,
+                "published": published,
+            }
+
+            if alias:
+                resource_data["alias"] = alias
+
+            if tvs:
+                resource_data["tvs"] = tvs
+
+            # Appeler l'API MODX
+            logger.info(f"Creating resource: {pagetitle}")
+            client = get_modx_client()
+            endpoint = settings.MODX_ENDPOINTS["resource"]["create"]
+            response = client.post(endpoint, resource_data)
+
+            # Ajouter la ressource créée au contexte
+            if response.get("success") and "data" in response:
+                created_resource = response["data"]
+                if isinstance(created_resource, dict) and "id" in created_resource:
+                    # La ressource est créée avec droits read et update
+                    # Cela sera géré par le client MCP/l'agent
+                    logger.info(f"Resource created successfully: ID {created_resource['id']}")
+
+            return {
+                "success": response.get("success", False),
+                "code": response.get("code", 500),
+                "data": response.get("data", []),
+                "message": response.get("message", "Resource creation completed")
+            }
+
+        except PermissionError as e:
+            logger.warning(f"Permission denied: {e.message}")
+            return {
+                "success": False,
+                "code": e.code,
+                "data": [],
+                "message": e.message
+            }
+        except MODXAPIError as e:
+            logger.error(f"MODX API error: {e.message}")
+            return {
+                "success": False,
+                "code": e.code,
+                "data": [],
+                "message": e.message
+            }
+        except ValidationError as e:
+            logger.error(f"Validation error: {e.message}")
+            return {
+                "success": False,
+                "code": e.code,
+                "data": [],
+                "message": e.message
+            }
+        except Exception as e:
+            logger.error(f"Unexpected error in create_resource: {str(e)}")
+            return {
+                "success": False,
+                "code": 500,
+                "data": [],
+                "message": f"Internal error: {str(e)}"
+            }
+
+
+# Instance globale de l'outil
+create_resource_tool = CreateResourceTool()

+ 89 - 49
mcp_server/tools/resource/get_resource.py

@@ -1,52 +1,92 @@
 """
------------------------------------------------------------------------------------------
-INTERSEL - 4 cité d'Hauteville - 75010 PARIS
-RCS PARIS 488 379 660 - NAF 721Z
-
-File : tools/resource/get_resource.py
-Object : Tool to get resources for the MCP server
------------------------------------------------------------------------------------------
-Modifications :
-- 2026/01/16 - 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)
------------------------------------------------------------------------------------------
-
+Outil pour lire une ressource MODX.
 """
+import logging
+from typing import Dict, Any
+import asyncio
+from mcp_server.tools.tool_class import Tool, ToolParameter
+from mcp_server.api.modx_client import get_modx_client
+from mcp_server.config import settings
+from mcp_server.core.errors import (
+    ResourceNotFoundError,
+    MODXAPIError,
+    InternalError,
+)
+
+logger = logging.getLogger(__name__)
+
+
+class GetResourceTool(Tool):
+    """Outil pour lire une ressource MODX."""
+
+    def __init__(self):
+        """Initialiser l'outil GetResource."""
+        super().__init__(
+            name="get_resource",
+            description="Retrieve a resource from MODX by its ID.",
+            remarks="The resource must be available in the context with read permission. "
+                   "Returns full resource data including TVs and metadata.",
+            parameters={
+                "id": ToolParameter(
+                    required=True,
+                    type="integer",
+                    description="ID of the resource to retrieve"
+                ),
+            }
+        )
+
+    async def handler(self, **kwargs) -> Dict[str, Any]:
+        """
+        Lire une ressource MODX.
+        
+        Returns:
+            Dict avec structure {success, code, data, message}
+        """
+        try:
+            # Extraire les paramètres
+            resource_id = kwargs.get("id")
+
+            # Validation basique
+            if not isinstance(resource_id, int) or resource_id <= 0:
+                return {
+                    "success": False,
+                    "code": 400,
+                    "data": [],
+                    "message": "id must be a positive integer"
+                }
+
+            # Appeler l'API MODX
+            logger.info(f"Retrieving resource: ID {resource_id}")
+            client = get_modx_client()
+            endpoint = settings.MODX_ENDPOINTS["resource"]["read"].format(id=resource_id)
+            response = client.get(endpoint)
+
+            return {
+                "success": response.get("success", False),
+                "code": response.get("code", 500),
+                "data": response.get("data", []),
+                "message": response.get("message", "Resource retrieval completed")
+            }
+
+        except MODXAPIError as e:
+            logger.error(f"MODX API error: {e.message}")
+            return {
+                "success": False,
+                "code": e.code,
+                "data": [],
+                "message": e.message
+            }
+        except Exception as e:
+            logger.error(f"Unexpected error in get_resource: {str(e)}")
+            return {
+                "success": False,
+                "code": 500,
+                "data": [],
+                "message": f"Internal error: {str(e)}"
+            }
+
 
-from mcp_server.tools.resource import ResourceTool
-
-def get_resource_tool():
-    """Create and return the Get Resource tool."""
-    parameters = {
-        "id": {
-            "type": "string",
-            "description": "ID of the resource to retrieve",
-            "required": True,
-            "default": None
-        },
-        "mandatoryParents": {
-                "type": "integer",
-                "description": "An authorized parent for the given id",
-                "required": False,
-                "default": None
-        }
-    }
-    
-    tool = ResourceTool(
-        name="Get Resource",
-        description="Retrieve a resource by its ID.",
-        remarks="",
-        parameters=parameters,
-        handler=get_resource_tool_handler
-    )
-    
-    return tool
-
-
-async def get_resource_tool_handler(resource_id):
-        """Handler function to get the resource."""
-        pass
+# Instance globale de l'outil
+# get_resource_tool = GetResourceTool()
+#         """Handler function to get the resource."""
+#         pass

+ 158 - 0
mcp_server/tools/resource/update_resource.py

@@ -0,0 +1,158 @@
+"""
+Outil pour mettre à jour une ressource MODX.
+"""
+import logging
+from typing import Dict, Any
+import asyncio
+from mcp_server.tools.tool_class import Tool, ToolParameter
+from mcp_server.api.modx_client import get_modx_client
+from mcp_server.config import settings
+from mcp_server.core.errors import (
+    ResourceNotFoundError,
+    MODXAPIError,
+    ValidationError,
+    InternalError,
+)
+
+logger = logging.getLogger(__name__)
+
+
+class UpdateResourceTool(Tool):
+    """Outil pour mettre à jour une ressource MODX."""
+
+    def __init__(self):
+        """Initialiser l'outil UpdateResource."""
+        super().__init__(
+            name="update_resource",
+            description="Update an existing resource in MODX.",
+            remarks="The resource must be available in the context with update permission. "
+                   "Only provided fields will be updated; omitted fields remain unchanged.",
+            parameters={
+                "id": ToolParameter(
+                    required=True,
+                    type="integer",
+                    description="ID of the resource to update"
+                ),
+                "pagetitle": ToolParameter(
+                    required=False,
+                    type="string",
+                    description="New page title",
+                    default=None
+                ),
+                "content": ToolParameter(
+                    required=False,
+                    type="string",
+                    description="New content",
+                    default=None
+                ),
+                "published": ToolParameter(
+                    required=False,
+                    type="boolean",
+                    description="Publication status",
+                    default=None
+                ),
+                "tvs": ToolParameter(
+                    required=False,
+                    type="object",
+                    description="Updated template variable values as {tv_name: value}",
+                    default={}
+                ),
+                "alias": ToolParameter(
+                    required=False,
+                    type="string",
+                    description="New URL alias",
+                    default=None
+                ),
+            }
+        )
+
+    async def handler(self, **kwargs) -> Dict[str, Any]:
+        """
+        Mettre à jour une ressource MODX.
+        
+        Returns:
+            Dict avec structure {success, code, data, message}
+        """
+        try:
+            # Extraire les paramètres
+            resource_id = kwargs.get("id")
+
+            # Validation basique
+            if not isinstance(resource_id, int) or resource_id <= 0:
+                return {
+                    "success": False,
+                    "code": 400,
+                    "data": [],
+                    "message": "id must be a positive integer"
+                }
+
+            # Préparer les données à mettre à jour (seulement les champs fournis)
+            resource_data = {"id": resource_id}
+
+            # Ajouter les champs optionnels s'ils sont fournis
+            if kwargs.get("pagetitle") is not None:
+                resource_data["pagetitle"] = kwargs.get("pagetitle")
+
+            if kwargs.get("content") is not None:
+                resource_data["content"] = kwargs.get("content")
+
+            if kwargs.get("published") is not None:
+                resource_data["published"] = kwargs.get("published")
+
+            if kwargs.get("alias") is not None:
+                resource_data["alias"] = kwargs.get("alias")
+
+            tvs = kwargs.get("tvs", {})
+            if tvs:
+                resource_data["tvs"] = tvs
+
+            # Vérifier qu'au moins un champ est à mettre à jour
+            if len(resource_data) == 1:  # Seulement l'id
+                return {
+                    "success": False,
+                    "code": 400,
+                    "data": [],
+                    "message": "At least one field must be provided for update"
+                }
+
+            # Appeler l'API MODX
+            logger.info(f"Updating resource: ID {resource_id}")
+            client = get_modx_client()
+            endpoint = settings.MODX_ENDPOINTS["resource"]["update"].format(id=resource_id)
+            response = client.put(endpoint, resource_data)
+
+            return {
+                "success": response.get("success", False),
+                "code": response.get("code", 500),
+                "data": response.get("data", []),
+                "message": response.get("message", "Resource update completed")
+            }
+
+        except MODXAPIError as e:
+            logger.error(f"MODX API error: {e.message}")
+            return {
+                "success": False,
+                "code": e.code,
+                "data": [],
+                "message": e.message
+            }
+        except ValidationError as e:
+            logger.error(f"Validation error: {e.message}")
+            return {
+                "success": False,
+                "code": e.code,
+                "data": [],
+                "message": e.message
+            }
+        except Exception as e:
+            logger.error(f"Unexpected error in update_resource: {str(e)}")
+            return {
+                "success": False,
+                "code": 500,
+                "data": [],
+                "message": f"Internal error: {str(e)}"
+            }
+
+
+# Instance globale de l'outil
+update_resource_tool = UpdateResourceTool()