Răsfoiți Sursa

initialize mcp server

Khanh Nguyen 5 luni în urmă
comite
237dd86418

+ 9 - 0
.cursorignore

@@ -0,0 +1,9 @@
+.env
+.venv/
+
+#mcp_*.md
+
+#src/
+
+README.md
+

+ 3 - 0
.env.example

@@ -0,0 +1,3 @@
+BASE_URL=https://api.site.local
+LWE_TOKEN=replace_with_token
+PHPSESSID=replace_with_phpsessid

+ 16 - 0
.gitignore

@@ -0,0 +1,16 @@
+.venv/
+__pycache__/
+*.pyc
+.env
+
+mcp_*.md
+
+htmlcov/
+.coverage
+.coverage.*
+coverage.xml
+.pytest_cache/
+
+.cursor/
+
+uv.lock

+ 25 - 0
pyproject.toml

@@ -0,0 +1,25 @@
+[project]
+name = "lw-mcp-server"
+version = "0.1.0"
+description = "MCP server for Livinweb Engine REST tools"
+readme = "README.md"
+requires-python = ">=3.13"
+dependencies = [
+  "httpx>=0.28.1",
+  "mcp[cli]>=1.2.7",
+  "python-dotenv>=1.2.2",
+]
+
+[project.scripts]
+lw-mcp-server = "src.main:main"
+
+[dependency-groups]
+dev = [
+    "pytest>=8.0",
+    "pytest-cov>=7.1.0",
+]
+
+[tool.pytest.ini_options]
+testpaths = ["tests"]
+pythonpath = ["."]
+

+ 1 - 0
src/__init__.py

@@ -0,0 +1 @@
+"""LW MCP Server package."""

+ 1 - 0
src/config/__init__.py

@@ -0,0 +1 @@
+"""Configuration package."""

+ 49 - 0
src/config/initialization.py

@@ -0,0 +1,49 @@
+"""Initialisation et validation de la configuration globale."""
+
+from __future__ import annotations
+
+import os
+from dataclasses import dataclass
+from functools import lru_cache
+
+from dotenv import load_dotenv
+
+
+@dataclass(frozen=True)
+class Settings:
+    """Configuration runtime chargee depuis les variables d'environnement."""
+
+    base_url: str
+    lwe_token: str
+    phpsessid: str
+    timeout_seconds: float = 10.0
+
+
+class InitializationError(RuntimeError):
+    """Erreur critique de configuration."""
+
+
+@lru_cache(maxsize=1)
+def get_settings() -> Settings:
+    """Charge le .env et valide la presence des secrets requis."""
+    load_dotenv()
+
+    base_url = (os.getenv("BASE_URL") or "").strip().rstrip("/")
+    lwe_token = (os.getenv("LWE_TOKEN") or "").strip()
+    phpsessid = (os.getenv("PHPSESSID") or "").strip()
+
+    missing = [
+        name
+        for name, value in (
+            ("BASE_URL", base_url),
+            ("LWE_TOKEN", lwe_token),
+            ("PHPSESSID", phpsessid),
+        )
+        if not value
+    ]
+    if missing:
+        raise InitializationError(
+            f"Variables d'environnement manquantes: {', '.join(missing)}"
+        )
+
+    return Settings(base_url=base_url, lwe_token=lwe_token, phpsessid=phpsessid)

+ 19 - 0
src/main.py

@@ -0,0 +1,19 @@
+"""Point d'entree du serveur MCP LW Copilot."""
+
+from __future__ import annotations
+
+from src.config.initialization import get_settings
+from src.server_mcp.server import build_server
+from src.services.client_rest import ClientRest
+
+
+
+def main() -> None:
+    """Valide la configuration puis lance le serveur MCP via stdio."""
+    get_settings()
+    server = build_server(ClientRest())
+    server.run(transport="stdio")
+
+
+if __name__ == "__main__":
+    main()

+ 1 - 0
src/server_mcp/__init__.py

@@ -0,0 +1 @@
+"""MCP package."""

+ 194 - 0
src/server_mcp/resources.py

@@ -0,0 +1,194 @@
+"""Definition des ressources MCP (operations de lecture)."""
+
+from __future__ import annotations
+
+from typing import Any
+
+import httpx
+
+from ..services.client_rest import ClientRest, HTTPMethod
+
+
+_GET_RESOURCE_WHITELIST = {
+    "id",
+    "alias",
+    "cacheable",
+    "class_key",
+    "context_key",
+    "content",
+    "content_type",
+    "description",
+    "hidemenu",
+    "introtext",
+    "isfolder",
+    "link_attributes",
+    "longtitle",
+    "menuindex",
+    "menutitle",
+    "pagetitle",
+    "parent",
+    "published",
+    "template",
+    "uri",
+    "full_uri",
+    "imxcache",
+    "templateVars",
+}
+
+_GET_RESOURCES_WHITELIST = {
+    "id",
+    "alias",
+    "class_key",
+    "content",
+    "description",
+    "isfolder",
+    "pagetitle",
+    "parent",
+    "published",
+    "template",
+    "uri",
+}
+
+
+def _filter_dict(data: dict[str, Any], whitelist: set[str]) -> dict[str, Any]:
+    return {key: value for key, value in data.items() if key in whitelist}
+
+
+def _filter_list(items: list[Any], whitelist: set[str]) -> list[Any]:
+    filtered: list[Any] = []
+    for item in items:
+        if isinstance(item, dict):
+            filtered.append(_filter_dict(item, whitelist))
+        else:
+            filtered.append(item)
+    return filtered
+
+
+def _unwrap_data(response: Any) -> Any:
+    """Extrait le payload utile des réponses LWE {code,message,data}."""
+    if isinstance(response, dict) and "data" in response:
+        return response["data"]
+    return response
+
+
+def register_resources(mcp_server: Any, client_rest: ClientRest) -> None:
+    """Enregistre les ressources de lecture du serveur MCP."""
+
+    @mcp_server.resource("modx://resource/{id}", 
+        mime_type="application/json",
+        description="Récupérer une ressource MODX.",
+    )
+    def get_resource(id: str) -> dict[str, Any]:
+        try:
+            response = client_rest.execute(
+                method=HTTPMethod.GET,
+                endpoint=f"/rest/tools/resource/{id}",
+                params={"showUnpublished": 1},
+            )
+        except httpx.HTTPStatusError:
+            # Certains serveurs REST LWE retournent 500 avec ce parametre.
+            response = client_rest.execute(
+                method=HTTPMethod.GET,
+                endpoint=f"/rest/tools/resource/{id}",
+            )
+
+        data = _unwrap_data(response)
+        if isinstance(data, dict):
+            return _filter_dict(data, _GET_RESOURCE_WHITELIST)
+        return {"data": response}
+
+    @mcp_server.resource("modx://resources/{id}", 
+        mime_type="application/json",
+        description="Récupérer une liste de ressources MODX enfants niveau 1 d'un parent donné.",
+    )
+    def get_resources(id: str) -> dict[str, Any]:
+        try:
+            response = client_rest.execute(
+                method=HTTPMethod.GET,
+                endpoint=f"/rest/tools/getresources/{id}",
+                params={"depth": -1, "includedTv": 0, "showUnpublished": 1},
+            )
+        except httpx.HTTPStatusError:
+            response = client_rest.execute(
+                method=HTTPMethod.GET,
+                endpoint=f"/rest/tools/getresources/{id}",
+            )
+
+        data = _unwrap_data(response)
+        if isinstance(data, list):
+            return {"items": _filter_list(data, _GET_RESOURCES_WHITELIST)}
+        if isinstance(data, dict):
+            if "items" in data and isinstance(data["items"], list):
+                return {
+                    **data,
+                    "items": _filter_list(data["items"], _GET_RESOURCES_WHITELIST),
+                }
+            return _filter_dict(data, _GET_RESOURCES_WHITELIST)
+        return {"data": response}
+
+    @mcp_server.resource("modx://template/{id}", 
+        mime_type="application/json",
+        description="Récupérer un template MODX et ses variables de modèle (TV) liées.",
+    )
+    def get_template(id: str) -> dict[str, Any]:
+        response = client_rest.execute(
+            method=HTTPMethod.GET,
+            endpoint=f"/rest/tools/template/{id}",
+        )
+        data = _unwrap_data(response)
+        return data if isinstance(data, dict) else {"data": data}
+
+    @mcp_server.resource("modx://templates", 
+        mime_type="application/json",
+        description="Récupérer une liste de templates MODX.",
+    )
+    def get_templates() -> dict[str, Any]:
+        response = client_rest.execute(
+            method=HTTPMethod.GET,
+            endpoint="/rest/tools/templates",
+        )
+        data = _unwrap_data(response)
+        return {"items": data} if isinstance(data, list) else {"data": data}
+
+    @mcp_server.resource("modx://tv/{id}", 
+        mime_type="application/json",
+        description="Récupérer une variable de modèle (TV) spécifique.",
+    )
+    def get_tv(id: str) -> dict[str, Any]:
+        response = client_rest.execute(
+            method=HTTPMethod.GET,
+            endpoint=f"/rest/tools/tv/{id}",
+        )
+        data = _unwrap_data(response)
+        return data if isinstance(data, dict) else {"data": data}
+
+    @mcp_server.resource("modx://category/{id}", 
+        mime_type="application/json",
+        description="Récupérer une catégorie MODX.",
+    )
+    def get_category(id: str) -> dict[str, Any]:
+        response = client_rest.execute(
+            method=HTTPMethod.GET,
+            endpoint=f"/rest/tools/category/{id}",
+        )
+        data = _unwrap_data(response)
+        return data if isinstance(data, dict) else {"data": data}
+
+    @mcp_server.resource("modx://categories", 
+        mime_type="application/json",
+        description="Récupérer une liste de catégories MODX.",
+    )
+    def get_categories() -> dict[str, Any]:
+        try:
+            response = client_rest.execute(
+                method=HTTPMethod.GET,
+                endpoint="/rest/tools/categories",
+            )
+            data = _unwrap_data(response)
+            return {"items": data} if isinstance(data, list) else {"data": data}
+        except httpx.HTTPStatusError:
+            # Endpoint non expose sur certains serveurs LWE.
+            return {
+                "items": [],
+                "warning": "Endpoint /rest/tools/categories indisponible sur ce serveur.",
+            }

+ 17 - 0
src/server_mcp/server.py

@@ -0,0 +1,17 @@
+"""Assemblage du serveur MCP."""
+
+from __future__ import annotations
+
+from mcp.server.fastmcp import FastMCP
+
+from .resources import register_resources
+from .tools import register_tools
+from src.services.client_rest import ClientRest
+
+
+def build_server(client_rest: ClientRest) -> FastMCP:
+    """Construit l'instance MCP et enregistre ses capacités."""
+    server = FastMCP("lw-copilot-mcp-server")
+    register_tools(server, client_rest)
+    register_resources(server, client_rest)
+    return server

+ 485 - 0
src/server_mcp/tools.py

@@ -0,0 +1,485 @@
+"""Definition des outils MCP (operations d'ecriture)."""
+
+from __future__ import annotations
+
+from typing import Annotated, Any
+
+from mcp.types import ToolAnnotations
+
+from ..services.client_rest import ClientRest, HTTPMethod
+
+_WRITE_ONLY = ToolAnnotations(readOnlyHint=False, destructiveHint=False)
+_WRITE_DESTRUCTIVE = ToolAnnotations(readOnlyHint=False, destructiveHint=True)
+_WRITE_IDEMPOTENT = ToolAnnotations(
+    readOnlyHint=False, destructiveHint=True, idempotentHint=True
+)
+
+# --- createResource / updateResource ---
+
+Pagetitle = Annotated[str, "page title of the resource"]
+PagetitleOpt = Annotated[str | None, "page title of the resource"]
+Alias = Annotated[str | None, "alias that will be used in the URL (default: pagetitle)"]
+Cacheable = Annotated[bool | None, "tells if the resource is cacheable"]
+Content = Annotated[str | None, "content of the resource"]
+ContextKey = Annotated[str | None, "context of the resource (default: web)"]
+Deleted = Annotated[bool | None, "tells if the resource is deleted or not"]
+Description = Annotated[str | None, "description of the resource"]
+Hidemenu = Annotated[
+    bool | None, "tells if the resource should be hidden from menu display"
+]
+Introtext = Annotated[str | None, "introduction of the resource"]
+ResourceIdDuplicate = Annotated[int | None, "a resource id to duplicate"]
+ResourceId = Annotated[int, "a resource id to modify"]
+ResourceIdDelete = Annotated[int, "resource id to delete"]
+Isfolder = Annotated[
+    bool | None, "tells if the resource is to be considered as a folder of resources"
+]
+LinkAttributes = Annotated[
+    str | None, "link attributes that may be used in menu or links"
+]
+Longtitle = Annotated[str | None, "long title of the resource"]
+Menuindex = Annotated[int | None, "order index of the resource in a menu"]
+Menutitle = Annotated[
+    str | None, "title of the resource if displayed in a menu tree"
+]
+PagetitleUnique = Annotated[
+    str | None,
+    "if set, modify pagetitle to get a unique pagetitle and alias "
+    "('1'/'uniqueid' adds uniqid, 'date' adds timestamp; default: 0)",
+]
+Parent = Annotated[int | None, "parent of the resource (default: 0, root)"]
+Published = Annotated[bool | None, "tells if the resource is published"]
+PubDate = Annotated[
+    str | None, "date in the future that the resource should be published"
+]
+Searchable = Annotated[bool | None, "tells if the resource may be found in a search process"]
+TemplateId = Annotated[
+    int | None,
+    "resource id of the template (default: default_template setting, e.g. 12)",
+]
+UnpubDate = Annotated[str | None, "date when the resource should be unpublished"]
+TemplateVars = Annotated[
+    dict[str, Any] | list[Any] | str | None,
+    "json list of template variables content",
+]
+ResourceGroups = Annotated[
+    dict[str, Any] | list[Any] | str | None,
+    "comma-separated list of resource group ids, or JSON "
+    '[{"id":"<resource id>","access":"<0|1>"}]',
+]
+ResourceGroupsUpdate = Annotated[
+    dict[str, Any] | list[Any] | str | None,
+    "resource groups to add; to remove a group send JSON with access=0",
+]
+MandatoryParents = Annotated[
+    int | str | list[int] | None,
+    "comma-separated list of resource ids giving the authorized parents",
+]
+ContentType = Annotated[str | None, "mime type of the resource content (default: text/html)"]
+Syncsite = Annotated[bool | None, "if set, it will refresh the resource cache (default: 0)"]
+MandatoryParent = Annotated[
+    int | None,
+    "set the mandatory parent of the id to verify the resource id is appropriate",
+]
+
+# --- createTemplate / updateTemplate ---
+
+TemplateName = Annotated[str, "name of the template"]
+TemplateNameOpt = Annotated[str | None, "name of the template"]
+TemplateIdMandatory = Annotated[int, "id of the template"]
+TemplateDescription = Annotated[str | None, "description of the template"]
+Category = Annotated[str | None, "category the element belongs in"]
+IsStatic = Annotated[
+    bool | None,
+    "if true, the element source is stored in an external file (default: false)",
+]
+StaticFile = Annotated[
+    str | None,
+    "if isStatic true, path of the external file where the element source is stored",
+]
+MediaSourceForStaticFile = Annotated[
+    str | None,
+    "media source base path for static element file (default: Filesystem)",
+]
+TemplateContent = Annotated[str | None, "template code (HTML)"]
+LockTemplate = Annotated[
+    bool | None,
+    "lock template for editing; requires edit_locked attribute (default: false)",
+]
+TemplateVarsAccess = Annotated[
+    dict[str, Any] | list[Any] | str | None,
+    "JSON list that indicates the access of template vars (default: {})",
+]
+
+# --- createTv / updateTv ---
+
+TvName = Annotated[str, "name of the template variable"]
+TvNameOpt = Annotated[str | None, "name of the TV"]
+TvId = Annotated[int, "id of the TV"]
+TvDescription = Annotated[str | None, "description of the template variable"]
+TvCaption = Annotated[
+    str | None,
+    "text displayed beside the TV when editing it in a Resource",
+]
+TvCategory = Annotated[str | None, "category the TV belongs in"]
+TvType = Annotated[str | None, "the type of TV"]
+TvElement = Annotated[
+    str | None,
+    "list of options for TV; only use if the type of TV is listbox",
+]
+TvDefaultText = Annotated[
+    str | None,
+    "default option for TV; only use if the type of TV is listbox",
+]
+TvInputPropeties = Annotated[
+    str | None, "JSON list of the input properties of the TV"
+]
+TvTemplates = Annotated[
+    dict[str, Any] | list[Any] | str | None,
+    "JSON list that indicates the access of templates (default: {})",
+]
+
+# --- createCategory / updateCategory ---
+
+CategoryName = Annotated[str, "name of the category"]
+CategoryNameOpt = Annotated[str | None, "name of the category"]
+CategoryId = Annotated[int, "id of the category"]
+CategoryParent = Annotated[int | None, "parent id of the category (default: 0)"]
+
+
+def _omit_none(**kwargs: Any) -> dict[str, Any]:
+    return {key: value for key, value in kwargs.items() if value is not None}
+
+
+def register_tools(mcp_server: Any, client_rest: ClientRest) -> None:
+    """Enregistre les outils d'ecriture du serveur MCP."""
+
+    @mcp_server.tool(
+        description="Creer une ressource MODX",
+        annotations=_WRITE_ONLY,
+    )
+    def createResource(
+        pagetitle: Pagetitle,
+        alias: Alias = None,
+        cacheable: Cacheable = None,
+        content: Content = None,
+        context_key: ContextKey = None,
+        deleted: Deleted = None,
+        description: Description = None,
+        hidemenu: Hidemenu = None,
+        introtext: Introtext = None,
+        id: ResourceIdDuplicate = None,
+        isfolder: Isfolder = None,
+        link_attributes: LinkAttributes = None,
+        longtitle: Longtitle = None,
+        menuindex: Menuindex = None,
+        menutitle: Menutitle = None,
+        pagetitleUnique: PagetitleUnique = None,
+        parent: Parent = None,
+        published: Published = None,
+        pub_date: PubDate = None,
+        searchable: Searchable = None,
+        template: TemplateId = None,
+        unpub_date: UnpubDate = None,
+        templateVars: TemplateVars = None,
+        resourceGroups: ResourceGroups = None,
+        mandatoryParents: MandatoryParents = None,
+        content_type: ContentType = None,
+        syncsite: Syncsite = None,
+    ) -> dict[str, Any]:
+        return client_rest.execute(
+            method=HTTPMethod.POST,
+            endpoint="/rest/tools/resource",
+            params=_omit_none(
+                pagetitle=pagetitle,
+                alias=alias,
+                cacheable=cacheable,
+                content=content,
+                context_key=context_key,
+                deleted=deleted,
+                description=description,
+                hidemenu=hidemenu,
+                introtext=introtext,
+                id=id,
+                isfolder=isfolder,
+                link_attributes=link_attributes,
+                longtitle=longtitle,
+                menuindex=menuindex,
+                menutitle=menutitle,
+                pagetitleUnique=pagetitleUnique,
+                parent=parent,
+                published=published,
+                pub_date=pub_date,
+                searchable=searchable,
+                template=template,
+                unpub_date=unpub_date,
+                templateVars=templateVars,
+                resourceGroups=resourceGroups,
+                mandatoryParents=mandatoryParents,
+                content_type=content_type,
+                syncsite=syncsite,
+            ),
+        )
+
+    @mcp_server.tool(
+        description=(
+            "Mettre a jour une ressource MODX. "
+            "Attention: les nouveaux parametres ecraseront les anciens, "
+            "meme s'ils ne sont pas renseignes; faire un get_resource au prealable."
+        ),
+        annotations=_WRITE_IDEMPOTENT,
+    )
+    def updateResource(
+        id: ResourceId,
+        alias: Alias = None,
+        cacheable: Cacheable = None,
+        content: Content = None,
+        deleted: Deleted = None,
+        description: Description = None,
+        hidemenu: Hidemenu = None,
+        introtext: Introtext = None,
+        isfolder: Isfolder = None,
+        link_attributes: LinkAttributes = None,
+        longtitle: Longtitle = None,
+        menuindex: Menuindex = None,
+        menutitle: Menutitle = None,
+        pagetitle: PagetitleOpt = None,
+        parent: Parent = None,
+        published: Published = None,
+        pub_date: PubDate = None,
+        resourceGroups: ResourceGroupsUpdate = None,
+        searchable: Searchable = None,
+        template: TemplateId = None,
+        templateVars: TemplateVars = None,
+        unpub_date: UnpubDate = None,
+        syncsite: Syncsite = None,
+    ) -> dict[str, Any]:
+        return client_rest.execute(
+            method=HTTPMethod.PUT,
+            endpoint="/rest/tools/resource",
+            params=_omit_none(
+                id=id,
+                alias=alias,
+                cacheable=cacheable,
+                content=content,
+                deleted=deleted,
+                description=description,
+                hidemenu=hidemenu,
+                introtext=introtext,
+                isfolder=isfolder,
+                link_attributes=link_attributes,
+                longtitle=longtitle,
+                menuindex=menuindex,
+                menutitle=menutitle,
+                pagetitle=pagetitle,
+                parent=parent,
+                published=published,
+                pub_date=pub_date,
+                resourceGroups=resourceGroups,
+                searchable=searchable,
+                template=template,
+                templateVars=templateVars,
+                unpub_date=unpub_date,
+                syncsite=syncsite,
+            ),
+        )
+
+    @mcp_server.tool(
+        description="Supprimer une ressource MODX",
+        annotations=_WRITE_DESTRUCTIVE,
+    )
+    def deleteResource(
+        id: ResourceIdDelete,
+        mandatoryParent: MandatoryParent = None,
+        syncsite: Syncsite = None,
+    ) -> dict[str, Any]:
+        return client_rest.execute(
+            method=HTTPMethod.DELETE,
+            endpoint="/rest/tools/resource",
+            params=_omit_none(
+                id=id,
+                mandatoryParent=mandatoryParent,
+                syncsite=syncsite,
+            ),
+        )
+
+    @mcp_server.tool(
+        description="Creer un template MODX",
+        annotations=_WRITE_ONLY,
+    )
+    def createTemplate(
+        name: TemplateName,
+        description: TemplateDescription = None,
+        category: Category = None,
+        isStatic: IsStatic = None,
+        staticFile: StaticFile = None,
+        mediaSourceForStaticFile: MediaSourceForStaticFile = None,
+        content: TemplateContent = None,
+        lockTemplate: LockTemplate = None,
+        templateVars: TemplateVarsAccess = None,
+    ) -> dict[str, Any]:
+        return client_rest.execute(
+            method=HTTPMethod.POST,
+            endpoint="/rest/tools/template",
+            params=_omit_none(
+                name=name,
+                description=description,
+                category=category,
+                isStatic=isStatic,
+                staticFile=staticFile,
+                mediaSourceForStaticFile=mediaSourceForStaticFile,
+                content=content,
+                lockTemplate=lockTemplate,
+                templateVars=templateVars,
+            ),
+        )
+
+    @mcp_server.tool(
+        description=(
+            "Mettre a jour un template MODX. "
+            "Attention: les nouveaux parametres ecraseront les anciens; "
+            "faire un get_template au prealable."
+        ),
+        annotations=_WRITE_IDEMPOTENT,
+    )
+    def updateTemplate(
+        id: TemplateIdMandatory,
+        name: TemplateNameOpt = None,
+        description: TemplateDescription = None,
+        category: Category = None,
+        isStatic: IsStatic = None,
+        staticFile: StaticFile = None,
+        mediaSourceForStaticFile: MediaSourceForStaticFile = None,
+        content: TemplateContent = None,
+        lockTemplate: LockTemplate = None,
+        templateVars: TemplateVarsAccess = None,
+    ) -> dict[str, Any]:
+        return client_rest.execute(
+            method=HTTPMethod.PUT,
+            endpoint="/rest/tools/template",
+            params=_omit_none(
+                id=id,
+                name=name,
+                description=description,
+                category=category,
+                isStatic=isStatic,
+                staticFile=staticFile,
+                mediaSourceForStaticFile=mediaSourceForStaticFile,
+                content=content,
+                lockTemplate=lockTemplate,
+                templateVars=templateVars,
+            ),
+        )
+
+    @mcp_server.tool(
+        description="Creer une template variable MODX",
+        annotations=_WRITE_ONLY,
+    )
+    def createTv(
+        name: TvName,
+        description: TvDescription = None,
+        caption: TvCaption = None,
+        category: TvCategory = None,
+        type: TvType = None,
+        element: TvElement = None,
+        defaultText: TvDefaultText = None,
+        lockTemplate: LockTemplate = None,
+        inputPropeties: TvInputPropeties = None,
+        isStatic: IsStatic = None,
+        staticFile: StaticFile = None,
+        templates: TvTemplates = None,
+    ) -> dict[str, Any]:
+        return client_rest.execute(
+            method=HTTPMethod.POST,
+            endpoint="/rest/tools/tv",
+            params=_omit_none(
+                name=name,
+                description=description,
+                caption=caption,
+                category=category,
+                type=type,
+                element=element,
+                defaultText=defaultText,
+                lockTemplate=lockTemplate,
+                inputPropeties=inputPropeties,
+                isStatic=isStatic,
+                staticFile=staticFile,
+                templates=templates,
+            ),
+        )
+
+    @mcp_server.tool(
+        description=(
+            "Mettre a jour une template variable MODX. "
+            "Attention: les nouveaux parametres ecraseront les anciens; "
+            "faire un get_tv au prealable."
+        ),
+        annotations=_WRITE_IDEMPOTENT,
+    )
+    def updateTv(
+        id: TvId,
+        name: TvNameOpt = None,
+        description: TvDescription = None,
+        caption: TvCaption = None,
+        category: TvCategory = None,
+        type: TvType = None,
+        element: TvElement = None,
+        defaultText: TvDefaultText = None,
+        lockTemplate: LockTemplate = None,
+        inputPropeties: TvInputPropeties = None,
+        isStatic: IsStatic = None,
+        staticFile: StaticFile = None,
+        templates: TvTemplates = None,
+    ) -> dict[str, Any]:
+        return client_rest.execute(
+            method=HTTPMethod.PUT,
+            endpoint="/rest/tools/tv",
+            params=_omit_none(
+                id=id,
+                name=name,
+                description=description,
+                caption=caption,
+                category=category,
+                type=type,
+                element=element,
+                defaultText=defaultText,
+                lockTemplate=lockTemplate,
+                inputPropeties=inputPropeties,
+                isStatic=isStatic,
+                staticFile=staticFile,
+                templates=templates,
+            ),
+        )
+
+    @mcp_server.tool(
+        description="Creer une categorie MODX",
+        annotations=_WRITE_ONLY,
+    )
+    def createCategory(
+        category: CategoryName,
+        parent: CategoryParent = None,
+    ) -> dict[str, Any]:
+        return client_rest.execute(
+            method=HTTPMethod.POST,
+            endpoint="/rest/tools/category",
+            params=_omit_none(category=category, parent=parent),
+        )
+
+    @mcp_server.tool(
+        description=(
+            "Mettre a jour une categorie MODX. "
+            "Attention: les nouveaux parametres ecraseront les anciens; "
+            "faire un get_category au prealable."
+        ),
+        annotations=_WRITE_IDEMPOTENT,
+    )
+    def updateCategory(
+        id: CategoryId,
+        category: CategoryNameOpt = None,
+        parent: CategoryParent = None,
+    ) -> dict[str, Any]:
+        return client_rest.execute(
+            method=HTTPMethod.PUT,
+            endpoint="/rest/tools/category",
+            params=_omit_none(id=id, category=category, parent=parent),
+        )

+ 1 - 0
src/services/__init__.py

@@ -0,0 +1 @@
+"""Services package."""

+ 64 - 0
src/services/client_rest.py

@@ -0,0 +1,64 @@
+"""Client REST synchrone pour les appels LWE."""
+
+from __future__ import annotations
+
+from enum import StrEnum
+from typing import Any
+
+import httpx
+
+from src.config.initialization import Settings, get_settings
+
+class HTTPMethod(StrEnum):
+    GET = "GET"
+    POST = "POST"
+    PUT = "PUT"
+    DELETE = "DELETE"
+
+
+class ClientRest:
+    """Couche transport centralisee pour l'API distante."""
+
+    def __init__(self, settings: Settings | None = None) -> None:
+        self.settings = settings or get_settings()
+        self.headers = {
+            "Authorization": self.settings.lwe_token,
+            "Cookie": f"PHPSESSID={self.settings.phpsessid}",
+            "Accept": "application/json",
+        }
+
+    def execute(
+        self, 
+        method: HTTPMethod, 
+        endpoint: str, 
+        params: dict[str, Any] | None = None,
+        json: dict[str, Any] | None = None
+    ) -> dict[str, Any]:
+        """Execute une requete HTTP et retourne la reponse JSON brute."""
+        url = self._build_url(endpoint)
+        params = params or {}
+        headers = self.headers.copy()
+
+        if json:
+            headers["Content-Type"] = "application/json"
+
+        try:
+            with httpx.Client(timeout=self.settings.timeout_seconds) as client:
+                if method == HTTPMethod.GET:
+                    response = client.get(url, headers=headers, params=params)
+                elif method == HTTPMethod.POST:
+                    response = client.post(url, headers=headers, json=json)
+                elif method == HTTPMethod.PUT:
+                    response = client.put(url, headers=headers, json=json)
+                elif method == HTTPMethod.DELETE:
+                    response = client.delete(url, headers=headers)
+                else:
+                    raise ValueError(f"Methode HTTP non supportee: {method}")
+            response.raise_for_status()
+            return response.json()
+        except httpx.TimeoutException as e:
+            raise TimeoutError(f"Timeout lors de l'exécution de la requête: {e}") from e
+
+    def _build_url(self, endpoint: str) -> str:
+        endpoint = endpoint if endpoint.startswith("/") else f"/{endpoint}"
+        return f"{self.settings.base_url}{endpoint}"