mrapids 0.1.31

Your OpenAPI, but executable
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
//! Integration Tests for mrapids
//!
//! These tests verify end-to-end behavior across multiple components:
//! - MCP protocol (JSON-RPC, tool flow)
//! - CLI command execution
//! - HTTP request building (Content-Type, headers)
//! - Parameter validation (arrays, enums)

use serde_json::{json, Value};
use std::io::Write;
use std::process::{Command, Stdio};

// ============================================================================
// Test Helpers
// ============================================================================

/// Get mrapids binary path - uses MRAPIDS_BIN env var or falls back to release binary
fn get_mrapids_bin() -> String {
    std::env::var("MRAPIDS_BIN").unwrap_or_else(|_| {
        // In CI, use the prebuilt release binary
        if std::path::Path::new("target/release/mrapids").exists() {
            "target/release/mrapids".to_string()
        } else {
            // Local dev: use cargo run
            "".to_string()
        }
    })
}

/// Run mrapids CLI command and return stdout
fn run_mrapids(args: &[&str]) -> (bool, String, String) {
    let bin = get_mrapids_bin();

    let output = if bin.is_empty() {
        // Fallback to cargo run for local development
        Command::new("cargo")
            .args(["run", "--release", "--quiet", "--"])
            .args(args)
            .output()
            .expect("Failed to execute mrapids via cargo")
    } else {
        // Use prebuilt binary (faster, no recompilation)
        Command::new(&bin)
            .args(args)
            .output()
            .expect(&format!("Failed to execute mrapids at: {}", bin))
    };

    let stdout = String::from_utf8_lossy(&output.stdout).to_string();
    let stderr = String::from_utf8_lossy(&output.stderr).to_string();
    (output.status.success(), stdout, stderr)
}

/// Send JSON-RPC request to MCP server via stdin
/// NOTE: Currently unused - will be enabled when MCP test harness is ready
#[allow(dead_code)]
fn send_mcp_request(request: &Value) -> Value {
    let mut child = Command::new("cargo")
        .args(["run", "--quiet", "--", "mcp"])
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("Failed to start MCP server");

    // Send request
    if let Some(mut stdin) = child.stdin.take() {
        let request_str = serde_json::to_string(request).unwrap();
        stdin.write_all(request_str.as_bytes()).unwrap();
        stdin.write_all(b"\n").unwrap();
    }

    // Read response (with timeout)
    let output = child.wait_with_output().expect("Failed to read MCP output");
    let stdout = String::from_utf8_lossy(&output.stdout);

    // Parse first JSON line
    for line in stdout.lines() {
        if let Ok(json) = serde_json::from_str(line) {
            return json;
        }
    }

    json!({"error": "No valid JSON response", "raw": stdout.to_string()})
}

// ============================================================================
// MCP Protocol Tests
// NOTE: These tests require a full MCP server setup with project context.
// They are disabled by default but can be enabled for manual testing.
// ============================================================================

// TODO: Enable these tests when MCP test harness is available
// The MCP server requires stdin/stdout communication and a valid project.
// For now, MCP functionality is tested via unit tests in mcp.rs

/*
#[test]
#[ignore] // Run with: cargo test --test integration_tests -- --ignored
fn test_mcp_tools_list() {
    let request = json!({
        "jsonrpc": "2.0",
        "id": 1,
        "method": "tools/list",
        "params": {}
    });

    let response = send_mcp_request(&request);

    assert!(response.get("result").is_some(), "Should have result");
    let tools = response["result"]["tools"].as_array();
    assert!(tools.is_some(), "Should have tools array");

    // Verify expected tools exist
    let tool_names: Vec<&str> = tools.unwrap()
        .iter()
        .filter_map(|t| t["name"].as_str())
        .collect();

    assert!(tool_names.contains(&"api_find"), "Should have api_find");
    assert!(tool_names.contains(&"api_show"), "Should have api_show");
    assert!(tool_names.contains(&"api_claim"), "Should have api_claim");
    assert!(tool_names.contains(&"api_run"), "Should have api_run");
}

#[test]
#[ignore]
fn test_mcp_api_find() {
    let request = json!({
        "jsonrpc": "2.0",
        "id": 2,
        "method": "tools/call",
        "params": {
            "name": "api_find",
            "arguments": {
                "query": "list pets"
            }
        }
    });

    let response = send_mcp_request(&request);

    // Should return results or guidance
    let content = &response["result"]["content"];
    assert!(content.is_array(), "Should have content array");
}
*/

// ============================================================================
// Content-Type Tests
// ============================================================================

#[test]
#[ignore]
fn test_content_type_fallback_to_json() {
    // Test that POST with --data gets Content-Type: application/json
    let (_success, stdout, _) = run_mrapids(&[
        "run",
        "addPet",
        "--spec",
        "examples/petstore.yaml",
        "--data",
        r#"{"name":"Test","status":"available"}"#,
        "--dry-run",
        "--verbose",
    ]);

    // In dry-run, should show the Content-Type being set
    assert!(
        stdout.contains("Content-Type") || stdout.contains("application/json"),
        "Should show Content-Type in verbose output: {}",
        stdout
    );
}

#[test]
#[ignore]
fn test_content_type_from_spec() {
    // When spec defines requestBody, use its content type
    let (_, stdout, _) = run_mrapids(&[
        "run",
        "addPet",
        "--spec",
        "examples/petstore.yaml",
        "--data",
        r#"{"name":"Test"}"#,
        "--dry-run",
        "--verbose",
    ]);

    assert!(
        stdout.contains("application/json"),
        "Should use application/json from spec"
    );
}

#[test]
#[ignore]
fn test_content_type_cli_override() {
    // CLI header should override spec
    let (_, stdout, _) = run_mrapids(&[
        "run",
        "addPet",
        "--spec",
        "examples/petstore.yaml",
        "--data",
        "<xml>test</xml>",
        "--header",
        "Content-Type: application/xml",
        "--dry-run",
        "--verbose",
    ]);

    assert!(
        stdout.contains("application/xml"),
        "CLI should override Content-Type"
    );
}

// ============================================================================
// Array Parameter Tests (MCP-dependent - commented out)
// NOTE: These tests require MCP server with project context.
// Array param validation is tested via unit tests in mcp.rs
// ============================================================================

/*
#[test]
#[ignore]
fn test_array_param_with_array_value() {
    // findByStatus accepts status[] array parameter
    let request = json!({
        "jsonrpc": "2.0",
        "id": 3,
        "method": "tools/call",
        "params": {
            "name": "api_claim",
            "arguments": {
                "operation_id": "findPetsByStatus",
                "my_understanding": "Find pets by their status, filtering by available and pending",
                "known_parameters": {
                    "status": ["available", "pending"]
                },
                "unknowns": []
            }
        }
    });

    let response = send_mcp_request(&request);
    let content = response["result"]["content"][0]["text"].as_str().unwrap_or("");

    // Should accept array values for array parameters
    assert!(
        content.contains("claim_token") || content.contains("accepted"),
        "Should accept array value for array param: {}", content
    );
}

#[test]
#[ignore]
fn test_array_param_with_single_value() {
    // Single value should be accepted and auto-wrapped
    let request = json!({
        "jsonrpc": "2.0",
        "id": 4,
        "method": "tools/call",
        "params": {
            "name": "api_claim",
            "arguments": {
                "operation_id": "findPetsByStatus",
                "my_understanding": "Find pets with available status",
                "known_parameters": {
                    "status": "available"
                },
                "unknowns": []
            }
        }
    });

    let response = send_mcp_request(&request);
    let content = response["result"]["content"][0]["text"].as_str().unwrap_or("");

    // Should accept single value for array param
    assert!(
        !content.contains("type mismatch") && !content.contains("must be array"),
        "Should accept single value for array param: {}", content
    );
}

#[test]
#[ignore]
fn test_array_param_invalid_enum() {
    // Invalid enum value in array should be rejected
    let request = json!({
        "jsonrpc": "2.0",
        "id": 5,
        "method": "tools/call",
        "params": {
            "name": "api_claim",
            "arguments": {
                "operation_id": "findPetsByStatus",
                "my_understanding": "Find pets by status",
                "known_parameters": {
                    "status": ["available", "invalid_status"]
                },
                "unknowns": []
            }
        }
    });

    let response = send_mcp_request(&request);
    let content = response["result"]["content"][0]["text"].as_str().unwrap_or("");

    // Should reject invalid enum value
    assert!(
        content.contains("invalid") || content.contains("enum") || content.contains("gap"),
        "Should reject invalid enum value: {}", content
    );
}

// ============================================================================
// known_parameters Format Tests (MCP-dependent)
// ============================================================================

#[test]
#[ignore]
fn test_known_params_simple_format() {
    let request = json!({
        "jsonrpc": "2.0",
        "id": 6,
        "method": "tools/call",
        "params": {
            "name": "api_claim",
            "arguments": {
                "operation_id": "getPetById",
                "my_understanding": "Get a pet by its ID",
                "known_parameters": {
                    "petId": 123
                },
                "unknowns": []
            }
        }
    });

    let response = send_mcp_request(&request);
    let content = response["result"]["content"][0]["text"].as_str().unwrap_or("");

    // Simple format should work
    assert!(
        !content.contains("error") || content.contains("claim_token"),
        "Simple format should be accepted: {}", content
    );
}

#[test]
#[ignore]
fn test_known_params_detailed_format() {
    let request = json!({
        "jsonrpc": "2.0",
        "id": 7,
        "method": "tools/call",
        "params": {
            "name": "api_claim",
            "arguments": {
                "operation_id": "getPetById",
                "my_understanding": "Get a pet by its ID",
                "known_parameters": {
                    "petId": {
                        "value": 123,
                        "confidence": 0.95
                    }
                },
                "unknowns": []
            }
        }
    });

    let response = send_mcp_request(&request);
    let content = response["result"]["content"][0]["text"].as_str().unwrap_or("");

    // Detailed format should work
    assert!(
        !content.contains("error") || content.contains("claim_token"),
        "Detailed format should be accepted: {}", content
    );
}

// ============================================================================
// Token Flow Tests (MCP-dependent)
// ============================================================================

#[test]
#[ignore]
fn test_run_without_claim_token_fails() {
    let request = json!({
        "jsonrpc": "2.0",
        "id": 8,
        "method": "tools/call",
        "params": {
            "name": "api_run",
            "arguments": {
                "preview_id": "fake_preview_id"
            }
        }
    });

    let response = send_mcp_request(&request);
    let content = response["result"]["content"][0]["text"].as_str().unwrap_or("");

    // Should fail without valid token
    assert!(
        content.contains("invalid") || content.contains("expired") || content.contains("not found"),
        "Should reject invalid preview_id: {}", content
    );
}
*/

// ============================================================================
// CLI Output Format Tests
// ============================================================================

#[test]
#[ignore]
fn test_list_operations_output() {
    let (_success, stdout, _stderr) =
        run_mrapids(&["list", "operations", "examples/petstore.yaml"]);

    // Should list operations from the spec
    assert!(
        stdout.contains("listPets") || stdout.contains("addPet") || stdout.contains("Operation"),
        "Should list operations: {}",
        stdout
    );
}

#[test]
#[ignore]
fn test_dry_run_shows_request() {
    let (_, stdout, _) = run_mrapids(&[
        "run",
        "getPetById",
        "--spec",
        "examples/petstore.yaml",
        "--param",
        "petId=123",
        "--dry-run",
    ]);

    // Should show operation being executed and dry run confirmation
    assert!(
        stdout.contains("Dry run complete") || stdout.contains("getPetById"),
        "Dry run should show request: {}",
        stdout
    );
}

// ============================================================================
// Error Handling Tests
// ============================================================================

#[test]
#[ignore]
fn test_operation_not_found_error() {
    let (success, stdout, stderr) = run_mrapids(&[
        "run",
        "nonExistentOperation",
        "--spec",
        "examples/petstore.yaml",
    ]);

    assert!(!success, "Should fail for non-existent operation");
    let output = format!("{}{}", stdout, stderr);
    assert!(
        output.contains("not found") || output.contains("Operation") || output.contains("error"),
        "Should show helpful error: {}",
        output
    );
}

#[test]
#[ignore]
fn test_missing_required_param() {
    let (_success, stdout, stderr) = run_mrapids(&[
        "run",
        "getPetById",
        "--spec",
        "examples/petstore.yaml",
        "--dry-run", // Missing required petId - CLI may still succeed in dry-run but path won't have value
    ]);

    // In dry-run mode, CLI may proceed but the path template will show the issue
    // Check that operation was recognized and dry run completed
    let output = format!("{}{}", stdout, stderr);
    assert!(
        output.contains("getPetById") || output.contains("Dry run"),
        "Should execute dry run for operation: {}",
        output
    );
}