shuttle-rs 2026.6.2

Local-first event log CLI for agent memory, repository context, task coordination, handoffs, messaging, mesh sync, and MCP access.
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
use std::env;
use std::net::SocketAddr;
use std::path::PathBuf;

use crate::core::{Event, Result, ShuttleError};
use crate::oauth::{self, OAuthConfig, OAuthStore};
use crate::store::SqliteEventStore;
use axum::extract::{Form, Query, State};
use axum::http::{header, HeaderMap, HeaderValue, StatusCode};
use axum::response::{Html, IntoResponse, Redirect, Response};
use axum::routing::{get, post};
use axum::{Json, Router};
use serde::Serialize;
use serde_json::json;

#[derive(Clone)]
pub struct AppRuntime {
    pub store: SqliteEventStore,
    pub cwd: PathBuf,
    pub workspace_id: String,
    pub agent: String,
    pub session_id: String,
    pub oauth: Option<OAuthRuntime>,
}

#[derive(Clone)]
pub struct OAuthRuntime {
    pub config: OAuthConfig,
    pub store: OAuthStore,
}

#[derive(Debug, Serialize)]
struct Dashboard {
    inbox: Vec<Event>,
    tasks: Vec<crate::task::TaskSummary>,
    memories: Vec<Event>,
    context: crate::context::Context,
}

pub async fn serve(runtime: AppRuntime, addr: SocketAddr) -> Result<()> {
    let app = router(runtime);
    let listener = tokio::net::TcpListener::bind(addr)
        .await
        .map_err(|err| ShuttleError::Store(err.to_string()))?;
    axum::serve(listener, app)
        .await
        .map_err(|err| ShuttleError::Store(err.to_string()))
}

pub fn router(runtime: AppRuntime) -> Router {
    Router::new()
        .route("/", get(index))
        .route("/api/dashboard", get(dashboard))
        .route("/api/inbox", get(inbox))
        .route("/api/tasks", get(tasks))
        .route("/api/memories", get(memories))
        .route("/api/context", get(context))
        .route(
            "/mcp",
            get(mcp_health)
                .post(mcp_post)
                .delete(mcp_delete)
                .options(mcp_options),
        )
        .route(
            "/.well-known/oauth-protected-resource",
            get(oauth_protected_resource),
        )
        .route(
            "/.well-known/oauth-protected-resource/mcp",
            get(oauth_protected_resource),
        )
        .route(
            "/.well-known/oauth-authorization-server",
            get(oauth_authorization_server),
        )
        .route("/oauth/register", post(oauth_register))
        .route(
            "/oauth/authorize",
            get(oauth_authorize_page).post(oauth_authorize_submit),
        )
        .route("/oauth/token", post(oauth_token))
        .with_state(runtime)
}

async fn index(headers: HeaderMap, State(runtime): State<AppRuntime>) -> Response {
    if let Some(response) = mcp_unauthorized_response(runtime.oauth.as_ref(), &headers) {
        return response;
    }
    Html(
        r#"<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Shuttle</title>
  <style>
    body { font-family: system-ui, sans-serif; margin: 2rem; color: #1f2937; }
    main { display: grid; gap: 1rem; grid-template-columns: repeat(auto-fit, minmax(260px, 1fr)); }
    section { border: 1px solid #d1d5db; border-radius: 8px; padding: 1rem; }
    h1 { margin-top: 0; }
    pre { white-space: pre-wrap; overflow-wrap: anywhere; }
  </style>
</head>
<body>
  <h1>Shuttle</h1>
  <main id="dashboard"></main>
  <script>
    fetch('/api/dashboard').then(r => r.json()).then(data => {
      const root = document.getElementById('dashboard');
      for (const [name, value] of Object.entries(data)) {
        const section = document.createElement('section');
        const heading = document.createElement('h2');
        heading.textContent = name;
        const pre = document.createElement('pre');
        pre.textContent = JSON.stringify(value, null, 2);
        section.append(heading, pre);
        root.append(section);
      }
    });
  </script>
</body>
</html>"#,
    )
    .into_response()
}

async fn dashboard(headers: HeaderMap, State(runtime): State<AppRuntime>) -> Response {
    if let Some(response) = mcp_unauthorized_response(runtime.oauth.as_ref(), &headers) {
        return response;
    }
    Json(Dashboard {
        inbox: crate::message::inbox(&runtime.store, &runtime.agent)
            .await
            .unwrap_or_default(),
        tasks: crate::task::open_tasks(&runtime.store, &runtime.workspace_id, Some(20))
            .await
            .unwrap_or_default(),
        memories: crate::memory::memories(&runtime.store)
            .await
            .unwrap_or_default(),
        context: crate::context::assemble_context(
            &runtime.store,
            &runtime.cwd,
            &runtime.workspace_id,
            &runtime.agent,
        )
        .await
        .unwrap_or_else(|_| crate::context::Context {
            repo: runtime.cwd.display().to_string(),
            branch: "unknown".to_owned(),
            commit: "unknown".to_owned(),
            git_remote: None,
            dirty: false,
            dirty_files: Vec::new(),
            open_tasks: Vec::new(),
            claimed_tasks: Vec::new(),
            recent_decisions: Vec::new(),
            related_memories: Vec::new(),
            recent_messages: Vec::new(),
            pending_handoffs: Vec::new(),
            recent_completed_handoffs: Vec::new(),
            inbox: Vec::new(),
        }),
    })
    .into_response()
}

async fn inbox(headers: HeaderMap, State(runtime): State<AppRuntime>) -> Response {
    if let Some(response) = mcp_unauthorized_response(runtime.oauth.as_ref(), &headers) {
        return response;
    }
    Json(
        crate::message::inbox(&runtime.store, &runtime.agent)
            .await
            .unwrap_or_default(),
    )
    .into_response()
}

async fn tasks(headers: HeaderMap, State(runtime): State<AppRuntime>) -> Response {
    if let Some(response) = mcp_unauthorized_response(runtime.oauth.as_ref(), &headers) {
        return response;
    }
    Json(
        crate::task::open_tasks(&runtime.store, &runtime.workspace_id, Some(20))
            .await
            .unwrap_or_default(),
    )
    .into_response()
}

async fn memories(headers: HeaderMap, State(runtime): State<AppRuntime>) -> Response {
    if let Some(response) = mcp_unauthorized_response(runtime.oauth.as_ref(), &headers) {
        return response;
    }
    Json(
        crate::memory::memories(&runtime.store)
            .await
            .unwrap_or_default(),
    )
    .into_response()
}

async fn context(headers: HeaderMap, State(runtime): State<AppRuntime>) -> Response {
    if let Some(response) = mcp_unauthorized_response(runtime.oauth.as_ref(), &headers) {
        return response;
    }
    Json(
        crate::context::assemble_context(
            &runtime.store,
            &runtime.cwd,
            &runtime.workspace_id,
            &runtime.agent,
        )
        .await
        .ok(),
    )
    .into_response()
}

async fn mcp_health(headers: HeaderMap, State(runtime): State<AppRuntime>) -> Response {
    if let Some(response) = mcp_unauthorized_response(runtime.oauth.as_ref(), &headers) {
        return response;
    }
    with_cors((StatusCode::OK, "Shuttle MCP server"))
}

async fn mcp_delete(headers: HeaderMap, State(runtime): State<AppRuntime>) -> Response {
    if let Some(response) = mcp_unauthorized_response(runtime.oauth.as_ref(), &headers) {
        return response;
    }
    with_cors((StatusCode::OK, "OK"))
}

async fn mcp_options() -> Response {
    with_cors(StatusCode::NO_CONTENT)
}

async fn mcp_post(
    headers: HeaderMap,
    State(runtime): State<AppRuntime>,
    Json(request): Json<crate::mcp::Request>,
) -> Response {
    if let Some(response) = mcp_unauthorized_response(runtime.oauth.as_ref(), &headers) {
        return response;
    }
    let response = crate::mcp::handle_request(
        &crate::mcp::McpRuntime {
            store: runtime.store,
            cwd: runtime.cwd,
            workspace_id: runtime.workspace_id,
            agent: runtime.agent,
            session_id: runtime.session_id,
        },
        request,
    )
    .await;
    with_cors(Json(response))
}

async fn oauth_protected_resource(State(runtime): State<AppRuntime>) -> Response {
    let Some(oauth) = runtime.oauth else {
        return (StatusCode::NOT_FOUND, "OAuth is not configured").into_response();
    };
    Json(oauth::protected_resource_metadata(&oauth.config)).into_response()
}

async fn oauth_authorization_server(State(runtime): State<AppRuntime>) -> Response {
    let Some(oauth) = runtime.oauth else {
        return (StatusCode::NOT_FOUND, "OAuth is not configured").into_response();
    };
    Json(oauth::authorization_server_metadata(&oauth.config)).into_response()
}

async fn oauth_register(
    State(runtime): State<AppRuntime>,
    Json(request): Json<oauth::RegisterRequest>,
) -> Response {
    let Some(oauth) = runtime.oauth else {
        return (StatusCode::NOT_FOUND, "OAuth is not configured").into_response();
    };
    match oauth.store.register_client(request) {
        Ok(client) => Json(json!({
            "client_id": client.client_id,
            "client_id_issued_at": chrono::Utc::now().timestamp(),
            "redirect_uris": client.redirect_uris,
            "client_name": client.client_name,
            "token_endpoint_auth_method": "none",
        }))
        .into_response(),
        Err(err) => oauth_error(StatusCode::BAD_REQUEST, "invalid_request", &err.to_string()),
    }
}

async fn oauth_authorize_page(
    State(runtime): State<AppRuntime>,
    Query(request): Query<oauth::AuthorizeRequest>,
) -> Response {
    let Some(oauth) = runtime.oauth else {
        return (StatusCode::NOT_FOUND, "OAuth is not configured").into_response();
    };
    if request.response_type != "code" {
        return oauth_error(
            StatusCode::BAD_REQUEST,
            "unsupported_response_type",
            "response_type must be code",
        );
    }
    match oauth
        .store
        .client_allows_redirect(&request.client_id, &request.redirect_uri)
    {
        Ok(true) => {
            Html(authorize_html(&request, oauth.config.admin_token.is_some())).into_response()
        }
        Ok(false) => oauth_error(
            StatusCode::BAD_REQUEST,
            "invalid_request",
            "unknown client_id or redirect_uri",
        ),
        Err(_) => oauth_error(
            StatusCode::INTERNAL_SERVER_ERROR,
            "server_error",
            "failed to validate OAuth client",
        ),
    }
}

async fn oauth_authorize_submit(
    State(runtime): State<AppRuntime>,
    Form(form): Form<oauth::AuthorizeForm>,
) -> Response {
    let Some(oauth) = runtime.oauth else {
        return (StatusCode::NOT_FOUND, "OAuth is not configured").into_response();
    };
    if let Some(expected) = oauth.config.admin_token.as_deref() {
        if !constant_time_eq(form.admin_token.as_bytes(), expected.as_bytes()) {
            return oauth_error(
                StatusCode::UNAUTHORIZED,
                "access_denied",
                "invalid admin token",
            );
        }
    }
    let request = oauth::AuthorizeRequest::from(form);
    if request.response_type != "code" {
        return oauth_error(
            StatusCode::BAD_REQUEST,
            "unsupported_response_type",
            "response_type must be code",
        );
    }
    match oauth.store.create_code(request.clone()) {
        Ok(code) => Redirect::to(&oauth::authorize_redirect(
            &request.redirect_uri,
            &code,
            request.state.as_deref(),
        ))
        .into_response(),
        Err(err) => oauth_error(StatusCode::BAD_REQUEST, "invalid_request", &err.to_string()),
    }
}

async fn oauth_token(
    State(runtime): State<AppRuntime>,
    Form(request): Form<oauth::TokenRequest>,
) -> Response {
    let Some(oauth) = runtime.oauth else {
        return (StatusCode::NOT_FOUND, "OAuth is not configured").into_response();
    };
    if request.grant_type != "authorization_code" {
        return oauth_error(
            StatusCode::BAD_REQUEST,
            "unsupported_grant_type",
            "grant_type must be authorization_code",
        );
    }
    match oauth.store.exchange_code(request) {
        Ok(token) => Json(token).into_response(),
        Err(err) => oauth_error(StatusCode::BAD_REQUEST, "invalid_grant", &err.to_string()),
    }
}

fn mcp_unauthorized_response(
    oauth: Option<&OAuthRuntime>,
    headers: &HeaderMap,
) -> Option<Response> {
    if let Some(oauth) = oauth {
        let Some(token) = bearer_token(headers) else {
            return Some(unauthorized_oauth(&oauth.config));
        };
        return match oauth.store.validate_access_token(token) {
            Ok(true) => None,
            Ok(false) => Some(unauthorized_oauth(&oauth.config)),
            Err(_) => Some(oauth_error(
                StatusCode::UNAUTHORIZED,
                "invalid_token",
                "failed to validate access token",
            )),
        };
    }

    let token = env::var("SHUTTLE_MCP_BEARER_TOKEN")
        .ok()
        .filter(|token| !token.is_empty())?;
    let expected = format!("Bearer {token}");
    if headers
        .get("authorization")
        .and_then(|header| header.to_str().ok())
        .is_some_and(|actual| constant_time_eq(actual.as_bytes(), expected.as_bytes()))
    {
        None
    } else {
        Some(with_cors(StatusCode::UNAUTHORIZED))
    }
}

fn bearer_token(headers: &HeaderMap) -> Option<&str> {
    headers
        .get(header::AUTHORIZATION)
        .and_then(|header| header.to_str().ok())
        .and_then(|value| {
            let (scheme, token) = value.split_once(' ')?;
            scheme.eq_ignore_ascii_case("Bearer").then_some(token)
        })
}

fn constant_time_eq(left: &[u8], right: &[u8]) -> bool {
    let mut diff = left.len() ^ right.len();
    for index in 0..left.len().max(right.len()) {
        let left = *left.get(index).unwrap_or(&0);
        let right = *right.get(index).unwrap_or(&0);
        diff |= (left ^ right) as usize;
    }
    diff == 0
}

fn with_cors(response: impl IntoResponse) -> Response {
    let (mut parts, body) = response.into_response().into_parts();
    parts
        .headers
        .insert("access-control-allow-origin", HeaderValue::from_static("*"));
    parts.headers.insert(
        "access-control-allow-methods",
        HeaderValue::from_static("GET,POST,DELETE,OPTIONS"),
    );
    parts.headers.insert(
        "access-control-allow-headers",
        HeaderValue::from_static(
            "accept,authorization,content-type,mcp-protocol-version,mcp-session-id",
        ),
    );
    parts.headers.insert(
        "access-control-expose-headers",
        HeaderValue::from_static("mcp-session-id"),
    );
    Response::from_parts(parts, body)
}

fn unauthorized_oauth(config: &OAuthConfig) -> Response {
    let mut response = with_cors(StatusCode::UNAUTHORIZED);
    let header_value = format!(
        r#"Bearer resource_metadata="{}/.well-known/oauth-protected-resource/mcp", scope="mcp""#,
        quoted_header_value(&config.public_url)
    );
    if let Ok(value) = HeaderValue::from_str(&header_value) {
        response
            .headers_mut()
            .insert(header::WWW_AUTHENTICATE, value);
    }
    response
}

fn oauth_error(status: StatusCode, code: &str, description: &str) -> Response {
    (
        status,
        Json(json!({ "error": code, "error_description": description })),
    )
        .into_response()
}

fn authorize_html(request: &oauth::AuthorizeRequest, requires_admin_token: bool) -> String {
    let admin = if requires_admin_token {
        r#"<label>Admin token <input name="admin_token" type="password" autocomplete="current-password" required></label>"#
    } else {
        r#"<input name="admin_token" type="hidden" value="">"#
    };
    format!(
        r#"<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Authorize Shuttle</title>
  <style>
    body {{ font-family: system-ui, sans-serif; margin: 2rem; color: #1f2937; }}
    form {{ display: grid; gap: 1rem; max-width: 32rem; }}
    input, button {{ font: inherit; padding: .6rem; }}
    label {{ display: grid; gap: .35rem; }}
  </style>
</head>
<body>
  <h1>Authorize Shuttle MCP</h1>
  <p>{client_id} is requesting access to Shuttle MCP.</p>
  <form method="post" action="/oauth/authorize">
    {admin}
    <input type="hidden" name="response_type" value="{response_type}">
    <input type="hidden" name="client_id" value="{client_id}">
    <input type="hidden" name="redirect_uri" value="{redirect_uri}">
    <input type="hidden" name="state" value="{state}">
    <input type="hidden" name="scope" value="{scope}">
    <input type="hidden" name="code_challenge" value="{code_challenge}">
    <input type="hidden" name="code_challenge_method" value="{code_challenge_method}">
    <button type="submit">Authorize</button>
  </form>
</body>
</html>"#,
        admin = admin,
        response_type = html_escape(&request.response_type),
        client_id = html_escape(&request.client_id),
        redirect_uri = html_escape(&request.redirect_uri),
        state = html_escape(request.state.as_deref().unwrap_or("")),
        scope = html_escape(request.scope.as_deref().unwrap_or("mcp")),
        code_challenge = html_escape(request.code_challenge.as_deref().unwrap_or("")),
        code_challenge_method =
            html_escape(request.code_challenge_method.as_deref().unwrap_or("S256")),
    )
}

fn html_escape(value: &str) -> String {
    value
        .replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
        .replace('"', "&quot;")
}

fn quoted_header_value(value: &str) -> String {
    value.replace('\\', "\\\\").replace('"', "\\\"")
}

#[cfg(test)]
mod tests {
    use super::*;
    use axum::body::Body;
    use axum::http::{Method, Request};
    use base64::engine::general_purpose::URL_SAFE_NO_PAD;
    use base64::Engine;
    use http_body_util::BodyExt;
    use sha2::{Digest, Sha256};
    use tower::ServiceExt;

    fn runtime(oauth: Option<OAuthRuntime>) -> AppRuntime {
        let dir = tempfile::tempdir().unwrap().keep();
        let db = dir.join("shuttle.db");
        AppRuntime {
            store: SqliteEventStore::open(&db).unwrap(),
            cwd: dir,
            workspace_id: "workspace".to_owned(),
            agent: "codex".to_owned(),
            session_id: "session".to_owned(),
            oauth,
        }
    }

    fn oauth_runtime() -> OAuthRuntime {
        let dir = tempfile::tempdir().unwrap().keep();
        OAuthRuntime {
            config: OAuthConfig {
                public_url: "https://shuttle.example.test".to_owned(),
                admin_token: Some("admin-token".to_owned()),
            },
            store: OAuthStore::open(dir.join("oauth.db")).unwrap(),
        }
    }

    fn issue_access_token(oauth: &OAuthRuntime) -> String {
        let verifier = "abc123abc123abc123abc123abc123abc123abc123abc123";
        let challenge = URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes()));
        let client = oauth
            .store
            .register_client(oauth::RegisterRequest {
                redirect_uris: vec!["https://client.example.test/callback".to_owned()],
                client_name: Some("client".to_owned()),
            })
            .unwrap();
        let code = oauth
            .store
            .create_code(oauth::AuthorizeRequest {
                response_type: "code".to_owned(),
                client_id: client.client_id.clone(),
                redirect_uri: "https://client.example.test/callback".to_owned(),
                state: None,
                scope: Some("mcp".to_owned()),
                code_challenge: Some(challenge),
                code_challenge_method: Some("S256".to_owned()),
            })
            .unwrap();
        oauth
            .store
            .exchange_code(oauth::TokenRequest {
                grant_type: "authorization_code".to_owned(),
                client_id: client.client_id,
                redirect_uri: "https://client.example.test/callback".to_owned(),
                code: Some(code),
                code_verifier: Some(verifier.to_owned()),
            })
            .unwrap()
            .access_token
    }

    async fn request(
        runtime: AppRuntime,
        path: &str,
        authorization: Option<&str>,
    ) -> axum::response::Response {
        let mut builder = Request::builder().method(Method::GET).uri(path);
        if let Some(authorization) = authorization {
            builder = builder.header(header::AUTHORIZATION, authorization);
        }
        router(runtime)
            .oneshot(builder.body(Body::empty()).unwrap())
            .await
            .unwrap()
    }

    #[tokio::test]
    async fn dashboard_routes_require_bearer_when_oauth_is_configured() {
        let oauth = oauth_runtime();
        let token = issue_access_token(&oauth);

        let index = request(runtime(Some(oauth.clone())), "/", None).await;
        let dashboard = request(runtime(Some(oauth.clone())), "/api/dashboard", None).await;
        let authorized_index = request(
            runtime(Some(oauth.clone())),
            "/",
            Some(&format!("Bearer {token}")),
        )
        .await;
        let authorized_dashboard = request(
            runtime(Some(oauth)),
            "/api/dashboard",
            Some(&format!("Bearer {token}")),
        )
        .await;

        assert_eq!(index.status(), StatusCode::UNAUTHORIZED);
        assert_eq!(dashboard.status(), StatusCode::UNAUTHORIZED);
        assert_eq!(authorized_index.status(), StatusCode::OK);
        assert_eq!(authorized_dashboard.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn dashboard_routes_remain_local_open_without_auth_configuration() {
        let index = request(runtime(None), "/", None).await;
        let dashboard = request(runtime(None), "/api/dashboard", None).await;

        assert_eq!(index.status(), StatusCode::OK);
        assert_eq!(dashboard.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn oauth_metadata_is_not_blocked_by_dashboard_auth() {
        let response = request(
            runtime(Some(oauth_runtime())),
            "/.well-known/oauth-authorization-server",
            None,
        )
        .await;

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

    #[tokio::test]
    async fn oauth_authorize_submit_redirects_callback_with_get() {
        let oauth = oauth_runtime();
        let client = oauth
            .store
            .register_client(oauth::RegisterRequest {
                redirect_uris: vec!["https://claude.ai/api/mcp/auth_callback".to_owned()],
                client_name: Some("Claude".to_owned()),
            })
            .unwrap();
        let body = format!(
            "admin_token=admin-token&response_type=code&client_id={}&redirect_uri=https%3A%2F%2Fclaude.ai%2Fapi%2Fmcp%2Fauth_callback&state=state-123&scope=mcp&code_challenge=challenge&code_challenge_method=S256",
            client.client_id
        );
        let response = router(runtime(Some(oauth)))
            .oneshot(
                Request::builder()
                    .method(Method::POST)
                    .uri("/oauth/authorize")
                    .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
                    .body(Body::from(body))
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::SEE_OTHER);
        let location = response
            .headers()
            .get(header::LOCATION)
            .and_then(|value| value.to_str().ok())
            .unwrap();
        assert!(location.starts_with("https://claude.ai/api/mcp/auth_callback?code=stl_"));
        assert!(location.contains("&state=state-123"));
        assert!(!location.contains("&iss="));
        assert!(!location.contains("?iss="));
    }

    #[tokio::test]
    async fn oauth_authorize_rejects_redirect_uri_with_trailing_slash() {
        let oauth = oauth_runtime();
        let client = oauth
            .store
            .register_client(oauth::RegisterRequest {
                redirect_uris: vec!["https://claude.ai/api/mcp/auth_callback".to_owned()],
                client_name: Some("Claude".to_owned()),
            })
            .unwrap();
        let body = format!(
            "admin_token=admin-token&response_type=code&client_id={}&redirect_uri=https%3A%2F%2Fclaude.ai%2Fapi%2Fmcp%2Fauth_callback%2F&state=state-123&scope=mcp&code_challenge=challenge&code_challenge_method=S256",
            client.client_id
        );
        let response = router(runtime(Some(oauth)))
            .oneshot(
                Request::builder()
                    .method(Method::POST)
                    .uri("/oauth/authorize")
                    .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
                    .body(Body::from(body))
                    .unwrap(),
            )
            .await
            .unwrap();

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

    #[tokio::test]
    async fn dashboard_html_renders_json_as_text_not_inner_html() {
        let response = request(runtime(None), "/", None).await;
        let body = response.into_body().collect().await.unwrap().to_bytes();
        let html = String::from_utf8(body.to_vec()).unwrap();

        assert!(html.contains("heading.textContent = name"));
        assert!(html.contains("pre.textContent = JSON.stringify(value, null, 2)"));
        assert!(!html.contains("section.innerHTML"));
    }
}