github_mcp/validation/
validator.rs1use std::collections::HashMap;
23use std::sync::{Mutex, OnceLock};
24
25use serde::Deserialize;
26use serde_json::Value;
27
28use crate::core::errors::McpifyError;
29
30#[derive(Debug, Deserialize)]
31struct OperationSchemas {
32 #[serde(rename = "inputSchema")]
33 input_schema: Value,
34 #[serde(rename = "outputSchema")]
35 output_schema: Value,
36}
37
38fn schemas_zst_for(api_version: &str) -> Option<&'static [u8]> {
40 match api_version {
41 "gh-2026-03-10" => Some(include_bytes!("generated_schemas.json.zst")),
42 "ghec-2026-03-10" => Some(include_bytes!("generated_schemas_vghec-2026-03-10.json.zst")),
43 "ghes-3.21" => Some(include_bytes!("generated_schemas_vghes-3.21.json.zst")),
44 "ghes-3.20" => Some(include_bytes!("generated_schemas_vghes-3.20.json.zst")),
45 "ghes-3.19" => Some(include_bytes!("generated_schemas_vghes-3.19.json.zst")),
46 "ghes-2.22" => Some(include_bytes!("generated_schemas_vghes-2.22.json.zst")),
47 _ => None,
48 }
49}
50fn schemas_by_operation(api_version: &str) -> &'static HashMap<String, OperationSchemas> {
53 static SCHEMAS: OnceLock<Mutex<HashMap<String, &'static HashMap<String, OperationSchemas>>>> =
54 OnceLock::new();
55 static EMPTY: OnceLock<HashMap<String, OperationSchemas>> = OnceLock::new();
56 let empty = EMPTY.get_or_init(HashMap::new);
57
58 let cache = SCHEMAS.get_or_init(|| Mutex::new(HashMap::new()));
59 let mut cache = cache.lock().unwrap();
60 if let Some(schemas) = cache.get(api_version) {
61 return schemas;
62 }
63
64 let Some(compressed) = schemas_zst_for(api_version) else {
65 return empty;
66 };
67 let parsed: HashMap<String, OperationSchemas> = zstd::decode_all(compressed)
68 .ok()
69 .and_then(|json| serde_json::from_slice(&json).ok())
70 .unwrap_or_default();
71 let leaked: &'static HashMap<String, OperationSchemas> = Box::leak(Box::new(parsed));
72 cache.insert(api_version.to_string(), leaked);
73 leaked
74}
75
76fn validate_against(
77 cache: &Mutex<HashMap<String, jsonschema::Validator>>,
78 operation_id: &str,
79 schema: &Value,
80 data: &Value,
81) -> Result<(), Vec<String>> {
82 let mut cache = cache.lock().unwrap();
83 let validator = cache.entry(operation_id.to_string()).or_insert_with(|| {
84 jsonschema::validator_for(schema).unwrap_or_else(|_| {
85 jsonschema::validator_for(&Value::Object(Default::default())).unwrap()
86 })
87 });
88
89 if validator.is_valid(data) {
90 return Ok(());
91 }
92 let errors = validator
93 .iter_errors(data)
94 .map(|error| error.to_string())
95 .collect::<Vec<_>>();
96 Err(errors)
97}
98
99pub fn validate_input(
102 api_version: &str,
103 operation_id: &str,
104 data: &Value,
105) -> Result<(), McpifyError> {
106 static CACHE: OnceLock<Mutex<HashMap<String, jsonschema::Validator>>> = OnceLock::new();
107 let cache = CACHE.get_or_init(|| Mutex::new(HashMap::new()));
108
109 let empty = Value::Object(Default::default());
110 let schema = schemas_by_operation(api_version)
111 .get(operation_id)
112 .map(|schemas| &schemas.input_schema)
113 .unwrap_or(&empty);
114
115 let cache_key = format!("{api_version} {operation_id}");
116 validate_against(cache, &cache_key, schema, data).map_err(|errors| McpifyError::Validation {
117 message: format!("invalid input for '{operation_id}'"),
118 details: Some(serde_json::json!(errors)),
119 })
120}
121
122pub fn validate_output(
127 api_version: &str,
128 operation_id: &str,
129 data: &Value,
130) -> Result<(), McpifyError> {
131 static CACHE: OnceLock<Mutex<HashMap<String, jsonschema::Validator>>> = OnceLock::new();
132 let cache = CACHE.get_or_init(|| Mutex::new(HashMap::new()));
133
134 let empty = Value::Object(Default::default());
135 let schema = schemas_by_operation(api_version)
136 .get(operation_id)
137 .map(|schemas| &schemas.output_schema)
138 .unwrap_or(&empty);
139
140 let cache_key = format!("{api_version} {operation_id}");
141 validate_against(cache, &cache_key, schema, data).map_err(|errors| McpifyError::Validation {
142 message: format!("unexpected response shape for '{operation_id}'"),
143 details: Some(serde_json::json!(errors)),
144 })
145}
146
147#[cfg(test)]
148mod tests {
149 use super::*;
150
151 #[test]
157 fn an_unknown_operation_id_falls_back_to_an_always_valid_schema() {
158 assert!(
159 validate_input(
160 "gh-2026-03-10",
161 "__unknown_operation__",
162 &serde_json::json!({"anything": true})
163 )
164 .is_ok()
165 );
166 assert!(
167 validate_output(
168 "gh-2026-03-10",
169 "__unknown_operation__",
170 &serde_json::json!(42)
171 )
172 .is_ok()
173 );
174 }
175
176 #[test]
177 fn an_unknown_api_version_also_falls_back_to_an_always_valid_schema() {
178 assert!(
179 validate_input(
180 "__unknown_version__",
181 "__unknown_operation__",
182 &serde_json::json!({"anything": true})
183 )
184 .is_ok()
185 );
186 }
187
188 #[test]
189 fn validate_against_reports_every_schema_violation() {
190 static CACHE: OnceLock<Mutex<HashMap<String, jsonschema::Validator>>> = OnceLock::new();
191 let cache = CACHE.get_or_init(|| Mutex::new(HashMap::new()));
192 let schema = serde_json::json!({
193 "type": "object",
194 "required": ["name"],
195 "properties": { "name": { "type": "string" } },
196 });
197
198 let ok = validate_against(
199 cache,
200 "test_op_ok",
201 &schema,
202 &serde_json::json!({"name": "widget"}),
203 );
204 assert!(ok.is_ok());
205
206 let err = validate_against(cache, "test_op_missing", &schema, &serde_json::json!({}));
207 assert!(err.is_err());
208 }
209}