Forráskód Böngészése

Ajout de la gestion du contexte et debut de tests associés

Damien Lugagne-Delpon 10 hónapja
szülő
commit
9b208123ac

+ 0 - 0
mcp_server/__init__.py


+ 8 - 2
mcp_server/config/logger.py

@@ -19,10 +19,15 @@ Modifications :
 
 import logging
 
-from config.settings import LOG_LEVEL, APP_NAME
+from mcp_server.config.settings import LOG_LEVEL, APP_NAME
+
+LOGGER = None
 
 def init_logger():
     """Initilize the logger for the MCP server."""
+    global LOGGER 
+    if LOGGER is not None:
+        return LOGGER
     logger = logging.getLogger(APP_NAME)
     if logger.hasHandlers():
         logger.handlers.clear()
@@ -33,4 +38,5 @@ def init_logger():
     formatter = logging.Formatter('[%(asctime)s] - [%(levelname)s] - %(name)s - %(message)s')
     ch.setFormatter(formatter)
     logger.addHandler(ch)
-    return logger
+    LOGGER = logger
+

+ 0 - 0
mcp_server/core/__init__.py


+ 32 - 0
mcp_server/core/constants.py

@@ -0,0 +1,32 @@
+"""
+-----------------------------------------------------------------------------------------
+INTERSEL - 4 cité d'Hauteville - 75010 PARIS
+RCS PARIS 488 379 660 - NAF 721Z
+
+File : core/constants.py
+Object : Constants, enums, globals for the MCP server
+-----------------------------------------------------------------------------------------
+Modifications :
+- 2026/01/20 - 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 enum import Enum
+
+class ModxType(str, Enum):
+    """Enumeration of MODX types."""
+    RESOURCE = "resource"
+    TEMPLATE = "template"
+    TV = "tv"
+    CHUNK = "chunk"
+
+class actionType(str, Enum):
+    """Enumeration of action types."""
+    UPDATE = "update"
+    READ = "read"

+ 32 - 10
mcp_server/core/context/context_manager.py

@@ -16,9 +16,9 @@ Modifications :
 -----------------------------------------------------------------------------------------
 
 """
-
-from .context_schema import DEFAULT_CONTEXT
-
+from mcp_server.core.constants import ModxType, actionType
+from mcp_server.core.context.context_schema import DEFAULT_CONTEXT
+from mcp_server.config.logger import LOGGER as logger
 
 class ContextManager:
     """Context manager for the MCP server."""
@@ -27,14 +27,36 @@ class ContextManager:
         """Initialize the context manager."""
         self.context = DEFAULT_CONTEXT.copy()
     
-    def add_context(self, key: str, value):
-        """"""
-        pass
-    
-    def remove_context(self, key: str):
-        """Supprimer du contexte."""
-        pass
+    def add_to_context(self, modx_type, items):
+        """Add items of a given MODX type to the context."""
+        if modx_type in self.context:
+            for element_id, actions in items.items():
+                filtered_actions = {}
+                for action, value in actions.items():
+                    if action not in actionType.__members__.values():
+                        logger.warning(f"ContextManager - add_to_context - Unknown action type '{action}' for MODX type '{modx_type}'. Skipping this action.")
+                    else:
+                        filtered_actions[action] = value
+                self.context[modx_type][element_id] = filtered_actions
+            logger.debug(f"ContextManager - add_to_context - Items added to context.")
+        else:
+            logger.warning(f"ContextManager - add_to_context - MODX type '{modx_type}' not in context. Cannot add items to context.")
     
+    def remove_from_context(self, modx_type, item_ids):
+        """Remove items of a given MODX type from the context by their IDs."""
+        if modx_type in self.context:
+            for item_id in item_ids:
+                if item_id in self.context[modx_type]:
+                    del self.context[modx_type][item_id]
+            logger.debug(f"ContextManager - remove_from_context - Items removed from context.")
+        else:
+            logger.warning(f"ContextManager - remove_from_context - MODX type '{modx_type}' not in context. Cannot remove items from context.")
+
+    def clear_context(self):
+        """Clear the entire context."""
+        self.context = DEFAULT_CONTEXT.copy()
+        logger.debug("ContextManager - clear_context - Context cleared.")
+
     def get_context(self):
         """Obtenir le contexte complet."""
         return self.context

+ 15 - 8
mcp_server/core/context/context_schema.py

@@ -5,6 +5,18 @@ RCS PARIS 488 379 660 - NAF 721Z
 
 File : core/context/context_schema.py
 Object : Context schema for the MCP server
+
+Must respect the following structure :
+{
+    <ModxType>: {
+        <id>: {
+            <actionType>: True,
+            <actionType>: False
+        },...
+    },
+    ...
+}
+
 -----------------------------------------------------------------------------------------
 Modifications :
 - 2026/01/16 - Damien Lugagne-Delpon - V1.0.0- Creation
@@ -17,14 +29,9 @@ Modifications :
 
 """
 
-
-
+from mcp_server.core.constants import ModxType, actionType
 
 DEFAULT_CONTEXT = {
-    "resources": [
-
-    ],
-    "templates": [
-
-    ],
+    ModxType.RESOURCE: {},
+    ModxType.TEMPLATE: {},
 }

+ 3 - 4
mcp_server/main.py

@@ -18,12 +18,11 @@ Modifications :
 """
 
 
-from config.logger import init_logger
-
+from mcp_server.config.logger import init_logger, LOGGER
 
 def main():
     """MCP server main entry point."""
-    logger = init_logger()
-    logger.debug("main - Starting MCP server...")
+    init_logger()
+    LOGGER.debug("main - Starting MCP server...")
 
     pass

+ 0 - 0
mcp_server/tests/__init__.py


+ 55 - 0
mcp_server/tests/test_context.py

@@ -0,0 +1,55 @@
+"""
+-----------------------------------------------------------------------------------------
+INTERSEL - 4 cité d'Hauteville - 75010 PARIS
+RCS PARIS 488 379 660 - NAF 721Z
+
+File : tests/test_context.py
+Object : Tests for the context manager of the MCP server
+-----------------------------------------------------------------------------------------
+Modifications :
+- 2026/01/20 - 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 mcp_server.config.logger import LOGGER, init_logger
+from mcp_server.tests.test_manager import TestManager
+from mcp_server.core.context.context_manager import ContextManager
+from mcp_server.core.constants import ModxType, actionType
+
+
+init_logger()
+tm = TestManager()
+
+
+@tm.test("Context manager initializes")
+def test_context_initialization():
+    cm = ContextManager()
+    tm.assert_is_not_none(cm)
+
+
+@tm.test("Set and get context value")
+def test_set_get_context():
+    cm = ContextManager()
+    cm.add_to_context(ModxType.RESOURCE, {
+        1: {
+            actionType.UPDATE: True,
+            actionType.READ: True
+        },
+        2: {
+            actionType.READ: True
+        }
+    })
+    context = cm.get_context()
+    tm.assert_equal(len(context[ModxType.RESOURCE]), 2)
+
+
+
+
+if __name__ == "__main__":
+    tm.run()

+ 70 - 0
mcp_server/tests/test_manager.py

@@ -0,0 +1,70 @@
+"""
+-----------------------------------------------------------------------------------------
+INTERSEL - 4 cité d'Hauteville - 75010 PARIS
+RCS PARIS 488 379 660 - NAF 721Z
+
+File : tests/test_manager.py
+Object : Tests manager for the MCP server
+-----------------------------------------------------------------------------------------
+Modifications :
+- 2026/01/20 - 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 mcp_server.config.logger import init_logger
+init_logger()
+
+class TestFailure(Exception):
+    pass
+
+class TestManager:
+    def __init__(self):
+        self.tests = []
+        self.passed = 0
+        self.failed = 0
+
+    def test(self, name):
+        """Decorator to register a test"""
+        def wrapper(fn):
+            self.tests.append((name, fn))
+            return fn
+        return wrapper
+
+    # Assertions basiques
+    def assert_equal(self, a, b, message=None):
+        if a != b:
+            raise TestFailure(message or f"{a} != {b}")
+
+    def assert_is_none(self, value, message=None):
+        if value is not None:
+            raise TestFailure(message or f"{value} is not None")
+
+    def assert_is_not_none(self, value, message=None):
+        if value is None:
+            raise TestFailure(message or "value is None")
+
+    def run(self):
+        print(f"Running {len(self.tests)} tests\n")
+
+        for name, test_fn in self.tests:
+            try:
+                test_fn()
+                self.passed += 1
+                print(f"[PASS] {name}")
+            except Exception as e:
+                self.failed += 1
+                print(f"[FAIL] {name}")
+                print(f"       {e}")
+
+        print("\n---")
+        print(f"Passed: {self.passed}")
+        print(f"Failed: {self.failed}")
+
+        if self.failed > 0:
+            raise SystemExit(1)

+ 1 - 1
mcp_server/tools/resource/get_resource.py

@@ -17,7 +17,7 @@ Modifications :
 
 """
 
-from . import ResourceTool
+from mcp_server.tools.resource import ResourceTool
 
 def get_resource_tool():
     """Create and return the Get Resource tool."""