Coverage for mcpgateway / plugins / framework / loader / config.py: 100%
18 statements
« prev ^ index » next coverage.py v7.13.1, created at 2026-02-11 07:10 +0000
« prev ^ index » next coverage.py v7.13.1, created at 2026-02-11 07:10 +0000
1# -*- coding: utf-8 -*-
2"""Location: ./mcpgateway/plugins/framework/loader/config.py
3Copyright 2025
4SPDX-License-Identifier: Apache-2.0
5Authors: Teryl Taylor, Mihai Criveti
7Configuration loader implementation.
8This module loads configurations for plugins.
9"""
11# Standard
12import os
14# Third-Party
15import jinja2
16import yaml
18# First-Party
19from mcpgateway.plugins.framework.models import Config, PluginSettings
22class ConfigLoader:
23 """A configuration loader.
25 Examples:
26 >>> import tempfile
27 >>> import os
28 >>> from mcpgateway.plugins.framework.models import PluginSettings
29 >>> # Create a temporary config file
30 >>> with tempfile.NamedTemporaryFile(mode='w', suffix='.yaml', delete=False) as f:
31 ... _ = f.write(\"\"\"
32 ... plugin_settings:
33 ... enable_plugin_api: true
34 ... plugin_timeout: 30
35 ... plugin_dirs: ['/path/to/plugins']
36 ... \"\"\")
37 ... temp_path = f.name
38 >>> try:
39 ... config = ConfigLoader.load_config(temp_path, use_jinja=False)
40 ... config.plugin_settings.enable_plugin_api
41 ... finally:
42 ... os.unlink(temp_path)
43 True
44 """
46 @staticmethod
47 def load_config(config: str, use_jinja: bool = True) -> Config:
48 """Load the plugin configuration from a file path.
50 Args:
51 config: the configuration path.
52 use_jinja: use jinja to replace env variables if true.
54 Returns:
55 The plugin configuration object.
57 Examples:
58 >>> import tempfile
59 >>> import os
60 >>> with tempfile.NamedTemporaryFile(mode='w', suffix='.yaml', delete=False) as f:
61 ... _ = f.write(\"\"\"
62 ... plugin_settings:
63 ... plugin_timeout: 60
64 ... enable_plugin_api: false
65 ... plugin_dirs: []
66 ... \"\"\")
67 ... temp_path = f.name
68 >>> try:
69 ... cfg = ConfigLoader.load_config(temp_path, use_jinja=False)
70 ... cfg.plugin_settings.plugin_timeout
71 ... finally:
72 ... os.unlink(temp_path)
73 60
74 """
75 try:
76 with open(os.path.normpath(config), "r", encoding="utf-8") as file:
77 template = file.read()
78 if use_jinja:
79 jinja_env = jinja2.Environment(loader=jinja2.BaseLoader(), autoescape=True)
80 rendered_template = jinja_env.from_string(template).render(env=os.environ)
81 else:
82 rendered_template = template
83 config_data = yaml.safe_load(rendered_template) or {}
84 return Config(**config_data)
85 except FileNotFoundError:
86 # Graceful fallback for tests and minimal environments without plugin config
87 return Config(plugins=[], plugin_dirs=[], plugin_settings=PluginSettings())