agent-tools-interface 0.7.11

Agent Tools Interface — secure CLI for AI agent tool execution
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
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
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
/// Integration tests for OpenAPI handler support.
///
/// Tests:
/// - Manifest loading with handler = "openapi"
/// - Tool registration from OpenAPI spec
/// - Parameter classification (path/query/header/body)
/// - Path parameter substitution
/// - Tag/operation filtering
/// - Auth detection
/// - ManifestRegistry integration (tools appear in list, search, etc.)
/// - Proxy server serves OpenAPI tools via /call, /mcp, /health
use tempfile::TempDir;

// ---------------------------------------------------------------------------
// Helper: create a test OpenAPI spec + TOML manifest in a temp directory
// ---------------------------------------------------------------------------

const PETSTORE_SPEC: &str = r#"{
    "openapi": "3.0.3",
    "info": {
        "title": "Petstore",
        "version": "1.0.0",
        "description": "A sample pet store API"
    },
    "servers": [{ "url": "https://petstore.example.com/v3" }],
    "paths": {
        "/pet/{petId}": {
            "get": {
                "operationId": "getPetById",
                "summary": "Find pet by ID",
                "description": "Returns a single pet",
                "tags": ["pet"],
                "parameters": [
                    {
                        "name": "petId",
                        "in": "path",
                        "required": true,
                        "schema": { "type": "integer", "format": "int64" },
                        "description": "ID of pet to return"
                    }
                ],
                "responses": { "200": { "description": "successful operation" } }
            },
            "delete": {
                "operationId": "deletePet",
                "summary": "Deletes a pet",
                "tags": ["pet"],
                "parameters": [
                    {
                        "name": "petId",
                        "in": "path",
                        "required": true,
                        "schema": { "type": "integer" }
                    },
                    {
                        "name": "api_key",
                        "in": "header",
                        "schema": { "type": "string" }
                    }
                ],
                "responses": { "200": { "description": "successful operation" } }
            }
        },
        "/pet": {
            "post": {
                "operationId": "addPet",
                "summary": "Add a new pet to the store",
                "tags": ["pet"],
                "requestBody": {
                    "required": true,
                    "content": {
                        "application/json": {
                            "schema": {
                                "type": "object",
                                "required": ["name"],
                                "properties": {
                                    "name": {
                                        "type": "string",
                                        "description": "Pet name"
                                    },
                                    "status": {
                                        "type": "string",
                                        "description": "Pet status in the store",
                                        "enum": ["available", "pending", "sold"]
                                    },
                                    "photoUrls": {
                                        "type": "array",
                                        "items": { "type": "string" }
                                    }
                                }
                            }
                        }
                    }
                },
                "responses": { "200": { "description": "OK" } }
            }
        },
        "/pet/findByStatus": {
            "get": {
                "operationId": "findPetsByStatus",
                "summary": "Finds Pets by status",
                "tags": ["pet"],
                "parameters": [
                    {
                        "name": "status",
                        "in": "query",
                        "description": "Status values to filter by",
                        "schema": { "type": "string", "enum": ["available", "pending", "sold"] }
                    }
                ],
                "responses": { "200": { "description": "OK" } }
            }
        },
        "/store/inventory": {
            "get": {
                "operationId": "getInventory",
                "summary": "Returns pet inventories by status",
                "tags": ["store"],
                "responses": { "200": { "description": "OK" } }
            }
        },
        "/user/{username}": {
            "get": {
                "operationId": "getUserByName",
                "summary": "Get user by user name",
                "tags": ["user"],
                "parameters": [
                    {
                        "name": "username",
                        "in": "path",
                        "required": true,
                        "schema": { "type": "string" }
                    }
                ],
                "responses": { "200": { "description": "OK" } }
            }
        }
    },
    "components": {
        "securitySchemes": {
            "api_key": {
                "type": "apiKey",
                "in": "header",
                "name": "api_key"
            },
            "petstore_auth": {
                "type": "oauth2",
                "flows": {
                    "clientCredentials": {
                        "tokenUrl": "https://petstore.example.com/oauth/token",
                        "scopes": {}
                    }
                }
            }
        }
    }
}"#;

/// Create a temp dir with specs/ and manifests/ subdirectories.
fn create_test_ati_dir(manifest_toml: &str, spec_json: &str, spec_filename: &str) -> TempDir {
    let dir = TempDir::new().unwrap();
    let specs_dir = dir.path().join("specs");
    let manifests_dir = dir.path().join("manifests");
    std::fs::create_dir_all(&specs_dir).unwrap();
    std::fs::create_dir_all(&manifests_dir).unwrap();

    // Write spec
    std::fs::write(specs_dir.join(spec_filename), spec_json).unwrap();

    // Write manifest
    std::fs::write(manifests_dir.join("petstore.toml"), manifest_toml).unwrap();

    dir
}

// ---------------------------------------------------------------------------
// Test: manifest loading with handler = "openapi" registers tools
// ---------------------------------------------------------------------------

#[test]
fn test_openapi_manifest_loads_tools() {
    let manifest = r#"
[provider]
name = "petstore"
description = "Petstore API"
handler = "openapi"
base_url = "https://petstore.example.com/v3"
openapi_spec = "petstore.json"
auth_type = "none"
"#;

    let dir = create_test_ati_dir(manifest, PETSTORE_SPEC, "petstore.json");
    let registry =
        ati::core::manifest::ManifestRegistry::load(&dir.path().join("manifests")).unwrap();

    // Should have discovered all 6 operations
    let tools = registry.list_public_tools();
    assert!(tools.len() >= 6, "Expected >= 6 tools, got {}", tools.len());

    // Check specific tools exist with correct prefixed names
    assert!(registry.get_tool("petstore:getPetById").is_some());
    assert!(registry.get_tool("petstore:addPet").is_some());
    assert!(registry.get_tool("petstore:findPetsByStatus").is_some());
    assert!(registry.get_tool("petstore:getInventory").is_some());
    assert!(registry.get_tool("petstore:getUserByName").is_some());
    assert!(registry.get_tool("petstore:deletePet").is_some());
}

// ---------------------------------------------------------------------------
// Test: tag filtering (include_tags)
// ---------------------------------------------------------------------------

#[test]
fn test_openapi_include_tags_filter() {
    let manifest = r#"
[provider]
name = "petstore"
description = "Petstore API"
handler = "openapi"
base_url = "https://petstore.example.com/v3"
openapi_spec = "petstore.json"
auth_type = "none"
openapi_include_tags = ["pet"]
"#;

    let dir = create_test_ati_dir(manifest, PETSTORE_SPEC, "petstore.json");
    let registry =
        ati::core::manifest::ManifestRegistry::load(&dir.path().join("manifests")).unwrap();

    let tools: Vec<_> = registry
        .list_public_tools()
        .into_iter()
        .filter(|(p, _)| p.name == "petstore")
        .collect();
    // Only pet-tagged operations: getPetById, deletePet, addPet, findPetsByStatus
    assert_eq!(
        tools.len(),
        4,
        "Expected 4 pet-tagged tools, got {}",
        tools.len()
    );

    // Store and user tools should NOT be present
    assert!(registry.get_tool("petstore:getInventory").is_none());
    assert!(registry.get_tool("petstore:getUserByName").is_none());
}

// ---------------------------------------------------------------------------
// Test: exclude tags filter
// ---------------------------------------------------------------------------

#[test]
fn test_openapi_exclude_tags_filter() {
    let manifest = r#"
[provider]
name = "petstore"
description = "Petstore API"
handler = "openapi"
base_url = "https://petstore.example.com/v3"
openapi_spec = "petstore.json"
auth_type = "none"
openapi_exclude_tags = ["store", "user"]
"#;

    let dir = create_test_ati_dir(manifest, PETSTORE_SPEC, "petstore.json");
    let registry =
        ati::core::manifest::ManifestRegistry::load(&dir.path().join("manifests")).unwrap();

    // Only pet-tagged operations remain
    assert!(registry.get_tool("petstore:getInventory").is_none());
    assert!(registry.get_tool("petstore:getUserByName").is_none());
    assert!(registry.get_tool("petstore:getPetById").is_some());
}

// ---------------------------------------------------------------------------
// Test: max_operations cap
// ---------------------------------------------------------------------------

#[test]
fn test_openapi_max_operations() {
    let manifest = r#"
[provider]
name = "petstore"
description = "Petstore API"
handler = "openapi"
base_url = "https://petstore.example.com/v3"
openapi_spec = "petstore.json"
auth_type = "none"
openapi_max_operations = 2
"#;

    let dir = create_test_ati_dir(manifest, PETSTORE_SPEC, "petstore.json");
    let registry =
        ati::core::manifest::ManifestRegistry::load(&dir.path().join("manifests")).unwrap();

    let tools: Vec<_> = registry
        .list_public_tools()
        .into_iter()
        .filter(|(p, _)| p.name == "petstore")
        .collect();
    assert_eq!(
        tools.len(),
        2,
        "Expected exactly 2 tools (capped), got {}",
        tools.len()
    );
}

// ---------------------------------------------------------------------------
// Test: exclude_operations filter
// ---------------------------------------------------------------------------

#[test]
fn test_openapi_exclude_operations() {
    let manifest = r#"
[provider]
name = "petstore"
description = "Petstore API"
handler = "openapi"
base_url = "https://petstore.example.com/v3"
openapi_spec = "petstore.json"
auth_type = "none"
openapi_exclude_operations = ["deletePet", "getInventory"]
"#;

    let dir = create_test_ati_dir(manifest, PETSTORE_SPEC, "petstore.json");
    let registry =
        ati::core::manifest::ManifestRegistry::load(&dir.path().join("manifests")).unwrap();

    assert!(registry.get_tool("petstore:deletePet").is_none());
    assert!(registry.get_tool("petstore:getInventory").is_none());
    assert!(registry.get_tool("petstore:getPetById").is_some());
    assert!(registry.get_tool("petstore:addPet").is_some());
}

// ---------------------------------------------------------------------------
// Test: tool properties have correct structure
// ---------------------------------------------------------------------------

#[test]
fn test_openapi_tool_properties() {
    let manifest = r#"
[provider]
name = "petstore"
description = "Petstore API"
handler = "openapi"
base_url = "https://petstore.example.com/v3"
openapi_spec = "petstore.json"
auth_type = "none"
"#;

    let dir = create_test_ati_dir(manifest, PETSTORE_SPEC, "petstore.json");
    let registry =
        ati::core::manifest::ManifestRegistry::load(&dir.path().join("manifests")).unwrap();

    // Check getPetById tool properties
    let (provider, tool) = registry.get_tool("petstore:getPetById").unwrap();
    assert_eq!(provider.name, "petstore");
    assert_eq!(provider.handler, "openapi");
    assert!(tool.description.contains("Find pet by ID"));
    assert_eq!(tool.endpoint, "/pet/{petId}");

    // Check input schema has petId param with path location
    let schema = tool.input_schema.as_ref().unwrap();
    let props = schema.get("properties").unwrap().as_object().unwrap();
    let pet_id_prop = props.get("petId").unwrap();
    assert_eq!(
        pet_id_prop
            .get("x-ati-param-location")
            .unwrap()
            .as_str()
            .unwrap(),
        "path"
    );
    assert_eq!(
        pet_id_prop.get("type").unwrap().as_str().unwrap(),
        "integer"
    );

    // Check required fields
    let required = schema.get("required").unwrap().as_array().unwrap();
    assert!(required.iter().any(|r| r.as_str() == Some("petId")));

    // Check tags come from the spec
    assert!(tool.tags.contains(&"pet".to_string()));
}

// ---------------------------------------------------------------------------
// Test: request body params get body location
// ---------------------------------------------------------------------------

#[test]
fn test_openapi_body_params_location() {
    let manifest = r#"
[provider]
name = "petstore"
description = "Petstore API"
handler = "openapi"
base_url = "https://petstore.example.com/v3"
openapi_spec = "petstore.json"
auth_type = "none"
"#;

    let dir = create_test_ati_dir(manifest, PETSTORE_SPEC, "petstore.json");
    let registry =
        ati::core::manifest::ManifestRegistry::load(&dir.path().join("manifests")).unwrap();

    let (_, tool) = registry.get_tool("petstore:addPet").unwrap();
    let schema = tool.input_schema.as_ref().unwrap();
    let props = schema.get("properties").unwrap().as_object().unwrap();

    // Body params should have x-ati-param-location = "body"
    let name_prop = props.get("name").unwrap();
    assert_eq!(
        name_prop
            .get("x-ati-param-location")
            .unwrap()
            .as_str()
            .unwrap(),
        "body"
    );
}

// ---------------------------------------------------------------------------
// Test: query params get query location
// ---------------------------------------------------------------------------

#[test]
fn test_openapi_query_params_location() {
    let manifest = r#"
[provider]
name = "petstore"
description = "Petstore API"
handler = "openapi"
base_url = "https://petstore.example.com/v3"
openapi_spec = "petstore.json"
auth_type = "none"
"#;

    let dir = create_test_ati_dir(manifest, PETSTORE_SPEC, "petstore.json");
    let registry =
        ati::core::manifest::ManifestRegistry::load(&dir.path().join("manifests")).unwrap();

    let (_, tool) = registry.get_tool("petstore:findPetsByStatus").unwrap();
    let schema = tool.input_schema.as_ref().unwrap();
    let props = schema.get("properties").unwrap().as_object().unwrap();

    let status_prop = props.get("status").unwrap();
    assert_eq!(
        status_prop
            .get("x-ati-param-location")
            .unwrap()
            .as_str()
            .unwrap(),
        "query"
    );
}

// ---------------------------------------------------------------------------
// Test: per-operation overrides
// ---------------------------------------------------------------------------

#[test]
fn test_openapi_overrides() {
    let manifest = r#"
[provider]
name = "petstore"
description = "Petstore API"
handler = "openapi"
base_url = "https://petstore.example.com/v3"
openapi_spec = "petstore.json"
auth_type = "none"

[provider.openapi_overrides.getPetById]
hint = "Use this to fetch a single pet by its numeric ID"
description = "Get a pet (overridden)"
tags = ["lookup", "single-entity"]
"#;

    let dir = create_test_ati_dir(manifest, PETSTORE_SPEC, "petstore.json");
    let registry =
        ati::core::manifest::ManifestRegistry::load(&dir.path().join("manifests")).unwrap();

    let (_, tool) = registry.get_tool("petstore:getPetById").unwrap();
    assert_eq!(tool.description, "Get a pet (overridden)");
    assert_eq!(
        tool.hint.as_deref(),
        Some("Use this to fetch a single pet by its numeric ID")
    );
    // Tags should be merged (spec tags + override tags)
    assert!(tool.tags.contains(&"pet".to_string()));
    assert!(tool.tags.contains(&"lookup".to_string()));
    assert!(tool.tags.contains(&"single-entity".to_string()));
}

// ---------------------------------------------------------------------------
// Test: graceful degradation when spec file is missing
// ---------------------------------------------------------------------------

#[test]
fn test_openapi_missing_spec_graceful() {
    let manifest = r#"
[provider]
name = "broken"
description = "Broken API"
handler = "openapi"
base_url = "https://example.com"
openapi_spec = "nonexistent.json"
auth_type = "none"
"#;

    let dir = TempDir::new().unwrap();
    let manifests_dir = dir.path().join("manifests");
    std::fs::create_dir_all(&manifests_dir).unwrap();
    std::fs::write(manifests_dir.join("broken.toml"), manifest).unwrap();

    // Should not panic — graceful degradation
    let registry = ati::core::manifest::ManifestRegistry::load(&manifests_dir).unwrap();
    // Provider loads but with 0 tools (excluding the built-in file_manager provider)
    let tools: Vec<_> = registry
        .list_public_tools()
        .into_iter()
        .filter(|(p, _)| p.name != "file_manager")
        .collect();
    assert_eq!(tools.len(), 0);
}

// ---------------------------------------------------------------------------
// Test: OpenAPI tools coexist with HTTP tools
// ---------------------------------------------------------------------------

#[test]
fn test_openapi_coexists_with_http_tools() {
    let dir = TempDir::new().unwrap();
    let specs_dir = dir.path().join("specs");
    let manifests_dir = dir.path().join("manifests");
    std::fs::create_dir_all(&specs_dir).unwrap();
    std::fs::create_dir_all(&manifests_dir).unwrap();

    // Write OpenAPI spec
    std::fs::write(specs_dir.join("petstore.json"), PETSTORE_SPEC).unwrap();

    // Write OpenAPI manifest
    let openapi_manifest = r#"
[provider]
name = "petstore"
description = "Petstore API"
handler = "openapi"
base_url = "https://petstore.example.com/v3"
openapi_spec = "petstore.json"
auth_type = "none"
"#;
    std::fs::write(manifests_dir.join("petstore.toml"), openapi_manifest).unwrap();

    // Write a traditional HTTP manifest
    let http_manifest = r#"
[provider]
name = "example_http"
description = "Example HTTP API"
base_url = "https://api.example.com"
auth_type = "bearer"
auth_key_name = "example_key"

[[tools]]
name = "search"
description = "Search for things"
endpoint = "/search"
method = "GET"

[tools.input_schema]
type = "object"

[tools.input_schema.properties.q]
type = "string"
description = "Search query"
"#;
    std::fs::write(manifests_dir.join("example.toml"), http_manifest).unwrap();

    let registry = ati::core::manifest::ManifestRegistry::load(&manifests_dir).unwrap();

    // Both providers should be present
    let providers = registry.list_providers();
    assert!(providers.len() >= 2);

    // Both tool types should be accessible
    assert!(registry.get_tool("petstore:getPetById").is_some());
    assert!(registry.get_tool("search").is_some());

    // Total tools: 6 OpenAPI + 1 HTTP = 7
    let tools = registry.list_public_tools();
    assert!(tools.len() >= 7, "Expected >= 7 tools, got {}", tools.len());
}

// ---------------------------------------------------------------------------
// Test: auth detection from spec
// ---------------------------------------------------------------------------

#[test]
fn test_auth_detection_bearer() {
    let spec_json = r#"{
        "openapi": "3.0.3",
        "info": { "title": "Test", "version": "1.0.0" },
        "paths": {},
        "components": {
            "securitySchemes": {
                "bearerAuth": {
                    "type": "http",
                    "scheme": "bearer"
                }
            }
        }
    }"#;

    let spec = ati::core::openapi::parse_spec(spec_json).unwrap();
    let (auth_type, extra) = ati::core::openapi::detect_auth(&spec);
    assert_eq!(auth_type, "bearer");
    assert!(extra.is_empty());
}

#[test]
fn test_auth_detection_apikey_query() {
    let spec_json = r#"{
        "openapi": "3.0.3",
        "info": { "title": "Test", "version": "1.0.0" },
        "paths": {},
        "components": {
            "securitySchemes": {
                "apiKey": {
                    "type": "apiKey",
                    "in": "query",
                    "name": "appid"
                }
            }
        }
    }"#;

    let spec = ati::core::openapi::parse_spec(spec_json).unwrap();
    let (auth_type, extra) = ati::core::openapi::detect_auth(&spec);
    assert_eq!(auth_type, "query");
    assert_eq!(extra.get("auth_query_name").unwrap(), "appid");
}

#[test]
fn test_auth_detection_oauth2() {
    let spec = ati::core::openapi::parse_spec(PETSTORE_SPEC).unwrap();
    let (auth_type, extra) = ati::core::openapi::detect_auth(&spec);
    // The petstore spec has both apiKey and oauth2 — first match wins
    // apiKey comes first alphabetically
    assert!(
        auth_type == "header" || auth_type == "oauth2",
        "Expected header or oauth2, got: {auth_type}"
    );
    if auth_type == "oauth2" {
        assert!(extra.contains_key("oauth2_token_url"));
    }
}

// ---------------------------------------------------------------------------
// Test: path parameter substitution
// ---------------------------------------------------------------------------

#[test]
fn test_path_param_substitution() {
    use ati::core::openapi;

    let spec = openapi::parse_spec(PETSTORE_SPEC).unwrap();
    let filters = openapi::OpenApiFilters {
        include_tags: vec![],
        exclude_tags: vec![],
        include_operations: vec!["getPetById".to_string()],
        exclude_operations: vec![],
        max_operations: None,
    };
    let tools = openapi::extract_tools(&spec, &filters);
    assert_eq!(tools.len(), 1);
    assert_eq!(tools[0].endpoint, "/pet/{petId}");

    // Verify the tool has path location metadata
    let schema = &tools[0].input_schema;
    let props = schema.get("properties").unwrap().as_object().unwrap();
    let pet_id = props.get("petId").unwrap();
    assert_eq!(
        pet_id
            .get("x-ati-param-location")
            .unwrap()
            .as_str()
            .unwrap(),
        "path"
    );
}

// ---------------------------------------------------------------------------
// Test: YAML spec parsing
// ---------------------------------------------------------------------------

#[test]
fn test_yaml_spec_parsing() {
    let yaml_spec = r#"
openapi: "3.0.3"
info:
  title: YAML Test API
  version: "1.0.0"
paths:
  /hello:
    get:
      operationId: sayHello
      summary: Say hello
      responses:
        "200":
          description: OK
"#;

    let spec = ati::core::openapi::parse_spec(yaml_spec).unwrap();
    assert_eq!(spec.info.title, "YAML Test API");

    let ops = ati::core::openapi::list_operations(&spec);
    assert_eq!(ops.len(), 1);
    assert_eq!(ops[0].operation_id, "sayHello");
}

// ---------------------------------------------------------------------------
// Test: proxy server serves OpenAPI tools
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_proxy_serves_openapi_tools() {
    use axum::body::Body;
    use http_body_util::BodyExt;
    use tower::ServiceExt;

    let dir = TempDir::new().unwrap();
    let specs_dir = dir.path().join("specs");
    let manifests_dir = dir.path().join("manifests");
    std::fs::create_dir_all(&specs_dir).unwrap();
    std::fs::create_dir_all(&manifests_dir).unwrap();

    std::fs::write(specs_dir.join("petstore.json"), PETSTORE_SPEC).unwrap();
    std::fs::write(
        manifests_dir.join("petstore.toml"),
        r#"
[provider]
name = "petstore"
description = "Petstore API"
handler = "openapi"
base_url = "https://petstore.example.com/v3"
openapi_spec = "petstore.json"
auth_type = "none"
"#,
    )
    .unwrap();

    let registry = ati::core::manifest::ManifestRegistry::load(&manifests_dir).unwrap();
    let keyring = ati::core::keyring::Keyring::empty();

    let skill_registry =
        ati::core::skill::SkillRegistry::load(std::path::Path::new("/nonexistent")).unwrap();
    let state = std::sync::Arc::new(ati::proxy::server::ProxyState {
        registry,
        skill_registry,
        keyring,
        jwt_config: None,
        jwks_json: None,
        auth_cache: ati::core::auth_generator::AuthCache::new(),
    });

    let app = ati::proxy::server::build_router(state);

    // Test /health shows OpenAPI tools
    let req = axum::http::Request::builder()
        .uri("/health")
        .body(Body::empty())
        .unwrap();

    let response = app.clone().oneshot(req).await.unwrap();
    let body_bytes = response.into_body().collect().await.unwrap().to_bytes();
    let health: serde_json::Value = serde_json::from_slice(&body_bytes).unwrap();

    assert_eq!(health["status"], "ok");
    assert!(
        health["tools"].as_u64().unwrap() >= 6,
        "Expected >= 6 tools in health, got {}",
        health["tools"]
    );

    // Test MCP tools/list includes OpenAPI tools
    let mcp_list = serde_json::json!({
        "jsonrpc": "2.0",
        "id": 1,
        "method": "tools/list",
        "params": {}
    });

    let req = axum::http::Request::builder()
        .uri("/mcp")
        .method("POST")
        .header("content-type", "application/json")
        .body(Body::from(serde_json::to_string(&mcp_list).unwrap()))
        .unwrap();

    let response = app.clone().oneshot(req).await.unwrap();
    let body_bytes = response.into_body().collect().await.unwrap().to_bytes();
    let mcp_response: serde_json::Value = serde_json::from_slice(&body_bytes).unwrap();

    let tools_list = mcp_response["result"]["tools"].as_array().unwrap();
    assert!(
        tools_list.len() >= 6,
        "Expected >= 6 tools in MCP tools/list, got {}",
        tools_list.len()
    );

    // Verify a specific tool appears with correct name
    let pet_tool = tools_list
        .iter()
        .find(|t| t["name"] == "petstore:getPetById");
    assert!(
        pet_tool.is_some(),
        "petstore:getPetById not in MCP tools/list"
    );
    let pet_tool = pet_tool.unwrap();
    assert!(pet_tool["description"]
        .as_str()
        .unwrap()
        .contains("Find pet by ID"));
}

// ---------------------------------------------------------------------------
// Test: OpenAPI tools show up in list_openapi_providers
// ---------------------------------------------------------------------------

#[test]
fn test_list_openapi_providers() {
    let manifest = r#"
[provider]
name = "petstore"
description = "Petstore API"
handler = "openapi"
base_url = "https://petstore.example.com/v3"
openapi_spec = "petstore.json"
auth_type = "none"
"#;

    let dir = create_test_ati_dir(manifest, PETSTORE_SPEC, "petstore.json");
    let registry =
        ati::core::manifest::ManifestRegistry::load(&dir.path().join("manifests")).unwrap();

    let openapi_providers = registry.list_openapi_providers();
    assert_eq!(openapi_providers.len(), 1);
    assert_eq!(openapi_providers[0].name, "petstore");
}

// ---------------------------------------------------------------------------
// Test: operation listing for inspect command
// ---------------------------------------------------------------------------

#[test]
fn test_list_operations() {
    let spec = ati::core::openapi::parse_spec(PETSTORE_SPEC).unwrap();
    let ops = ati::core::openapi::list_operations(&spec);

    assert_eq!(ops.len(), 6);

    // Verify we have the expected operations
    let op_ids: Vec<&str> = ops.iter().map(|o| o.operation_id.as_str()).collect();
    assert!(op_ids.contains(&"getPetById"));
    assert!(op_ids.contains(&"addPet"));
    assert!(op_ids.contains(&"findPetsByStatus"));
    assert!(op_ids.contains(&"getInventory"));
    assert!(op_ids.contains(&"getUserByName"));
    assert!(op_ids.contains(&"deletePet"));
}

// ---------------------------------------------------------------------------
// Test: collection format metadata injection — array with default style (multi)
// ---------------------------------------------------------------------------

#[test]
fn test_openapi_collection_format_multi_default() {
    let spec_json = r#"{
        "openapi": "3.0.3",
        "info": { "title": "Test", "version": "1.0.0" },
        "paths": {
            "/pets": {
                "get": {
                    "operationId": "findPets",
                    "summary": "Find pets",
                    "parameters": [
                        {
                            "name": "status",
                            "in": "query",
                            "schema": {
                                "type": "array",
                                "items": { "type": "string" }
                            }
                        }
                    ],
                    "responses": { "200": { "description": "OK" } }
                }
            }
        }
    }"#;

    let manifest = r#"
[provider]
name = "test"
description = "Test API"
handler = "openapi"
base_url = "https://example.com"
openapi_spec = "test.json"
auth_type = "none"
"#;

    let dir = create_test_ati_dir(manifest, spec_json, "test.json");
    let registry =
        ati::core::manifest::ManifestRegistry::load(&dir.path().join("manifests")).unwrap();
    let (_, tool) = registry.get_tool("test:findPets").unwrap();
    let schema = tool.input_schema.as_ref().unwrap();
    let props = schema.get("properties").unwrap().as_object().unwrap();
    let status = props.get("status").unwrap();

    // Default style=form + explode=true → "multi"
    assert_eq!(
        status
            .get("x-ati-collection-format")
            .unwrap()
            .as_str()
            .unwrap(),
        "multi"
    );
}

// ---------------------------------------------------------------------------
// Test: collection format — explode:false → csv
// ---------------------------------------------------------------------------

#[test]
fn test_openapi_collection_format_csv() {
    let spec_json = r#"{
        "openapi": "3.0.3",
        "info": { "title": "Test", "version": "1.0.0" },
        "paths": {
            "/pets": {
                "get": {
                    "operationId": "findPets",
                    "summary": "Find pets",
                    "parameters": [
                        {
                            "name": "ids",
                            "in": "query",
                            "explode": false,
                            "schema": {
                                "type": "array",
                                "items": { "type": "integer" }
                            }
                        }
                    ],
                    "responses": { "200": { "description": "OK" } }
                }
            }
        }
    }"#;

    let manifest = r#"
[provider]
name = "test"
description = "Test API"
handler = "openapi"
base_url = "https://example.com"
openapi_spec = "test.json"
auth_type = "none"
"#;

    let dir = create_test_ati_dir(manifest, spec_json, "test.json");
    let registry =
        ati::core::manifest::ManifestRegistry::load(&dir.path().join("manifests")).unwrap();
    let (_, tool) = registry.get_tool("test:findPets").unwrap();
    let schema = tool.input_schema.as_ref().unwrap();
    let props = schema.get("properties").unwrap().as_object().unwrap();
    let ids = props.get("ids").unwrap();

    assert_eq!(
        ids.get("x-ati-collection-format")
            .unwrap()
            .as_str()
            .unwrap(),
        "csv"
    );
}

// ---------------------------------------------------------------------------
// Test: collection format — spaceDelimited → ssv
// ---------------------------------------------------------------------------

#[test]
fn test_openapi_collection_format_ssv() {
    let spec_json = r#"{
        "openapi": "3.0.3",
        "info": { "title": "Test", "version": "1.0.0" },
        "paths": {
            "/pets": {
                "get": {
                    "operationId": "findPets",
                    "summary": "Find pets",
                    "parameters": [
                        {
                            "name": "tags",
                            "in": "query",
                            "style": "spaceDelimited",
                            "schema": {
                                "type": "array",
                                "items": { "type": "string" }
                            }
                        }
                    ],
                    "responses": { "200": { "description": "OK" } }
                }
            }
        }
    }"#;

    let manifest = r#"
[provider]
name = "test"
description = "Test API"
handler = "openapi"
base_url = "https://example.com"
openapi_spec = "test.json"
auth_type = "none"
"#;

    let dir = create_test_ati_dir(manifest, spec_json, "test.json");
    let registry =
        ati::core::manifest::ManifestRegistry::load(&dir.path().join("manifests")).unwrap();
    let (_, tool) = registry.get_tool("test:findPets").unwrap();
    let schema = tool.input_schema.as_ref().unwrap();
    let props = schema.get("properties").unwrap().as_object().unwrap();
    let tags = props.get("tags").unwrap();

    assert_eq!(
        tags.get("x-ati-collection-format")
            .unwrap()
            .as_str()
            .unwrap(),
        "ssv"
    );
}

// ---------------------------------------------------------------------------
// Test: collection format — pipeDelimited → pipes
// ---------------------------------------------------------------------------

#[test]
fn test_openapi_collection_format_pipes() {
    let spec_json = r#"{
        "openapi": "3.0.3",
        "info": { "title": "Test", "version": "1.0.0" },
        "paths": {
            "/pets": {
                "get": {
                    "operationId": "findPets",
                    "summary": "Find pets",
                    "parameters": [
                        {
                            "name": "colors",
                            "in": "query",
                            "style": "pipeDelimited",
                            "schema": {
                                "type": "array",
                                "items": { "type": "string" }
                            }
                        }
                    ],
                    "responses": { "200": { "description": "OK" } }
                }
            }
        }
    }"#;

    let manifest = r#"
[provider]
name = "test"
description = "Test API"
handler = "openapi"
base_url = "https://example.com"
openapi_spec = "test.json"
auth_type = "none"
"#;

    let dir = create_test_ati_dir(manifest, spec_json, "test.json");
    let registry =
        ati::core::manifest::ManifestRegistry::load(&dir.path().join("manifests")).unwrap();
    let (_, tool) = registry.get_tool("test:findPets").unwrap();
    let schema = tool.input_schema.as_ref().unwrap();
    let props = schema.get("properties").unwrap().as_object().unwrap();
    let colors = props.get("colors").unwrap();

    assert_eq!(
        colors
            .get("x-ati-collection-format")
            .unwrap()
            .as_str()
            .unwrap(),
        "pipes"
    );
}

// ---------------------------------------------------------------------------
// Test: no collection format for scalar query params
// ---------------------------------------------------------------------------

#[test]
fn test_openapi_no_collection_format_for_scalar() {
    let manifest = r#"
[provider]
name = "petstore"
description = "Petstore API"
handler = "openapi"
base_url = "https://petstore.example.com/v3"
openapi_spec = "petstore.json"
auth_type = "none"
"#;

    let dir = create_test_ati_dir(manifest, PETSTORE_SPEC, "petstore.json");
    let registry =
        ati::core::manifest::ManifestRegistry::load(&dir.path().join("manifests")).unwrap();

    // findPetsByStatus has a scalar string query param "status" (not array)
    let (_, tool) = registry.get_tool("petstore:findPetsByStatus").unwrap();
    let schema = tool.input_schema.as_ref().unwrap();
    let props = schema.get("properties").unwrap().as_object().unwrap();
    let status = props.get("status").unwrap();

    // Scalar params should NOT have collection format
    assert!(
        status.get("x-ati-collection-format").is_none(),
        "Scalar query params should not have x-ati-collection-format"
    );
}

// ---------------------------------------------------------------------------
// Test: form-urlencoded body encoding metadata
// ---------------------------------------------------------------------------

#[test]
fn test_openapi_form_urlencoded_body() {
    let spec_json = r#"{
        "openapi": "3.0.3",
        "info": { "title": "Test", "version": "1.0.0" },
        "paths": {
            "/token": {
                "post": {
                    "operationId": "getToken",
                    "summary": "Get OAuth token",
                    "requestBody": {
                        "required": true,
                        "content": {
                            "application/x-www-form-urlencoded": {
                                "schema": {
                                    "type": "object",
                                    "required": ["grant_type"],
                                    "properties": {
                                        "grant_type": { "type": "string" },
                                        "client_id": { "type": "string" },
                                        "client_secret": { "type": "string" }
                                    }
                                }
                            }
                        }
                    },
                    "responses": { "200": { "description": "OK" } }
                }
            }
        }
    }"#;

    let manifest = r#"
[provider]
name = "test"
description = "Test API"
handler = "openapi"
base_url = "https://example.com"
openapi_spec = "test.json"
auth_type = "none"
"#;

    let dir = create_test_ati_dir(manifest, spec_json, "test.json");
    let registry =
        ati::core::manifest::ManifestRegistry::load(&dir.path().join("manifests")).unwrap();
    let (_, tool) = registry.get_tool("test:getToken").unwrap();
    let schema = tool.input_schema.as_ref().unwrap();

    assert_eq!(
        schema.get("x-ati-body-encoding").unwrap().as_str().unwrap(),
        "form"
    );
}

// ---------------------------------------------------------------------------
// Test: JSON body does NOT get encoding flag
// ---------------------------------------------------------------------------

#[test]
fn test_openapi_json_body_no_encoding_flag() {
    let manifest = r#"
[provider]
name = "petstore"
description = "Petstore API"
handler = "openapi"
base_url = "https://petstore.example.com/v3"
openapi_spec = "petstore.json"
auth_type = "none"
"#;

    let dir = create_test_ati_dir(manifest, PETSTORE_SPEC, "petstore.json");
    let registry =
        ati::core::manifest::ManifestRegistry::load(&dir.path().join("manifests")).unwrap();

    // addPet has a JSON body
    let (_, tool) = registry.get_tool("petstore:addPet").unwrap();
    let schema = tool.input_schema.as_ref().unwrap();

    assert!(
        schema.get("x-ati-body-encoding").is_none(),
        "JSON body should not have x-ati-body-encoding flag"
    );
}

// ---------------------------------------------------------------------------
// Test: base URL extraction from spec
// ---------------------------------------------------------------------------

#[test]
fn test_spec_base_url() {
    let spec = ati::core::openapi::parse_spec(PETSTORE_SPEC).unwrap();
    let base_url = ati::core::openapi::spec_base_url(&spec);
    assert_eq!(base_url.as_deref(), Some("https://petstore.example.com/v3"));
}