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
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
// === QA Plan P0 - 1.1: Tool schema validator ===
//!
//! Validates tool parameter schemas against OpenAI strict-mode rules.
//!
//! This module provides a comprehensive validation function and a test that
//! exercises every built-in tool's `parameters_schema()` to ensure compatibility
//! with the OpenAI function calling API strict mode.
/// Strict CI-time validation of a JSON schema against OpenAI strict-mode rules.
///
/// Use this function in tests and CI to catch subtle schema defects that the
/// lenient runtime validator allows (freeform properties, missing
/// `additionalProperties`, enum-type mismatches).
///
/// For the lenient runtime variant used at tool-registration time, see
/// [`validate_tool_schema`](crate::tools::tool::validate_tool_schema) in
/// `tool.rs`.
///
/// Returns `Ok(())` if the schema is valid, or `Err(errors)` with a list of
/// all violations found. The validation is recursive for nested objects and
/// array items.
///
/// # Rules enforced
///
/// 1. Top-level must have `"type": "object"`
/// 2. Must have `"properties"` as a JSON object
/// 3. Every key in `"required"` must exist in `"properties"`
/// 4. Every property must have a `"type"` field (freeform/any-type is flagged)
/// 5. `"additionalProperties"` must be explicitly `false` if present
/// 6. Nested objects follow the same rules recursively
/// 7. `"enum"` values must match the declared type
/// 8. Array properties must have an `"items"` definition
pub fn validate_strict_schema(
schema: &serde_json::Value,
tool_name: &str,
) -> Result<(), Vec<String>> {
let errors = check_object_schema(schema, tool_name);
if errors.is_empty() {
Ok(())
} else {
Err(errors)
}
}
/// Returns true if the schema uses `oneOf`, `anyOf`, or `allOf` combinators
/// where at least one variant is an object type (has `type: "object"` or `properties`).
fn has_object_combinator_variants(schema: &serde_json::Value) -> bool {
for key in ["oneOf", "anyOf", "allOf"] {
if let Some(variants) = schema.get(key).and_then(|v| v.as_array())
&& variants.iter().any(|v| {
v.get("type").and_then(|t| t.as_str()) == Some("object")
|| v.get("properties").is_some()
})
{
return true;
}
}
false
}
/// Recursively validate an object-typed schema node.
fn check_object_schema(schema: &serde_json::Value, path: &str) -> Vec<String> {
let mut errors = Vec::new();
// Report non-array combinator values as errors.
for key in ["oneOf", "anyOf", "allOf"] {
if let Some(val) = schema.get(key)
&& !val.is_array()
{
errors.push(format!("{path}: \"{key}\" must be an array"));
}
}
let has_combinators = has_object_combinator_variants(schema);
// Rule 1: must have "type": "object" (unless combinators define the structure)
match schema.get("type").and_then(|t| t.as_str()) {
Some("object") => {}
Some(other) => {
errors.push(format!("{path}: expected type \"object\", got \"{other}\""));
return errors;
}
None => {
if !has_combinators {
errors.push(format!("{path}: missing \"type\": \"object\""));
return errors;
}
}
}
// Validate combinator variants recursively
for key in ["allOf", "oneOf", "anyOf"] {
if let Some(variants) = schema.get(key).and_then(|v| v.as_array()) {
for (i, variant) in variants.iter().enumerate() {
if variant.get("type").and_then(|t| t.as_str()) == Some("object")
|| variant.get("properties").is_some()
{
let variant_path = format!("{path}.{key}[{i}]");
errors.extend(check_object_schema(variant, &variant_path));
}
}
}
}
// Rule 2: must have "properties" as an object (unless combinators define them)
let properties = match schema.get("properties").and_then(|p| p.as_object()) {
Some(p) => p,
None => {
if !has_combinators {
errors.push(format!("{path}: missing or non-object \"properties\""));
return errors;
}
// Combinators define the structure — validate top-level `required` keys
// against merged properties from all combinator variants.
if let Some(required) = schema.get("required").and_then(|r| r.as_array()) {
let mut merged_keys = std::collections::HashSet::new();
if let Some(all_of) = schema.get("allOf").and_then(|a| a.as_array()) {
for variant in all_of {
if let Some(props) = variant.get("properties").and_then(|p| p.as_object()) {
merged_keys.extend(props.keys().cloned());
}
}
}
for key in ["oneOf", "anyOf"] {
if let Some(variants) = schema.get(key).and_then(|v| v.as_array()) {
for variant in variants {
if let Some(props) =
variant.get("properties").and_then(|p| p.as_object())
{
merged_keys.extend(props.keys().cloned());
}
}
}
}
for req in required {
if let Some(key) = req.as_str()
&& !merged_keys.contains(key)
{
errors.push(format!(
"{path}: required key \"{key}\" not found in any combinator variant properties"
));
}
}
}
return errors;
}
};
// Rule 3: every key in "required" must exist in "properties"
if let Some(required) = schema.get("required").and_then(|r| r.as_array()) {
for req in required {
if let Some(key) = req.as_str()
&& !properties.contains_key(key)
{
errors.push(format!(
"{path}: required key \"{key}\" not found in properties"
));
}
}
}
// Rule 4: every property should have a "type" field
for (key, prop) in properties {
let prop_path = format!("{path}.{key}");
if prop.get("type").is_none() {
// Freeform properties (no type) are intentionally allowed in some tools
// (json "data", http "body") for OpenAI compatibility with union types.
// We flag them as warnings but don't treat them as hard errors.
// Uncomment the next line to enforce strict typing:
// errors.push(format!("{prop_path}: property missing \"type\" field"));
continue;
}
let prop_type = prop.get("type").and_then(|t| t.as_str()).unwrap_or("");
// Rule 5: additionalProperties must be false if present
if let Some(additional) = prop.get("additionalProperties")
&& additional != &serde_json::Value::Bool(false)
// Allow additionalProperties with a type schema (e.g. {"type": "string"})
// which is valid in JSON Schema and used by tools like create_job's credentials.
&& additional.get("type").is_none()
{
errors.push(format!(
"{prop_path}: \"additionalProperties\" should be false or a type schema"
));
}
// Rule 7: enum values must match the declared type
if let Some(enum_values) = prop.get("enum").and_then(|e| e.as_array()) {
for (i, val) in enum_values.iter().enumerate() {
let type_matches = match prop_type {
"string" => val.is_string(),
"integer" | "number" => val.is_number(),
"boolean" => val.is_boolean(),
_ => true, // unknown types: skip check
};
if !type_matches {
errors.push(format!(
"{prop_path}: enum[{i}] value {val} does not match declared type \"{prop_type}\""
));
}
}
}
// Rule 6: nested objects follow the same rules
if prop_type == "object" {
// Objects with additionalProperties as a type schema (e.g. credentials map)
// are valid JSON Schema patterns, not strict-mode objects with fixed properties.
if prop.get("additionalProperties").is_some() && prop.get("properties").is_none() {
// This is a map type (e.g. {"type": "object", "additionalProperties": {"type": "string"}})
// Valid pattern, skip recursive object validation.
} else {
errors.extend(check_object_schema(prop, &prop_path));
}
}
// Rule 8: arrays must have "items"
if prop_type == "array" {
if prop.get("items").is_none() {
errors.push(format!("{prop_path}: array property missing \"items\""));
} else if let Some(items) = prop.get("items") {
// Recurse into items if they are objects
if items.get("type").and_then(|t| t.as_str()) == Some("object") {
errors.extend(check_object_schema(items, &format!("{prop_path}.items")));
}
}
}
}
// Also check top-level additionalProperties (rule 5)
if let Some(additional) = schema.get("additionalProperties")
&& additional != &serde_json::Value::Bool(false)
&& additional.get("type").is_none()
{
errors.push(format!(
"{path}: top-level \"additionalProperties\" should be false or a type schema"
));
}
errors
}
#[cfg(test)]
mod tests {
use super::*;
// ── Unit tests for the validator itself ──────────────────────────────
#[test]
fn test_valid_schema_passes() {
let schema = serde_json::json!({
"type": "object",
"properties": {
"name": { "type": "string", "description": "A name" }
},
"required": ["name"]
});
assert!(validate_strict_schema(&schema, "test").is_ok());
}
#[test]
fn test_missing_type_fails() {
let schema = serde_json::json!({
"properties": {
"name": { "type": "string" }
}
});
let err = validate_strict_schema(&schema, "test").unwrap_err();
assert!(err[0].contains("missing \"type\": \"object\""));
}
#[test]
fn test_wrong_type_fails() {
let schema = serde_json::json!({ "type": "string" });
let err = validate_strict_schema(&schema, "test").unwrap_err();
assert!(err[0].contains("expected type \"object\""));
}
#[test]
fn test_required_not_in_properties_fails() {
let schema = serde_json::json!({
"type": "object",
"properties": {
"name": { "type": "string" }
},
"required": ["name", "age"]
});
let err = validate_strict_schema(&schema, "test").unwrap_err();
assert!(err.iter().any(|e| e.contains("\"age\" not found")));
}
#[test]
fn test_nested_object_validated() {
let schema = serde_json::json!({
"type": "object",
"properties": {
"config": {
"type": "object",
"properties": {
"key": { "type": "string" }
},
"required": ["key", "missing"]
}
}
});
let err = validate_strict_schema(&schema, "test").unwrap_err();
assert!(
err.iter()
.any(|e| e.contains("test.config") && e.contains("\"missing\""))
);
}
#[test]
fn test_array_missing_items_fails() {
let schema = serde_json::json!({
"type": "object",
"properties": {
"tags": { "type": "array", "description": "Tags" }
}
});
let err = validate_strict_schema(&schema, "test").unwrap_err();
assert!(
err.iter()
.any(|e| e.contains("array property missing \"items\""))
);
}
#[test]
fn test_array_with_items_passes() {
let schema = serde_json::json!({
"type": "object",
"properties": {
"tags": {
"type": "array",
"items": { "type": "string" }
}
}
});
assert!(validate_strict_schema(&schema, "test").is_ok());
}
#[test]
fn test_enum_type_mismatch_fails() {
let schema = serde_json::json!({
"type": "object",
"properties": {
"mode": {
"type": "string",
"enum": ["fast", 42, "slow"]
}
}
});
let err = validate_strict_schema(&schema, "test").unwrap_err();
assert!(err.iter().any(|e| e.contains("enum[1]")));
}
#[test]
fn test_enum_matching_type_passes() {
let schema = serde_json::json!({
"type": "object",
"properties": {
"mode": {
"type": "string",
"enum": ["fast", "slow"]
}
}
});
assert!(validate_strict_schema(&schema, "test").is_ok());
}
#[test]
fn test_nested_array_items_object_validated() {
let schema = serde_json::json!({
"type": "object",
"properties": {
"headers": {
"type": "array",
"items": {
"type": "object",
"properties": {
"name": { "type": "string" }
},
"required": ["name", "ghost"]
}
}
}
});
let err = validate_strict_schema(&schema, "test").unwrap_err();
assert!(
err.iter()
.any(|e| e.contains("headers.items") && e.contains("\"ghost\""))
);
}
#[test]
fn test_additional_properties_false_passes() {
let schema = serde_json::json!({
"type": "object",
"properties": {
"header": {
"type": "object",
"properties": {
"name": { "type": "string" }
},
"additionalProperties": false
}
}
});
assert!(validate_strict_schema(&schema, "test").is_ok());
}
#[test]
fn test_additional_properties_type_schema_passes() {
// Map pattern: {"type": "object", "additionalProperties": {"type": "string"}}
let schema = serde_json::json!({
"type": "object",
"properties": {
"credentials": {
"type": "object",
"description": "Map of secret names to env var names",
"additionalProperties": { "type": "string" }
}
}
});
assert!(validate_strict_schema(&schema, "test").is_ok());
}
// ── Comprehensive test: validate ALL built-in tool schemas ───────────
#[test]
fn test_all_simple_tool_schemas() {
use crate::tools::Tool;
use crate::tools::builtin::{
ApplyPatchTool, EchoTool, HttpTool, JsonTool, ListDirTool, ReadFileTool, ShellTool,
TimeTool, WriteFileTool,
};
let tools: Vec<Box<dyn Tool>> = vec![
Box::new(EchoTool),
Box::new(TimeTool),
Box::new(JsonTool),
Box::new(HttpTool::new()),
Box::new(ShellTool::new()),
Box::new(ReadFileTool::new()),
Box::new(WriteFileTool::new()),
Box::new(ListDirTool::new()),
Box::new(ApplyPatchTool::new()),
];
let mut failures = Vec::new();
for tool in &tools {
let schema = tool.parameters_schema();
if let Err(errors) = validate_strict_schema(&schema, tool.name()) {
failures.push(format!("Tool '{}': {}", tool.name(), errors.join("; ")));
}
}
assert!(
failures.is_empty(),
"Schema validation failures:\n{}",
failures.join("\n")
);
}
#[test]
fn test_job_tool_schemas() {
use std::sync::Arc;
use crate::context::ContextManager;
use crate::tools::Tool;
use crate::tools::builtin::{CancelJobTool, CreateJobTool, JobStatusTool, ListJobsTool};
let ctx_mgr = Arc::new(ContextManager::new(5));
let tools: Vec<Box<dyn Tool>> = vec![
Box::new(CreateJobTool::new(Arc::clone(&ctx_mgr))),
Box::new(ListJobsTool::new(Arc::clone(&ctx_mgr))),
Box::new(JobStatusTool::new(Arc::clone(&ctx_mgr))),
Box::new(CancelJobTool::new(Arc::clone(&ctx_mgr))),
];
let mut failures = Vec::new();
for tool in &tools {
let schema = tool.parameters_schema();
if let Err(errors) = validate_strict_schema(&schema, tool.name()) {
failures.push(format!("Tool '{}': {}", tool.name(), errors.join("; ")));
}
}
assert!(
failures.is_empty(),
"Schema validation failures:\n{}",
failures.join("\n")
);
}
#[test]
fn test_skill_tool_schemas() {
use std::sync::Arc;
use crate::skills::catalog::SkillCatalog;
use crate::skills::registry::SkillRegistry;
use crate::tools::Tool;
use crate::tools::builtin::{
SkillInstallTool, SkillListTool, SkillRemoveTool, SkillSearchTool,
};
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.keep();
let registry = Arc::new(std::sync::RwLock::new(SkillRegistry::new(path)));
let catalog = Arc::new(SkillCatalog::with_url("http://127.0.0.1:1"));
let tools: Vec<Box<dyn Tool>> = vec![
Box::new(SkillListTool::new(Arc::clone(®istry))),
Box::new(SkillSearchTool::new(
Arc::clone(®istry),
Arc::clone(&catalog),
)),
Box::new(SkillInstallTool::new(
Arc::clone(®istry),
Arc::clone(&catalog),
)),
Box::new(SkillRemoveTool::new(Arc::clone(®istry))),
];
let mut failures = Vec::new();
for tool in &tools {
let schema = tool.parameters_schema();
if let Err(errors) = validate_strict_schema(&schema, tool.name()) {
failures.push(format!("Tool '{}': {}", tool.name(), errors.join("; ")));
}
}
assert!(
failures.is_empty(),
"Schema validation failures:\n{}",
failures.join("\n")
);
}
/// Validate schemas from tools that cannot be easily constructed by
/// inlining the JSON schema directly. This covers the extension tools and
/// routine tools whose constructors require heavy dependencies.
#[test]
fn test_inline_schemas_for_complex_tools() {
// These schemas are extracted from the source code of tools with complex deps.
// If the source schemas change, these tests serve as a canary.
let schemas: Vec<(&str, serde_json::Value)> = vec![
// Extension tools
(
"tool_search",
serde_json::json!({
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "Search query"
},
"discover": {
"type": "boolean",
"description": "Search online",
"default": false
}
},
"required": ["query"]
}),
),
(
"tool_install",
serde_json::json!({
"type": "object",
"properties": {
"name": { "type": "string", "description": "Extension name" },
"url": { "type": "string", "description": "Explicit URL" },
"kind": {
"type": "string",
"enum": ["mcp_server", "wasm_tool", "wasm_channel"],
"description": "Extension type"
}
},
"required": ["name"]
}),
),
(
"tool_auth",
serde_json::json!({
"type": "object",
"properties": {
"name": { "type": "string", "description": "Extension name" }
},
"required": ["name"]
}),
),
(
"tool_activate",
serde_json::json!({
"type": "object",
"properties": {
"name": { "type": "string", "description": "Extension name" }
},
"required": ["name"]
}),
),
(
"tool_list",
serde_json::json!({
"type": "object",
"properties": {
"kind": {
"type": "string",
"enum": ["mcp_server", "wasm_tool", "wasm_channel"],
"description": "Filter by extension type"
},
"include_available": {
"type": "boolean",
"description": "Include not-yet-installed entries",
"default": false
}
}
}),
),
(
"tool_remove",
serde_json::json!({
"type": "object",
"properties": {
"name": { "type": "string", "description": "Extension name" }
},
"required": ["name"]
}),
),
// Routine tools
(
"routine_create",
crate::tools::builtin::routine::routine_create_parameters_schema(),
),
(
"routine_list",
serde_json::json!({
"type": "object",
"properties": {},
"required": []
}),
),
(
"routine_update",
crate::tools::builtin::routine::routine_update_parameters_schema(),
),
(
"routine_delete",
serde_json::json!({
"type": "object",
"properties": {
"name": { "type": "string", "description": "Name" }
},
"required": ["name"]
}),
),
(
"routine_fire",
serde_json::json!({
"type": "object",
"properties": {
"name": { "type": "string", "description": "Routine name" }
},
"required": ["name"]
}),
),
(
"routine_history",
serde_json::json!({
"type": "object",
"properties": {
"name": { "type": "string", "description": "Routine name" },
"limit": { "type": "integer", "description": "Max runs", "default": 10 }
},
"required": ["name"]
}),
),
(
"event_emit",
crate::tools::builtin::routine::event_emit_parameters_schema(),
),
// Job tools with complex deps
(
"job_events",
serde_json::json!({
"type": "object",
"properties": {
"job_id": { "type": "string", "description": "Job ID" },
"limit": { "type": "integer", "description": "Max events" }
},
"required": ["job_id"]
}),
),
(
"job_prompt",
serde_json::json!({
"type": "object",
"properties": {
"job_id": { "type": "string", "description": "Job ID" },
"content": { "type": "string", "description": "Prompt text" },
"done": { "type": "boolean", "description": "Signal finish" }
},
"required": ["job_id", "content"]
}),
),
];
let mut failures = Vec::new();
for (name, schema) in &schemas {
if let Err(errors) = validate_strict_schema(schema, name) {
failures.push(format!("Tool '{}': {}", name, errors.join("; ")));
}
}
assert!(
failures.is_empty(),
"Schema validation failures for inline schemas:\n{}",
failures.join("\n")
);
}
/// Validate that the memory tool schemas (which need Workspace) are correct.
/// Since Workspace requires a database connection, we validate the schemas
/// are structurally correct by inlining them.
#[test]
fn test_memory_tool_schemas_inline() {
let schemas: Vec<(&str, serde_json::Value)> = vec![
(
"memory_search",
serde_json::json!({
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "Search query"
},
"limit": {
"type": "integer",
"description": "Max results",
"default": 5,
"minimum": 1,
"maximum": 20
}
},
"required": ["query"]
}),
),
(
"memory_write",
serde_json::json!({
"type": "object",
"properties": {
"content": { "type": "string", "description": "Content to write" },
"target": { "type": "string", "description": "Where to write", "default": "daily_log" },
"append": { "type": "boolean", "description": "Append or replace", "default": true }
},
"required": ["content"]
}),
),
(
"memory_read",
serde_json::json!({
"type": "object",
"properties": {
"path": { "type": "string", "description": "Path to read" }
},
"required": ["path"]
}),
),
(
"memory_tree",
serde_json::json!({
"type": "object",
"properties": {
"path": { "type": "string", "description": "Root path", "default": "" },
"depth": { "type": "integer", "description": "Max depth", "default": 1, "minimum": 1, "maximum": 10 }
}
}),
),
];
let mut failures = Vec::new();
for (name, schema) in &schemas {
if let Err(errors) = validate_strict_schema(schema, name) {
failures.push(format!("Tool '{}': {}", name, errors.join("; ")));
}
}
assert!(
failures.is_empty(),
"Schema validation failures for memory tool schemas:\n{}",
failures.join("\n")
);
}
// ── WASM and MCP tool schema validation (QA 1.1 extension) ─────────
/// Representative WASM tool schemas -- these mirror the shapes produced by
/// `WasmToolWrapper::parameters_schema()` from real WASM modules.
#[test]
fn test_wasm_tool_schemas() {
let schemas: Vec<(&str, serde_json::Value)> = vec![
// Typical WASM tool with simple params
(
"wasm_weather",
serde_json::json!({
"type": "object",
"properties": {
"city": { "type": "string", "description": "City name" },
"units": {
"type": "string",
"enum": ["celsius", "fahrenheit"],
"description": "Temperature units"
}
},
"required": ["city"]
}),
),
// WASM tool with nested object (e.g., HTTP tool)
(
"wasm_http_client",
serde_json::json!({
"type": "object",
"properties": {
"url": { "type": "string", "description": "URL to fetch" },
"method": {
"type": "string",
"enum": ["GET", "POST", "PUT", "DELETE"],
"description": "HTTP method"
},
"headers": {
"type": "object",
"properties": {},
"description": "Custom headers"
},
"body": { "type": "string", "description": "Request body" }
},
"required": ["url"]
}),
),
// WASM tool with array params
(
"wasm_batch_processor",
serde_json::json!({
"type": "object",
"properties": {
"items": {
"type": "array",
"items": { "type": "string" },
"description": "Items to process"
},
"parallel": { "type": "boolean", "description": "Run in parallel" }
},
"required": ["items"]
}),
),
// Empty WASM tool (no required params)
(
"wasm_status",
serde_json::json!({
"type": "object",
"properties": {}
}),
),
];
let mut failures = Vec::new();
for (name, schema) in &schemas {
if let Err(errors) = validate_strict_schema(schema, name) {
failures.push(format!("WASM tool '{}': {}", name, errors.join("; ")));
}
}
assert!(
failures.is_empty(),
"Schema validation failures for WASM tool schemas:\n{}",
failures.join("\n")
);
}
/// Representative MCP tool schemas -- these mirror the shapes received from
/// MCP servers via `McpTool::input_schema` (camelCase `inputSchema` in protocol).
#[test]
fn test_mcp_tool_schemas() {
let schemas: Vec<(&str, serde_json::Value)> = vec![
// Default MCP schema (empty object -- from default_input_schema())
(
"mcp_default",
serde_json::json!({"type": "object", "properties": {}}),
),
// Typical MCP server tool (e.g., filesystem server)
(
"mcp_read_file",
serde_json::json!({
"type": "object",
"properties": {
"path": { "type": "string", "description": "File path to read" }
},
"required": ["path"]
}),
),
// MCP tool with complex nested params (e.g., database query)
(
"mcp_sql_query",
serde_json::json!({
"type": "object",
"properties": {
"query": { "type": "string", "description": "SQL query to execute" },
"params": {
"type": "array",
"items": { "type": "string" },
"description": "Query parameters"
},
"timeout_ms": {
"type": "integer",
"description": "Query timeout in milliseconds"
}
},
"required": ["query"]
}),
),
// MCP tool with additionalProperties: false (strict server)
(
"mcp_strict_tool",
serde_json::json!({
"type": "object",
"properties": {
"action": {
"type": "string",
"enum": ["start", "stop", "restart"],
"description": "Action to perform"
}
},
"required": ["action"],
"additionalProperties": false
}),
),
];
let mut failures = Vec::new();
for (name, schema) in &schemas {
if let Err(errors) = validate_strict_schema(schema, name) {
failures.push(format!("MCP tool '{}': {}", name, errors.join("; ")));
}
}
assert!(
failures.is_empty(),
"Schema validation failures for MCP tool schemas:\n{}",
failures.join("\n")
);
}
/// Verify the validator catches common issues in externally-sourced schemas.
/// WASM modules and MCP servers may produce schemas with defects that
/// built-in tools wouldn't have.
#[test]
fn test_external_schema_defects_detected() {
// Missing top-level type (MCP server omitted it)
let bad_no_type = serde_json::json!({
"properties": {
"query": { "type": "string" }
}
});
assert!(validate_strict_schema(&bad_no_type, "ext_no_type").is_err());
// Required key not in properties (WASM module typo)
let bad_required = serde_json::json!({
"type": "object",
"properties": {
"input": { "type": "string" }
},
"required": ["inpt"]
});
assert!(validate_strict_schema(&bad_required, "ext_typo").is_err());
// Array without items definition (MCP server bug)
let bad_array = serde_json::json!({
"type": "object",
"properties": {
"tags": { "type": "array" }
}
});
assert!(validate_strict_schema(&bad_array, "ext_no_items").is_err());
// Enum type mismatch (WASM module declares string enum with integers)
let bad_enum = serde_json::json!({
"type": "object",
"properties": {
"mode": {
"type": "string",
"enum": [1, 2, 3]
}
}
});
assert!(validate_strict_schema(&bad_enum, "ext_enum_mismatch").is_err());
// Nested object without type (deeply nested MCP schema)
let bad_nested = serde_json::json!({
"type": "object",
"properties": {
"config": {
"type": "object",
"properties": {
"setting": { "description": "missing type field" }
}
}
}
});
// This may pass or fail depending on whether we enforce type on every
// nested property -- the validator allows freeform for compatibility.
// The important thing is it doesn't panic.
let _ = validate_strict_schema(&bad_nested, "ext_nested_no_type");
}
}