embacle-server 0.21.1

Unified OpenAI-compatible REST API + MCP server for embacle LLM runners
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
// ABOUTME: Integration tests for the embacle-server REST API and MCP endpoints
// ABOUTME: Exercises router, auth middleware, health, models, completions, and MCP via axum test client
//
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) 2026 dravr.ai

#![allow(
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::panic,
    clippy::str_to_string
)]

use std::collections::HashSet;
use std::env;
use std::sync::Arc;

use axum::body::Body;
use axum::http::{Request, StatusCode};
use embacle::config::CliRunnerType;
use embacle::discovery;
use embacle_mcp::ServerState;
use embacle_server::completions;
use embacle_server::state::AppState;
use http_body_util::BodyExt;
use tokio::sync::Mutex;
use tower::ServiceExt;

use embacle_server::router;

/// Guards access to `EMBACLE_API_KEY` env var across parallel tests.
/// All tests that read or mutate this env var must hold this lock.
static ENV_MUTEX: Mutex<()> = Mutex::const_new(());

/// Build a POST /v1/chat/completions request from a JSON body
fn post_completions(body: &serde_json::Value) -> Request<Body> {
    Request::builder()
        .method("POST")
        .uri("/v1/chat/completions")
        .header("content-type", "application/json")
        .body(Body::from(serde_json::to_vec(body).expect("serialize")))
        .expect("build request")
}

/// Build a test app with the given default provider
fn test_app() -> axum::Router {
    let state = Arc::new(ServerState::new(CliRunnerType::Copilot));
    router::build(AppState::new(state))
}

/// Send a request and parse the response body as JSON
async fn send_and_parse(
    app: axum::Router,
    request: Request<Body>,
) -> (StatusCode, serde_json::Value) {
    let response = app.oneshot(request).await.expect("send request");
    let status = response.status();
    let bytes = response
        .into_body()
        .collect()
        .await
        .expect("collect")
        .to_bytes();
    let json = serde_json::from_slice(&bytes).unwrap_or(serde_json::Value::Null);
    (status, json)
}

// ============================================================================
// Health Endpoint
// ============================================================================

#[tokio::test]
async fn health_returns_json_with_status_field() {
    let _guard = ENV_MUTEX.lock().await;
    env::remove_var("EMBACLE_API_KEY");

    let app = test_app();

    let response = app
        .oneshot(
            Request::builder()
                .uri("/health")
                .body(Body::empty())
                .expect("build request"),
        )
        .await
        .expect("send request");

    let body = response.into_body();
    let bytes = body.collect().await.expect("collect body").to_bytes();
    let json: serde_json::Value = serde_json::from_slice(&bytes).expect("parse json");

    assert!(json.get("status").is_some(), "missing status field");
    assert!(json.get("providers").is_some(), "missing providers field");

    let status = json["status"].as_str().expect("status is string");
    assert!(
        status == "ok" || status == "degraded",
        "unexpected status: {status}"
    );
}

#[tokio::test]
async fn health_providers_contains_all_twelve() {
    let _guard = ENV_MUTEX.lock().await;
    env::remove_var("EMBACLE_API_KEY");

    let app = test_app();

    let response = app
        .oneshot(
            Request::builder()
                .uri("/health")
                .body(Body::empty())
                .expect("build request"),
        )
        .await
        .expect("send request");

    let bytes = response
        .into_body()
        .collect()
        .await
        .expect("collect")
        .to_bytes();
    let json: serde_json::Value = serde_json::from_slice(&bytes).expect("parse json");

    let providers = json["providers"].as_object().expect("providers is object");
    assert_eq!(providers.len(), 13, "expected 13 providers");

    // Each provider should have a status string
    for (name, value) in providers {
        assert!(value.is_string(), "provider {name} status is not a string");
    }
}

// ============================================================================
// Models Endpoint
// ============================================================================

#[tokio::test]
async fn models_returns_list_object() {
    let _guard = ENV_MUTEX.lock().await;
    env::remove_var("EMBACLE_API_KEY");

    let app = test_app();

    let response = app
        .oneshot(
            Request::builder()
                .uri("/v1/models")
                .body(Body::empty())
                .expect("build request"),
        )
        .await
        .expect("send request");

    assert_eq!(response.status(), StatusCode::OK);

    let bytes = response
        .into_body()
        .collect()
        .await
        .expect("collect")
        .to_bytes();
    let json: serde_json::Value = serde_json::from_slice(&bytes).expect("parse json");

    assert_eq!(json["object"], "list");
    assert!(json["data"].is_array(), "data should be an array");
}

// ============================================================================
// Auth Middleware
//
// All auth tests run in a single function to avoid env var races.
// `EMBACLE_API_KEY` is global process state; parallel tests would
// see each other's set_var/remove_var calls.
// ============================================================================

#[tokio::test]
async fn auth_middleware_scenarios() {
    let _guard = ENV_MUTEX.lock().await;

    let health = |hdr: Option<&'static str>| {
        let mut b = Request::builder().uri("/health");
        if let Some(h) = hdr {
            b = b.header("Authorization", h);
        }
        b.body(Body::empty()).expect("build request")
    };

    // Scenario 1: No key set → pass through
    env::remove_var("EMBACLE_API_KEY");
    let (status, _) = send_and_parse(test_app(), health(None)).await;
    assert_ne!(status, StatusCode::UNAUTHORIZED, "should allow without key");

    // Scenario 2: Key set, no header → 401 "Missing"
    env::set_var("EMBACLE_API_KEY", "test-auth-key");
    let (status, json) = send_and_parse(test_app(), health(None)).await;
    assert_eq!(status, StatusCode::UNAUTHORIZED);
    assert_eq!(json["error"]["type"], "authentication_error");
    assert!(json["error"]["message"]
        .as_str()
        .expect("msg")
        .contains("Missing"));

    // Scenario 3: Wrong bearer → 401 "Invalid"
    let (status, json) = send_and_parse(test_app(), health(Some("Bearer wrong-key"))).await;
    assert_eq!(status, StatusCode::UNAUTHORIZED);
    assert!(json["error"]["message"]
        .as_str()
        .expect("msg")
        .contains("Invalid"));

    // Scenario 4: Correct bearer → passes
    let (status, _) = send_and_parse(test_app(), health(Some("Bearer test-auth-key"))).await;
    assert_ne!(status, StatusCode::UNAUTHORIZED, "correct key should pass");

    // Scenario 5: Non-Bearer scheme → 401 "Bearer"
    let (status, json) = send_and_parse(test_app(), health(Some("Basic c2VjcmV0"))).await;
    assert_eq!(status, StatusCode::UNAUTHORIZED);
    assert!(json["error"]["message"]
        .as_str()
        .expect("msg")
        .contains("Bearer"));

    env::remove_var("EMBACLE_API_KEY");
}

// ============================================================================
// Completions Endpoint
// ============================================================================

#[tokio::test]
async fn completions_rejects_empty_model_array() {
    let _guard = ENV_MUTEX.lock().await;
    env::remove_var("EMBACLE_API_KEY");

    let app = test_app();

    let body = serde_json::json!({
        "model": [],
        "messages": [{"role": "user", "content": "hello"}]
    });

    let response = app
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/v1/chat/completions")
                .header("content-type", "application/json")
                .body(Body::from(serde_json::to_vec(&body).expect("serialize")))
                .expect("build request"),
        )
        .await
        .expect("send request");

    assert_eq!(response.status(), StatusCode::BAD_REQUEST);

    let bytes = response
        .into_body()
        .collect()
        .await
        .expect("collect")
        .to_bytes();
    let json: serde_json::Value = serde_json::from_slice(&bytes).expect("parse json");

    assert!(json["error"]["message"]
        .as_str()
        .expect("message")
        .contains("empty"));
}

#[tokio::test]
async fn completions_rejects_multiplex_with_stream() {
    let _guard = ENV_MUTEX.lock().await;
    env::remove_var("EMBACLE_API_KEY");

    let app = test_app();

    let body = serde_json::json!({
        "model": ["copilot:gpt-4o", "claude:opus"],
        "messages": [{"role": "user", "content": "hello"}],
        "stream": true
    });

    let response = app
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/v1/chat/completions")
                .header("content-type", "application/json")
                .body(Body::from(serde_json::to_vec(&body).expect("serialize")))
                .expect("build request"),
        )
        .await
        .expect("send request");

    assert_eq!(response.status(), StatusCode::BAD_REQUEST);

    let bytes = response
        .into_body()
        .collect()
        .await
        .expect("collect")
        .to_bytes();
    let json: serde_json::Value = serde_json::from_slice(&bytes).expect("parse json");

    assert!(json["error"]["message"]
        .as_str()
        .expect("message")
        .contains("Streaming"));
}

#[tokio::test]
async fn completions_returns_error_for_invalid_json() {
    let _guard = ENV_MUTEX.lock().await;
    env::remove_var("EMBACLE_API_KEY");

    let app = test_app();

    let response = app
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/v1/chat/completions")
                .header("content-type", "application/json")
                .body(Body::from(b"not valid json".to_vec()))
                .expect("build request"),
        )
        .await
        .expect("send request");

    // Axum returns 422 for JSON deserialization failures
    assert!(
        response.status().is_client_error(),
        "expected client error, got {}",
        response.status()
    );
}

// ============================================================================
// Input Validation
// ============================================================================

#[tokio::test]
async fn completions_rejects_temperature_above_max() {
    let _guard = ENV_MUTEX.lock().await;
    env::remove_var("EMBACLE_API_KEY");

    let body = serde_json::json!({
        "model": "copilot",
        "messages": [{"role": "user", "content": "hi"}],
        "temperature": 2.5
    });
    let (status, json) = send_and_parse(test_app(), post_completions(&body)).await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert!(json["error"]["message"]
        .as_str()
        .expect("msg")
        .contains("temperature"));
}

#[tokio::test]
async fn completions_rejects_negative_temperature() {
    let _guard = ENV_MUTEX.lock().await;
    env::remove_var("EMBACLE_API_KEY");

    let body = serde_json::json!({
        "model": "copilot",
        "messages": [{"role": "user", "content": "hi"}],
        "temperature": -0.1
    });
    let (status, json) = send_and_parse(test_app(), post_completions(&body)).await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert!(json["error"]["message"]
        .as_str()
        .expect("msg")
        .contains("temperature"));
}

#[tokio::test]
async fn completions_rejects_zero_max_tokens() {
    let _guard = ENV_MUTEX.lock().await;
    env::remove_var("EMBACLE_API_KEY");

    let body = serde_json::json!({
        "model": "copilot",
        "messages": [{"role": "user", "content": "hi"}],
        "max_tokens": 0
    });
    let (status, json) = send_and_parse(test_app(), post_completions(&body)).await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert!(json["error"]["message"]
        .as_str()
        .expect("msg")
        .contains("max_tokens"));
}

#[tokio::test]
async fn completions_accepts_temperature_at_boundaries() {
    let _guard = ENV_MUTEX.lock().await;
    env::remove_var("EMBACLE_API_KEY");

    // temperature=0.0 should pass validation (fail at provider, not 400)
    let body = serde_json::json!({
        "model": "copilot",
        "messages": [{"role": "user", "content": "hi"}],
        "temperature": 0.0
    });
    let (status, _) = send_and_parse(test_app(), post_completions(&body)).await;
    assert_ne!(
        status,
        StatusCode::BAD_REQUEST,
        "temperature 0.0 should pass validation"
    );

    // temperature=2.0 should pass validation
    let body = serde_json::json!({
        "model": "copilot",
        "messages": [{"role": "user", "content": "hi"}],
        "temperature": 2.0
    });
    let (status, _) = send_and_parse(test_app(), post_completions(&body)).await;
    assert_ne!(
        status,
        StatusCode::BAD_REQUEST,
        "temperature 2.0 should pass validation"
    );
}

#[tokio::test]
async fn completions_accepts_valid_max_tokens() {
    let _guard = ENV_MUTEX.lock().await;
    env::remove_var("EMBACLE_API_KEY");

    let body = serde_json::json!({
        "model": "copilot",
        "messages": [{"role": "user", "content": "hi"}],
        "max_tokens": 1
    });
    let (status, _) = send_and_parse(test_app(), post_completions(&body)).await;
    assert_ne!(
        status,
        StatusCode::BAD_REQUEST,
        "max_tokens 1 should pass validation"
    );
}

#[tokio::test]
async fn multiplex_forwards_temperature_past_validation() {
    let _guard = ENV_MUTEX.lock().await;
    env::remove_var("EMBACLE_API_KEY");

    // Multiplex with valid temperature should pass validation and reach
    // the provider layer (5xx for missing binary, not 400 for validation)
    let body = serde_json::json!({
        "model": ["copilot", "claude"],
        "messages": [{"role": "user", "content": "hi"}],
        "temperature": 0.7,
        "max_tokens": 100
    });
    let (status, _) = send_and_parse(test_app(), post_completions(&body)).await;
    assert_ne!(
        status,
        StatusCode::BAD_REQUEST,
        "multiplex with valid params should pass validation"
    );
}

// ============================================================================
// Tool Calling
// ============================================================================

#[tokio::test]
async fn completions_accepts_tools_with_tool_choice_none() {
    let _guard = ENV_MUTEX.lock().await;
    env::remove_var("EMBACLE_API_KEY");

    // tool_choice=none should skip tool injection even when tools are provided
    let body = serde_json::json!({
        "model": "copilot",
        "messages": [{"role": "user", "content": "hi"}],
        "tools": [{
            "type": "function",
            "function": {
                "name": "get_weather",
                "description": "Get weather",
                "parameters": {"type": "object", "properties": {"city": {"type": "string"}}}
            }
        }],
        "tool_choice": "none"
    });
    let (status, _) = send_and_parse(test_app(), post_completions(&body)).await;
    // Should pass validation (not 400) — the provider layer handles execution
    assert_ne!(
        status,
        StatusCode::BAD_REQUEST,
        "tool_choice=none should pass validation"
    );
}

#[tokio::test]
async fn completions_accepts_tool_choice_specific() {
    let _guard = ENV_MUTEX.lock().await;
    env::remove_var("EMBACLE_API_KEY");

    let body = serde_json::json!({
        "model": "copilot",
        "messages": [{"role": "user", "content": "hi"}],
        "tools": [{
            "type": "function",
            "function": {
                "name": "get_weather",
                "description": "Get weather",
                "parameters": {"type": "object"}
            }
        }],
        "tool_choice": {"type": "function", "function": {"name": "get_weather"}}
    });
    let (status, _) = send_and_parse(test_app(), post_completions(&body)).await;
    assert_ne!(
        status,
        StatusCode::BAD_REQUEST,
        "specific tool_choice should pass validation"
    );
}

#[tokio::test]
async fn completions_accepts_response_format() {
    let _guard = ENV_MUTEX.lock().await;
    env::remove_var("EMBACLE_API_KEY");

    let body = serde_json::json!({
        "model": "copilot",
        "messages": [{"role": "user", "content": "hi"}],
        "response_format": {"type": "json_object"}
    });
    let (status, _) = send_and_parse(test_app(), post_completions(&body)).await;
    // json_object format should be accepted by the parser (provider may or may not support it)
    assert_ne!(
        status,
        StatusCode::UNPROCESSABLE_ENTITY,
        "response_format should deserialize"
    );
}

// ============================================================================
// Router
// ============================================================================

#[tokio::test]
async fn unknown_route_returns_404() {
    let _guard = ENV_MUTEX.lock().await;
    env::remove_var("EMBACLE_API_KEY");

    let app = test_app();

    let response = app
        .oneshot(
            Request::builder()
                .uri("/nonexistent")
                .body(Body::empty())
                .expect("build request"),
        )
        .await
        .expect("send request");

    assert_eq!(response.status(), StatusCode::NOT_FOUND);
}

#[tokio::test]
async fn completions_rejects_get_method() {
    let _guard = ENV_MUTEX.lock().await;
    env::remove_var("EMBACLE_API_KEY");

    let app = test_app();

    let response = app
        .oneshot(
            Request::builder()
                .method("GET")
                .uri("/v1/chat/completions")
                .body(Body::empty())
                .expect("build request"),
        )
        .await
        .expect("send request");

    assert_eq!(response.status(), StatusCode::METHOD_NOT_ALLOWED);
}

#[tokio::test]
async fn models_rejects_post_method() {
    let _guard = ENV_MUTEX.lock().await;
    env::remove_var("EMBACLE_API_KEY");

    let app = test_app();

    let response = app
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/v1/models")
                .body(Body::empty())
                .expect("build request"),
        )
        .await
        .expect("send request");

    assert_eq!(response.status(), StatusCode::METHOD_NOT_ALLOWED);
}

// ============================================================================
// Streaming Format
// ============================================================================

#[tokio::test]
async fn streaming_generate_id_format() {
    let id = completions::generate_id();
    assert!(
        id.starts_with("chatcmpl-"),
        "ID should start with chatcmpl-, got: {id}"
    );
    assert!(
        id.len() > "chatcmpl-".len(),
        "ID should have content after prefix"
    );
}

#[tokio::test]
async fn generate_id_produces_unique_ids() {
    let ids: Vec<String> = (0..100).map(|_| completions::generate_id()).collect();
    let unique: HashSet<&String> = ids.iter().collect();
    assert_eq!(
        ids.len(),
        unique.len(),
        "Expected all IDs to be unique within the same second"
    );
}

#[tokio::test]
async fn generate_id_unique_across_concurrent_tasks() {
    let mut handles = Vec::with_capacity(50);
    for _ in 0..50 {
        handles.push(tokio::spawn(async { completions::generate_id() }));
    }

    let mut ids = Vec::with_capacity(50);
    for handle in handles {
        ids.push(handle.await.expect("task join"));
    }

    let unique: HashSet<&String> = ids.iter().collect();
    assert_eq!(
        ids.len(),
        unique.len(),
        "Expected all IDs to be unique across concurrent tasks"
    );
}

// ============================================================================
// Provider Resolver (integration-level)
// ============================================================================

#[tokio::test]
async fn provider_resolver_round_trip_via_completions() {
    let _guard = ENV_MUTEX.lock().await;
    env::remove_var("EMBACLE_API_KEY");

    let app = test_app();

    // A single-model request with a provider prefix using a model id that
    // exists in the Copilot catalog so resolution does not trip on the
    // ModelUnavailable → 404 shortcut.
    let body = serde_json::json!({
        "model": "copilot:claude-opus-4.7",
        "messages": [{"role": "user", "content": "test"}]
    });

    let response = app
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/v1/chat/completions")
                .header("content-type", "application/json")
                .body(Body::from(serde_json::to_vec(&body).expect("serialize")))
                .expect("build request"),
        )
        .await
        .expect("send request");

    // Verify correct routing: provider prefix is parsed and forwarded to the
    // runner layer. The result depends on binary availability — 5xx (binary
    // missing or invocation failure) or 2xx (actual completion). Either way it
    // must NOT be a 4xx, which would indicate a routing/parsing error.
    let status = response.status();
    assert!(
        !status.is_client_error(),
        "expected non-4xx for provider-prefixed model, got {status}"
    );
}

// ============================================================================
// State
// ============================================================================

#[tokio::test]
async fn state_active_provider_accessible() {
    let state = ServerState::new(CliRunnerType::ClaudeCode);
    assert_eq!(state.active_provider().await, CliRunnerType::ClaudeCode);
}

#[tokio::test]
async fn state_runner_creation_reflects_binary_availability() {
    let state = ServerState::new(CliRunnerType::OpenCode);
    let result = state.get_runner(CliRunnerType::OpenCode).await;

    // Verify get_runner outcome matches actual binary availability
    let binary_on_path = which::which("opencode").is_ok();
    if binary_on_path {
        assert!(
            result.is_ok(),
            "opencode binary found on PATH but get_runner failed"
        );
    } else {
        assert!(
            result.is_err(),
            "opencode binary not on PATH but get_runner succeeded"
        );
    }
}

#[test]
fn resolve_binary_fails_for_missing_binary() {
    let result = discovery::resolve_binary("embacle_nonexistent_test_binary_xyz", None);
    assert!(result.is_err(), "expected error for missing binary");
}

// ============================================================================
// MCP Endpoint (via embacle-mcp)
// ============================================================================

/// Build a POST /mcp request with a JSON-RPC body
fn post_mcp(body: &serde_json::Value) -> Request<Body> {
    Request::builder()
        .method("POST")
        .uri("/mcp")
        .header("content-type", "application/json")
        .body(Body::from(serde_json::to_vec(body).expect("serialize")))
        .expect("build request")
}

#[tokio::test]
async fn mcp_initialize_returns_protocol_version() {
    let _guard = ENV_MUTEX.lock().await;
    env::remove_var("EMBACLE_API_KEY");

    let body = serde_json::json!({
        "jsonrpc": "2.0",
        "id": 1,
        "method": "initialize",
        "params": {
            "protocolVersion": "2024-11-05",
            "capabilities": {},
            "clientInfo": { "name": "test-client", "version": "1.0" }
        }
    });

    let (status, json) = send_and_parse(test_app(), post_mcp(&body)).await;
    assert_eq!(status, StatusCode::OK);
    assert_eq!(json["jsonrpc"], "2.0");
    assert_eq!(json["id"], 1);
    // dravr-tronc 0.5's dual-era engine advertises its current protocol revision
    // (2025-11-25) in the initialize response rather than echoing the legacy
    // version the client requested; the client adapts per the MCP handshake.
    assert_eq!(json["result"]["protocolVersion"], "2025-11-25");
    assert_eq!(json["result"]["serverInfo"]["name"], "embacle-mcp");
    assert!(json["result"]["capabilities"]["tools"].is_object());
}

#[tokio::test]
async fn mcp_tools_list_returns_registered_tools() {
    let _guard = ENV_MUTEX.lock().await;
    env::remove_var("EMBACLE_API_KEY");

    let body = serde_json::json!({
        "jsonrpc": "2.0",
        "id": 2,
        "method": "tools/list"
    });

    let (status, json) = send_and_parse(test_app(), post_mcp(&body)).await;
    assert_eq!(status, StatusCode::OK);

    let tools = json["result"]["tools"].as_array().expect("tools is array");
    assert_eq!(tools.len(), 7, "expected 7 MCP tools from embacle-mcp");

    let names: Vec<&str> = tools.iter().filter_map(|t| t["name"].as_str()).collect();
    assert!(names.contains(&"prompt"), "missing prompt tool");
    assert!(names.contains(&"get_provider"), "missing get_provider tool");
    assert!(names.contains(&"set_provider"), "missing set_provider tool");
    assert!(names.contains(&"get_model"), "missing get_model tool");
    assert!(names.contains(&"set_model"), "missing set_model tool");
    assert!(
        names.contains(&"get_multiplex_provider"),
        "missing get_multiplex_provider tool"
    );
    assert!(
        names.contains(&"set_multiplex_provider"),
        "missing set_multiplex_provider tool"
    );
}

#[tokio::test]
async fn mcp_ping_returns_empty_object() {
    let _guard = ENV_MUTEX.lock().await;
    env::remove_var("EMBACLE_API_KEY");

    let body = serde_json::json!({
        "jsonrpc": "2.0",
        "id": 3,
        "method": "ping"
    });

    let (status, json) = send_and_parse(test_app(), post_mcp(&body)).await;
    assert_eq!(status, StatusCode::OK);
    assert_eq!(json["result"], serde_json::json!({}));
}

#[tokio::test]
async fn mcp_unknown_method_returns_error() {
    let _guard = ENV_MUTEX.lock().await;
    env::remove_var("EMBACLE_API_KEY");

    let body = serde_json::json!({
        "jsonrpc": "2.0",
        "id": 4,
        "method": "nonexistent/method"
    });

    let (status, json) = send_and_parse(test_app(), post_mcp(&body)).await;
    assert_eq!(status, StatusCode::OK);
    assert_eq!(json["error"]["code"], -32601);
}

#[tokio::test]
async fn mcp_notification_returns_no_content() {
    let _guard = ENV_MUTEX.lock().await;
    env::remove_var("EMBACLE_API_KEY");

    let body = serde_json::json!({
        "jsonrpc": "2.0",
        "method": "notifications/initialized"
    });

    let app = test_app();
    let response = app.oneshot(post_mcp(&body)).await.expect("send request");

    assert_eq!(response.status(), StatusCode::NO_CONTENT);
}

#[tokio::test]
async fn mcp_invalid_json_returns_parse_error() {
    let _guard = ENV_MUTEX.lock().await;
    env::remove_var("EMBACLE_API_KEY");

    let request = Request::builder()
        .method("POST")
        .uri("/mcp")
        .header("content-type", "application/json")
        .body(Body::from("not valid json"))
        .expect("build request");

    let (status, json) = send_and_parse(test_app(), request).await;
    assert_eq!(status, StatusCode::OK);
    assert_eq!(json["error"]["code"], -32700);
}

#[tokio::test]
async fn mcp_auth_enforced_when_key_set() {
    let _guard = ENV_MUTEX.lock().await;
    env::set_var("EMBACLE_API_KEY", "mcp-test-key");

    let body = serde_json::json!({
        "jsonrpc": "2.0",
        "id": 5,
        "method": "ping"
    });

    // No auth header → 401
    let (status, _) = send_and_parse(test_app(), post_mcp(&body)).await;
    assert_eq!(status, StatusCode::UNAUTHORIZED);

    // With auth header → 200
    let request = Request::builder()
        .method("POST")
        .uri("/mcp")
        .header("content-type", "application/json")
        .header("Authorization", "Bearer mcp-test-key")
        .body(Body::from(serde_json::to_vec(&body).expect("serialize")))
        .expect("build request");

    let (status, json) = send_and_parse(test_app(), request).await;
    assert_eq!(status, StatusCode::OK);
    assert_eq!(json["result"], serde_json::json!({}));

    env::remove_var("EMBACLE_API_KEY");
}