ferro-api-mcp 0.2.16

Standalone MCP server that bridges OpenAPI specs to MCP tools
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
use openapiv3::{OpenAPI, Operation, Parameter, ReferenceOr, RequestBody};
use serde_json::Value;

use crate::error::Error;
use crate::types::{ApiOperation, ApiParam, ParamLocation};

/// Metadata extracted from an OpenAPI spec's info and servers sections.
pub struct SpecMetadata {
    /// The API title from `info.title`, or "API" if missing.
    pub title: String,
    /// The first server URL from `servers[0].url`, if present.
    pub server_url: Option<String>,
}

/// Extract metadata (title, server URL) from an OpenAPI spec JSON string.
///
/// This is a lightweight parse that only reads the `info` and `servers`
/// sections, independent of the full `parse_spec` operation.
pub fn extract_metadata(json: &str) -> Result<SpecMetadata, Error> {
    let spec: OpenAPI = serde_json::from_str(json).map_err(|e| Error::SpecParse(e.to_string()))?;

    let title = if spec.info.title.is_empty() {
        "API".to_string()
    } else {
        spec.info.title.clone()
    };

    let server_url = spec.servers.first().map(|s| s.url.clone());

    Ok(SpecMetadata { title, server_url })
}

/// Fetch an OpenAPI spec from a URL.
///
/// Returns the raw JSON string for parsing with `parse_spec`.
/// Categorizes fetch errors for actionable diagnostics:
/// connection refused, timeout, decode errors, non-2xx status, non-JSON content.
pub async fn fetch_spec(url: &str) -> Result<String, Error> {
    let response = reqwest::get(url)
        .await
        .map_err(|e| categorize_reqwest_error(url, &e))?;

    let status = response.status();
    if !status.is_success() {
        return Err(Error::SpecFetch(format!(
            "HTTP {status} — expected 200 with OpenAPI JSON"
        )));
    }

    let body = response
        .text()
        .await
        .map_err(|e| categorize_reqwest_error(url, &e))?;

    // Quick JSON validity check before returning
    if serde_json::from_str::<Value>(&body).is_err() {
        return Err(Error::SpecFetch(
            "response is not valid JSON — expected an OpenAPI 3.0.x JSON document".into(),
        ));
    }

    Ok(body)
}

/// Categorize a reqwest error into a specific diagnostic message.
fn categorize_reqwest_error(url: &str, e: &reqwest::Error) -> Error {
    if e.is_connect() {
        Error::SpecFetch(format!(
            "connection refused — is the server running at {url}?"
        ))
    } else if e.is_timeout() {
        Error::SpecFetch("request timed out — check network connectivity".into())
    } else if e.is_decode() {
        Error::SpecFetch("failed to decode response body".into())
    } else {
        Error::SpecFetch(e.to_string())
    }
}

/// Parse an OpenAPI 3.0.x JSON spec into a list of API operations.
///
/// Validates the spec version (only 3.0.x supported), extracts all
/// operations from paths, resolves `$ref` references, and builds
/// `ApiOperation` for each (method, path, operation) tuple.
pub fn parse_spec(json: &str) -> Result<Vec<ApiOperation>, Error> {
    let spec: OpenAPI = serde_json::from_str(json).map_err(|e| Error::SpecParse(e.to_string()))?;

    if !spec.openapi.starts_with("3.") {
        return Err(Error::UnsupportedVersion(spec.openapi.clone()));
    }

    let mut operations = Vec::new();

    for (path, path_item_ref) in &spec.paths.paths {
        let path_item = match path_item_ref {
            ReferenceOr::Item(item) => item,
            ReferenceOr::Reference { .. } => continue,
        };

        let methods: &[(&str, &Option<Operation>)] = &[
            ("GET", &path_item.get),
            ("POST", &path_item.post),
            ("PUT", &path_item.put),
            ("PATCH", &path_item.patch),
            ("DELETE", &path_item.delete),
        ];

        for &(method, op_opt) in methods {
            if let Some(operation) = op_opt {
                // Skip operations marked as hidden via x-mcp-hidden
                let hidden = operation
                    .extensions
                    .get("x-mcp-hidden")
                    .and_then(|v| v.as_bool())
                    .unwrap_or(false);
                if hidden {
                    continue;
                }

                // Extract x-mcp overrides
                let mcp_tool_name = operation
                    .extensions
                    .get("x-mcp-tool-name")
                    .and_then(|v| v.as_str())
                    .map(String::from);
                let mcp_description = operation
                    .extensions
                    .get("x-mcp-description")
                    .and_then(|v| v.as_str())
                    .map(String::from);
                let mcp_hint = operation
                    .extensions
                    .get("x-mcp-hint")
                    .and_then(|v| v.as_str())
                    .map(String::from);

                // Use x-mcp values as overrides with existing behavior as fallback
                let tool_name = mcp_tool_name.unwrap_or_else(|| {
                    generate_tool_name(operation.operation_id.as_deref(), method, path)
                });
                let description =
                    mcp_description.unwrap_or_else(|| build_description(operation, &tool_name));

                let parameters =
                    extract_parameters(&spec, &operation.parameters, &path_item.parameters);
                let request_body_schema = extract_request_body(&spec, &operation.request_body);

                let mut op =
                    ApiOperation::new(tool_name, method.to_string(), path.clone(), description);
                op.parameters = parameters;
                op.request_body_schema = request_body_schema;
                op.hint = mcp_hint;

                operations.push(op);
            }
        }
    }

    Ok(operations)
}

/// Generate a tool name from an operation ID or method+path.
///
/// If `operation_id` is present, dots are replaced with underscores.
/// Otherwise, a name is generated from `{method}_{sanitized_path}`.
fn generate_tool_name(operation_id: Option<&str>, method: &str, path: &str) -> String {
    if let Some(id) = operation_id {
        return id.replace('.', "_");
    }

    let sanitized_path = path
        .split('/')
        .filter(|s| !s.is_empty() && !s.starts_with('{'))
        .collect::<Vec<_>>()
        .join("_");

    format!("{}_{}", method.to_lowercase(), sanitized_path)
}

/// Build a description from operation summary and description fields.
///
/// Priority: "summary - description" > "summary" > tool_name fallback.
fn build_description(operation: &Operation, tool_name: &str) -> String {
    match (&operation.summary, &operation.description) {
        (Some(summary), Some(desc)) => format!("{summary} - {desc}"),
        (Some(summary), None) => summary.clone(),
        (None, Some(desc)) => desc.clone(),
        (None, None) => tool_name.to_string(),
    }
}

/// Extract parameters from both operation-level and path-level parameter lists.
///
/// Resolves `$ref` references to `#/components/parameters/...`. Operation-level
/// parameters are processed first, then path-level parameters that don't
/// duplicate names already seen.
fn extract_parameters(
    spec: &OpenAPI,
    operation_params: &[ReferenceOr<Parameter>],
    path_params: &[ReferenceOr<Parameter>],
) -> Vec<ApiParam> {
    let mut result = Vec::new();
    let mut seen_names = std::collections::HashSet::new();

    // Operation-level parameters take precedence
    for param_ref in operation_params {
        if let Some(param) = resolve_parameter(spec, param_ref) {
            seen_names.insert(param.name.clone());
            result.push(param);
        }
    }

    // Path-level parameters (skip if already defined at operation level)
    for param_ref in path_params {
        if let Some(param) = resolve_parameter(spec, param_ref) {
            if seen_names.insert(param.name.clone()) {
                result.push(param);
            }
        }
    }

    result
}

/// Resolve a single parameter reference to an `ApiParam`.
fn resolve_parameter(spec: &OpenAPI, param_ref: &ReferenceOr<Parameter>) -> Option<ApiParam> {
    let param = match param_ref {
        ReferenceOr::Item(p) => p,
        ReferenceOr::Reference { reference } => resolve_parameter_ref(spec, reference)?,
    };

    let data = param.parameter_data_ref();
    let location = match param {
        Parameter::Path { .. } => ParamLocation::Path,
        Parameter::Query { .. } => ParamLocation::Query,
        Parameter::Header { .. } => ParamLocation::Header,
        Parameter::Cookie { .. } => return None, // Skip cookie params
    };

    let schema = extract_parameter_schema(data);

    Some(ApiParam {
        name: data.name.clone(),
        location,
        required: data.required,
        schema,
        description: data.description.clone(),
    })
}

/// Look up a parameter in `#/components/parameters/`.
fn resolve_parameter_ref<'a>(spec: &'a OpenAPI, reference: &str) -> Option<&'a Parameter> {
    let name = reference.strip_prefix("#/components/parameters/")?;
    let components = spec.components.as_ref()?;
    let param_ref = components.parameters.get(name)?;

    match param_ref {
        ReferenceOr::Item(p) => Some(p),
        ReferenceOr::Reference { .. } => {
            tracing::warn!("nested $ref in parameter {reference}, skipping");
            None
        }
    }
}

/// Extract the JSON Schema value from a parameter's schema-or-content.
fn extract_parameter_schema(data: &openapiv3::ParameterData) -> Value {
    match &data.format {
        openapiv3::ParameterSchemaOrContent::Schema(schema_ref) => match schema_ref {
            ReferenceOr::Item(schema) => {
                serde_json::to_value(schema).unwrap_or(Value::Object(Default::default()))
            }
            ReferenceOr::Reference { .. } => {
                // For parameter schemas that are $ref, serialize the schema type as-is
                Value::Object(Default::default())
            }
        },
        openapiv3::ParameterSchemaOrContent::Content(_) => Value::Object(Default::default()),
    }
}

/// Extract the request body JSON schema from an operation.
///
/// Looks for `application/json` content type and resolves `$ref` in the
/// schema. Returns `None` if no request body, no JSON content, or
/// unresolvable reference.
fn extract_request_body(spec: &OpenAPI, body: &Option<ReferenceOr<RequestBody>>) -> Option<Value> {
    let body_ref = body.as_ref()?;

    let request_body = match body_ref {
        ReferenceOr::Item(rb) => rb,
        ReferenceOr::Reference { reference } => {
            tracing::warn!("$ref for requestBody not yet supported: {reference}");
            return None;
        }
    };

    let media_type = request_body.content.get("application/json")?;
    let schema_ref = media_type.schema.as_ref()?;

    match schema_ref {
        ReferenceOr::Item(schema) => serde_json::to_value(schema).ok(),
        ReferenceOr::Reference { reference } => resolve_schema_ref(spec, reference),
    }
}

/// Resolve a `$ref` pointing to `#/components/schemas/...` into a JSON Value.
///
/// Looks up the schema name in `spec.components.schemas`, serializes it
/// via serde. Returns `None` and logs a warning for unresolvable refs.
fn resolve_schema_ref(spec: &OpenAPI, reference: &str) -> Option<Value> {
    let name = reference
        .strip_prefix("#/components/schemas/")
        .or_else(|| {
            tracing::warn!("unsupported $ref path: {reference}");
            None
        })?;

    let components = spec.components.as_ref().or_else(|| {
        tracing::warn!("$ref {reference} but no components section");
        None
    })?;

    let schema_ref = components.schemas.get(name).or_else(|| {
        tracing::warn!("unresolved $ref: {reference}");
        None
    })?;

    match schema_ref {
        ReferenceOr::Item(schema) => serde_json::to_value(schema).ok(),
        ReferenceOr::Reference { reference: nested } => {
            tracing::warn!("nested $ref in schema {reference} -> {nested}, skipping");
            None
        }
    }
}

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

    // Helper: minimal valid OpenAPI 3.0.3 spec shell
    fn spec_shell(paths: serde_json::Value) -> String {
        json!({
            "openapi": "3.0.3",
            "info": { "title": "Test API", "version": "1.0.0" },
            "paths": paths
        })
        .to_string()
    }

    fn spec_shell_with_components(
        paths: serde_json::Value,
        components: serde_json::Value,
    ) -> String {
        json!({
            "openapi": "3.0.3",
            "info": { "title": "Test API", "version": "1.0.0" },
            "paths": paths,
            "components": components
        })
        .to_string()
    }

    // ── 1. Version validation ──────────────────────────────────────

    #[test]
    fn version_3_0_3_accepted() {
        let spec = spec_shell(json!({}));
        let result = parse_spec(&spec);
        assert!(result.is_ok(), "3.0.3 should be accepted");
    }

    #[test]
    fn version_3_0_0_accepted() {
        let spec = json!({
            "openapi": "3.0.0",
            "info": { "title": "Test", "version": "1.0.0" },
            "paths": {}
        })
        .to_string();
        let result = parse_spec(&spec);
        assert!(result.is_ok(), "3.0.0 should be accepted");
    }

    #[test]
    fn version_3_1_accepted() {
        let spec = json!({
            "openapi": "3.1.0",
            "info": { "title": "Test", "version": "1.0.0" },
            "paths": {}
        })
        .to_string();
        let result = parse_spec(&spec);
        assert!(result.is_ok(), "3.1.0 should be accepted");
    }

    #[test]
    fn version_2_0_rejected() {
        // openapiv3 cannot parse Swagger 2.0 at all, so we expect a parse error
        let spec = json!({
            "swagger": "2.0",
            "info": { "title": "Test", "version": "1.0.0" },
            "paths": {}
        })
        .to_string();
        let result = parse_spec(&spec);
        assert!(result.is_err(), "2.0 should be rejected");
    }

    // ── 2. Operation extraction ────────────────────────────────────

    #[test]
    fn extracts_single_get_operation() {
        let spec = spec_shell(json!({
            "/api/users": {
                "get": {
                    "operationId": "api.users.index",
                    "summary": "List users",
                    "responses": { "200": { "description": "OK" } }
                }
            }
        }));
        let ops = parse_spec(&spec).unwrap();
        assert_eq!(ops.len(), 1);
        assert_eq!(ops[0].method, "GET");
        assert_eq!(ops[0].path, "/api/users");
    }

    #[test]
    fn extracts_multiple_operations() {
        let spec = spec_shell(json!({
            "/api/users": {
                "post": {
                    "operationId": "api.users.store",
                    "responses": { "201": { "description": "Created" } }
                }
            },
            "/api/users/{id}": {
                "delete": {
                    "operationId": "api.users.destroy",
                    "responses": { "204": { "description": "Deleted" } }
                }
            }
        }));
        let ops = parse_spec(&spec).unwrap();
        assert_eq!(ops.len(), 2);

        let methods: Vec<&str> = ops.iter().map(|o| o.method.as_str()).collect();
        assert!(methods.contains(&"POST"));
        assert!(methods.contains(&"DELETE"));
    }

    #[test]
    fn empty_paths_returns_empty_vec() {
        let spec = spec_shell(json!({}));
        let ops = parse_spec(&spec).unwrap();
        assert!(ops.is_empty());
    }

    // ── 3. Tool naming ─────────────────────────────────────────────

    #[test]
    fn tool_name_from_operation_id_dots_to_underscores() {
        let spec = spec_shell(json!({
            "/api/users": {
                "get": {
                    "operationId": "api.users.index",
                    "responses": { "200": { "description": "OK" } }
                }
            }
        }));
        let ops = parse_spec(&spec).unwrap();
        assert_eq!(ops[0].tool_name, "api_users_index");
    }

    #[test]
    fn tool_name_generated_when_no_operation_id() {
        let spec = spec_shell(json!({
            "/api/users": {
                "get": {
                    "responses": { "200": { "description": "OK" } }
                }
            }
        }));
        let ops = parse_spec(&spec).unwrap();
        assert_eq!(ops[0].tool_name, "get_api_users");
    }

    #[test]
    fn tool_name_mixed_with_and_without_operation_id() {
        let spec = spec_shell(json!({
            "/api/users": {
                "get": {
                    "operationId": "api.users.index",
                    "responses": { "200": { "description": "OK" } }
                }
            },
            "/api/posts": {
                "get": {
                    "responses": { "200": { "description": "OK" } }
                }
            }
        }));
        let ops = parse_spec(&spec).unwrap();
        assert_eq!(ops.len(), 2);

        let names: Vec<&str> = ops.iter().map(|o| o.tool_name.as_str()).collect();
        assert!(names.contains(&"api_users_index"));
        assert!(names.contains(&"get_api_posts"));
    }

    // ── 4. Parameter extraction ────────────────────────────────────

    #[test]
    fn extracts_path_parameter() {
        let spec = spec_shell(json!({
            "/api/users/{id}": {
                "get": {
                    "operationId": "api.users.show",
                    "parameters": [
                        {
                            "name": "id",
                            "in": "path",
                            "required": true,
                            "schema": { "type": "integer" }
                        }
                    ],
                    "responses": { "200": { "description": "OK" } }
                }
            }
        }));
        let ops = parse_spec(&spec).unwrap();
        assert_eq!(ops[0].parameters.len(), 1);
        assert_eq!(ops[0].parameters[0].name, "id");
        assert_eq!(ops[0].parameters[0].location, ParamLocation::Path);
        assert!(ops[0].parameters[0].required);
    }

    #[test]
    fn extracts_query_parameter() {
        let spec = spec_shell(json!({
            "/api/users": {
                "get": {
                    "operationId": "api.users.index",
                    "parameters": [
                        {
                            "name": "page",
                            "in": "query",
                            "required": false,
                            "schema": { "type": "integer" }
                        }
                    ],
                    "responses": { "200": { "description": "OK" } }
                }
            }
        }));
        let ops = parse_spec(&spec).unwrap();
        assert_eq!(ops[0].parameters.len(), 1);
        assert_eq!(ops[0].parameters[0].name, "page");
        assert_eq!(ops[0].parameters[0].location, ParamLocation::Query);
        assert!(!ops[0].parameters[0].required);
    }

    #[test]
    fn no_parameters_returns_empty_vec() {
        let spec = spec_shell(json!({
            "/api/health": {
                "get": {
                    "operationId": "health.check",
                    "responses": { "200": { "description": "OK" } }
                }
            }
        }));
        let ops = parse_spec(&spec).unwrap();
        assert!(ops[0].parameters.is_empty());
    }

    #[test]
    fn merges_path_level_and_operation_level_parameters() {
        let spec = spec_shell(json!({
            "/api/users/{id}": {
                "parameters": [
                    {
                        "name": "id",
                        "in": "path",
                        "required": true,
                        "schema": { "type": "integer" }
                    }
                ],
                "get": {
                    "operationId": "api.users.show",
                    "parameters": [
                        {
                            "name": "include",
                            "in": "query",
                            "required": false,
                            "schema": { "type": "string" }
                        }
                    ],
                    "responses": { "200": { "description": "OK" } }
                }
            }
        }));
        let ops = parse_spec(&spec).unwrap();
        assert_eq!(ops[0].parameters.len(), 2);

        let names: Vec<&str> = ops[0].parameters.iter().map(|p| p.name.as_str()).collect();
        assert!(names.contains(&"id"));
        assert!(names.contains(&"include"));
    }

    // ── 5. Request body extraction ─────────────────────────────────

    #[test]
    fn extracts_json_request_body_schema() {
        let spec = spec_shell(json!({
            "/api/users": {
                "post": {
                    "operationId": "api.users.store",
                    "requestBody": {
                        "required": true,
                        "content": {
                            "application/json": {
                                "schema": {
                                    "type": "object",
                                    "properties": {
                                        "name": { "type": "string" },
                                        "email": { "type": "string" }
                                    },
                                    "required": ["name", "email"]
                                }
                            }
                        }
                    },
                    "responses": { "201": { "description": "Created" } }
                }
            }
        }));
        let ops = parse_spec(&spec).unwrap();
        let body = ops[0].request_body_schema.as_ref().unwrap();
        let props = body.get("properties").unwrap();
        assert!(props.get("name").is_some());
        assert!(props.get("email").is_some());
    }

    #[test]
    fn get_has_no_request_body() {
        let spec = spec_shell(json!({
            "/api/users": {
                "get": {
                    "operationId": "api.users.index",
                    "responses": { "200": { "description": "OK" } }
                }
            }
        }));
        let ops = parse_spec(&spec).unwrap();
        assert!(ops[0].request_body_schema.is_none());
    }

    // ── 6. $ref resolution ─────────────────────────────────────────

    #[test]
    fn resolves_request_body_schema_ref() {
        let spec = spec_shell_with_components(
            json!({
                "/api/users": {
                    "post": {
                        "operationId": "api.users.store",
                        "requestBody": {
                            "required": true,
                            "content": {
                                "application/json": {
                                    "schema": {
                                        "$ref": "#/components/schemas/CreateUserRequest"
                                    }
                                }
                            }
                        },
                        "responses": { "201": { "description": "Created" } }
                    }
                }
            }),
            json!({
                "schemas": {
                    "CreateUserRequest": {
                        "type": "object",
                        "properties": {
                            "name": { "type": "string" },
                            "email": { "type": "string" }
                        },
                        "required": ["name", "email"]
                    }
                }
            }),
        );
        let ops = parse_spec(&spec).unwrap();
        let body = ops[0].request_body_schema.as_ref().unwrap();
        let props = body.get("properties").unwrap();
        assert!(props.get("name").is_some());
        assert!(props.get("email").is_some());
    }

    #[test]
    fn unresolvable_ref_degrades_gracefully() {
        // An unresolvable $ref should NOT fail the entire parse.
        // The operation should still be extracted, with request_body_schema = None.
        let spec = spec_shell_with_components(
            json!({
                "/api/users": {
                    "post": {
                        "operationId": "api.users.store",
                        "requestBody": {
                            "required": true,
                            "content": {
                                "application/json": {
                                    "schema": {
                                        "$ref": "#/components/schemas/NonExistent"
                                    }
                                }
                            }
                        },
                        "responses": { "201": { "description": "Created" } }
                    }
                }
            }),
            json!({
                "schemas": {}
            }),
        );
        let ops = parse_spec(&spec).unwrap();
        assert_eq!(ops.len(), 1);
        // Body schema should be None since the ref couldn't be resolved
        assert!(ops[0].request_body_schema.is_none());
    }

    #[test]
    fn resolves_parameter_schema_ref() {
        let spec = spec_shell_with_components(
            json!({
                "/api/users": {
                    "get": {
                        "operationId": "api.users.index",
                        "parameters": [
                            {
                                "$ref": "#/components/parameters/PageParam"
                            }
                        ],
                        "responses": { "200": { "description": "OK" } }
                    }
                }
            }),
            json!({
                "parameters": {
                    "PageParam": {
                        "name": "page",
                        "in": "query",
                        "required": false,
                        "schema": { "type": "integer" }
                    }
                }
            }),
        );
        let ops = parse_spec(&spec).unwrap();
        assert_eq!(ops[0].parameters.len(), 1);
        assert_eq!(ops[0].parameters[0].name, "page");
        assert_eq!(ops[0].parameters[0].location, ParamLocation::Query);
    }

    // ── 7. Description extraction ──────────────────────────────────

    #[test]
    fn description_from_summary_and_description() {
        let spec = spec_shell(json!({
            "/api/users": {
                "get": {
                    "operationId": "api.users.index",
                    "summary": "List users",
                    "description": "Returns all users",
                    "responses": { "200": { "description": "OK" } }
                }
            }
        }));
        let ops = parse_spec(&spec).unwrap();
        assert_eq!(ops[0].description, "List users - Returns all users");
    }

    #[test]
    fn description_from_summary_only() {
        let spec = spec_shell(json!({
            "/api/users": {
                "get": {
                    "operationId": "api.users.index",
                    "summary": "List users",
                    "responses": { "200": { "description": "OK" } }
                }
            }
        }));
        let ops = parse_spec(&spec).unwrap();
        assert_eq!(ops[0].description, "List users");
    }

    #[test]
    fn description_fallback_to_tool_name() {
        let spec = spec_shell(json!({
            "/api/users": {
                "get": {
                    "operationId": "api.users.index",
                    "responses": { "200": { "description": "OK" } }
                }
            }
        }));
        let ops = parse_spec(&spec).unwrap();
        assert_eq!(ops[0].description, "api_users_index");
    }

    // ── 8. x-mcp vendor extensions ───────────────────────────────

    #[test]
    fn x_mcp_tool_name_overrides_operation_id() {
        let spec = spec_shell(json!({
            "/api/users": {
                "get": {
                    "operationId": "api.users.index",
                    "summary": "List users",
                    "x-mcp-tool-name": "list_all_users",
                    "responses": { "200": { "description": "OK" } }
                }
            }
        }));
        let ops = parse_spec(&spec).unwrap();
        assert_eq!(ops[0].tool_name, "list_all_users");
    }

    #[test]
    fn x_mcp_description_overrides_summary() {
        let spec = spec_shell(json!({
            "/api/users": {
                "get": {
                    "operationId": "api.users.index",
                    "summary": "List users",
                    "x-mcp-description": "Retrieve all user records with pagination",
                    "responses": { "200": { "description": "OK" } }
                }
            }
        }));
        let ops = parse_spec(&spec).unwrap();
        assert_eq!(
            ops[0].description,
            "Retrieve all user records with pagination"
        );
    }

    #[test]
    fn x_mcp_hidden_excludes_operation() {
        let spec = spec_shell(json!({
            "/api/users": {
                "get": {
                    "operationId": "api.users.index",
                    "summary": "List users",
                    "responses": { "200": { "description": "OK" } }
                }
            },
            "/api/internal/health": {
                "get": {
                    "operationId": "internal.health",
                    "summary": "Health check",
                    "x-mcp-hidden": true,
                    "responses": { "200": { "description": "OK" } }
                }
            }
        }));
        let ops = parse_spec(&spec).unwrap();
        assert_eq!(ops.len(), 1);
        assert_eq!(ops[0].tool_name, "api_users_index");
    }

    #[test]
    fn x_mcp_hint_extracted() {
        let spec = spec_shell(json!({
            "/api/users": {
                "get": {
                    "operationId": "api.users.index",
                    "summary": "List users",
                    "x-mcp-hint": "Use page and per_page query params for pagination",
                    "responses": { "200": { "description": "OK" } }
                }
            }
        }));
        let ops = parse_spec(&spec).unwrap();
        assert_eq!(
            ops[0].hint.as_deref(),
            Some("Use page and per_page query params for pagination")
        );
    }

    #[test]
    fn x_mcp_fallback_without_extensions() {
        let spec = spec_shell(json!({
            "/api/users": {
                "get": {
                    "operationId": "api.users.index",
                    "summary": "List users",
                    "responses": { "200": { "description": "OK" } }
                }
            }
        }));
        let ops = parse_spec(&spec).unwrap();
        assert_eq!(ops[0].tool_name, "api_users_index");
        assert_eq!(ops[0].description, "List users");
        assert!(ops[0].hint.is_none());
    }

    #[test]
    fn x_mcp_partial_extensions() {
        let spec = spec_shell(json!({
            "/api/users": {
                "get": {
                    "operationId": "api.users.index",
                    "summary": "List users",
                    "x-mcp-tool-name": "fetch_users",
                    "responses": { "200": { "description": "OK" } }
                }
            }
        }));
        let ops = parse_spec(&spec).unwrap();
        assert_eq!(ops[0].tool_name, "fetch_users");
        assert_eq!(ops[0].description, "List users");
        assert!(ops[0].hint.is_none());
    }
}