leviath-cli 0.3.8

Command-line interface for Leviath agent framework
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
//! MCP server management endpoints.
//!
//! Full CRUD plus login over HTTP, mirroring `lev mcp`. The paths, browser
//! opener, and clock live in [`McpAdmin`] so the handlers are unit-testable
//! without the real home directory or a browser.

use axum::extract::{Path as AxumPath, State};
use axum::http::StatusCode;
use axum::response::{IntoResponse, Json};
use serde::{Deserialize, Serialize};

use super::types::{AppState, err};
use crate::config::Config;
use leviath_mcp::{AuthStore, LoginOutcome, MCPClient, MCPServerConfig, OAuthClient};

/// Where `lev serve` reads and writes MCP state, plus the seams the login flow
/// needs. Cheap to clone (paths + fn pointers).
#[derive(Clone)]
pub struct McpAdmin {
    /// Config file to read and rewrite.
    pub config_path: std::path::PathBuf,
    /// OAuth token store.
    pub store_path: std::path::PathBuf,
    /// How to open the browser during a login.
    pub opener: leviath_mcp::BrowserOpener,
    /// Current Unix time; a fn so a long-lived server stays current per request.
    pub clock: fn() -> u64,
}

/// Real Unix time in seconds.
fn system_now() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0)
}

impl Default for McpAdmin {
    fn default() -> Self {
        Self {
            config_path: Config::config_path(),
            store_path: AuthStore::default_path().unwrap_or_default(),
            opener: std::sync::Arc::new(leviath_sys::open_url),
            clock: system_now,
        }
    }
}

/// A server, as reported by the list/status endpoints.
#[derive(Serialize)]
pub(super) struct McpServerInfo {
    name: String,
    transport: String,
    endpoint: String,
    auth: String,
}

impl McpServerInfo {
    fn describe(server: &MCPServerConfig, store: &AuthStore, now: u64) -> Self {
        let (transport, endpoint) = match server.resolve() {
            Ok(leviath_mcp::ResolvedTransport::Stdio { command, .. }) => {
                ("stdio".to_string(), command.to_string())
            }
            Ok(leviath_mcp::ResolvedTransport::Http { url, .. }) => {
                ("http".to_string(), url.to_string())
            }
            Err(_) => ("invalid".to_string(), String::new()),
        };
        Self {
            name: server.name.clone(),
            transport,
            endpoint,
            auth: auth_status(server, store, now),
        }
    }
}

/// A one-word auth state for a server.
fn auth_status(server: &MCPServerConfig, store: &AuthStore, now: u64) -> String {
    let is_http = matches!(
        server.resolve(),
        Ok(leviath_mcp::ResolvedTransport::Http { .. })
    );
    if !is_http {
        return "n/a".to_string();
    }
    match store.get(&server.name) {
        Some(auth) if auth.is_expired_at(now) => "expired".to_string(),
        Some(_) => "authenticated".to_string(),
        // A configured `Authorization` header is a credential too, and calling
        // it "none" is what puts a login button in front of a server that needs
        // no login.
        None if server.has_auth_header() => "header".to_string(),
        None => "none".to_string(),
    }
}

/// `GET /api/mcp/servers` - list configured servers with their auth status.
pub(super) async fn list_servers(State(state): State<AppState>) -> impl IntoResponse {
    let admin = &state.mcp;
    let config = match Config::load_from_path_public(&admin.config_path) {
        Ok(config) => config,
        Err(e) => return err(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
    };
    let store = AuthStore::load(&admin.store_path).unwrap_or_default();
    let now = (admin.clock)();
    let servers: Vec<McpServerInfo> = config
        .mcp_servers
        .iter()
        .map(|s| McpServerInfo::describe(s, &store, now))
        .collect();
    Json(servers).into_response()
}

/// Body of `POST /api/mcp/servers`.
#[derive(Deserialize)]
pub(super) struct AddServerRequest {
    name: String,
    #[serde(default)]
    url: Option<String>,
    #[serde(default)]
    command: Option<String>,
    #[serde(default)]
    args: Vec<String>,
    #[serde(default)]
    headers: std::collections::HashMap<String, String>,
}

/// `POST /api/mcp/servers` - add a server.
pub(super) async fn add_server(
    State(state): State<AppState>,
    Json(req): Json<AddServerRequest>,
) -> impl IntoResponse {
    let admin = &state.mcp;
    let server = MCPServerConfig {
        name: req.name,
        command: req.command,
        url: req.url,
        args: req.args,
        headers: req.headers,
        ..Default::default()
    };
    if let Err(e) = server.validate() {
        return err(StatusCode::BAD_REQUEST, e.to_string()).into_response();
    }

    let mut config = match Config::load_from_path_public(&admin.config_path) {
        Ok(config) => config,
        Err(e) => return err(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
    };
    if config.mcp_servers.iter().any(|s| s.name == server.name) {
        return err(
            StatusCode::CONFLICT,
            format!("an MCP server named '{}' already exists", server.name),
        )
        .into_response();
    }
    config.mcp_servers.push(server.clone());
    if let Err(e) = config.save_to_path_public(&admin.config_path) {
        return err(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response();
    }
    (
        StatusCode::CREATED,
        Json(serde_json::json!({ "name": server.name })),
    )
        .into_response()
}

/// `DELETE /api/mcp/servers/{name}` - remove a server and its credentials.
pub(super) async fn remove_server(
    State(state): State<AppState>,
    AxumPath(name): AxumPath<String>,
) -> impl IntoResponse {
    let admin = &state.mcp;
    let mut config = match Config::load_from_path_public(&admin.config_path) {
        Ok(config) => config,
        Err(e) => return err(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
    };
    let before = config.mcp_servers.len();
    config.mcp_servers.retain(|s| s.name != name);
    if config.mcp_servers.len() == before {
        return err(
            StatusCode::NOT_FOUND,
            format!("no MCP server named '{name}'"),
        )
        .into_response();
    }
    if let Err(e) = config.save_to_path_public(&admin.config_path) {
        return err(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response();
    }
    if let Ok(mut store) = AuthStore::load(&admin.store_path)
        && store.remove(&name)
    {
        let _ = store.save(&admin.store_path);
    }
    StatusCode::NO_CONTENT.into_response()
}

/// `POST /api/mcp/servers/{name}/login` - run the OAuth browser flow.
///
/// On the host running `lev serve` this opens the operator's browser and
/// completes the loopback redirect, the same flow `lev mcp login` uses.
pub(super) async fn login(
    State(state): State<AppState>,
    AxumPath(name): AxumPath<String>,
) -> impl IntoResponse {
    let admin = &state.mcp;
    let config = match Config::load_from_path_public(&admin.config_path) {
        Ok(config) => config,
        Err(e) => return err(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
    };
    let Some(server) = config.mcp_servers.iter().find(|s| s.name == name) else {
        return err(
            StatusCode::NOT_FOUND,
            format!("no MCP server named '{name}'"),
        )
        .into_response();
    };
    let url = match server.resolve() {
        Ok(leviath_mcp::ResolvedTransport::Http { url, .. }) => url.to_string(),
        _ => {
            return err(
                StatusCode::BAD_REQUEST,
                format!("server '{name}' does not use HTTP transport and cannot log in"),
            )
            .into_response();
        }
    };

    let mut store = AuthStore::load(&admin.store_path).unwrap_or_default();
    let reuse = store.get(&name).map(|a| a.client_id.clone());
    let outcome = match OAuthClient::new()
        .login(
            &url,
            &server.headers,
            &config.security.allow_env_vars,
            admin.opener.clone(),
            (admin.clock)(),
            reuse.as_deref(),
        )
        .await
    {
        Ok(outcome) => outcome,
        Err(e) => return err(StatusCode::BAD_GATEWAY, e.to_string()).into_response(),
    };
    // A server that answered the probe wants no OAuth, so there is nothing to
    // store. Reporting it as an error would be wrong: the caller asked whether a
    // login was needed, and the answer is no.
    let LoginOutcome::Authenticated(auth) = outcome else {
        return Json(serde_json::json!({ "status": "not_required", "server": name }))
            .into_response();
    };
    store.set(&name, *auth);
    if let Err(e) = store.save(&admin.store_path) {
        return err(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response();
    }
    Json(serde_json::json!({ "status": "authenticated", "server": name })).into_response()
}

/// `GET /api/mcp/servers/{name}/status` - one server's transport and auth state.
pub(super) async fn status(
    State(state): State<AppState>,
    AxumPath(name): AxumPath<String>,
) -> impl IntoResponse {
    let admin = &state.mcp;
    let config = match Config::load_from_path_public(&admin.config_path) {
        Ok(config) => config,
        Err(e) => return err(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
    };
    let Some(server) = config.mcp_servers.iter().find(|s| s.name == name) else {
        return err(
            StatusCode::NOT_FOUND,
            format!("no MCP server named '{name}'"),
        )
        .into_response();
    };
    let store = AuthStore::load(&admin.store_path).unwrap_or_default();
    Json(McpServerInfo::describe(server, &store, (admin.clock)())).into_response()
}

/// `POST /api/mcp/servers/{name}/test` - connect and report the tool count.
pub(super) async fn test_server(
    State(state): State<AppState>,
    AxumPath(name): AxumPath<String>,
) -> impl IntoResponse {
    let admin = &state.mcp;
    let config = match Config::load_from_path_public(&admin.config_path) {
        Ok(config) => config,
        Err(e) => return err(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
    };
    let Some(server) = config.mcp_servers.iter().find(|s| s.name == name) else {
        return err(
            StatusCode::NOT_FOUND,
            format!("no MCP server named '{name}'"),
        )
        .into_response();
    };
    let auth_header = match OAuthClient::new()
        .authorization_header(&name, &admin.store_path, (admin.clock)())
        .await
    {
        Ok(header) => header,
        Err(e) => return err(StatusCode::BAD_GATEWAY, e.to_string()).into_response(),
    };
    let result = connect_and_list(server, auth_header, &config.security.allow_env_vars).await;
    match result {
        Ok(tools) => Json(serde_json::json!({ "server": name, "tools": tools })).into_response(),
        Err(e) => err(StatusCode::BAD_GATEWAY, e.to_string()).into_response(),
    }
}

/// Connect to `server` and return its tool names.
///
/// The client is shut down on EVERY path, not just success: `MCPClient` has no
/// `Drop` and a stdio transport's child process does not die with the handle,
/// so the early-return `?`s here each orphaned a spawned MCP server process
/// per failed test request.
async fn connect_and_list(
    server: &MCPServerConfig,
    auth_header: Option<(String, String)>,
    allow_env: &[String],
) -> anyhow::Result<Vec<String>> {
    // The allowlist has to come from the config, not be an empty slice: an
    // empty one refuses every `${VAR}` header, so testing a server whose token
    // comes from the environment failed here while the same server worked for
    // an agent.
    let mut client = MCPClient::from_config_with_auth(server, auth_header, allow_env).await?;
    let listed = async {
        client.connect().await?;
        client.list_tools().await
    }
    .await;
    let _ = client.shutdown().await;
    let tools = listed?;
    Ok(tools.into_iter().map(|t| t.name).collect())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::commands::serve::types::ServerEvent;
    use axum::Router;
    use axum::body::Body;
    use axum::http::Request;
    use axum::routing::{delete, get, post};
    use std::sync::Arc;
    use tokio::sync::broadcast;
    use tower::ServiceExt;

    fn never_opens(_: &str) -> bool {
        false
    }

    fn fixed_clock() -> u64 {
        1_000
    }

    /// An app state whose MCP admin points at temp paths.
    fn state_at(
        dir: &std::path::Path,
        opener: impl Fn(&str) -> bool + Send + Sync + 'static,
    ) -> AppState {
        let (tx, _) = broadcast::channel::<ServerEvent>(16);
        AppState {
            config: Arc::new(Config::default()),
            event_tx: tx,
            control: crate::commands::serve::testutil::no_daemon_client(),
            mcp: McpAdmin {
                config_path: dir.join("config.toml"),
                store_path: dir.join("mcp-auth.json"),
                opener: Arc::new(opener),
                clock: fixed_clock,
            },
            limits: Default::default(),
        }
    }

    fn router(state: AppState) -> Router {
        Router::new()
            .route("/api/mcp/servers", get(list_servers).post(add_server))
            .route("/api/mcp/servers/{name}", delete(remove_server))
            .route("/api/mcp/servers/{name}/status", get(status))
            .route("/api/mcp/servers/{name}/login", post(login))
            .route("/api/mcp/servers/{name}/test", post(test_server))
            .with_state(state)
    }

    async fn send(
        app: &Router,
        method: &str,
        uri: &str,
        body: Option<serde_json::Value>,
    ) -> (StatusCode, serde_json::Value) {
        let req = Request::builder()
            .method(method)
            .uri(uri)
            .header("content-type", "application/json")
            .body(
                body.map(|b| Body::from(b.to_string()))
                    .unwrap_or(Body::empty()),
            )
            .unwrap();
        let resp = app.clone().oneshot(req).await.unwrap();
        let status = resp.status();
        let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        let json = if bytes.is_empty() {
            serde_json::Value::Null
        } else {
            serde_json::from_slice(&bytes).unwrap_or(serde_json::Value::Null)
        };
        (status, json)
    }

    #[tokio::test]
    async fn add_list_status_and_remove_round_trip() {
        let dir = tempfile::tempdir().unwrap();
        let app = router(state_at(dir.path(), never_opens));

        // Empty to start.
        let (status_code, body) = send(&app, "GET", "/api/mcp/servers", None).await;
        assert_eq!(status_code, StatusCode::OK);
        assert_eq!(body.as_array().unwrap().len(), 0);

        // Add an HTTP server.
        let (status_code, _) = send(
            &app,
            "POST",
            "/api/mcp/servers",
            Some(serde_json::json!({ "name": "remote", "url": "https://e.com/mcp" })),
        )
        .await;
        assert_eq!(status_code, StatusCode::CREATED);

        // It lists, with auth "none".
        let (_, body) = send(&app, "GET", "/api/mcp/servers", None).await;
        assert_eq!(body[0]["name"], "remote");
        assert_eq!(body[0]["transport"], "http");
        assert_eq!(body[0]["auth"], "none");

        // Status for the one server.
        let (status_code, body) = send(&app, "GET", "/api/mcp/servers/remote/status", None).await;
        assert_eq!(status_code, StatusCode::OK);
        assert_eq!(body["endpoint"], "https://e.com/mcp");

        // Remove it.
        let (status_code, _) = send(&app, "DELETE", "/api/mcp/servers/remote", None).await;
        assert_eq!(status_code, StatusCode::NO_CONTENT);
        let (_, body) = send(&app, "GET", "/api/mcp/servers", None).await;
        assert_eq!(body.as_array().unwrap().len(), 0);
    }

    #[tokio::test]
    async fn add_rejects_a_malformed_server() {
        let dir = tempfile::tempdir().unwrap();
        let app = router(state_at(dir.path(), never_opens));
        let (status_code, _) = send(
            &app,
            "POST",
            "/api/mcp/servers",
            // Neither url nor command.
            Some(serde_json::json!({ "name": "bad" })),
        )
        .await;
        assert_eq!(status_code, StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    async fn add_rejects_a_duplicate() {
        let dir = tempfile::tempdir().unwrap();
        let app = router(state_at(dir.path(), never_opens));
        let body = serde_json::json!({ "name": "x", "command": "npx" });
        send(&app, "POST", "/api/mcp/servers", Some(body.clone())).await;
        let (status_code, _) = send(&app, "POST", "/api/mcp/servers", Some(body)).await;
        assert_eq!(status_code, StatusCode::CONFLICT);
    }

    #[tokio::test]
    async fn remove_of_an_unknown_server_is_404() {
        let dir = tempfile::tempdir().unwrap();
        let app = router(state_at(dir.path(), never_opens));
        let (status_code, _) = send(&app, "DELETE", "/api/mcp/servers/ghost", None).await;
        assert_eq!(status_code, StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn status_of_an_unknown_server_is_404() {
        let dir = tempfile::tempdir().unwrap();
        let app = router(state_at(dir.path(), never_opens));
        let (status_code, _) = send(&app, "GET", "/api/mcp/servers/ghost/status", None).await;
        assert_eq!(status_code, StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn login_of_an_unknown_server_is_404() {
        let dir = tempfile::tempdir().unwrap();
        let app = router(state_at(dir.path(), never_opens));
        let (status_code, _) = send(&app, "POST", "/api/mcp/servers/ghost/login", None).await;
        assert_eq!(status_code, StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn login_of_a_stdio_server_is_rejected() {
        let dir = tempfile::tempdir().unwrap();
        let app = router(state_at(dir.path(), never_opens));
        send(
            &app,
            "POST",
            "/api/mcp/servers",
            Some(serde_json::json!({ "name": "local", "command": "npx" })),
        )
        .await;
        let (status_code, _) = send(&app, "POST", "/api/mcp/servers/local/login", None).await;
        assert_eq!(status_code, StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    async fn test_of_an_unknown_server_is_404() {
        let dir = tempfile::tempdir().unwrap();
        let app = router(state_at(dir.path(), never_opens));
        let (status_code, _) = send(&app, "POST", "/api/mcp/servers/ghost/test", None).await;
        assert_eq!(status_code, StatusCode::NOT_FOUND);
    }

    // ─── full login + test against a mock OAuth + MCP server ──────────────

    use axum::extract::State as AxumState;

    async fn mock_oauth_server() -> String {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let base = format!("http://{}", listener.local_addr().unwrap());
        let s = base.clone();
        let app = Router::new()
            .route(
                "/mcp",
                post(|AxumState(base): AxumState<String>| async move {
                    let hint = format!(
                        "Bearer resource_metadata=\"{base}/.well-known/oauth-protected-resource\""
                    );
                    (
                        StatusCode::UNAUTHORIZED,
                        [(reqwest::header::WWW_AUTHENTICATE, hint)],
                    )
                }),
            )
            .route(
                "/.well-known/oauth-protected-resource",
                get(|AxumState(base): AxumState<String>| async move {
                    Json(serde_json::json!({
                        "resource": format!("{base}/mcp"),
                        "authorization_servers": [base],
                    }))
                }),
            )
            .route(
                "/.well-known/oauth-authorization-server",
                get(|AxumState(base): AxumState<String>| async move {
                    Json(serde_json::json!({
                        "issuer": base,
                        "authorization_endpoint": format!("{base}/authorize"),
                        "token_endpoint": format!("{base}/token"),
                        "registration_endpoint": format!("{base}/register"),
                        "scopes_supported": ["openid"],
                    }))
                }),
            )
            .route(
                "/register",
                post(|| async { Json(serde_json::json!({ "client_id": "rest-client" })) }),
            )
            .route(
                "/token",
                post(|| async {
                    Json(serde_json::json!({
                        "access_token": "rest-access",
                        "refresh_token": "rest-refresh",
                        "expires_in": 3600,
                    }))
                }),
            )
            .with_state(s);
        tokio::spawn(std::future::IntoFuture::into_future(axum::serve(
            listener, app,
        )));
        base
    }

    fn auto_consent(authorize_url: &str) -> bool {
        let url = reqwest::Url::parse(authorize_url).unwrap();
        let params: std::collections::HashMap<_, _> = url.query_pairs().into_owned().collect();
        let redirect = params["redirect_uri"].clone();
        let state = params["state"].clone();
        tokio::spawn(async move {
            let cb = format!("{redirect}?code=rest-code&state={state}");
            let _ = reqwest::Client::new().get(&cb).send().await;
        });
        true
    }

    #[tokio::test]
    async fn login_completes_and_status_reports_authenticated() {
        let base = mock_oauth_server().await;
        let dir = tempfile::tempdir().unwrap();
        let app = router(state_at(dir.path(), auto_consent));

        send(
            &app,
            "POST",
            "/api/mcp/servers",
            Some(serde_json::json!({ "name": "navigator", "url": format!("{base}/mcp") })),
        )
        .await;

        let (status_code, body) =
            send(&app, "POST", "/api/mcp/servers/navigator/login", None).await;
        assert_eq!(status_code, StatusCode::OK, "login body: {body}");
        assert_eq!(body["status"], "authenticated");

        // Now status shows authenticated.
        let (_, body) = send(&app, "GET", "/api/mcp/servers/navigator/status", None).await;
        assert_eq!(body["auth"], "authenticated");
    }

    /// The website's login button on a header-authenticated server. It used to
    /// surface the discovery 404 as a bad gateway; the honest answer is that no
    /// login is needed.
    #[tokio::test]
    async fn login_reports_not_required_when_headers_already_satisfy_the_server() {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let base = format!("http://{}", listener.local_addr().unwrap());
        // Publishes no OAuth metadata, so an attempted discovery fails loudly.
        let mcp =
            axum::Router::new().route("/mcp", axum::routing::post(|| async { StatusCode::OK }));
        tokio::spawn(std::future::IntoFuture::into_future(axum::serve(
            listener, mcp,
        )));

        let dir = tempfile::tempdir().unwrap();
        let app = router(state_at(dir.path(), never_opens));
        send(
            &app,
            "POST",
            "/api/mcp/servers",
            Some(serde_json::json!({
                "name": "hub",
                "url": format!("{base}/mcp"),
                "headers": { "Authorization": "Bearer configured-token" },
            })),
        )
        .await;

        let (status_code, body) = send(&app, "POST", "/api/mcp/servers/hub/login", None).await;
        assert_eq!(status_code, StatusCode::OK, "login body: {body}");
        assert_eq!(body["status"], "not_required");
        // `never_opens` would have failed the flow had discovery been attempted.

        // And the listing calls it credentialed, so no UI offers a login here.
        let (_, body) = send(&app, "GET", "/api/mcp/servers/hub/status", None).await;
        assert_eq!(body["auth"], "header");
    }

    #[tokio::test]
    async fn login_reports_a_bad_gateway_when_discovery_fails() {
        let dir = tempfile::tempdir().unwrap();
        let app = router(state_at(dir.path(), never_opens));
        send(
            &app,
            "POST",
            "/api/mcp/servers",
            Some(serde_json::json!({ "name": "dead", "url": "http://127.0.0.1:1/mcp" })),
        )
        .await;
        let (status_code, _) = send(&app, "POST", "/api/mcp/servers/dead/login", None).await;
        assert_eq!(status_code, StatusCode::BAD_GATEWAY);
    }

    #[tokio::test]
    async fn test_endpoint_connects_and_lists_tools() {
        let dir = tempfile::tempdir().unwrap();
        let app = router(state_at(dir.path(), never_opens));
        let stub = r#"
import sys, json
for line in sys.stdin:
    line = line.strip()
    if not line: continue
    req = json.loads(line); m = req.get("method",""); i = req.get("id")
    if m == "initialize":
        print(json.dumps({"jsonrpc":"2.0","id":i,"result":{"capabilities":{},"protocolVersion":"2024-11-05"}}), flush=True)
    elif m == "tools/list":
        print(json.dumps({"jsonrpc":"2.0","id":i,"result":{"tools":[{"name":"ping","inputSchema":{}}]}}), flush=True)
"#;
        send(
            &app,
            "POST",
            "/api/mcp/servers",
            Some(
                serde_json::json!({ "name": "local", "command": "python3", "args": ["-c", stub] }),
            ),
        )
        .await;
        let (status_code, body) = send(&app, "POST", "/api/mcp/servers/local/test", None).await;
        assert_eq!(status_code, StatusCode::OK, "body: {body}");
        assert_eq!(body["tools"][0], "ping");
    }

    #[tokio::test]
    async fn test_endpoint_reports_a_bad_gateway_on_connect_failure() {
        let dir = tempfile::tempdir().unwrap();
        let app = router(state_at(dir.path(), never_opens));
        send(
            &app,
            "POST",
            "/api/mcp/servers",
            Some(serde_json::json!({ "name": "dead", "url": "http://127.0.0.1:1/mcp" })),
        )
        .await;
        let (status_code, _) = send(&app, "POST", "/api/mcp/servers/dead/test", None).await;
        assert_eq!(status_code, StatusCode::BAD_GATEWAY);
    }

    #[tokio::test]
    async fn test_reports_a_bad_gateway_when_the_token_cannot_refresh() {
        let dir = tempfile::tempdir().unwrap();
        let app = router(state_at(dir.path(), never_opens));
        send(
            &app,
            "POST",
            "/api/mcp/servers",
            Some(serde_json::json!({ "name": "remote", "url": "http://127.0.0.1:1/mcp" })),
        )
        .await;
        // Seed an expired token with a dead refresh endpoint.
        let mut store = AuthStore::default();
        store.set(
            "remote",
            leviath_mcp::ServerAuth {
                token_endpoint: "http://127.0.0.1:1/token".to_string(),
                refresh_token: Some("good".to_string()),
                expires_at: 1,
                ..Default::default()
            },
        );
        store.save(&dir.path().join("mcp-auth.json")).unwrap();
        let (status_code, _) = send(&app, "POST", "/api/mcp/servers/remote/test", None).await;
        assert_eq!(status_code, StatusCode::BAD_GATEWAY);
    }

    // ─── I/O failure arms ─────────────────────────────────────────────────

    /// A state whose config/store paths are directories, so reads fail.
    fn broken_state(dir: &std::path::Path) -> AppState {
        let cfg = dir.join("cfg-dir");
        let store = dir.join("store-dir");
        std::fs::create_dir(&cfg).unwrap();
        std::fs::create_dir(&store).unwrap();
        let (tx, _) = broadcast::channel::<ServerEvent>(16);
        AppState {
            config: Arc::new(Config::default()),
            event_tx: tx,
            control: crate::commands::serve::testutil::no_daemon_client(),
            mcp: McpAdmin {
                config_path: cfg,
                store_path: store,
                opener: Arc::new(never_opens),
                clock: fixed_clock,
            },
            limits: Default::default(),
        }
    }

    #[tokio::test]
    async fn read_endpoints_surface_an_unreadable_config() {
        let dir = tempfile::tempdir().unwrap();
        let app = router(broken_state(dir.path()));
        for (method, uri) in [
            ("GET", "/api/mcp/servers"),
            ("GET", "/api/mcp/servers/x/status"),
            ("POST", "/api/mcp/servers/x/login"),
            ("POST", "/api/mcp/servers/x/test"),
            ("DELETE", "/api/mcp/servers/x"),
        ] {
            let (status_code, _) = send(&app, method, uri, None).await;
            assert_eq!(
                status_code,
                StatusCode::INTERNAL_SERVER_ERROR,
                "{method} {uri}"
            );
        }
    }

    #[tokio::test]
    async fn add_surfaces_an_unreadable_config() {
        let dir = tempfile::tempdir().unwrap();
        let app = router(broken_state(dir.path()));
        let (status_code, _) = send(
            &app,
            "POST",
            "/api/mcp/servers",
            Some(serde_json::json!({ "name": "x", "command": "npx" })),
        )
        .await;
        assert_eq!(status_code, StatusCode::INTERNAL_SERVER_ERROR);
    }

    #[tokio::test]
    async fn add_surfaces_an_unwritable_config() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("a-file");
        std::fs::write(&file, b"x").unwrap();
        let (tx, _) = broadcast::channel::<ServerEvent>(16);
        let state = AppState {
            config: Arc::new(Config::default()),
            event_tx: tx,
            control: crate::commands::serve::testutil::no_daemon_client(),
            mcp: McpAdmin {
                config_path: file.join("config.toml"),
                store_path: dir.path().join("s.json"),
                opener: Arc::new(never_opens),
                clock: fixed_clock,
            },
            limits: Default::default(),
        };
        let app = router(state);
        let (status_code, _) = send(
            &app,
            "POST",
            "/api/mcp/servers",
            Some(serde_json::json!({ "name": "x", "command": "npx" })),
        )
        .await;
        assert_eq!(status_code, StatusCode::INTERNAL_SERVER_ERROR);
    }

    #[tokio::test]
    async fn remove_surfaces_an_unwritable_config() {
        // Config reads fine, add one server, then make the config file read-only.
        let dir = tempfile::tempdir().unwrap();
        let app = router(state_at(dir.path(), never_opens));
        send(
            &app,
            "POST",
            "/api/mcp/servers",
            Some(serde_json::json!({ "name": "x", "command": "npx" })),
        )
        .await;
        let cfg = dir.path().join("config.toml");
        let mut perms = std::fs::metadata(&cfg).unwrap().permissions();
        perms.set_readonly(true);
        std::fs::set_permissions(&cfg, perms).unwrap();
        let (status_code, _) = send(&app, "DELETE", "/api/mcp/servers/x", None).await;
        assert_eq!(status_code, StatusCode::INTERNAL_SERVER_ERROR);
    }

    #[tokio::test]
    async fn login_surfaces_an_unwritable_store() {
        let base = mock_oauth_server().await;
        let dir = tempfile::tempdir().unwrap();
        let app = router(state_at(dir.path(), auto_consent));
        send(
            &app,
            "POST",
            "/api/mcp/servers",
            Some(serde_json::json!({ "name": "navigator", "url": format!("{base}/mcp") })),
        )
        .await;
        // Make the store a read-only file so persisting the token fails.
        let store = dir.path().join("mcp-auth.json");
        AuthStore::default().save(&store).unwrap();
        let mut perms = std::fs::metadata(&store).unwrap().permissions();
        perms.set_readonly(true);
        std::fs::set_permissions(&store, perms).unwrap();
        let (status_code, _) = send(&app, "POST", "/api/mcp/servers/navigator/login", None).await;
        assert_eq!(status_code, StatusCode::INTERNAL_SERVER_ERROR);
    }

    // ─── McpAdmin::default ────────────────────────────────────────────────

    #[tokio::test]
    async fn list_and_status_describe_a_stdio_server() {
        let dir = tempfile::tempdir().unwrap();
        let app = router(state_at(dir.path(), never_opens));
        send(
            &app,
            "POST",
            "/api/mcp/servers",
            Some(serde_json::json!({ "name": "local", "command": "npx" })),
        )
        .await;
        let (_, body) = send(&app, "GET", "/api/mcp/servers", None).await;
        assert_eq!(body[0]["transport"], "stdio");
        assert_eq!(body[0]["endpoint"], "npx");
        assert_eq!(body[0]["auth"], "n/a");
        let (_, body) = send(&app, "GET", "/api/mcp/servers/local/status", None).await;
        assert_eq!(body["transport"], "stdio");
    }

    #[tokio::test]
    async fn remove_clears_stored_credentials() {
        let dir = tempfile::tempdir().unwrap();
        let app = router(state_at(dir.path(), never_opens));
        send(
            &app,
            "POST",
            "/api/mcp/servers",
            Some(serde_json::json!({ "name": "remote", "url": "https://e.com/mcp" })),
        )
        .await;
        // Seed a credential so removal has something to clear.
        let mut store = AuthStore::default();
        store.set("remote", leviath_mcp::ServerAuth::default());
        store.save(&dir.path().join("mcp-auth.json")).unwrap();

        let (status_code, _) = send(&app, "DELETE", "/api/mcp/servers/remote", None).await;
        assert_eq!(status_code, StatusCode::NO_CONTENT);
        let reloaded = AuthStore::load(&dir.path().join("mcp-auth.json")).unwrap();
        assert!(reloaded.get("remote").is_none());
    }

    #[tokio::test]
    async fn a_second_login_reuses_the_client_id() {
        let base = mock_oauth_server().await;
        let dir = tempfile::tempdir().unwrap();
        let app = router(state_at(dir.path(), auto_consent));
        send(
            &app,
            "POST",
            "/api/mcp/servers",
            Some(serde_json::json!({ "name": "navigator", "url": format!("{base}/mcp") })),
        )
        .await;
        send(&app, "POST", "/api/mcp/servers/navigator/login", None).await;
        // Second login: store.get is Some, so the client_id is reused.
        let (status_code, _) = send(&app, "POST", "/api/mcp/servers/navigator/login", None).await;
        assert_eq!(status_code, StatusCode::OK);
    }

    #[tokio::test]
    async fn test_endpoint_reports_a_spawn_failure() {
        let dir = tempfile::tempdir().unwrap();
        let app = router(state_at(dir.path(), never_opens));
        send(
            &app,
            "POST",
            "/api/mcp/servers",
            Some(serde_json::json!({ "name": "x", "command": "definitely-not-a-real-binary-xyz" })),
        )
        .await;
        let (status_code, _) = send(&app, "POST", "/api/mcp/servers/x/test", None).await;
        assert_eq!(status_code, StatusCode::BAD_GATEWAY);
    }

    #[tokio::test]
    async fn test_endpoint_reports_a_list_tools_failure() {
        let dir = tempfile::tempdir().unwrap();
        let app = router(state_at(dir.path(), never_opens));
        let stub = r#"
import sys, json
for line in sys.stdin:
    line = line.strip()
    if not line: continue
    req = json.loads(line); m = req.get("method",""); i = req.get("id")
    if m == "initialize":
        print(json.dumps({"jsonrpc":"2.0","id":i,"result":{"capabilities":{},"protocolVersion":"2024-11-05"}}), flush=True)
    elif m == "tools/list":
        print(json.dumps({"jsonrpc":"2.0","id":i,"error":{"code":-32603,"message":"boom"}}), flush=True)
"#;
        send(
            &app,
            "POST",
            "/api/mcp/servers",
            Some(
                serde_json::json!({ "name": "local", "command": "python3", "args": ["-c", stub] }),
            ),
        )
        .await;
        let (status_code, _) = send(&app, "POST", "/api/mcp/servers/local/test", None).await;
        assert_eq!(status_code, StatusCode::BAD_GATEWAY);
    }

    #[test]
    fn never_opens_reports_no_browser() {
        assert!(!never_opens("https://x"));
    }

    #[test]
    fn default_admin_uses_real_paths() {
        // Constructing the default must not panic even with no LEVIATH_HOME; it
        // resolves the real config/store locations.
        let admin = McpAdmin::default();
        assert!(admin.config_path.to_string_lossy().contains("config.toml"));
    }

    #[test]
    fn system_now_advances_past_the_epoch() {
        assert!(system_now() > 1_600_000_000);
    }

    #[test]
    fn describe_marks_an_invalid_entry() {
        let bad = MCPServerConfig {
            name: "broken".to_string(),
            ..Default::default()
        };
        let info = McpServerInfo::describe(&bad, &AuthStore::default(), 0);
        assert_eq!(info.transport, "invalid");
        assert_eq!(info.auth, "n/a");
    }

    #[test]
    fn auth_status_reports_expired() {
        let http = MCPServerConfig::http("s", "https://e.com/mcp");
        let mut store = AuthStore::default();
        store.set(
            "s",
            leviath_mcp::ServerAuth {
                expires_at: 100,
                ..Default::default()
            },
        );
        assert_eq!(auth_status(&http, &store, 1_000), "expired");
    }
}