mcp_memory/lib.rs
1pub mod actions;
2#[cfg(feature = "code")]
3pub mod code;
4#[cfg(feature = "code")]
5pub mod code_registry;
6pub mod config;
7pub mod errors;
8pub mod http;
9pub mod ivf;
10pub mod kg;
11pub mod protocol;
12pub mod server;
13pub mod tls;
14pub mod tools;
15pub mod types;
16pub mod watcher;
17pub mod vector_actions;
18pub mod vector_store;
19
20use clap::{Parser, ValueEnum};
21use usearch::{MetricKind, ScalarKind};
22use vector_store::{IndexKind, VectorConfig};
23
24/// ANN index backend selectable from the CLI.
25#[derive(Clone, Copy, Debug, ValueEnum)]
26pub enum VecIndex {
27 /// usearch HNSW graph index (default): best recall/latency.
28 Hnsw,
29 /// IVF-Flat: k-means partitioned, lighter memory, fast to build/rebuild.
30 Ivf,
31}
32
33impl From<VecIndex> for IndexKind {
34 fn from(v: VecIndex) -> Self {
35 match v {
36 VecIndex::Hnsw => IndexKind::Hnsw,
37 VecIndex::Ivf => IndexKind::Ivf,
38 }
39 }
40}
41
42/// Distance metric for the vector index.
43#[derive(Clone, Copy, Debug, ValueEnum)]
44pub enum VecMetric {
45 /// Cosine similarity (default; good for normalized embeddings).
46 Cos,
47 /// Inner / dot product.
48 Ip,
49 /// Squared Euclidean (L2) distance.
50 L2sq,
51}
52
53impl From<VecMetric> for MetricKind {
54 fn from(m: VecMetric) -> Self {
55 match m {
56 VecMetric::Cos => MetricKind::Cos,
57 VecMetric::Ip => MetricKind::IP,
58 VecMetric::L2sq => MetricKind::L2sq,
59 }
60 }
61}
62
63/// Scalar representation stored in the index (lower precision = less memory).
64#[derive(Clone, Copy, Debug, ValueEnum)]
65pub enum VecQuant {
66 /// 32-bit float (default; full precision).
67 F32,
68 /// 16-bit half-precision IEEE float (half the memory, slight recall loss).
69 F16,
70 /// 16-bit brain float (half the memory, wider range than f16).
71 Bf16,
72 /// 8-bit integer quantization (quarter the memory).
73 I8,
74}
75
76impl From<VecQuant> for ScalarKind {
77 fn from(q: VecQuant) -> Self {
78 match q {
79 VecQuant::F32 => ScalarKind::F32,
80 VecQuant::F16 => ScalarKind::F16,
81 VecQuant::Bf16 => ScalarKind::BF16,
82 VecQuant::I8 => ScalarKind::I8,
83 }
84 }
85}
86
87/// Wire transport the server listens on. The JSON-RPC/MCP semantics are
88/// identical across all three — only the framing differs.
89#[derive(Copy, Clone, Debug, PartialEq, Eq, ValueEnum)]
90#[clap(rename_all = "lowercase")]
91pub enum Transport {
92 /// Newline-delimited JSON-RPC over stdin/stdout (default; for Claude
93 /// Desktop / Claude Code and other process-spawning clients).
94 Stdio,
95 /// Newline-delimited JSON-RPC over a TCP socket (one message per line),
96 /// accepting many concurrent connections.
97 Tcp,
98 /// MCP Streamable HTTP: POST JSON-RPC to `/mcp` (responses as JSON or, when
99 /// the client `Accept`s it, an SSE stream), plus `GET /mcp` for a standalone
100 /// server→client SSE stream.
101 Http,
102}
103
104#[derive(Parser, Debug)]
105#[command(name = "MCP Memory Server")]
106#[command(about = "Knowledge graph memory server for MCP — entities, relations, and observations persisted in SQLite with FTS5 search", long_about = None)]
107pub struct Args {
108 /// Path to the memory file
109 #[arg(short = 'f', long = "memory-file")]
110 pub memory_file: Option<String>,
111
112 /// Transport to listen on: stdio, tcp, or http
113 #[arg(short = 't', long = "transport", value_enum, default_value_t = Transport::Stdio)]
114 pub transport: Transport,
115
116 /// Address to bind for the `tcp` and `http` transports
117 #[arg(short = 'b', long = "bind", default_value = "127.0.0.1:8080")]
118 pub bind: String,
119
120 /// Log level
121 #[arg(short, long, default_value = "info")]
122 pub log_level: String,
123
124 /// Bearer token required on the `tcp` (first line) and `http`
125 /// (`Authorization` header) transports. Overrides `--auth-token-file` and
126 /// the `MCP_MEMORY_AUTH_TOKEN` env var. stdio is never authenticated.
127 #[arg(long = "auth-token")]
128 pub auth_token: Option<String>,
129
130 /// Path to a file whose trimmed contents are the bearer token. An empty
131 /// file is rejected (fail closed). Ignored if `--auth-token` is set.
132 #[arg(long = "auth-token-file")]
133 pub auth_token_file: Option<String>,
134
135 /// SQLite mmap size in bytes (default: 64 MiB).
136 #[arg(long = "mmap-size", default_value_t = 67108864)]
137 pub mmap_size: i64,
138
139 /// SQLite page size in bytes; power of two (default: 4096, matches the Linux
140 /// page / filesystem block size). Only applies to a freshly-created database.
141 #[arg(long = "page-size", default_value_t = 4096)]
142 pub page_size: i64,
143
144 /// SQLite page cache size in MiB (default: 32).
145 #[arg(long = "cache-size-mb", default_value_t = 32)]
146 pub cache_size_mb: i64,
147
148 /// SQLite busy timeout in milliseconds (default: 5000).
149 #[arg(long = "busy-timeout-ms", default_value_t = 5000)]
150 pub busy_timeout_ms: u64,
151
152 /// Interval in milliseconds for a background `wal_checkpoint(PASSIVE)` that
153 /// bounds the durability window in async mode (default: 500). 0 disables it.
154 #[arg(long = "wal-flush-ms", default_value_t = 500)]
155 pub wal_flush_ms: u64,
156
157 /// Entity-metadata LRU cache capacity (0 falls back to 10000).
158 #[arg(long = "lru-cache-size", default_value_t = 10000)]
159 pub lru_cache_size: usize,
160
161 /// Number of read-only SQLite connections backing concurrent reads. WAL
162 /// mode allows readers to run in parallel with each other and the single
163 /// writer; a larger pool raises read concurrency at the cost of a little
164 /// memory (each connection carries its own page cache). `0` (default)
165 /// auto-scales to the CPU count, clamped to [1, 32].
166 #[arg(long = "read-pool-size", default_value_t = 4)]
167 pub read_pool_size: usize,
168
169 /// Path to a PEM certificate chain to serve the `http` transport over TLS
170 /// (HTTPS). Requires --tls-key. Falls back to the MCP_TLS_CERT env var.
171 /// When unset, the `http` transport stays plaintext.
172 #[arg(long = "tls-cert")]
173 pub tls_cert: Option<String>,
174
175 /// Path to the PEM private key matching --tls-cert. Falls back to the
176 /// MCP_TLS_KEY env var.
177 #[arg(long = "tls-key")]
178 pub tls_key: Option<String>,
179
180 /// Enable vector / semantic search: exposes the `vector_*` and
181 /// `hybrid_search` tools backed by a usearch HNSW index. Off by default
182 /// (a pure knowledge-graph server). The `--embedding-dims` / `--vec-*` flags
183 /// only take effect when this is set.
184 #[arg(long = "vectors", default_value_t = false)]
185 pub vectors: bool,
186
187 /// Enable tree-sitter code-symbol indexing: exposes the `code_index`,
188 /// `code_outline`, `code_search`, and `code_get_symbol` tools, which parse
189 /// source files and store functions/classes/methods (and their
190 /// call/define edges) in the graph. On by default (when built with the `code`
191 /// feature, which is on by default).
192 #[arg(long = "code", default_value_t = true)]
193 pub code: bool,
194
195 /// Embedding dimension for vector search (default: 384). Requires --vectors.
196 #[arg(long = "embedding-dims", default_value_t = 384)]
197 pub embedding_dims: u32,
198
199 /// Distance metric for the vector index. Requires --vectors.
200 #[arg(long = "vec-metric", value_enum, default_value_t = VecMetric::Cos)]
201 pub vec_metric: VecMetric,
202
203 /// Scalar quantization for the vector index (lower = less memory). Requires --vectors.
204 #[arg(long = "vec-quantization", value_enum, default_value_t = VecQuant::F32)]
205 pub vec_quantization: VecQuant,
206
207 /// HNSW graph degree `M` (higher = better recall, more memory). Requires --vectors.
208 #[arg(long = "vec-connectivity", default_value_t = 16)]
209 pub vec_connectivity: usize,
210
211 /// HNSW `efConstruction` (higher = better index quality, slower inserts). Requires --vectors.
212 #[arg(long = "vec-expansion-add", default_value_t = 200)]
213 pub vec_expansion_add: usize,
214
215 /// HNSW `efSearch` (higher = better recall, slower queries). Requires --vectors.
216 #[arg(long = "vec-expansion-search", default_value_t = 50)]
217 pub vec_expansion_search: usize,
218
219 /// ANN index backend: `hnsw` (default) or `ivf` (IVF-Flat). Requires --vectors.
220 #[arg(long = "vec-index", value_enum, default_value_t = VecIndex::Hnsw)]
221 pub vec_index: VecIndex,
222
223 /// IVF: number of Voronoi cells / centroids (default: 256). Requires --vec-index ivf.
224 #[arg(long = "ivf-nlist", default_value_t = 256)]
225 pub ivf_nlist: usize,
226
227 /// IVF: cells probed per query — higher = better recall, slower (default: 8).
228 /// Requires --vec-index ivf.
229 #[arg(long = "ivf-nprobe", default_value_t = 8)]
230 pub ivf_nprobe: usize,
231}
232
233impl Args {
234 /// Build the vector index configuration from the `--embedding-dims` /
235 /// `--vec-*` / `--ivf-*` flags. Only meaningful when `--vectors` is set.
236 pub fn vector_config(&self) -> VectorConfig {
237 VectorConfig {
238 dims: self.embedding_dims,
239 index_kind: self.vec_index.into(),
240 metric: self.vec_metric.into(),
241 quantization: self.vec_quantization.into(),
242 connectivity: self.vec_connectivity,
243 expansion_add: self.vec_expansion_add,
244 expansion_search: self.vec_expansion_search,
245 ivf_nlist: self.ivf_nlist,
246 ivf_nprobe: self.ivf_nprobe,
247 }
248 }
249}