lean-ctx-server 3.12.3

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
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
// SPDX-License-Identifier: Apache-2.0
use super::*;
use lean_ctx::core::policy::runtime::TestPolicyOverride;

fn policy(extra: &str) -> TestPolicyOverride {
    let pack = lean_ctx::core::policy::parse(&format!(
        "name = \"release-test\"\nversion = \"1.0.0\"\ndescription = \"test\"\n{extra}"
    ))
    .expect("valid policy");
    TestPolicyOverride::set(Some(
        lean_ctx::core::policy::resolve(&pack).expect("resolved policy"),
    ))
}

async fn process(
    server: &LeanCtxServer,
    name: &str,
    args: &serde_json::Map<String, serde_json::Value>,
    text: &str,
    blocks: Option<Vec<ContentBlock>>,
) -> McpProcessed {
    reversible_post_process(
        server,
        name,
        Some(args),
        true,
        lean_ctx::core::config::Config::load_arc(),
        false,
        None,
        None,
        None,
        McpPrimitive::Raw(McpRawOutput {
            archive_authority: None,
            result_text: text.into(),
            tool_error: false,
            tool_saved_tokens: 0,
            shell_outcome: None,
            content_blocks: blocks,
            tool_start: std::time::Instant::now(),
        }),
    )
    .await
    .expect("post-processing succeeds")
}

#[tokio::test]
async fn protected_output_omits_unattributed_automatic_context() {
    let _data = lean_ctx::core::data_dir::isolated_data_dir();
    let _policy = policy("[redaction]\ncustomer = 'K-[0-9]{6}'");
    let root = tempfile::tempdir().expect("project root");
    let server = LeanCtxServer::new_with_project_root(root.path().to_str());
    let args = serde_json::json!({"task": "investigate authentication"});
    let processed = reversible_post_process(
        &server,
        "ctx_compose",
        args.as_object(),
        true,
        lean_ctx::core::config::Config::load_arc(),
        false,
        Some("--- AUTO CONTEXT ---\nprivate-metadata-canary.rs\n--- END AUTO CONTEXT ---".into()),
        None,
        None,
        McpPrimitive::Raw(McpRawOutput {
            archive_authority: None,
            result_text: "PERMITTED_CONTEXT K-482193".into(),
            tool_error: false,
            tool_saved_tokens: 0,
            shell_outcome: None,
            content_blocks: None,
            tool_start: std::time::Instant::now(),
        }),
    )
    .await
    .expect("post-processing succeeds");
    assert_ne!(processed.result.is_error, Some(true));
    let text = serde_json::to_string(&processed.result).unwrap();
    assert!(text.contains("PERMITTED_CONTEXT"));
    assert!(text.contains("REDACTED"));
    assert!(!text.contains("private-metadata-canary"));
    assert!(!text.contains("K-482193"));
}

#[tokio::test]
async fn raw_reads_protect_output_and_persisted_ir_metadata() {
    let _data = lean_ctx::core::data_dir::isolated_data_dir();
    let _policy = policy("[redaction]\ncustomer = 'K-[0-9]{6}'");
    let root = tempfile::tempdir().expect("project root");
    let server = LeanCtxServer::new_with_project_root(root.path().to_str());
    let args = serde_json::json!({
        "raw": true, "mode": "raw", "path": "customer-K-482193.txt",
        "command": "cat customer-K-482193.txt"
    });
    let processed = process(
        &server,
        "ctx_read",
        args.as_object().unwrap(),
        "Kundennummer K-482193\nGrüezi 客户",
        None,
    )
    .await;
    assert_ne!(processed.result.is_error, Some(true));
    let output = serde_json::to_string(&processed.result).unwrap();
    assert!(!output.contains("K-482193"));
    assert!(output.contains("[REDACTED:customer]"));
    assert!(
        !processed
            .ir
            .as_ref()
            .unwrap()
            .content_excerpt
            .contains("K-482193")
    );
    record_context_ir(&server, &processed).await;
    let ir = server.context_ir.as_ref().unwrap().read().await;
    assert!(!serde_json::to_string(&*ir).unwrap().contains("K-482193"));
    let persisted = lean_ctx::core::context_ir::ContextIrV1::load();
    assert!(
        !serde_json::to_string(&persisted)
            .unwrap()
            .contains("K-482193")
    );
}

#[tokio::test]
async fn blocking_content_creates_no_ir_archive_or_receipt_intent() {
    let _data = lean_ctx::core::data_dir::isolated_data_dir();
    let _policy =
        policy("[redaction]\nlabel = 'CONFIDENTIAL'\n[filters]\nclassification = 'block'");
    let root = tempfile::tempdir().expect("project root");
    let server = LeanCtxServer::new_with_project_root(root.path().to_str());
    let processed = process(
        &server,
        "ctx_shell",
        serde_json::json!({"raw": true}).as_object().unwrap(),
        "CONFIDENTIAL\nK-482193",
        None,
    )
    .await;
    assert_eq!(processed.result.is_error, Some(true));
    assert!(
        !serde_json::to_string(&processed.result)
            .unwrap()
            .contains("K-482193")
    );
    assert!(processed.ir.is_none());
    assert!(processed.receipt.is_none());
    assert!(lean_ctx::core::archive::list_entries(None).is_empty());
}

#[tokio::test]
async fn protected_images_are_withheld() {
    let _data = lean_ctx::core::data_dir::isolated_data_dir();
    let _policy = policy("");
    let root = tempfile::tempdir().expect("project root");
    let server = LeanCtxServer::new_with_project_root(root.path().to_str());
    let block = serde_json::from_value(serde_json::json!({
        "type": "image", "mimeType": "image/png", "data": "S1ktNDgyMTkz"
    }))
    .unwrap();
    let processed = process(
        &server,
        "ctx_read",
        &serde_json::Map::new(),
        "",
        Some(vec![block]),
    )
    .await;
    assert_eq!(processed.result.is_error, Some(true));
    assert!(
        !serde_json::to_string(&processed.result)
            .unwrap()
            .contains("S1ktNDgyMTkz")
    );
}

#[tokio::test]
async fn failed_knowledge_write_is_an_error_without_success_artifacts() {
    let _data = lean_ctx::core::data_dir::isolated_data_dir();
    let _policy = policy("[redaction]\ncustomer = 'K-[0-9]{6}'");
    let root = tempfile::tempdir().expect("project root");
    let server = LeanCtxServer::new_with_project_root(root.path().to_str());
    let processed = process(
        &server,
        "ctx_knowledge",
        serde_json::json!({"action":"remember"})
            .as_object()
            .unwrap(),
        "Error: knowledge was not saved: K-482193",
        None,
    )
    .await;
    assert_eq!(processed.result.is_error, Some(true));
    let text = serde_json::to_string(&processed.result).unwrap();
    assert!(text.contains("knowledge was not saved") && !text.contains("K-482193"));
    assert!(
        processed.ir.is_none() && processed.receipt.is_none() && processed.checkpoint.is_none()
    );
    assert!(lean_ctx::core::archive::list_entries(None).is_empty());
}

#[tokio::test]
async fn text_content_blocks_share_the_same_policy_path() {
    let _data = lean_ctx::core::data_dir::isolated_data_dir();
    let _policy = policy("[redaction]\ncustomer = 'K-[0-9]{6}'");
    let root = tempfile::tempdir().expect("project root");
    let server = LeanCtxServer::new_with_project_root(root.path().to_str());
    let processed = process(
        &server,
        "ctx_read",
        &serde_json::Map::new(),
        "",
        Some(vec![ContentBlock::text("K-482193")]),
    )
    .await;
    assert_ne!(processed.result.is_error, Some(true));
    assert!(
        !serde_json::to_string(&processed.result)
            .unwrap()
            .contains("K-482193")
    );
    assert!(
        processed
            .ir
            .as_ref()
            .unwrap()
            .content_excerpt
            .contains("[REDACTED:customer]")
    );
}

#[test]
fn terminal_errors_cannot_echo_customer_numbers_or_structured_payloads() {
    let _data = lean_ctx::core::data_dir::isolated_data_dir();
    let _policy = policy("[redaction]\ncustomer = 'K-[0-9]{6}'");
    let mut error = CallToolResult::error(vec![ContentBlock::text("invalid K-482193")]);
    error.structured_content = Some(serde_json::json!({"untrusted": "K-482193"}));
    let result = protect_terminal_result("ctx_read", error);
    assert_eq!(result.is_error, Some(true));
    assert!(result.structured_content.is_none());
    assert!(!serde_json::to_string(&result).unwrap().contains("K-482193"));
}

#[tokio::test]
async fn unavailable_archive_preserves_default_bound_and_wrapped_raw_output() {
    use crate::server::tool_trait::{
        BackgroundDisplay, BackgroundJobState, BackgroundShellOutcome, ShellOutcome,
    };
    use std::fmt::Write as _;
    let _data = lean_ctx::core::data_dir::isolated_data_dir();
    let _policy = policy("[redaction]\ncustomer = 'K-[0-9]{6}'");
    let root = tempfile::tempdir().unwrap();
    let server = LeanCtxServer::new_with_project_root(root.path().to_str());
    let mut text = String::new();
    for n in 0..3000 {
        writeln!(&mut text, "safe line {n} K-482193 🙂 data").unwrap();
    }
    let mut config = lean_ctx::core::config::Config::load();
    config.archive.ephemeral = true;
    config.archive.ephemeral_min_tokens = 100;
    config.archive.verbatim_max_tokens = 100;
    let config = std::sync::Arc::new(config);
    for background in [false, true] {
        for raw in [false, true] {
            let args = if background {
                serde_json::json!({"background_action":"status","job_id":"shell_test","raw":raw})
            } else {
                serde_json::json!({"command":"example-output","raw":raw})
            };
            let (name, args) = if raw {
                (
                    "ctx_call",
                    serde_json::json!({"name":"ctx_shell","arguments":args}),
                )
            } else {
                ("ctx_shell", args)
            };
            let shell_outcome = if background {
                Some(ShellOutcome::Background(BackgroundShellOutcome {
                    state: BackgroundJobState::Completed,
                    exit_code: Some(0),
                    job_id: "shell_test".into(),
                    archive_id: None,
                    archive_truncated: None,
                    captured_chars: None,
                    archived_chars: None,
                    summary: "completed".into(),
                    is_error: false,
                    display: Some(BackgroundDisplay {
                        header: "[background:shell_test completed, exit 0]".into(),
                        footer: None,
                    }),
                }))
            } else {
                Some(ShellOutcome::Exit(0))
            };
            let processed = reversible_post_process(
                &server,
                name,
                args.as_object(),
                true,
                config.clone(),
                false,
                None,
                None,
                None,
                McpPrimitive::Raw(McpRawOutput {
                    archive_authority: None,
                    result_text: text.clone(),
                    tool_error: false,
                    tool_saved_tokens: 0,
                    shell_outcome,
                    content_blocks: None,
                    tool_start: std::time::Instant::now(),
                }),
            )
            .await
            .unwrap();
            let wire = serde_json::to_string(&processed.result).unwrap();
            assert!(!wire.contains("K-482193"));
            assert!(wire.contains("safe line"));
            assert!(!wire.contains("ctx_expand"));
            if raw {
                assert!(wire.contains("safe line 1500"));
            } else {
                assert!(
                    wire.len() < 15_000,
                    "unexpected unbounded output: {}",
                    wire.len()
                );
                assert!(wire.contains("recovery unavailable"));
                assert!(!wire.contains("safe line 1500"));
            }
            if background {
                let metadata = processed.result.structured_content.as_ref().unwrap();
                assert_eq!(metadata["state"], "completed");
                assert_eq!(metadata["exitCode"], 0);
                assert!(metadata["capturedChars"].as_u64().unwrap() > 50_000);
                assert!(metadata.get("archiveId").is_none());
                assert!(metadata.get("archivedChars").is_none());
                assert!(metadata.get("archiveTruncated").is_none());
            }
        }
    }
    assert!(lean_ctx::core::archive::list_entries(None).is_empty());
}

#[tokio::test]
async fn archive_binding_is_used_only_for_its_file_output_class() {
    use lean_ctx::core::{archive, policy::runtime};
    let _data = lean_ctx::core::data_dir::isolated_data_dir();
    let _policy = policy("");
    let root = tempfile::tempdir().unwrap();
    let path = root.path().join("source.txt");
    std::fs::write(&path, "public source").unwrap();
    let path = std::fs::canonicalize(path).unwrap();
    let authority = archive::authority::ArchiveAuthority::file(
        root.path(),
        path.to_str().unwrap(),
        "ctx_execute",
        "public source",
    )
    .unwrap();
    let server = LeanCtxServer::new_with_project_root(root.path().to_str());
    let output = "archive binding permitted output\n".repeat(4000);
    runtime::REQUEST_PROJECT
        .scope(
            std::cell::RefCell::new(Some(root.path().to_path_buf())),
            async {
                for (name, action, expected, wrapped) in [
                    ("ctx_shell", "file", false, false),
                    ("ctx_shell", "file", false, true),
                    ("ctx_execute", "code", false, false),
                    ("ctx_execute", "code", false, true),
                    ("ctx_execute", "file", true, false),
                    ("ctx_execute", "file", true, true),
                ] {
                    let args = serde_json::json!({"action":action,"path":path});
                    let (name, args) = if wrapped {
                        (
                            "ctx_call",
                            serde_json::json!({"name":name,"arguments":args}),
                        )
                    } else {
                        (name, args)
                    };
                    let result = reversible_post_process(
                        &server,
                        name,
                        args.as_object(),
                        true,
                        lean_ctx::core::config::Config::load_arc(),
                        false,
                        None,
                        None,
                        None,
                        McpPrimitive::Raw(McpRawOutput {
                            archive_authority: Some(Box::new(authority.clone())),
                            result_text: output.clone(),
                            tool_error: false,
                            tool_saved_tokens: 0,
                            shell_outcome: None,
                            content_blocks: None,
                            tool_start: std::time::Instant::now(),
                        }),
                    )
                    .await
                    .unwrap();
                    let entries = archive::list_entries(None);
                    assert_eq!(entries.len(), usize::from(expected), "{name}/{action}");
                    if expected {
                        assert!(
                            archive::retrieve(&entries[0].id)
                                .unwrap()
                                .contains("binding permitted")
                        );
                        assert!(
                            serde_json::to_string(&result.result)
                                .unwrap()
                                .contains(&entries[0].id)
                        );
                    }
                }
            },
        )
        .await;
}

/// The recovery copy of a declared reader, through the real post-process
/// path (no policy pack, gateway governed): `ctx_read` declares its source
/// set, the admitted reader publishes it, and the pipeline binds the archive
/// copy to it. The id resolves while the source is unchanged and is refused
/// once the source is deleted or reclassified. Before the declaration the
/// pipeline bound only `ctx_execute file`; a `ctx_read` copy was refused at
/// store time under protection.
#[tokio::test]
async fn recovery_copy_of_a_declared_read_is_refused_once_its_source_loses_its_rights() {
    use lean_ctx::core::{archive, policy::runtime};
    let _data = lean_ctx::core::data_dir::isolated_data_dir();
    let _community = TestPolicyOverride::set(None);
    let config_dir = lean_ctx::core::paths::config_dir_read_only().expect("isolated config dir");
    std::fs::create_dir_all(&config_dir).expect("config dir");
    // A reply names the recovery copy of a file read only under a profile
    // that asks for the archive hint (`output_hints.archive_hint`, off in
    // every built-in profile; a read is never firewalled into a digest that
    // would name it). The test's profile is the default one with that hint.
    std::fs::write(
        config_dir.join("config.toml"),
        "profile = \"recovery-hint\"\n\n\
         [context_gateway]\nmode = \"governed\"\nclassification = \"block\"\n",
    )
    .expect("config");
    let profiles = lean_ctx::core::data_dir::lean_ctx_data_dir()
        .expect("isolated data dir")
        .join("profiles");
    std::fs::create_dir_all(&profiles).expect("profiles dir");
    std::fs::write(
        profiles.join("recovery-hint.toml"),
        "[profile]\ninherits = \"coder\"\n\n[output_hints]\narchive_hint = true\n",
    )
    .expect("profile");
    assert!(
        lean_ctx::core::profiles::active_profile()
            .output_hints
            .archive_hint(),
        "the test's profile is the active one"
    );
    let directory = tempfile::tempdir().expect("project");
    let root = directory.path().canonicalize().expect("canonical root");
    let server = LeanCtxServer::new_with_project_root(root.to_str());
    assert!(
        tool_declaration(
            &server,
            "ctx_read",
            serde_json::json!({"path": "x.rs", "mode": "full"}).as_object(),
        )
        .publishes_every_source,
        "the test server carries the registry and ctx_read declares its source set"
    );
    runtime::REQUEST_PROJECT
        .scope(std::cell::RefCell::new(Some(root.clone())), async {
            for scenario in ["deleted", "reclassified"] {
                let path = root.join(format!("{scenario}.rs"));
                let source = format!("pub fn recovery_{scenario}_fixture() {{}}\n").repeat(4000);
                std::fs::write(&path, &source).expect("source");
                let path_text = path.to_str().expect("utf-8 path");
                let (admitted, authority) = archive::authority::capture(async {
                    crate::tools::ctx_read::read_file_for_tool_rooted(
                        path_text,
                        root.to_str().expect("utf-8 root"),
                        "ctx_read",
                    )
                })
                .await;
                let admitted = admitted.expect("admitted read");
                let authority = authority.expect("the admitted reader published its source");
                assert!(!authority.is_incomplete(), "{scenario}");

                let known: std::collections::HashSet<String> = archive::list_entries(None)
                    .into_iter()
                    .map(|entry| entry.id)
                    .collect();
                let args = serde_json::json!({"path": path_text, "mode": "full"});
                let processed = reversible_post_process(
                    &server,
                    "ctx_read",
                    args.as_object(),
                    true,
                    lean_ctx::core::config::Config::load_arc(),
                    false,
                    None,
                    None,
                    None,
                    McpPrimitive::Raw(McpRawOutput {
                        archive_authority: Some(Box::new(authority)),
                        result_text: admitted,
                        tool_error: false,
                        tool_saved_tokens: 0,
                        shell_outcome: None,
                        content_blocks: None,
                        tool_start: std::time::Instant::now(),
                    }),
                )
                .await
                .expect("post-processing succeeds");
                assert_ne!(processed.result.is_error, Some(true), "{scenario}");
                let stored: Vec<String> = archive::list_entries(None)
                    .into_iter()
                    .map(|entry| entry.id)
                    .filter(|id| !known.contains(id))
                    .collect();
                assert_eq!(
                    stored.len(),
                    1,
                    "{scenario}: one source-bound recovery copy"
                );
                let id = &stored[0];
                let reply = serde_json::to_string(&processed.result).unwrap();
                assert!(
                    reply.contains(id.as_str()),
                    "{scenario}: the reply names its recovery copy {id}: {} bytes, ends {:?}",
                    reply.len(),
                    reply
                        .chars()
                        .skip(reply.chars().count().saturating_sub(600))
                        .collect::<String>()
                );
                let marker = format!("recovery_{scenario}_fixture");
                assert!(
                    archive::retrieve_checked(id).is_ok_and(|text| text.contains(&marker)),
                    "{scenario}: resolves while the source is unchanged"
                );

                if scenario == "deleted" {
                    std::fs::remove_file(&path).expect("delete the source");
                } else {
                    std::fs::write(&path, format!("*** TOP SECRET ***\n{source}"))
                        .expect("reclassify the source");
                }
                assert!(
                    matches!(
                        archive::retrieve_checked(id),
                        Err(archive::ArchiveResolveError::Refused(_))
                    ),
                    "{scenario}: the recovery copy is refused, got {:?}",
                    archive::retrieve_checked(id).map(|text| text.len())
                );
            }
        })
        .await;
}