lean-ctx-server 3.12.10

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
// SPDX-License-Identifier: Apache-2.0
//! GH #1722: MCP Tasks (SEP-2663) over `ctx_shell` background jobs, driven
//! through a real rmcp client over an in-memory transport.

use rmcp::ServiceExt;
use rmcp::model::{
    CallToolRequestParams, CallToolResponse, CancelTaskParams, ClientCapabilities, ClientConfig,
    GetTaskParams, GetTaskResult, Implementation, TaskPayload, TaskStatus,
};
use rmcp::service::{RunningService, ServiceError};

use crate::server::background_shell::{self, JobState};
use crate::server::shell_tasks;
use crate::tools::LeanCtxServer;

struct Host {
    tasks: bool,
}

impl rmcp::ClientHandler for Host {
    fn get_info(&self) -> ClientConfig {
        let capabilities = if self.tasks {
            ClientCapabilities::builder().enable_tasks().build()
        } else {
            ClientCapabilities::default()
        };
        ClientConfig::new(
            capabilities,
            Implementation::new("tasks-test-host", "1.0.0"),
        )
    }
}

type Client = RunningService<rmcp::RoleClient, Host>;

/// The `shell_*` job a task id names (`shell_…@g<N>`).
fn job_of(task_id: &str) -> String {
    task_id
        .rsplit_once("@g")
        .map_or(task_id, |(job, _)| job)
        .to_string()
}

/// Cancels and forgets a task's job (and its task handle) when the test ends.
struct JobGuard(String);

impl Drop for JobGuard {
    fn drop(&mut self) {
        let job = job_of(&self.0);
        let _ = background_shell::cancel(&job);
        for _ in 0..120 {
            if !matches!(
                background_shell::status(&job),
                Some(JobState::Running { .. })
            ) {
                break;
            }
            std::thread::sleep(std::time::Duration::from_millis(25));
        }
        background_shell::remove_for_test(&job);
        shell_tasks::forget_for_test(&self.0);
    }
}

async fn connect(tasks: bool) -> (LeanCtxServer, Client) {
    // The initialize handshake's startup maintenance (rules, skills, hook
    // refresh) writes into the real HOME; a test must never touch it.
    lean_ctx::test_env::set_var("LEAN_CTX_HEADLESS", "1");
    let server = LeanCtxServer::new_with_project_root(Some(env!("CARGO_MANIFEST_DIR")));
    let (server_io, client_io) = tokio::io::duplex(1 << 16);
    let served = server.clone();
    tokio::spawn(async move {
        if let Ok(running) = Box::pin(served.serve(server_io)).await {
            let _ = running.waiting().await;
        }
    });
    let client = Host { tasks }.serve(client_io).await.expect("connect");
    (server, client)
}

fn shell_args(command: &str, timeout_ms: Option<u64>) -> CallToolRequestParams {
    let mut args = serde_json::Map::new();
    args.insert("command".into(), serde_json::json!(command));
    args.insert("run_in_background".into(), serde_json::json!(true));
    if let Some(timeout) = timeout_ms {
        args.insert("timeout_ms".into(), serde_json::json!(timeout));
    }
    CallToolRequestParams::new("ctx_shell").with_arguments(args)
}

fn poll_args(action: &str, job_id: &str) -> CallToolRequestParams {
    let mut args = serde_json::Map::new();
    args.insert("background_action".into(), serde_json::json!(action));
    args.insert("job_id".into(), serde_json::json!(job_id));
    CallToolRequestParams::new("ctx_shell").with_arguments(args)
}

/// Launch as a task and return the task id (`shell_*` job id + generation).
async fn launch_task(client: &Client, command: &str, timeout_ms: Option<u64>) -> String {
    let response = client
        .call_tool_once(shell_args(command, timeout_ms))
        .await
        .expect("tools/call");
    let CallToolResponse::Task(created) = response else {
        panic!("a tasks client launching a background job gets a task: {response:?}");
    };
    assert_eq!(created.task.status, TaskStatus::Working);
    assert_eq!(
        created.task.poll_interval_ms,
        Some(shell_tasks::POLL_INTERVAL_MS)
    );
    let wire = serde_json::to_value(&created).unwrap();
    assert_eq!(wire["resultType"], serde_json::json!("task"));
    let task_id = created.task.task_id.clone();
    let job = job_of(&task_id);
    assert!(
        job.starts_with("shell_") && job != task_id,
        "task id is the job id plus its generation: {task_id}"
    );
    let snapshot = background_shell::snapshot(&job).expect("job registered");
    assert_eq!(task_id, format!("{job}@g{}", snapshot.generation));
    task_id
}

async fn get(client: &Client, task_id: &str) -> Result<GetTaskResult, ServiceError> {
    client.get_task(GetTaskParams::new(task_id)).await
}

/// Poll `tasks/get` until the task leaves `working`.
async fn settle(client: &Client, task_id: &str) -> GetTaskResult {
    let deadline = std::time::Instant::now() + std::time::Duration::from_mins(1);
    loop {
        let result = get(client, task_id).await.expect("tasks/get");
        if result.task.task.status != TaskStatus::Working {
            return result;
        }
        assert!(
            std::time::Instant::now() < deadline,
            "task {task_id} never settled"
        );
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
    }
}

fn completed_result(result: &GetTaskResult) -> &rmcp::model::JsonObject {
    assert_eq!(result.task.task.status, TaskStatus::Completed);
    match &result.task.payload {
        TaskPayload::Completed { result } => result,
        other => panic!("completed task carries its result: {other:?}"),
    }
}

fn error_of(error: ServiceError) -> rmcp::ErrorData {
    match error {
        ServiceError::McpError(error) => error,
        other => panic!("expected a JSON-RPC error, got {other:?}"),
    }
}

fn error_code_of(error: &rmcp::ErrorData) -> Option<String> {
    error
        .data
        .as_ref()
        .and_then(|data| data.get("errorCode"))
        .and_then(|code| code.as_str())
        .map(str::to_string)
}

fn text_of(result: &rmcp::model::JsonObject) -> String {
    result["content"]
        .as_array()
        .into_iter()
        .flatten()
        .filter_map(|block| block["text"].as_str())
        .collect()
}

#[tokio::test(flavor = "multi_thread")]
async fn server_declares_the_tasks_extension() {
    let _data = lean_ctx::core::data_dir::isolated_data_dir();
    let (_server, client) = connect(true).await;
    let info = client.peer_info().expect("initialize result");
    assert!(info.capabilities.supports_tasks());
}

#[tokio::test(flavor = "multi_thread")]
async fn a_client_without_the_extension_gets_the_unchanged_tool_result() {
    let _data = lean_ctx::core::data_dir::isolated_data_dir();
    let (server, client) = connect(false).await;
    // The one-time `lean-ctx setup` tip goes on a server's first result only,
    // and only on a machine without host guidance (CI runners): mark it shown
    // so the two calls compared below are the same call.
    server
        .rules_tip_shown
        .store(true, std::sync::atomic::Ordering::Relaxed);
    let request = shell_args("sleep 600 # GH1722_NO_TASKS", Some(900_000));

    let response = client
        .call_tool_once(request.clone())
        .await
        .expect("tools/call");
    let CallToolResponse::Complete(result) = response else {
        panic!("no tasks extension, no task: {response:?}");
    };
    let structured = result.structured_content.clone().expect("structured ack");
    let job_id = structured["jobId"].as_str().expect("job id").to_string();
    let _job = JobGuard(job_id.clone());
    assert_eq!(structured["state"], serde_json::json!("running"));

    // Byte-identical to the pipeline's own reply for the same launch (the
    // identical running job coalesces onto the same id).
    let direct = server
        .call_tool_guarded(request)
        .await
        .expect("direct pipeline call");
    // rmcp strips the SEP-2322 `resultType` discriminator for a peer on a
    // protocol version without it; everything else is the same reply.
    assert_eq!(
        serde_json::to_value(&result).unwrap(),
        without_result_type(serde_json::to_value(&direct).unwrap())
    );

    // Task methods are refused for a client that never declared the extension.
    let refused = error_of(get(&client, &job_id).await.unwrap_err());
    assert_eq!(refused.code.0, -32021, "{refused:?}");
}

#[tokio::test(flavor = "multi_thread")]
async fn a_successful_job_completes_with_the_status_poll_result() {
    let _data = lean_ctx::core::data_dir::isolated_data_dir();
    let (_server, client) = connect(true).await;
    let task_id = launch_task(&client, "printf GH1722_OK", None).await;
    let _job = JobGuard(task_id.clone());

    let settled = settle(&client, &task_id).await;
    let result = completed_result(&settled).clone();
    assert_ne!(result.get("isError"), Some(&serde_json::json!(true)));
    let structured = &result["structuredContent"];
    assert_eq!(structured["state"], serde_json::json!("completed"));
    assert_eq!(structured["exitCode"], serde_json::json!(0));
    assert_eq!(structured["jobId"], serde_json::json!(job_of(&task_id)));
    assert!(text_of(&result).contains("GH1722_OK"), "{result:?}");

    // Repeated reads return the same terminal reply.
    let again = get(&client, &task_id).await.expect("tasks/get again");
    assert_eq!(
        serde_json::to_string(&settled).unwrap(),
        serde_json::to_string(&again).unwrap()
    );

    // The polling API keeps working on the same job and returns the same
    // tool result the task carries.
    let polled = client
        .call_tool(poll_args("status", &job_of(&task_id)))
        .await
        .expect("status poll");
    assert_eq!(
        serde_json::to_value(&polled).unwrap(),
        without_result_type(serde_json::Value::Object(result))
    );
}

#[tokio::test(flavor = "multi_thread")]
async fn a_non_zero_exit_completes_with_an_error_result() {
    let _data = lean_ctx::core::data_dir::isolated_data_dir();
    let (_server, client) = connect(true).await;
    let task_id = launch_task(&client, "ls /gh1722-no-such-directory", None).await;
    let _job = JobGuard(task_id.clone());

    let settled = settle(&client, &task_id).await;
    let result = completed_result(&settled);
    assert_eq!(result.get("isError"), Some(&serde_json::json!(true)));
    let structured = &result["structuredContent"];
    assert_eq!(structured["state"], serde_json::json!("failed"));
    let exit = structured["exitCode"].as_i64().expect("exit code");
    assert_ne!(exit, 0);
}

#[tokio::test(flavor = "multi_thread")]
async fn a_timed_out_job_completes_with_exit_124() {
    let _data = lean_ctx::core::data_dir::isolated_data_dir();
    let (_server, client) = connect(true).await;
    let task_id = launch_task(&client, "sleep 30 # GH1722_TIMEOUT", Some(300)).await;
    let _job = JobGuard(task_id.clone());

    let settled = settle(&client, &task_id).await;
    let result = completed_result(&settled);
    assert_eq!(result.get("isError"), Some(&serde_json::json!(true)));
    assert_eq!(
        result["structuredContent"]["exitCode"],
        serde_json::json!(124)
    );
}

#[tokio::test(flavor = "multi_thread")]
async fn tasks_cancel_kills_the_job_and_settles_cancelled() {
    let _data = lean_ctx::core::data_dir::isolated_data_dir();
    let (_server, client) = connect(true).await;
    let task_id = launch_task(&client, "sleep 600 # GH1722_CANCEL", Some(900_000)).await;
    let _job = JobGuard(task_id.clone());

    let working = get(&client, &task_id).await.expect("tasks/get");
    assert_eq!(working.task.task.status, TaskStatus::Working);
    assert!(matches!(working.task.payload, TaskPayload::Working));

    client
        .cancel_task(CancelTaskParams::new(&task_id))
        .await
        .expect("tasks/cancel");

    let settled = settle(&client, &task_id).await;
    assert_eq!(settled.task.task.status, TaskStatus::Cancelled);
    assert!(matches!(settled.task.payload, TaskPayload::Cancelled));
    assert!(matches!(
        background_shell::status(&job_of(&task_id)),
        Some(JobState::Cancelled { .. })
    ));

    // Cancelling a settled task is a benign no-op, as in the polling API.
    client
        .cancel_task(CancelTaskParams::new(&task_id))
        .await
        .expect("cancel of a cancelled task");
}

#[tokio::test(flavor = "multi_thread")]
async fn an_evicted_job_is_an_explicit_error() {
    let _data = lean_ctx::core::data_dir::isolated_data_dir();
    let (_server, client) = connect(true).await;
    let task_id = launch_task(&client, "printf GH1722_EVICT", None).await;
    let _job = JobGuard(task_id.clone());

    background_shell::remove_for_test(&job_of(&task_id));

    let error = error_of(get(&client, &task_id).await.unwrap_err());
    assert_eq!(error.code.0, -32602, "{error:?}");
    assert_eq!(
        error_code_of(&error).as_deref(),
        Some(shell_tasks::TASK_EVICTED)
    );
    let error = error_of(
        client
            .cancel_task(CancelTaskParams::new(&task_id))
            .await
            .unwrap_err(),
    );
    assert_eq!(
        error_code_of(&error).as_deref(),
        Some(shell_tasks::TASK_EVICTED)
    );
}

#[tokio::test(flavor = "multi_thread")]
async fn an_unknown_task_id_is_an_explicit_error() {
    let _data = lean_ctx::core::data_dir::isolated_data_dir();
    let (_server, client) = connect(true).await;

    for task_id in [
        "shell_0000000000000000",
        "shell_0000000000000000@g1",
        "not-a-task",
    ] {
        let error = error_of(get(&client, task_id).await.unwrap_err());
        assert_eq!(error.code.0, -32602, "{error:?}");
        assert_eq!(
            error_code_of(&error).as_deref(),
            Some(shell_tasks::TASK_NOT_FOUND)
        );
        let error = error_of(
            client
                .cancel_task(CancelTaskParams::new(task_id))
                .await
                .unwrap_err(),
        );
        assert_eq!(
            error_code_of(&error).as_deref(),
            Some(shell_tasks::TASK_NOT_FOUND)
        );
    }
}

#[tokio::test(flavor = "multi_thread")]
async fn a_status_poll_and_a_foreground_call_never_become_tasks() {
    let _data = lean_ctx::core::data_dir::isolated_data_dir();
    let (_server, client) = connect(true).await;
    let task_id = launch_task(&client, "sleep 600 # GH1722_POLL", Some(900_000)).await;
    let _job = JobGuard(task_id.clone());

    // A poll of a running job also reports `state: running`; it stays a tool
    // result and keeps the existing explicit polling contract.
    let response = client
        .call_tool_once(poll_args("status", &job_of(&task_id)))
        .await
        .expect("status poll");
    let CallToolResponse::Complete(polled) = response else {
        panic!("a poll is never a task: {response:?}");
    };
    let structured = polled.structured_content.expect("structured poll");
    assert_eq!(structured["state"], serde_json::json!("running"));
    assert_eq!(structured["jobId"], serde_json::json!(job_of(&task_id)));

    // Unknown job ids keep the polling path's explicit lookup error.
    let response = client
        .call_tool_once(poll_args("status", "shell_ffffffffffffffff"))
        .await
        .expect("status poll of an unknown job");
    let CallToolResponse::Complete(missing) = response else {
        panic!("a lookup error is a tool result: {response:?}");
    };
    assert_eq!(
        missing.structured_content.expect("lookup error")["errorCode"],
        serde_json::json!("background_job_not_found_or_expired")
    );

    // A command that finishes in the foreground returns its result directly.
    let mut args = serde_json::Map::new();
    args.insert("command".into(), serde_json::json!("printf GH1722_FG"));
    let response = client
        .call_tool_once(CallToolRequestParams::new("ctx_shell").with_arguments(args))
        .await
        .expect("foreground call");
    assert!(
        matches!(response, CallToolResponse::Complete(_)),
        "{response:?}"
    );
}

#[tokio::test(flavor = "multi_thread")]
async fn a_gate_refusal_is_a_tool_result_and_starts_no_job() {
    let _data = lean_ctx::core::data_dir::isolated_data_dir();
    lean_ctx::test_env::set_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE", "echo");
    lean_ctx::test_env::set_var("LEAN_CTX_SHELL_SECURITY", "enforce");
    lean_ctx::test_env::remove_var("LEAN_CTX_SHELL_APPROVAL");
    let (_server, client) = connect(true).await;

    let response = client
        .call_tool_once(shell_args("uname # GH1722_GATE", None))
        .await;

    lean_ctx::test_env::remove_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE");
    lean_ctx::test_env::remove_var("LEAN_CTX_SHELL_SECURITY");
    let CallToolResponse::Complete(result) = response.expect("tools/call") else {
        panic!("a refused launch is never a task");
    };
    let text: String = result
        .content
        .iter()
        .filter_map(|block| block.as_text().map(|t| t.text.clone()))
        .collect();
    assert!(
        text.contains("not in the shell allowlist") || text.contains("BLOCKED"),
        "{text}"
    );
}

#[tokio::test(flavor = "multi_thread")]
async fn a_rerun_of_the_same_command_is_a_new_task_and_the_old_one_stays_settled() {
    let _data = lean_ctx::core::data_dir::isolated_data_dir();
    let (_server, client) = connect(true).await;
    let first = launch_task(&client, "printf GH1722_RERUN", None).await;
    let _first = JobGuard(first.clone());
    let settled = settle(&client, &first).await;
    assert_eq!(settled.task.task.status, TaskStatus::Completed);

    // The identical command reuses the content-addressed job id with a new
    // generation: a new task, never the old one back in `working`.
    let second = launch_task(&client, "printf GH1722_RERUN", None).await;
    let _second = JobGuard(second.clone());
    assert_eq!(job_of(&first), job_of(&second));
    assert_ne!(first, second);

    let error = error_of(get(&client, &first).await.unwrap_err());
    assert_eq!(
        error_code_of(&error).as_deref(),
        Some(shell_tasks::TASK_EVICTED),
        "{error:?}"
    );
    let settled = settle(&client, &second).await;
    assert!(text_of(completed_result(&settled)).contains("GH1722_RERUN"));
}

#[tokio::test(flavor = "multi_thread")]
async fn tasks_get_runs_under_the_callers_rights_and_serves_nothing_cached() {
    use crate::tools::registered::ctx_execute::session_rights_fixture::developer;
    let _data = lean_ctx::core::data_dir::isolated_data_dir();
    let (server, client) = connect(true).await;
    let task_id = launch_task(&client, "printf GH1722_PRIVATE", None).await;
    let _job = JobGuard(task_id.clone());
    // Settle it for the launching session first, so a cache would hold it.
    let settled = settle(&client, &task_id).await;
    assert!(text_of(completed_result(&settled)).contains("GH1722_PRIVATE"));

    // Another session whose rights deny ctx_shell learns nothing.
    let denied = developer(&["ctx_shell"]);
    let error = shell_tasks::get(&server, &task_id, denied.state())
        .await
        .expect_err("a caller whose rights deny ctx_shell is refused");
    let rendered = format!("{error:?}");
    assert!(!rendered.contains("GH1722_PRIVATE"), "{rendered}");
    let error = shell_tasks::cancel(&server, &task_id, denied.state())
        .await
        .expect_err("cancel is refused too");
    assert!(!format!("{error:?}").contains("GH1722_PRIVATE"));

    // The launching session still reads it.
    let again = settle(&client, &task_id).await;
    assert!(text_of(completed_result(&again)).contains("GH1722_PRIVATE"));
    // The embedded tool result carries no SEP-2322 reply marker.
    assert!(completed_result(&again).get("resultType").is_none());
}

/// A tool result without the SEP-2322 `resultType` discriminator, which rmcp
/// strips on the wire for a peer whose protocol version predates it.
fn without_result_type(mut value: serde_json::Value) -> serde_json::Value {
    if let Some(object) = value.as_object_mut() {
        object.remove("resultType");
    }
    value
}