github-mcp 0.1.3

GitHub v3 REST API MCP server, generated by mcpify.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
// GitHub v3 REST API MCP server — generated by mcpify. Do not hand-edit.
//
// Single data-access layer against mcp_store.db — both the relational
// `endpoints` table and the `semantic_endpoints` vec0 virtual table
// (REQ-2.4.1's single-store consolidation). Mirrors the shape of
// mcpify's own src/db/open.rs almost directly, since both the generator
// and the generated project use the identical rusqlite+sqlite-vec crate
// pair. Unlike mcpify's own src/db/schema.rs, this module never creates
// tables — mcpify's shared pipeline (Story 5/6) already wrote
// mcp_store.db's schema before any generated code runs.

use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::{Mutex, Once, OnceLock};
use std::time::Duration;

use anyhow::{Context, Result};
use rusqlite::backup::Backup;
use rusqlite::{Connection, OpenFlags, Row};
use serde::Serialize;

static REGISTER_VEC_EXTENSION: Once = Once::new();

// mcpify:versions:begin
pub const VERSION_STORE_FILES: &[(&str, &str)] = &[
    ("gh-2026-03-10", "mcp_store.db"),
    ("ghec-2026-03-10", "mcp_store_vghec-2026-03-10.db"),
    ("ghes-3.21", "mcp_store_vghes-3.21.db"),
    ("ghes-3.20", "mcp_store_vghes-3.20.db"),
    ("ghes-3.19", "mcp_store_vghes-3.19.db"),
    ("ghes-2.22", "mcp_store_vghes-2.22.db"),
];

const VERSION_STORE_BYTES: &[(&str, &[u8])] = &[
    ("gh-2026-03-10", include_bytes!("../../mcp_store.db")),
    ("ghec-2026-03-10", include_bytes!("../../mcp_store_vghec-2026-03-10.db")),
    ("ghes-3.21", include_bytes!("../../mcp_store_vghes-3.21.db")),
    ("ghes-3.20", include_bytes!("../../mcp_store_vghes-3.20.db")),
    ("ghes-3.19", include_bytes!("../../mcp_store_vghes-3.19.db")),
    ("ghes-2.22", include_bytes!("../../mcp_store_vghes-2.22.db")),
];
// mcpify:versions:end

/// Resolves the active `api_version` (from the config cascade) to its
/// store file. Every `.db` this crate supports is embedded into the
/// compiled binary via `include_bytes!` (`VERSION_STORE_BYTES`) exactly
/// like `validator.rs` embeds each version's schema — there is no
/// filesystem fallback chain to reason about, and this crate never
/// depends on any particular `.db` file existing anywhere on disk after
/// `cargo install`. The one difference from a schema lookup: SQLite
/// needs a real file to open a `Connection` against (unlike a `&[u8]`
/// JSON schema, read directly from memory), so this extracts the
/// embedded bytes to a fixed path in the OS temp dir on every call —
/// cheap, since it only runs once per process start, and it means a
/// rebuilt binary with different embedded bytes (a `populate_embeddings`
/// re-run, an `add-version` update) can never be shadowed by a stale
/// leftover from a previous install at that same path.
pub fn resolve_store_path(api_version: &str) -> Result<PathBuf> {
    let file = VERSION_STORE_FILES
        .iter()
        .find(|(label, _)| *label == api_version)
        .map(|(_, file)| *file)
        .with_context(|| format!("unknown api_version '{api_version}' — run the 'versions' command to see what's available"))?;
    let bytes = VERSION_STORE_BYTES
        .iter()
        .find(|(label, _)| *label == api_version)
        .map(|(_, bytes)| *bytes)
        .with_context(|| format!("no embedded store data for api_version '{api_version}'"))?;

    let mut dir = std::env::temp_dir();
    dir.push(concat!(env!("CARGO_PKG_NAME"), "-store"));
    std::fs::create_dir_all(&dir)
        .with_context(|| format!("failed to create temp dir '{}'", dir.display()))?;

    let path = dir.join(file);
    // Always (re)writes rather than skipping when the path already
    // exists: the extraction path doesn't vary by build, so a stale copy
    // from a previous install (older embedded bytes, e.g. before a
    // `populate_embeddings` re-run or an `add-version` update) would
    // otherwise linger forever, silently serving outdated data. The
    // write is cheap — this runs once per process start, not per query.
    std::fs::write(&path, bytes).with_context(|| {
        format!(
            "failed to extract embedded store data to '{}'",
            path.display()
        )
    })?;

    Ok(path)
}

const ENDPOINT_COLUMNS: &str = "operation_id, path, method, summary, description, input_schema, output_schema, auth_scheme_ref";

/// Registers the `sqlite-vec` extension once per process, via
/// `sqlite3_auto_extension` — matching the pattern the `sqlite-vec` crate
/// itself documents for `rusqlite`.
fn register_vec_extension() {
    REGISTER_VEC_EXTENSION.call_once(|| unsafe {
        #[allow(clippy::missing_transmute_annotations)]
        rusqlite::ffi::sqlite3_auto_extension(Some(std::mem::transmute(
            sqlite_vec::sqlite3_vec_init as *const (),
        )));
    });
}

/// Opens `mcp_store.db` read-only: this crate's binaries only ever read
/// it, except `github-mcp-populate-embeddings` (a separate `[[bin]]`), which uses
/// `open_store_read_write` instead.
pub fn open_store(path: &Path) -> Result<Connection> {
    register_vec_extension();
    Connection::open_with_flags(path, OpenFlags::SQLITE_OPEN_READ_ONLY)
        .with_context(|| format!("failed to open '{}'", path.display()))
}

/// Read-write counterpart to `open_store` — for `bin/populate_embeddings.rs`,
/// the one binary that actually writes to `mcp_store.db` (backfilling
/// `semantic_endpoints`, whose table every other caller only ever reads
/// from).
pub fn open_store_read_write(path: &Path) -> Result<Connection> {
    register_vec_extension();
    Connection::open_with_flags(path, OpenFlags::SQLITE_OPEN_READ_WRITE)
        .with_context(|| format!("failed to open '{}'", path.display()))
}

/// Returns a process-wide, in-memory-backed connection for `api_version`:
/// on first access, opens the on-disk file read-only via `open_store`,
/// copies its entire contents into a fresh `:memory:` connection (via
/// SQLite's backup API), then drops the on-disk connection immediately —
/// so its file handle/lock is held only for that brief copy, not for the
/// process's lifetime. This means an external process (a fresh
/// `github-mcp-populate-embeddings` run, a deployment replacing the file) can update
/// `mcp_store.db` without hitting "database is locked" against a live
/// server, at the cost of the running process only picking up such an
/// update on its next restart.
///
/// Returns the connection behind a `Mutex` rather than handing it out
/// directly: callers must finish with the guard (and drop it) *before*
/// any `.await` — `rusqlite::Connection` isn't `Sync`, so holding the
/// guard across an await point would make the enclosing future
/// non-`Send`, the same constraint `core/mcp_server.rs`'s tool handlers
/// already respect for a plain `Connection`.
pub fn cached_store_connection(api_version: &str) -> Result<&'static Mutex<Connection>> {
    let path = resolve_store_path(api_version)?;
    cached_in_memory_connection(api_version, &path)
}

/// Does the actual work for `cached_store_connection`, taking an explicit
/// path (rather than resolving one from `api_version` itself) so it's
/// testable against an arbitrary tempdir path — `cache_key` and `path`
/// are separate parameters because two different `api_version`s should
/// never collide in the process-wide cache even if (hypothetically) they
/// resolved to the same file.
fn cached_in_memory_connection(cache_key: &str, path: &Path) -> Result<&'static Mutex<Connection>> {
    static CACHE: OnceLock<Mutex<HashMap<String, &'static Mutex<Connection>>>> = OnceLock::new();
    let cache = CACHE.get_or_init(|| Mutex::new(HashMap::new()));

    if let Some(conn) = cache.lock().unwrap().get(cache_key) {
        return Ok(conn);
    }

    let disk_conn = open_store(path)?;
    let mut mem_conn =
        Connection::open_in_memory().context("failed to open an in-memory SQLite connection")?;
    Backup::new(&disk_conn, &mut mem_conn)
        .context("failed to start SQLite backup into memory")?
        .run_to_completion(i32::MAX, Duration::from_millis(0), None)
        .with_context(|| format!("failed to back up '{}' into memory", path.display()))?;
    drop(disk_conn);

    let leaked: &'static Mutex<Connection> = Box::leak(Box::new(Mutex::new(mem_conn)));
    let mut cache = cache.lock().unwrap();
    Ok(*cache.entry(cache_key.to_string()).or_insert(leaked))
}

#[derive(Debug, Clone, Serialize)]
pub struct EndpointRecord {
    pub operation_id: String,
    pub path: String,
    pub method: String,
    pub summary: Option<String>,
    pub description: Option<String>,
    pub input_schema: serde_json::Value,
    pub output_schema: serde_json::Value,
    pub auth_scheme_ref: Option<String>,
}

fn row_to_endpoint(row: &Row) -> rusqlite::Result<EndpointRecord> {
    let input_schema: String = row.get(5)?;
    let output_schema: String = row.get(6)?;
    Ok(EndpointRecord {
        operation_id: row.get(0)?,
        path: row.get(1)?,
        method: row.get(2)?,
        summary: row.get(3)?,
        description: row.get(4)?,
        input_schema: serde_json::from_str(&input_schema).unwrap_or(serde_json::Value::Null),
        output_schema: serde_json::from_str(&output_schema).unwrap_or(serde_json::Value::Null),
        auth_scheme_ref: row.get(7)?,
    })
}

pub fn get_endpoint(conn: &Connection, operation_id: &str) -> Result<Option<EndpointRecord>> {
    let mut stmt = conn.prepare(&format!(
        "SELECT {ENDPOINT_COLUMNS} FROM endpoints WHERE operation_id = ?1"
    ))?;
    match stmt.query_row([operation_id], row_to_endpoint) {
        Ok(record) => Ok(Some(record)),
        Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
        Err(err) => Err(err.into()),
    }
}

pub fn list_endpoints(conn: &Connection) -> Result<Vec<EndpointRecord>> {
    let mut stmt = conn.prepare(&format!("SELECT {ENDPOINT_COLUMNS} FROM endpoints"))?;
    let rows = stmt.query_map([], row_to_endpoint)?;
    Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
}

#[derive(Debug, Clone, Serialize)]
pub struct SearchResult {
    pub operation_id: String,
    pub summary: Option<String>,
    pub similarity: f64,
}

/// k-nearest-neighbor search over `semantic_endpoints` (sqlite-vec's
/// documented `MATCH ... AND k = ...` query form). `query_embedding` must
/// come from the same model as the vectors it's compared against — see
/// `services::embedding_service`. Bound as a raw little-endian `f32` blob,
/// the same wire format `bin/populate_embeddings.rs` writes (sqlite-vec
/// accepts either that or a JSON array per-call, independent of how any
/// given row was originally inserted, so this is a consistency choice, not
/// a correctness requirement).
///
/// `similarity` is a simple `1 - distance` transform of sqlite-vec's L2
/// distance, not a true cosine-similarity computation; since embeddings
/// are normalized (unit vectors), L2-distance ordering already matches
/// cosine-similarity ordering, so result *ranking* is correct even though
/// the displayed score is an approximation.
pub fn search_endpoints(
    conn: &Connection,
    query_embedding: &[f32],
    limit: usize,
) -> Result<Vec<SearchResult>> {
    let blob: Vec<u8> = query_embedding
        .iter()
        .flat_map(|value| value.to_le_bytes())
        .collect();

    let mut stmt = conn.prepare(
        "SELECT e.operation_id, e.summary, s.distance
         FROM semantic_endpoints s
         JOIN endpoints e ON e.operation_id = s.operation_id
         WHERE s.embedding MATCH ?1 AND k = ?2
         ORDER BY s.distance",
    )?;
    let rows = stmt.query_map(rusqlite::params![blob, limit], |row| {
        let distance: f64 = row.get(2)?;
        Ok(SearchResult {
            operation_id: row.get(0)?,
            summary: row.get(1)?,
            similarity: 1.0 - distance,
        })
    })?;
    Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Guards against `VERSION_STORE_FILES` and `VERSION_STORE_BYTES`
    /// silently drifting apart — every `api_version` this crate lists must
    /// resolve to embedded bytes, or `resolve_store_path` fails at runtime
    /// for exactly that version and nothing else, which is easy to miss in
    /// review since the two arrays are edited in different places.
    #[test]
    fn every_version_store_file_has_embedded_bytes() {
        let file_labels: std::collections::HashSet<_> = VERSION_STORE_FILES
            .iter()
            .map(|(label, _)| *label)
            .collect();
        let byte_labels: std::collections::HashSet<_> = VERSION_STORE_BYTES
            .iter()
            .map(|(label, _)| *label)
            .collect();
        assert_eq!(file_labels, byte_labels);
    }

    /// Builds a read-write connection with the same schema mcpify's shared
    /// pipeline writes, and seeds it with one row — real usage never
    /// creates this schema (mcpify already wrote it before any generated
    /// code runs), so this setup is test-only fixture, not production
    /// code these tests exercise.
    fn seeded_store(path: &Path) -> Connection {
        unsafe {
            #[allow(clippy::missing_transmute_annotations)]
            rusqlite::ffi::sqlite3_auto_extension(Some(std::mem::transmute(
                sqlite_vec::sqlite3_vec_init as *const (),
            )));
        }
        let conn = Connection::open(path).unwrap();
        conn.execute(
            "CREATE TABLE endpoints (
                operation_id TEXT PRIMARY KEY,
                path TEXT NOT NULL,
                method TEXT NOT NULL,
                summary TEXT,
                description TEXT,
                input_schema TEXT NOT NULL,
                output_schema TEXT NOT NULL,
                auth_scheme_ref TEXT
            )",
            [],
        )
        .unwrap();
        conn.execute(
            "CREATE VIRTUAL TABLE semantic_endpoints USING vec0(
                operation_id TEXT PRIMARY KEY,
                embedding FLOAT[4]
            )",
            [],
        )
        .unwrap();
        conn.execute(
            "INSERT INTO endpoints (operation_id, path, method, summary, description, input_schema, output_schema, auth_scheme_ref)
             VALUES ('listWidgets', '/widgets', 'GET', 'List widgets', NULL, '{}', '[]', NULL)",
            [],
        )
        .unwrap();
        let embedding: Vec<u8> = [1.0f32, 0.0, 0.0, 0.0]
            .iter()
            .flat_map(|v| v.to_le_bytes())
            .collect();
        conn.execute(
            "INSERT INTO semantic_endpoints (operation_id, embedding) VALUES ('listWidgets', ?1)",
            rusqlite::params![embedding],
        )
        .unwrap();
        conn
    }

    #[test]
    fn get_endpoint_returns_a_seeded_row() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("mcp_store.db");
        let _conn = seeded_store(&path);

        let store = open_store(&path).unwrap();
        let endpoint = get_endpoint(&store, "listWidgets").unwrap().unwrap();
        assert_eq!(endpoint.path, "/widgets");
        assert_eq!(endpoint.method, "GET");
        assert_eq!(endpoint.summary.as_deref(), Some("List widgets"));
    }

    #[test]
    fn get_endpoint_returns_none_for_an_unknown_operation() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("mcp_store.db");
        let _conn = seeded_store(&path);

        let store = open_store(&path).unwrap();
        assert!(get_endpoint(&store, "unknownOp").unwrap().is_none());
    }

    #[test]
    fn list_endpoints_returns_every_row() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("mcp_store.db");
        let _conn = seeded_store(&path);

        let store = open_store(&path).unwrap();
        let endpoints = list_endpoints(&store).unwrap();
        assert_eq!(endpoints.len(), 1);
        assert_eq!(endpoints[0].operation_id, "listWidgets");
    }

    #[test]
    fn search_endpoints_finds_the_nearest_neighbor() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("mcp_store.db");
        let _conn = seeded_store(&path);

        let store = open_store(&path).unwrap();
        let results = search_endpoints(&store, &[1.0, 0.0, 0.0, 0.0], 5).unwrap();
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].operation_id, "listWidgets");
        assert!(results[0].similarity > 0.99);
    }

    #[test]
    fn cached_in_memory_connection_serves_seeded_data() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("mcp_store.db");
        let _conn = seeded_store(&path);

        let cached = cached_in_memory_connection("cached-serves-seeded-data", &path).unwrap();
        let endpoint = get_endpoint(&cached.lock().unwrap(), "listWidgets")
            .unwrap()
            .unwrap();
        assert_eq!(endpoint.path, "/widgets");

        // vec0 search must also work against the in-memory copy —
        // `register_vec_extension`'s `sqlite3_auto_extension` applies
        // process-wide, so it isn't specific to file-backed connections.
        let results = search_endpoints(&cached.lock().unwrap(), &[1.0, 0.0, 0.0, 0.0], 5).unwrap();
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].operation_id, "listWidgets");
    }

    #[test]
    fn cached_in_memory_connection_holds_no_lingering_lock_on_the_disk_file() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("mcp_store.db");
        let _conn = seeded_store(&path);

        let cached = cached_in_memory_connection("cached-releases-disk-handle", &path).unwrap();

        // If the disk connection were still open, removing the file out
        // from under it would be the exact failure mode this fix exists
        // to avoid.
        std::fs::remove_file(&path).unwrap();

        let endpoint = get_endpoint(&cached.lock().unwrap(), "listWidgets")
            .unwrap()
            .unwrap();
        assert_eq!(endpoint.path, "/widgets");
    }

    #[test]
    fn cached_in_memory_connection_reuses_the_same_connection_for_the_same_key() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("mcp_store.db");
        let _conn = seeded_store(&path);

        let first = cached_in_memory_connection("cached-reuses-same-key", &path).unwrap()
            as *const Mutex<Connection>;
        let second = cached_in_memory_connection("cached-reuses-same-key", &path).unwrap()
            as *const Mutex<Connection>;
        assert_eq!(
            first, second,
            "expected the same cached connection, not a fresh backup"
        );
    }
}