resources_element.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. """Definition des ressources MCP (operations de lecture)."""
  2. from __future__ import annotations
  3. from typing import Any
  4. import httpx
  5. from ..services.client_rest import ClientRest, HTTPMethod
  6. _GET_RESOURCE_WHITELIST = {
  7. "id",
  8. "alias",
  9. "cacheable",
  10. "class_key",
  11. "context_key",
  12. "content",
  13. "content_type",
  14. "description",
  15. "hidemenu",
  16. "introtext",
  17. "isfolder",
  18. "link_attributes",
  19. "longtitle",
  20. "menuindex",
  21. "menutitle",
  22. "pagetitle",
  23. "parent",
  24. "published",
  25. "template",
  26. "uri",
  27. "full_uri",
  28. "imxcache",
  29. "templateVars",
  30. }
  31. _GET_RESOURCES_WHITELIST = {
  32. "id",
  33. "alias",
  34. "class_key",
  35. "content",
  36. "description",
  37. "isfolder",
  38. "pagetitle",
  39. "parent",
  40. "published",
  41. "template",
  42. "uri",
  43. }
  44. def _filter_dict(data: dict[str, Any], whitelist: set[str]) -> dict[str, Any]:
  45. return {key: value for key, value in data.items() if key in whitelist}
  46. def _filter_list(items: list[Any], whitelist: set[str]) -> list[Any]:
  47. filtered: list[Any] = []
  48. for item in items:
  49. if isinstance(item, dict):
  50. filtered.append(_filter_dict(item, whitelist))
  51. else:
  52. filtered.append(item)
  53. return filtered
  54. def _unwrap_data(response: Any) -> Any:
  55. """Extrait le payload utile des réponses LWE {code,message,data}."""
  56. if isinstance(response, dict) and "data" in response:
  57. return response["data"]
  58. return response
  59. def register_element_resources(mcp_server: Any, client_rest: ClientRest) -> None:
  60. """Enregistre les ressources de lecture du serveur MCP."""
  61. @mcp_server.resource("modx://resource/{id}",
  62. mime_type="application/json",
  63. description="Récupérer une ressource MODX.",
  64. )
  65. def get_resource(id: str) -> dict[str, Any]:
  66. try:
  67. response = client_rest.execute(
  68. method=HTTPMethod.GET,
  69. endpoint=f"/rest/tools/resource/{id}",
  70. params={"showUnpublished": 1},
  71. )
  72. except httpx.HTTPStatusError:
  73. # Certains serveurs REST LWE retournent 500 avec ce parametre.
  74. response = client_rest.execute(
  75. method=HTTPMethod.GET,
  76. endpoint=f"/rest/tools/resource/{id}",
  77. )
  78. data = _unwrap_data(response)
  79. if isinstance(data, dict):
  80. return _filter_dict(data, _GET_RESOURCE_WHITELIST)
  81. return {"data": response}
  82. @mcp_server.resource("modx://resources/{id}",
  83. mime_type="application/json",
  84. description="Récupérer une liste de ressources MODX enfants niveau 1 d'un parent donné.",
  85. )
  86. def get_resources(id: str) -> dict[str, Any]:
  87. try:
  88. response = client_rest.execute(
  89. method=HTTPMethod.GET,
  90. endpoint=f"/rest/tools/getresources/{id}",
  91. params={"depth": -1, "includedTv": 0, "showUnpublished": 1},
  92. )
  93. except httpx.HTTPStatusError:
  94. response = client_rest.execute(
  95. method=HTTPMethod.GET,
  96. endpoint=f"/rest/tools/getresources/{id}",
  97. )
  98. data = _unwrap_data(response)
  99. if isinstance(data, list):
  100. return {"items": _filter_list(data, _GET_RESOURCES_WHITELIST)}
  101. if isinstance(data, dict):
  102. if "items" in data and isinstance(data["items"], list):
  103. return {
  104. **data,
  105. "items": _filter_list(data["items"], _GET_RESOURCES_WHITELIST),
  106. }
  107. return _filter_dict(data, _GET_RESOURCES_WHITELIST)
  108. return {"data": response}
  109. @mcp_server.resource("modx://template/{id}",
  110. mime_type="application/json",
  111. description="Récupérer un template MODX et ses variables de modèle (TV) liées.",
  112. )
  113. def get_template(id: str) -> dict[str, Any]:
  114. response = client_rest.execute(
  115. method=HTTPMethod.GET,
  116. endpoint=f"/rest/tools/template/{id}",
  117. )
  118. data = _unwrap_data(response)
  119. return data if isinstance(data, dict) else {"data": data}
  120. @mcp_server.resource("modx://templates",
  121. mime_type="application/json",
  122. description="Récupérer une liste de templates MODX.",
  123. )
  124. def get_templates() -> dict[str, Any]:
  125. response = client_rest.execute(
  126. method=HTTPMethod.GET,
  127. endpoint="/rest/tools/templates",
  128. )
  129. data = _unwrap_data(response)
  130. return {"items": data} if isinstance(data, list) else {"data": data}
  131. @mcp_server.resource("modx://tv/{id}",
  132. mime_type="application/json",
  133. description="Récupérer une variable de modèle (TV) spécifique.",
  134. )
  135. def get_tv(id: str) -> dict[str, Any]:
  136. response = client_rest.execute(
  137. method=HTTPMethod.GET,
  138. endpoint=f"/rest/tools/tv/{id}",
  139. )
  140. data = _unwrap_data(response)
  141. return data if isinstance(data, dict) else {"data": data}
  142. @mcp_server.resource("modx://category/{id}",
  143. mime_type="application/json",
  144. description="Récupérer une catégorie MODX.",
  145. )
  146. def get_category(id: str) -> dict[str, Any]:
  147. response = client_rest.execute(
  148. method=HTTPMethod.GET,
  149. endpoint=f"/rest/tools/category/{id}",
  150. )
  151. data = _unwrap_data(response)
  152. return data if isinstance(data, dict) else {"data": data}
  153. @mcp_server.resource("modx://categories",
  154. mime_type="application/json",
  155. description="Récupérer une liste de catégories MODX.",
  156. )
  157. def get_categories() -> dict[str, Any]:
  158. try:
  159. response = client_rest.execute(
  160. method=HTTPMethod.GET,
  161. endpoint="/rest/tools/categories",
  162. )
  163. data = _unwrap_data(response)
  164. return {"items": data} if isinstance(data, list) else {"data": data}
  165. except httpx.HTTPStatusError:
  166. # Endpoint non expose sur certains serveurs LWE.
  167. return {
  168. "items": [],
  169. "warning": "Endpoint /rest/tools/categories indisponible sur ce serveur.",
  170. }