lean-ctx-server 3.12.12

The LeanCTX MCP server and its tools on top of LeanCTX | OSS.
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
// SPDX-License-Identifier: Apache-2.0
//! #2262: Claude Code subagents share one MCP connection. A `cwd` argument or a
//! `cd` in one agent's ctx_shell call must not change where the next call runs,
//! nor what a relative path in ctx_read or ctx_patch names.

use rmcp::model::CallToolResult;
use serde_json::{Value, json};

use crate::tools::LeanCtxServer;

async fn call(server: &LeanCtxServer, tool: &str, args: Value) -> CallToolResult {
    super::dispatch_and_post_process(
        server,
        tool,
        args.as_object(),
        false,
        lean_ctx::core::config::Config::load_arc(),
        false,
        None,
        None,
        "shell-cwd-2262".to_string(),
        None,
    )
    .await
    .expect("a tool result, not a transport error")
}

fn text(result: &CallToolResult) -> String {
    result
        .content
        .iter()
        .filter_map(|block| block.as_text().map(|text| text.text.as_str()))
        .collect::<Vec<_>>()
        .join("\n")
}

/// A project root holding a Claude Code worktree (own `.git` file) nested at
/// `.claude/worktrees/wt`, with `FILE.txt` in both trees and a `sub` directory.
struct Fixture {
    _dir: tempfile::TempDir,
    root: std::path::PathBuf,
    wt: std::path::PathBuf,
}

fn fixture() -> Fixture {
    let dir = tempfile::tempdir().unwrap();
    let root = lean_ctx::core::pathutil::safe_canonicalize_or_self(dir.path());
    std::fs::create_dir_all(root.join(".git")).unwrap();
    std::fs::create_dir_all(root.join("sub")).unwrap();
    std::fs::write(root.join("FILE.txt"), "ROOT_COPY_2262\n").unwrap();
    let wt = root.join(".claude/worktrees/wt");
    std::fs::create_dir_all(&wt).unwrap();
    std::fs::write(wt.join(".git"), "gitdir: ../../../.git/worktrees/wt\n").unwrap();
    std::fs::write(wt.join("FILE.txt"), "WORKTREE_COPY_2262\n").unwrap();
    Fixture {
        _dir: dir,
        root,
        wt,
    }
}

fn server_for(fixture: &Fixture) -> LeanCtxServer {
    LeanCtxServer::new_with_project_root(Some(&fixture.root.to_string_lossy()))
}

/// The directory `pwd` printed, as one whole output line.
fn ran_in(result: &CallToolResult, dir: &std::path::Path) -> bool {
    let want = dir.to_string_lossy();
    text(result).lines().any(|line| line.trim() == want)
}

#[tokio::test(flavor = "multi_thread")]
async fn an_explicit_cwd_applies_to_its_own_call_only() {
    let _data = lean_ctx::core::data_dir::isolated_data_dir();
    let f = fixture();
    let server = server_for(&f);
    let shell_cwd_before = server.session.read().await.shell_cwd.clone();

    let first = call(
        &server,
        "ctx_shell",
        json!({"command": "pwd", "cwd": f.wt.to_string_lossy()}),
    )
    .await;
    assert!(ran_in(&first, &f.wt), "{}", text(&first));

    let second = call(&server, "ctx_shell", json!({"command": "pwd"})).await;
    assert!(ran_in(&second, &f.root), "{}", text(&second));
    assert_eq!(server.session.read().await.shell_cwd, shell_cwd_before);
}

#[tokio::test(flavor = "multi_thread")]
async fn a_cd_inside_a_command_applies_to_that_command_only() {
    let _data = lean_ctx::core::data_dir::isolated_data_dir();
    let f = fixture();
    let server = server_for(&f);

    let first = call(&server, "ctx_shell", json!({"command": "cd sub && pwd"})).await;
    assert!(ran_in(&first, &f.root.join("sub")), "{}", text(&first));

    let second = call(&server, "ctx_shell", json!({"command": "pwd"})).await;
    assert!(ran_in(&second, &f.root), "{}", text(&second));

    // Through the same dispatch, a relative read after the `cd` still names
    // the project root, not `sub/`.
    let read = call(
        &server,
        "ctx_read",
        json!({"path": "FILE.txt", "mode": "full"}),
    )
    .await;
    assert!(text(&read).contains("ROOT_COPY_2262"), "{}", text(&read));
}

/// The batch forms resolve like a single call: `ctx_read` `paths[]` and
/// `ctx_patch` `ops[]` with relative paths name the project root after a
/// worktree `cwd`, never the worktree copy.
#[tokio::test(flavor = "multi_thread")]
async fn batch_read_and_patch_stay_in_the_project_root_after_a_worktree_cwd() {
    let _data = lean_ctx::core::data_dir::isolated_data_dir();
    let f = fixture();
    let server = server_for(&f);
    std::fs::write(f.root.join("SECOND.txt"), "ROOT_SECOND_2262\n").unwrap();
    std::fs::write(f.wt.join("SECOND.txt"), "WORKTREE_SECOND_2262\n").unwrap();
    call(
        &server,
        "ctx_shell",
        json!({"command": "pwd", "cwd": f.wt.to_string_lossy()}),
    )
    .await;

    let read = call(
        &server,
        "ctx_read",
        json!({"paths": ["FILE.txt", "SECOND.txt"], "mode": "full"}),
    )
    .await;
    for want in ["ROOT_COPY_2262", "ROOT_SECOND_2262"] {
        assert!(text(&read).contains(want), "{want}: {}", text(&read));
    }
    for unwanted in ["WORKTREE_COPY_2262", "WORKTREE_SECOND_2262"] {
        assert!(
            !text(&read).contains(unwanted),
            "{unwanted}: {}",
            text(&read)
        );
    }

    let patch = call(
        &server,
        "ctx_patch",
        json!({"ops": [
            {"path": "FILE.txt", "op": "replace_unique",
             "old_text": "ROOT_COPY_2262", "new_text": "ROOT_PATCHED_2262"},
            {"path": "SECOND.txt", "op": "replace_unique",
             "old_text": "ROOT_SECOND_2262", "new_text": "ROOT_SECOND_PATCHED_2262"}
        ]}),
    )
    .await;
    assert_ne!(patch.is_error, Some(true), "{}", text(&patch));
    assert_eq!(
        std::fs::read_to_string(f.root.join("FILE.txt")).unwrap(),
        "ROOT_PATCHED_2262\n"
    );
    assert_eq!(
        std::fs::read_to_string(f.root.join("SECOND.txt")).unwrap(),
        "ROOT_SECOND_PATCHED_2262\n"
    );
    assert_eq!(
        std::fs::read_to_string(f.wt.join("FILE.txt")).unwrap(),
        "WORKTREE_COPY_2262\n"
    );
    assert_eq!(
        std::fs::read_to_string(f.wt.join("SECOND.txt")).unwrap(),
        "WORKTREE_SECOND_2262\n"
    );
}

#[tokio::test(flavor = "multi_thread")]
async fn relative_read_and_patch_stay_in_the_project_root_after_a_worktree_cwd() {
    let _data = lean_ctx::core::data_dir::isolated_data_dir();
    let f = fixture();
    let server = server_for(&f);
    call(
        &server,
        "ctx_shell",
        json!({"command": "pwd", "cwd": f.wt.to_string_lossy()}),
    )
    .await;

    let read = call(
        &server,
        "ctx_read",
        json!({"path": "FILE.txt", "mode": "full"}),
    )
    .await;
    assert!(text(&read).contains("ROOT_COPY_2262"), "{}", text(&read));
    assert!(
        !text(&read).contains("WORKTREE_COPY_2262"),
        "{}",
        text(&read)
    );

    let patch = call(
        &server,
        "ctx_patch",
        json!({"path": "FILE.txt", "op": "replace_unique",
               "old_text": "ROOT_COPY_2262", "new_text": "ROOT_PATCHED_2262"}),
    )
    .await;
    assert_ne!(patch.is_error, Some(true), "{}", text(&patch));
    assert_eq!(
        std::fs::read_to_string(f.root.join("FILE.txt")).unwrap(),
        "ROOT_PATCHED_2262\n"
    );
    assert_eq!(
        std::fs::read_to_string(f.wt.join("FILE.txt")).unwrap(),
        "WORKTREE_COPY_2262\n"
    );
}

/// The #2262 repro table: after `cwd=<worktree>`, every way of naming a file
/// reaches the same file in ctx_read and ctx_patch — none is doubled.
#[tokio::test(flavor = "multi_thread")]
async fn read_and_patch_agree_on_every_path_of_the_repro_table() {
    let _data = lean_ctx::core::data_dir::isolated_data_dir();
    let f = fixture();
    let server = server_for(&f);
    call(
        &server,
        "ctx_shell",
        json!({"command": "pwd", "cwd": f.wt.to_string_lossy()}),
    )
    .await;

    // One file per row, so no row reads a file an earlier row patched.
    let wt_abs = |name: &str| f.wt.join(name).to_string_lossy().to_string();
    let root_abs = |name: &str| f.root.join(name).to_string_lossy().to_string();
    let table = [
        (".claude/worktrees/wt/A.txt".to_string(), wt_abs("A.txt")),
        (wt_abs("B.txt"), wt_abs("B.txt")),
        ("C.txt".to_string(), root_abs("C.txt")),
        (root_abs("D.txt"), root_abs("D.txt")),
    ];
    for (path, file) in &table {
        std::fs::write(file, "MARKER_2262\n").unwrap();
        let read = call(&server, "ctx_read", json!({"path": path, "mode": "full"})).await;
        assert!(
            text(&read).contains("MARKER_2262"),
            "{path}: {}",
            text(&read)
        );
        assert!(
            !text(&read).contains("does not exist"),
            "{path}: {}",
            text(&read)
        );

        let patch = call(
            &server,
            "ctx_patch",
            json!({"path": path, "op": "replace_unique",
                   "old_text": "MARKER_2262", "new_text": "PATCHED_2262"}),
        )
        .await;
        assert_ne!(patch.is_error, Some(true), "{path}: {}", text(&patch));
        assert_eq!(
            std::fs::read_to_string(file).unwrap(),
            "PATCHED_2262\n",
            "{path}"
        );
    }
}

/// Two subagents on one connection, each with its own `cwd`, then a call
/// without one: it runs in the project root, not in either earlier cwd.
#[tokio::test(flavor = "multi_thread")]
async fn two_agents_with_different_cwds_leave_the_default_in_the_project_root() {
    let _data = lean_ctx::core::data_dir::isolated_data_dir();
    let f = fixture();
    let server = server_for(&f);
    let sub = f.root.join("sub");

    let a = call(
        &server,
        "ctx_shell",
        json!({"command": "pwd", "cwd": f.wt.to_string_lossy()}),
    )
    .await;
    assert!(ran_in(&a, &f.wt), "{}", text(&a));
    let b = call(
        &server,
        "ctx_shell",
        json!({"command": "pwd", "cwd": sub.to_string_lossy()}),
    )
    .await;
    assert!(ran_in(&b, &sub), "{}", text(&b));

    let plain = call(&server, "ctx_shell", json!({"command": "pwd"})).await;
    assert!(ran_in(&plain, &f.root), "{}", text(&plain));
    assert_eq!(
        server.session.read().await.project_root.as_deref(),
        Some(&*f.root.to_string_lossy())
    );
}

/// A `cwd` in another checkout says, once and stably, that relative file-tool
/// paths still name the project root; a subdirectory or no `cwd` says nothing.
#[tokio::test(flavor = "multi_thread")]
async fn a_worktree_cwd_notes_where_relative_paths_resolve() {
    let _data = lean_ctx::core::data_dir::isolated_data_dir();
    let f = fixture();
    let server = server_for(&f);
    let note = format!(
        "[note: relative paths in ctx_read/ctx_patch resolve to {}; use absolute paths for {}]",
        f.root.display(),
        f.wt.display()
    );

    let wt = call(
        &server,
        "ctx_shell",
        json!({"command": "pwd", "cwd": f.wt.to_string_lossy()}),
    )
    .await;
    assert_eq!(text(&wt).matches(&note).count(), 1, "{}", text(&wt));
    let sub = call(
        &server,
        "ctx_shell",
        json!({"command": "pwd", "cwd": f.root.join("sub").to_string_lossy()}),
    )
    .await;
    assert!(
        !text(&sub).contains("[note: relative paths"),
        "{}",
        text(&sub)
    );
    let plain = call(&server, "ctx_shell", json!({"command": "pwd"})).await;
    assert!(
        !text(&plain).contains("[note: relative paths"),
        "{}",
        text(&plain)
    );
}

/// A session without a project root learns it from its own start directory,
/// never from one call's `cwd` (another agent's checkout), and keeps it.
#[tokio::test(flavor = "multi_thread")]
async fn a_missing_root_is_learned_from_the_start_dir_not_a_calls_cwd() {
    // The jail's runtime widenings (the roots-derived allow-list, the session
    // read-only roots) are process-wide and never cleared: in one `cargo test`
    // process another test can leave one that admits `other`, so the refusal
    // this test is about would pass through. Run it in its own process.
    if lean_ctx::test_env::run_in_own_process(
        "server::call_tool::shell_cwd_tests::a_missing_root_is_learned_from_the_start_dir_not_a_calls_cwd",
        &[],
    ) {
        return;
    }
    let _data = lean_ctx::core::data_dir::isolated_data_dir();
    // The default `projects` scope also admits, for reading, any project below
    // `$HOME`. Where the checkout lies below `$HOME` (GitHub runners:
    // `/home/runner/work/…`) it would admit `other` without the learned root,
    // so pin the scope to the project boundary this test is about. Held under
    // the env lock `_data` took, restored on drop.
    let _scope = lean_ctx::test_env::VarGuard::set("LEAN_CTX_PATH_JAIL_SCOPE", "project");
    let f = fixture();
    let server = server_for(&f);
    {
        let mut session = server.session.write().await;
        session.project_root = None;
        session.shell_cwd = Some(f.root.to_string_lossy().to_string());
    }
    let expected = lean_ctx::core::protocol::detect_project_root(&f.root.to_string_lossy());
    assert!(expected.is_some());
    // Another agent's checkout: a directory of a different repository that the
    // rootless jail admits (it lies under the process cwd, this crate), and
    // only through that: the scope is pinned above.
    let other = concat!(env!("CARGO_MANIFEST_DIR"), "/src");
    assert_ne!(
        lean_ctx::core::protocol::detect_project_root(other),
        expected
    );

    // While the root is unknown the call runs in its own `cwd`, and the root
    // is learned from the start directory instead.
    let first = call(
        &server,
        "ctx_shell",
        json!({"command": "pwd", "cwd": other}),
    )
    .await;
    assert!(
        text(&first)
            .lines()
            .any(|line| line.trim().ends_with("/src")),
        "{}",
        text(&first)
    );
    assert_eq!(
        server.session.read().await.project_root,
        expected,
        "{}",
        text(&first)
    );

    // A `no-jail` build (`cargo test --all-features`, the public CI) has no
    // jail to hold the learned root to: `jail_path` admits every directory
    // there, so the refusal below exists only with the jail compiled in.
    if cfg!(feature = "no-jail") {
        return;
    }

    // Once the root is known, the jail holds to it: the other checkout's `cwd`
    // is refused and the command does not run at all; the root is kept.
    let second = call(
        &server,
        "ctx_shell",
        json!({"command": "pwd", "cwd": other}),
    )
    .await;
    assert!(
        text(&second).contains("working directory rejected, command not run"),
        "{}\nsession read-only roots: {:?}",
        text(&second),
        lean_ctx::core::pathjail::session_read_only_roots()
    );
    assert!(
        !text(&second)
            .lines()
            .any(|line| line.trim().ends_with("/src")),
        "{}",
        text(&second)
    );
    assert_eq!(
        server.session.read().await.project_root,
        expected,
        "{}",
        text(&second)
    );
}