Skip to main content

lean_ctx/tools/registered/
ctx_session.rs

1use rmcp::ErrorData;
2use rmcp::model::Tool;
3use serde_json::{Map, Value, json};
4use std::time::Duration;
5
6use crate::server::tool_trait::{McpTool, ToolContext, ToolOutput, get_bool, get_str};
7use crate::tool_defs::tool_def;
8
9/// #1570 P1: `compact` records a directive (summary in `value`); the proxy
10/// replaces the pre-cut span on every request until `restore` clears it —
11/// lossless by construction since the client resends full history each turn.
12fn handle_compact_action(
13    action: &str,
14    value: Option<&str>,
15    args: &Map<String, Value>,
16) -> ToolOutput {
17    let text = if action == "restore" {
18        if crate::core::compact_directive::clear() {
19            "Compaction cleared — the next request carries the full original history again."
20                .to_string()
21        } else {
22            "No active compaction to restore.".to_string()
23        }
24    } else {
25        let keep = args
26            .get("keep_recent_turns")
27            .and_then(serde_json::Value::as_u64)
28            .map_or(6, |n| n as usize)
29            .max(4);
30        match value {
31            None | Some("") => "compact requires value = the summary that replaces the \
32                 compacted span. Write it exhaustive-but-lean: every file path, decision, \
33                 constraint and finding that keeps context integrity; quote short user \
34                 requests verbatim; drop dead-end exploration."
35                .to_string(),
36            Some(summary) => {
37                match crate::core::compact_directive::create(keep, summary.to_string()) {
38                    Ok(()) => {
39                        crate::core::nudge::record_recovery();
40                        format!(
41                            "Compaction armed (keeps last {keep} user turns verbatim). It applies \
42                         to your NEXT request onward, only outside the provider-cached \
43                         prefix, at tool-pair-safe boundaries. Undo any time: \
44                         ctx_session action=\"restore\"."
45                        )
46                    }
47                    Err(reason) => reason,
48                }
49            }
50        }
51    };
52    ToolOutput {
53        text,
54        original_tokens: 0,
55        saved_tokens: 0,
56        mode: Some(action.to_string()),
57        path: None,
58        changed: false,
59        shell_outcome: None,
60        content_blocks: None,
61    }
62}
63
64pub struct CtxSessionTool;
65
66/// Session management is useful, but it must never make the entire MCP server
67/// wait behind a long-lived writer. Explicitly retryable operations fail fast.
68const SESSION_LOCK_BUDGET: Duration = Duration::from_millis(250);
69
70impl McpTool for CtxSessionTool {
71    fn name(&self) -> &'static str {
72        "ctx_session"
73    }
74
75    fn tool_def(&self) -> Tool {
76        tool_def(
77            "ctx_session",
78            "Session memory. save at session end, load at start, status = snapshot;\n\
79             task|finding|decision record progress (value=text).\n\
80             ANTIPATTERN: permanent project knowledge → ctx_knowledge.",
81            json!({
82                "type": "object",
83                "properties": {
84                    "action": {
85                        "type": "string",
86                        "description": "status|handoff|load|save|task|finding|decision|compact|restore|list|… (invalid action lists all)"
87                    },
88                    "value": { "type": "string" },
89                    "keep_recent_turns": { "type": "integer", "description": "compact: trailing user turns kept verbatim (default 6)" },
90                    "session_id": { "type": "string", "description": "Omit for latest" }
91                },
92                "required": ["action"]
93            }),
94        )
95    }
96
97    fn handle(
98        &self,
99        args: &Map<String, Value>,
100        ctx: &ToolContext,
101    ) -> Result<ToolOutput, ErrorData> {
102        let action = get_str(args, "action")
103            .ok_or_else(|| ErrorData::invalid_params("action is required", None))?;
104        let value = get_str(args, "value");
105        let sid = get_str(args, "session_id");
106        let format = get_str(args, "format");
107        let path = get_str(args, "path");
108        let write = get_bool(args, "write").unwrap_or(false);
109        let privacy = get_str(args, "privacy");
110        let terse = get_bool(args, "terse");
111
112        // #1570 P1: agent-driven reversible compaction. Handled here for
113        // direct args access; independent of the session store. The proxy
114        // applies the directive cache-safely on every subsequent request.
115        if action == "compact" || action == "restore" {
116            return Ok(handle_compact_action(&action, value.as_deref(), args));
117        }
118
119        let tool_calls_handle = ctx
120            .tool_calls
121            .as_ref()
122            .ok_or_else(|| ErrorData::internal_error("tool_calls not available", None))?;
123        let call_durations: Vec<(String, u64)> = crate::server::bounded_lock::read_for(
124            tool_calls_handle,
125            "ctx_session tool-call snapshot",
126            SESSION_LOCK_BUDGET,
127        )
128        .map_or_else(Vec::new, |tc| {
129            tc.iter().map(|c| (c.tool.clone(), c.duration_ms)).collect()
130        });
131        let agent_id = ctx
132            .agent_id
133            .as_ref()
134            .and_then(|agent_id| agent_id.try_read().ok().and_then(|id| id.clone()));
135
136        let result = if let Some(result) = crate::tools::ctx_session::handle_without_session(
137            &action,
138            value.as_deref(),
139            sid.as_deref(),
140        ) {
141            result
142        } else {
143            let session_handle = ctx
144                .session
145                .as_ref()
146                .ok_or_else(|| ErrorData::internal_error("session not available", None))?;
147
148            if matches!(action.as_str(), "export" | "resume" | "snapshot") {
149                let Some(snapshot) = crate::server::bounded_lock::read_for(
150                    session_handle,
151                    "ctx_session snapshot",
152                    SESSION_LOCK_BUDGET,
153                )
154                .map(|session| session.clone()) else {
155                    return Err(ErrorData::internal_error(
156                        "session is busy; retry the operation",
157                        None,
158                    ));
159                };
160                crate::tools::ctx_session::handle_snapshot_read_action(
161                    &snapshot,
162                    &action,
163                    value.as_deref(),
164                    crate::tools::ctx_session::SessionToolOptions {
165                        format: format.as_deref(),
166                        path: path.as_deref(),
167                        write,
168                        privacy: privacy.as_deref(),
169                        terse,
170                        agent_id: agent_id.as_deref(),
171                    },
172                )
173                .expect("snapshot action is explicitly handled")
174            } else if matches!(action.as_str(), "status" | "show" | "handoff") {
175                let Some(session) = crate::server::bounded_lock::read_for(
176                    session_handle,
177                    "ctx_session read",
178                    SESSION_LOCK_BUDGET,
179                ) else {
180                    return Err(ErrorData::internal_error(
181                        "session is busy; retry the operation",
182                        None,
183                    ));
184                };
185                crate::tools::ctx_session::handle_read_only(&session, &action)
186                    .expect("read-only action is explicitly handled")
187            } else {
188                let Some(mut session) = crate::server::bounded_lock::write_for(
189                    session_handle,
190                    "ctx_session write",
191                    SESSION_LOCK_BUDGET,
192                ) else {
193                    return Err(ErrorData::internal_error(
194                        "session is busy; retry the operation",
195                        None,
196                    ));
197                };
198                crate::tools::ctx_session::handle(
199                    &mut session,
200                    &call_durations,
201                    &action,
202                    value.as_deref(),
203                    sid.as_deref(),
204                    crate::tools::ctx_session::SessionToolOptions {
205                        format: format.as_deref(),
206                        path: path.as_deref(),
207                        write,
208                        privacy: privacy.as_deref(),
209                        terse,
210                        agent_id: agent_id.as_deref(),
211                    },
212                )
213            }
214        };
215
216        Ok(ToolOutput {
217            text: result,
218            original_tokens: 0,
219            saved_tokens: 0,
220            mode: Some(action),
221            path: None,
222            changed: false,
223            shell_outcome: None,
224            content_blocks: None,
225        })
226    }
227}