1use crate::errors::{MCSError, Result};
2use crate::Transport;
3use std::sync::Arc;
4
5#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub enum Durability {
18 Async,
19 Sync,
20}
21
22impl Durability {
23 pub const fn is_sync(self) -> bool {
24 matches!(self, Durability::Sync)
25 }
26}
27
28impl std::str::FromStr for Durability {
29 type Err = String;
30 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
31 match s {
32 "async" | "Async" => Ok(Durability::Async),
33 "sync" | "Sync" => Ok(Durability::Sync),
34 _ => Err(format!("unknown durability '{s}'; expected 'async' or 'sync'")),
35 }
36 }
37}
38
39#[derive(Debug, Clone, Copy)]
44pub struct SqliteTuning {
45 pub mmap_size: i64,
47 pub page_size: i64,
49 pub cache_size_kb: i64,
51 pub busy_timeout_ms: u64,
53 pub journal_size_limit: i64,
55}
56
57impl Default for SqliteTuning {
58 fn default() -> Self {
59 Self {
60 mmap_size: 268_435_456, page_size: 4096, cache_size_kb: 50_000, busy_timeout_ms: 5000,
64 journal_size_limit: 134_217_728, }
66 }
67}
68
69#[derive(Debug, Clone)]
70pub struct Config {
71 pub memory_file_path: String,
72 pub transport: Transport,
73 pub bind_addr: String,
74 pub durability: Durability,
75 pub auth_token: Option<Arc<str>>,
79 pub mmap_size: i64,
80 pub page_size: i64,
82 pub cache_size_kb: i64,
84 pub busy_timeout_ms: u64,
86 pub wal_flush_ms: u64,
89 pub lru_cache_size: usize,
90 pub read_pool_size: usize,
92 pub tls_cert: Option<std::path::PathBuf>,
96 pub tls_key: Option<std::path::PathBuf>,
98 pub vectors_enabled: bool,
101}
102
103pub fn resolve_read_pool_size(requested: usize) -> usize {
108 if requested == 0 {
109 std::thread::available_parallelism()
110 .map(|n| n.get())
111 .unwrap_or(4)
112 .clamp(1, 32)
113 } else {
114 requested.max(1)
115 }
116}
117
118impl Config {
119 pub fn sqlite_tuning(&self) -> SqliteTuning {
122 SqliteTuning {
123 mmap_size: self.mmap_size,
124 page_size: self.page_size,
125 cache_size_kb: self.cache_size_kb,
126 busy_timeout_ms: self.busy_timeout_ms,
127 ..SqliteTuning::default()
128 }
129 }
130
131 pub fn from_args(args: &super::Args) -> Result<Self> {
132 let memory_file_path = args
133 .memory_file
134 .clone()
135 .or_else(|| std::env::var("MEMORY_FILE_PATH").ok())
136 .unwrap_or_else(|| "memory.mcpmem".to_string());
137
138 let auth_token: Option<Arc<str>> = if let Some(t) = args.auth_token.clone() {
142 Some(Arc::from(t.as_str()))
143 } else if let Some(path) = args.auth_token_file.clone() {
144 let contents = std::fs::read_to_string(&path).map_err(|e| {
145 MCSError::InvalidParams(format!("failed to read --auth-token-file '{path}': {e}"))
146 })?;
147 let token = contents.trim();
148 if token.is_empty() {
149 return Err(MCSError::InvalidParams(format!(
150 "--auth-token-file '{path}' is empty; refusing to start with auth disabled"
151 )));
152 }
153 Some(Arc::from(token))
154 } else {
155 std::env::var("MCP_MEMORY_AUTH_TOKEN")
156 .ok()
157 .filter(|t| !t.is_empty())
158 .map(|t| Arc::from(t.as_str()))
159 };
160
161 let durability = if let Ok(env) = std::env::var("MCP_MEMORY_DURABILITY") {
162 env.parse().unwrap_or_else(|e| {
163 tracing::warn!("MCP_MEMORY_DURABILITY parse failed: {e}; falling back to Async");
164 Durability::Async
165 })
166 } else {
167 Durability::Async
168 };
169
170 let tls_cert = args
173 .tls_cert
174 .clone()
175 .or_else(|| std::env::var("MCP_TLS_CERT").ok())
176 .filter(|s| !s.is_empty())
177 .map(std::path::PathBuf::from);
178 let tls_key = args
179 .tls_key
180 .clone()
181 .or_else(|| std::env::var("MCP_TLS_KEY").ok())
182 .filter(|s| !s.is_empty())
183 .map(std::path::PathBuf::from);
184 if tls_cert.is_some() != tls_key.is_some() {
185 return Err(MCSError::InvalidParams(
186 "--tls-cert and --tls-key must be provided together (or both omitted for plaintext HTTP)"
187 .to_string(),
188 ));
189 }
190
191 Ok(Config {
192 memory_file_path,
193 transport: args.transport,
194 bind_addr: args.bind.clone(),
195 durability,
196 auth_token,
197 mmap_size: args.mmap_size,
198 page_size: args.page_size,
199 cache_size_kb: args.cache_size_mb.saturating_mul(1024),
200 busy_timeout_ms: args.busy_timeout_ms,
201 wal_flush_ms: args.wal_flush_ms,
202 lru_cache_size: args.lru_cache_size,
203 read_pool_size: resolve_read_pool_size(args.read_pool_size),
204 tls_cert,
205 tls_key,
206 vectors_enabled: args.vectors,
207 })
208 }
209}
210
211impl Default for Config {
212 fn default() -> Self {
213 Self {
214 memory_file_path: "memory.mcpmem".to_string(),
215 transport: Transport::Stdio,
216 bind_addr: "127.0.0.1:8080".to_string(),
217 durability: Durability::Async,
218 auth_token: None,
219 mmap_size: 268435456,
220 page_size: SqliteTuning::default().page_size,
221 cache_size_kb: SqliteTuning::default().cache_size_kb,
222 busy_timeout_ms: SqliteTuning::default().busy_timeout_ms,
223 wal_flush_ms: 250,
224 lru_cache_size: 10000,
225 read_pool_size: 4,
226 tls_cert: None,
227 tls_key: None,
228 vectors_enabled: false,
229 }
230 }
231}
232
233#[cfg(test)]
234mod tests {
235 use super::*;
236
237 #[test]
238 fn test_resolve_read_pool_size_auto_scales_within_bounds() {
239 let auto = resolve_read_pool_size(0);
240 assert!((1..=32).contains(&auto), "auto pool {auto} out of [1,32]");
241 assert_eq!(
242 auto,
243 std::thread::available_parallelism().map(|n| n.get()).unwrap_or(4).clamp(1, 32)
244 );
245 }
246
247 #[test]
248 fn test_resolve_read_pool_size_honours_explicit_values() {
249 assert_eq!(resolve_read_pool_size(1), 1);
250 assert_eq!(resolve_read_pool_size(8), 8);
251 assert_eq!(resolve_read_pool_size(100), 100);
253 }
254}
255