local-develop-server 0.11.0

Unified MCP server for the coding pipeline — consolidates git / recipe / sandbox tooling into one process with shared session state
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
//! End-to-end MCP wire test: spawns the actual `lds` binary as a
//! subprocess, talks to it over stdio via rmcp, and exercises a
//! representative slice of tools to confirm the protocol surface.
//!
//! These tests run cargo's debug binary; `cargo build` is implied.

use std::path::Path;
use std::process::Command as StdCommand;

use rmcp::{
    ServiceError, ServiceExt, model::CallToolRequestParams, model::ErrorCode,
    transport::TokioChildProcess,
};
use serde_json::{Value, json};
use tokio::process::Command;

fn server_bin() -> String {
    std::env::var("CARGO_BIN_EXE_lds")
        .unwrap_or_else(|_| format!("{}/target/debug/lds", env!("CARGO_MANIFEST_DIR")))
}

async fn connect() -> rmcp::service::RunningService<rmcp::RoleClient, ()> {
    let cmd = Command::new(server_bin());
    let transport = TokioChildProcess::new(cmd).expect("failed to spawn lds server");
    ().serve(transport)
        .await
        .expect("failed to initialize MCP client")
}

/// Spawn the lds server with `dir` as its working directory.
///
/// Use this variant when the test needs to control whether auto-start fires.
/// A dir that contains `.git` or `justfile` will trigger auto-start; a plain
/// tempdir will not (crux §3 — must distinguish the two cases).
async fn connect_in(dir: &std::path::Path) -> rmcp::service::RunningService<rmcp::RoleClient, ()> {
    let mut cmd = Command::new(server_bin());
    cmd.current_dir(dir);
    let transport = TokioChildProcess::new(cmd).expect("failed to spawn lds server");
    ().serve(transport)
        .await
        .expect("failed to initialize MCP client")
}

fn call_params(name: &str, args: Value) -> CallToolRequestParams {
    let req = CallToolRequestParams::new(name.to_string());
    match args {
        Value::Object(map) => req.with_arguments(map),
        _ => req,
    }
}

fn extract_text(result: &rmcp::model::CallToolResult) -> String {
    result
        .content
        .iter()
        .filter_map(|c| match &c.raw {
            rmcp::model::RawContent::Text(t) => Some(t.text.as_str()),
            _ => None,
        })
        .collect::<Vec<_>>()
        .join("\n")
}

struct TempRepo {
    dir: tempfile::TempDir,
}

impl TempRepo {
    fn new() -> Self {
        let dir = tempfile::tempdir().expect("tempdir");
        Self::run_git(dir.path(), &["init", "-b", "main"]);
        Self::run_git(dir.path(), &["config", "user.email", "test@test.com"]);
        Self::run_git(dir.path(), &["config", "user.name", "Test"]);
        std::fs::write(dir.path().join("README.md"), "# test\n").unwrap();
        Self::run_git(dir.path(), &["add", "."]);
        Self::run_git(dir.path(), &["commit", "-m", "initial"]);
        std::fs::create_dir_all(dir.path().join(".worktrees")).unwrap();
        Self { dir }
    }

    fn run_git(dir: &Path, args: &[&str]) {
        StdCommand::new("git")
            .args(args)
            .current_dir(dir)
            .output()
            .expect("git invocation");
    }

    fn path_str(&self) -> &str {
        self.dir.path().to_str().unwrap()
    }
}

#[tokio::test]
async fn list_tools_includes_static_surface() {
    let client = connect().await;
    let tools = client.peer().list_all_tools().await.unwrap();
    let names: Vec<&str> = tools.iter().map(|t| t.name.as_ref()).collect();

    // Spot-check a representative tool from each module so the wire
    // surface stays in lock-step with what the agents call.
    for expected in [
        "session_start",
        "session_info",
        "git_status",
        "git_log",
        "git_diff",
        "git_commit",
        "git_worktree_add",
        "git_worktree_remove",
        "git_worktree_list",
        "git_merge",
        "git_branch_delete",
        "recipe_list",
        "recipe_run",
        "recipe_logs",
        "sandbox_write",
        "sandbox_read",
        "sandbox_edit",
        "sandbox_append",
        "sandbox_head",
        "sandbox_tail",
        "sandbox_rollback",
        "sandbox_history",
        "sandbox_python",
        "sandbox_python_file",
        "gh_run_view",
        "gh_run_log_failed",
        "mcp_call",
        "mcp_route_list",
        "mcp_route_register",
        "mcp_route_remove",
    ] {
        assert!(
            names.contains(&expected),
            "tool {expected:?} missing from list_tools; got {names:?}"
        );
    }

    client.cancel().await.unwrap();
}

#[tokio::test]
async fn session_start_returns_id() {
    let repo = TempRepo::new();
    let client = connect().await;

    let result = client
        .peer()
        .call_tool(call_params(
            "session_start",
            json!({ "root": repo.path_str() }),
        ))
        .await
        .unwrap();

    let text = extract_text(&result);
    assert!(text.contains("session_id"));
    assert!(text.contains(repo.path_str()));
    assert!(text.contains("\"is_default\": true"));

    client.cancel().await.unwrap();
}

/// session_start accepts an optional `alias` and the alias round-trips through
/// `session_describe(key=<alias>)`. Guards against regressing the field back to
/// the hard-coded `None` that made the parameter useless in v0.5.0.
#[tokio::test]
async fn session_start_alias_round_trip() {
    let repo = TempRepo::new();
    let client = connect().await;

    let start = client
        .peer()
        .call_tool(call_params(
            "session_start",
            json!({ "root": repo.path_str(), "alias": "main-worker" }),
        ))
        .await
        .unwrap();
    let start_text = extract_text(&start);
    assert!(
        start_text.contains("\"alias\": \"main-worker\""),
        "session_start must echo the alias, got: {start_text}"
    );

    let describe = client
        .peer()
        .call_tool(call_params(
            "session_describe",
            json!({ "key": "main-worker" }),
        ))
        .await
        .unwrap();
    let describe_text = extract_text(&describe);
    assert!(
        describe_text.contains("\"alias\": \"main-worker\""),
        "session_describe(key=alias) must resolve, got: {describe_text}"
    );
    assert!(describe_text.contains(repo.path_str()));

    client.cancel().await.unwrap();
}

#[tokio::test]
async fn git_status_round_trip() {
    let repo = TempRepo::new();
    let client = connect().await;

    client
        .peer()
        .call_tool(call_params(
            "session_start",
            json!({ "root": repo.path_str() }),
        ))
        .await
        .unwrap();

    // --- clean phase ---
    // git_status now returns typed JSON. The freshly-initialised repo only
    // has the committed README.md plus the `.worktrees/` dir, so we expect
    // staged + unstaged to be empty. (untracked may include `.worktrees`,
    // which is benign and explicitly allowed.)
    let result_clean = client
        .peer()
        .call_tool(call_params("git_status", json!({})))
        .await
        .unwrap();
    let text_clean = extract_text(&result_clean);
    let json_clean: Value =
        serde_json::from_str(&text_clean).expect("git_status clean: payload must be JSON");
    assert_eq!(json_clean["staged"], json!([]), "got: {text_clean}");
    assert_eq!(json_clean["unstaged"], json!([]), "got: {text_clean}");
    assert_eq!(json_clean["branch"], json!("main"), "got: {text_clean}");

    // --- dirty phase ---
    // An untracked file is now reported under `untracked`, not as a free-
    // form debug-format token. The path must appear verbatim in that array.
    std::fs::write(repo.dir.path().join("dirty.txt"), "content\n").unwrap();
    let result_dirty = client
        .peer()
        .call_tool(call_params("git_status", json!({})))
        .await
        .unwrap();
    let text_dirty = extract_text(&result_dirty);
    let json_dirty: Value =
        serde_json::from_str(&text_dirty).expect("git_status dirty: payload must be JSON");
    let untracked = json_dirty["untracked"]
        .as_array()
        .expect("untracked must be an array");
    assert!(
        untracked.iter().any(|v| v.as_str() == Some("dirty.txt")),
        "expected dirty.txt in untracked, got: {text_dirty}"
    );

    client.cancel().await.unwrap();
}

#[tokio::test]
async fn sandbox_write_read_round_trip() {
    let repo = TempRepo::new();
    let client = connect().await;

    client
        .peer()
        .call_tool(call_params(
            "session_start",
            json!({ "root": repo.path_str() }),
        ))
        .await
        .unwrap();

    let write_result = client
        .peer()
        .call_tool(call_params(
            "sandbox_write",
            json!({ "path": "note.txt", "content": "from e2e\nsecond line\n" }),
        ))
        .await
        .unwrap();
    let write_text = extract_text(&write_result);
    assert!(write_text.contains("\"path\": \"note.txt\""));
    assert!(write_text.contains("bytes_written"));

    let read_result = client
        .peer()
        .call_tool(call_params("sandbox_read", json!({ "path": "note.txt" })))
        .await
        .unwrap();
    let read_text = extract_text(&read_result);
    assert!(read_text.contains("from e2e"));
    assert!(read_text.contains("second line"));

    client.cancel().await.unwrap();
}

#[tokio::test]
async fn calling_tool_without_session_errors() {
    // Spawn the server in a plain tempdir that has neither `.git` nor
    // `justfile`, so auto-start does NOT fire. Calling git_status without
    // session_start must return an error (crux §3: non-ProjectRoot CWD path).
    let tmpdir = tempfile::tempdir().expect("tempdir");
    let client = connect_in(tmpdir.path()).await;
    let outcome = client
        .peer()
        .call_tool(call_params("git_status", json!({})))
        .await;
    assert!(outcome.is_err(), "expected error, got {outcome:?}");

    client.cancel().await.unwrap();
}

#[tokio::test]
async fn calling_tool_auto_starts_in_project_root() {
    // Spawn the server with a TempRepo (contains `.git`) as CWD.
    // Auto-start should fire and git_status must succeed without an explicit
    // session_start call (crux §3: ProjectRoot CWD path).
    let repo = TempRepo::new();
    let client = connect_in(repo.dir.path()).await;
    let outcome = client
        .peer()
        .call_tool(call_params("git_status", json!({})))
        .await;
    assert!(
        outcome.is_ok(),
        "expected auto-start to succeed, got {outcome:?}"
    );

    client.cancel().await.unwrap();
}

#[tokio::test]
async fn no_session_error_has_internal_error_code() {
    // Regression: all no-session paths must return the unified error code
    // -32603 (McpError::INTERNAL_ERROR). Previously each handler inlined a
    // separate McpError::internal_error("no session", None) call — this test
    // pins the code so any divergence is caught at the E2E boundary.
    //
    // Use a non-ProjectRoot tmpdir so auto-start does NOT fire (crux §3).
    let tmpdir = tempfile::tempdir().expect("tempdir");
    let client = connect_in(tmpdir.path()).await;
    let outcome = client
        .peer()
        .call_tool(call_params("git_status", json!({})))
        .await;

    match outcome {
        Err(ServiceError::McpError(ref err_data)) => {
            assert_eq!(
                err_data.code,
                ErrorCode::INTERNAL_ERROR,
                "no-session error must use code -32603 (INTERNAL_ERROR), got {:?}",
                err_data.code
            );
        }
        Err(other) => panic!("expected McpError(-32603), got ServiceError variant: {other:?}"),
        Ok(_) => panic!("expected error for no-session call, got Ok"),
    }

    client.cancel().await.unwrap();
}

#[tokio::test]
async fn mcp_call_self_loop_rejected() {
    // Auto-start via a real TempRepo so `inner.router` is actually populated
    // (an empty McpRouter) — this exercises the real self-loop guard inside
    // `McpRouter::call_uri`, not merely the "no session" guard.
    let repo = TempRepo::new();
    let client = connect_in(repo.dir.path()).await;

    let outcome = client
        .peer()
        .call_tool(call_params(
            "mcp_call",
            json!({ "uri": "lds://git_status", "args": {} }),
        ))
        .await;

    match outcome {
        Err(ServiceError::McpError(ref err_data)) => {
            assert!(
                err_data.message.contains("self-loop"),
                "expected self-loop error message, got: {}",
                err_data.message
            );
        }
        Ok(result) => {
            let text = extract_text(&result);
            assert!(
                result.is_error == Some(true) && text.contains("self-loop"),
                "expected self-loop error, got Ok: {text}"
            );
        }
        Err(other) => panic!("unexpected error variant: {other:?}"),
    }

    client.cancel().await.unwrap();
}

#[tokio::test]
async fn mcp_call_proxies_to_child_lds_server() {
    // Parent A: real ProjectRoot so auto-start populates `inner.router`.
    let repo_a = TempRepo::new();
    let client_a = connect_in(repo_a.dir.path()).await;

    // Child B: a separate ProjectRoot the parent will proxy into. Its `lds`
    // subprocess is spawned by `RouteClient` with an unrelated CWD (it does
    // not set `current_dir`), so child B's session must be started explicitly
    // via a proxied `session_start` call rather than relying on auto-start.
    let repo_b = TempRepo::new();

    let register_result = client_a
        .peer()
        .call_tool(call_params(
            "mcp_route_register",
            json!({ "name": "child_lds", "command": server_bin() }),
        ))
        .await
        .unwrap();
    assert!(
        register_result.is_error != Some(true),
        "mcp_route_register should succeed, got: {:?}",
        extract_text(&register_result)
    );

    let start_result = client_a
        .peer()
        .call_tool(call_params(
            "mcp_call",
            json!({
                "uri": "child_lds://session_start",
                "args": { "root": repo_b.path_str() },
            }),
        ))
        .await
        .unwrap();
    let start_text = extract_text(&start_result);
    assert!(
        start_result.is_error != Some(true) && start_text.contains("session_id"),
        "proxied session_start on child_lds should succeed, got: {start_text}"
    );

    let status_result = client_a
        .peer()
        .call_tool(call_params(
            "mcp_call",
            json!({ "uri": "child_lds://git_status", "args": {} }),
        ))
        .await
        .unwrap();
    let status_text = extract_text(&status_result);
    assert!(
        status_result.is_error != Some(true),
        "proxied git_status on child_lds should succeed, got: {status_text}"
    );
    let status_json: Value = serde_json::from_str(&status_text)
        .expect("proxied git_status payload must be transparent JSON");
    assert_eq!(status_json["branch"], json!("main"), "got: {status_text}");

    client_a.cancel().await.unwrap();
}

#[tokio::test]
async fn session_start_recovers_after_previous_root_deleted() {
    // Regression guard for K-239: after the session root has been deleted,
    // `session_start` must succeed on a new root even though
    // `try_plugin_call` (via RecipeModule::list_plugins / check_session_root)
    // would have rejected the call on the dead session before this fix.
    //
    // Step 1: create tempdir A with a minimal justfile.
    let dir_a = tempfile::tempdir().expect("tempdir A");
    std::fs::write(dir_a.path().join("justfile"), "default:\n\t@echo ok\n").unwrap();

    // Step 2: use connect() (non-ProjectRoot spawn) so auto-start does NOT
    // fire — this isolates the session_start path from the auto-start gate.
    let client = connect().await;

    // Step 3: session_start with root = A — must succeed.
    let result = client
        .peer()
        .call_tool(call_params(
            "session_start",
            json!({ "root": dir_a.path().to_str().unwrap() }),
        ))
        .await
        .unwrap();
    let text = extract_text(&result);
    assert!(
        text.contains("session_id"),
        "step 3: session_start(A) should succeed, got: {text}"
    );

    // Step 4: recipe_list — sanity check that the session is functional.
    let result = client
        .peer()
        .call_tool(call_params("recipe_list", json!({})))
        .await
        .unwrap();
    assert!(
        result.is_error != Some(true),
        "step 4: recipe_list after session_start(A) should succeed, got: {:?}",
        extract_text(&result)
    );

    // Step 5: delete dir A — the session root is now gone.
    std::fs::remove_dir_all(dir_a.path()).unwrap();

    // Step 6: recipe_list must fail with SessionRootGone.
    let outcome = client
        .peer()
        .call_tool(call_params("recipe_list", json!({})))
        .await;
    match outcome {
        Err(ServiceError::McpError(ref err_data)) => {
            assert!(
                err_data
                    .message
                    .contains("session root path no longer exists"),
                "step 6: expected 'session root path no longer exists' in error message, got: {}",
                err_data.message
            );
        }
        Ok(result) => {
            // Some MCP implementations surface errors as Ok(isError:true).
            let text = extract_text(&result);
            assert!(
                result.is_error == Some(true)
                    && text.contains("session root path no longer exists"),
                "step 6: expected SessionRootGone error, got Ok: {text}"
            );
        }
        Err(other) => panic!("step 6: unexpected error variant: {other:?}"),
    }

    // Step 7: create tempdir B with a minimal justfile.
    let dir_b = tempfile::tempdir().expect("tempdir B");
    std::fs::write(dir_b.path().join("justfile"), "default:\n\t@echo ok\n").unwrap();

    // Step 8: session_start with root = B — this is the core assertion of the fix.
    // Before the fix, try_plugin_call would hit check_session_root on the dead
    // session A and reject session_start entirely.
    let result = client
        .peer()
        .call_tool(call_params(
            "session_start",
            json!({ "root": dir_b.path().to_str().unwrap() }),
        ))
        .await
        .unwrap();
    let text = extract_text(&result);
    assert!(
        text.contains("session_id"),
        "step 8: session_start(B) must succeed after root A was deleted, got: {text}"
    );

    // Step 9: recipe_list with B — confirm the new session is fully functional.
    let result = client
        .peer()
        .call_tool(call_params("recipe_list", json!({})))
        .await
        .unwrap();
    assert!(
        result.is_error != Some(true),
        "step 9: recipe_list after session_start(B) should succeed, got: {:?}",
        extract_text(&result)
    );

    client.cancel().await.unwrap();
}