Skip to main content

lean_ctx_server/tools/registered/
ctx_session.rs

1// SPDX-License-Identifier: Apache-2.0
2use rmcp::ErrorData;
3use rmcp::model::Tool;
4use serde_json::{Map, Value, json};
5use std::time::Duration;
6
7use crate::server::tool_trait::{McpTool, ToolContext, ToolOutput, get_bool, get_str};
8use lean_ctx::tool_defs::tool_def;
9
10/// #1570 P1: `compact` records a directive (summary in `value`) for this
11/// server's app session (`LEAN_CTX_SESSION_ID`); the proxy replaces the
12/// pre-cut span on that session's requests until `restore` clears it —
13/// lossless by construction since the client resends full history each turn.
14/// The reply says "armed" only when a proxy carries the session; otherwise
15/// nothing is armed and the reply says why.
16fn handle_compact_action(
17    action: &str,
18    value: Option<&str>,
19    args: &Map<String, Value>,
20) -> ToolOutput {
21    let session = lean_ctx::core::activity::session_id_from_env();
22    let text = if action == "restore" {
23        match session.as_deref() {
24            Some(session) if lean_ctx_ext::core::compact_directive::clear(session) => {
25                "Compaction cleared — the next request carries the full original history again."
26                    .to_string()
27            }
28            _ => "No active compaction to restore.".to_string(),
29        }
30    } else if session.is_none() && value.is_some_and(|v| !v.is_empty()) {
31        "Compaction not armed: this MCP server has no app session id \
32         (LEAN_CTX_SESSION_ID), so no proxy can key a compaction to your session. \
33         Your context stays as it is."
34            .to_string()
35    } else if let Some(session) = session.as_deref()
36        && value.is_some_and(|v| !v.is_empty())
37        && !lean_ctx_ext::core::compact_directive::is_carried(session)
38    {
39        "Compaction not armed: no proxy carries this session (no request with its \
40         session id reached a LeanCTX proxy recently), and only a proxy can shorten \
41         the conversation. Run the agent through the proxy, then compact again. \
42         Your context stays as it is."
43            .to_string()
44    } else {
45        let session = session.unwrap_or_default();
46        let keep = args
47            .get("keep_recent_turns")
48            .and_then(serde_json::Value::as_u64)
49            .map_or(6, |n| n as usize)
50            .max(4);
51        match value {
52            None | Some("") => "compact requires value = the summary that replaces the \
53                 compacted span. Write it exhaustive-but-lean: every file path, decision, \
54                 constraint and finding that keeps context integrity; quote short user \
55                 requests verbatim; drop dead-end exploration."
56                .to_string(),
57            Some(summary) => {
58                match lean_ctx_ext::core::compact_directive::create(
59                    &session,
60                    keep,
61                    summary.to_string(),
62                ) {
63                    Ok(()) => format!(
64                        "Compaction armed (keeps last {keep} user turns verbatim). It applies \
65                         to your NEXT request onward, only outside the provider-cached \
66                         prefix, at tool-pair-safe boundaries. Undo any time: \
67                         ctx_session action=\"restore\"."
68                    ),
69                    Err(reason) => reason,
70                }
71            }
72        }
73    };
74    ToolOutput {
75        text,
76        original_tokens: 0,
77        saved_tokens: 0,
78        mode: Some(action.to_string()),
79        path: None,
80        changed: false,
81        shell_outcome: None,
82        content_blocks: None,
83    }
84}
85
86pub struct CtxSessionTool;
87
88/// Session management is useful, but it must never make the entire MCP server
89/// wait behind a long-lived writer. Explicitly retryable operations fail fast.
90const SESSION_LOCK_BUDGET: Duration = Duration::from_millis(250);
91
92fn session_matches_snapshot(
93    live: &lean_ctx::core::session::SessionState,
94    snapshot: &lean_ctx::core::session::SessionState,
95) -> bool {
96    live.id == snapshot.id
97        && live.version == snapshot.version
98        && live.project_root == snapshot.project_root
99        && live.shell_cwd == snapshot.shell_cwd
100        && live.extra_roots == snapshot.extra_roots
101}
102
103impl McpTool for CtxSessionTool {
104    fn name(&self) -> &'static str {
105        "ctx_session"
106    }
107
108    fn tool_def(&self) -> Tool {
109        tool_def(
110            "ctx_session",
111            "Session memory. save at session end, load at start, status = snapshot;\n\
112             task|finding|decision record progress (value=text).\n\
113             ANTIPATTERN: permanent project knowledge → ctx_knowledge.",
114            json!({
115                "type": "object",
116                "properties": {
117                    "action": {
118                        "type": "string",
119                        "description": "status|handoff|load|save|task|finding|decision|compact|restore|list|… (invalid action lists all)"
120                    },
121                    "value": { "type": "string" },
122                    "tag": { "type": "string", "enum": ["note", "dead_end"], "description": "finding: dead_end = tried and abandoned" },
123                    "keep_recent_turns": { "type": "integer", "description": "compact: trailing user turns kept verbatim (default 6)" },
124                    "session_id": { "type": "string", "description": "Omit for your own session" }
125                },
126                "required": ["action"]
127            }),
128        )
129    }
130
131    fn handle(
132        &self,
133        args: &Map<String, Value>,
134        ctx: &ToolContext,
135    ) -> Result<ToolOutput, ErrorData> {
136        let action = get_str(args, "action")
137            .ok_or_else(|| ErrorData::invalid_params("action is required", None))?;
138        let value = get_str(args, "value");
139        let sid = get_str(args, "session_id");
140        let format = get_str(args, "format");
141        let path = get_str(args, "path");
142        let write = get_bool(args, "write").unwrap_or(false);
143        let privacy = get_str(args, "privacy");
144        let terse = get_bool(args, "terse");
145        let dead_end = match get_str(args, "tag").as_deref() {
146            None | Some("note") => false,
147            Some("dead_end") => true,
148            Some(_) => {
149                return Err(ErrorData::invalid_params(
150                    "tag must be note or dead_end",
151                    None,
152                ));
153            }
154        };
155
156        // Restore is content-free. Compact summaries are admitted against a
157        // detached, trusted session scope before the directive reaches disk.
158        if action == "restore" {
159            return Ok(handle_compact_action(&action, value.as_deref(), args));
160        }
161        if action == "compact" {
162            let Some(summary) = value.as_deref().filter(|summary| !summary.is_empty()) else {
163                return Ok(handle_compact_action(&action, value.as_deref(), args));
164            };
165            let session_handle = ctx
166                .session
167                .as_ref()
168                .ok_or_else(|| ErrorData::internal_error("session not available", None))?;
169            let Some(snapshot) = crate::server::bounded_lock::read_for(
170                session_handle,
171                "ctx_session compact admission snapshot",
172                SESSION_LOCK_BUDGET,
173            )
174            .map(|session| session.clone()) else {
175                return Err(ErrorData::internal_error(
176                    "session is busy; retry the operation",
177                    None,
178                ));
179            };
180            let admitted =
181                lean_ctx::core::session::admission::admit_storable_session_text(&snapshot, summary)
182                    .map_err(|_| {
183                        ErrorData::invalid_params(
184                            "compact summary withheld by current policy",
185                            None,
186                        )
187                    })?;
188            return Ok(handle_compact_action(&action, Some(&admitted), args));
189        }
190
191        let tool_calls_handle = ctx
192            .tool_calls
193            .as_ref()
194            .ok_or_else(|| ErrorData::internal_error("tool_calls not available", None))?;
195        let call_durations: Vec<(String, u64)> = crate::server::bounded_lock::read_for(
196            tool_calls_handle,
197            "ctx_session tool-call snapshot",
198            SESSION_LOCK_BUDGET,
199        )
200        .map_or_else(Vec::new, |tc| {
201            tc.iter().map(|c| (c.tool.clone(), c.duration_ms)).collect()
202        });
203        let agent_id = ctx
204            .agent_id
205            .as_ref()
206            .and_then(|agent_id| agent_id.try_read().ok().and_then(|id| id.clone()));
207
208        let result = if let Some(result) = crate::tools::ctx_session::handle_without_session(
209            &action,
210            value.as_deref(),
211            sid.as_deref(),
212        ) {
213            result
214        } else {
215            let session_handle = ctx
216                .session
217                .as_ref()
218                .ok_or_else(|| ErrorData::internal_error("session not available", None))?;
219
220            if action == "save" {
221                let Some(snapshot) = crate::server::bounded_lock::read_for(
222                    session_handle,
223                    "ctx_session save snapshot",
224                    SESSION_LOCK_BUDGET,
225                )
226                .map(|session| session.clone()) else {
227                    return Err(ErrorData::internal_error(
228                        "session is busy; retry the operation",
229                        None,
230                    ));
231                };
232                let result =
233                    match lean_ctx::core::session::SessionState::save_shared_sync(session_handle) {
234                        Err(error) => format!("Save failed: {error}"),
235                        Ok(receipt) if receipt.current => {
236                            format!("Session {} saved (v{}).", receipt.id, receipt.version)
237                        }
238                        Ok(receipt) => format!(
239                            "Session {} snapshot v{} saved; newer session changes remain pending.",
240                            receipt.id, receipt.version
241                        ),
242                    };
243                lean_ctx::core::session::admission::admit_tool_value(&snapshot, &result)
244                    .unwrap_or_else(|_| {
245                        "ERROR: session save result withheld by current policy.".into()
246                    })
247            } else if action == "reset" {
248                let Some(snapshot) = crate::server::bounded_lock::read_for(
249                    session_handle,
250                    "ctx_session reset snapshot",
251                    SESSION_LOCK_BUDGET,
252                )
253                .map(|session| session.clone()) else {
254                    return Err(ErrorData::internal_error(
255                        "session is busy; retry the operation",
256                        None,
257                    ));
258                };
259                let output =
260                    match lean_ctx::core::session::SessionState::save_shared_sync(session_handle) {
261                        Err(error) => {
262                            format!("Reset refused: current session was not saved: {error}")
263                        }
264                        Ok(receipt)
265                            if !receipt.current
266                                || receipt.id != snapshot.id
267                                || receipt.version != snapshot.version =>
268                        {
269                            "Reset refused: session changed while it was being saved; retry.".into()
270                        }
271                        Ok(_) => {
272                            let Some(mut live) = crate::server::bounded_lock::write_for(
273                                session_handle,
274                                "ctx_session reset commit",
275                                SESSION_LOCK_BUDGET,
276                            ) else {
277                                return Err(ErrorData::internal_error(
278                                    "session is busy; retry the operation",
279                                    None,
280                                ));
281                            };
282                            if !session_matches_snapshot(&live, &snapshot)
283                                || !std::sync::Arc::ptr_eq(&live.save_gate, &snapshot.save_gate)
284                            {
285                                return Err(ErrorData::internal_error(
286                                    "session changed during reset; retry the operation",
287                                    None,
288                                ));
289                            }
290                            crate::tools::ctx_session::reset_after_save(&mut live)
291                        }
292                    };
293                lean_ctx::core::session::admission::admit_tool_value(&snapshot, &output)
294                    .unwrap_or_else(|_| "ERROR: reset result withheld by current policy.".into())
295            } else if action == "load" {
296                let Some(snapshot) = crate::server::bounded_lock::read_for(
297                    session_handle,
298                    "ctx_session load snapshot",
299                    SESSION_LOCK_BUDGET,
300                )
301                .map(|session| session.clone()) else {
302                    return Err(ErrorData::internal_error(
303                        "session is busy; retry the operation",
304                        None,
305                    ));
306                };
307                let (candidate, output) =
308                    crate::tools::ctx_session::prepare_load(&snapshot, sid.as_deref()).map_err(
309                        |_| {
310                            ErrorData::invalid_params(
311                                "session load denied by current project scope or content policy",
312                                None,
313                            )
314                        },
315                    )?;
316                let Some(mut live) = crate::server::bounded_lock::write_for(
317                    session_handle,
318                    "ctx_session load commit",
319                    SESSION_LOCK_BUDGET,
320                ) else {
321                    return Err(ErrorData::internal_error(
322                        "session is busy; retry the operation",
323                        None,
324                    ));
325                };
326                if !session_matches_snapshot(&live, &snapshot) {
327                    return Err(ErrorData::internal_error(
328                        "session changed during load; retry the operation",
329                        None,
330                    ));
331                }
332                *live = candidate;
333                output
334            } else if matches!(action.as_str(), "export" | "resume" | "snapshot") {
335                let Some(snapshot) = crate::server::bounded_lock::read_for(
336                    session_handle,
337                    "ctx_session snapshot",
338                    SESSION_LOCK_BUDGET,
339                )
340                .map(|session| session.clone()) else {
341                    return Err(ErrorData::internal_error(
342                        "session is busy; retry the operation",
343                        None,
344                    ));
345                };
346                crate::tools::ctx_session::handle_snapshot_read_action(
347                    &snapshot,
348                    &action,
349                    value.as_deref(),
350                    crate::tools::ctx_session::SessionToolOptions {
351                        format: format.as_deref(),
352                        path: path.as_deref(),
353                        write,
354                        privacy: privacy.as_deref(),
355                        terse,
356                        agent_id: agent_id.as_deref(),
357                    },
358                )
359                .expect("snapshot action is explicitly handled")
360            } else if matches!(action.as_str(), "status" | "show" | "handoff") {
361                let Some(snapshot) = crate::server::bounded_lock::read_for(
362                    session_handle,
363                    "ctx_session read",
364                    SESSION_LOCK_BUDGET,
365                )
366                .map(|session| session.clone()) else {
367                    return Err(ErrorData::internal_error(
368                        "session is busy; retry the operation",
369                        None,
370                    ));
371                };
372                crate::tools::ctx_session::handle_read_only(&snapshot, &action)
373                    .expect("read-only action is explicitly handled")
374            } else if matches!(action.as_str(), "task" | "finding" | "decision" | "list") {
375                let Some(snapshot) = crate::server::bounded_lock::read_for(
376                    session_handle,
377                    "ctx_session admitted action snapshot",
378                    SESSION_LOCK_BUDGET,
379                )
380                .map(|session| session.clone()) else {
381                    return Err(ErrorData::internal_error(
382                        "session is busy; retry the operation",
383                        None,
384                    ));
385                };
386                let prepared = crate::tools::ctx_session::prepare_admitted_action(
387                    &snapshot,
388                    &call_durations,
389                    &action,
390                    value.as_deref(),
391                    sid.as_deref(),
392                    crate::tools::ctx_session::SessionToolOptions {
393                        format: format.as_deref(),
394                        path: path.as_deref(),
395                        write,
396                        privacy: privacy.as_deref(),
397                        terse,
398                        agent_id: agent_id.as_deref(),
399                    },
400                )
401                .map_err(|_| {
402                    ErrorData::invalid_params(
403                        "session action withheld by current project or content policy",
404                        None,
405                    )
406                })?;
407                if matches!(action.as_str(), "task" | "finding" | "decision") {
408                    let candidate = prepared.candidate;
409                    let output = prepared.output;
410                    let Some(mut live) = crate::server::bounded_lock::write_for(
411                        session_handle,
412                        "ctx_session admitted action commit",
413                        SESSION_LOCK_BUDGET,
414                    ) else {
415                        return Err(ErrorData::internal_error(
416                            "session is busy; retry the operation",
417                            None,
418                        ));
419                    };
420                    if !session_matches_snapshot(&live, &snapshot) {
421                        return Err(ErrorData::internal_error(
422                            "session changed during content admission; retry the operation",
423                            None,
424                        ));
425                    }
426                    if !prepared.store_admission.is_current() {
427                        return Err(ErrorData::internal_error(
428                            "session policy changed during content admission; retry the operation",
429                            None,
430                        ));
431                    }
432                    *live = candidate.clone();
433                    drop(live);
434                    // The finding as the session keeps it (admitted, redacted)
435                    // becomes one of the session episode's dead ends.
436                    if dead_end
437                        && action == "finding"
438                        && let Some(finding) = candidate.findings.last()
439                    {
440                        lean_ctx_cloud::capture::episode::note_dead_end(
441                            &candidate.id,
442                            &finding.summary,
443                        );
444                    }
445                    lean_ctx::core::session::admission::admit_tool_value(&candidate, &output)
446                        .unwrap_or_else(|_| "[lean-ctx gateway: session content withheld]".into())
447                } else {
448                    if !prepared.store_admission.is_current() {
449                        return Err(ErrorData::internal_error(
450                            "session policy changed during content admission; retry the operation",
451                            None,
452                        ));
453                    }
454                    prepared.output
455                }
456            } else {
457                let Some(mut session) = crate::server::bounded_lock::write_for(
458                    session_handle,
459                    "ctx_session write",
460                    SESSION_LOCK_BUDGET,
461                ) else {
462                    return Err(ErrorData::internal_error(
463                        "session is busy; retry the operation",
464                        None,
465                    ));
466                };
467                crate::tools::ctx_session::handle(
468                    &mut session,
469                    &call_durations,
470                    &action,
471                    value.as_deref(),
472                    sid.as_deref(),
473                    crate::tools::ctx_session::SessionToolOptions {
474                        format: format.as_deref(),
475                        path: path.as_deref(),
476                        write,
477                        privacy: privacy.as_deref(),
478                        terse,
479                        agent_id: agent_id.as_deref(),
480                    },
481                )
482            }
483        };
484
485        Ok(ToolOutput {
486            text: result,
487            original_tokens: 0,
488            saved_tokens: 0,
489            mode: Some(action),
490            path: None,
491            changed: false,
492            shell_outcome: None,
493            content_blocks: None,
494        })
495    }
496
497    // No action declares `publishes_every_source` (the trait default applies).
498    // `status` and `show` print a counters line and `Root: <project>`: that
499    // is session-derived context, which is neither published into the call's
500    // source capture nor marks it incomplete, so their reply cannot claim a
501    // complete source set. A session reply is therefore never registered in
502    // the delivered-lineage register. The delivery calls stay
503    // (`SessionState::format_compact_delivered`, `finding_served`): a finding
504    // bound to a source that no longer admits is left out of the reply.
505}