create_resource.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. """
  2. -----------------------------------------------------------------------------------------
  3. INTERSEL - 4 cité d'Hauteville - 75010 PARIS
  4. RCS PARIS 488 379 660 - NAF 721Z
  5. File : tools/resource/create_resource.py
  6. Object : CreateResource tool for the MCP server
  7. -----------------------------------------------------------------------------------------
  8. Modifications :
  9. - 2026/01/27 - Damien Lugagne-Delpon - V1.0.0 - Creation
  10. -----------------------------------------------------------------------------------------
  11. @copyright : Intersel 2026
  12. @author : Damien Lugagne-Delpon - damien.lugagne-delpon@livinweb.fr
  13. @version : 1.0.0 (to be updated to the current_version of the developed software if file is touched)
  14. -----------------------------------------------------------------------------------------
  15. """
  16. import logging
  17. from typing import Dict, Any
  18. import asyncio
  19. from mcp_server.tools.tool_class import Tool
  20. from mcp_server.api.modx_client import get_modx_client
  21. from mcp_server.config import settings
  22. from mcp_server.core.constants import ModxType, actionType
  23. from mcp_server.core.permissions import check_permission
  24. from mcp_server.core.errors import (
  25. ValidationError,
  26. PermissionError,
  27. MODXAPIError,
  28. InternalError,
  29. )
  30. logger = logging.getLogger(__name__)
  31. class CreateResourceTool(Tool):
  32. """Outil pour créer une ressource MODX."""
  33. def __init__(self):
  34. """Initialiser l'outil CreateResource."""
  35. super().__init__(
  36. name="create_resource",
  37. description="Create a new resource in MODX with specified template and properties.",
  38. remarks="The template must be available in the context with read permission. "
  39. "Use get_template to understand template structure before creation.",
  40. parameters={
  41. "pagetitle": {
  42. "required":True,
  43. "type":"string",
  44. "description":"Page title of the resource"
  45. },
  46. "template": {
  47. "required":True,
  48. "type":"integer",
  49. "description":"Template ID to use for the resource"
  50. },
  51. "content": {
  52. "required":False,
  53. "type":"string",
  54. "description":"Main content of the resource",
  55. "default":""
  56. },
  57. "parent": {
  58. "required":False,
  59. "type":"integer",
  60. "description":"Parent resource ID (0 for root)",
  61. "default":0
  62. },
  63. "published": {
  64. "required":False,
  65. "type":"boolean",
  66. "description":"Publish the resource",
  67. "default":False
  68. },
  69. "tvs": {
  70. "required":False,
  71. "type":"object",
  72. "description":"Template variable values as {tv_name: value}",
  73. "default":{}
  74. },
  75. "alias": {
  76. "required":False,
  77. "type":"string",
  78. "description":"URL alias for the resource",
  79. "default":""
  80. },
  81. }
  82. )
  83. async def handler(self, **kwargs) -> Dict[str, Any]:
  84. """
  85. Créer une ressource MODX.
  86. Returns:
  87. Dict avec structure {success, code, data, message}
  88. """
  89. try:
  90. # Extraire les paramètres
  91. pagetitle = kwargs.get("pagetitle")
  92. template_id = kwargs.get("template")
  93. content = kwargs.get("content", "")
  94. parent = kwargs.get("parent", 0)
  95. published = kwargs.get("published", False)
  96. tvs = kwargs.get("tvs", {})
  97. alias = kwargs.get("alias", "")
  98. # Validation basique
  99. if not pagetitle or not isinstance(pagetitle, str):
  100. return {
  101. "success": False,
  102. "code": 400,
  103. "data": [],
  104. "message": "pagetitle is required and must be a string"
  105. }
  106. if not isinstance(template_id, int) or template_id <= 0:
  107. return {
  108. "success": False,
  109. "code": 400,
  110. "data": [],
  111. "message": "template must be a positive integer"
  112. }
  113. # Préparer les données pour l'API
  114. resource_data = {
  115. "pagetitle": pagetitle,
  116. "template": template_id,
  117. "content": content,
  118. "parent": parent,
  119. "published": published,
  120. }
  121. if alias:
  122. resource_data["alias"] = alias
  123. if tvs:
  124. resource_data["tvs"] = tvs
  125. # Appeler l'API MODX
  126. logger.info(f"Creating resource: {pagetitle}")
  127. client = get_modx_client()
  128. endpoint = settings.MODX_ENDPOINTS["resource"]["create"]
  129. response = client.post(endpoint, resource_data)
  130. # Ajouter la ressource créée au contexte
  131. if response.get("success") and "data" in response:
  132. created_resource = response["data"]
  133. if isinstance(created_resource, dict) and "id" in created_resource:
  134. # La ressource est créée avec droits read et update
  135. # Cela sera géré par le client MCP/l'agent
  136. logger.info(f"Resource created successfully: ID {created_resource['id']}")
  137. return {
  138. "success": response.get("success", False),
  139. "code": response.get("code", 500),
  140. "data": response.get("data", []),
  141. "message": response.get("message", "Resource creation completed")
  142. }
  143. except PermissionError as e:
  144. logger.warning(f"Permission denied: {e.message}")
  145. return {
  146. "success": False,
  147. "code": e.code,
  148. "data": [],
  149. "message": e.message
  150. }
  151. except MODXAPIError as e:
  152. logger.error(f"MODX API error: {e.message}")
  153. return {
  154. "success": False,
  155. "code": e.code,
  156. "data": [],
  157. "message": e.message
  158. }
  159. except ValidationError as e:
  160. logger.error(f"Validation error: {e.message}")
  161. return {
  162. "success": False,
  163. "code": e.code,
  164. "data": [],
  165. "message": e.message
  166. }
  167. except Exception as e:
  168. logger.error(f"Unexpected error in create_resource: {str(e)}")
  169. return {
  170. "success": False,
  171. "code": 500,
  172. "data": [],
  173. "message": f"Internal error: {str(e)}"
  174. }
  175. # Instance globale de l'outil
  176. create_resource_tool = CreateResourceTool()