mcp_stdio_proxy/
config.rs

1use anyhow::Result;
2use serde::Deserialize;
3use std::env;
4use std::fs::File;
5use std::path::Path;
6
7/// The default config file
8const DEFAULT_CONFIG_YAML: &str = include_str!("../config.yml");
9
10#[allow(dead_code)]
11#[derive(Debug, Deserialize)]
12pub struct AppConfig {
13    pub server: ServerConfig,
14    pub log: LogConfig,
15}
16#[allow(dead_code)]
17#[derive(Debug, Deserialize)]
18pub struct ServerConfig {
19    /// The port to listen on for incoming connections
20    pub port: u16,
21}
22#[allow(dead_code)]
23#[derive(Debug, Deserialize)]
24pub struct LogConfig {
25    /// The log level to use
26    pub level: String,
27    /// The path to the log file
28    pub path: String,
29    /// The number of log files to retain (default: 20)
30    #[serde(default = "default_retain_days")]
31    pub retain_days: u32,
32}
33
34/// Default log files to retain
35fn default_retain_days() -> u32 {
36    5
37}
38
39#[allow(dead_code)]
40impl AppConfig {
41    /// Load the config file from the following sources:
42    /// 1. /app/config.yml
43    /// 2. config.yml
44    /// 3. BOT_SERVER_CONFIG environment variable
45    pub fn load_config() -> Result<Self> {
46        let ret = match (
47            File::open("/app/config.yml"),
48            File::open("config.yml"),
49            env::var("BOT_SERVER_CONFIG"),
50        ) {
51            (Ok(file), _, _) => serde_yaml::from_reader(file),
52            (_, Ok(file), _) => serde_yaml::from_reader(file),
53            (_, _, Ok(file_path)) => serde_yaml::from_reader(File::open(file_path)?),
54            _ => {
55                // 如果都没有,则使用默认配置
56                serde_yaml::from_str::<AppConfig>(DEFAULT_CONFIG_YAML)
57            }
58        };
59
60        Ok(ret?)
61    }
62
63    pub fn log_path_init(&self) -> Result<()> {
64        let log_path = &self.log.path;
65
66        // 获取日志文件的父目录
67        if let Some(parent) = Path::new(log_path).parent() {
68            if !parent.exists() {
69                std::fs::create_dir_all(parent)?;
70            }
71        }
72        Ok(())
73    }
74}