Skip to main content

sapphire_framework_server/
config.rs

1//! The server's own settings: `<config dir>/server.toml`.
2//!
3//! What a server offers beyond its IPC endpoint is the host's choice, so it lives in the
4//! application's config directory beside `workspace.toml`. Every setting is off or empty by
5//! default, and a missing file is all defaults. The server reads the file when it starts.
6//!
7//! ```toml
8//! [http]
9//! # Where the HTTP listener binds. Overrides the application's default address.
10//! listen = "127.0.0.1:3173"
11//! # The Host names clients use beyond loopback (a LAN name, a Tailscale name).
12//! allowed_hosts = ["box.tailnet.ts.net"]
13//!
14//! [mcp]
15//! # Serve the application's MCP tools at /mcp, behind an external device's token.
16//! http = true
17//! ```
18
19use std::net::SocketAddr;
20use std::path::{Path, PathBuf};
21
22use sapphire_workspace::AppContext;
23use serde::{Deserialize, Serialize};
24
25use crate::error::{Error, Result};
26
27/// The file's name inside the application's config directory.
28pub const SERVER_CONFIG_FILE: &str = "server.toml";
29
30/// What `server.toml` holds.
31#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
32#[serde(deny_unknown_fields)]
33pub struct ServerConfig {
34    /// The HTTP listener.
35    #[serde(default)]
36    pub http: HttpConfig,
37    /// MCP over HTTP.
38    #[serde(default)]
39    pub mcp: McpConfig,
40}
41
42/// The `[http]` table: the listener every HTTP route shares.
43///
44/// The listener binds only when something is served over it. Every route on it is behind
45/// an external device's bearer token (`sapphire-framework-keys`).
46#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
47#[serde(deny_unknown_fields)]
48pub struct HttpConfig {
49    /// Where to bind. `None` is the application's default address, if it has one.
50    #[serde(default, skip_serializing_if = "Option::is_none")]
51    pub listen: Option<SocketAddr>,
52    /// The `Host` names clients reach the server by, beyond loopback.
53    #[serde(default, skip_serializing_if = "Vec::is_empty")]
54    pub allowed_hosts: Vec<String>,
55}
56
57/// The `[mcp]` table.
58#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
59#[serde(deny_unknown_fields)]
60pub struct McpConfig {
61    /// Serve the application's MCP tools at `/mcp` on the HTTP listener. Off by default.
62    #[serde(default)]
63    pub http: bool,
64}
65
66impl ServerConfig {
67    /// `ctx`'s application's file; `None` while its config directory is unresolved.
68    pub fn path_for_app(ctx: &AppContext) -> Option<PathBuf> {
69        ctx.try_config_dir().map(|dir| dir.join(SERVER_CONFIG_FILE))
70    }
71
72    /// `ctx`'s application's settings. A context whose config directory was never resolved
73    /// has no file to read, and gets the defaults — as it gets no log file.
74    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    /// Read the file at `path`; a missing file is all defaults.
82    ///
83    /// A file that does not parse is an error rather than defaults: a host that asked for
84    /// something and got nothing would not find out why.
85    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}