lean-ctx-server 3.12.1

The LeanCTX MCP server and its tools on top of LeanCTX | OSS.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
// SPDX-License-Identifier: Apache-2.0
//! Pre-dispatch permission-inheritance gate.
//!
//! When `permission_inheritance = on`, lean-ctx mirrors the host IDE's
//! tool-permission rules onto its own MCP tools so that, e.g., `ctx_shell`
//! honors the user's `bash` / `rm *` rules instead of forming a parallel,
//! ungoverned execution path. Shaped like [`super::role_guard`]: returns a
//! blocking [`CallToolResult`] message, or `None` to proceed.
//!
//! The decision is split into a pure `decide` (policy in, decision out — fully
//! unit-tested) and a thin [`check`] that loads/caches the IDE policy from disk.
//! lean-ctx never *writes* the IDE's `permission` block; this is read-only.

use std::path::Path;
use std::sync::{Mutex, OnceLock, PoisonError};
use std::time::{Duration, Instant};

use rmcp::model::{CallToolResult, ContentBlock};
use serde_json::{Map, Value};

use lean_ctx::core::config::{Config, PermissionInheritance};
use lean_ctx::core::ide_permissions::{self, IdePermissionPolicy, PermAction, PermDecision};

/// Result of a permission-inheritance check.
pub struct PermissionCheck {
    pub blocked: bool,
    pub message: Option<String>,
}

impl PermissionCheck {
    fn allow() -> Self {
        Self {
            blocked: false,
            message: None,
        }
    }

    fn blocked(message: String) -> Self {
        Self {
            blocked: true,
            message: Some(message),
        }
    }
}

const CACHE_TTL: Duration = Duration::from_secs(5);

struct CacheEntry {
    key: String,
    at: Instant,
    policy: IdePermissionPolicy,
}

static POLICY_CACHE: OnceLock<Mutex<Option<CacheEntry>>> = OnceLock::new();

/// Map an MCP client name (from the `initialize` handshake) to a known IDE id we
/// can read a permission config for. `None` → no reader → never gated.
fn client_id(client_name: &str) -> Option<&'static str> {
    let n = client_name.to_ascii_lowercase();
    if n.contains("opencode") {
        Some("opencode")
    } else {
        None
    }
}

/// Map a lean-ctx tool + its args to the IDE permission key and the relevant
/// input (command / path / pattern). `None` → tool not mirrored → allowed.
fn map_tool(
    tool: &str,
    args: Option<&Map<String, Value>>,
) -> Option<(&'static str, Option<String>)> {
    let get = |k: &str| crate::server::helpers::get_str(args, k);
    match tool {
        "ctx_shell" | "ctx_execute" => Some(("bash", get("command"))),
        "ctx_read" => Some(("read", get("path"))),
        "ctx_edit" | "ctx_patch" => Some(("edit", get("path"))),
        "ctx_search" => Some(("grep", get("pattern").or_else(|| get("query")))),
        _ => None,
    }
}

/// Public entry point used by the dispatch path. Honors config + env, detects
/// the IDE, loads (and caches) its permission policy, then defers to `decide`.
#[must_use]
pub fn check(
    client_name: &str,
    tool: &str,
    args: Option<&Map<String, Value>>,
    project_root: Option<&str>,
    config: &Config,
) -> PermissionCheck {
    if config.permission_inheritance_effective() != PermissionInheritance::On {
        return PermissionCheck::allow();
    }
    let Some(cid) = client_id(client_name) else {
        return PermissionCheck::allow();
    };
    let Some((key, input)) = map_tool(tool, args) else {
        return PermissionCheck::allow();
    };
    let policy = policy_for(cid, project_root);
    if policy.is_empty() {
        return PermissionCheck::allow();
    }

    // Shadow mode writes top-level rules (read/grep/glob/bash) into the IDE's
    // permission config. A blanket skip would also suppress user sub-command
    // rules like "rm *": "ask" — a dangerous bypass (GH #1428). Instead: run
    // the check, then filter out top-level denies for the four shadow-denied
    // tool keys (those were written by lean-ctx itself). User sub-command rules
    // (e.g. "bash:rm *") are always honored.
    if config.shadow_mode {
        let decision = policy.resolve(key, input.as_deref());
        if let Some(ref d) = decision {
            if is_shadow_written_deny(&d.rule) {
                return PermissionCheck::allow();
            }
        }
        return decide(display_name(cid), &policy, tool, key, input.as_deref());
    }

    decide(display_name(cid), &policy, tool, key, input.as_deref())
}

/// The four tool keys that shadow mode writes into the IDE's permission
/// config (`"ask"` since #1864, `"deny"` in older releases). A matched rule
/// whose name is exactly one of these was
/// shadow-written by lean-ctx — not user-authored — and should be skipped
/// so the agent retains working tools. Sub-command rules like `"bash:rm *"`
/// are user-authored and must be honored.
fn is_shadow_written_deny(rule: &str) -> bool {
    matches!(rule, "bash" | "read" | "grep" | "glob")
}

/// Pure decision: given a loaded policy, resolve the action for `tool` (mapped to
/// IDE `key` + `input`) and turn it into a [`PermissionCheck`].
fn decide(
    ide: &str,
    policy: &IdePermissionPolicy,
    tool: &str,
    key: &str,
    input: Option<&str>,
) -> PermissionCheck {
    let Some(decision) = policy.resolve(key, input) else {
        return PermissionCheck::allow();
    };
    match decision.action {
        PermAction::Allow => PermissionCheck::allow(),
        PermAction::Ask => PermissionCheck::blocked(ask_message(ide, &decision, key, input)),
        PermAction::Deny => {
            PermissionCheck::blocked(deny_message(ide, tool, &decision, key, input))
        }
    }
}

fn ask_message(ide: &str, decision: &PermDecision, key: &str, input: Option<&str>) -> String {
    format!(
        "[IDE PERMISSION] {ide} gates this with `{rule}` = ask. lean-ctx mirrors your IDE \
         permissions (permission_inheritance=on) and cannot show an interactive prompt for MCP \
         tools, so the call is held back to honor your rule.{suffix}\n\
         Approve it via {ide}'s native tool, set the rule to `allow`, or disable inheritance with \
         `lean-ctx config set permission_inheritance off`.",
        ide = ide,
        rule = decision.rule,
        suffix = input_suffix(key, input),
    )
}

fn deny_message(
    ide: &str,
    tool: &str,
    decision: &PermDecision,
    key: &str,
    input: Option<&str>,
) -> String {
    format!(
        "[IDE PERMISSION] {ide} blocks this via `{rule}` = deny. lean-ctx mirrors your IDE \
         permissions (permission_inheritance=on), so `{tool}` is blocked too.{suffix}",
        ide = ide,
        rule = decision.rule,
        tool = tool,
        suffix = input_suffix(key, input),
    )
}

fn input_suffix(key: &str, input: Option<&str>) -> String {
    let Some(value) = input else {
        return String::new();
    };
    let label = match key {
        "bash" => "Command",
        "grep" => "Pattern",
        _ => "Path",
    };
    format!(" {label}: `{}`", truncate(value, 200))
}

fn truncate(s: &str, max: usize) -> String {
    if s.chars().count() <= max {
        return s.to_string();
    }
    let mut out: String = s.chars().take(max).collect();
    out.push('…');
    out
}

fn display_name(client_id: &str) -> &'static str {
    lean_ctx::core::client_constraints::by_client_id(client_id)
        .map_or("your IDE", |c| c.display_name)
}

fn policy_for(client_id: &str, project_root: Option<&str>) -> IdePermissionPolicy {
    let key = format!("{client_id}|{}", project_root.unwrap_or(""));
    let cache = POLICY_CACHE.get_or_init(|| Mutex::new(None));
    let mut guard = cache.lock().unwrap_or_else(PoisonError::into_inner);
    if let Some(entry) = guard.as_ref()
        && entry.key == key
        && entry.at.elapsed() < CACHE_TTL
    {
        return entry.policy.clone();
    }
    let policy = load_policy(client_id, project_root);
    *guard = Some(CacheEntry {
        key,
        at: Instant::now(),
        policy: policy.clone(),
    });
    policy
}

fn load_policy(client_id: &str, project_root: Option<&str>) -> IdePermissionPolicy {
    let Some(home) = dirs::home_dir() else {
        return IdePermissionPolicy::default();
    };
    match client_id {
        "opencode" => ide_permissions::load_opencode(&home, project_root.map(Path::new)),
        _ => IdePermissionPolicy::default(),
    }
}

/// Convert a check into a blocking tool result (like `role_guard`): a tool
/// error carrying the explanation, so the agent reads *why* it was held back.
#[must_use]
pub fn into_call_tool_result(check: &PermissionCheck) -> Option<CallToolResult> {
    if check.blocked {
        Some(CallToolResult::error(vec![ContentBlock::text(
            check
                .message
                .clone()
                .unwrap_or_else(|| "Blocked by IDE permission inheritance".to_string()),
        )]))
    } else {
        None
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    fn policy(v: Value) -> IdePermissionPolicy {
        match v {
            Value::Object(map) => IdePermissionPolicy::from_rules(map),
            _ => IdePermissionPolicy::default(),
        }
    }

    #[test]
    fn client_id_detects_opencode() {
        assert_eq!(client_id("opencode"), Some("opencode"));
        assert_eq!(client_id("OpenCode 1.2"), Some("opencode"));
        assert_eq!(client_id("cursor"), None);
        assert_eq!(client_id(""), None);
    }

    #[test]
    fn map_tool_covers_mirrored_tools() {
        let args = json!({ "command": "rm -rf x", "path": "a.rs", "pattern": "foo" });
        let map = args.as_object().unwrap();
        assert_eq!(map_tool("ctx_shell", Some(map)).unwrap().0, "bash");
        assert_eq!(map_tool("ctx_execute", Some(map)).unwrap().0, "bash");
        assert_eq!(map_tool("ctx_read", Some(map)).unwrap().0, "read");
        assert_eq!(map_tool("ctx_edit", Some(map)).unwrap().0, "edit");
        // ctx_patch (anchored editing) inherits the same "edit" permission key.
        assert_eq!(map_tool("ctx_patch", Some(map)).unwrap().0, "edit");
        assert_eq!(map_tool("ctx_search", Some(map)).unwrap().0, "grep");
        assert!(map_tool("ctx_knowledge", Some(map)).is_none());
    }

    #[test]
    fn decide_allow_passes() {
        let p = policy(json!({ "bash": "allow" }));
        let c = decide("OpenCode", &p, "ctx_shell", "bash", Some("ls"));
        assert!(!c.blocked);
    }

    #[test]
    fn decide_deny_blocks_with_message() {
        let p = policy(json!({ "bash": "deny" }));
        let c = decide("OpenCode", &p, "ctx_shell", "bash", Some("ls"));
        assert!(c.blocked);
        let msg = c.message.unwrap();
        assert!(msg.contains("deny"));
        assert!(msg.contains("ctx_shell"));
        assert!(msg.contains("Command: `ls`"));
    }

    #[test]
    fn decide_ask_holds_back_rm() {
        // The user's screenshot scenario: bash=allow but rm *=ask.
        let p = policy(json!({ "bash": "allow", "rm *": "ask" }));
        let c = decide("OpenCode", &p, "ctx_shell", "bash", Some("rm -rf /tmp/x"));
        assert!(c.blocked);
        let msg = c.message.unwrap();
        assert!(msg.contains("ask"));
        assert!(msg.contains("bash:rm *"));
        assert!(msg.contains("permission_inheritance off"));
    }

    #[test]
    fn decide_unmatched_tool_input_allows() {
        let p = policy(json!({ "read": "deny" }));
        // bash has no rule here → allowed.
        let c = decide("OpenCode", &p, "ctx_shell", "bash", Some("ls"));
        assert!(!c.blocked);
    }

    #[test]
    fn into_result_only_when_blocked() {
        assert!(into_call_tool_result(&PermissionCheck::allow()).is_none());
        // A block is a tool error, like a role or policy denial.
        let blocked =
            into_call_tool_result(&PermissionCheck::blocked("x".into())).expect("blocked");
        assert_eq!(blocked.is_error, Some(true));
    }

    #[test]
    fn check_off_by_default_allows_everything() {
        // Env var takes precedence over config; skip if a stray one is set.
        if std::env::var("LEAN_CTX_PERMISSION_INHERITANCE").is_ok() {
            return;
        }
        let cfg = Config {
            permission_inheritance: Some("off".to_string()),
            ..Default::default()
        };
        let args = json!({ "command": "rm -rf /" });
        let c = check(
            "opencode",
            "ctx_shell",
            Some(args.as_object().unwrap()),
            None,
            &cfg,
        );
        assert!(!c.blocked);
    }

    #[test]
    fn truncate_keeps_short_strings() {
        assert_eq!(truncate("short", 200), "short");
        assert_eq!(truncate("abcdef", 3), "abc\u{2026}");
    }

    #[test]
    fn is_shadow_written_deny_recognizes_tool_keys() {
        assert!(is_shadow_written_deny("bash"));
        assert!(is_shadow_written_deny("read"));
        assert!(is_shadow_written_deny("grep"));
        assert!(is_shadow_written_deny("glob"));
    }

    #[test]
    fn is_shadow_written_deny_rejects_user_rules() {
        assert!(!is_shadow_written_deny("bash:rm *"));
        assert!(!is_shadow_written_deny("bash:*"));
        assert!(!is_shadow_written_deny("read:*.env"));
        assert!(!is_shadow_written_deny("*"));
        assert!(!is_shadow_written_deny("edit"));
    }

    #[test]
    fn shadow_mode_honors_user_rm_ask_rule() {
        // GH #1428: the exact scenario Stephen reported — shadow mode must
        // NOT bypass the user's "rm *": "ask" rule.
        let p = policy(json!({ "bash": "deny", "rm *": "ask" }));
        // Direct policy resolve → the sub-command rule wins:
        let d = p.resolve("bash", Some("rm -rf /tmp/important")).unwrap();
        assert_eq!(d.action, PermAction::Ask);
        assert_eq!(d.rule, "bash:rm *");
        // The helper correctly classifies this as user-authored:
        assert!(!is_shadow_written_deny(&d.rule));
    }

    #[test]
    fn shadow_mode_skips_shadow_written_bash_deny() {
        // When shadow mode wrote "bash": "deny", a plain `ls` command must
        // not be denied — that deny is shadow-written, not user-authored.
        let p = policy(json!({ "bash": "deny" }));
        let d = p.resolve("bash", Some("ls")).unwrap();
        assert_eq!(d.action, PermAction::Deny);
        assert_eq!(d.rule, "bash");
        assert!(is_shadow_written_deny(&d.rule));
    }
}