lean-ctx 3.11.4

LeanCTX Engine: the open-source runtime for the Context Gateway for AI Systems. CLI, MCP server, and supported proxy integrations.
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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
use std::sync::{Mutex, OnceLock};

#[derive(Debug, Clone)]
pub(crate) struct ClientMcpCapabilities {
    pub client_id: String,
    pub resources: bool,
    pub prompts: bool,
    pub elicitation: bool,
    pub sampling: bool,
    pub dynamic_tools: bool,
    pub max_tools: Option<usize>,
}

impl Default for ClientMcpCapabilities {
    fn default() -> Self {
        Self {
            client_id: "unknown".to_string(),
            resources: false,
            prompts: false,
            elicitation: false,
            sampling: false,
            dynamic_tools: false,
            max_tools: None,
        }
    }
}

impl ClientMcpCapabilities {
    pub(crate) fn detect(client_name: &str) -> Self {
        let hint = std::env::var("LEAN_CTX_CLIENT_HINT").ok();
        Self::detect_with_hint(client_name, hint.as_deref())
    }

    fn detect_with_hint(client_name: &str, hint: Option<&str>) -> Self {
        let effective = match hint {
            Some(h) if !h.trim().is_empty() => h.trim().to_lowercase(),
            _ => client_name.to_lowercase(),
        };
        let id = identify_client(&effective);
        // Capabilities follow the established classes; the finer `id` only
        // names the host (telemetry, summaries) and never changes behaviour.
        let class = capability_class(&effective);

        match class {
            "cursor" | "kiro" => Self {
                client_id: id,
                resources: true,
                prompts: true,
                elicitation: true,
                sampling: false,
                dynamic_tools: true,
                max_tools: None,
            },
            "claude-code" => Self {
                client_id: id,
                resources: true,
                prompts: true,
                elicitation: true,
                sampling: true,
                dynamic_tools: true,
                max_tools: None,
            },
            "windsurf" => Self {
                client_id: id,
                resources: false,
                prompts: false,
                elicitation: false,
                sampling: false,
                dynamic_tools: true,
                max_tools: Some(100),
            },
            "zed" => Self {
                client_id: id,
                resources: false,
                prompts: true,
                elicitation: false,
                sampling: false,
                dynamic_tools: true,
                max_tools: None,
            },
            "vscode-copilot" => Self {
                client_id: id,
                resources: true,
                prompts: true,
                elicitation: false,
                sampling: false,
                dynamic_tools: true,
                max_tools: None,
            },
            "codex" => Self {
                client_id: id,
                resources: true,
                prompts: false,
                elicitation: false,
                sampling: false,
                dynamic_tools: true,
                max_tools: None,
            },
            "antigravity" | "gemini-cli" => Self {
                client_id: id,
                resources: false,
                prompts: false,
                elicitation: false,
                sampling: false,
                dynamic_tools: false,
                max_tools: None,
            },
            _ => Self {
                client_id: id,
                ..Default::default()
            },
        }
    }

    pub(crate) fn tier(&self) -> u8 {
        let score = [
            self.resources,
            self.prompts,
            self.elicitation,
            self.sampling,
            self.dynamic_tools,
        ]
        .iter()
        .filter(|&&v| v)
        .count();

        match score {
            4..=5 => 1,
            2..=3 => 2,
            1 => 3,
            _ => 4,
        }
    }

    pub(crate) fn format_summary(&self) -> String {
        let features: Vec<&str> = [
            ("resources", self.resources),
            ("prompts", self.prompts),
            ("elicitation", self.elicitation),
            ("sampling", self.sampling),
            ("dynamic_tools", self.dynamic_tools),
        ]
        .iter()
        .filter(|(_, v)| *v)
        .map(|(k, _)| *k)
        .collect();

        let tools_note = self
            .max_tools
            .map(|n| format!(" (max {n} tools)"))
            .unwrap_or_default();

        format!(
            "{} (tier {}): [{}]{}",
            self.client_id,
            self.tier(),
            features.join(", "),
            tools_note,
        )
    }
}

/// The capability class a client name has always mapped to. Kept separate
/// from [`identify_client`] so naming more hosts never changes what LeanCTX
/// offers them over MCP.
fn capability_class(lower: &str) -> &'static str {
    if lower.contains("cursor") {
        "cursor"
    } else if lower.contains("codebuddy") {
        "codebuddy"
    } else if lower.contains("codewhale") {
        "codewhale"
    } else if lower.contains("claude") {
        "claude-code"
    } else if lower.contains("windsurf") || lower.contains("codeium") {
        "windsurf"
    } else if lower.contains("zed") {
        "zed"
    } else if lower.contains("copilot")
        || lower.contains("github")
        || lower.contains("visual studio code")
        || lower.contains("vscode")
    {
        "vscode-copilot"
    } else if lower.contains("kiro") {
        "kiro"
    } else if lower.contains("codex") || lower.contains("openai") {
        "codex"
    } else if lower.contains("antigravity") {
        "antigravity"
    } else if lower.contains("gemini") {
        "gemini-cli"
    } else {
        "unknown"
    }
}

fn identify_client(lower: &str) -> String {
    // Hosts whose names contain another host's keyword come first: Kilo Code
    // and Roo Code before Cline, the Copilot CLI before VS Code Copilot,
    // Claude Desktop before Claude Code, Visual Studio before VS Code.
    let has = |words: &[&str]| words.iter().any(|word| lower.contains(word));
    let id = if lower.contains("cursor") {
        "cursor"
    } else if lower.contains("codebuddy") {
        "codebuddy"
    } else if lower.contains("codewhale") {
        // #1402. Matched on the product name only — CodeWhale's legacy config
        // dir is `~/.deepseek`, but "deepseek" is a *model* family name that
        // shows up in unrelated clients' identifiers, so it is not a client
        // discriminator here.
        "codewhale"
    } else if has(&["claude-ai", "claude desktop", "claude-desktop"]) {
        "claude-desktop"
    } else if lower.contains("claude") {
        "claude-code"
    } else if lower.contains("windsurf") || lower.contains("codeium") {
        "windsurf"
    } else if lower.contains("zed") {
        "zed"
    } else if has(&["copilot-cli", "copilot cli"]) {
        "copilot-cli"
    } else if has(&["visual-studio", "visualstudio"])
        || (lower.contains("visual studio") && !lower.contains("visual studio code"))
    {
        "visual-studio"
    } else if lower.contains("kilo") {
        "kilo-code"
    } else if has(&["roo-code", "roo code", "roocode", "roo-cline"]) {
        "roo-code"
    } else if lower.contains("cline") {
        "cline"
    } else if lower.contains("copilot")
        || lower.contains("github")
        || lower.contains("visual studio code")
        || lower.contains("vscode")
    {
        "vscode-copilot"
    } else if lower.contains("kiro") {
        "kiro"
    } else if lower.contains("chatgpt") {
        "chatgpt"
    } else if lower.contains("codex") || lower.contains("openai") {
        "codex"
    } else if lower.contains("antigravity") {
        "antigravity"
    } else if lower.contains("gemini") {
        "gemini-cli"
    } else if lower.contains("qwen") {
        "qwen-code"
    } else if lower.contains("opencode") {
        "opencode"
    } else if lower.contains("goose") {
        "goose"
    } else if lower == "amp" || lower.starts_with("amp-") || lower.starts_with("amp ") {
        "amp"
    } else if lower.contains("augment") {
        "augment"
    } else if has(&[
        "jetbrains",
        "intellij",
        "pycharm",
        "webstorm",
        "goland",
        "junie",
    ]) {
        "jetbrains"
    } else if lower.contains("warp") {
        "warp"
    } else if lower == "trae" || lower.starts_with("trae-") || lower.starts_with("trae ") {
        "trae"
    } else if lower.contains("crush") {
        "crush"
    } else if has(&["lm studio", "lm-studio", "lmstudio"]) {
        "lm-studio"
    } else if has(&["neovim", "nvim", "mcphub"]) {
        "neovim"
    } else if has(&["emacs", "gptel"]) {
        "emacs"
    } else if has(&["factory-droid", "factory droid", "factory.ai"]) || lower == "factory" {
        "factory"
    } else if lower.contains("continue") {
        "continue"
    } else {
        "unknown"
    };
    id.to_string()
}

/// Whether any process recorded an MCP handshake within `max_age_secs`,
/// recognised or not. Separates "no MCP client" (CLI and shell hooks only)
/// from "a client LeanCTX does not recognise" for telemetry.
pub(crate) fn handshake_seen(max_age_secs: u64) -> bool {
    let Some(content) = persisted_path().and_then(|path| std::fs::read_to_string(path).ok()) else {
        return false;
    };
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map_or(0, |d| d.as_secs());
    serde_json::from_str::<serde_json::Value>(&content)
        .ok()
        .and_then(|val| val.get("ts").and_then(serde_json::Value::as_u64))
        .is_some_and(|ts| now.saturating_sub(ts) <= max_age_secs)
}

static GLOBAL: OnceLock<Mutex<ClientMcpCapabilities>> = OnceLock::new();

pub(crate) fn global() -> &'static Mutex<ClientMcpCapabilities> {
    GLOBAL.get_or_init(|| Mutex::new(ClientMcpCapabilities::default()))
}

pub(crate) fn set_detected(caps: &ClientMcpCapabilities) {
    if let Ok(mut g) = global().lock() {
        *g = caps.clone();
    }
    persist_to_disk(caps);
}

pub(crate) fn current() -> ClientMcpCapabilities {
    global().lock().map(|g| g.clone()).unwrap_or_default()
}

/// Load persisted client info from disk (for cross-process use, e.g. dashboard).
/// Returns `None` if file missing or older than `max_age_secs`.
pub(crate) fn load_persisted(max_age_secs: u64) -> Option<ClientMcpCapabilities> {
    let path = persisted_path()?;
    let content = std::fs::read_to_string(&path).ok()?;
    let val: serde_json::Value = serde_json::from_str(&content).ok()?;

    let ts = val.get("ts").and_then(serde_json::Value::as_u64)?;
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map_or(0, |d| d.as_secs());
    if now.saturating_sub(ts) > max_age_secs {
        return None;
    }

    let client_id = val
        .get("client_id")
        .and_then(|v| v.as_str())
        .unwrap_or("unknown")
        .to_string();

    if client_id == "unknown" {
        return None;
    }

    Some(ClientMcpCapabilities::detect(&client_id))
}

fn persisted_path() -> Option<std::path::PathBuf> {
    Some(
        super::data_dir::lean_ctx_data_dir()
            .ok()?
            .join("client-id.json"),
    )
}

fn persist_to_disk(caps: &ClientMcpCapabilities) {
    let Some(path) = persisted_path() else {
        return;
    };
    let ts = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map_or(0, |d| d.as_secs());
    let payload = serde_json::json!({
        "client_id": caps.client_id,
        "tier": caps.tier(),
        "features": caps.format_summary(),
        "ts": ts,
    });
    let tmp = path.with_extension("tmp");
    if let Ok(json) = serde_json::to_string_pretty(&payload)
        && std::fs::write(&tmp, &json).is_ok()
    {
        let _ = std::fs::rename(&tmp, &path);
    }
}

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

    #[test]
    fn cursor_detection() {
        let caps = ClientMcpCapabilities::detect("Cursor");
        assert_eq!(caps.client_id, "cursor");
        assert!(caps.resources);
        assert!(caps.prompts);
        assert!(caps.elicitation);
        assert!(caps.dynamic_tools);
        assert_eq!(caps.tier(), 1);
    }

    #[test]
    fn claude_code_detection() {
        let caps = ClientMcpCapabilities::detect("claude-code");
        assert_eq!(caps.client_id, "claude-code");
        assert!(caps.sampling);
        assert_eq!(caps.tier(), 1);
    }

    #[test]
    fn windsurf_detection() {
        let caps = ClientMcpCapabilities::detect("Windsurf");
        assert_eq!(caps.client_id, "windsurf");
        assert!(!caps.resources);
        assert!(!caps.prompts);
        assert_eq!(caps.max_tools, Some(100));
        assert_eq!(caps.tier(), 3);
    }

    #[test]
    fn codewhale_detection_is_distinct_and_not_confused_with_deepseek_models() {
        assert_eq!(identify_client("codewhale"), "codewhale");
        assert_eq!(identify_client("codewhale/0.9.9"), "codewhale");
        // "deepseek" alone is a model family, not the CodeWhale client (#1402).
        assert_eq!(identify_client("deepseek-v3"), "unknown");
    }

    #[test]
    fn unknown_client_tier4() {
        let caps = ClientMcpCapabilities::detect("random-editor");
        assert_eq!(caps.client_id, "unknown");
        assert_eq!(caps.tier(), 4);
    }

    #[test]
    fn copilot_detection() {
        let caps = ClientMcpCapabilities::detect("GitHub Copilot");
        assert_eq!(caps.client_id, "vscode-copilot");
        assert!(caps.resources);
        assert!(caps.prompts);
        assert!(caps.dynamic_tools);
        assert_eq!(caps.tier(), 2);
    }

    #[test]
    fn vscode_plain_detection() {
        let caps = ClientMcpCapabilities::detect("Visual Studio Code");
        assert_eq!(caps.client_id, "vscode-copilot");
        assert_eq!(caps.tier(), 2);
    }

    #[test]
    fn vscode_lowercase_detection() {
        let caps = ClientMcpCapabilities::detect("vscode");
        assert_eq!(caps.client_id, "vscode-copilot");
        assert_eq!(caps.tier(), 2);
    }

    #[test]
    fn client_hint_override() {
        let caps = ClientMcpCapabilities::detect_with_hint(
            "random-unknown-editor",
            Some("vscode-copilot"),
        );
        assert_eq!(caps.client_id, "vscode-copilot");
        assert_eq!(caps.tier(), 2);
    }

    #[test]
    fn client_hint_empty_falls_back() {
        let caps = ClientMcpCapabilities::detect_with_hint("Cursor", Some(""));
        assert_eq!(caps.client_id, "cursor");
        assert_eq!(caps.tier(), 1);
    }

    #[test]
    fn more_hosts_are_named_without_changing_their_capabilities() {
        for (name, id, same_caps_as) in [
            ("Cline", "cline", "unknown-editor"),
            ("Roo Code", "roo-code", "unknown-editor"),
            ("Kilo Code", "kilo-code", "unknown-editor"),
            ("continue-client", "continue", "unknown-editor"),
            ("opencode", "opencode", "unknown-editor"),
            ("goose", "goose", "unknown-editor"),
            ("amp", "amp", "unknown-editor"),
            ("JetBrains AI Assistant", "jetbrains", "unknown-editor"),
            ("claude-ai", "claude-desktop", "claude-code"),
            ("GitHub Copilot CLI", "copilot-cli", "vscode-copilot"),
            ("Visual Studio", "visual-studio", "unknown-editor"),
            ("LM Studio", "lm-studio", "unknown-editor"),
            ("Qwen Code", "qwen-code", "unknown-editor"),
        ] {
            let caps = ClientMcpCapabilities::detect_with_hint(name, None);
            let reference = ClientMcpCapabilities::detect_with_hint(same_caps_as, None);
            assert_eq!(caps.client_id, id, "{name}");
            assert_eq!(
                (
                    caps.resources,
                    caps.prompts,
                    caps.elicitation,
                    caps.sampling,
                    caps.dynamic_tools,
                    caps.max_tools
                ),
                (
                    reference.resources,
                    reference.prompts,
                    reference.elicitation,
                    reference.sampling,
                    reference.dynamic_tools,
                    reference.max_tools
                ),
                "{name}"
            );
            assert!(
                crate::core::telemetry_v2::ClientFamily::from_client_id(id).is_some(),
                "{id} has a wire family"
            );
            // A persisted id is re-detected as the same host.
            assert_eq!(identify_client(id), id, "{id}");
        }
        assert_eq!(
            ClientMcpCapabilities::detect_with_hint("Visual Studio Code", None).client_id,
            "vscode-copilot"
        );
        assert_eq!(
            ClientMcpCapabilities::detect_with_hint("claude-code", None).client_id,
            "claude-code"
        );
    }

    #[test]
    fn client_hint_none_falls_back() {
        let caps = ClientMcpCapabilities::detect_with_hint("Cursor", None);
        assert_eq!(caps.client_id, "cursor");
        assert_eq!(caps.tier(), 1);
    }

    #[test]
    fn format_summary() {
        let caps = ClientMcpCapabilities::detect("Cursor");
        let s = caps.format_summary();
        assert!(s.contains("cursor"));
        assert!(s.contains("tier 1"));
    }
}