Skip to main content

endpoint_libs/model/
json_schema.rs

1//! Conversion of the endpoint [`Type`] model into JSON Schema, as required by
2//! MCP (Model Context Protocol) tool definitions (`inputSchema` / `outputSchema`).
3//!
4//! The conversion is a pure function over [`Type`]; `StructRef`/`EnumRef`/
5//! `StructTable` references are resolved through a caller-provided
6//! [`TypeRegistry`] and emitted as `$ref` entries under `$defs`.
7
8use std::collections::BTreeMap;
9
10use convert_case::{Case, Casing};
11use eyre::{Result, bail};
12use serde_json::{Value, json};
13
14use crate::model::endpoint::EndpointSchema;
15use crate::model::types::{Field, Type};
16
17/// Name → [`Type`] map used to resolve `StructRef`, `EnumRef` and
18/// `StructTable` while converting to JSON Schema.
19///
20/// Built by the caller (a server at startup, or `endpoint-gen`) from the known
21/// struct and enum definitions.
22#[derive(Debug, Default, Clone)]
23pub struct TypeRegistry {
24    structs: BTreeMap<String, Type>,
25    enums: BTreeMap<String, Type>,
26}
27
28impl TypeRegistry {
29    pub fn new() -> Self {
30        Self::default()
31    }
32
33    /// Indexes `Struct` and `Enum` definitions found in `ty`, recursing into
34    /// struct fields and container types so nested definitions are captured.
35    pub fn add(&mut self, ty: &Type) {
36        match ty {
37            Type::Struct { name, fields } => {
38                self.structs.insert(name.clone(), ty.clone());
39                for field in fields {
40                    self.add(&field.ty);
41                }
42            }
43            Type::Enum { name, .. } => {
44                self.enums.insert(name.clone(), ty.clone());
45            }
46            Type::Vec(inner) | Type::Optional(inner) => self.add(inner),
47            _ => {}
48        }
49    }
50
51    /// Indexes every type in `tys`. See [`TypeRegistry::add`].
52    pub fn add_all<'a>(&mut self, tys: impl IntoIterator<Item = &'a Type>) {
53        for ty in tys {
54            self.add(ty);
55        }
56    }
57
58    /// Indexes all types referenced by an endpoint's parameters, returns and
59    /// stream response.
60    pub fn add_endpoint(&mut self, schema: &EndpointSchema) {
61        self.add_all(schema.parameters.iter().map(|f| &f.ty));
62        self.add_all(schema.returns.iter().map(|f| &f.ty));
63        if let Some(stream) = &schema.stream_response {
64            self.add(stream);
65        }
66    }
67
68    pub fn get_struct(&self, name: &str) -> Option<&Type> {
69        self.structs.get(name)
70    }
71
72    pub fn get_enum(&self, name: &str) -> Option<&Type> {
73        self.enums.get(name)
74    }
75}
76
77/// Definition name used for `$defs`/`$ref`. Enums keep their optional `Enum`
78/// prefix (mirrors `prefixed_name` handling in generated Rust code).
79fn enum_def_name(name: &str, prefixed_name: bool) -> String {
80    if prefixed_name {
81        format!("Enum{}", name.to_case(Case::Pascal))
82    } else {
83        name.to_case(Case::Pascal)
84    }
85}
86
87fn struct_def_name(name: &str) -> String {
88    name.to_case(Case::Pascal)
89}
90
91fn ref_to(def_name: &str) -> Value {
92    json!({ "$ref": format!("#/$defs/{def_name}") })
93}
94
95/// Builds an object schema over `fields`, in camelCase (matching the
96/// `#[serde(rename_all = "camelCase")]` on generated structs). Fields whose
97/// type is `Optional` are excluded from `required`.
98pub(crate) fn fields_to_object_schema(
99    fields: &[Field],
100    registry: &TypeRegistry,
101    defs: &mut BTreeMap<String, Value>,
102) -> Result<Value> {
103    let mut properties = serde_json::Map::new();
104    let mut required = Vec::new();
105
106    for field in fields {
107        let key = field.name.to_case(Case::Camel);
108        let mut schema = match &field.ty {
109            // Optional fields may be omitted or explicitly null on the wire.
110            Type::Optional(_) => field.ty.to_json_schema(registry, defs)?,
111            other => {
112                required.push(Value::String(key.clone()));
113                other.to_json_schema(registry, defs)?
114            }
115        };
116        if !field.description.is_empty()
117            && let Value::Object(map) = &mut schema
118        {
119            map.entry("description")
120                .or_insert_with(|| Value::String(field.description.clone()));
121        }
122        properties.insert(key, schema);
123    }
124
125    let mut obj = serde_json::Map::new();
126    obj.insert("type".into(), "object".into());
127    obj.insert("properties".into(), Value::Object(properties));
128    obj.insert("required".into(), Value::Array(required));
129    obj.insert("additionalProperties".into(), Value::Bool(false));
130    Ok(Value::Object(obj))
131}
132
133fn enum_to_schema(name: &str, variants: &[crate::model::types::EnumVariant]) -> Value {
134    let one_of: Vec<Value> = variants
135        .iter()
136        .map(|v| {
137            let mut entry = serde_json::Map::new();
138            entry.insert("const".into(), Value::String(v.name.clone()));
139            entry.insert("title".into(), Value::String(v.name.clone()));
140            if !v.description.is_empty() {
141                entry.insert("description".into(), Value::String(v.description.clone()));
142            }
143            Value::Object(entry)
144        })
145        .collect();
146    json!({
147        "type": "string",
148        "title": name,
149        "oneOf": one_of,
150    })
151}
152
153impl Type {
154    /// Converts this type to a JSON Schema fragment.
155    ///
156    /// `Struct`/`Enum` definitions (inline or by reference) are recorded in
157    /// `defs` and referenced via `$ref` so shared definitions are emitted once.
158    /// Returns an error for `StructRef`/`EnumRef`/`StructTable` names that are
159    /// not present in `registry` — callers should fail at startup rather than
160    /// emit a schema with dangling references.
161    pub fn to_json_schema(
162        &self,
163        registry: &TypeRegistry,
164        defs: &mut BTreeMap<String, Value>,
165    ) -> Result<Value> {
166        Ok(match self {
167            Type::UInt32 => json!({ "type": "integer", "minimum": 0, "maximum": u32::MAX }),
168            Type::Int32 => json!({ "type": "integer", "minimum": i32::MIN, "maximum": i32::MAX }),
169            Type::Int64 => json!({ "type": "integer" }),
170            Type::TimeStampMs => {
171                json!({ "type": "integer", "description": "Unix timestamp in milliseconds" })
172            }
173            Type::Float64 => json!({ "type": "number" }),
174            Type::Boolean => json!({ "type": "boolean" }),
175            Type::String => json!({ "type": "string" }),
176            Type::Bytea => json!({ "type": "string", "contentEncoding": "base64" }),
177            Type::UUID => json!({ "type": "string", "format": "uuid" }),
178            Type::NanoId { len } => json!({
179                "type": "string",
180                "minLength": len,
181                "maxLength": len,
182                "pattern": "^[0-9A-Za-z]+$",
183            }),
184            // Both IPv4 and IPv6 are accepted on the wire, so no single JSON
185            // Schema `format` applies.
186            Type::IpAddr => json!({ "type": "string", "description": "IPv4 or IPv6 address" }),
187            Type::Object => json!({ "type": "object" }),
188            Type::Unit => json!({ "type": "null" }),
189            Type::BlockchainDecimal => {
190                json!({ "type": "string", "description": "Decimal number as string" })
191            }
192            Type::BlockchainAddress => {
193                json!({ "type": "string", "pattern": "^0x[0-9a-fA-F]{40}$" })
194            }
195            Type::BlockchainTransactionHash => {
196                json!({ "type": "string", "pattern": "^0x[0-9a-fA-F]{64}$" })
197            }
198            Type::Vec(inner) => {
199                json!({ "type": "array", "items": inner.to_json_schema(registry, defs)? })
200            }
201            Type::Optional(inner) => {
202                // Optional values accept null in every schema position.
203                let inner = inner.to_json_schema(registry, defs)?;
204                json!({ "anyOf": [inner, { "type": "null" }] })
205            }
206            Type::Struct { name, fields } => {
207                let def_name = struct_def_name(name);
208                if !defs.contains_key(&def_name) {
209                    // Reserve the slot first so recursive references terminate.
210                    defs.insert(def_name.clone(), Value::Null);
211                    let schema = fields_to_object_schema(fields, registry, defs)?;
212                    defs.insert(def_name.clone(), schema);
213                }
214                ref_to(&def_name)
215            }
216            Type::StructRef(name) => {
217                let Some(ty) = registry.get_struct(name).cloned() else {
218                    bail!("unresolved StructRef: {name} (not present in TypeRegistry)");
219                };
220                ty.to_json_schema(registry, defs)?
221            }
222            Type::StructTable { struct_ref } => {
223                let Some(ty) = registry.get_struct(struct_ref).cloned() else {
224                    bail!("unresolved StructTable ref: {struct_ref} (not present in TypeRegistry)");
225                };
226                let items = ty.to_json_schema(registry, defs)?;
227                json!({ "type": "array", "items": items })
228            }
229            Type::Enum { name, variants } => {
230                let def_name = enum_def_name(name, false);
231                defs.entry(def_name.clone())
232                    .or_insert_with(|| enum_to_schema(&def_name, variants));
233                ref_to(&def_name)
234            }
235            Type::EnumRef {
236                name,
237                prefixed_name,
238            } => {
239                let Some(Type::Enum { variants, .. }) = registry.get_enum(name) else {
240                    bail!("unresolved EnumRef: {name} (not present in TypeRegistry)");
241                };
242                let def_name = enum_def_name(name, *prefixed_name);
243                if !defs.contains_key(&def_name) {
244                    let schema = enum_to_schema(&def_name, variants);
245                    defs.insert(def_name.clone(), schema);
246                }
247                ref_to(&def_name)
248            }
249        })
250    }
251}
252
253/// Attaches accumulated `$defs` to a root schema object, if any.
254fn attach_defs(mut root: Value, defs: BTreeMap<String, Value>) -> Value {
255    if !defs.is_empty()
256        && let Value::Object(map) = &mut root
257    {
258        map.insert("$defs".into(), json!(defs));
259    }
260    root
261}
262
263impl EndpointSchema {
264    /// MCP tool name for this endpoint: the endpoint name in snake_case
265    /// (e.g. `UserListSymbols` → `user_list_symbols`).
266    pub fn tool_name(&self) -> String {
267        self.name.to_case(Case::Snake)
268    }
269
270    /// MCP `inputSchema`: an object schema over `parameters`. Non-`Optional`
271    /// parameters are listed in `required`.
272    pub fn to_mcp_input_schema(&self, registry: &TypeRegistry) -> Result<Value> {
273        let mut defs = BTreeMap::new();
274        let root = fields_to_object_schema(&self.parameters, registry, &mut defs)?;
275        Ok(attach_defs(root, defs))
276    }
277
278    /// MCP `outputSchema`: an object schema over `returns`.
279    pub fn to_mcp_output_schema(&self, registry: &TypeRegistry) -> Result<Value> {
280        let mut defs = BTreeMap::new();
281        let root = fields_to_object_schema(&self.returns, registry, &mut defs)?;
282        Ok(attach_defs(root, defs))
283    }
284}
285
286#[cfg(test)]
287mod tests {
288    use super::*;
289    use crate::model::types::EnumVariant;
290
291    fn schema_of(ty: &Type) -> Value {
292        let registry = TypeRegistry::new();
293        let mut defs = BTreeMap::new();
294        let schema = ty.to_json_schema(&registry, &mut defs).unwrap();
295        attach_defs(schema, defs)
296    }
297
298    #[test]
299    fn primitives() {
300        assert_eq!(
301            schema_of(&Type::UInt32),
302            json!({ "type": "integer", "minimum": 0, "maximum": u32::MAX })
303        );
304        assert_eq!(
305            schema_of(&Type::Int32),
306            json!({ "type": "integer", "minimum": i32::MIN, "maximum": i32::MAX })
307        );
308        assert_eq!(schema_of(&Type::Int64), json!({ "type": "integer" }));
309        assert_eq!(schema_of(&Type::Float64), json!({ "type": "number" }));
310        assert_eq!(schema_of(&Type::Boolean), json!({ "type": "boolean" }));
311        assert_eq!(schema_of(&Type::String), json!({ "type": "string" }));
312        assert_eq!(schema_of(&Type::Object), json!({ "type": "object" }));
313        assert_eq!(schema_of(&Type::Unit), json!({ "type": "null" }));
314    }
315
316    #[test]
317    fn string_formats() {
318        assert_eq!(
319            schema_of(&Type::Bytea),
320            json!({ "type": "string", "contentEncoding": "base64" })
321        );
322        assert_eq!(
323            schema_of(&Type::UUID),
324            json!({ "type": "string", "format": "uuid" })
325        );
326        assert_eq!(
327            schema_of(&Type::NanoId { len: 21 }),
328            json!({
329                "type": "string",
330                "minLength": 21,
331                "maxLength": 21,
332                "pattern": "^[0-9A-Za-z]+$",
333            })
334        );
335        assert_eq!(
336            schema_of(&Type::BlockchainAddress),
337            json!({ "type": "string", "pattern": "^0x[0-9a-fA-F]{40}$" })
338        );
339        assert_eq!(
340            schema_of(&Type::BlockchainTransactionHash),
341            json!({ "type": "string", "pattern": "^0x[0-9a-fA-F]{64}$" })
342        );
343    }
344
345    #[test]
346    fn containers() {
347        assert_eq!(
348            schema_of(&Type::vec(Type::String)),
349            json!({ "type": "array", "items": { "type": "string" } })
350        );
351        assert_eq!(
352            schema_of(&Type::optional(Type::Int64)),
353            json!({ "anyOf": [{ "type": "integer" }, { "type": "null" }] })
354        );
355    }
356
357    #[test]
358    fn inline_struct_goes_to_defs() {
359        let ty = Type::struct_(
360            "UserInfo",
361            vec![
362                Field::new("user_id", Type::Int64),
363                Field::new("email", Type::optional(Type::String)),
364            ],
365        );
366        let schema = schema_of(&ty);
367        assert_eq!(schema["$ref"], json!("#/$defs/UserInfo"));
368        let def = &schema["$defs"]["UserInfo"];
369        assert_eq!(def["type"], json!("object"));
370        assert_eq!(def["properties"]["userId"]["type"], json!("integer"));
371        assert_eq!(
372            def["properties"]["email"],
373            json!({ "anyOf": [{ "type": "string" }, { "type": "null" }] })
374        );
375        // Optional field is not required.
376        assert_eq!(def["required"], json!(["userId"]));
377        assert_eq!(def["additionalProperties"], json!(false));
378    }
379
380    #[test]
381    fn enum_schema() {
382        let ty = Type::enum_(
383            "role",
384            vec![
385                EnumVariant::new_with_description("Admin", "administrator", 1),
386                EnumVariant::new("User", 2),
387            ],
388        );
389        let schema = schema_of(&ty);
390        assert_eq!(schema["$ref"], json!("#/$defs/Role"));
391        let def = &schema["$defs"]["Role"];
392        assert_eq!(def["type"], json!("string"));
393        assert_eq!(def["oneOf"][0]["const"], json!("Admin"));
394        assert_eq!(def["oneOf"][0]["title"], json!("Admin"));
395        assert_eq!(def["oneOf"][0]["description"], json!("administrator"));
396        assert_eq!(def["oneOf"][1], json!({ "const": "User", "title": "User" }));
397    }
398
399    #[test]
400    fn struct_ref_resolves_through_registry() {
401        let user_info = Type::struct_("UserInfo", vec![Field::new("user_id", Type::Int64)]);
402        let mut registry = TypeRegistry::new();
403        registry.add(&user_info);
404
405        let mut defs = BTreeMap::new();
406        let schema = Type::struct_ref("UserInfo")
407            .to_json_schema(&registry, &mut defs)
408            .unwrap();
409        assert_eq!(schema, json!({ "$ref": "#/$defs/UserInfo" }));
410        assert!(defs.contains_key("UserInfo"));
411    }
412
413    #[test]
414    fn struct_table_resolves_to_array() {
415        let row = Type::struct_("Row", vec![Field::new("id", Type::Int64)]);
416        let mut registry = TypeRegistry::new();
417        registry.add(&row);
418
419        let mut defs = BTreeMap::new();
420        let schema = Type::struct_table("Row")
421            .to_json_schema(&registry, &mut defs)
422            .unwrap();
423        assert_eq!(
424            schema,
425            json!({ "type": "array", "items": { "$ref": "#/$defs/Row" } })
426        );
427    }
428
429    #[test]
430    fn unresolved_refs_error() {
431        let registry = TypeRegistry::new();
432        let mut defs = BTreeMap::new();
433        assert!(
434            Type::struct_ref("Missing")
435                .to_json_schema(&registry, &mut defs)
436                .is_err()
437        );
438        assert!(
439            Type::enum_ref("Missing", true)
440                .to_json_schema(&registry, &mut defs)
441                .is_err()
442        );
443        assert!(
444            Type::struct_table("Missing")
445                .to_json_schema(&registry, &mut defs)
446                .is_err()
447        );
448    }
449
450    #[test]
451    fn enum_ref_prefixed_naming() {
452        let role = Type::enum_("role", vec![EnumVariant::new("Admin", 1)]);
453        let mut registry = TypeRegistry::new();
454        registry.add(&role);
455
456        let mut defs = BTreeMap::new();
457        let schema = Type::enum_ref("role", true)
458            .to_json_schema(&registry, &mut defs)
459            .unwrap();
460        assert_eq!(schema, json!({ "$ref": "#/$defs/EnumRole" }));
461        assert!(defs.contains_key("EnumRole"));
462    }
463
464    #[test]
465    fn shared_defs_emitted_once() {
466        let user_info = Type::struct_("UserInfo", vec![Field::new("user_id", Type::Int64)]);
467        let outer = Type::struct_(
468            "Outer",
469            vec![
470                Field::new("a", user_info.clone()),
471                Field::new("b", user_info),
472            ],
473        );
474        let schema = schema_of(&outer);
475        let def = &schema["$defs"]["Outer"];
476        assert_eq!(
477            def["properties"]["a"],
478            json!({ "$ref": "#/$defs/UserInfo" })
479        );
480        assert_eq!(
481            def["properties"]["b"],
482            json!({ "$ref": "#/$defs/UserInfo" })
483        );
484        assert!(schema["$defs"]["UserInfo"].is_object());
485    }
486
487    #[test]
488    fn tool_name_is_snake_case() {
489        let schema = EndpointSchema::new("UserListSymbols", 10020, vec![], vec![]);
490        assert_eq!(schema.tool_name(), "user_list_symbols");
491    }
492
493    #[test]
494    fn endpoint_input_schema_golden() {
495        let endpoint = EndpointSchema::new(
496            "UserGetProfile",
497            10010,
498            vec![
499                Field::new("user_id", Type::Int64),
500                Field::new_with_description(
501                    "nickname",
502                    "Optional display name",
503                    Type::optional(Type::String),
504                ),
505            ],
506            vec![Field::new("profile", Type::struct_ref("UserProfile"))],
507        );
508
509        let profile = Type::struct_(
510            "UserProfile",
511            vec![
512                Field::new("user_id", Type::Int64),
513                Field::new("role", Type::enum_ref("role", true)),
514            ],
515        );
516        let role = Type::enum_("role", vec![EnumVariant::new("Admin", 1)]);
517        let mut registry = TypeRegistry::new();
518        registry.add(&profile);
519        registry.add(&role);
520
521        let input = endpoint.to_mcp_input_schema(&registry).unwrap();
522        assert_eq!(
523            input,
524            json!({
525                "type": "object",
526                "properties": {
527                    "userId": { "type": "integer" },
528                    "nickname": {
529                        "anyOf": [{ "type": "string" }, { "type": "null" }],
530                        "description": "Optional display name",
531                    },
532                },
533                "required": ["userId"],
534                "additionalProperties": false,
535            })
536        );
537
538        let output = endpoint.to_mcp_output_schema(&registry).unwrap();
539        assert_eq!(
540            output["properties"]["profile"],
541            json!({ "$ref": "#/$defs/UserProfile" })
542        );
543        assert_eq!(output["required"], json!(["profile"]));
544        assert_eq!(
545            output["$defs"]["UserProfile"]["properties"]["role"],
546            json!({ "$ref": "#/$defs/EnumRole" })
547        );
548        assert!(output["$defs"]["EnumRole"].is_object());
549    }
550}