sapphire_framework_server/
config.rs1use std::net::SocketAddr;
20use std::path::{Path, PathBuf};
21
22use sapphire_workspace::AppContext;
23use serde::{Deserialize, Serialize};
24
25use crate::error::{Error, Result};
26
27pub const SERVER_CONFIG_FILE: &str = "server.toml";
29
30#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
32#[serde(deny_unknown_fields)]
33pub struct ServerConfig {
34 #[serde(default)]
36 pub http: HttpConfig,
37 #[serde(default)]
39 pub mcp: McpConfig,
40}
41
42#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
47#[serde(deny_unknown_fields)]
48pub struct HttpConfig {
49 #[serde(default, skip_serializing_if = "Option::is_none")]
51 pub listen: Option<SocketAddr>,
52 #[serde(default, skip_serializing_if = "Vec::is_empty")]
54 pub allowed_hosts: Vec<String>,
55}
56
57#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
59#[serde(deny_unknown_fields)]
60pub struct McpConfig {
61 #[serde(default)]
63 pub http: bool,
64}
65
66impl ServerConfig {
67 pub fn path_for_app(ctx: &AppContext) -> Option<PathBuf> {
69 ctx.try_config_dir().map(|dir| dir.join(SERVER_CONFIG_FILE))
70 }
71
72 pub fn load_for_app(ctx: &AppContext) -> Result<ServerConfig> {
75 match ServerConfig::path_for_app(ctx) {
76 Some(path) => ServerConfig::load(&path),
77 None => Ok(ServerConfig::default()),
78 }
79 }
80
81 pub fn load(path: &Path) -> Result<ServerConfig> {
86 match std::fs::read_to_string(path) {
87 Ok(text) => {
88 toml::from_str(&text).map_err(|e| Error::Config(format!("{}: {e}", path.display())))
89 }
90 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(ServerConfig::default()),
91 Err(e) => Err(Error::Io(e)),
92 }
93 }
94}
95
96#[cfg(test)]
97mod tests {
98 use super::*;
99
100 #[test]
101 fn a_missing_file_is_all_defaults_and_mcp_is_off() {
102 let tmp = tempfile::TempDir::new().unwrap();
103 let config = ServerConfig::load(&tmp.path().join(SERVER_CONFIG_FILE)).unwrap();
104 assert_eq!(config, ServerConfig::default());
105 assert!(!config.mcp.http);
106 assert_eq!(config.http.listen, None);
107 }
108
109 #[test]
110 fn the_file_turns_mcp_on_and_names_the_listener() {
111 let tmp = tempfile::TempDir::new().unwrap();
112 let path = tmp.path().join(SERVER_CONFIG_FILE);
113 std::fs::write(
114 &path,
115 "[http]\nlisten = \"127.0.0.1:3173\"\nallowed_hosts = [\"box.example\"]\n\n[mcp]\nhttp = true\n",
116 )
117 .unwrap();
118 let config = ServerConfig::load(&path).unwrap();
119 assert!(config.mcp.http);
120 assert_eq!(config.http.listen, Some("127.0.0.1:3173".parse().unwrap()));
121 assert_eq!(config.http.allowed_hosts, vec!["box.example".to_owned()]);
122 }
123
124 #[test]
125 fn a_misspelt_setting_is_an_error_not_a_default() {
126 let tmp = tempfile::TempDir::new().unwrap();
127 let path = tmp.path().join(SERVER_CONFIG_FILE);
128 std::fs::write(&path, "[mcp]\nhtpp = true\n").unwrap();
129 assert!(ServerConfig::load(&path).is_err());
130 }
131}