Skip to main content

sqlserver_mcp_catalog/tools/
search_tool.rs

1// SQL Server 2025 - master/msdb/sandbox combined catalog MCP server — generated by mcpify. Do not hand-edit.
2
3use rusqlite::Connection;
4
5use crate::data::store::search_endpoints;
6use crate::services::embedding_service::embed;
7
8/// Cheap diagnostic: compares `semantic_endpoints` row count against
9/// `endpoints` row count for the store behind `conn`. A store can end up
10/// with `endpoints` rows but no matching `semantic_endpoints` rows if the
11/// `populate-embeddings` step silently skipped or partially failed some
12/// rows — this surfaces that as a warning without changing the
13/// success/`[]` return contract for legitimately-empty search results.
14fn warn_if_embeddings_incomplete(conn: &Connection) {
15    let counts: rusqlite::Result<(i64, i64)> = conn.query_row(
16        "SELECT (SELECT COUNT(*) FROM endpoints), (SELECT COUNT(*) FROM semantic_endpoints)",
17        [],
18        |row| Ok((row.get(0)?, row.get(1)?)),
19    );
20    if let Ok((endpoints_count, semantic_count)) = counts
21        && semantic_count < endpoints_count
22    {
23        tracing::warn!(
24            endpoints_count,
25            semantic_count,
26            "semantic_endpoints is missing {} row(s) compared to endpoints — search results \
27             may be incomplete; re-run populate-embeddings for this store",
28            endpoints_count - semantic_count
29        );
30    }
31}
32
33/// Semantic similarity lookup matching a natural-language query against
34/// candidate API operations (PRD §1.5) — so an LLM never needs the full
35/// OpenAPI spec in context to find the right operation.
36pub fn search_operations(
37    conn: &Connection,
38    query: &str,
39    limit: usize,
40) -> anyhow::Result<serde_json::Value> {
41    warn_if_embeddings_incomplete(conn);
42    let query_embedding = embed(query)?;
43    let results = search_endpoints(conn, &query_embedding, limit)?;
44    Ok(serde_json::to_value(results)?)
45}
46
47#[cfg(test)]
48mod tests {
49    use super::*;
50
51    /// Same schema/registration pattern as `data::store`'s own tests
52    /// (`sqlite3_auto_extension` registration is process-global and
53    /// idempotent for the same function pointer, so calling it again here
54    /// alongside that module's tests in the same test binary is harmless) --
55    /// but with a real 768-dim `semantic_endpoints` column, matching
56    /// `services::embedding_service::embed`'s actual output width, since
57    /// `search_operations` calls the real embedding model rather than
58    /// taking a pre-computed vector.
59    fn seeded_store() -> Connection {
60        unsafe {
61            #[allow(clippy::missing_transmute_annotations)]
62            rusqlite::ffi::sqlite3_auto_extension(Some(std::mem::transmute(
63                sqlite_vec::sqlite3_vec_init as *const (),
64            )));
65        }
66        let conn = Connection::open_in_memory().unwrap();
67        conn.execute(
68            "CREATE TABLE endpoints (
69                operation_id TEXT PRIMARY KEY,
70                path TEXT NOT NULL,
71                method TEXT NOT NULL,
72                summary TEXT,
73                description TEXT,
74                input_schema TEXT NOT NULL,
75                output_schema TEXT NOT NULL,
76                auth_scheme_ref TEXT
77            )",
78            [],
79        )
80        .unwrap();
81        conn.execute(
82            "CREATE VIRTUAL TABLE semantic_endpoints USING vec0(
83                operation_id TEXT PRIMARY KEY,
84                embedding FLOAT[768]
85            )",
86            [],
87        )
88        .unwrap();
89        conn.execute(
90            "INSERT INTO endpoints (operation_id, path, method, summary, description, input_schema, output_schema, auth_scheme_ref)
91             VALUES ('listWidgets', '/widgets', 'GET', 'List widgets', NULL, '{}', '[]', NULL)",
92            [],
93        )
94        .unwrap();
95        let embedding: Vec<u8> = std::iter::once(1.0f32)
96            .chain(std::iter::repeat(0.0f32).take(767))
97            .flat_map(|v| v.to_le_bytes())
98            .collect();
99        conn.execute(
100            "INSERT INTO semantic_endpoints (operation_id, embedding) VALUES ('listWidgets', ?1)",
101            rusqlite::params![embedding],
102        )
103        .unwrap();
104        conn
105    }
106
107    #[test]
108    fn search_operations_finds_the_only_seeded_row() {
109        let conn = seeded_store();
110        let result = search_operations(&conn, "list all the widgets", 5).unwrap();
111        let results = result.as_array().unwrap();
112        assert_eq!(results.len(), 1);
113        assert_eq!(results[0]["operation_id"], "listWidgets");
114    }
115
116    #[test]
117    fn warn_if_embeddings_incomplete_does_not_panic_on_a_matched_store() {
118        // No `semantic_endpoints` shortfall here (1 endpoint, 1 embedding) --
119        // this just exercises the query-and-compare path without asserting
120        // on log output.
121        let conn = seeded_store();
122        warn_if_embeddings_incomplete(&conn);
123    }
124
125    #[test]
126    fn warn_if_embeddings_incomplete_does_not_panic_on_a_missing_table() {
127        // conn.query_row's `Err` case (schema doesn't even have the
128        // expected tables) -- warn_if_embeddings_incomplete must swallow
129        // this via its `if let Ok(...)`, not propagate/panic.
130        let conn = Connection::open_in_memory().unwrap();
131        warn_if_embeddings_incomplete(&conn);
132    }
133}