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
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
// SPDX-License-Identifier: Apache-2.0
//! Serve `file://` URIs through `resources/read` by reading the local file.
//!
//! Agents (especially Claude Code) sometimes call `readMcpResource` with a
//! `file://` URI instead of `ctx_read`.  Rather than returning a confusing
//! "Unknown resource" error, we resolve the path, validate it against the
//! session's PathJail roots, and return the file content as a text resource.
//!
//! A resource read is never wider than a tool read of the same path: it
//! passes the same PathJail resolver `ctx_read` uses
//! ([`lean_ctx::core::path_resolve::resolve_tool_path_refusing`]) *and* a
//! strict containment in the session's explicit roots. A session without a
//! project root has no explicit root to contain the read in, so only its
//! `extra_roots` are served and everything else is refused (GHSA-836r-2hg2-j56w).
//!
//! GH #1418

use rmcp::model::ResourceContents;
use std::path::Path;

const MAX_FILE_BYTES: u64 = 2 * 1024 * 1024; // 2 MiB

/// Why a `file://` resource request could not be served.
#[derive(Debug)]
pub(super) enum FileResourceError {
    /// URI is not a file path — caller should fall through to the default error.
    NotAFilePath,
    /// Path resolved but the file does not exist.
    NotFound(String),
    /// File exceeds the size guard.
    TooLarge(String, u64),
    /// File is not valid UTF-8.
    NotUtf8(String),
    /// I/O error while reading.
    Io(String, std::io::Error),
    /// Path rejected by PathJail (outside project root / extra roots).
    OutsideJail(String),
    /// The session has no project root and the path is in none of its
    /// extra roots: there is no boundary to serve it under (fail closed).
    Unbound(String),
    /// The shared tool-path resolver refused the path (the same refusal a
    /// `ctx_read` of it would get).
    Refused(String),
    /// Runtime context requires source-aware admission, even inside an allowed root.
    ProtectedContext(String),
}

impl std::fmt::Display for FileResourceError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::NotAFilePath => write!(f, "Not a file path"),
            Self::ProtectedContext(reason) => write!(f, "Protected context: {reason}"),
            Self::NotFound(p) => write!(f, "File not found: {p}"),
            Self::TooLarge(p, sz) => write!(
                f,
                "File too large for resource read ({sz} bytes, limit {MAX_FILE_BYTES}): {p}",
            ),
            Self::NotUtf8(p) => write!(
                f,
                "File is not valid UTF-8 (binary?): {p}. Use ctx_read for binary-safe reads."
            ),
            Self::Io(p, e) => write!(f, "I/O error reading {p}: {e}"),
            Self::OutsideJail(p) => write!(
                f,
                "Path outside project root: {p}. \
                 Add the parent directory to extra_roots in config.toml if needed."
            ),
            Self::Unbound(p) => write!(
                f,
                "No project root is bound for this session, so resources/read cannot \
                 serve {p}. Open the project (start the client in a directory with a \
                 project marker such as .git), bind one with LEAN_CTX_PROJECT_ROOT, or add \
                 the parent directory to extra_roots in config.toml."
            ),
            Self::Refused(reason) => write!(f, "Path refused: {reason}"),
        }
    }
}

/// Try to serve a `file://` URI (or raw absolute path) as a text resource.
///
/// Returns `Err(NotAFilePath)` when the URI is not a recognisable file path,
/// signalling the caller to fall through to the default resource-not-found path.
///
/// `project_root`, `shell_cwd` and `extra_roots` are the session's: the path
/// must be admitted by the shared tool-path jail for that session (what a
/// `ctx_read` of it would get) and lie inside the project root or an extra
/// root. Without a project root only the extra roots are served.
pub(super) fn read_file_resource(
    uri: &str,
    project_root: Option<&str>,
    shell_cwd: Option<&str>,
    extra_roots: &[String],
) -> Result<Vec<ResourceContents>, FileResourceError> {
    let project_root = project_root.filter(|root| !root.is_empty());
    let path_str = resolve_path(uri)?;
    let path = Path::new(&path_str);
    lean_ctx::core::protected_store::enforce_protected_store_path(path)
        .map_err(FileResourceError::ProtectedContext)?;
    // Under a Workspace a resource read is confined like a tool path (#2120).
    lean_ctx::core::workspace_authority::confine(&path_str, project_root.unwrap_or(""), false)
        .map_err(FileResourceError::ProtectedContext)?;

    // Strict containment in the session's explicit roots first: it names the
    // boundary (no root bound, or outside it) in the refusal.
    let contained = validate_jail(path, project_root, extra_roots)?;
    // Then the tool jail itself, so a resource read can never be wider than a
    // ctx_read of the same path (protected zones, secret files, Workspace).
    lean_ctx::core::path_resolve::resolve_tool_path_refusing(
        project_root,
        shell_cwd,
        &path_str,
        extra_roots,
    )
    .map_err(|refusal| FileResourceError::Refused(refusal.message))?;

    if !contained.is_file() {
        return Err(FileResourceError::NotFound(path_str));
    }

    let meta =
        std::fs::metadata(&contained).map_err(|e| FileResourceError::Io(path_str.clone(), e))?;
    if meta.len() > MAX_FILE_BYTES {
        return Err(FileResourceError::TooLarge(path_str, meta.len()));
    }

    let content = std::fs::read_to_string(&contained).map_err(|e| {
        if e.kind() == std::io::ErrorKind::InvalidData {
            FileResourceError::NotUtf8(path_str.clone())
        } else {
            FileResourceError::Io(path_str.clone(), e)
        }
    })?;

    Ok(vec![super::resources::text_resource(&content, uri)])
}

/// Parse `file://` URIs and raw absolute paths to a local path string.
fn resolve_path(uri: &str) -> Result<String, FileResourceError> {
    if uri.starts_with("file://") {
        super::roots::uri_to_path(uri).ok_or(FileResourceError::NotAFilePath)
    } else if is_absolute_path(uri) {
        Ok(uri.to_string())
    } else {
        Err(FileResourceError::NotAFilePath)
    }
}

fn is_absolute_path(s: &str) -> bool {
    s.starts_with('/')
        || (cfg!(windows)
            && s.len() > 2
            && s.as_bytes()[0].is_ascii_alphabetic()
            && s.as_bytes()[1] == b':')
}

/// The canonical form of `path`; for a path that does not exist (yet), its
/// canonical parent joined with the final name, so a missing file inside a
/// root reached through a symlink (macOS `/var` -> `/private/var`) is judged
/// where it would live and reported as not found. Anything else unresolvable
/// stays as given and can only be refused, never widened.
fn canonical_or_parent(path: &Path) -> std::path::PathBuf {
    if let Ok(canon) = path.canonicalize() {
        return canon;
    }
    match (path.parent(), path.file_name()) {
        (Some(parent), Some(name)) => parent
            .canonicalize()
            .map_or_else(|_| path.to_path_buf(), |parent| parent.join(name)),
        _ => path.to_path_buf(),
    }
}

/// The canonical form of `path` when it lies inside `project_root` or one of
/// `extra_roots`; the file is then read through it, so a symlink swapped in
/// after this check cannot redirect the read outside the roots.
fn validate_jail(
    path: &Path,
    project_root: Option<&str>,
    extra_roots: &[String],
) -> Result<std::path::PathBuf, FileResourceError> {
    // Intentionally NOT using jail_path_with_roots here: the full PathJail
    // widens access via global config (allow_paths, state_dir, IDE dirs,
    // env vars). For resources/read (a fallback for agents that use the
    // wrong API), we enforce strict containment in session-explicit roots
    // only — no implicit widening. The tool jail runs as well, in
    // `read_file_resource`, so this only ever narrows it.
    let canon = canonical_or_parent(path);
    // A path that could not be fully resolved keeps its `..` parts, and a
    // lexical `starts_with` would read `/root/missing/../../etc` as inside.
    let unresolved_dots = canon
        .components()
        .any(|c| matches!(c, std::path::Component::ParentDir));
    let roots = project_root
        .into_iter()
        .chain(extra_roots.iter().map(String::as_str))
        .filter(|root| !root.is_empty());
    for root in roots {
        if !unresolved_dots
            && let Ok(root_canon) = Path::new(root).canonicalize()
            && canon.starts_with(&root_canon)
        {
            return Ok(canon);
        }
    }

    let shown = path.to_string_lossy().to_string();
    Err(if project_root.is_none() {
        FileResourceError::Unbound(shown)
    } else {
        FileResourceError::OutsideJail(shown)
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[cfg(target_os = "macos")]
    #[test]
    fn resource_read_cannot_reopen_runtime_context_with_explicit_roots() {
        let isolated = lean_ctx::core::data_dir::isolated_data_dir();
        let path = isolated.path().join("knowledge/fixture.json");
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        std::fs::write(&path, "provider-value").unwrap();
        let uri = path_to_file_uri(&path);
        let root = isolated.path().to_str().unwrap();
        assert!(read_file_resource(&uri, Some(root), None, &[]).is_ok());
        let _pin = lean_ctx::core::protected_store::pin_synthetic_session(isolated.path()).unwrap();
        assert!(matches!(
            read_file_resource(&uri, Some(root), None, &[root.to_owned()]),
            Err(FileResourceError::ProtectedContext(_))
        ));
        assert!(matches!(
            read_file_resource(&uri, None, None, &[]),
            Err(FileResourceError::ProtectedContext(_))
        ));
    }

    fn path_to_file_uri(p: &std::path::Path) -> String {
        let s = p.to_string_lossy().replace('\\', "/");
        if s.starts_with('/') {
            format!("file://{s}")
        } else {
            format!("file:///{s}")
        }
    }

    #[cfg(unix)]
    #[test]
    fn resolve_file_uri() {
        let path = resolve_path("file:///tmp/test.txt").unwrap();
        assert_eq!(path, "/tmp/test.txt");
    }

    #[cfg(unix)]
    #[test]
    fn resolve_raw_absolute_path() {
        let path = resolve_path("/home/user/file.rs").unwrap();
        assert_eq!(path, "/home/user/file.rs");
    }

    #[test]
    fn resolve_relative_path_returns_not_a_file() {
        assert!(matches!(
            resolve_path("relative/file.rs"),
            Err(FileResourceError::NotAFilePath)
        ));
    }

    #[test]
    fn resolve_lean_ctx_uri_returns_not_a_file() {
        assert!(matches!(
            resolve_path("lean-ctx://context/summary"),
            Err(FileResourceError::NotAFilePath)
        ));
    }

    fn root_of(dir: &tempfile::TempDir) -> String {
        dir.path()
            .canonicalize()
            .unwrap()
            .to_string_lossy()
            .to_string()
    }

    #[test]
    fn unresolvable_dot_dot_never_counts_as_inside() {
        let _iso = lean_ctx::core::data_dir::isolated_data_dir();
        let dir = tempfile::tempdir().unwrap();
        let root = root_of(&dir);
        // Built from the plain temp path: on Windows the canonical root carries
        // the `\\?\` prefix, which is no absolute path a client sends.
        let escape = format!(
            "{}/missing/../../../../../../etc/hostname",
            dir.path().to_string_lossy()
        );
        let result = read_file_resource(&escape, Some(&root), None, &[]);
        assert!(
            matches!(result, Err(FileResourceError::OutsideJail(_))),
            "{result:?}"
        );
    }

    #[test]
    fn read_nonexistent_file_inside_root() {
        let _iso = lean_ctx::core::data_dir::isolated_data_dir();
        let dir = tempfile::tempdir().unwrap();
        let root = root_of(&dir);
        let uri = path_to_file_uri(&dir.path().join("does_not_exist.txt"));
        let result = read_file_resource(&uri, Some(&root), None, &[]);
        assert!(
            matches!(result, Err(FileResourceError::NotFound(_))),
            "{result:?}"
        );
    }

    /// GHSA-836r-2hg2-j56w: a session without a project root served any
    /// UTF-8 file on the machine.
    #[cfg(unix)]
    #[test]
    fn unbound_session_refuses_system_files() {
        let _iso = lean_ctx::core::data_dir::isolated_data_dir();
        for system in ["/etc/hostname", "/etc/hosts", "/etc/passwd"] {
            if !Path::new(system).is_file() {
                continue;
            }
            for uri in [format!("file://{system}"), system.to_string()] {
                let result = read_file_resource(&uri, None, None, &[]);
                assert!(
                    matches!(result, Err(FileResourceError::Unbound(_))),
                    "{uri}: {result:?}"
                );
                let shell_cwd = std::env::current_dir().unwrap();
                let result =
                    read_file_resource(&uri, None, Some(&shell_cwd.to_string_lossy()), &[]);
                assert!(
                    matches!(result, Err(FileResourceError::Unbound(_))),
                    "{uri}: {result:?}"
                );
                // An empty root is no root.
                let result = read_file_resource(&uri, Some(""), None, &[]);
                assert!(
                    matches!(result, Err(FileResourceError::Unbound(_))),
                    "{uri}: {result:?}"
                );
            }
        }
    }

    #[test]
    fn unbound_session_refuses_a_project_outside_every_root() {
        let _iso = lean_ctx::core::data_dir::isolated_data_dir();
        let project = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(project.path().join(".git")).unwrap();
        let file = project.path().join("README.md");
        std::fs::write(&file, "project").unwrap();
        let cwd = root_of(&project);
        for uri in [path_to_file_uri(&file), file.to_string_lossy().to_string()] {
            for shell_cwd in [None, Some(cwd.as_str())] {
                let result = read_file_resource(&uri, None, shell_cwd, &[]);
                let err = result.unwrap_err();
                assert!(
                    matches!(err, FileResourceError::Unbound(_)),
                    "{uri}: {err:?}"
                );
                let text = err.to_string();
                assert!(
                    text.contains("No project root") && text.contains("extra_roots"),
                    "{text}"
                );
            }
        }
    }

    #[test]
    fn unbound_session_serves_its_extra_roots() {
        let _iso = lean_ctx::core::data_dir::isolated_data_dir();
        let extra = tempfile::tempdir().unwrap();
        let file = extra.path().join("notes.txt");
        std::fs::write(&file, "allowed").unwrap();
        let roots = vec![root_of(&extra)];
        let result = read_file_resource(&path_to_file_uri(&file), None, None, &roots);
        assert!(result.is_ok(), "{result:?}");
    }

    #[test]
    fn read_file_outside_jail() {
        let _iso = lean_ctx::core::data_dir::isolated_data_dir();
        let jail = tempfile::tempdir().unwrap();
        let outside = tempfile::tempdir().unwrap();
        let file = outside.path().join("secret.txt");
        std::fs::write(&file, "secret").unwrap();
        let root = root_of(&jail);
        for uri in [path_to_file_uri(&file), file.to_string_lossy().to_string()] {
            let result = read_file_resource(&uri, Some(&root), Some(&root), &[]);
            assert!(
                matches!(result, Err(FileResourceError::OutsideJail(_))),
                "{result:?}"
            );
        }
    }

    #[test]
    fn read_file_inside_jail() {
        let _iso = lean_ctx::core::data_dir::isolated_data_dir();
        let jail = tempfile::tempdir().unwrap();
        let file = jail.path().join("test.txt");
        std::fs::write(&file, "allowed").unwrap();
        let root = root_of(&jail);
        for uri in [path_to_file_uri(&file), file.to_string_lossy().to_string()] {
            let result = read_file_resource(&uri, Some(&root), Some(&root), &[]);
            assert_eq!(result.unwrap().len(), 1);
        }
    }

    #[test]
    fn bound_root_also_serves_extra_roots() {
        let _iso = lean_ctx::core::data_dir::isolated_data_dir();
        let jail = tempfile::tempdir().unwrap();
        let extra = tempfile::tempdir().unwrap();
        let file = extra.path().join("shared.txt");
        std::fs::write(&file, "shared").unwrap();
        let root = root_of(&jail);
        let uri = path_to_file_uri(&file);
        assert!(matches!(
            read_file_resource(&uri, Some(&root), None, &[]),
            Err(FileResourceError::OutsideJail(_))
        ));
        let roots = vec![root_of(&extra)];
        let result = read_file_resource(&uri, Some(&root), None, &roots);
        assert!(result.is_ok(), "{result:?}");
    }

    #[cfg(unix)]
    #[test]
    fn symlink_inside_root_to_outside_is_refused() {
        let _iso = lean_ctx::core::data_dir::isolated_data_dir();
        let jail = tempfile::tempdir().unwrap();
        let outside = tempfile::tempdir().unwrap();
        let target = outside.path().join("secret.txt");
        std::fs::write(&target, "secret").unwrap();
        let link = jail.path().join("link.txt");
        std::os::unix::fs::symlink(&target, &link).unwrap();
        let root = root_of(&jail);
        let result = read_file_resource(&path_to_file_uri(&link), Some(&root), None, &[]);
        assert!(
            matches!(result, Err(FileResourceError::OutsideJail(_))),
            "{result:?}"
        );
        // A linked directory is no way out either.
        let dir_link = jail.path().join("out");
        std::os::unix::fs::symlink(outside.path(), &dir_link).unwrap();
        let via_dir = dir_link.join("secret.txt");
        let result = read_file_resource(&path_to_file_uri(&via_dir), Some(&root), None, &[]);
        assert!(
            matches!(result, Err(FileResourceError::OutsideJail(_))),
            "{result:?}"
        );
        // And without a root the same link is refused as unbound.
        let result = read_file_resource(&path_to_file_uri(&link), None, None, &[]);
        assert!(
            matches!(result, Err(FileResourceError::Unbound(_))),
            "{result:?}"
        );
    }

    /// Inside the root a resource read gets exactly the tool jail's verdict:
    /// a secret file a ctx_read is refused (boundary mode Enforce) is refused
    /// here too, and one it serves (Warn) is served.
    #[test]
    fn resource_read_follows_the_tool_jail_inside_the_root() {
        let _iso = lean_ctx::core::data_dir::isolated_data_dir();
        let jail = tempfile::tempdir().unwrap();
        let root = root_of(&jail);
        std::fs::create_dir_all(jail.path().join(".ssh")).unwrap();
        for name in [".env", ".ssh/id_rsa", "plain.txt"] {
            let file = jail.path().join(name);
            std::fs::write(&file, "value").unwrap();
            let path = file.to_string_lossy().to_string();
            let tool = lean_ctx::core::path_resolve::resolve_tool_path_refusing(
                Some(&root),
                Some(&root),
                &path,
                &[],
            );
            let resource = read_file_resource(&path, Some(&root), Some(&root), &[]);
            assert_eq!(tool.is_ok(), resource.is_ok(), "{name}: {resource:?}");
            if tool.is_err() {
                assert!(
                    matches!(resource, Err(FileResourceError::Refused(_))),
                    "{name}"
                );
            }
        }
    }

    #[cfg(unix)]
    #[test]
    fn dot_dot_out_of_the_root_is_refused() {
        let _iso = lean_ctx::core::data_dir::isolated_data_dir();
        let parent = tempfile::tempdir().unwrap();
        let jail = parent.path().join("project");
        std::fs::create_dir_all(&jail).unwrap();
        std::fs::write(parent.path().join("secret.txt"), "secret").unwrap();
        let root = jail.canonicalize().unwrap().to_string_lossy().to_string();
        let escaped = format!("{root}/../secret.txt");
        let result = read_file_resource(&escaped, Some(&root), None, &[]);
        assert!(
            matches!(result, Err(FileResourceError::OutsideJail(_))),
            "{result:?}"
        );
    }

    #[test]
    fn non_file_uri_is_not_a_file_path() {
        assert!(matches!(
            read_file_resource("https://example.com", None, None, &[]),
            Err(FileResourceError::NotAFilePath)
        ));
    }
}