Ver Fonte

update tool parametres name

Khanh Nguyen há 4 meses atrás
pai
commit
d28ef36684

+ 1 - 1
src/server_mcp/resources_element.py

@@ -106,7 +106,7 @@ def register_element_resources(mcp_server: Any, client_rest: ClientRest) -> None
             response = client_rest.execute(
                 method=HTTPMethod.GET,
                 endpoint=f"/rest/tools/getresources/{id}",
-                params={"depth": -1, "includedTv": 0, "showUnpublished": 1},
+                params={"depth": -1, "includeTVs": 0, "showUnpublished": 1},
             )
         except httpx.HTTPStatusError:
             response = client_rest.execute(

+ 108 - 38
src/server_mcp/tools_element.py

@@ -2,7 +2,9 @@
 
 from __future__ import annotations
 
+import json
 from typing import Annotated, Any
+from urllib.parse import urlparse
 
 from pydantic import Field
 
@@ -73,7 +75,7 @@ TemplateName = Annotated[str, Field(description="name of the template")]
 TemplateNameOpt = Annotated[str | None, Field(default=None, description="name of the template")]
 TemplateIdMandatory = Annotated[int, Field(description="id of the template")]
 TemplateDescription = Annotated[str | None, Field(default=None, description="description of the template")]
-Category = Annotated[str | None, Field(default=None, description="category the element belongs in")]
+Category = Annotated[int | None, Field(default=None, description="category id the element belongs in")]
 IsStatic = Annotated[
     bool | None, 
     Field(default=None, description="if true, the element source is stored in an external file (default: false)")
@@ -83,13 +85,17 @@ StaticFile = Annotated[
     Field(default=None, description="if isStatic true, path of the external file where the element source is stored")
 ]
 TemplateContent = Annotated[str | None, Field(default=None, description="template code (HTML)")]
-LockTemplate = Annotated[
-    bool | None, 
-    Field(default=None, description="lock template for editing; requires edit_locked attribute (default: false)")
+Locked = Annotated[
+    bool | None,
+    Field(default=None, description="lock template for editing (default: false)"),
+]
+TemplateProperties = Annotated[
+    dict[str, Any] | list[Any] | str | None,
+    Field(default=None, description="template properties (JSON)"),
 ]
 TemplateVarsAccess = Annotated[
     dict[str, Any] | list[Any] | str | None,
-    Field(default=None, description="JSON list that indicates the access of template vars (default: {})")
+    Field(default=None, description="JSON list of linked TVs: [{id, access, rank}] or [tvId, ...]")
 ]
 
 # --- createTv / updateTv ---
@@ -99,22 +105,36 @@ TvNameOpt = Annotated[str | None, Field(default=None, description="name of the T
 TvId = Annotated[int, Field(description="id of the TV")]
 TvDescription = Annotated[str | None, Field(default=None, description="description of the template variable")]
 TvCaption = Annotated[str | None, Field(default=None, description="text displayed beside the TV when editing it in a Resource")]
-TvCategory = Annotated[str | None, Field(default=None, description="category the TV belongs in")]
-TvType = Annotated[str | None, Field(default=None, description="the type of TV")]
+TvCategory = Annotated[int | None, Field(default=None, description="category id the TV belongs in")]
+TvType = Annotated[str, Field(description="the type of TV (e.g. text, textarea, listbox)")]
+TvTypeOpt = Annotated[str | None, Field(default=None, description="the type of TV (e.g. text, textarea, listbox)")]
 TvElements = Annotated[
     str | None,
-    Field(default=None, description="list of options for TV; only use if the type of TV is listbox"),
+    Field(default=None, description="option elements for list-type TVs"),
 ]
-TvDefaultText = Annotated[
-    str | None,
-    Field(default=None, description="default option for TV; only use if the type of TV is listbox"),
+TvDefaultText = Annotated[str | None, Field(default=None, description="default value")]
+TvRank = Annotated[int | None, Field(default=None, description="TV rank/order")]
+TvDisplay = Annotated[str | None, Field(default=None, description="output widget type")]
+TvProperties = Annotated[
+    dict[str, Any] | list[Any] | str | None,
+    Field(default=None, description="TV properties (JSON)"),
+]
+TvInputProperties = Annotated[
+    dict[str, Any] | list[Any] | str | None,
+    Field(default=None, description="input widget properties (JSON)"),
+]
+TvOutputProperties = Annotated[
+    dict[str, Any] | list[Any] | str | None,
+    Field(default=None, description="output widget properties (JSON)"),
 ]
-TvInputPropeties = Annotated[
-    str | None, Field(default=None, description="JSON list of the input properties of the TV")
+TvEditorType = Annotated[int | None, Field(default=None, description="editor type id")]
+LockTemplate = Annotated[
+    bool | None,
+    Field(default=None, description="lock TV for editing (maps to locked, default: false)"),
 ]
 TvTemplates = Annotated[
     dict[str, Any] | list[Any] | str | None,
-    Field(default=None, description="JSON list that indicates the access of templates (default: {})")
+    Field(default=None, description="JSON list of linked templates: [{id, access, rank}] or [templateId, ...]")
 ]
 
 # --- createCategory / updateCategory ---
@@ -123,6 +143,7 @@ CategoryName = Annotated[str, Field(description="name of the category")]
 CategoryNameOpt = Annotated[str | None, Field(default=None, description="name of the category")]
 CategoryId = Annotated[int, Field(description="id of the category")]
 CategoryParent = Annotated[int | None, Field(default=None, description="parent id of the category (default: 0)")]
+CategoryRank = Annotated[int | None, Field(default=None, description="category rank/order")]
 
 # --- getPage ---
 
@@ -141,6 +162,25 @@ PageLimit = Annotated[
 def _omit_none(**kwargs: Any) -> dict[str, Any]:
     return {key: value for key, value in kwargs.items() if value is not None}
 
+
+def _response_to_text(response: Any) -> str:
+    """Convertit la reponse ClientRest en texte exploitable par getPage."""
+    if isinstance(response, dict):
+        if "text" in response:
+            return response["text"]
+        return json.dumps(response, ensure_ascii=False)
+    return str(response)
+
+
+def _redirect_endpoint(location: str) -> str:
+    """Extrait le chemin relatif depuis un en-tete Location."""
+    parsed = urlparse(location)
+    endpoint = parsed.path or "/"
+    if parsed.query:
+        endpoint = f"{endpoint}?{parsed.query}"
+    return endpoint
+
+
 def _search_keyword(html: str, keyword: PageKeyword, offsetTop: PageOffsetTop, start: PageStart, limit: PageLimit) -> str:
     if limit == 0:
         limit = len(html)
@@ -316,7 +356,8 @@ def register_element_tools(mcp_server: Any, client_rest: ClientRest) -> None:
         isStatic: IsStatic = None,
         staticFile: StaticFile = None,
         content: TemplateContent = None,
-        lockTemplate: LockTemplate = None,
+        locked: Locked = None,
+        properties: TemplateProperties = None,
         templateVars: TemplateVarsAccess = None,
     ) -> dict[str, Any]:
         return client_rest.execute(
@@ -329,7 +370,8 @@ def register_element_tools(mcp_server: Any, client_rest: ClientRest) -> None:
                 isStatic=isStatic,
                 staticFile=staticFile,
                 content=content,
-                lockTemplate=lockTemplate,
+                locked=locked,
+                properties=properties,
                 templateVars=templateVars,
             ),
         )
@@ -350,7 +392,8 @@ def register_element_tools(mcp_server: Any, client_rest: ClientRest) -> None:
         isStatic: IsStatic = None,
         staticFile: StaticFile = None,
         content: TemplateContent = None,
-        lockTemplate: LockTemplate = None,
+        locked: Locked = None,
+        properties: TemplateProperties = None,
         templateVars: TemplateVarsAccess = None,
     ) -> dict[str, Any]:
         return client_rest.execute(
@@ -364,7 +407,8 @@ def register_element_tools(mcp_server: Any, client_rest: ClientRest) -> None:
                 isStatic=isStatic,
                 staticFile=staticFile,
                 content=content,
-                lockTemplate=lockTemplate,
+                locked=locked,
+                properties=properties,
                 templateVars=templateVars,
             ),
         )
@@ -375,16 +419,21 @@ def register_element_tools(mcp_server: Any, client_rest: ClientRest) -> None:
     )
     def createTv(
         name: TvName,
+        type: TvType,
         description: TvDescription = None,
         caption: TvCaption = None,
         category: TvCategory = None,
-        type: TvType = None,
         elements: TvElements = None,
+        rank: TvRank = None,
+        display: TvDisplay = None,
         defaultText: TvDefaultText = None,
+        properties: TvProperties = None,
+        inputProperties: TvInputProperties = None,
+        outputProperties: TvOutputProperties = None,
         lockTemplate: LockTemplate = None,
-        inputPropeties: TvInputPropeties = None,
         isStatic: IsStatic = None,
         staticFile: StaticFile = None,
+        editorType: TvEditorType = None,
         templates: TvTemplates = None,
     ) -> dict[str, Any]:
         return client_rest.execute(
@@ -392,16 +441,21 @@ def register_element_tools(mcp_server: Any, client_rest: ClientRest) -> None:
             endpoint="/rest/tools/tv",
             json=_omit_none(
                 name=name,
+                type=type,
                 description=description,
                 caption=caption,
                 category=category,
-                type=type,
                 elements=elements,
+                rank=rank,
+                display=display,
                 defaultText=defaultText,
+                properties=properties,
+                inputProperties=inputProperties,
+                outputProperties=outputProperties,
                 lockTemplate=lockTemplate,
-                inputPropeties=inputPropeties,
                 isStatic=isStatic,
                 staticFile=staticFile,
+                editorType=editorType,
                 templates=templates,
             ),
         )
@@ -417,16 +471,21 @@ def register_element_tools(mcp_server: Any, client_rest: ClientRest) -> None:
     def updateTv(
         id: TvId,
         name: TvNameOpt = None,
+        type: TvTypeOpt = None,
         description: TvDescription = None,
         caption: TvCaption = None,
         category: TvCategory = None,
-        type: TvType = None,
         elements: TvElements = None,
+        rank: TvRank = None,
+        display: TvDisplay = None,
         defaultText: TvDefaultText = None,
+        properties: TvProperties = None,
+        inputProperties: TvInputProperties = None,
+        outputProperties: TvOutputProperties = None,
         lockTemplate: LockTemplate = None,
-        inputPropeties: TvInputPropeties = None,
         isStatic: IsStatic = None,
         staticFile: StaticFile = None,
+        editorType: TvEditorType = None,
         templates: TvTemplates = None,
     ) -> dict[str, Any]:
         return client_rest.execute(
@@ -435,16 +494,21 @@ def register_element_tools(mcp_server: Any, client_rest: ClientRest) -> None:
             json=_omit_none(
                 id=id,
                 name=name,
+                type=type,
                 description=description,
                 caption=caption,
                 category=category,
-                type=type,
                 elements=elements,
+                rank=rank,
+                display=display,
                 defaultText=defaultText,
+                properties=properties,
+                inputProperties=inputProperties,
+                outputProperties=outputProperties,
                 lockTemplate=lockTemplate,
-                inputPropeties=inputPropeties,
                 isStatic=isStatic,
                 staticFile=staticFile,
+                editorType=editorType,
                 templates=templates,
             ),
         )
@@ -456,11 +520,12 @@ def register_element_tools(mcp_server: Any, client_rest: ClientRest) -> None:
     def createCategory(
         name: CategoryName,
         parent: CategoryParent = None,
+        rank: CategoryRank = None,
     ) -> dict[str, Any]:
         return client_rest.execute(
             method=HTTPMethod.POST,
             endpoint="/rest/tools/category",
-            json=_omit_none(name=name, parent=parent),
+            json=_omit_none(name=name, parent=parent, rank=rank),
         )
 
     @mcp_server.tool(
@@ -475,11 +540,12 @@ def register_element_tools(mcp_server: Any, client_rest: ClientRest) -> None:
         id: CategoryId,
         name: CategoryNameOpt = None,
         parent: CategoryParent = None,
+        rank: CategoryRank = None,
     ) -> dict[str, Any]:
         return client_rest.execute(
             method=HTTPMethod.PUT,
             endpoint="/rest/tools/category",
-            json=_omit_none(id=id, name=name, parent=parent),
+            json=_omit_none(id=id, name=name, parent=parent, rank=rank),
         )
 
     @mcp_server.tool(
@@ -497,16 +563,20 @@ def register_element_tools(mcp_server: Any, client_rest: ClientRest) -> None:
         limit: PageLimit = 1000,
     ) -> str:
         try:
-            html = client_rest.execute(
+            response = client_rest.execute(
                 method=HTTPMethod.GET,
-                endpoint=f"/{url}",
+                endpoint=f"/{url}" if url else "/",
             )
         except httpx.HTTPStatusError as e:
-            if e.response.status_code == 301:
-                html = client_rest.execute(
-                    method=HTTPMethod.GET,
-                    endpoint=f"/{url}/",
-                )
-            else:
-                raise e
-        return _search_keyword(html, keyword, offsetTop, start, limit)
+            if e.response.status_code not in (301, 302, 303, 307, 308):
+                raise
+            location = e.response.headers.get("location")
+            if not location:
+                raise
+            response = client_rest.execute(
+                method=HTTPMethod.GET,
+                endpoint=_redirect_endpoint(location),
+            )
+        return _search_keyword(
+            _response_to_text(response), keyword, offsetTop, start, limit
+        )

+ 6 - 11
src/server_mcp/tools_groupmgt.py

@@ -77,7 +77,7 @@ ContextKey = Annotated[str | None, Field(default=None, description="context key"
 
 # --- updateAccess / removeAccess ---
 AccessId = Annotated[int, Field(description="ACL access entry id")]
-UserGroupIdRemove = Annotated[int, Field(description="user group id")]
+UserGroupIdRemove = Annotated[int | str, Field(description="user group id or name")]
 
 
 def _omit_none(**kwargs: Any) -> dict[str, Any]:
@@ -122,8 +122,8 @@ def register_groupmgt_tools(mcp_server: Any, client_rest: ClientRest) -> None:
     ) -> dict[str, Any]:
         return client_rest.execute(
             method=HTTPMethod.PUT,
-            endpoint="/rest/groupmgt/resources",
-            json={"id": id, "resources": resources},
+            endpoint=f"/rest/groupmgt/resources/{id}",
+            json={"resources": resources},
         )
 
     @mcp_server.tool(
@@ -137,9 +137,7 @@ def register_groupmgt_tools(mcp_server: Any, client_rest: ClientRest) -> None:
         return client_rest.execute(
             method=HTTPMethod.DELETE,
             endpoint=f"/rest/groupmgt/resources/{id}",
-            params={
-                "resources[]": resources
-            }
+            params={"resources[]": resources},
         )
 
     @mcp_server.tool(
@@ -204,9 +202,8 @@ def register_groupmgt_tools(mcp_server: Any, client_rest: ClientRest) -> None:
     ) -> dict[str, Any]:
         return client_rest.execute(
             method=HTTPMethod.PUT,
-            endpoint="/rest/groupmgt/access",
+            endpoint=f"/rest/groupmgt/access/{id}",
             json=_omit_none(
-                id=id,
                 accessId=accessId,
                 resourceGroup=resourceGroup,
                 policy=policy,
@@ -226,7 +223,5 @@ def register_groupmgt_tools(mcp_server: Any, client_rest: ClientRest) -> None:
         return client_rest.execute(
             method=HTTPMethod.DELETE,
             endpoint=f"/rest/groupmgt/access/{id}",
-            params={
-                "accessId": accessId
-            }
+            params={"accessId": accessId},
         )

+ 1 - 1
src/services/client_rest.py

@@ -60,7 +60,7 @@ class ClientRest:
         except httpx.TimeoutException as e:
             raise TimeoutError(f"Timeout lors de l'exécution de la requête: {e}") from e
         except JSONDecodeError as e:
-            return response.text
+            return {"text": response.text}
 
     def _build_url(self, endpoint: str) -> str:
         endpoint = endpoint if endpoint.startswith("/") else f"/{endpoint}"

+ 1 - 6
tests/conftest.py

@@ -13,9 +13,7 @@ from mcp.server.fastmcp import FastMCP
 from mcp.shared.memory import create_connected_server_and_client_session
 
 from src.config.initialization import InitializationError, get_settings
-from src.server_mcp.resources import register_resources
 from src.server_mcp.server import build_server
-from src.server_mcp.tools import register_tools
 from src.services.client_rest import ClientRest
 
 
@@ -26,10 +24,7 @@ def client_rest() -> MagicMock:
 
 @pytest.fixture
 def mcp_server(client_rest: MagicMock) -> FastMCP:
-    server = FastMCP("lw-copilot-mcp-server-test")
-    register_resources(server, client_rest)
-    register_tools(server, client_rest)
-    return server
+    return build_server(client_rest)
 
 
 @pytest.fixture

+ 1 - 1
tests/test_integration_get_resource.py

@@ -7,7 +7,7 @@ import os
 import pytest
 from mcp.client.session import ClientSession
 
-from src.server_mcp.resources import _GET_RESOURCE_WHITELIST
+from src.server_mcp.resources_element import _GET_RESOURCE_WHITELIST
 from tests.conftest import read_resource_json
 
 # ID par defaut : Accueil (cf. .cursor/docs/architecture.md)

+ 10 - 3
tests/test_resources.py

@@ -10,7 +10,7 @@ import pytest
 from mcp.client.session import ClientSession
 
 
-from src.server_mcp.resources import (
+from src.server_mcp.resources_element import (
     _GET_RESOURCES_WHITELIST,
     _filter_list,
     _unwrap_data,
@@ -52,7 +52,14 @@ class TestResourcesMcpIntegration:
         result = await mcp_session.list_resources()
 
         uris = {str(resource.uri) for resource in result.resources}
-        assert uris == {"modx://templates", "modx://categories"}
+        assert uris >= {
+            "modx://templates",
+            "modx://categories",
+            "modx://clientconfig/settings",
+            "modx://clientconfig/groups",
+            "modx://groupmgt/resourcegroups",
+            "modx://groupmgt/usergroups",
+        }
 
     async def test_get_resource_via_client_session(
         self,
@@ -122,7 +129,7 @@ class TestResourcesMcpIntegration:
         client_rest.execute.assert_called_once_with(
             method=HTTPMethod.GET,
             endpoint="/rest/tools/getresources/10000",
-            params={"depth": -1, "includedTv": 0, "showUnpublished": 1},
+            params={"depth": -1, "includeTVs": 0, "showUnpublished": 1},
         )
 
     async def test_get_resources_filters_items_inside_dict(

+ 36 - 13
tests/test_tools.py

@@ -1,5 +1,7 @@
 from __future__ import annotations
 
+import json
+
 import httpx
 import pytest
 
@@ -14,9 +16,14 @@ class TestToolsMcpIntegration:
     async def test_list_tools_exposes_static_endpoints(self, mcp_session: ClientSession) -> None:
         result = await mcp_session.list_tools()
         tools_name = {tool.name for tool in result.tools}
-        assert tools_name == {"createResource", "updateResource", "deleteResource",
-                              "createTemplate", "updateTemplate", "createTv", 
-                              "updateTv", "createCategory", "updateCategory", "getPage"}
+        assert tools_name >= {
+            "createResource", "updateResource", "deleteResource",
+            "createTemplate", "updateTemplate", "createTv",
+            "updateTv", "createCategory", "updateCategory", "getPage",
+            "createResourceGroup", "updateResourceGroup", "removeResourceGroup",
+            "createUserGroup", "createAccess", "updateAccess", "removeAccess",
+            "createConfig", "updateConfig", "createConfigGroup",
+        }
     
     async def test_create_resource(self, mcp_session: ClientSession, client_rest: MagicMock) -> None:
         client_rest.execute.return_value = {
@@ -130,7 +137,7 @@ class TestToolsMcpIntegration:
                 "name": "test-tv",
             },
         }
-        result = await call_tool(mcp_session, "createTv", {"name": "Test TV"})
+        result = await call_tool(mcp_session, "createTv", {"name": "Test TV", "type": "text"})
         assert result == {
             "code": "200",
             "data": {
@@ -141,7 +148,7 @@ class TestToolsMcpIntegration:
         client_rest.execute.assert_called_once_with(
             method=HTTPMethod.POST,
             endpoint="/rest/tools/tv",
-            json={"name": "Test TV"},
+            json={"name": "Test TV", "type": "text"},
         )
     
     async def test_update_tv(self, mcp_session: ClientSession, client_rest: MagicMock) -> None:
@@ -203,7 +210,7 @@ class TestToolsMcpIntegration:
     
     async def test_get_page_returns_html_slice(self, mcp_session: ClientSession, client_rest: MagicMock) -> None:
         html = "0123456789" * 20
-        client_rest.execute.return_value = html
+        client_rest.execute.return_value = {"text": html}
 
         result = await call_tool_text(mcp_session, "getPage", {"url": "accueil/test", "limit": 50})
 
@@ -215,7 +222,7 @@ class TestToolsMcpIntegration:
 
     async def test_get_page_with_keyword(self, mcp_session: ClientSession, client_rest: MagicMock) -> None:
         html = "aaaKEYWORDbbb"
-        client_rest.execute.return_value = html
+        client_rest.execute.return_value = {"text": html}
 
         result = await call_tool_text(
             mcp_session,
@@ -230,18 +237,34 @@ class TestToolsMcpIntegration:
         )
 
     async def test_get_page_retries_on_301(self, mcp_session: ClientSession, client_rest: MagicMock) -> None:
-        request = httpx.Request("GET", "https://example.com/accueil/test")
-        response = httpx.Response(301, request=request)
+        request = httpx.Request("GET", "https://example.com/accueil")
+        response = httpx.Response(
+            301,
+            request=request,
+            headers={"location": "https://example.com/"},
+        )
         redirect_error = httpx.HTTPStatusError("Moved", request=request, response=response)
         html = "<html><body>redirected</body></html>"
-        client_rest.execute.side_effect = [redirect_error, html]
+        client_rest.execute.side_effect = [redirect_error, {"text": html}]
 
-        result = await call_tool_text(mcp_session, "getPage", {"url": "accueil/test"})
+        result = await call_tool_text(mcp_session, "getPage", {"url": "accueil"})
 
         assert result == html[:100]
         assert client_rest.execute.call_count == 2
-        client_rest.execute.assert_any_call(method=HTTPMethod.GET, endpoint="/accueil/test")
-        client_rest.execute.assert_any_call(method=HTTPMethod.GET, endpoint="/accueil/test/")
+        client_rest.execute.assert_any_call(method=HTTPMethod.GET, endpoint="/accueil")
+        client_rest.execute.assert_any_call(method=HTTPMethod.GET, endpoint="/")
+
+    async def test_get_page_handles_json_response(self, mcp_session: ClientSession, client_rest: MagicMock) -> None:
+        payload = {"code": "200", "data": {"id": 1}}
+        client_rest.execute.return_value = payload
+
+        result = await call_tool_text(
+            mcp_session,
+            "getPage",
+            {"url": "rest/tools/resource/get.json", "limit": 50},
+        )
+
+        assert result == json.dumps(payload, ensure_ascii=False)[:50]
 
     async def test_get_page_propagates_http_error(self, mcp_session: ClientSession, client_rest: MagicMock) -> None:
         request = httpx.Request("GET", "https://example.com/missing")