Skip to main content

mcp_memory/
config.rs

1use crate::errors::{MCSError, Result};
2use crate::Transport;
3use std::sync::Arc;
4
5/// How aggressively to push WAL writes to durable storage before acknowledging
6/// the client.
7///
8/// The default [`Async`](Durability::Async) flushes to the kernel page cache
9/// and returns immediately; the background sync thread calls `fsync` within
10/// ~1 second. Journal-mode filesystems (ext4, APFS, NTFS) typically absorb a
11/// power loss within that window.
12///
13/// [`Sync`](Durability::Sync) calls `fsync` before returning, confirming the
14/// data is on stable media. Use this when every write must survive an immediate
15/// power failure, at the cost of higher write latency.
16#[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/// Tunable SQLite pragmas applied when opening the database. `page_size` and
40/// `auto_vacuum` only take effect on a freshly-created database (they are fixed
41/// once the file has content); the rest apply on every open. Defaults target a
42/// Linux host (4 KiB pages match the OS page / filesystem block size).
43#[derive(Debug, Clone, Copy)]
44pub struct SqliteTuning {
45    /// `PRAGMA mmap_size` in bytes.
46    pub mmap_size: i64,
47    /// `PRAGMA page_size` in bytes (fresh DB only). Must be a power of two.
48    pub page_size: i64,
49    /// `PRAGMA cache_size` magnitude in KiB (applied as the negative form).
50    pub cache_size_kb: i64,
51    /// `PRAGMA busy_timeout` in milliseconds.
52    pub busy_timeout_ms: u64,
53    /// `PRAGMA journal_size_limit` in bytes.
54    pub journal_size_limit: i64,
55}
56
57impl Default for SqliteTuning {
58    fn default() -> Self {
59        Self {
60            mmap_size: 268_435_456,          // 256 MiB
61            page_size: 4096,                 // 4 KiB — matches Linux page/fs block
62            cache_size_kb: 50_000,           // ~50 MiB
63            busy_timeout_ms: 5000,
64            journal_size_limit: 134_217_728, // 128 MiB
65        }
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    /// Optional bearer token required on the `tcp` and `http` transports. When
76    /// `None`, those transports accept unauthenticated connections (stdio is
77    /// always local and never authenticated).
78    pub auth_token: Option<Arc<str>>,
79    pub mmap_size: i64,
80    /// `PRAGMA page_size` in bytes (fresh DB only).
81    pub page_size: i64,
82    /// `PRAGMA cache_size` magnitude in KiB.
83    pub cache_size_kb: i64,
84    /// `PRAGMA busy_timeout` in milliseconds.
85    pub busy_timeout_ms: u64,
86    /// Interval in milliseconds for the background `wal_checkpoint(PASSIVE)`
87    /// flush. `0` disables it (rely on SQLite auto-checkpoint + maintenance).
88    pub wal_flush_ms: u64,
89    pub lru_cache_size: usize,
90    /// Size of the read-only connection pool (concurrent reads). Always >= 1.
91    pub read_pool_size: usize,
92    /// PEM certificate chain for serving the `http` transport over TLS (HTTPS).
93    /// `None` (the default) keeps the transport plaintext. Engaged only when
94    /// both `tls_cert` and `tls_key` are set.
95    pub tls_cert: Option<std::path::PathBuf>,
96    /// PEM private key matching `tls_cert`.
97    pub tls_key: Option<std::path::PathBuf>,
98    /// Enable the vector / semantic-search subsystem (`vector_*` + `hybrid_search`
99    /// tools backed by a usearch HNSW index). Off by default.
100    pub vectors_enabled: bool,
101}
102
103/// Resolve the read-only connection-pool size. `0` means "auto": scale to the
104/// number of available CPUs (clamped to `[1, 32]` so a many-core host doesn't
105/// open an unreasonable number of connections, each carrying its own page
106/// cache). Any explicit value is honoured but floored at 1.
107pub 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    /// Build the SQLite pragma tuning from this config, keeping the fixed
120    /// `journal_size_limit` default.
121    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        // Resolve the auth token from --auth-token, then --auth-token-file, then
139        // the MCP_MEMORY_AUTH_TOKEN env var. A configured-but-empty token file
140        // is a hard error: fail closed rather than silently disabling auth.
141        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        // TLS cert/key for the `http` transport, from CLI flags or env vars.
171        // Both must be supplied together; one without the other is a hard error.
172        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        // A huge explicit value is honoured (only the auto path is clamped).
252        assert_eq!(resolve_read_pool_size(100), 100);
253    }
254}
255