erinra 0.2.0

Memory MCP server for LLM coding assistants
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
//! Web dashboard server: axum HTTP server with embedded SPA.

pub mod auth;
pub mod daemon;
mod routes;

use std::net::SocketAddr;

use anyhow::Result;
use axum::Router;
#[cfg(debug_assertions)]
use tower_http::services::ServeDir;
use tower_http::set_header::SetResponseHeaderLayer;

use crate::service::MemoryService;

/// Shared state for axum handlers.
#[derive(Clone)]
pub struct AppState {
    pub service: MemoryService,
    pub auth_token: String,
}

/// Options for the web server.
pub struct ServeOptions {
    pub open_browser: bool,
}

/// Build the full app Router with all routes, SPA fallback, and security headers.
pub(crate) fn app_router(state: AppState) -> Router {
    let auth_layer =
        axum::middleware::from_fn_with_state(state.clone(), auth::require_bearer_token);
    let mcp_service = build_mcp_service(&state);

    Router::new()
        .nest(
            "/api",
            routes::api_router().layer(auth_layer.clone()),
        )
        .route(
            "/mcp",
            axum::routing::any_service(mcp_service).layer(auth_layer),
        )
        .fallback_service(spa_service())
        .with_state(state)
        .layer(SetResponseHeaderLayer::overriding(
            axum::http::header::X_CONTENT_TYPE_OPTIONS,
            axum::http::HeaderValue::from_static("nosniff"),
        ))
        .layer(SetResponseHeaderLayer::overriding(
            axum::http::header::X_FRAME_OPTIONS,
            axum::http::HeaderValue::from_static("DENY"),
        ))
        .layer(SetResponseHeaderLayer::overriding(
            axum::http::header::CONTENT_SECURITY_POLICY,
            axum::http::HeaderValue::from_static(
                "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:",
            ),
        ))
}

/// Build the streamable HTTP MCP service for mounting at `/mcp`.
fn build_mcp_service(
    state: &AppState,
) -> rmcp::transport::streamable_http_server::tower::StreamableHttpService<
    crate::mcp::ErinraServer,
    rmcp::transport::streamable_http_server::session::never::NeverSessionManager,
> {
    use rmcp::transport::streamable_http_server::{
        session::never::NeverSessionManager,
        tower::{StreamableHttpServerConfig, StreamableHttpService},
    };
    // Pre-build the server once; the factory just clones it per request.
    // This avoids per-request DB mutex acquisition and taxonomy queries
    // that ErinraServer::new() performs to cache instructions.
    let server = crate::mcp::ErinraServer::new(state.service.clone());

    // Stateless mode: no sessions, plain JSON responses (no SSE framing).
    let config_http = StreamableHttpServerConfig::default()
        .with_stateful_mode(false)
        .with_json_response(true);

    StreamableHttpService::new(
        move || Ok(server.clone()),
        std::sync::Arc::new(NeverSessionManager::default()),
        config_http,
    )
}

/// Start the web server and block until shutdown.
pub async fn serve(
    service: MemoryService,
    auth_token: String,
    addr: SocketAddr,
    opts: ServeOptions,
) -> Result<()> {
    // Save token ref before moving into AppState, for use in browser URL.
    let browser_token = if opts.open_browser {
        Some(auth_token.clone())
    } else {
        None
    };

    let state = AppState {
        service,
        auth_token,
    };

    let app = app_router(state);

    let listener = tokio::net::TcpListener::bind(addr).await?;
    let local_addr = listener.local_addr()?;
    eprintln!("Erinra dashboard: http://{local_addr}");

    if let Some(token) = browser_token {
        let url = format!("http://{local_addr}?token={token}");
        if let Err(e) = open::that(url) {
            tracing::warn!("failed to open browser: {e}");
        }
    }

    axum::serve(listener, app).await?;
    Ok(())
}

/// Serve the embedded SPA. In release builds, the SPA is compiled into the binary.
/// In debug builds, we serve from the `web/build` directory on disk if it exists,
/// falling back to a simple HTML page if not built yet.
fn spa_service() -> axum::routing::MethodRouter {
    #[cfg(not(debug_assertions))]
    {
        use axum::http::StatusCode;

        use axum::response::IntoResponse;

        static SPA_DIR: include_dir::Dir =
            include_dir::include_dir!("$CARGO_MANIFEST_DIR/web/build");

        axum::routing::get(|uri: axum::http::Uri| async move {
            let path = uri.path().trim_start_matches('/');
            let is_exact = SPA_DIR.get_file(path).is_some();
            let file = if is_exact {
                SPA_DIR.get_file(path)
            } else {
                SPA_DIR.get_file("index.html")
            };
            match file {
                Some(file) => {
                    let content_type = if is_exact && !path.is_empty() {
                        mime_guess::from_path(path)
                            .first_or_text_plain()
                            .to_string()
                    } else {
                        "text/html; charset=utf-8".to_string()
                    };
                    (
                        [(axum::http::header::CONTENT_TYPE, content_type)],
                        file.contents(),
                    )
                        .into_response()
                }
                None => {
                    tracing::error!("SPA index.html missing from embedded assets");
                    (StatusCode::INTERNAL_SERVER_ERROR, "SPA assets missing").into_response()
                }
            }
        })
    }

    #[cfg(debug_assertions)]
    {
        use axum::response::Html;

        let build_dir = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("web/build");
        if build_dir.exists() {
            axum::routing::get_service(ServeDir::new(&build_dir).fallback(
                tower_http::services::ServeFile::new(build_dir.join("index.html")),
            ))
        } else {
            axum::routing::get(|| async {
                Html(
                    "<h1>Erinra Dashboard</h1>\
                     <p>SPA not built yet. Run <code>cd web && npm run build</code> first.</p>",
                )
            })
        }
    }
}

#[cfg(test)]
mod tests {
    use std::sync::{Arc, Mutex};

    use axum::body::Body;
    use axum::http::Request;
    use tower::ServiceExt;

    use super::*;
    use crate::db::{Database, DbConfig};
    use crate::embedding::MockEmbedder;
    use crate::service::ServiceConfig;

    const TEST_TOKEN: &str = "test-secret-token-1234";

    fn test_app() -> Router {
        let db = Database::open_in_memory(&DbConfig::default()).unwrap();
        let service = MemoryService::new(
            Arc::new(Mutex::new(db)),
            Arc::new(MockEmbedder::new(768)),
            None,
            ServiceConfig::default(),
        );
        let state = AppState {
            service,
            auth_token: TEST_TOKEN.to_string(),
        };
        app_router(state)
    }

    #[tokio::test]
    async fn mcp_initialize_with_valid_auth_returns_server_info() {
        let app = test_app();
        let body = serde_json::json!({
            "jsonrpc": "2.0",
            "id": 1,
            "method": "initialize",
            "params": {
                "protocolVersion": "2025-03-26",
                "capabilities": {},
                "clientInfo": {"name": "test", "version": "0.1"}
            }
        });
        let response = app
            .oneshot(
                Request::post("/mcp")
                    .header("Authorization", format!("Bearer {TEST_TOKEN}"))
                    .header("Content-Type", "application/json")
                    .header("Accept", "application/json, text/event-stream")
                    .body(Body::from(serde_json::to_vec(&body).unwrap()))
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), 200, "MCP initialize should return 200");
        let body = axum::body::to_bytes(response.into_body(), 1_000_000)
            .await
            .unwrap();
        let json: serde_json::Value =
            serde_json::from_slice(&body).expect("response should be valid JSON");
        assert!(
            json["result"]["serverInfo"].is_object(),
            "response should contain serverInfo, got: {json}"
        );
        assert_eq!(json["result"]["serverInfo"]["name"], "erinra");
    }

    #[tokio::test]
    async fn mcp_wrong_content_type_returns_415() {
        let app = test_app();
        let response = app
            .oneshot(
                Request::post("/mcp")
                    .header("Authorization", format!("Bearer {TEST_TOKEN}"))
                    .header("Content-Type", "text/plain")
                    .header("Accept", "application/json, text/event-stream")
                    .body(Body::from("not json"))
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(
            response.status(),
            415,
            "wrong Content-Type should return 415 Unsupported Media Type"
        );
    }

    #[tokio::test]
    async fn mcp_coexists_with_existing_routes() {
        let app = test_app();

        // API route still works.
        let api_resp = app
            .oneshot(
                Request::get("/api/discover")
                    .header("Authorization", format!("Bearer {TEST_TOKEN}"))
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(api_resp.status(), 200, "API discover should still work");
        let content_type = api_resp
            .headers()
            .get("content-type")
            .unwrap()
            .to_str()
            .unwrap();
        assert!(
            content_type.contains("application/json"),
            "API should return JSON, got: {content_type}"
        );

        // SPA route still works.
        let app = test_app();
        let spa_resp = app
            .oneshot(Request::get("/").body(Body::empty()).unwrap())
            .await
            .unwrap();
        assert_eq!(spa_resp.status(), 200, "SPA root should still work");
        let spa_ct = spa_resp
            .headers()
            .get("content-type")
            .unwrap()
            .to_str()
            .unwrap();
        assert!(
            spa_ct.contains("text/html"),
            "SPA should return HTML, got: {spa_ct}"
        );
    }

    #[tokio::test]
    async fn mcp_without_auth_returns_401() {
        let app = test_app();
        let body = serde_json::json!({
            "jsonrpc": "2.0",
            "id": 1,
            "method": "initialize",
            "params": {
                "protocolVersion": "2025-03-26",
                "capabilities": {},
                "clientInfo": {"name": "test", "version": "0.1"}
            }
        });
        let response = app
            .oneshot(
                Request::post("/mcp")
                    .header("Content-Type", "application/json")
                    .header("Accept", "application/json, text/event-stream")
                    .body(Body::from(serde_json::to_vec(&body).unwrap()))
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(
            response.status(),
            401,
            "MCP request without auth should return 401"
        );
    }

    #[tokio::test]
    async fn get_root_returns_html() {
        let app = test_app();
        let response = app
            .oneshot(Request::get("/").body(Body::empty()).unwrap())
            .await
            .unwrap();

        assert_eq!(response.status(), 200);
        let content_type = response
            .headers()
            .get("content-type")
            .expect("should have content-type header")
            .to_str()
            .unwrap();
        assert!(
            content_type.contains("text/html"),
            "expected text/html, got: {content_type}"
        );

        let body = axum::body::to_bytes(response.into_body(), 1_000_000)
            .await
            .unwrap();
        let body_str = String::from_utf8(body.to_vec()).unwrap();
        assert!(
            body_str.contains("<!doctype html>") || body_str.contains("<!DOCTYPE html>"),
            "body should contain HTML doctype, got: {}",
            &body_str[..body_str.len().min(200)]
        );
    }

    #[tokio::test]
    async fn spa_fallback_returns_index_html() {
        let app = test_app();
        let response = app
            .oneshot(
                Request::get("/nonexistent/spa/route")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), 200);
        let content_type = response
            .headers()
            .get("content-type")
            .expect("should have content-type header")
            .to_str()
            .unwrap();
        assert!(
            content_type.contains("text/html"),
            "SPA fallback should return HTML, got: {content_type}"
        );

        let body = axum::body::to_bytes(response.into_body(), 1_000_000)
            .await
            .unwrap();
        let body_str = String::from_utf8(body.to_vec()).unwrap();
        assert!(
            body_str.contains("<!doctype html>") || body_str.contains("<!DOCTYPE html>"),
            "SPA fallback body should contain HTML doctype"
        );
    }

    #[tokio::test]
    async fn robots_txt_returns_correct_content() {
        let app = test_app();
        let response = app
            .oneshot(Request::get("/robots.txt").body(Body::empty()).unwrap())
            .await
            .unwrap();

        assert_eq!(response.status(), 200);
        let content_type = response
            .headers()
            .get("content-type")
            .expect("should have content-type header")
            .to_str()
            .unwrap();
        assert!(
            content_type.contains("text/plain"),
            "robots.txt should be text/plain, got: {content_type}"
        );

        let body = axum::body::to_bytes(response.into_body(), 10_000)
            .await
            .unwrap();
        let body_str = String::from_utf8(body.to_vec()).unwrap();
        assert!(
            body_str.contains("User-agent"),
            "robots.txt should contain User-agent directive, got: {body_str}"
        );
    }

    #[tokio::test]
    async fn static_assets_get_correct_mime_types() {
        let app = test_app();
        let response = app
            .oneshot(Request::get("/_app/env.js").body(Body::empty()).unwrap())
            .await
            .unwrap();

        assert_eq!(response.status(), 200);
        let content_type = response
            .headers()
            .get("content-type")
            .expect("should have content-type header")
            .to_str()
            .unwrap();
        assert!(
            content_type.contains("javascript"),
            "env.js should have javascript content-type, got: {content_type}"
        );
    }

    #[tokio::test]
    async fn security_headers_present_on_spa_responses() {
        let app = test_app();
        let response = app
            .oneshot(Request::get("/").body(Body::empty()).unwrap())
            .await
            .unwrap();

        assert_eq!(response.status(), 200);

        let headers = response.headers();

        let xcto = headers
            .get("x-content-type-options")
            .expect("should have x-content-type-options header")
            .to_str()
            .unwrap();
        assert_eq!(xcto, "nosniff");

        let xfo = headers
            .get("x-frame-options")
            .expect("should have x-frame-options header")
            .to_str()
            .unwrap();
        assert_eq!(xfo, "DENY");

        let csp = headers
            .get("content-security-policy")
            .expect("should have content-security-policy header")
            .to_str()
            .unwrap();
        assert_eq!(
            csp,
            "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:"
        );
    }

    #[tokio::test]
    async fn api_routes_take_priority_over_spa_fallback() {
        let app = test_app();
        let response = app
            .oneshot(
                Request::get("/api/discover")
                    .header("Authorization", format!("Bearer {TEST_TOKEN}"))
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), 200);
        let content_type = response
            .headers()
            .get("content-type")
            .expect("should have content-type header")
            .to_str()
            .unwrap();
        assert!(
            content_type.contains("application/json"),
            "API route should return JSON, got: {content_type}"
        );
    }

    #[tokio::test]
    async fn api_with_valid_bearer_token_returns_200() {
        let app = test_app();
        let response = app
            .oneshot(
                Request::get("/api/discover")
                    .header("Authorization", format!("Bearer {TEST_TOKEN}"))
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), 200);
    }

    #[tokio::test]
    async fn api_without_bearer_token_returns_401() {
        let app = test_app();
        let response = app
            .oneshot(Request::get("/api/discover").body(Body::empty()).unwrap())
            .await
            .unwrap();

        assert_eq!(response.status(), 401);
    }

    #[tokio::test]
    async fn api_with_wrong_bearer_token_returns_401() {
        let app = test_app();
        let response = app
            .oneshot(
                Request::get("/api/discover")
                    .header("Authorization", "Bearer wrong-token")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), 401);
    }

    #[tokio::test]
    async fn api_with_malformed_auth_headers_returns_401() {
        let malformed_headers = vec![
            "Basic abc", // wrong scheme
            "Bearer ",   // no value after space
            "",          // empty
            "Bearer",    // no space separator
        ];

        for header_value in malformed_headers {
            let app = test_app();
            let response = app
                .oneshot(
                    Request::get("/api/discover")
                        .header("Authorization", header_value)
                        .body(Body::empty())
                        .unwrap(),
                )
                .await
                .unwrap();

            assert_eq!(
                response.status(),
                401,
                "Expected 401 for Authorization: '{header_value}'"
            );
        }
    }
}