mcpls-core 0.8.0

Core library for MCP to LSP protocol translation
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
//! # mcpls-core
//!
//! Core library for MCP (Model Context Protocol) to LSP (Language Server Protocol) translation.
//!
//! This crate provides the fundamental building blocks for bridging AI agents with
//! language servers, enabling semantic code intelligence through MCP tools.
//!
//! ## Architecture
//!
//! The library is organized into several modules:
//!
//! - [`lsp`] - LSP client implementation for communicating with language servers
//! - [`mcp`] - MCP tool definitions and handlers
//! - [`bridge`] - Translation layer between MCP and LSP protocols
//! - [`config`] - Configuration types and loading
//! - [`mod@error`] - Error types for the library
//!
//! ## Example
//!
//! ```rust,ignore
//! use mcpls_core::{serve, serve_with, Transport, ServerConfig};
//!
//! #[tokio::main]
//! async fn main() {
//!     let config = ServerConfig::load().expect("failed to load config");
//!     // Stdio (default):
//!     let result = serve(config).await;
//!     // HTTP (requires `transport-http` feature):
//!     // let http = mcpls_core::HttpConfig::new("127.0.0.1:3000".parse().unwrap());
//!     // let result = serve_with(config, Transport::Http(http)).await;
//!
//!     // See `serve`/`serve_with`'s "Shutdown" docs: process::exit avoids a
//!     // runtime-shutdown hang under the stdio transport.
//!     std::process::exit(if result.is_ok() { 0 } else { 1 });
//! }
//! ```

#![cfg_attr(
    not(test),
    warn(clippy::arithmetic_side_effects, clippy::indexing_slicing)
)]
#![cfg_attr(docsrs, feature(doc_cfg))]

pub mod bridge;
pub mod config;
pub mod error;
pub mod lsp;
pub mod mcp;
mod redaction;
pub(crate) mod runtime;
pub mod transport;
mod util;

#[cfg(test)]
mod test_lsp;
#[cfg(test)]
mod test_support;

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

use bridge::{NotificationCache, Translator, WorkspaceRoots};
pub use config::{
    ProjectConfigStatus, ProjectConfigTrust, ServerAllowlist, ServerConfig, WorkspaceTrust,
};
use config::{ServerId, ToolRouter};
pub use error::Error;
use mcp::SubscriptionRegistry;
use runtime::disk_sweep::{spawn_disk_sweep, stop_disk_sweep};
use runtime::{StartPlan, plan_server_starts, shutdown, spawn_lsp_servers_background};
use tokio::sync::Mutex;
use tokio_util::sync::CancellationToken;
use tracing::{info, warn};
pub use transport::Transport;
#[cfg(feature = "transport-http")]
use transport::run_http;
#[cfg(feature = "transport-http")]
#[cfg_attr(docsrs, doc(cfg(feature = "transport-http")))]
pub use transport::{
    AllowedHost, AllowedOrigin, ConnectionLimit, HeaderReadTimeout, HttpConfig, HttpPath,
    InvalidAllowedHost, InvalidAllowedOrigin, InvalidHttpPath, LeaseWindow, ListenLease,
    ProbeDeadline, ProbeInterval, RequestBodyLimit, ResponseStreamDeadline, SessionLimit,
    StreamLiveness, WriteStallTimeout,
};
use transport::{ShutdownSignal, run_stdio};
pub use util::{escape_control, needs_control_escape};

/// Start the MCPLS server with the given configuration over stdio.
///
/// This is the backward-compatible entry point. It is equivalent to calling
/// `serve_with(config, Transport::Stdio)`.
///
/// # Errors
///
/// Returns an error if:
/// - MCP server setup fails
/// - Configuration is invalid
///
/// # Graceful Degradation
///
/// - **All servers succeed**: Service runs normally
/// - **Partial success**: Logs warnings for failures, continues with available servers
/// - **All servers fail**: Keeps serving; tools for the affected languages return `Error::ServerFailedToStart` with the spawn failure
///
/// # Shutdown
///
/// See [`serve_with`]'s "Shutdown" section — this function uses
/// [`Transport::Stdio`], so the same `std::process::exit` requirement
/// applies to callers.
pub async fn serve(config: ServerConfig) -> Result<(), Error> {
    serve_with(config, Transport::Stdio).await
}

/// Resolves the workspace roots and plans the server starts on the blocking
/// pool, since both walk the file system.
///
/// `initialize` still waits for the plan: it is needed to build the router the
/// MCP server answers from. Only the runtime workers stay free.
async fn plan_off_runtime(
    config: &ServerConfig,
    redactions: &Arc<redaction::Redactions>,
) -> Result<(WorkspaceRoots, StartPlan), Error> {
    let (config, redactions) = (config.clone(), Arc::clone(redactions));
    on_blocking_pool(move || {
        let roots = WorkspaceRoots::from_configured(&config.workspace.roots)?;
        let plan = plan_server_starts(&config, &roots, &redactions);
        Ok((roots, plan))
    })
    .await
    .map_err(|source| Error::TaskFailed {
        task: error::BackgroundTask::ServerPlanning,
        source,
    })?
}

/// Runs `work` on the blocking pool and returns its result, re-raising a panic
/// in it on the caller. A join that failed for any other reason (the runtime
/// shutting down cancelled it) is returned as the error.
pub(crate) async fn on_blocking_pool<T: Send + 'static>(
    work: impl FnOnce() -> T + Send + 'static,
) -> Result<T, tokio::task::JoinError> {
    match tokio::task::spawn_blocking(work).await {
        Ok(value) => Ok(value),
        Err(error) => match error.try_into_panic() {
            Ok(payload) => std::panic::resume_unwind(payload),
            Err(cancelled) => Err(cancelled),
        },
    }
}

/// Start the MCPLS server with an explicit transport.
///
/// Performs all shared setup (workspace discovery, LSP spawning, translator
/// initialization, diagnostic pump tasks) and then delegates to the
/// appropriate transport runner.
///
/// # Errors
///
/// Returns an error if:
/// - The MCP server or transport fails to start
/// - Configuration is invalid, including two applicable `[[lsp_servers]]`
///   entries whose per-tool routing is ambiguous in this workspace (shared
///   routing identity, two catch-alls, or the same tool claimed by both) --
///   see `config::ToolRouter::from_configs`
///
/// # DNS rebinding protection (HTTP transport)
///
/// When using `Transport::Http`, the underlying rmcp service validates the
/// inbound `Host` header against an allowlist that defaults to loopback
/// addresses only (`localhost`, `127.0.0.1`, `::1`). Requests with any other
/// `Host` value are rejected with `421 Misdirected Request`.
///
/// If you bind to a non-loopback address (e.g. `0.0.0.0:3000`) and expose the
/// service through a reverse proxy, the proxy must forward `Host: localhost`
/// (or another loopback alias) to the mcpls process. Direct non-loopback
/// access is intentionally blocked to prevent DNS-rebinding attacks.
///
/// # Shutdown
///
/// [`Transport::Stdio`] is backed by `tokio::io::stdin()`, which internally
/// parks an uncancellable blocking-pool thread in a raw `read()` syscall
/// that only returns on more input or EOF. If your `main` uses
/// `#[tokio::main]` and simply returns after awaiting this function, the
/// macro-generated runtime-shutdown wrapper blocks waiting for that thread
/// -- hanging indefinitely on `SIGTERM`/`SIGINT` as long as the MCP
/// client's stdin write end is still open, since that never triggers EOF.
/// Call `std::process::exit` right after this function resolves instead of
/// returning normally from `main`, as in the example below (see mcpls's own
/// `mcpls-cli` binary; tracked as #308). This does not apply to
/// `Transport::Http`, which never touches `tokio::io::stdin()`.
///
/// # Examples
///
/// ```rust,ignore
/// use mcpls_core::{serve_with, Transport, ServerConfig};
///
/// #[tokio::main]
/// async fn main() {
///     let config = ServerConfig::load().expect("failed to load config");
///     let exit_code = match serve_with(config, Transport::Stdio).await {
///         Ok(()) => 0,
///         Err(_) => 1,
///     };
///     // See "Shutdown" above: process::exit avoids a runtime-shutdown hang.
///     std::process::exit(exit_code);
/// }
/// ```
pub async fn serve_with(config: ServerConfig, transport: Transport) -> Result<(), Error> {
    info!("Starting MCPLS server...");

    // Registered before any other startup work -- including
    // `spawn_lsp_servers_background` below, which spawns LSP child processes
    // concurrently on another worker thread -- so a `SIGTERM`/`SIGINT`
    // arriving during config validation, workspace-root heuristics, or LSP
    // spawning is caught rather than hitting the OS's default disposition
    // (immediate termination, skipping the `shutdown()` cleanup below
    // entirely; any LSP child mid-spawn still dies with the lifeline/job
    // binding, see #270 and #526). See
    // `ShutdownSignal`'s docs for why this must be a single instance carried
    // through by value rather than re-registered later.
    let shutdown_signal = ShutdownSignal::new();

    // A programmatic `ServerConfig` skips the allowlist check the `load_*` functions run.
    config.validate()?;

    let language_map = config.build_effective_language_map();

    let startup_redactions = Arc::new(redaction::Redactions::for_servers(
        &config.lsp_servers,
        lsp::current_environment(),
    ));
    let (workspace_roots, plan) = plan_off_runtime(&config, &startup_redactions).await?;
    let (applicable_configs, refused, refusals) = plan.into_parts();

    info!(
        "Attempting to spawn {} applicable LSP server(s)...",
        applicable_configs.len()
    );

    // Built over the applicable (post-heuristics) configs only: this is where
    // #174's workspace-scoped routing rules (duplicate ServerId, conflicting
    // `handles` claims) are enforced -- a startup error naming the
    // conflicting `[[lsp_servers]]` entries, not a silent drop.
    let router = ToolRouter::from_configs(
        applicable_configs
            .iter()
            .map(lsp::ServerInitConfig::server_config)
            .chain(&refused),
    )?;

    // Built here (rather than alongside `subscription_registry` below) so
    // it can be handed to the translator, which uses it to invalidate a
    // respawned server's stale cached diagnostics -- see
    // `Translator::with_notification_cache`. Independent of `translator`
    // itself, which holds no outer lock: the pump only ever locks this
    // cache, so it never contends with a request handler running an
    // in-flight LSP round-trip.
    let notification_cache = Arc::new(Mutex::new(NotificationCache::new()));

    let mut translator = Translator::new()
        .with_startup_redactions(Arc::clone(&startup_redactions))
        .with_resource_limits(config.workspace.resource_limits())
        .with_workspace_trust(config.workspace_trust.clone())
        .with_extensions(language_map)
        .with_file_patterns(
            config
                .lsp_servers
                .iter()
                .flat_map(|server| server.file_patterns.iter().cloned()),
        )
        .with_router(router)
        .with_notification_cache(Arc::clone(&notification_cache))
        .with_indexing_ready_timeout(config.workspace.indexing_ready_timeout_seconds);
    // moved, not cloned -- `config`'s last use is above
    let (project_config_status, mcp) = (config.project_config_status, config.mcp);
    let max_concurrent_server_starts = config.workspace.max_concurrent_server_starts;
    translator.set_workspace_roots(workspace_roots.clone());

    // Mark applicable servers as "expected" so a tool call that arrives while
    // its server is still initializing gets a clear "still initializing" error
    // (instead of "no server configured"), telling the caller to wait and retry.
    let expected_servers: HashSet<ServerId> = applicable_configs
        .iter()
        .map(|c| c.server_config().id())
        .collect();
    translator.set_expected_servers(expected_servers);
    translator.record_refusals(&refusals);

    // Shared state, built BEFORE LSP initialization so the MCP server can answer
    // `initialize` immediately. LSP servers (which can take minutes to initialize
    // on a large solution, e.g. a 130-project Unity .sln via OmniSharp) are spawned
    // in a background task and registered into this shared translator once ready.
    // Blocking the MCP handshake on LSP init makes slow servers exceed the client's
    // initialize-request timeout (Claude Code: ~60s) -> "Request timed out".
    // `workspace_roots` is fixed for the server's lifetime and cheap to clone,
    // so cache-only handlers (e.g. `get_cached_diagnostics`, `read_resource`)
    // validate a path from their own copy without locking `translator` below.

    let translator = Arc::new(translator);
    // Shared across every session (one per HTTP session, or the sole stdio
    // session): each joins it on its first subscribe -- see
    // `SubscriptionRegistry`.
    let subscription_registry = SubscriptionRegistry::new();

    // Cancels the pump and startup tasks; dropping `serve_with` cancels it too.
    let cancel = CancellationToken::new();
    let _cancel_on_drop = cancel.clone().drop_guard();

    let lsp_init_handle = if applicable_configs.is_empty() {
        warn_protocol_only(if refusals.is_empty() {
            ProtocolOnlyCause::NothingConfigured
        } else {
            ProtocolOnlyCause::AllRefused
        });
        None
    } else {
        info!(
            "Spawning {} LSP server(s) in the background...",
            applicable_configs.len()
        );
        Some(spawn_lsp_servers_background(
            applicable_configs,
            Arc::clone(&translator),
            Arc::clone(&notification_cache),
            subscription_registry.clone(),
            cancel.clone(),
            workspace_roots.clone(),
            max_concurrent_server_starts,
        ))
    };
    let disk_sweep = spawn_disk_sweep(
        &translator,
        &notification_cache,
        &subscription_registry,
        &cancel,
    );

    info!("Starting MCP server with rmcp...");
    let mcp_server = mcp::McplsServer::new(
        Arc::clone(&translator),
        Arc::clone(&notification_cache),
        workspace_roots,
        subscription_registry,
        project_config_status,
        mcp,
    );
    info!("MCPLS server initialized successfully");

    let result = match transport {
        Transport::Stdio => {
            info!("Listening for MCP requests on stdio...");
            run_stdio(mcp_server, shutdown_signal).await
        }
        #[cfg(feature = "transport-http")]
        Transport::Http(cfg) => run_http(mcp_server, cfg, shutdown_signal).await,
    };

    stop_disk_sweep(disk_sweep).await;
    shutdown(&cancel, &translator, lsp_init_handle).await;

    info!("MCPLS server shutting down");
    result
}

/// Why no LSP server is started.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ProtocolOnlyCause {
    /// The configuration has no server applicable to the workspace.
    NothingConfigured,
    /// An untrusted workspace refused every applicable server.
    AllRefused,
}

/// Logs why no LSP server is started.
fn warn_protocol_only(cause: ProtocolOnlyCause) {
    match cause {
        ProtocolOnlyCause::NothingConfigured => {
            warn!("No applicable LSP servers configured — starting in protocol-only mode");
        }
        ProtocolOnlyCause::AllRefused => warn!(
            "The workspace is untrusted and no applicable LSP server was allowed — starting \
             in protocol-only mode; allow servers with `--allow-server <id>`"
        ),
    }
}

#[cfg(test)]
mod tests {
    use std::assert_matches;

    use super::*;
    use crate::config::{
        IndexingReadyTimeoutSecs, LanguageId, PositionEncodings, ServerStartConcurrency,
        TimeoutSecs,
    };

    /// #659: a panic in the planning work reaches the caller instead of
    /// being swallowed by the blocking pool.
    #[tokio::test]
    async fn test_on_blocking_pool_returns_the_value_and_propagates_a_panic() {
        assert_eq!(on_blocking_pool(|| 7).await.unwrap(), 7);

        let panicked =
            crate::util::catch_panic(on_blocking_pool(|| -> u8 { panic!("planning exploded") }))
                .await
                .unwrap_err();
        assert_eq!(panicked.message(), "planning exploded");
    }

    /// #679: the work runs on a blocking-pool thread, not on the caller's.
    #[tokio::test]
    async fn test_on_blocking_pool_runs_off_the_calling_thread() {
        let caller = std::thread::current().id();
        let worker = on_blocking_pool(|| std::thread::current().id())
            .await
            .unwrap();
        assert_ne!(caller, worker);
    }

    // Tests for graceful degradation behavior
    mod graceful_degradation_tests {
        use super::*;
        use crate::config::{DocumentLimit, FilePattern, SearchDepth, ServerCommand, SizeLimit};

        #[tokio::test]
        async fn test_serve_degrades_when_all_servers_fail_to_spawn() {
            use crate::config::{LspServerConfig, ServerStartConcurrency, WorkspaceConfig};

            // A configured server whose command cannot spawn used to make serve()
            // fail synchronously with AllServersFailedToInit.
            // LSP initialization now runs in a background task so the MCP
            // `initialize` handshake is never blocked, which means the spawn
            // failure is handled in the background instead: serve() starts the MCP
            // server in degraded mode (mirroring `test_serve_starts_with_empty_config`)
            // rather than failing fast. Any error it surfaces must therefore be a
            // transport/MCP error from the closed test connection, NOT a fail-fast
            // server-availability error.
            let config = ServerConfig {
                mcp: crate::config::McpConfig::default(),
                workspace: WorkspaceConfig {
                    roots: vec![crate::config::ConfiguredRoot::new("/tmp/test-workspace").unwrap()],
                    position_encodings: PositionEncodings::DEFAULT,
                    language_extensions: vec![],
                    heuristics_max_depth: SearchDepth::DEFAULT,
                    max_documents: DocumentLimit::DEFAULT,
                    max_file_size: SizeLimit::DEFAULT,
                    indexing_ready_timeout_seconds: IndexingReadyTimeoutSecs::DEFAULT,
                    max_concurrent_server_starts: ServerStartConcurrency::DEFAULT,
                },
                lsp_servers: vec![LspServerConfig {
                    language_id: LanguageId::from_static("rust"),
                    command: ServerCommand::from_static("nonexistent-command-that-will-fail-12345")
                        .into(),
                    args: crate::config::ServerArgs::default(),
                    env: crate::config::ServerEnv::default(),
                    file_patterns: vec![FilePattern::from_static("**/*.rs")],
                    initialization_options: None,
                    settings: None,
                    timeout_seconds: TimeoutSecs::new(10).unwrap(),
                    request_timeout_seconds: TimeoutSecs::new(10).unwrap(),
                    heuristics: None,
                    name: None,
                    handles: None,
                    indexing: crate::bridge::IndexingPolicy::Auto,
                }],
                project_config_status: ProjectConfigStatus::NotIgnored,
                workspace_trust: crate::config::WorkspaceTrust::default(),
            };

            // serve() proceeds to run the MCP server and blocks on the stdio
            // transport until EOF; bound it so the test can't hang if stdin stays
            // open (e.g. under multi-threaded `cargo test`, where several serve()
            // tests share the process stdin).
            let outcome =
                tokio::time::timeout(std::time::Duration::from_secs(2), serve(config)).await;

            match outcome {
                // Still serving after the deadline => it did not fail fast. Good.
                Err(_elapsed) => {}
                // Transport closed cleanly. Also fine.
                Ok(Ok(())) => {}
                // It returned an error: it must not be a fail-fast availability error.
                Ok(Err(err)) => assert!(
                    !matches!(err, Error::AllServersFailedToInit { .. }),
                    "serve() must not fail fast now that LSP init is backgrounded; got: {err:?}"
                ),
            }
        }

        /// #674: dropping the `serve_with` future cancels startup, so a server
        /// still initializing is abandoned and its process killed, instead of
        /// lingering until its init timeout.
        #[tokio::test]
        #[cfg(all(unix, feature = "transport-http"))]
        async fn test_dropping_serve_with_abandons_a_server_still_initializing() {
            use crate::config::{LspServerConfig, ServerStartConcurrency, WorkspaceConfig};

            let dir = tempfile::TempDir::new().unwrap();
            let root = dunce::canonicalize(dir.path()).unwrap();
            let pid_file = root.join("pid");
            let script = format!("echo $$ > {}; exec sleep 600", pid_file.display());
            let config = ServerConfig {
                mcp: crate::config::McpConfig::default(),
                workspace: WorkspaceConfig {
                    roots: vec![crate::config::ConfiguredRoot::new(&root).unwrap()],
                    position_encodings: PositionEncodings::DEFAULT,
                    language_extensions: vec![],
                    heuristics_max_depth: SearchDepth::DEFAULT,
                    max_documents: DocumentLimit::DEFAULT,
                    max_file_size: SizeLimit::DEFAULT,
                    indexing_ready_timeout_seconds: IndexingReadyTimeoutSecs::DEFAULT,
                    max_concurrent_server_starts: ServerStartConcurrency::DEFAULT,
                },
                lsp_servers: vec![LspServerConfig {
                    language_id: LanguageId::from_static("rust"),
                    command: ServerCommand::from_static("sh").into(),
                    args: crate::config::ServerArgs::new(["-c".to_owned(), script]).unwrap(),
                    env: crate::config::ServerEnv::default(),
                    file_patterns: vec![FilePattern::from_static("**/*.rs")],
                    initialization_options: None,
                    settings: None,
                    timeout_seconds: TimeoutSecs::new(30).unwrap(),
                    request_timeout_seconds: TimeoutSecs::new(30).unwrap(),
                    heuristics: None,
                    name: None,
                    handles: None,
                    indexing: crate::bridge::IndexingPolicy::Auto,
                }],
                project_config_status: ProjectConfigStatus::NotIgnored,
                workspace_trust: crate::config::WorkspaceTrust::default(),
            };
            let http = crate::transport::HttpConfig::new("127.0.0.1:0".parse().unwrap());
            let serving = tokio::spawn(serve_with(config, Transport::Http(http)));

            let pid = tokio::time::timeout(std::time::Duration::from_secs(15), async {
                loop {
                    if let Ok(text) = std::fs::read_to_string(&pid_file)
                        && let Some(pid) = text.trim().parse::<u32>().ok()
                    {
                        break pid;
                    }
                    tokio::time::sleep(std::time::Duration::from_millis(20)).await;
                }
            })
            .await
            .expect("the server was never spawned");

            serving.abort();
            drop(serving.await);

            let alive = |pid: u32| {
                std::process::Command::new("kill")
                    .args(["-0", &pid.to_string()])
                    .stderr(std::process::Stdio::null())
                    .status()
                    .is_ok_and(|status| status.success())
            };
            tokio::time::timeout(std::time::Duration::from_secs(10), async {
                while alive(pid) {
                    tokio::time::sleep(std::time::Duration::from_millis(50)).await;
                }
            })
            .await
            .expect("the abandoned server process is still running");
        }

        #[tokio::test]
        async fn test_serve_starts_with_empty_config() {
            use crate::config::WorkspaceConfig;

            // Server starts in protocol-only mode when no LSP servers are configured.
            // serve() blocks until the MCP transport closes, so it will error with a
            // connection/transport error — not AllServersFailedToInit.
            let config = ServerConfig {
                mcp: crate::config::McpConfig::default(),
                workspace: WorkspaceConfig {
                    roots: vec![crate::config::ConfiguredRoot::new("/tmp/test-workspace").unwrap()],
                    position_encodings: PositionEncodings::DEFAULT,
                    language_extensions: vec![],
                    heuristics_max_depth: SearchDepth::DEFAULT,
                    max_documents: DocumentLimit::DEFAULT,
                    max_file_size: SizeLimit::DEFAULT,
                    indexing_ready_timeout_seconds: IndexingReadyTimeoutSecs::DEFAULT,
                    max_concurrent_server_starts: ServerStartConcurrency::DEFAULT,
                },
                lsp_servers: vec![],
                project_config_status: ProjectConfigStatus::NotIgnored,
                workspace_trust: crate::config::WorkspaceTrust::default(),
            };

            let result = serve(config).await;

            // serve() may succeed or fail with a transport error, but must NOT
            // return AllServersFailedToInit when the config simply has no servers.
            if let Err(ref err) = result {
                assert!(
                    !matches!(err, Error::AllServersFailedToInit { .. }),
                    "serve() must not return AllServersFailedToInit for empty lsp_servers config"
                );
            }
        }

        /// #348 case 1 (tester-flagged coverage gap): proves `serve_with`
        /// itself skips `current_dir()` for an all-absolute
        /// `workspace.roots`, not just that `WorkspaceRoots::from_configured_with`
        /// tolerates an unread cwd when called directly (see
        /// `test_from_configured_ignores_cwd_when_all_absolute` in
        /// `bridge::workspace_roots`, which never exercises `serve_with`'s
        /// wiring). Mutates the process cwd (chdir into a directory,
        /// then remove it -- `current_dir()` reliably fails afterward on
        /// Unix), so it uses the crate-shared `test_support::CwdGuard` --
        /// the same lock/restore-on-drop `config::tests` uses -- rather than
        /// a one-off guard, since both modules' tests mutate cwd and compile
        /// into one binary. Unix-only since removing a directory that is
        /// still a live process's cwd is a Windows-specific error case, not
        /// the same reproducible `current_dir()` failure.
        #[tokio::test]
        #[cfg(unix)]
        async fn test_serve_with_all_absolute_roots_skips_current_dir() {
            use crate::config::WorkspaceConfig;
            use crate::test_support::CwdGuard;

            // Kept alive for the whole test so the configured workspace root
            // stays a valid, existing absolute directory distinct from the
            // cwd this test is about to remove.
            let workspace_root_dir = tempfile::TempDir::new().unwrap();
            let workspace_root = dunce::canonicalize(workspace_root_dir.path()).unwrap();

            let doomed_cwd = tempfile::TempDir::new().unwrap();
            let _guard = CwdGuard::enter(doomed_cwd.path());
            doomed_cwd.close().unwrap();

            let config = ServerConfig {
                mcp: crate::config::McpConfig::default(),
                workspace: WorkspaceConfig {
                    roots: vec![crate::config::ConfiguredRoot::new(workspace_root).unwrap()],
                    position_encodings: PositionEncodings::DEFAULT,
                    language_extensions: vec![],
                    heuristics_max_depth: SearchDepth::DEFAULT,
                    max_documents: DocumentLimit::DEFAULT,
                    max_file_size: SizeLimit::DEFAULT,
                    indexing_ready_timeout_seconds: IndexingReadyTimeoutSecs::DEFAULT,
                    max_concurrent_server_starts: ServerStartConcurrency::DEFAULT,
                },
                lsp_servers: vec![],
                project_config_status: ProjectConfigStatus::NotIgnored,
                workspace_trust: crate::config::WorkspaceTrust::default(),
            };

            // serve() with no LSP servers configured blocks on the stdio
            // transport, same as `test_serve_starts_with_empty_config`;
            // bound it so the test can't hang.
            let outcome =
                tokio::time::timeout(std::time::Duration::from_secs(2), serve(config)).await;

            match outcome {
                // Still serving after the deadline => it did not fail fast. Good.
                Err(_elapsed) => {}
                // Transport closed cleanly. Also fine.
                Ok(Ok(())) => {}
                // It returned an error: it must not be the `current_dir()`
                // failure this test set up (`ErrorKind::NotFound` from the
                // removed cwd). Narrowed to that specific `io::ErrorKind`
                // rather than any `Error::Io`, since the latter would also
                // match an unrelated IO error from the stdio transport
                // within the timeout window.
                Ok(Err(err)) => assert!(
                    !matches!(&err, Error::Io(e) if e.kind() == std::io::ErrorKind::NotFound),
                    "serve() must not need a working process cwd for an all-absolute \
                     workspace.roots; got: {err:?}"
                ),
            }
        }

        /// #282: a `ServerConfig` built programmatically (not via `load`/
        /// `load_from`, which already run `validate()`) previously skipped
        /// validation entirely, so `serve`/`serve_with` never rejected it —
        /// misconfiguration only surfaced later as silent accessor-level
        /// clamping. `serve` delegates straight to `serve_with`, so
        /// exercising it here also covers `serve_with`'s own `validate()`
        /// call. `validate()` runs before any LSP spawn or transport setup,
        /// so this returns immediately without needing a timeout guard.
        #[tokio::test]
        async fn test_serve_rejects_invalid_caller_supplied_config() {
            use crate::config::{LspServerConfig, ServerStartConcurrency, WorkspaceConfig};

            let config = ServerConfig {
                mcp: crate::config::McpConfig::default(),
                workspace: WorkspaceConfig {
                    roots: vec![],
                    position_encodings: PositionEncodings::DEFAULT,
                    language_extensions: vec![],
                    heuristics_max_depth: SearchDepth::DEFAULT,
                    max_documents: DocumentLimit::DEFAULT,
                    max_file_size: SizeLimit::DEFAULT,
                    indexing_ready_timeout_seconds: IndexingReadyTimeoutSecs::DEFAULT,
                    max_concurrent_server_starts: ServerStartConcurrency::DEFAULT,
                },
                lsp_servers: vec![LspServerConfig {
                    language_id: LanguageId::from_static("rust"),
                    command: ServerCommand::from_static("rust-analyzer").into(),
                    args: crate::config::ServerArgs::default(),
                    env: crate::config::ServerEnv::default(),
                    file_patterns: vec![FilePattern::from_static("**/*.rs")],
                    initialization_options: None,
                    settings: None,
                    timeout_seconds: TimeoutSecs::new(10).unwrap(),
                    request_timeout_seconds: TimeoutSecs::new(10).unwrap(),
                    heuristics: None,
                    name: None,
                    handles: None,
                    indexing: crate::bridge::IndexingPolicy::Auto,
                }],
                project_config_status: ProjectConfigStatus::NotIgnored,
                workspace_trust: crate::config::WorkspaceTrust::untrusted([
                    crate::config::ServerId::from_static("not-configured"),
                ]),
            };

            // `validate()` runs before any spawn/transport work and should
            // return immediately; bound it anyway so a regression that lets
            // an invalid config reach the stdio transport fails fast with a
            // clear timeout instead of hanging nextest for the default 120s
            // (mirroring the guard on `test_serve_degrades_when_all_servers_fail_to_spawn`).
            let outcome =
                tokio::time::timeout(std::time::Duration::from_secs(2), serve(config)).await;

            match outcome {
                Err(elapsed) => panic!(
                    "serve() must reject the invalid config immediately, not hang until \
                     timeout: {elapsed}"
                ),
                Ok(result) => assert_matches!(
                    result,
                    Err(Error::Config(_)),
                    "serve() must reject a caller-supplied config that allows an unconfigured server \
                     via Error::Config, matching the load_from path; got: {result:?}"
                ),
            }
        }
    }
}