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