bote 0.91.0

MCP core service — JSON-RPC 2.0 protocol, tool registry, audit integration, and TypeScript bridge
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
//! JSON Schema validation — compile `ToolSchema` into a typed representation
//! and validate parameters against it.
//!
//! Supports type checking (string, number, integer, boolean, array, object),
//! enum constraints, numeric bounds, and default value injection.

use std::collections::HashMap;

use crate::registry::ToolSchema;

/// Property type with constraints.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum SchemaType {
    String {
        enum_values: Option<Vec<String>>,
        default: Option<String>,
    },
    Number {
        minimum: Option<f64>,
        maximum: Option<f64>,
        default: Option<f64>,
    },
    Integer {
        minimum: Option<i64>,
        maximum: Option<i64>,
        default: Option<i64>,
    },
    Boolean {
        default: Option<bool>,
    },
    Array {
        items: Option<Box<PropertyDef>>,
    },
    Object {
        properties: HashMap<String, PropertyDef>,
        required: Vec<String>,
    },
    /// Fallback for unrecognized schemas — accepts any value.
    Any,
}

/// A property definition with type and optional description.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct PropertyDef {
    pub schema_type: SchemaType,
    pub description: Option<String>,
}

impl PropertyDef {
    #[must_use]
    pub fn new(schema_type: SchemaType) -> Self {
        Self {
            schema_type,
            description: None,
        }
    }

    #[must_use]
    pub fn with_description(mut self, description: impl Into<String>) -> Self {
        self.description = Some(description.into());
        self
    }
}

/// A compiled schema for fast validation.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct CompiledSchema {
    pub properties: HashMap<String, PropertyDef>,
    pub required: Vec<String>,
}

impl CompiledSchema {
    /// Compile a `ToolSchema` into a `CompiledSchema`.
    ///
    /// Properties that cannot be parsed fall back to `SchemaType::Any`.
    pub fn compile(schema: &ToolSchema) -> crate::Result<Self> {
        let mut properties = HashMap::with_capacity(schema.properties.len());

        for (name, value) in &schema.properties {
            let prop = parse_property(name, value);
            properties.insert(name.clone(), prop);
        }

        Ok(Self {
            properties,
            required: schema.required.clone(),
        })
    }

    /// Validate parameters against this schema.
    ///
    /// Collects all violations rather than failing on the first.
    pub fn validate(&self, params: &serde_json::Value) -> std::result::Result<(), Vec<String>> {
        let map = match params.as_object() {
            Some(m) => m,
            None => return Err(vec!["params must be an object".into()]),
        };

        let mut violations = Vec::new();

        // Check required fields.
        for req in &self.required {
            if !map.contains_key(req) {
                violations.push(format!("missing required field: {req}"));
            }
        }

        // Type-check provided fields.
        for (name, value) in map {
            if let Some(prop) = self.properties.get(name) {
                validate_value(name, value, &prop.schema_type, &mut violations);
            }
            // Extra fields without schema are allowed (permissive).
        }

        if violations.is_empty() {
            Ok(())
        } else {
            Err(violations)
        }
    }

    /// Inject default values for missing optional fields.
    pub fn apply_defaults(&self, params: &mut serde_json::Value) {
        let map = match params.as_object_mut() {
            Some(m) => m,
            None => return,
        };

        for (name, prop) in &self.properties {
            if map.contains_key(name) {
                continue;
            }
            if let Some(default) = default_value(&prop.schema_type) {
                map.insert(name.clone(), default);
            }
        }
    }
}

/// Parse a JSON Schema property value into a `PropertyDef`.
fn parse_property(name: &str, value: &serde_json::Value) -> PropertyDef {
    let description = value
        .get("description")
        .and_then(|v| v.as_str())
        .map(String::from);

    let schema_type = match value.get("type").and_then(|v| v.as_str()) {
        Some("string") => SchemaType::String {
            enum_values: value.get("enum").and_then(|v| {
                v.as_array().map(|arr| {
                    arr.iter()
                        .filter_map(|v| v.as_str().map(String::from))
                        .collect()
                })
            }),
            default: value
                .get("default")
                .and_then(|v| v.as_str())
                .map(String::from),
        },
        Some("number") => SchemaType::Number {
            minimum: value.get("minimum").and_then(|v| v.as_f64()),
            maximum: value.get("maximum").and_then(|v| v.as_f64()),
            default: value.get("default").and_then(|v| v.as_f64()),
        },
        Some("integer") => SchemaType::Integer {
            minimum: value.get("minimum").and_then(|v| v.as_i64()),
            maximum: value.get("maximum").and_then(|v| v.as_i64()),
            default: value.get("default").and_then(|v| v.as_i64()),
        },
        Some("boolean") => SchemaType::Boolean {
            default: value.get("default").and_then(|v| v.as_bool()),
        },
        Some("array") => SchemaType::Array {
            items: value
                .get("items")
                .map(|v| Box::new(parse_property(&format!("{name}[]"), v))),
        },
        Some("object") => {
            let props = value
                .get("properties")
                .and_then(|v| v.as_object())
                .map(|obj| {
                    obj.iter()
                        .map(|(k, v)| (k.clone(), parse_property(k, v)))
                        .collect()
                })
                .unwrap_or_default();
            let required = value
                .get("required")
                .and_then(|v| v.as_array())
                .map(|arr| {
                    arr.iter()
                        .filter_map(|v| v.as_str().map(String::from))
                        .collect()
                })
                .unwrap_or_default();
            SchemaType::Object {
                properties: props,
                required,
            }
        }
        Some(other) => {
            tracing::warn!(
                field = name,
                schema_type = other,
                "unknown schema type, using Any"
            );
            SchemaType::Any
        }
        None => SchemaType::Any,
    };

    PropertyDef {
        schema_type,
        description,
    }
}

/// Validate a value against a schema type.
fn validate_value(
    path: &str,
    value: &serde_json::Value,
    schema_type: &SchemaType,
    violations: &mut Vec<String>,
) {
    match schema_type {
        SchemaType::String {
            enum_values,
            default: _,
        } => {
            if let Some(s) = value.as_str() {
                if let Some(allowed) = enum_values
                    && !allowed.iter().any(|a| a == s)
                {
                    violations.push(format!(
                        "{path}: value '{s}' not in enum [{}]",
                        allowed.join(", ")
                    ));
                }
            } else {
                violations.push(format!("{path}: expected string"));
            }
        }
        SchemaType::Number {
            minimum,
            maximum,
            default: _,
        } => {
            if let Some(n) = value.as_f64() {
                if let Some(min) = minimum
                    && n < *min
                {
                    violations.push(format!("{path}: {n} is less than minimum {min}"));
                }
                if let Some(max) = maximum
                    && n > *max
                {
                    violations.push(format!("{path}: {n} is greater than maximum {max}"));
                }
            } else {
                violations.push(format!("{path}: expected number"));
            }
        }
        SchemaType::Integer {
            minimum,
            maximum,
            default: _,
        } => {
            if let Some(n) = value.as_i64() {
                if let Some(min) = minimum
                    && n < *min
                {
                    violations.push(format!("{path}: {n} is less than minimum {min}"));
                }
                if let Some(max) = maximum
                    && n > *max
                {
                    violations.push(format!("{path}: {n} is greater than maximum {max}"));
                }
            } else {
                violations.push(format!("{path}: expected integer"));
            }
        }
        SchemaType::Boolean { default: _ } => {
            if !value.is_boolean() {
                violations.push(format!("{path}: expected boolean"));
            }
        }
        SchemaType::Array { items } => {
            if let Some(arr) = value.as_array() {
                if let Some(item_schema) = items {
                    for (i, item) in arr.iter().enumerate() {
                        validate_value(
                            &format!("{path}[{i}]"),
                            item,
                            &item_schema.schema_type,
                            violations,
                        );
                    }
                }
            } else {
                violations.push(format!("{path}: expected array"));
            }
        }
        SchemaType::Object {
            properties,
            required,
        } => {
            if let Some(obj) = value.as_object() {
                for req in required {
                    if !obj.contains_key(req) {
                        violations.push(format!("{path}.{req}: missing required field"));
                    }
                }
                for (key, val) in obj {
                    if let Some(prop) = properties.get(key) {
                        validate_value(
                            &format!("{path}.{key}"),
                            val,
                            &prop.schema_type,
                            violations,
                        );
                    }
                }
            } else {
                violations.push(format!("{path}: expected object"));
            }
        }
        SchemaType::Any => {}
    }
}

/// Extract the default value from a schema type, if any.
fn default_value(schema_type: &SchemaType) -> Option<serde_json::Value> {
    match schema_type {
        SchemaType::String { default, .. } => default.as_ref().map(|v| serde_json::json!(v)),
        SchemaType::Number { default, .. } => default.map(|v| serde_json::json!(v)),
        SchemaType::Integer { default, .. } => default.map(|v| serde_json::json!(v)),
        SchemaType::Boolean { default } => default.map(|v| serde_json::json!(v)),
        _ => None,
    }
}

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

    fn schema_with_properties(props: serde_json::Value) -> ToolSchema {
        let properties: HashMap<String, serde_json::Value> = props
            .as_object()
            .unwrap()
            .iter()
            .map(|(k, v)| (k.clone(), v.clone()))
            .collect();
        ToolSchema {
            schema_type: "object".into(),
            properties,
            required: vec![],
        }
    }

    // --- Type checking ---

    #[test]
    fn validate_string_type() {
        let schema = schema_with_properties(serde_json::json!({
            "name": {"type": "string"}
        }));
        let compiled = CompiledSchema::compile(&schema).unwrap();

        assert!(
            compiled
                .validate(&serde_json::json!({"name": "alice"}))
                .is_ok()
        );
        assert!(compiled.validate(&serde_json::json!({"name": 42})).is_err());
    }

    #[test]
    fn validate_number_type() {
        let schema = schema_with_properties(serde_json::json!({
            "score": {"type": "number"}
        }));
        let compiled = CompiledSchema::compile(&schema).unwrap();

        assert!(
            compiled
                .validate(&serde_json::json!({"score": 3.15}))
                .is_ok()
        );
        assert!(compiled.validate(&serde_json::json!({"score": 42})).is_ok());
        assert!(
            compiled
                .validate(&serde_json::json!({"score": "abc"}))
                .is_err()
        );
    }

    #[test]
    fn validate_integer_type() {
        let schema = schema_with_properties(serde_json::json!({
            "count": {"type": "integer"}
        }));
        let compiled = CompiledSchema::compile(&schema).unwrap();

        assert!(compiled.validate(&serde_json::json!({"count": 42})).is_ok());
        assert!(
            compiled
                .validate(&serde_json::json!({"count": 3.15}))
                .is_err()
        );
    }

    #[test]
    fn validate_boolean_type() {
        let schema = schema_with_properties(serde_json::json!({
            "flag": {"type": "boolean"}
        }));
        let compiled = CompiledSchema::compile(&schema).unwrap();

        assert!(
            compiled
                .validate(&serde_json::json!({"flag": true}))
                .is_ok()
        );
        assert!(
            compiled
                .validate(&serde_json::json!({"flag": "yes"}))
                .is_err()
        );
    }

    #[test]
    fn validate_array_type() {
        let schema = schema_with_properties(serde_json::json!({
            "tags": {"type": "array", "items": {"type": "string"}}
        }));
        let compiled = CompiledSchema::compile(&schema).unwrap();

        assert!(
            compiled
                .validate(&serde_json::json!({"tags": ["a", "b"]}))
                .is_ok()
        );
        assert!(
            compiled
                .validate(&serde_json::json!({"tags": [1, 2]}))
                .is_err()
        );
        assert!(
            compiled
                .validate(&serde_json::json!({"tags": "not array"}))
                .is_err()
        );
    }

    #[test]
    fn validate_nested_object() {
        let schema = schema_with_properties(serde_json::json!({
            "config": {
                "type": "object",
                "properties": {
                    "host": {"type": "string"},
                    "port": {"type": "integer"}
                },
                "required": ["host"]
            }
        }));
        let compiled = CompiledSchema::compile(&schema).unwrap();

        assert!(
            compiled
                .validate(&serde_json::json!({"config": {"host": "localhost", "port": 8080}}))
                .is_ok()
        );
        assert!(
            compiled
                .validate(&serde_json::json!({"config": {"port": 8080}}))
                .is_err()
        ); // missing required host
        assert!(
            compiled
                .validate(&serde_json::json!({"config": {"host": 42}}))
                .is_err()
        ); // wrong type
    }

    // --- Enum constraints ---

    #[test]
    fn validate_string_enum() {
        let schema = schema_with_properties(serde_json::json!({
            "mode": {"type": "string", "enum": ["read", "write", "append"]}
        }));
        let compiled = CompiledSchema::compile(&schema).unwrap();

        assert!(
            compiled
                .validate(&serde_json::json!({"mode": "read"}))
                .is_ok()
        );
        assert!(
            compiled
                .validate(&serde_json::json!({"mode": "delete"}))
                .is_err()
        );
    }

    // --- Numeric bounds ---

    #[test]
    fn validate_number_bounds() {
        let schema = schema_with_properties(serde_json::json!({
            "age": {"type": "number", "minimum": 0, "maximum": 150}
        }));
        let compiled = CompiledSchema::compile(&schema).unwrap();

        assert!(compiled.validate(&serde_json::json!({"age": 25})).is_ok());
        assert!(compiled.validate(&serde_json::json!({"age": -1})).is_err());
        assert!(compiled.validate(&serde_json::json!({"age": 200})).is_err());
    }

    #[test]
    fn validate_integer_bounds() {
        let schema = schema_with_properties(serde_json::json!({
            "retries": {"type": "integer", "minimum": 0, "maximum": 5}
        }));
        let compiled = CompiledSchema::compile(&schema).unwrap();

        assert!(
            compiled
                .validate(&serde_json::json!({"retries": 3}))
                .is_ok()
        );
        assert!(
            compiled
                .validate(&serde_json::json!({"retries": -1}))
                .is_err()
        );
        assert!(
            compiled
                .validate(&serde_json::json!({"retries": 10}))
                .is_err()
        );
    }

    // --- Required fields ---

    #[test]
    fn validate_required_fields() {
        let mut schema = schema_with_properties(serde_json::json!({
            "name": {"type": "string"},
            "age": {"type": "integer"}
        }));
        schema.required = vec!["name".into()];
        let compiled = CompiledSchema::compile(&schema).unwrap();

        assert!(
            compiled
                .validate(&serde_json::json!({"name": "alice"}))
                .is_ok()
        );
        assert!(compiled.validate(&serde_json::json!({"age": 25})).is_err());
    }

    // --- Multiple violations ---

    #[test]
    fn multiple_violations_reported() {
        let mut schema = schema_with_properties(serde_json::json!({
            "name": {"type": "string"},
            "age": {"type": "integer"}
        }));
        schema.required = vec!["name".into(), "age".into()];
        let compiled = CompiledSchema::compile(&schema).unwrap();

        let result = compiled.validate(&serde_json::json!({}));
        let violations = result.unwrap_err();
        assert_eq!(violations.len(), 2);
    }

    // --- Default values ---

    #[test]
    fn apply_defaults_fills_missing() {
        let schema = schema_with_properties(serde_json::json!({
            "mode": {"type": "string", "default": "read"},
            "retries": {"type": "integer", "default": 3},
            "verbose": {"type": "boolean", "default": false}
        }));
        let compiled = CompiledSchema::compile(&schema).unwrap();

        let mut params = serde_json::json!({"mode": "write"});
        compiled.apply_defaults(&mut params);

        assert_eq!(params["mode"], "write"); // not overwritten
        assert_eq!(params["retries"], 3);
        assert_eq!(params["verbose"], false);
    }

    #[test]
    fn apply_defaults_no_op_for_non_object() {
        let schema = schema_with_properties(serde_json::json!({}));
        let compiled = CompiledSchema::compile(&schema).unwrap();

        let mut params = serde_json::json!("not an object");
        compiled.apply_defaults(&mut params);
        assert_eq!(params, serde_json::json!("not an object"));
    }

    // --- Backward compat ---

    #[test]
    fn empty_properties_still_validates_required() {
        let schema = ToolSchema {
            schema_type: "object".into(),
            properties: HashMap::new(),
            required: vec!["path".into()],
        };
        let compiled = CompiledSchema::compile(&schema).unwrap();

        assert!(
            compiled
                .validate(&serde_json::json!({"path": "/tmp"}))
                .is_ok()
        );
        assert!(compiled.validate(&serde_json::json!({})).is_err());
    }

    #[test]
    fn unknown_type_falls_back_to_any() {
        let schema = schema_with_properties(serde_json::json!({
            "data": {"type": "custom_type"}
        }));
        let compiled = CompiledSchema::compile(&schema).unwrap();

        // Any value should be accepted.
        assert!(compiled.validate(&serde_json::json!({"data": 42})).is_ok());
        assert!(
            compiled
                .validate(&serde_json::json!({"data": "hello"}))
                .is_ok()
        );
    }

    #[test]
    fn extra_fields_allowed() {
        let schema = schema_with_properties(serde_json::json!({
            "name": {"type": "string"}
        }));
        let compiled = CompiledSchema::compile(&schema).unwrap();

        // Extra field "extra" is not in schema but should be accepted.
        assert!(
            compiled
                .validate(&serde_json::json!({"name": "alice", "extra": 42}))
                .is_ok()
        );
    }

    #[test]
    fn non_object_params_rejected() {
        let schema = schema_with_properties(serde_json::json!({}));
        let compiled = CompiledSchema::compile(&schema).unwrap();

        let result = compiled.validate(&serde_json::json!("not an object"));
        assert!(result.is_err());
        assert!(result.unwrap_err()[0].contains("params must be an object"));
    }
}