lean-ctx-server 3.12.11

The LeanCTX MCP server and its tools on top of LeanCTX | OSS.
Documentation
// SPDX-License-Identifier: Apache-2.0
//! MCP Tasks (SEP-2663, `io.modelcontextprotocol/tasks`) over the existing
//! `ctx_shell` background job registry (GH #1722).
//!
//! This is a protocol view of [`crate::server::background_shell`], not a second
//! job runtime:
//!
//! - A task is only materialised after the ordinary `tools/call` pipeline ran
//!   `ctx_shell` and that call itself started (or auto-detached onto) a
//!   `shell_*` job. Every gate the synchronous path applies — allowlist, path
//!   jail, role, policy, workflow, loop throttle, write doctrine — has already
//!   decided by then; a refused call stays an ordinary tool result.
//! - The task id is the `shell_*` job id plus the job's registry generation
//!   (`shell_…@g<N>`). `ctx_shell(background_action=…)` polling keeps working
//!   on the job id; a later run of the identical command (same content-addressed
//!   job id, new generation) is a new task, so a settled task never returns to
//!   `working`.
//! - Every `tasks/get` and `tasks/cancel` runs the polling call
//!   (`ctx_shell(background_action="status"|"cancel", job_id=…)`) through the
//!   same guarded pipeline under the caller's rights. Nothing about a job is
//!   answered from a cache: a caller the pipeline refuses learns nothing, a
//!   task's result is exactly the tool result a status poll returns (after the
//!   same output admission), and cancellation passes the same gates.
//! - Clients that did not declare the extension never reach this module: the
//!   `tools/call` reply is unchanged, byte for byte.
//!
//! State mapping (SEP-2663 `TaskStatus`):
//!
//! | job / poll state                       | task status | payload                     |
//! |----------------------------------------|-------------|-----------------------------|
//! | running (incl. cancel requested)       | `working`   | —                           |
//! | completed, exit 0                      | `completed` | `result`: the status poll   |
//! | completed, exit ≠ 0 (incl. timeout 124)| `completed` | `result` with `isError:true`|
//! | cancelled                              | `cancelled` | —                           |
//! | evicted / expired / newer run of the id| JSON-RPC `-32602`, `errorCode: background_job_not_found_or_expired` |
//! | never issued as a task                 | JSON-RPC `-32602`, `errorCode: task_not_found` |
//!
//! SEP-2663 reserves `failed` for a request that failed with a JSON-RPC error.
//! A shell command's own failure is a tool result with `isError: true`, so it
//! settles as `completed`, as the spec requires.

use std::collections::HashMap;
use std::sync::{LazyLock, Mutex};

use rmcp::ErrorData;
use rmcp::model::{
    CallToolRequestParams, CallToolResult, CreateTaskResult, DetailedTask, GetTaskResult,
    JsonObject, Task, TaskPayload, TaskStatus,
};

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

/// Suggested `tasks/get` interval. Shell jobs are long work; a faster poll only
/// costs the client round trips.
pub(crate) const POLL_INTERVAL_MS: u64 = 2_000;

/// Upper bound on remembered task handles. The job registry itself keeps at
/// most 64 finished jobs, so older handles could only report eviction anyway.
const MAX_TASK_HANDLES: usize = 256;

/// Error code for a task id this server never issued.
pub(crate) const TASK_NOT_FOUND: &str = "task_not_found";
/// Error code for a task whose job left the registry (same code the polling
/// path reports for an evicted job).
pub(crate) const TASK_EVICTED: &str = "background_job_not_found_or_expired";

/// Separates the job id from the registry generation in a task id.
const GENERATION_SEP: &str = "@g";

struct Handle {
    created_at: String,
    /// When a `tasks/get` first observed the terminal state. Only the
    /// timestamp is remembered — never the result: every `tasks/get` runs the
    /// status poll under the caller's own rights.
    settled_at: Option<String>,
    /// Insertion order, for bounding the table.
    seq: u64,
}

#[derive(Default)]
struct Table {
    handles: HashMap<String, Handle>,
    next_seq: u64,
}

static TASKS: LazyLock<Mutex<Table>> = LazyLock::new(|| Mutex::new(Table::default()));

fn table() -> std::sync::MutexGuard<'static, Table> {
    TASKS
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
}

/// The task id of one run of a job: the `shell_*` job id plus the registry
/// generation. A later launch of the identical command reuses the
/// content-addressed job id with a new generation, so it gets a new task; the
/// old task reports eviction and can never return to `working`.
fn task_id_for(job_id: &str, generation: u64) -> String {
    format!("{job_id}{GENERATION_SEP}{generation}")
}

/// `(job id, generation)` of a task id this module issued.
fn parse_task_id(task_id: &str) -> Option<(&str, u64)> {
    let (job_id, generation) = task_id.rsplit_once(GENERATION_SEP)?;
    if !job_id.starts_with("shell_") {
        return None;
    }
    Some((job_id, generation.parse().ok()?))
}

fn lookup_error(task_id: &str, code: &str, message: String) -> ErrorData {
    ErrorData::invalid_params(
        message,
        Some(serde_json::json!({ "taskId": task_id, "errorCode": code })),
    )
}

fn unknown_task(task_id: &str) -> ErrorData {
    lookup_error(task_id, TASK_NOT_FOUND, format!("unknown task: {task_id}"))
}

fn evicted_task(task_id: &str) -> ErrorData {
    lookup_error(
        task_id,
        TASK_EVICTED,
        format!("task {task_id}: background job not found or retained terminal verdict expired"),
    )
}

/// Whether a `tools/call` may be answered with a task: a `ctx_shell` call (or
/// its `shell` alias) that runs a command. A `background_action` poll of a
/// running job also reports `state: running`, but it observes a job — it never
/// starts one.
pub(crate) fn is_task_candidate(request: &CallToolRequestParams) -> bool {
    matches!(request.name.as_ref(), "ctx_shell" | "shell")
        && request
            .arguments
            .as_ref()
            .is_none_or(|args| !args.contains_key("background_action"))
}

/// The `shell_*` job a finished `ctx_shell` call started or detached onto, read
/// from the structured launch acknowledgement (`state: running`, `jobId`).
fn started_job(result: &CallToolResult) -> Option<&str> {
    if result.is_error == Some(true) {
        return None;
    }
    let structured = result.structured_content.as_ref()?;
    if structured.get("state")?.as_str()? != "running" {
        return None;
    }
    structured
        .get("jobId")?
        .as_str()
        .filter(|id| id.starts_with("shell_"))
}

/// Whether a handle can be dropped without losing a live task: its job run
/// finished, or left the registry.
fn is_settled(task_id: &str) -> bool {
    let Some((job_id, generation)) = parse_task_id(task_id) else {
        return true;
    };
    background_shell::snapshot(job_id).is_none_or(|snapshot| {
        snapshot.generation != generation || !matches!(snapshot.state, JobState::Running { .. })
    })
}

/// Turn a `ctx_shell` launch acknowledgement into a task handle. `None` keeps
/// the ordinary result: the call started no job, the job is already gone, or
/// every remembered task is still running and the table is full.
pub(crate) fn materialize(result: &CallToolResult) -> Option<CreateTaskResult> {
    let job_id = started_job(result)?;
    let snapshot = background_shell::snapshot(job_id)?;
    let task_id = task_id_for(job_id, snapshot.generation);
    let mut table = table();
    if !table.handles.contains_key(&task_id) && !make_room(&mut table) {
        return None;
    }
    let seq = table.next_seq;
    table.next_seq += 1;
    // A coalesced launch of the same running job keeps its handle.
    let handle = table
        .handles
        .entry(task_id.clone())
        .or_insert_with(|| Handle {
            created_at: rmcp::task_manager::current_timestamp(),
            settled_at: None,
            seq,
        });
    Some(CreateTaskResult::new(base_task(
        &task_id,
        handle,
        TaskStatus::Working,
    )))
}

/// Free one slot below [`MAX_TASK_HANDLES`], dropping the oldest settled
/// handle. A running task is never forgotten: when every handle is live, the
/// call keeps its ordinary launch acknowledgement instead (`false`).
fn make_room(table: &mut Table) -> bool {
    if table.handles.len() < MAX_TASK_HANDLES {
        return true;
    }
    let mut by_age: Vec<(u64, String)> = table
        .handles
        .iter()
        .map(|(id, handle)| (handle.seq, id.clone()))
        .collect();
    by_age.sort_unstable();
    for (_, id) in by_age {
        if is_settled(&id) {
            table.handles.remove(&id);
            if table.handles.len() < MAX_TASK_HANDLES {
                return true;
            }
        }
    }
    table.handles.len() < MAX_TASK_HANDLES
}

fn base_task(task_id: &str, handle: &Handle, status: TaskStatus) -> Task {
    let updated = handle
        .settled_at
        .clone()
        .unwrap_or_else(|| handle.created_at.clone());
    let mut task = Task::new(task_id, status, handle.created_at.clone(), updated)
        .with_poll_interval_ms(POLL_INTERVAL_MS);
    // Retention follows the job registry (bounded by count and bytes, not by
    // a fixed lifetime): eviction is reported explicitly instead.
    task.ttl_ms = None;
    task
}

/// The job run a task names, if it is still the one in the registry.
/// `Ok(job id)`, else the explicit lookup error.
fn current_job(task_id: &str) -> Result<&str, ErrorData> {
    if !table().handles.contains_key(task_id) {
        return Err(unknown_task(task_id));
    }
    let (job_id, generation) = parse_task_id(task_id).ok_or_else(|| unknown_task(task_id))?;
    match background_shell::snapshot(job_id) {
        Some(snapshot) if snapshot.generation == generation => Ok(job_id),
        _ => Err(evicted_task(task_id)),
    }
}

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

/// The polling call through the ordinary guarded pipeline, under the rights
/// bound to the tasks request. A panic becomes an internal error, as it does
/// for an ordinary `tools/call`.
async fn run_poll(
    server: &LeanCtxServer,
    task_id: &str,
    job_id: &str,
    action: &str,
    rights: lean_ctx::core::session_rights::State,
) -> Result<CallToolResult, ErrorData> {
    use futures::FutureExt as _;
    let poll = lean_ctx::core::session_rights::scope(
        rights,
        server.call_tool_guarded(poll_request(job_id, action)),
    );
    let Ok(result) = std::panic::AssertUnwindSafe(poll).catch_unwind().await else {
        // The panic message can quote job output; the log names the event only.
        tracing::error!("tasks poll panicked (tool_panic)");
        return Err(ErrorData::internal_error(
            format!("task {task_id}: the ctx_shell {action} call failed"),
            Some(serde_json::json!({ "taskId": task_id })),
        ));
    };
    result
}

/// A poll reply the pipeline refused (gate, throttle) carries no job state.
fn refused_poll(task_id: &str, result: &CallToolResult) -> ErrorData {
    let text: String = result
        .content
        .iter()
        .filter_map(|block| block.as_text().map(|text| text.text.clone()))
        .collect();
    ErrorData::internal_error(
        format!("task {task_id}: the ctx_shell status call was refused: {text}"),
        Some(serde_json::json!({ "taskId": task_id })),
    )
}

/// The tool result as a task's `result`. The SEP-2322 `resultType` marker
/// belongs to a `tools/call` reply, not to the embedded result.
fn result_object(task_id: &str, result: &CallToolResult) -> Result<JsonObject, ErrorData> {
    match serde_json::to_value(result) {
        Ok(serde_json::Value::Object(mut object)) => {
            object.remove("resultType");
            Ok(object)
        }
        Ok(_) => Err(ErrorData::internal_error(
            format!("task {task_id}: the tool result did not serialize to an object"),
            None,
        )),
        Err(err) => Err(ErrorData::internal_error(err.to_string(), None)),
    }
}

/// SEP-2663 `tasks/get`. Every call — running or finished — runs the status
/// poll through the guarded pipeline under the caller's rights, so a caller
/// the pipeline refuses learns nothing about the task, and the result passes
/// the same output admission as a status poll.
pub(crate) async fn get(
    server: &LeanCtxServer,
    task_id: &str,
    rights: lean_ctx::core::session_rights::State,
) -> Result<GetTaskResult, ErrorData> {
    let job_id = current_job(task_id)?;
    let result = run_poll(server, task_id, job_id, "status", rights).await?;
    // The id may have been reused between the lookup and the poll; the
    // generation is monotonic, so an unchanged one means the poll saw this run.
    current_job(task_id)?;
    let structured = result.structured_content.as_ref();
    if structured.is_some_and(|value| value.get("errorCode").is_some()) {
        return Err(evicted_task(task_id));
    }
    let state = structured
        .and_then(|value| value.get("state"))
        .and_then(|value| value.as_str());
    let payload = match state {
        Some("completed" | "failed") => TaskPayload::Completed {
            result: result_object(task_id, &result)?,
        },
        Some("cancelled") => TaskPayload::Cancelled,
        Some("running") => TaskPayload::Working,
        _ => return Err(refused_poll(task_id, &result)),
    };

    let mut table = table();
    let handle = table
        .handles
        .get_mut(task_id)
        .ok_or_else(|| evicted_task(task_id))?;
    if !matches!(payload, TaskPayload::Working) && handle.settled_at.is_none() {
        handle.settled_at = Some(rmcp::task_manager::current_timestamp());
    }
    let task = base_task(task_id, handle, payload.status());
    Ok(GetTaskResult::new(DetailedTask::new(task, payload)))
}

/// SEP-2663 `tasks/cancel`: the `background_action="cancel"` call through the
/// guarded pipeline. Cancelling a finished task is a benign no-op, as in the
/// polling API; the next `tasks/get` reports the settled state.
pub(crate) async fn cancel(
    server: &LeanCtxServer,
    task_id: &str,
    rights: lean_ctx::core::session_rights::State,
) -> Result<(), ErrorData> {
    let job_id = current_job(task_id)?;
    let result = run_poll(server, task_id, job_id, "cancel", rights).await?;
    let structured = result.structured_content.as_ref();
    if structured.is_some_and(|value| value.get("state").is_some()) {
        // A reused id after the lookup: this task's run is gone either way.
        current_job(task_id)?;
        return Ok(());
    }
    // The job left the registry between the lookup and the cancel: the polling
    // path answers that benignly (`not found — already finished or cancelled`).
    current_job(task_id)?;
    Err(refused_poll(task_id, &result))
}

/// SEP-2663 `tasks/update`: shell tasks never ask for input (`input_required`
/// is never reported), so there is nothing to route. Unknown keys are ignored
/// per spec; an unknown or evicted task is still an explicit error.
pub(crate) fn update(task_id: &str) -> Result<(), ErrorData> {
    current_job(task_id).map(|_| ())
}

/// The rights the shared daemon bound to this request, else this process's own.
pub(crate) fn request_rights(
    context: &rmcp::service::RequestContext<rmcp::service::RoleServer>,
) -> lean_ctx::core::session_rights::State {
    context
        .extensions
        .get::<lean_ctx::core::session_rights::RequestRights>()
        .map_or_else(lean_ctx::core::session_rights::current, |bound| {
            bound.0.clone()
        })
}

#[cfg(all(test, unix))]
pub(crate) fn forget_for_test(task_id: &str) {
    table().handles.remove(task_id);
}