Skip to main content

lean_ctx/tools/
server.rs

1use std::sync::Arc;
2use std::sync::atomic::AtomicUsize;
3use std::time::Instant;
4use tokio::sync::RwLock;
5
6use crate::core::cache::SessionCache;
7use crate::core::session::SessionState;
8use rmcp::service::{Peer, RoleServer};
9
10pub(super) struct CepComputedStats {
11    pub(super) cep_score: u32,
12    pub(super) cache_util: u32,
13    pub(super) mode_diversity: u32,
14    pub(super) compression_rate: u32,
15    pub(super) total_original: u64,
16    pub(super) total_compressed: u64,
17    pub(super) total_saved: u64,
18    pub(super) mode_counts: std::collections::HashMap<String, u64>,
19    pub(super) complexity: String,
20    pub(super) cache_hits: u64,
21    pub(super) total_reads: u64,
22    pub(super) tool_call_count: u64,
23    pub(super) adoption: AdoptionMetrics,
24}
25
26/// Measures lean-ctx adoption: what fraction of tool calls went through MCP
27/// rather than falling through to native/shell passthrough.
28#[derive(Default, Clone)]
29pub(super) struct AdoptionMetrics {
30    pub(super) ctx_tool_calls: u64,
31    pub(super) native_passthrough: u64,
32    pub(super) adoption_pct: u32,
33}
34
35pub use crate::core::protocol::CrpMode;
36// CrpMode is now defined in core::protocol to avoid reverse-dependency.
37// Re-exported here for backward compatibility.
38
39impl CrpMode {
40    /// Effective CRP mode: explicit env var wins; otherwise derived from CompressionLevel.
41    pub fn effective() -> Self {
42        if let Ok(v) = std::env::var("LEAN_CTX_CRP_MODE")
43            && !v.trim().is_empty()
44        {
45            return Self::parse(&v).unwrap_or(Self::Off);
46        }
47        let config = crate::core::config::Config::load();
48        let level = crate::core::config::CompressionLevel::effective(&config);
49        let (_, _, crp_str, _) = level.to_components();
50        Self::parse(crp_str).unwrap_or(Self::Off)
51    }
52
53    /// Returns true if the mode is TDD (maximum compression).
54    pub fn is_tdd(&self) -> bool {
55        *self == Self::Tdd
56    }
57}
58
59/// Thread-safe handle to the shared file content cache.
60pub type SharedCache = Arc<RwLock<SessionCache>>;
61
62#[derive(Clone, Copy, Debug, PartialEq, Eq)]
63pub enum SessionMode {
64    /// Traditional single-client session persistence under `~/.lean-ctx/sessions/`.
65    Personal,
66    /// Context OS mode: shared sessions + event bus for multi-client HTTP/team-server.
67    Shared,
68}
69
70/// IDE interaction mode communicated via `_meta.interactionMode` in MCP requests.
71/// Controls which tools are advertised and callable — Plan mode restricts to
72/// read-only tools (see `plan_mode_tools()`), Agent mode exposes the full set.
73#[derive(Clone, Copy, Debug, PartialEq, Eq)]
74#[repr(u8)]
75pub enum InteractionMode {
76    Agent = 0,
77    Plan = 1,
78}
79
80impl InteractionMode {
81    pub fn from_u8(v: u8) -> Self {
82        match v {
83            1 => Self::Plan,
84            _ => Self::Agent,
85        }
86    }
87
88    /// Parse the string value from `_meta.interactionMode`.
89    /// Accepts multiple conventions across IDEs (OpenCode, Cursor, Claude Code).
90    pub fn from_meta_str(s: &str) -> Option<Self> {
91        match s.to_ascii_lowercase().as_str() {
92            "plan" | "readonly" | "read-only" => Some(Self::Plan),
93            "agent" | "normal" | "edit" | "act" => Some(Self::Agent),
94            _ => None,
95        }
96    }
97}
98
99/// Central MCP server state: cache, session, metrics, and autonomy runtime.
100#[derive(Clone)]
101pub struct LeanCtxServer {
102    pub cache: SharedCache,
103    pub session: Arc<RwLock<SessionState>>,
104    pub tool_calls: Arc<RwLock<Vec<ToolCallRecord>>>,
105    pub call_count: Arc<AtomicUsize>,
106    pub pro_trigger_check_count: Arc<AtomicUsize>,
107    pub cache_ttl_secs: u64,
108    pub last_call: Arc<RwLock<Instant>>,
109    pub agent_id: Arc<RwLock<Option<String>>>,
110    pub task_envelope: Arc<RwLock<Option<lean_ctx_protocol::TaskEnvelopeV1>>>,
111    pub(crate) presence_agent_id: Arc<RwLock<Option<String>>>,
112    pub client_name: Arc<RwLock<String>>,
113    pub autonomy: Arc<crate::core::autonomy::AutonomyState>,
114    pub loop_detector: Arc<RwLock<crate::core::loop_detection::LoopDetector>>,
115    pub workflow: Arc<RwLock<Option<crate::core::workflow::WorkflowRun>>>,
116    pub ledger: Arc<RwLock<crate::core::context_ledger::ContextLedger>>,
117    pub pipeline_stats: Arc<RwLock<crate::core::pipeline::PipelineStats>>,
118    pub session_mode: SessionMode,
119    pub workspace_id: String,
120    pub channel_id: String,
121    pub context_os: Option<Arc<crate::core::context_os::ContextOsRuntime>>,
122    pub context_ir: Option<Arc<RwLock<crate::core::context_ir::ContextIrV1>>>,
123    pub registry: Option<Arc<crate::server::registry::ToolRegistry>>,
124    pub(crate) rules_stale_checked: Arc<std::sync::atomic::AtomicBool>,
125    pub(crate) rules_tip_shown: Arc<std::sync::atomic::AtomicBool>,
126    pub(crate) last_seen_event_id: Arc<std::sync::atomic::AtomicI64>,
127    pub(crate) startup_project_root: Option<String>,
128    pub(crate) startup_shell_cwd: Option<String>,
129    pub(crate) peer: Arc<RwLock<Option<Peer<RoleServer>>>>,
130    pub(crate) has_client_roots: Arc<std::sync::atomic::AtomicBool>,
131    pub(crate) roots_resolved: Arc<std::sync::atomic::AtomicBool>,
132    /// Failed `roots/list` attempts (GH #694): transient failures re-arm
133    /// `roots_resolved` until a small budget is exhausted.
134    pub(crate) roots_list_attempts: Arc<std::sync::atomic::AtomicU32>,
135    pub(crate) bm25_cache: Arc<std::sync::Mutex<Option<crate::core::bm25_cache::Bm25CacheEntry>>>,
136    pub(crate) _eviction_target: Arc<crate::core::eviction_orchestrator::EvictionOrchestrator>,
137    pub(crate) progress_sender: crate::server::progress::SharedProgressSender,
138    pub(crate) last_tools_config_hash: Arc<std::sync::atomic::AtomicU64>,
139    /// Current IDE interaction mode (Agent/Plan). Updated from `_meta.interactionMode`
140    /// on each tool call; controls tool visibility and destructive-tool guards.
141    pub(crate) interaction_mode: Arc<std::sync::atomic::AtomicU8>,
142}
143
144pub use crate::core::protocol::ToolCallRecord;
145
146#[cfg(test)]
147mod tests {
148    use super::InteractionMode;
149
150    #[test]
151    fn from_u8_round_trips() {
152        assert_eq!(InteractionMode::from_u8(0), InteractionMode::Agent);
153        assert_eq!(InteractionMode::from_u8(1), InteractionMode::Plan);
154        assert_eq!(InteractionMode::from_u8(42), InteractionMode::Agent);
155    }
156
157    #[test]
158    fn from_meta_str_plan_variants() {
159        for s in ["plan", "Plan", "PLAN", "readonly", "read-only"] {
160            assert_eq!(
161                InteractionMode::from_meta_str(s),
162                Some(InteractionMode::Plan),
163                "failed for: {s}"
164            );
165        }
166    }
167
168    #[test]
169    fn from_meta_str_agent_variants() {
170        for s in ["agent", "Agent", "normal", "edit", "act"] {
171            assert_eq!(
172                InteractionMode::from_meta_str(s),
173                Some(InteractionMode::Agent),
174                "failed for: {s}"
175            );
176        }
177    }
178
179    #[test]
180    fn from_meta_str_unknown_returns_none() {
181        assert_eq!(InteractionMode::from_meta_str("debug"), None);
182        assert_eq!(InteractionMode::from_meta_str(""), None);
183    }
184
185    #[test]
186    fn default_mode_is_agent() {
187        let mode = std::sync::atomic::AtomicU8::new(InteractionMode::Agent as u8);
188        assert_eq!(
189            InteractionMode::from_u8(mode.load(std::sync::atomic::Ordering::Relaxed)),
190            InteractionMode::Agent,
191        );
192    }
193}