-
Notifications
You must be signed in to change notification settings - Fork 117
Expand file tree
/
Copy pathconfig.py
More file actions
145 lines (118 loc) · 5 KB
/
Copy pathconfig.py
File metadata and controls
145 lines (118 loc) · 5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
"""
Configuration utilities for MCPM
"""
import json
import logging
import os
from typing import Any, Dict
logger = logging.getLogger(__name__)
# Default configuration paths
DEFAULT_CONFIG_DIR = os.path.expanduser("~/.config/mcpm")
DEFAULT_CONFIG_FILE = os.path.join(DEFAULT_CONFIG_DIR, "config.json")
# default router config
DEFAULT_HOST = "localhost"
DEFAULT_PORT = 6276 # 6276 represents MCPM on a T9 keypad (6=M, 2=C, 7=P, 6=M)
# default splitor pattern
DEFAULT_SHARE_ADDRESS = f"share.mcpm.sh:{DEFAULT_PORT}"
MCPM_AUTH_HEADER = "X-MCPM-SECRET"
MCPM_PROFILE_HEADER = "X-MCPM-PROFILE"
class ConfigManager:
"""Manages MCP basic configuration
Note: This class only manages basic system configuration.
Client-specific configurations are managed by ClientConfigManager.
"""
def __init__(self, config_path: str = DEFAULT_CONFIG_FILE):
self.config_path = config_path
self.config_dir = os.path.dirname(config_path)
self._config = None
self._ensure_dirs()
self._load_config()
def _ensure_dirs(self) -> None:
"""Ensure all configuration directories exist"""
os.makedirs(self.config_dir, exist_ok=True)
def _load_config(self) -> None:
"""Load configuration from file or create default"""
if os.path.exists(self.config_path):
try:
with open(self.config_path, "r", encoding="utf-8") as f:
self._config = json.load(f)
except json.JSONDecodeError:
logger.error(f"Error parsing config file: {self.config_path}")
self._config = self._default_config()
else:
self._config = self._default_config()
self._save_config()
def _default_config(self) -> Dict[str, Any]:
"""Create default configuration"""
# Return empty config - don't set any defaults
return {}
def _save_config(self) -> None:
"""Save current configuration to file"""
with open(self.config_path, "w", encoding="utf-8") as f:
json.dump(self._config, f, indent=2)
def get_config(self) -> Dict[str, Any]:
"""Get the complete configuration"""
return self._config
def set_config(self, key: str, value: Any) -> bool:
"""Set a configuration value and persist to file
Args:
key: Configuration key to set
value: Value to set for the key (must be JSON serializable)
Returns:
bool: Success or failure
"""
try:
if value is None and key in self._config:
# Remove the key if value is None
del self._config[key]
else:
# Set the key to the provided value
self._config[key] = value
# Save the updated configuration
self._save_config()
return True
except Exception as e:
logger.error(f"Error setting configuration {key}: {str(e)}")
return False
def get_router_config(self):
"""get router configuration from config file, if not exists, flush default config"""
config = self.get_config()
# check if router config exists
if "router" not in config:
# create default config and save
router_config = {"host": DEFAULT_HOST, "port": DEFAULT_PORT, "share_address": DEFAULT_SHARE_ADDRESS}
self.set_config("router", router_config)
return router_config
# get existing config
router_config = config.get("router", {})
# check if host and port exist, if not, set default values and update config
# user may only set a customized port while leave host undefined
updated = False
if "host" not in router_config:
router_config["host"] = DEFAULT_HOST
updated = True
if "port" not in router_config:
router_config["port"] = DEFAULT_PORT
updated = True
if "share_address" not in router_config:
router_config["share_address"] = DEFAULT_SHARE_ADDRESS
updated = True
# save config if updated
if updated:
self.set_config("router", router_config)
return router_config
def save_router_config(self, host, port, share_address, api_key: str | None = None, auth_enabled: bool = False):
"""save router configuration to config file"""
router_config = self.get_config().get("router", {})
# update config
router_config["host"] = host
router_config["port"] = port
router_config["share_address"] = share_address
router_config["api_key"] = api_key
router_config["auth_enabled"] = auth_enabled
# save config
return self.set_config("router", router_config)
def save_share_config(self, share_url: str | None = None, share_pid: int | None = None):
return self.set_config("share", {"url": share_url, "pid": share_pid})
def read_share_config(self) -> Dict[str, Any]:
return self.get_config().get("share", {})