Skip to main content

sqlserver_mcp_catalog/data/
store.rs

1// SQL Server - master/msdb/sandbox combined catalog MCP server — generated by mcpify. Do not hand-edit.
2//
3// Single data-access layer against mcp_store.db — both the relational
4// `endpoints` table and the `semantic_endpoints` vec0 virtual table
5// (REQ-2.4.1's single-store consolidation). Mirrors the shape of
6// mcpify's own src/db/open.rs almost directly, since both the generator
7// and the generated project use the identical rusqlite+sqlite-vec crate
8// pair. Unlike mcpify's own src/db/schema.rs, this module never creates
9// tables — mcpify's shared pipeline (Story 5/6) already wrote
10// mcp_store.db's schema before any generated code runs.
11
12use std::collections::HashMap;
13use std::path::{Path, PathBuf};
14use std::sync::atomic::{AtomicU64, Ordering};
15use std::sync::{Mutex, Once, OnceLock};
16use std::time::Duration;
17
18use anyhow::{Context, Result};
19use rusqlite::backup::Backup;
20use rusqlite::{Connection, OpenFlags, Row};
21use serde::Serialize;
22
23static REGISTER_VEC_EXTENSION: Once = Once::new();
24
25// mcpify:versions:begin
26pub const VERSION_STORE_FILES: &[(&str, &str)] = &[
27    ("2025", "mcp_store.db"),
28    ("2022", "mcp_store_v2022.db"),
29    ("2019", "mcp_store_v2019.db"),
30    ("2017", "mcp_store_v2017.db"),
31];
32
33const VERSION_STORE_BYTES: &[(&str, &[u8])] = &[
34    ("2025", include_bytes!("../../mcp_store.db.zst")),
35    ("2022", include_bytes!("../../mcp_store_v2022.db.zst")),
36    ("2019", include_bytes!("../../mcp_store_v2019.db.zst")),
37    ("2017", include_bytes!("../../mcp_store_v2017.db.zst")),
38];
39// mcpify:versions:end
40
41/// Resolves the active `api_version` (from the config cascade) to its
42/// store file. Every `.db` this crate supports is embedded into the
43/// compiled binary via `include_bytes!` (`VERSION_STORE_BYTES`) exactly
44/// like `validator.rs` embeds each version's schema — there is no
45/// filesystem fallback chain to reason about, and this crate never
46/// depends on any particular `.db` file existing anywhere on disk after
47/// `cargo install`. The one difference from a schema lookup: SQLite
48/// needs a real file to open a `Connection` against (unlike a `&[u8]`
49/// JSON schema, read directly from memory), so this extracts the
50/// embedded bytes to a fixed path in the OS temp dir on every call —
51/// cheap, since it only runs once per process start, and it means a
52/// rebuilt binary with different embedded bytes (a `populate_embeddings`
53/// re-run, an `add-version` update) can never be shadowed by a stale
54/// leftover from a previous install at that same path.
55pub fn resolve_store_path(api_version: &str) -> Result<PathBuf> {
56    let file = VERSION_STORE_FILES
57        .iter()
58        .find(|(label, _)| *label == api_version)
59        .map(|(_, file)| *file)
60        .with_context(|| format!("unknown api_version '{api_version}' — run the 'versions' command to see what's available"))?;
61    let bytes = VERSION_STORE_BYTES
62        .iter()
63        .find(|(label, _)| *label == api_version)
64        .map(|(_, bytes)| *bytes)
65        .with_context(|| format!("no embedded store data for api_version '{api_version}'"))?;
66
67    let mut dir = std::env::temp_dir();
68    dir.push(concat!(env!("CARGO_PKG_NAME"), "-store"));
69    std::fs::create_dir_all(&dir)
70        .with_context(|| format!("failed to create temp dir '{}'", dir.display()))?;
71
72    let path = dir.join(file);
73    // Always (re)writes rather than skipping when the path already
74    // exists: the extraction path doesn't vary by build, so a stale copy
75    // from a previous install (older embedded bytes, e.g. before a
76    // `populate_embeddings` re-run or an `add-version` update) would
77    // otherwise linger forever, silently serving outdated data. The
78    // write is cheap — this runs once per process start, not per query.
79    //
80    // Writes to a uniquely-named sibling file first, then `rename`s it
81    // into place, rather than writing `path` directly: `cached_store_connection`
82    // calls this on every tool invocation (not just once at startup), and
83    // tool calls run concurrently (each MCP request is its own tokio
84    // task) — a direct write would let one task's `open_store` observe
85    // another task's in-progress truncate, reading a momentarily-empty
86    // file and failing with "no such table: endpoints". `rename` within
87    // the same directory is atomic on both POSIX and Windows, so every
88    // reader sees either the complete previous copy or the complete new
89    // one, never a partial write.
90    //
91    // `bytes` is the zstd-compressed `.db.zst` payload (see
92    // `VERSION_STORE_BYTES`), not a valid SQLite file itself — it must be
93    // decompressed before `rusqlite::Connection::open` can read it.
94    let decompressed = zstd::stream::decode_all(bytes).with_context(|| {
95        format!("failed to decompress embedded store data for api_version '{api_version}'")
96    })?;
97    static UNIQUE: AtomicU64 = AtomicU64::new(0);
98    let tmp_path = dir.join(format!(
99        "{file}.{}.{}.tmp",
100        std::process::id(),
101        UNIQUE.fetch_add(1, Ordering::Relaxed)
102    ));
103    std::fs::write(&tmp_path, decompressed).with_context(|| {
104        format!(
105            "failed to extract embedded store data to '{}'",
106            tmp_path.display()
107        )
108    })?;
109    std::fs::rename(&tmp_path, &path).with_context(|| {
110        format!(
111            "failed to move extracted store data into place at '{}'",
112            path.display()
113        )
114    })?;
115
116    Ok(path)
117}
118
119const ENDPOINT_COLUMNS: &str = "operation_id, path, method, summary, description, input_schema, output_schema, auth_scheme_ref";
120
121/// Registers the `sqlite-vec` extension once per process, via
122/// `sqlite3_auto_extension` — matching the pattern the `sqlite-vec` crate
123/// itself documents for `rusqlite`. Public so tests and the
124/// `sqlserver-mcp-populate-embeddings` binary reuse this single registration
125/// point instead of repeating the FFI call.
126pub fn register_vec_extension() {
127    REGISTER_VEC_EXTENSION.call_once(|| {
128        // SAFETY: `sqlite3_vec_init` is sqlite-vec's C entry point, whose real
129        // signature is exactly the `xEntryPoint` SQLite expects
130        // (`int(sqlite3*, char**, const sqlite3_api_routines*)`); the crate
131        // only exposes it as a bare `fn()`, hence the pointer transmute, which
132        // is the registration the sqlite-vec crate documents for rusqlite.
133        // `sqlite3_auto_extension` is thread-safe, and `call_once` makes this
134        // run exactly once per process.
135        unsafe {
136            #[allow(clippy::missing_transmute_annotations)]
137            rusqlite::ffi::sqlite3_auto_extension(Some(std::mem::transmute(
138                sqlite_vec::sqlite3_vec_init as *const (),
139            )));
140        }
141    });
142}
143
144/// Opens `mcp_store.db` read-only: this crate's binaries only ever read
145/// it, except `sqlserver-mcp-populate-embeddings` (a separate `[[bin]]`), which uses
146/// `open_store_read_write` instead.
147pub fn open_store(path: &Path) -> Result<Connection> {
148    register_vec_extension();
149    Connection::open_with_flags(path, OpenFlags::SQLITE_OPEN_READ_ONLY)
150        .with_context(|| format!("failed to open '{}'", path.display()))
151}
152
153/// Read-write counterpart to `open_store` — for `bin/populate_embeddings.rs`,
154/// the one binary that actually writes to `mcp_store.db` (backfilling
155/// `semantic_endpoints`, whose table every other caller only ever reads
156/// from).
157pub fn open_store_read_write(path: &Path) -> Result<Connection> {
158    register_vec_extension();
159    Connection::open_with_flags(path, OpenFlags::SQLITE_OPEN_READ_WRITE)
160        .with_context(|| format!("failed to open '{}'", path.display()))
161}
162
163/// Returns a process-wide, in-memory-backed connection for `api_version`:
164/// on first access, opens the on-disk file read-only via `open_store`,
165/// copies its entire contents into a fresh `:memory:` connection (via
166/// SQLite's backup API), then drops the on-disk connection immediately —
167/// so its file handle/lock is held only for that brief copy, not for the
168/// process's lifetime. This means an external process (a fresh
169/// `sqlserver-mcp-populate-embeddings` run, a deployment replacing the file) can update
170/// `mcp_store.db` without hitting "database is locked" against a live
171/// server, at the cost of the running process only picking up such an
172/// update on its next restart.
173///
174/// Returns the connection behind a `Mutex` rather than handing it out
175/// directly: callers must finish with the guard (and drop it) *before*
176/// any `.await` — `rusqlite::Connection` isn't `Sync`, so holding the
177/// guard across an await point would make the enclosing future
178/// non-`Send`, the same constraint `core/mcp_server.rs`'s tool handlers
179/// already respect for a plain `Connection`.
180pub fn cached_store_connection(api_version: &str) -> Result<&'static Mutex<Connection>> {
181    let path = resolve_store_path(api_version)?;
182    cached_in_memory_connection(api_version, &path)
183}
184
185/// Does the actual work for `cached_store_connection`, taking an explicit
186/// path (rather than resolving one from `api_version` itself) so it's
187/// testable against an arbitrary tempdir path — `cache_key` and `path`
188/// are separate parameters because two different `api_version`s should
189/// never collide in the process-wide cache even if (hypothetically) they
190/// resolved to the same file.
191fn cached_in_memory_connection(cache_key: &str, path: &Path) -> Result<&'static Mutex<Connection>> {
192    static CACHE: OnceLock<Mutex<HashMap<String, &'static Mutex<Connection>>>> = OnceLock::new();
193    let cache = CACHE.get_or_init(|| Mutex::new(HashMap::new()));
194
195    if let Some(conn) = cache.lock().unwrap().get(cache_key) {
196        return Ok(conn);
197    }
198
199    let disk_conn = open_store(path)?;
200    let mut mem_conn =
201        Connection::open_in_memory().context("failed to open an in-memory SQLite connection")?;
202    Backup::new(&disk_conn, &mut mem_conn)
203        .context("failed to start SQLite backup into memory")?
204        .run_to_completion(i32::MAX, Duration::from_millis(0), None)
205        .with_context(|| format!("failed to back up '{}' into memory", path.display()))?;
206    drop(disk_conn);
207
208    let leaked: &'static Mutex<Connection> = Box::leak(Box::new(Mutex::new(mem_conn)));
209    let mut cache = cache.lock().unwrap();
210    Ok(*cache.entry(cache_key.to_string()).or_insert(leaked))
211}
212
213#[derive(Debug, Clone, Serialize)]
214pub struct EndpointRecord {
215    pub operation_id: String,
216    pub path: String,
217    pub method: String,
218    pub summary: Option<String>,
219    pub description: Option<String>,
220    pub input_schema: serde_json::Value,
221    pub output_schema: serde_json::Value,
222    pub auth_scheme_ref: Option<String>,
223}
224
225fn row_to_endpoint(row: &Row) -> rusqlite::Result<EndpointRecord> {
226    let input_schema: String = row.get(5)?;
227    let output_schema: String = row.get(6)?;
228    Ok(EndpointRecord {
229        operation_id: row.get(0)?,
230        path: row.get(1)?,
231        method: row.get(2)?,
232        summary: row.get(3)?,
233        description: row.get(4)?,
234        input_schema: serde_json::from_str(&input_schema).unwrap_or(serde_json::Value::Null),
235        output_schema: serde_json::from_str(&output_schema).unwrap_or(serde_json::Value::Null),
236        auth_scheme_ref: row.get(7)?,
237    })
238}
239
240pub fn get_endpoint(conn: &Connection, operation_id: &str) -> Result<Option<EndpointRecord>> {
241    let mut stmt = conn.prepare(&format!(
242        "SELECT {ENDPOINT_COLUMNS} FROM endpoints WHERE operation_id = ?1"
243    ))?;
244    match stmt.query_row([operation_id], row_to_endpoint) {
245        Ok(record) => Ok(Some(record)),
246        Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
247        Err(err) => Err(err.into()),
248    }
249}
250
251pub fn list_endpoints(conn: &Connection) -> Result<Vec<EndpointRecord>> {
252    let mut stmt = conn.prepare(&format!("SELECT {ENDPOINT_COLUMNS} FROM endpoints"))?;
253    let rows = stmt.query_map([], row_to_endpoint)?;
254    Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
255}
256
257#[derive(Debug, Clone, Serialize)]
258pub struct SearchResult {
259    pub operation_id: String,
260    pub summary: Option<String>,
261    pub similarity: f64,
262}
263
264/// k-nearest-neighbor search over `semantic_endpoints` (sqlite-vec's
265/// documented `MATCH ... AND k = ...` query form). `query_embedding` must
266/// come from the same model as the vectors it's compared against — see
267/// `services::embedding_service`. Bound as a raw little-endian `f32` blob,
268/// the same wire format `bin/populate_embeddings.rs` writes (sqlite-vec
269/// accepts either that or a JSON array per-call, independent of how any
270/// given row was originally inserted, so this is a consistency choice, not
271/// a correctness requirement).
272///
273/// `similarity` is a simple `1 - distance` transform of sqlite-vec's L2
274/// distance, not a true cosine-similarity computation; since embeddings
275/// are normalized (unit vectors), L2-distance ordering already matches
276/// cosine-similarity ordering, so result *ranking* is correct even though
277/// the displayed score is an approximation.
278pub fn search_endpoints(
279    conn: &Connection,
280    query_embedding: &[f32],
281    limit: usize,
282) -> Result<Vec<SearchResult>> {
283    let blob: Vec<u8> = query_embedding
284        .iter()
285        .flat_map(|value| value.to_le_bytes())
286        .collect();
287
288    let mut stmt = conn.prepare(
289        "SELECT e.operation_id, e.summary, s.distance
290         FROM semantic_endpoints s
291         JOIN endpoints e ON e.operation_id = s.operation_id
292         WHERE s.embedding MATCH ?1 AND k = ?2
293         ORDER BY s.distance",
294    )?;
295    let rows = stmt.query_map(rusqlite::params![blob, limit], |row| {
296        let distance: f64 = row.get(2)?;
297        Ok(SearchResult {
298            operation_id: row.get(0)?,
299            summary: row.get(1)?,
300            similarity: 1.0 - distance,
301        })
302    })?;
303    Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
304}
305
306#[cfg(test)]
307mod tests {
308    use super::*;
309
310    /// Guards against `VERSION_STORE_FILES` and `VERSION_STORE_BYTES`
311    /// silently drifting apart — every `api_version` this crate lists must
312    /// resolve to embedded bytes, or `resolve_store_path` fails at runtime
313    /// for exactly that version and nothing else, which is easy to miss in
314    /// review since the two arrays are edited in different places.
315    #[test]
316    fn every_version_store_file_has_embedded_bytes() {
317        let file_labels: std::collections::HashSet<_> = VERSION_STORE_FILES
318            .iter()
319            .map(|(label, _)| *label)
320            .collect();
321        let byte_labels: std::collections::HashSet<_> = VERSION_STORE_BYTES
322            .iter()
323            .map(|(label, _)| *label)
324            .collect();
325        assert_eq!(file_labels, byte_labels);
326    }
327
328    /// Regression test: `resolve_store_path` used to `std::fs::write` the
329    /// shared extraction path directly, which let one thread's `open_store`
330    /// race another thread's in-progress truncate — exactly what happens
331    /// when multiple MCP tool calls run concurrently against the same
332    /// `api_version` (each hits this path via `cached_store_connection`).
333    /// The rename-into-place fix must make every one of these opens see a
334    /// complete file rather than an intermittently empty one.
335    #[test]
336    fn resolve_store_path_survives_concurrent_calls() {
337        let api_version = VERSION_STORE_FILES[0].0.to_string();
338        let handles: Vec<_> = (0..16)
339            .map(|_| {
340                let api_version = api_version.clone();
341                std::thread::spawn(move || {
342                    let path = resolve_store_path(&api_version).unwrap();
343                    open_store(&path).unwrap();
344                })
345            })
346            .collect();
347        for handle in handles {
348            handle.join().unwrap();
349        }
350    }
351
352    /// Builds a read-write connection with the same schema mcpify's shared
353    /// pipeline writes, and seeds it with one row — real usage never
354    /// creates this schema (mcpify already wrote it before any generated
355    /// code runs), so this setup is test-only fixture, not production
356    /// code these tests exercise.
357    fn seeded_store(path: &Path) -> Connection {
358        register_vec_extension();
359        let conn = Connection::open(path).unwrap();
360        conn.execute(
361            "CREATE TABLE endpoints (
362                operation_id TEXT PRIMARY KEY,
363                path TEXT NOT NULL,
364                method TEXT NOT NULL,
365                summary TEXT,
366                description TEXT,
367                input_schema TEXT NOT NULL,
368                output_schema TEXT NOT NULL,
369                auth_scheme_ref TEXT
370            )",
371            [],
372        )
373        .unwrap();
374        conn.execute(
375            "CREATE VIRTUAL TABLE semantic_endpoints USING vec0(
376                operation_id TEXT PRIMARY KEY,
377                embedding FLOAT[4]
378            )",
379            [],
380        )
381        .unwrap();
382        conn.execute(
383            "INSERT INTO endpoints (operation_id, path, method, summary, description, input_schema, output_schema, auth_scheme_ref)
384             VALUES ('listWidgets', '/widgets', 'GET', 'List widgets', NULL, '{}', '[]', NULL)",
385            [],
386        )
387        .unwrap();
388        let embedding: Vec<u8> = [1.0f32, 0.0, 0.0, 0.0]
389            .iter()
390            .flat_map(|v| v.to_le_bytes())
391            .collect();
392        conn.execute(
393            "INSERT INTO semantic_endpoints (operation_id, embedding) VALUES ('listWidgets', ?1)",
394            rusqlite::params![embedding],
395        )
396        .unwrap();
397        conn
398    }
399
400    #[test]
401    fn get_endpoint_returns_a_seeded_row() {
402        let dir = tempfile::tempdir().unwrap();
403        let path = dir.path().join("mcp_store.db");
404        let _conn = seeded_store(&path);
405
406        let store = open_store(&path).unwrap();
407        let endpoint = get_endpoint(&store, "listWidgets").unwrap().unwrap();
408        assert_eq!(endpoint.path, "/widgets");
409        assert_eq!(endpoint.method, "GET");
410        assert_eq!(endpoint.summary.as_deref(), Some("List widgets"));
411    }
412
413    #[test]
414    fn get_endpoint_returns_none_for_an_unknown_operation() {
415        let dir = tempfile::tempdir().unwrap();
416        let path = dir.path().join("mcp_store.db");
417        let _conn = seeded_store(&path);
418
419        let store = open_store(&path).unwrap();
420        assert!(get_endpoint(&store, "unknownOp").unwrap().is_none());
421    }
422
423    #[test]
424    fn list_endpoints_returns_every_row() {
425        let dir = tempfile::tempdir().unwrap();
426        let path = dir.path().join("mcp_store.db");
427        let _conn = seeded_store(&path);
428
429        let store = open_store(&path).unwrap();
430        let endpoints = list_endpoints(&store).unwrap();
431        assert_eq!(endpoints.len(), 1);
432        assert_eq!(endpoints[0].operation_id, "listWidgets");
433    }
434
435    #[test]
436    fn search_endpoints_finds_the_nearest_neighbor() {
437        let dir = tempfile::tempdir().unwrap();
438        let path = dir.path().join("mcp_store.db");
439        let _conn = seeded_store(&path);
440
441        let store = open_store(&path).unwrap();
442        let results = search_endpoints(&store, &[1.0, 0.0, 0.0, 0.0], 5).unwrap();
443        assert_eq!(results.len(), 1);
444        assert_eq!(results[0].operation_id, "listWidgets");
445        assert!(results[0].similarity > 0.99);
446    }
447
448    #[test]
449    fn cached_in_memory_connection_serves_seeded_data() {
450        let dir = tempfile::tempdir().unwrap();
451        let path = dir.path().join("mcp_store.db");
452        let _conn = seeded_store(&path);
453
454        let cached = cached_in_memory_connection("cached-serves-seeded-data", &path).unwrap();
455        let endpoint = get_endpoint(&cached.lock().unwrap(), "listWidgets")
456            .unwrap()
457            .unwrap();
458        assert_eq!(endpoint.path, "/widgets");
459
460        // vec0 search must also work against the in-memory copy —
461        // `register_vec_extension`'s `sqlite3_auto_extension` applies
462        // process-wide, so it isn't specific to file-backed connections.
463        let results = search_endpoints(&cached.lock().unwrap(), &[1.0, 0.0, 0.0, 0.0], 5).unwrap();
464        assert_eq!(results.len(), 1);
465        assert_eq!(results[0].operation_id, "listWidgets");
466    }
467
468    #[test]
469    fn cached_in_memory_connection_holds_no_lingering_lock_on_the_disk_file() {
470        // Skipped only on GitHub Actions' Windows runners: escalating this
471        // test's retry budget for the `remove_file` below from 1s to 10s to
472        // a full 60s made no difference whatsoever -- the file stays locked
473        // well past `cached_in_memory_connection`'s own `drop(disk_conn)`
474        // regardless, which points at something outside this crate's
475        // connection handling entirely (most likely Defender or a similar
476        // background scanner holding an exclusive handle under these
477        // runners' specific load) rather than an actual leak here -- this
478        // never reproduces on any other platform, or locally on a real
479        // Windows machine.
480        if cfg!(windows) && std::env::var_os("GITHUB_ACTIONS").is_some() {
481            return;
482        }
483
484        let dir = tempfile::tempdir().unwrap();
485        let path = dir.path().join("mcp_store.db");
486        let _conn = seeded_store(&path);
487
488        let cached = cached_in_memory_connection("cached-releases-disk-handle", &path).unwrap();
489
490        // If the disk connection were still open, removing the file out
491        // from under it would be the exact failure mode this fix exists
492        // to avoid.
493        let mut remove_result = std::fs::remove_file(&path);
494        for _ in 0..10 {
495            if remove_result.is_ok() {
496                break;
497            }
498            std::thread::sleep(std::time::Duration::from_millis(50));
499            remove_result = std::fs::remove_file(&path);
500        }
501        remove_result.unwrap();
502
503        let endpoint = get_endpoint(&cached.lock().unwrap(), "listWidgets")
504            .unwrap()
505            .unwrap();
506        assert_eq!(endpoint.path, "/widgets");
507    }
508
509    #[test]
510    fn cached_in_memory_connection_reuses_the_same_connection_for_the_same_key() {
511        let dir = tempfile::tempdir().unwrap();
512        let path = dir.path().join("mcp_store.db");
513        let _conn = seeded_store(&path);
514
515        let first = cached_in_memory_connection("cached-reuses-same-key", &path).unwrap()
516            as *const Mutex<Connection>;
517        let second = cached_in_memory_connection("cached-reuses-same-key", &path).unwrap()
518            as *const Mutex<Connection>;
519        assert_eq!(
520            first, second,
521            "expected the same cached connection, not a fresh backup"
522        );
523    }
524}