github-mcp 0.8.2

GitHub v3 REST API MCP server, generated by mcpify.
Documentation
// GitHub v3 REST API MCP server — generated by mcpify. Do not hand-edit.
//
// jsonschema-based input/output validation. Schemas themselves are NOT
// embedded directly in this file's logic — they're loaded from a bundled
// zstd asset. Concatenating the per-version JSON before compression lets
// zstd reuse GitHub's shared schema vocabulary and keeps the published
// crate below crates.io's upload limit without dropping API versions.
//
// The asset is zstd-compressed: every operation's schema embeds a full
// copy of the spec's `$defs` library (a deliberate generator tradeoff —
// see `mcpify`'s `openapi::schema_resolve` — simpler than cross-schema
// `$ref` resolution, at the cost of file size), and a long-distance-
// matching compressor collapses that duplication (measured ~190 MB down
// to tens of KB on a real spec) without requiring any change to the JSON
// Schema shape itself. The bundle is decompressed transiently when a
// version is first requested; only that version remains in the cache.

use std::collections::HashMap;
use std::sync::{Mutex, OnceLock};

use serde::Deserialize;
use serde_json::Value;

use crate::core::errors::McpifyError;

#[derive(Debug, Deserialize)]
struct OperationSchemas {
    #[serde(rename = "inputSchema")]
    input_schema: Value,
    #[serde(rename = "outputSchema")]
    output_schema: Value,
}

const SCHEMAS_BUNDLE: &[u8] = include_bytes!("generated_schemas_bundle.json.zst");

// Byte ranges in the decompressed concatenation, in bundle build order.
// mcpify:versions:begin
fn schemas_range_for(api_version: &str) -> Option<std::ops::Range<usize>> {
    match api_version {
        "gh-2026-03-10" => Some(0..6_881_701),
        "ghec-2026-03-10" => Some(6_881_701..14_474_447),
        "ghes-3.21" => Some(14_474_447..20_865_307),
        "ghes-3.20" => Some(20_865_307..26_961_926),
        "ghes-3.19" => Some(26_961_926..32_715_723),
        _ => None,
    }
}
// mcpify:versions:end

fn schemas_by_operation(api_version: &str) -> &'static HashMap<String, OperationSchemas> {
    static SCHEMAS: OnceLock<Mutex<HashMap<String, &'static HashMap<String, OperationSchemas>>>> =
        OnceLock::new();
    static EMPTY: OnceLock<HashMap<String, OperationSchemas>> = OnceLock::new();
    let empty = EMPTY.get_or_init(HashMap::new);

    let cache = SCHEMAS.get_or_init(|| Mutex::new(HashMap::new()));
    let mut cache = cache.lock().unwrap();
    if let Some(schemas) = cache.get(api_version) {
        return schemas;
    }

    let Some(range) = schemas_range_for(api_version) else {
        return empty;
    };
    let parsed: HashMap<String, OperationSchemas> = zstd::decode_all(SCHEMAS_BUNDLE)
        .ok()
        .and_then(|json| {
            json.get(range)
                .and_then(|slice| serde_json::from_slice(slice).ok())
        })
        .unwrap_or_default();
    let leaked: &'static HashMap<String, OperationSchemas> = Box::leak(Box::new(parsed));
    cache.insert(api_version.to_string(), leaked);
    leaked
}

fn validate_against(
    cache: &Mutex<HashMap<String, jsonschema::Validator>>,
    operation_id: &str,
    schema: &Value,
    data: &Value,
) -> Result<(), Vec<String>> {
    let mut cache = cache.lock().unwrap();
    let validator = cache.entry(operation_id.to_string()).or_insert_with(|| {
        jsonschema::validator_for(schema).unwrap_or_else(|_| {
            jsonschema::validator_for(&Value::Object(Default::default())).unwrap()
        })
    });

    if validator.is_valid(data) {
        return Ok(());
    }
    let errors = validator
        .iter_errors(data)
        .map(|error| error.to_string())
        .collect::<Vec<_>>();
    Err(errors)
}

/// Returns `Err` if `data` doesn't satisfy `operation_id`'s input schema,
/// for the given `api_version`.
pub fn validate_input(
    api_version: &str,
    operation_id: &str,
    data: &Value,
) -> Result<(), McpifyError> {
    static CACHE: OnceLock<Mutex<HashMap<String, jsonschema::Validator>>> = OnceLock::new();
    let cache = CACHE.get_or_init(|| Mutex::new(HashMap::new()));

    let empty = Value::Object(Default::default());
    let schema = schemas_by_operation(api_version)
        .get(operation_id)
        .map(|schemas| &schemas.input_schema)
        .unwrap_or(&empty);

    let cache_key = format!("{api_version} {operation_id}");
    validate_against(cache, &cache_key, schema, data).map_err(|errors| McpifyError::Validation {
        message: format!("invalid input for '{operation_id}'"),
        details: Some(serde_json::json!(errors)),
    })
}

/// Returns `Err` if `data` doesn't satisfy `operation_id`'s output schema
/// — surfaces upstream API drift as a structured error rather than
/// silently returning a mismatched response (architecture.md's `call`
/// pipeline). Validates against the given `api_version`'s schema.
pub fn validate_output(
    api_version: &str,
    operation_id: &str,
    data: &Value,
) -> Result<(), McpifyError> {
    static CACHE: OnceLock<Mutex<HashMap<String, jsonschema::Validator>>> = OnceLock::new();
    let cache = CACHE.get_or_init(|| Mutex::new(HashMap::new()));

    let empty = Value::Object(Default::default());
    let schema = schemas_by_operation(api_version)
        .get(operation_id)
        .map(|schemas| &schemas.output_schema)
        .unwrap_or(&empty);

    let cache_key = format!("{api_version} {operation_id}");
    validate_against(cache, &cache_key, schema, data).map_err(|errors| McpifyError::Validation {
        message: format!("unexpected response shape for '{operation_id}'"),
        details: Some(serde_json::json!(errors)),
    })
}

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

    // These tests deliberately use an operationId that generated_schemas.json
    // never declares — they exercise the "no schema found" fallback (an
    // always-valid `{}` schema), rather than any spec-dependent content
    // this project's own generation happened to produce.

    #[test]
    fn an_unknown_operation_id_falls_back_to_an_always_valid_schema() {
        assert!(
            validate_input(
                "gh-2026-03-10",
                "__unknown_operation__",
                &serde_json::json!({"anything": true})
            )
            .is_ok()
        );
        assert!(
            validate_output(
                "gh-2026-03-10",
                "__unknown_operation__",
                &serde_json::json!(42)
            )
            .is_ok()
        );
    }

    #[test]
    fn an_unknown_api_version_also_falls_back_to_an_always_valid_schema() {
        assert!(
            validate_input(
                "__unknown_version__",
                "__unknown_operation__",
                &serde_json::json!({"anything": true})
            )
            .is_ok()
        );
    }

    #[test]
    fn bundled_schemas_decode_for_every_known_version() {
        for version in [
            "gh-2026-03-10",
            "ghec-2026-03-10",
            "ghes-3.21",
            "ghes-3.20",
            "ghes-3.19",
        ] {
            assert!(!schemas_by_operation(version).is_empty(), "{version}");
        }
    }

    #[test]
    fn validate_against_reports_every_schema_violation() {
        static CACHE: OnceLock<Mutex<HashMap<String, jsonschema::Validator>>> = OnceLock::new();
        let cache = CACHE.get_or_init(|| Mutex::new(HashMap::new()));
        let schema = serde_json::json!({
            "type": "object",
            "required": ["name"],
            "properties": { "name": { "type": "string" } },
        });

        let ok = validate_against(
            cache,
            "test_op_ok",
            &schema,
            &serde_json::json!({"name": "widget"}),
        );
        assert!(ok.is_ok());

        let err = validate_against(cache, "test_op_missing", &schema, &serde_json::json!({}));
        assert!(err.is_err());
    }

    #[test]
    fn validate_against_falls_back_to_an_always_valid_schema_when_compilation_fails() {
        static CACHE: OnceLock<Mutex<HashMap<String, jsonschema::Validator>>> = OnceLock::new();
        let cache = CACHE.get_or_init(|| Mutex::new(HashMap::new()));
        // "not-a-real-type" isn't a recognized JSON Schema `type` value, so
        // `jsonschema::validator_for` fails to compile it — exercising the
        // always-valid-empty-schema fallback rather than a real validator.
        let uncompilable_schema = serde_json::json!({"type": "not-a-real-type"});

        let result = validate_against(
            cache,
            "test_op_uncompilable_schema",
            &uncompilable_schema,
            &serde_json::json!({"anything": true}),
        );
        assert!(result.is_ok());
    }
}