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
9fn 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(()) => format!(
39 "Compaction armed (keeps last {keep} user turns verbatim). It applies \
40 to your NEXT request onward, only outside the provider-cached \
41 prefix, at tool-pair-safe boundaries. Undo any time: \
42 ctx_session action=\"restore\"."
43 ),
44 Err(reason) => reason,
45 }
46 }
47 }
48 };
49 ToolOutput {
50 text,
51 original_tokens: 0,
52 saved_tokens: 0,
53 mode: Some(action.to_string()),
54 path: None,
55 changed: false,
56 shell_outcome: None,
57 content_blocks: None,
58 }
59}
60
61pub struct CtxSessionTool;
62
63const SESSION_LOCK_BUDGET: Duration = Duration::from_millis(250);
66
67fn session_matches_snapshot(
68 live: &crate::core::session::SessionState,
69 snapshot: &crate::core::session::SessionState,
70) -> bool {
71 live.id == snapshot.id
72 && live.version == snapshot.version
73 && live.project_root == snapshot.project_root
74 && live.shell_cwd == snapshot.shell_cwd
75 && live.extra_roots == snapshot.extra_roots
76}
77
78impl McpTool for CtxSessionTool {
79 fn name(&self) -> &'static str {
80 "ctx_session"
81 }
82
83 fn tool_def(&self) -> Tool {
84 tool_def(
85 "ctx_session",
86 "Session memory. save at session end, load at start, status = snapshot;\n\
87 task|finding|decision record progress (value=text).\n\
88 ANTIPATTERN: permanent project knowledge → ctx_knowledge.",
89 json!({
90 "type": "object",
91 "properties": {
92 "action": {
93 "type": "string",
94 "description": "status|handoff|load|save|task|finding|decision|compact|restore|list|… (invalid action lists all)"
95 },
96 "value": { "type": "string" },
97 "tag": { "type": "string", "enum": ["note", "dead_end"], "description": "finding: dead_end = tried and abandoned" },
98 "keep_recent_turns": { "type": "integer", "description": "compact: trailing user turns kept verbatim (default 6)" },
99 "session_id": { "type": "string", "description": "Omit for your own session" }
100 },
101 "required": ["action"]
102 }),
103 )
104 }
105
106 fn handle(
107 &self,
108 args: &Map<String, Value>,
109 ctx: &ToolContext,
110 ) -> Result<ToolOutput, ErrorData> {
111 let action = get_str(args, "action")
112 .ok_or_else(|| ErrorData::invalid_params("action is required", None))?;
113 let value = get_str(args, "value");
114 let sid = get_str(args, "session_id");
115 let format = get_str(args, "format");
116 let path = get_str(args, "path");
117 let write = get_bool(args, "write").unwrap_or(false);
118 let privacy = get_str(args, "privacy");
119 let terse = get_bool(args, "terse");
120 let dead_end = match get_str(args, "tag").as_deref() {
121 None | Some("note") => false,
122 Some("dead_end") => true,
123 Some(_) => {
124 return Err(ErrorData::invalid_params(
125 "tag must be note or dead_end",
126 None,
127 ));
128 }
129 };
130
131 if action == "restore" {
134 return Ok(handle_compact_action(&action, value.as_deref(), args));
135 }
136 if action == "compact" {
137 let Some(summary) = value.as_deref().filter(|summary| !summary.is_empty()) else {
138 return Ok(handle_compact_action(&action, value.as_deref(), args));
139 };
140 let session_handle = ctx
141 .session
142 .as_ref()
143 .ok_or_else(|| ErrorData::internal_error("session not available", None))?;
144 let Some(snapshot) = crate::server::bounded_lock::read_for(
145 session_handle,
146 "ctx_session compact admission snapshot",
147 SESSION_LOCK_BUDGET,
148 )
149 .map(|session| session.clone()) else {
150 return Err(ErrorData::internal_error(
151 "session is busy; retry the operation",
152 None,
153 ));
154 };
155 let admitted =
156 crate::core::session::admission::admit_storable_session_text(&snapshot, summary)
157 .map_err(|_| {
158 ErrorData::invalid_params(
159 "compact summary withheld by current policy",
160 None,
161 )
162 })?;
163 return Ok(handle_compact_action(&action, Some(&admitted), args));
164 }
165
166 let tool_calls_handle = ctx
167 .tool_calls
168 .as_ref()
169 .ok_or_else(|| ErrorData::internal_error("tool_calls not available", None))?;
170 let call_durations: Vec<(String, u64)> = crate::server::bounded_lock::read_for(
171 tool_calls_handle,
172 "ctx_session tool-call snapshot",
173 SESSION_LOCK_BUDGET,
174 )
175 .map_or_else(Vec::new, |tc| {
176 tc.iter().map(|c| (c.tool.clone(), c.duration_ms)).collect()
177 });
178 let agent_id = ctx
179 .agent_id
180 .as_ref()
181 .and_then(|agent_id| agent_id.try_read().ok().and_then(|id| id.clone()));
182
183 let result = if let Some(result) = crate::tools::ctx_session::handle_without_session(
184 &action,
185 value.as_deref(),
186 sid.as_deref(),
187 ) {
188 result
189 } else {
190 let session_handle = ctx
191 .session
192 .as_ref()
193 .ok_or_else(|| ErrorData::internal_error("session not available", None))?;
194
195 if action == "save" {
196 let Some(snapshot) = crate::server::bounded_lock::read_for(
197 session_handle,
198 "ctx_session save snapshot",
199 SESSION_LOCK_BUDGET,
200 )
201 .map(|session| session.clone()) else {
202 return Err(ErrorData::internal_error(
203 "session is busy; retry the operation",
204 None,
205 ));
206 };
207 let result =
208 match crate::core::session::SessionState::save_shared_sync(session_handle) {
209 Err(error) => format!("Save failed: {error}"),
210 Ok(receipt) if receipt.current => {
211 format!("Session {} saved (v{}).", receipt.id, receipt.version)
212 }
213 Ok(receipt) => format!(
214 "Session {} snapshot v{} saved; newer session changes remain pending.",
215 receipt.id, receipt.version
216 ),
217 };
218 crate::core::session::admission::admit_tool_value(&snapshot, &result)
219 .unwrap_or_else(|_| {
220 "ERROR: session save result withheld by current policy.".into()
221 })
222 } else if action == "reset" {
223 let Some(snapshot) = crate::server::bounded_lock::read_for(
224 session_handle,
225 "ctx_session reset snapshot",
226 SESSION_LOCK_BUDGET,
227 )
228 .map(|session| session.clone()) else {
229 return Err(ErrorData::internal_error(
230 "session is busy; retry the operation",
231 None,
232 ));
233 };
234 let output =
235 match crate::core::session::SessionState::save_shared_sync(session_handle) {
236 Err(error) => {
237 format!("Reset refused: current session was not saved: {error}")
238 }
239 Ok(receipt)
240 if !receipt.current
241 || receipt.id != snapshot.id
242 || receipt.version != snapshot.version =>
243 {
244 "Reset refused: session changed while it was being saved; retry.".into()
245 }
246 Ok(_) => {
247 let Some(mut live) = crate::server::bounded_lock::write_for(
248 session_handle,
249 "ctx_session reset commit",
250 SESSION_LOCK_BUDGET,
251 ) else {
252 return Err(ErrorData::internal_error(
253 "session is busy; retry the operation",
254 None,
255 ));
256 };
257 if !session_matches_snapshot(&live, &snapshot)
258 || !std::sync::Arc::ptr_eq(&live.save_gate, &snapshot.save_gate)
259 {
260 return Err(ErrorData::internal_error(
261 "session changed during reset; retry the operation",
262 None,
263 ));
264 }
265 crate::tools::ctx_session::reset_after_save(&mut live)
266 }
267 };
268 crate::core::session::admission::admit_tool_value(&snapshot, &output)
269 .unwrap_or_else(|_| "ERROR: reset result withheld by current policy.".into())
270 } else if action == "load" {
271 let Some(snapshot) = crate::server::bounded_lock::read_for(
272 session_handle,
273 "ctx_session load snapshot",
274 SESSION_LOCK_BUDGET,
275 )
276 .map(|session| session.clone()) else {
277 return Err(ErrorData::internal_error(
278 "session is busy; retry the operation",
279 None,
280 ));
281 };
282 let (candidate, output) =
283 crate::tools::ctx_session::prepare_load(&snapshot, sid.as_deref()).map_err(
284 |_| {
285 ErrorData::invalid_params(
286 "session load denied by current project scope or content policy",
287 None,
288 )
289 },
290 )?;
291 let Some(mut live) = crate::server::bounded_lock::write_for(
292 session_handle,
293 "ctx_session load commit",
294 SESSION_LOCK_BUDGET,
295 ) else {
296 return Err(ErrorData::internal_error(
297 "session is busy; retry the operation",
298 None,
299 ));
300 };
301 if !session_matches_snapshot(&live, &snapshot) {
302 return Err(ErrorData::internal_error(
303 "session changed during load; retry the operation",
304 None,
305 ));
306 }
307 *live = candidate;
308 output
309 } else if matches!(action.as_str(), "export" | "resume" | "snapshot") {
310 let Some(snapshot) = crate::server::bounded_lock::read_for(
311 session_handle,
312 "ctx_session snapshot",
313 SESSION_LOCK_BUDGET,
314 )
315 .map(|session| session.clone()) else {
316 return Err(ErrorData::internal_error(
317 "session is busy; retry the operation",
318 None,
319 ));
320 };
321 crate::tools::ctx_session::handle_snapshot_read_action(
322 &snapshot,
323 &action,
324 value.as_deref(),
325 crate::tools::ctx_session::SessionToolOptions {
326 format: format.as_deref(),
327 path: path.as_deref(),
328 write,
329 privacy: privacy.as_deref(),
330 terse,
331 agent_id: agent_id.as_deref(),
332 },
333 )
334 .expect("snapshot action is explicitly handled")
335 } else if matches!(action.as_str(), "status" | "show" | "handoff") {
336 let Some(snapshot) = crate::server::bounded_lock::read_for(
337 session_handle,
338 "ctx_session read",
339 SESSION_LOCK_BUDGET,
340 )
341 .map(|session| session.clone()) else {
342 return Err(ErrorData::internal_error(
343 "session is busy; retry the operation",
344 None,
345 ));
346 };
347 crate::tools::ctx_session::handle_read_only(&snapshot, &action)
348 .expect("read-only action is explicitly handled")
349 } else if matches!(
350 action.as_str(),
351 "task" | "finding" | "decision" | "list" | "episodes" | "procedures"
352 ) {
353 let Some(snapshot) = crate::server::bounded_lock::read_for(
354 session_handle,
355 "ctx_session admitted action snapshot",
356 SESSION_LOCK_BUDGET,
357 )
358 .map(|session| session.clone()) else {
359 return Err(ErrorData::internal_error(
360 "session is busy; retry the operation",
361 None,
362 ));
363 };
364 let prepared = crate::tools::ctx_session::prepare_admitted_action(
365 &snapshot,
366 &call_durations,
367 &action,
368 value.as_deref(),
369 sid.as_deref(),
370 crate::tools::ctx_session::SessionToolOptions {
371 format: format.as_deref(),
372 path: path.as_deref(),
373 write,
374 privacy: privacy.as_deref(),
375 terse,
376 agent_id: agent_id.as_deref(),
377 },
378 )
379 .map_err(|_| {
380 ErrorData::invalid_params(
381 "session action withheld by current project or content policy",
382 None,
383 )
384 })?;
385 if matches!(action.as_str(), "task" | "finding" | "decision") {
386 let completed_task = prepared.completed_task;
387 let candidate = prepared.candidate;
388 let mut output = prepared.output;
389 let Some(mut live) = crate::server::bounded_lock::write_for(
390 session_handle,
391 "ctx_session admitted action commit",
392 SESSION_LOCK_BUDGET,
393 ) else {
394 return Err(ErrorData::internal_error(
395 "session is busy; retry the operation",
396 None,
397 ));
398 };
399 if !session_matches_snapshot(&live, &snapshot) {
400 return Err(ErrorData::internal_error(
401 "session changed during content admission; retry the operation",
402 None,
403 ));
404 }
405 if !prepared.store_admission.is_current() {
406 return Err(ErrorData::internal_error(
407 "session policy changed during content admission; retry the operation",
408 None,
409 ));
410 }
411 *live = candidate.clone();
412 drop(live);
413 if dead_end
416 && action == "finding"
417 && let Some(finding) = candidate.findings.last()
418 {
419 crate::core::hive::capture::episode::note_dead_end(
420 &candidate.id,
421 &finding.summary,
422 );
423 }
424 if let Some(note) =
425 crate::tools::ctx_session::record_completed_task_after_commit(
426 &candidate,
427 completed_task,
428 &call_durations,
429 agent_id.as_deref(),
430 )
431 {
432 output.push_str(¬e);
433 }
434 crate::core::session::admission::admit_tool_value(&candidate, &output)
435 .unwrap_or_else(|_| "[lean-ctx gateway: session content withheld]".into())
436 } else {
437 if !prepared.store_admission.is_current() {
438 return Err(ErrorData::internal_error(
439 "session policy changed during content admission; retry the operation",
440 None,
441 ));
442 }
443 prepared.output
444 }
445 } else {
446 let Some(mut session) = crate::server::bounded_lock::write_for(
447 session_handle,
448 "ctx_session write",
449 SESSION_LOCK_BUDGET,
450 ) else {
451 return Err(ErrorData::internal_error(
452 "session is busy; retry the operation",
453 None,
454 ));
455 };
456 crate::tools::ctx_session::handle(
457 &mut session,
458 &call_durations,
459 &action,
460 value.as_deref(),
461 sid.as_deref(),
462 crate::tools::ctx_session::SessionToolOptions {
463 format: format.as_deref(),
464 path: path.as_deref(),
465 write,
466 privacy: privacy.as_deref(),
467 terse,
468 agent_id: agent_id.as_deref(),
469 },
470 )
471 }
472 };
473
474 Ok(ToolOutput {
475 text: result,
476 original_tokens: 0,
477 saved_tokens: 0,
478 mode: Some(action),
479 path: None,
480 changed: false,
481 shell_outcome: None,
482 content_blocks: None,
483 })
484 }
485
486 }