|
| 1 | +import openstack |
| 2 | + |
| 3 | +from fastmcp import FastMCP |
| 4 | +from openstack import connection |
| 5 | +from openstack.config.loader import OpenStackConfig |
| 6 | + |
| 7 | +from openstack_mcp_server import config |
| 8 | + |
| 9 | + |
| 10 | +class ConnectionManager: |
| 11 | + _cloud_name = config.MCP_CLOUD_NAME |
| 12 | + |
| 13 | + def register_tools(self, mcp: FastMCP): |
| 14 | + mcp.tool(self.get_cloud_config) |
| 15 | + mcp.tool(self.get_cloud_names) |
| 16 | + mcp.tool(self.get_cloud_name) |
| 17 | + mcp.tool(self.set_cloud_name) |
| 18 | + |
| 19 | + def get_connection(self) -> connection.Connection: |
| 20 | + return openstack.connect(cloud=self._cloud_name) |
| 21 | + |
| 22 | + def get_cloud_names(self) -> list[str]: |
| 23 | + """List available cloud configurations. |
| 24 | +
|
| 25 | + :return: Names of OpenStack clouds from user's config file. |
| 26 | + """ |
| 27 | + config = OpenStackConfig() |
| 28 | + return list(config.get_cloud_names()) |
| 29 | + |
| 30 | + def get_cloud_config(self) -> dict: |
| 31 | + """Provide cloud configuration with secrets masked of current user's config file. |
| 32 | +
|
| 33 | + :return: Cloud configuration dictionary with credentials masked. |
| 34 | + """ |
| 35 | + config = OpenStackConfig() |
| 36 | + return ConnectionManager._mask_credential( |
| 37 | + config.cloud_config, ["password"] |
| 38 | + ) |
| 39 | + |
| 40 | + @staticmethod |
| 41 | + def _mask_credential( |
| 42 | + config_dict: dict, credential_keys: list[str] |
| 43 | + ) -> dict: |
| 44 | + masked = {} |
| 45 | + for k, v in config_dict.items(): |
| 46 | + if k in credential_keys: |
| 47 | + masked[k] = "****" |
| 48 | + elif isinstance(v, dict): |
| 49 | + masked[k] = ConnectionManager._mask_credential( |
| 50 | + v, credential_keys |
| 51 | + ) |
| 52 | + else: |
| 53 | + masked[k] = v |
| 54 | + return masked |
| 55 | + |
| 56 | + @classmethod |
| 57 | + def get_cloud_name(cls) -> str: |
| 58 | + """Return the currently selected cloud name. |
| 59 | +
|
| 60 | + :return: current OpenStack cloud name. |
| 61 | + """ |
| 62 | + return cls._cloud_name |
| 63 | + |
| 64 | + @classmethod |
| 65 | + def set_cloud_name(cls, cloud_name: str) -> None: |
| 66 | + """Set cloud name to use for later connections. Must set name from currently valid cloud config file. |
| 67 | +
|
| 68 | + :param cloud_name: Name of the OpenStack cloud profile to activate. |
| 69 | + """ |
| 70 | + cls._cloud_name = cloud_name |
0 commit comments