Skip to main content

sqlserver_mcp_catalog/tools/
search_tool.rs

1// SQL Server - 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        crate::data::store::register_vec_extension();
61        let conn = Connection::open_in_memory().unwrap();
62        conn.execute(
63            "CREATE TABLE endpoints (
64                operation_id TEXT PRIMARY KEY,
65                path TEXT NOT NULL,
66                method TEXT NOT NULL,
67                summary TEXT,
68                description TEXT,
69                input_schema TEXT NOT NULL,
70                output_schema TEXT NOT NULL,
71                auth_scheme_ref TEXT
72            )",
73            [],
74        )
75        .unwrap();
76        conn.execute(
77            "CREATE VIRTUAL TABLE semantic_endpoints USING vec0(
78                operation_id TEXT PRIMARY KEY,
79                embedding FLOAT[768]
80            )",
81            [],
82        )
83        .unwrap();
84        conn.execute(
85            "INSERT INTO endpoints (operation_id, path, method, summary, description, input_schema, output_schema, auth_scheme_ref)
86             VALUES ('listWidgets', '/widgets', 'GET', 'List widgets', NULL, '{}', '[]', NULL)",
87            [],
88        )
89        .unwrap();
90        let embedding: Vec<u8> = std::iter::once(1.0f32)
91            .chain(std::iter::repeat_n(0.0f32, 767))
92            .flat_map(|v| v.to_le_bytes())
93            .collect();
94        conn.execute(
95            "INSERT INTO semantic_endpoints (operation_id, embedding) VALUES ('listWidgets', ?1)",
96            rusqlite::params![embedding],
97        )
98        .unwrap();
99        conn
100    }
101
102    #[test]
103    fn search_operations_finds_the_only_seeded_row() {
104        let conn = seeded_store();
105        let result = search_operations(&conn, "list all the widgets", 5).unwrap();
106        let results = result.as_array().unwrap();
107        assert_eq!(results.len(), 1);
108        assert_eq!(results[0]["operation_id"], "listWidgets");
109    }
110
111    #[test]
112    fn warn_if_embeddings_incomplete_does_not_panic_on_a_matched_store() {
113        // No `semantic_endpoints` shortfall here (1 endpoint, 1 embedding) --
114        // this just exercises the query-and-compare path without asserting
115        // on log output.
116        let conn = seeded_store();
117        warn_if_embeddings_incomplete(&conn);
118    }
119
120    #[test]
121    fn warn_if_embeddings_incomplete_does_not_panic_on_a_missing_table() {
122        // conn.query_row's `Err` case (schema doesn't even have the
123        // expected tables) -- warn_if_embeddings_incomplete must swallow
124        // this via its `if let Ok(...)`, not propagate/panic.
125        let conn = Connection::open_in_memory().unwrap();
126        warn_if_embeddings_incomplete(&conn);
127    }
128}