kumiho-construct 2026.5.11

Construct — memory-native AI agent runtime powered by Kumiho
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
//! `/api/mcp/*` — discovery + health proxy for the in-process MCP server.
//!
//! The MCP server now runs as a tokio task inside the main construct daemon
//! (see `gateway::run_gateway`), not as a separate `construct-mcp` process. It
//! binds an *ephemeral* port and writes the real URL to
//! `~/.construct/mcp.json`; the frontend reads that instead of hardcoding a
//! port.
//!
//! This module exposes `GET /api/mcp/discovery` which:
//! 1. Reads the discovery file (mtime-cached).
//! 2. Issues a short-timeout `GET <url>/health` against the MCP server.
//! 3. Returns a uniform JSON shape the UI can use to drive the status badge.

use super::AppState;
use super::mcp_discovery::{McpDiscovery, read_construct_mcp};
use crate::config::schema::{McpServerConfig, McpTransport};
use crate::tools::mcp_client::McpServer;
use axum::{
    body::Body,
    extract::{Path, State},
    http::{HeaderMap, StatusCode, header},
    response::{IntoResponse, Json, Response},
};
use futures_util::StreamExt;
use serde::Deserialize;
use serde_json::{Value, json};
use std::collections::HashMap;
use std::time::{Duration, Instant};
use tokio::time::timeout;

/// Map a discovery URL (e.g. `http://127.0.0.1:51234/mcp`) to its health URL
/// (`http://127.0.0.1:51234/health`). Robust to either form (with or without
/// the trailing `/mcp`).
fn health_url_from_discovery(url: &str) -> String {
    let trimmed = url.trim_end_matches('/');
    match trimmed.strip_suffix("/mcp") {
        Some(base) => format!("{base}/health"),
        None => format!("{trimmed}/health"),
    }
}

/// Health probe interface — trivially mockable in tests.
#[async_trait::async_trait]
pub trait HealthProbe: Send + Sync {
    async fn get_health(&self, url: &str) -> Result<Value, String>;
}

/// Default `reqwest`-backed probe with a 500ms timeout.
pub struct ReqwestHealthProbe;

#[async_trait::async_trait]
impl HealthProbe for ReqwestHealthProbe {
    async fn get_health(&self, url: &str) -> Result<Value, String> {
        let client = reqwest::Client::builder()
            .timeout(Duration::from_millis(500))
            .build()
            .map_err(|e| e.to_string())?;
        let resp = client.get(url).send().await.map_err(|e| e.to_string())?;
        if !resp.status().is_success() {
            return Err(format!("health status {}", resp.status()));
        }
        resp.json::<Value>().await.map_err(|e| e.to_string())
    }
}

/// Core decision logic, factored so tests can inject fakes.
pub async fn build_discovery_payload(
    discovery: Option<McpDiscovery>,
    probe: &dyn HealthProbe,
) -> Value {
    let Some(d) = discovery else {
        return json!({
            "available": false,
            "reason": "discovery file missing",
        });
    };
    let health_url = health_url_from_discovery(&d.url);
    match probe.get_health(&health_url).await {
        Ok(health) => json!({
            "available": true,
            "url": d.url,
            "health": health,
        }),
        Err(_) => json!({
            "available": false,
            "reason": "health check failed",
        }),
    }
}

/// GET /api/mcp/discovery
pub async fn handle_api_mcp_discovery(
    State(state): State<AppState>,
    headers: HeaderMap,
) -> impl IntoResponse {
    if let Err(e) = super::api::require_auth(&state, &headers) {
        return e.into_response();
    }

    let discovery = read_construct_mcp().ok();
    let payload = build_discovery_payload(discovery, &ReqwestHealthProbe).await;
    (StatusCode::OK, Json(payload)).into_response()
}

// ───────────────────────────────────────────────────────────────────────────
// Reverse-proxy to the in-process MCP server (`127.0.0.1:<ephemeral>`).
//
// Why: the browser lives on the gateway's origin. The MCP axum router has no
// CORS layer and listens on a different port, so the V2 Code tab can't POST
// `/session` directly (ERR_CONNECTION_REFUSED / CORS). Funneling those
// requests through `/api/mcp/*` keeps the browser same-origin and reuses the
// gateway's existing bearer-auth middleware. External MCP clients (e.g.
// Claude Desktop) still read `~/.construct/mcp.json` and talk to the MCP port
// directly — nothing changes for them.
// ───────────────────────────────────────────────────────────────────────────

/// Join a (possibly trailing-slash) MCP base URL with a request path.
/// Split out for unit tests — the real call site pulls `base` from `AppState`.
fn join_mcp_url(base: &str, path: &str) -> String {
    format!("{}{path}", base.trim_end_matches('/'))
}

/// Build an upstream URL (`<mcp_base>/<path>`) from the stored local MCP base.
/// Returns `None` when the MCP server failed to bind during startup.
fn mcp_upstream_url(state: &AppState, path: &str) -> Option<String> {
    let base = state.mcp_local_url.as_ref()?;
    Some(join_mcp_url(base, path))
}

/// Uniform 503 body for when MCP never bound. Mirrors the shape used by
/// `/api/mcp/discovery` so the frontend can treat it identically.
fn mcp_unavailable() -> Response {
    (
        StatusCode::SERVICE_UNAVAILABLE,
        Json(json!({
            "available": false,
            "reason": "mcp server not bound",
        })),
    )
        .into_response()
}

/// GET /api/mcp/health — direct proxy to the MCP server's `/health` endpoint
/// (convenience for the UI). Not required for session setup.
pub async fn handle_api_mcp_health(State(state): State<AppState>, headers: HeaderMap) -> Response {
    if let Err(e) = super::api::require_auth(&state, &headers) {
        return e.into_response();
    }
    let Some(url) = mcp_upstream_url(&state, "/health") else {
        return mcp_unavailable();
    };
    let client = match reqwest::Client::builder()
        .timeout(Duration::from_secs(5))
        .build()
    {
        Ok(c) => c,
        Err(e) => {
            tracing::warn!("api_mcp: build client failed: {e}");
            return (StatusCode::INTERNAL_SERVER_ERROR, "client build failed").into_response();
        }
    };
    match client.get(&url).send().await {
        Ok(resp) => {
            let status =
                StatusCode::from_u16(resp.status().as_u16()).unwrap_or(StatusCode::BAD_GATEWAY);
            let ct = resp
                .headers()
                .get(header::CONTENT_TYPE)
                .and_then(|v| v.to_str().ok())
                .unwrap_or("application/json")
                .to_string();
            let body = resp.bytes().await.unwrap_or_default();
            (status, [(header::CONTENT_TYPE, ct)], body).into_response()
        }
        Err(e) => {
            tracing::warn!("api_mcp: health upstream error: {e}");
            (StatusCode::BAD_GATEWAY, "mcp upstream error").into_response()
        }
    }
}

/// POST /api/mcp/session — proxy to the MCP server's `POST /session`.
///
/// Body passes through verbatim (`{ cwd, label }` today, but we don't parse
/// it). Returns whatever the MCP server returns — `{ session_id, token, cwd }`
/// on success.
pub async fn handle_api_mcp_session_create(
    State(state): State<AppState>,
    headers: HeaderMap,
    body: axum::body::Bytes,
) -> Response {
    if let Err(e) = super::api::require_auth(&state, &headers) {
        return e.into_response();
    }
    let Some(url) = mcp_upstream_url(&state, "/session") else {
        return mcp_unavailable();
    };
    let client = match reqwest::Client::builder()
        .timeout(Duration::from_secs(10))
        .build()
    {
        Ok(c) => c,
        Err(e) => {
            tracing::warn!("api_mcp: build client failed: {e}");
            return (StatusCode::INTERNAL_SERVER_ERROR, "client build failed").into_response();
        }
    };
    let mut req = client.post(&url).body(body.to_vec());
    if let Some(ct) = headers
        .get(header::CONTENT_TYPE)
        .and_then(|v| v.to_str().ok())
    {
        req = req.header(header::CONTENT_TYPE, ct);
    } else {
        req = req.header(header::CONTENT_TYPE, "application/json");
    }
    match req.send().await {
        Ok(resp) => {
            let status =
                StatusCode::from_u16(resp.status().as_u16()).unwrap_or(StatusCode::BAD_GATEWAY);
            let ct = resp
                .headers()
                .get(header::CONTENT_TYPE)
                .and_then(|v| v.to_str().ok())
                .unwrap_or("application/json")
                .to_string();
            let bytes = resp.bytes().await.unwrap_or_default();
            (status, [(header::CONTENT_TYPE, ct)], bytes).into_response()
        }
        Err(e) => {
            tracing::warn!("api_mcp: session upstream error: {e}");
            (StatusCode::BAD_GATEWAY, "mcp upstream error").into_response()
        }
    }
}

/// POST /api/mcp/call — proxy to the MCP server's `POST /mcp` (JSON-RPC 2.0).
pub async fn handle_api_mcp_call(
    State(state): State<AppState>,
    headers: HeaderMap,
    body: axum::body::Bytes,
) -> Response {
    if let Err(e) = super::api::require_auth(&state, &headers) {
        return e.into_response();
    }
    let Some(url) = mcp_upstream_url(&state, "/mcp") else {
        return mcp_unavailable();
    };
    // JSON-RPC calls can include long-running tool invocations; allow enough
    // headroom but still bound it so a runaway call doesn't tie up a worker.
    let client = match reqwest::Client::builder()
        .timeout(Duration::from_secs(120))
        .build()
    {
        Ok(c) => c,
        Err(e) => {
            tracing::warn!("api_mcp: build client failed: {e}");
            return (StatusCode::INTERNAL_SERVER_ERROR, "client build failed").into_response();
        }
    };
    let mut req = client.post(&url).body(body.to_vec());
    if let Some(ct) = headers
        .get(header::CONTENT_TYPE)
        .and_then(|v| v.to_str().ok())
    {
        req = req.header(header::CONTENT_TYPE, ct);
    } else {
        req = req.header(header::CONTENT_TYPE, "application/json");
    }
    if let Some(auth) = headers
        .get(header::AUTHORIZATION)
        .and_then(|v| v.to_str().ok())
    {
        // Some JSON-RPC calls (e.g. those scoped to a session) require the
        // per-session bearer the MCP server issued via POST /session. That
        // token is opaque to the gateway; pass it through so callers that
        // already hold one can reuse it.
        req = req.header(header::AUTHORIZATION, auth);
    }
    match req.send().await {
        Ok(resp) => {
            let status =
                StatusCode::from_u16(resp.status().as_u16()).unwrap_or(StatusCode::BAD_GATEWAY);
            let ct = resp
                .headers()
                .get(header::CONTENT_TYPE)
                .and_then(|v| v.to_str().ok())
                .unwrap_or("application/json")
                .to_string();
            let bytes = resp.bytes().await.unwrap_or_default();
            (status, [(header::CONTENT_TYPE, ct)], bytes).into_response()
        }
        Err(e) => {
            tracing::warn!("api_mcp: call upstream error: {e}");
            (StatusCode::BAD_GATEWAY, "mcp upstream error").into_response()
        }
    }
}

/// GET /api/mcp/session/{id}/events — SSE passthrough.
///
/// Keeps the stream alive for the life of the session; reqwest's default
/// timeout is disabled via a long connect timeout + no request timeout so the
/// server-push stream isn't severed mid-flight.
pub async fn handle_api_mcp_session_events(
    State(state): State<AppState>,
    headers: HeaderMap,
    Path(session_id): Path<String>,
) -> Response {
    if let Err(e) = super::api::require_auth(&state, &headers) {
        return e.into_response();
    }
    let Some(url) = mcp_upstream_url(&state, &format!("/session/{session_id}/events")) else {
        return mcp_unavailable();
    };
    let client = match reqwest::Client::builder()
        .connect_timeout(Duration::from_secs(5))
        // No request-level timeout: SSE is long-lived.
        .build()
    {
        Ok(c) => c,
        Err(e) => {
            tracing::warn!("api_mcp: build sse client failed: {e}");
            return (StatusCode::INTERNAL_SERVER_ERROR, "client build failed").into_response();
        }
    };
    let mut req = client.get(&url).header(header::ACCEPT, "text/event-stream");
    if let Some(auth) = headers
        .get(header::AUTHORIZATION)
        .and_then(|v| v.to_str().ok())
    {
        req = req.header(header::AUTHORIZATION, auth);
    }
    let upstream = match req.send().await {
        Ok(r) => r,
        Err(e) => {
            tracing::warn!("api_mcp: sse upstream connect failed: {e}");
            return (StatusCode::BAD_GATEWAY, "mcp upstream error").into_response();
        }
    };
    if !upstream.status().is_success() {
        let status =
            StatusCode::from_u16(upstream.status().as_u16()).unwrap_or(StatusCode::BAD_GATEWAY);
        let body = upstream.bytes().await.unwrap_or_default();
        return (status, body).into_response();
    }
    let byte_stream = upstream
        .bytes_stream()
        .map(|r| r.map_err(std::io::Error::other));
    Response::builder()
        .status(StatusCode::OK)
        .header(header::CONTENT_TYPE, "text/event-stream")
        .header(header::CACHE_CONTROL, "no-cache")
        .header("x-accel-buffering", "no")
        .body(Body::from_stream(byte_stream))
        .unwrap_or_else(|_| {
            (StatusCode::INTERNAL_SERVER_ERROR, "response build failed").into_response()
        })
}

// ───────────────────────────────────────────────────────────────────────────
// POST /api/mcp/servers/test — "Test" button in ConfigV2 MCP editor.
// Performs the same `initialize` + `tools/list` handshake an external CLI
// would, and reports success/failure + tool count + latency.
// ───────────────────────────────────────────────────────────────────────────

/// Hard ceiling on the full handshake (initialize + tools/list).
/// Bounded so a misconfigured server cannot tie up a request thread.
const TEST_HANDSHAKE_TIMEOUT_SECS: u64 = 10;

/// Wire shape posted by ConfigV2's `McpServerEntry` — tolerant of unset fields
/// for the transport the user didn't select. We translate to
/// [`McpServerConfig`] before handing off to the existing client.
#[derive(Debug, Deserialize)]
pub struct TestServerRequest {
    pub name: String,
    pub transport: String,
    #[serde(default)]
    pub command: Option<String>,
    #[serde(default)]
    pub args: Option<Vec<String>>,
    #[serde(default)]
    pub env: Option<HashMap<String, String>>,
    #[serde(default)]
    pub url: Option<String>,
    #[serde(default)]
    pub headers: Option<HashMap<String, String>>,
    #[serde(default)]
    pub timeout_ms: Option<u64>,
}

/// Validate the request and build an [`McpServerConfig`] ready to connect.
///
/// Returns a human-readable error string suitable for the response body
/// when a required field for the chosen transport is missing or the
/// transport itself is unknown.
pub fn request_to_config(req: &TestServerRequest) -> Result<McpServerConfig, String> {
    if req.name.trim().is_empty() {
        return Err("name is required".to_string());
    }
    let transport = match req.transport.as_str() {
        "stdio" => McpTransport::Stdio,
        "http" => McpTransport::Http,
        "sse" => McpTransport::Sse,
        other => return Err(format!("unknown transport `{other}`")),
    };
    match transport {
        McpTransport::Stdio => {
            if req
                .command
                .as_deref()
                .map(str::trim)
                .unwrap_or("")
                .is_empty()
            {
                return Err("command is required for stdio transport".to_string());
            }
        }
        McpTransport::Http | McpTransport::Sse => {
            if req.url.as_deref().map(str::trim).unwrap_or("").is_empty() {
                return Err("url is required for http/sse transport".to_string());
            }
        }
    }
    let tool_timeout_secs = req.timeout_ms.map(|ms| (ms / 1000).max(1));
    Ok(McpServerConfig {
        name: req.name.clone(),
        transport,
        url: req.url.clone(),
        command: req.command.clone().unwrap_or_default(),
        args: req.args.clone().unwrap_or_default(),
        env: req.env.clone().unwrap_or_default(),
        headers: req.headers.clone().unwrap_or_default(),
        tool_timeout_secs,
    })
}

/// POST /api/mcp/servers/test
pub async fn handle_api_mcp_servers_test(
    State(state): State<AppState>,
    headers: HeaderMap,
    Json(req): Json<TestServerRequest>,
) -> impl IntoResponse {
    if let Err(e) = super::api::require_auth(&state, &headers) {
        return e.into_response();
    }

    let config = match request_to_config(&req) {
        Ok(c) => c,
        Err(msg) => {
            return (
                StatusCode::OK,
                Json(json!({
                    "ok": false,
                    "error": msg,
                    "latency_ms": 0,
                })),
            )
                .into_response();
        }
    };

    let started = Instant::now();
    let result = timeout(
        Duration::from_secs(TEST_HANDSHAKE_TIMEOUT_SECS),
        McpServer::connect(config),
    )
    .await;
    let latency_ms = started.elapsed().as_millis() as u64;

    let payload = match result {
        Ok(Ok(server)) => {
            let tools = server.tools().await;
            let tool_names: Vec<String> = tools.iter().map(|t| t.name.clone()).collect();
            json!({
                "ok": true,
                "tool_count": tools.len(),
                "tools": tool_names,
                "latency_ms": latency_ms,
            })
        }
        Ok(Err(e)) => json!({
            "ok": false,
            "error": format!("{e:#}"),
            "latency_ms": latency_ms,
        }),
        Err(_) => json!({
            "ok": false,
            "error": format!("timed out after {TEST_HANDSHAKE_TIMEOUT_SECS}s"),
            "latency_ms": latency_ms,
        }),
    };

    (StatusCode::OK, Json(payload)).into_response()
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicUsize, Ordering};

    struct FakeProbeOk;
    #[async_trait::async_trait]
    impl HealthProbe for FakeProbeOk {
        async fn get_health(&self, _url: &str) -> Result<Value, String> {
            Ok(json!({
                "status": "ok",
                "pid": 123,
                "uptime_seconds": 5,
                "started_at": "2026-04-17T00:00:00Z",
                "protocol_version": "2024-11-05",
            }))
        }
    }

    struct FakeProbeErr;
    #[async_trait::async_trait]
    impl HealthProbe for FakeProbeErr {
        async fn get_health(&self, _url: &str) -> Result<Value, String> {
            Err("connection refused".into())
        }
    }

    struct CountingProbe(AtomicUsize);
    #[async_trait::async_trait]
    impl HealthProbe for CountingProbe {
        async fn get_health(&self, url: &str) -> Result<Value, String> {
            self.0.fetch_add(1, Ordering::SeqCst);
            Ok(json!({"hit": url}))
        }
    }

    #[test]
    fn join_mcp_url_composes_base_and_path() {
        assert_eq!(
            join_mcp_url("http://127.0.0.1:60004", "/session"),
            "http://127.0.0.1:60004/session"
        );
        assert_eq!(
            join_mcp_url("http://127.0.0.1:60004/", "/session"),
            "http://127.0.0.1:60004/session"
        );
        assert_eq!(
            join_mcp_url("http://127.0.0.1:60004", "/session/abc/events"),
            "http://127.0.0.1:60004/session/abc/events"
        );
        assert_eq!(
            join_mcp_url("http://127.0.0.1:60004", "/mcp"),
            "http://127.0.0.1:60004/mcp"
        );
    }

    #[test]
    fn health_url_strips_mcp_suffix() {
        assert_eq!(
            health_url_from_discovery("http://127.0.0.1:54500/mcp"),
            "http://127.0.0.1:54500/health"
        );
        assert_eq!(
            health_url_from_discovery("http://127.0.0.1:54500/mcp/"),
            "http://127.0.0.1:54500/health"
        );
        assert_eq!(
            health_url_from_discovery("http://127.0.0.1:54500"),
            "http://127.0.0.1:54500/health"
        );
    }

    #[tokio::test]
    async fn discovery_missing_file() {
        let v = build_discovery_payload(None, &FakeProbeOk).await;
        assert_eq!(v["available"], false);
        assert_eq!(v["reason"], "discovery file missing");
    }

    #[tokio::test]
    async fn discovery_present_daemon_reachable() {
        let d = McpDiscovery {
            url: "http://127.0.0.1:50000/mcp".into(),
            pid: Some(42),
            started_at: None,
        };
        let v = build_discovery_payload(Some(d), &FakeProbeOk).await;
        assert_eq!(v["available"], true);
        assert_eq!(v["url"], "http://127.0.0.1:50000/mcp");
        assert_eq!(v["health"]["status"], "ok");
        assert_eq!(v["health"]["pid"], 123);
    }

    #[tokio::test]
    async fn discovery_present_daemon_unreachable() {
        let d = McpDiscovery {
            url: "http://127.0.0.1:50000/mcp".into(),
            pid: Some(42),
            started_at: None,
        };
        let v = build_discovery_payload(Some(d), &FakeProbeErr).await;
        assert_eq!(v["available"], false);
        assert_eq!(v["reason"], "health check failed");
    }

    #[test]
    fn request_to_config_rejects_empty_name() {
        let req = TestServerRequest {
            name: "  ".into(),
            transport: "stdio".into(),
            command: Some("x".into()),
            args: None,
            env: None,
            url: None,
            headers: None,
            timeout_ms: None,
        };
        assert!(request_to_config(&req).unwrap_err().contains("name"));
    }

    #[test]
    fn request_to_config_rejects_unknown_transport() {
        let req = TestServerRequest {
            name: "m".into(),
            transport: "carrier-pigeon".into(),
            command: None,
            args: None,
            env: None,
            url: None,
            headers: None,
            timeout_ms: None,
        };
        assert!(
            request_to_config(&req)
                .unwrap_err()
                .contains("unknown transport")
        );
    }

    #[test]
    fn request_to_config_stdio_requires_command() {
        let req = TestServerRequest {
            name: "m".into(),
            transport: "stdio".into(),
            command: Some("   ".into()),
            args: None,
            env: None,
            url: None,
            headers: None,
            timeout_ms: None,
        };
        assert!(request_to_config(&req).unwrap_err().contains("command"));
    }

    #[test]
    fn request_to_config_http_requires_url() {
        let req = TestServerRequest {
            name: "m".into(),
            transport: "http".into(),
            command: None,
            args: None,
            env: None,
            url: Some("".into()),
            headers: None,
            timeout_ms: None,
        };
        assert!(request_to_config(&req).unwrap_err().contains("url"));
    }

    #[test]
    fn request_to_config_maps_stdio_fields() {
        let mut env = HashMap::new();
        env.insert("API_KEY".into(), "secret".into());
        let req = TestServerRequest {
            name: "memory".into(),
            transport: "stdio".into(),
            command: Some("/usr/local/bin/mcp".into()),
            args: Some(vec!["--flag".into(), "v".into()]),
            env: Some(env.clone()),
            url: None,
            headers: None,
            timeout_ms: Some(30_000),
        };
        let cfg = request_to_config(&req).unwrap();
        assert_eq!(cfg.name, "memory");
        assert_eq!(cfg.transport, McpTransport::Stdio);
        assert_eq!(cfg.command, "/usr/local/bin/mcp");
        assert_eq!(cfg.args, vec!["--flag", "v"]);
        assert_eq!(cfg.env, env);
        assert_eq!(cfg.tool_timeout_secs, Some(30));
    }

    #[test]
    fn request_to_config_maps_http_fields() {
        let mut hdr = HashMap::new();
        hdr.insert("X-Auth".into(), "abc".into());
        let req = TestServerRequest {
            name: "remote".into(),
            transport: "sse".into(),
            command: None,
            args: None,
            env: None,
            url: Some("https://example.com/mcp".into()),
            headers: Some(hdr.clone()),
            timeout_ms: Some(500),
        };
        let cfg = request_to_config(&req).unwrap();
        assert_eq!(cfg.transport, McpTransport::Sse);
        assert_eq!(cfg.url.as_deref(), Some("https://example.com/mcp"));
        assert_eq!(cfg.headers, hdr);
        // sub-second timeouts clamp up to 1s so we don't pass 0 downstream.
        assert_eq!(cfg.tool_timeout_secs, Some(1));
    }

    #[tokio::test]
    async fn discovery_hits_health_url_only_once() {
        let probe = CountingProbe(AtomicUsize::new(0));
        let d = McpDiscovery {
            url: "http://127.0.0.1:50000/mcp".into(),
            pid: None,
            started_at: None,
        };
        let _ = build_discovery_payload(Some(d), &probe).await;
        assert_eq!(probe.0.load(Ordering::SeqCst), 1);
    }
}