Skip to main content

sqlserver_mcp_catalog/services/
embedding_service.rs

1// SQL Server 2025 - master/msdb/sandbox combined catalog MCP server.
2//
3// Single source of truth for embedding computation. bin/populate_embeddings.rs
4// (indexing time) and tools/search_tool.rs (live query time) both call
5// `embed()` from here, so the two are structurally guaranteed to share the
6// same model and vector space.
7//
8// mcpify's originally-generated `all-mpnet-base-v2` at its native 768
9// dimensions -- also mcpify's own generator hard-code for the
10// `semantic_endpoints` vec0 table's column width (`mcpify/src/db/schema.rs`,
11// not something this project's source controls), so this module's model
12// and every `mcp_store*.db.zst` file mcpify produces always agree on
13// dimension with no extra resize step needed between a `mcpify sync` and
14// `populate_embeddings`.
15//
16// A smaller 384-dim model (`all-MiniLM-L6-v2`) was tried at one point to
17// fit crates.io's 10 MiB package-size limit, back when this project's
18// stores were committed uncompressed -- with 4 SQL Server versions each
19// embedding ~700-800 operations, 768-dim float32 vectors alone pushed the
20// packaged crate right to that limit. Since then the stores were switched
21// to zstd-compressed (level 19) `.db.zst` embeds (see src/data/store.rs),
22// and re-measuring `cargo package` at 768-dim against the current catalog
23// came back at 8.5 MiB compressed -- comfortably under the limit again
24// (embedding vectors themselves are close to incompressible, so the
25// compression gain comes from the surrounding relational/schema data, not
26// the vectors) -- so the switch back to the full 768-dim model for better
27// `search` tool relevance was safe to make permanent.
28
29use std::sync::{Mutex, OnceLock};
30
31use fastembed::{EmbeddingModel, TextEmbedding, TextInitOptions};
32
33fn model() -> &'static Mutex<TextEmbedding> {
34    static MODEL: OnceLock<Mutex<TextEmbedding>> = OnceLock::new();
35    MODEL.get_or_init(|| {
36        // Downloads on first use and caches locally afterward (no network
37        // needed once cached). `.expect()` matches this project's other
38        // unrecoverable-startup-error handling: nothing useful can happen
39        // if the model can't be fetched/loaded.
40        Mutex::new(
41            TextEmbedding::try_new(TextInitOptions::new(EmbeddingModel::AllMpnetBaseV2))
42                .expect("failed to load the all-mpnet-base-v2 embedding model"),
43        )
44    })
45}
46
47/// Computes a 768-dim embedding vector for `text`, mean-pooled and
48/// normalized (fastembed's default behavior for this model, replicating
49/// the sentence-transformers reference implementation).
50pub fn embed(text: &str) -> anyhow::Result<Vec<f32>> {
51    let model = model();
52    let mut model = model.lock().unwrap();
53    let mut embeddings = model.embed(vec![text], None)?;
54    embeddings
55        .pop()
56        .ok_or_else(|| anyhow::anyhow!("embedding model returned no output for the given text"))
57}