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