Skip to content

Commit f3b7cca

Browse files
authored
Merge pull request #15 from SepineTam/codex/更新配置文件用法和索引方式
Update config handling
2 parents 6b8439b + 54ea9d1 commit f3b7cca

File tree

8 files changed

+93
-19
lines changed

8 files changed

+93
-19
lines changed

README.md

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,9 @@ The standard config json as follows, you can DIY your config via add envs.
4343
}
4444
```
4545

46-
For more detailed usage information, visit the [Usage guide](source/docs/Usages/Usage.md).
46+
For more detailed usage information, visit the [Usage guide](source/docs/Usages/Usage.md).
47+
48+
Configuration values are stored in `~/.stata-mcp/config.toml`. See the [Configuration guide](source/docs/Usages/Configuration.md) for details.
4749

4850
And some advanced usage, visit the [Advanced guide](source/docs/Usages/Advanced.md)
4951

@@ -84,6 +86,7 @@ uvx /path/to/your/whl/stata_mcp-1.6.0-py3-non-any.whl # here is the wheel file
8486

8587
## 📝 Documentation
8688
- For more detailed usage information, visit the [Usage guide](source/docs/Usages/Usage.md).
89+
- See how to edit the config file in the [Configuration guide](source/docs/Usages/Configuration.md).
8790
- Advanced Usage, visit the [Advanced](source/docs/Usages/Advanced.md)
8891
- Some questions, visit the [Questions](source/docs/Usages/Questions.md)
8992
- Difference with [Stata-MCP@hanlulong](https://github.com/hanlulong/stata-mcp), visit the [Difference](source/docs/Difference.md)

source/docs/README/cn/README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,8 @@
4646

4747
有关更详细的使用信息,请访问[使用指南](../../Usages/Usage.md)
4848

49+
配置文件位于 `~/.stata-mcp/config.toml`,详见[配置指南](../../Usages/Configuration.md)
50+
4951
一些高级的功能,访问[高级指南](../../Usages/Advanced.md)
5052

5153
### 前提条件
@@ -85,6 +87,7 @@ uvx /path/to/your/whl/stata_mcp-1.6.0-py3-non-any.whl # 这里的文件名可
8587

8688
## 📝 文档
8789
- 有关更详细的使用信息,请访问[使用指南](../../Usages/Usage.md)
90+
- 了解如何编辑配置文件,请阅读[配置指南](../../Usages/Configuration.md)
8891
- 高级用法,请访问[高级指南](../../Usages/Advanced.md)
8992
- 一些问题,请访问[问题](../../Usages/Questions.md)
9093
-[Stata-MCP@hanlulong](https://github.com/hanlulong/stata-mcp)的区别,请访问[区别](../../Difference.md)

source/docs/README/fr/README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@ Le fichier json de configuration standard est le suivant, vous pouvez personnali
4444
```
4545

4646
Pour des informations d'utilisation plus détaillées, consultez le [guide d'utilisation](../../Usages/Usage.md).
47+
Les valeurs de configuration sont stockées dans `~/.stata-mcp/config.toml`. Consultez le [guide de configuration](../../Usages/Configuration.md) pour plus de détails.
4748

4849
Et pour une utilisation avancée, visitez le [Guide avancé](../../Usages/Advanced.md)
4950

@@ -84,6 +85,7 @@ uvx /path/to/your/whl/stata_mcp-1.6.0-py3-non-any.whl # modifiez le nom du fich
8485

8586
## 📝 Documentation
8687
- Pour des informations d'utilisation plus détaillées, consultez le [guide d'utilisation](../../Usages/Usage.md).
88+
- Consultez le [guide de configuration](../../Usages/Configuration.md) pour modifier le fichier de configuration.
8789
- Utilisation avancée, visitez le [Guide avancé](../../Usages/Advanced.md)
8890
- Quelques questions, visitez les [Questions](../../Usages/Questions.md)
8991
- Différence avec [Stata-MCP@hanlulong](https://github.com/hanlulong/stata-mcp), visitez la [Différence](../../Difference.md)

source/docs/README/sp/README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@ El archivo json de configuración estándar es el siguiente; puedes personalizar
4444
```
4545

4646
Para información más detallada sobre el uso, visita la [guía de Uso](../../Usages/Usage.md).
47+
Los valores de configuración se almacenan en `~/.stata-mcp/config.toml`. Consulta la [guía de Configuración](../../Usages/Configuration.md) para más detalles.
4748

4849
Y para un uso más avanzado, visita la [Guía avanzada](../../Usages/Advanced.md)
4950

@@ -84,6 +85,7 @@ uvx /path/to/your/whl/stata_mcp-1.6.0-py3-non-any.whl # cambia el nombre del ar
8485

8586
## 📝 Documentación
8687
- Para información más detallada sobre el uso, visita la [guía de Uso](../../Usages/Usage.md).
88+
- Consulta la [guía de Configuración](../../Usages/Configuration.md) para editar el archivo de configuración.
8789
- Uso avanzado, visita la [Guía avanzada](../../Usages/Advanced.md)
8890
- Algunas preguntas, visita las [Preguntas](../../Usages/Questions.md)
8991
- Diferencia con [Stata-MCP@hanlulong](https://github.com/hanlulong/stata-mcp), visita las [Diferencias](../../Difference.md)

source/docs/Usages/Configuration.md

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
# Configuration File
2+
3+
Stata-MCP stores settings in `~/.stata-mcp/config.toml`. A sample file is located at `src/stata_mcp/config/example.toml`.
4+
Copy it to your home folder if the file does not exist and modify as needed.
5+
6+
## Accessing Values
7+
8+
You can read and write values in the configuration using dot notation:
9+
10+
```python
11+
from stata_mcp.config import Config
12+
cfg = Config()
13+
model = cfg.get("llm.ollama.MODEL")
14+
cfg.set("stata.stata_cli", "/path/to/stata")
15+
```
16+
17+
Sections mirror the TOML hierarchy, so `llm.ollama.MODEL` refers to the `MODEL` key inside `[llm.ollama]`.

src/stata_mcp/__init__.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,6 @@
2121
dotenv.load_dotenv()
2222
mcp = FastMCP(name="stata-mcp")
2323
config_mgr = Config()
24-
cfg = config_mgr.config
2524

2625
# Initialize optional parameters
2726
sys_os = platform.system()
@@ -38,7 +37,7 @@
3837
sys.exit("Unknown System")
3938

4039
# Use configured output path if available
41-
output_base_path = cfg.get("output_base_path") or os.path.join(
40+
output_base_path = config_mgr.get("stata-mcp.output_base_path") or os.path.join(
4241
documents_path, "stata-mcp-folder"
4342
)
4443
os.makedirs(output_base_path, exist_ok=True)
@@ -47,7 +46,9 @@
4746
# stata_cli
4847
finder = StataFinder()
4948
default_cli = finder.find_stata()
50-
stata_cli = cfg.get("stata_cli") or os.getenv("stata_cli", default_cli)
49+
stata_cli = config_mgr.get("stata.stata_cli") or os.getenv(
50+
"stata_cli", default_cli
51+
)
5152
if stata_cli is None:
5253
exit_msg = (
5354
"Missing Stata.exe, "

src/stata_mcp/config/__init__.py

Lines changed: 57 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55

66
class Config:
7-
"""Simple configuration manager for Stata-MCP."""
7+
"""Configuration manager supporting nested TOML sections."""
88

99
CONFIG_FILE_PATH = os.path.expanduser("~/.stata-mcp/config.toml")
1010

@@ -25,29 +25,75 @@ def _default_config(self) -> dict:
2525
else:
2626
documents_path = os.path.expanduser("~/Documents")
2727
return {
28-
"stata_cli": "",
29-
"output_base_path": os.path.join(documents_path, "stata-mcp-folder"),
28+
"stata": {"stata_cli": ""},
29+
"stata-mcp": {
30+
"output_base_path": os.path.join(
31+
documents_path, "stata-mcp-folder"
32+
)
33+
},
34+
"llm": {
35+
"LLM_TYPE": "ollama",
36+
"ollama": {
37+
"MODEL": "qwen2.5-coder:7b",
38+
"BASE_URL": "http://localhost:11434",
39+
},
40+
"openai": {
41+
"MODEL": "gpt-3.5-turbo",
42+
"BASE_URL": "https://api.openai.com/v1",
43+
"API_KEY": "<YOUR_OPENAI_API_KEY>",
44+
},
45+
},
3046
}
3147

48+
def _write_dict(self, f, data: dict, prefix: str = "") -> None:
49+
for key, value in data.items():
50+
if isinstance(value, dict):
51+
section = f"{prefix}.{key}" if prefix else key
52+
f.write(f"\n[{section}]\n")
53+
self._write_dict(f, value, section)
54+
else:
55+
escaped = str(value).replace('"', '\\"')
56+
f.write(f"{key} = \"{escaped}\"\n")
57+
3258
def _save(self) -> None:
3359
"""Write the current config to the TOML file."""
3460
with open(self.CONFIG_FILE_PATH, "w", encoding="utf-8") as f:
35-
for key, value in self.config.items():
36-
escaped = str(value).replace('"', '\\"')
37-
f.write(f"{key} = \"{escaped}\"\n")
61+
self._write_dict(f, self.config)
3862

3963
def load_config(self) -> dict:
4064
with open(self.CONFIG_FILE_PATH, "rb") as f:
4165
return tomllib.load(f)
4266

67+
def _get_nested(self, data: dict, keys: list[str], default=None):
68+
for k in keys:
69+
if isinstance(data, dict) and k in data:
70+
data = data[k]
71+
else:
72+
return default
73+
return data
74+
4375
def get(self, key: str, default: str | None = None):
44-
return self.config.get(key, default)
76+
keys = key.split(".")
77+
return self._get_nested(self.config, keys, default)
78+
79+
def _set_nested(self, data: dict, keys: list[str], value):
80+
for k in keys[:-1]:
81+
data = data.setdefault(k, {})
82+
data[keys[-1]] = value
4583

4684
def set(self, key: str, value: str) -> None:
47-
self.config[key] = value
85+
keys = key.split(".")
86+
self._set_nested(self.config, keys, value)
4887
self._save()
4988

89+
def _delete_nested(self, data: dict, keys: list[str]):
90+
for k in keys[:-1]:
91+
data = data.get(k)
92+
if not isinstance(data, dict):
93+
return
94+
data.pop(keys[-1], None)
95+
5096
def delete(self, key: str) -> None:
51-
if key in self.config:
52-
del self.config[key]
53-
self._save()
97+
keys = key.split(".")
98+
self._delete_nested(self.config, keys)
99+
self._save()

src/stata_mcp/webui/__init__.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,14 +16,14 @@ def config():
1616
if request.method == 'POST':
1717
stata_cli = request.form['stata_cli']
1818
output_base_path = request.form['output_base_path']
19-
config_mgr.set('stata_cli', stata_cli)
20-
config_mgr.set('output_base_path', output_base_path)
19+
config_mgr.set('stata.stata_cli', stata_cli)
20+
config_mgr.set('stata-mcp.output_base_path', output_base_path)
2121
return redirect(url_for('config', saved='1'))
2222

2323
return render_template(
2424
'config.html',
25-
stata_cli=config_mgr.get('stata_cli', ''),
26-
output_base_path=config_mgr.get('output_base_path', ''),
25+
stata_cli=config_mgr.get('stata.stata_cli', ''),
26+
output_base_path=config_mgr.get('stata-mcp.output_base_path', ''),
2727
saved=saved
2828
)
2929

0 commit comments

Comments
 (0)