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
9pub struct CtxSessionTool;
10
11/// Session management is useful, but it must never make the entire MCP server
12/// wait behind a long-lived writer. Explicitly retryable operations fail fast.
13const SESSION_LOCK_BUDGET: Duration = Duration::from_millis(250);
14
15impl McpTool for CtxSessionTool {
16    fn name(&self) -> &'static str {
17        "ctx_session"
18    }
19
20    fn tool_def(&self) -> Tool {
21        tool_def(
22            "ctx_session",
23            "Session memory. save at session end, load at start, status = snapshot;\n\
24             task|finding|decision record progress (value=text).\n\
25             ANTIPATTERN: permanent project knowledge → ctx_knowledge.",
26            json!({
27                "type": "object",
28                "properties": {
29                    "action": {
30                        "type": "string",
31                        "description": "status|handoff|load|save|task|finding|decision|list|… (invalid action lists all)"
32                    },
33                    "value": { "type": "string" },
34                    "session_id": { "type": "string", "description": "Omit for latest" }
35                },
36                "required": ["action"]
37            }),
38        )
39    }
40
41    fn handle(
42        &self,
43        args: &Map<String, Value>,
44        ctx: &ToolContext,
45    ) -> Result<ToolOutput, ErrorData> {
46        let action = get_str(args, "action")
47            .ok_or_else(|| ErrorData::invalid_params("action is required", None))?;
48        let value = get_str(args, "value");
49        let sid = get_str(args, "session_id");
50        let format = get_str(args, "format");
51        let path = get_str(args, "path");
52        let write = get_bool(args, "write").unwrap_or(false);
53        let privacy = get_str(args, "privacy");
54        let terse = get_bool(args, "terse");
55
56        let tool_calls_handle = ctx
57            .tool_calls
58            .as_ref()
59            .ok_or_else(|| ErrorData::internal_error("tool_calls not available", None))?;
60        let call_durations: Vec<(String, u64)> = crate::server::bounded_lock::read_for(
61            tool_calls_handle,
62            "ctx_session tool-call snapshot",
63            SESSION_LOCK_BUDGET,
64        )
65        .map_or_else(Vec::new, |tc| {
66            tc.iter().map(|c| (c.tool.clone(), c.duration_ms)).collect()
67        });
68        let agent_id = ctx
69            .agent_id
70            .as_ref()
71            .and_then(|agent_id| agent_id.try_read().ok().and_then(|id| id.clone()));
72
73        let result = if let Some(result) = crate::tools::ctx_session::handle_without_session(
74            &action,
75            value.as_deref(),
76            sid.as_deref(),
77        ) {
78            result
79        } else {
80            let session_handle = ctx
81                .session
82                .as_ref()
83                .ok_or_else(|| ErrorData::internal_error("session not available", None))?;
84
85            if matches!(action.as_str(), "export" | "resume" | "snapshot") {
86                let Some(snapshot) = crate::server::bounded_lock::read_for(
87                    session_handle,
88                    "ctx_session snapshot",
89                    SESSION_LOCK_BUDGET,
90                )
91                .map(|session| session.clone()) else {
92                    return Err(ErrorData::internal_error(
93                        "session is busy; retry the operation",
94                        None,
95                    ));
96                };
97                crate::tools::ctx_session::handle_snapshot_read_action(
98                    &snapshot,
99                    &action,
100                    value.as_deref(),
101                    crate::tools::ctx_session::SessionToolOptions {
102                        format: format.as_deref(),
103                        path: path.as_deref(),
104                        write,
105                        privacy: privacy.as_deref(),
106                        terse,
107                        agent_id: agent_id.as_deref(),
108                    },
109                )
110                .expect("snapshot action is explicitly handled")
111            } else if matches!(action.as_str(), "status" | "show" | "handoff") {
112                let Some(session) = crate::server::bounded_lock::read_for(
113                    session_handle,
114                    "ctx_session read",
115                    SESSION_LOCK_BUDGET,
116                ) else {
117                    return Err(ErrorData::internal_error(
118                        "session is busy; retry the operation",
119                        None,
120                    ));
121                };
122                crate::tools::ctx_session::handle_read_only(&session, &action)
123                    .expect("read-only action is explicitly handled")
124            } else {
125                let Some(mut session) = crate::server::bounded_lock::write_for(
126                    session_handle,
127                    "ctx_session write",
128                    SESSION_LOCK_BUDGET,
129                ) else {
130                    return Err(ErrorData::internal_error(
131                        "session is busy; retry the operation",
132                        None,
133                    ));
134                };
135                crate::tools::ctx_session::handle(
136                    &mut session,
137                    &call_durations,
138                    &action,
139                    value.as_deref(),
140                    sid.as_deref(),
141                    crate::tools::ctx_session::SessionToolOptions {
142                        format: format.as_deref(),
143                        path: path.as_deref(),
144                        write,
145                        privacy: privacy.as_deref(),
146                        terse,
147                        agent_id: agent_id.as_deref(),
148                    },
149                )
150            }
151        };
152
153        Ok(ToolOutput {
154            text: result,
155            original_tokens: 0,
156            saved_tokens: 0,
157            mode: Some(action),
158            path: None,
159            changed: false,
160            shell_outcome: None,
161            content_blocks: None,
162        })
163    }
164}