lean-ctx 3.9.14

Context Runtime for AI Agents with CCP. 71 MCP tools, 10 read modes, 95+ compression patterns, cross-session memory (CCP), persistent AI knowledge with temporal facts + contradiction detection, multi-agent context sharing, LITM-aware positioning, AAAK compact format, adaptive compression with Thompson Sampling bandits. Supports 24+ AI tools. Reduces LLM token consumption by up to 99%.
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
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
use std::io::Read;

use super::HOOK_STDIN_TIMEOUT;

const BINARY_EXTENSIONS: &[&str] = &[
    "png", "jpg", "jpeg", "gif", "webp", "ico", "bmp", "svg", "pdf", "zip", "tar", "gz", "bz2",
    "xz", "7z", "rar", "woff", "woff2", "ttf", "otf", "eot", "mp3", "mp4", "wav", "avi", "mov",
    "mkv", "so", "dylib", "dll", "exe", "bin", "o", "a", "class", "pyc", "wasm",
];

/// Handle the `lean-ctx hook deny` subcommand.
///
/// Called by PreToolUse hooks in Replace mode. Denies native Read/Grep/Glob/Shell
/// calls unless an exception applies (binary files, MCP down, etc.).
///
/// Output format matches both Claude Code and Cursor hook protocols.
pub fn handle_deny() {
    let stdin_payload = read_stdin_with_timeout();

    // #1407: Empty/unparseable payload → fail-open. This happens when the hook
    // is invoked with no stdin (e.g. Windsurf pre_mcp_tool_use with broken pipe)
    // or the payload format is completely unrecognized. Blocking in this case
    // would deny ALL tools including lean-ctx's own ctx_* MCP tools.
    if stdin_payload.trim().is_empty() {
        print_allow();
        return;
    }

    let tool_name = extract_tool_name(&stdin_payload);

    // #1407: If tool_name could not be extracted from a non-empty payload,
    // this is likely an MCP event we don't understand. Fail-open rather than
    // blocking unknown payloads — the deny hook's scope is native tools only.
    if tool_name.is_empty() {
        print_allow();
        return;
    }

    let file_path = extract_file_path(&stdin_payload);

    // #805: deny Write/Edit payloads that contain compression markers.
    // These indicate the agent is writing compressed ctx_read output to disk.
    if is_write_tool(&tool_name) {
        if !is_compression_guard_disabled()
            && let Some(content) = extract_write_content(&stdin_payload)
            && has_compression_markers(&content)
        {
            print_deny_compression_markers(&tool_name);
        }
        print_allow();
        return;
    }

    if should_allow(&tool_name, file_path.as_deref()) {
        print_allow();
    } else {
        print_smart_deny(&tool_name, &stdin_payload);
    }
}

fn should_allow(tool_name: &str, file_path: Option<&str>) -> bool {
    if super::is_disabled() {
        return true;
    }

    // GH #1329: lean-ctx MCP tools must never be blocked by the deny hook.
    // Devin (ex-Windsurf) routes MCP calls through its own PreToolUse
    // pipeline, so ctx_* tool invocations hit the deny hook. Allow them.
    if is_lean_ctx_tool(tool_name) {
        return true;
    }

    // Shadow-only surface: hooks compress native tools transparently,
    // so the deny guard must not block them.
    if is_shadow_only_surface() {
        return true;
    }

    if !is_mcp_server_reachable() {
        return true;
    }

    if file_path.is_some_and(is_binary_file) {
        return true;
    }

    // GH #1228: Claude/CodeBuddy auto memory must use native Read/Edit even
    // when Replace-mode deny hooks are installed.
    if file_path.is_some_and(|p| {
        crate::core::pathjail::is_harness_auto_memory_path(std::path::Path::new(p))
    }) {
        return true;
    }

    if is_replace_mode_disabled() {
        return true;
    }

    false
}

fn is_lean_ctx_tool(tool_name: &str) -> bool {
    tool_name.starts_with("ctx_") || tool_name == "shell"
}

fn is_mcp_server_reachable() -> bool {
    let path = crate::daemon::daemon_pid_path();
    if !path.exists() {
        return true;
    }
    if let Ok(pid_str) = std::fs::read_to_string(&path)
        && let Ok(pid) = pid_str.trim().parse::<u32>()
        && !crate::ipc::process::is_alive(pid)
    {
        return false;
    }
    true
}

/// Whether the shadow-only tool surface is explicitly configured. The deny guard
/// runs in hook context (no MCP client name available), so only an explicit
/// `tool_surface = "shadow"` disables it. `"auto"` keeps the guard active
/// because the hook cannot determine whether THIS client is hook-covered —
/// the MCP server's `list_tools` handler makes that decision per-client.
fn is_shadow_only_surface() -> bool {
    if let Ok(v) = std::env::var("LEAN_CTX_TOOL_SURFACE") {
        return v.eq_ignore_ascii_case("shadow");
    }
    let cfg = crate::core::config::Config::load();
    matches!(cfg.tool_surface.as_deref(), Some("shadow"))
}

fn is_replace_mode_disabled() -> bool {
    matches!(
        std::env::var("LEAN_CTX_REPLACE_MODE"),
        Ok(v) if v.trim() == "0" || v.trim().eq_ignore_ascii_case("off")
    )
}

fn is_binary_file(path: &str) -> bool {
    if let Some(ext) = path.rsplit('.').next() {
        return BINARY_EXTENSIONS.contains(&ext.to_lowercase().as_str());
    }
    false
}

fn extract_tool_name(payload: &str) -> String {
    if let Ok(json) = serde_json::from_str::<serde_json::Value>(payload) {
        // Claude Code / generic: top-level `tool_name`
        if let Some(name) = json.get("tool_name").and_then(serde_json::Value::as_str) {
            return name.to_string();
        }
        // Cursor: `hookSpecificInput.toolName`
        if let Some(name) = json
            .get("hookSpecificInput")
            .and_then(|h| h.get("toolName"))
            .and_then(serde_json::Value::as_str)
        {
            return name.to_string();
        }
        // #1407: Windsurf/Devin MCP hook format: `tool_info.mcp_tool_name`
        // (fires on pre_mcp_tool_use events, which carry the MCP tool name
        // in a nested object rather than the top-level tool_name field)
        if let Some(name) = json
            .get("tool_info")
            .and_then(|ti| ti.get("mcp_tool_name"))
            .and_then(serde_json::Value::as_str)
        {
            return name.to_string();
        }
        // Devin variant: `toolName` at top level (no nesting)
        if let Some(name) = json.get("toolName").and_then(serde_json::Value::as_str) {
            return name.to_string();
        }
    }
    String::new()
}

fn extract_file_path(payload: &str) -> Option<String> {
    let json: serde_json::Value = serde_json::from_str(payload).ok()?;

    let input = json
        .get("input")
        .or_else(|| json.get("hookSpecificInput").and_then(|h| h.get("input")));

    if let Some(input) = input {
        for key in ["file_path", "path", "filePath"] {
            if let Some(path) = input.get(key).and_then(serde_json::Value::as_str) {
                return Some(path.to_string());
            }
        }
    }
    None
}

fn is_write_tool(tool_name: &str) -> bool {
    matches!(
        tool_name,
        "Write"
            | "write"
            | "WriteFile"
            | "Edit"
            | "edit"
            | "MultiEdit"
            | "StrReplace"
            | "str_replace"
            | "EditNotebook"
    )
}

fn is_compression_guard_disabled() -> bool {
    std::env::var("LEAN_CTX_ALLOW_COMPRESSED_WRITE")
        .is_ok_and(|v| v.trim() == "1" || v.trim().eq_ignore_ascii_case("true"))
}

fn has_compression_markers(content: &str) -> bool {
    if content.contains("[lean-ctx:") || content.contains("--- lean-ctx:") {
        return true;
    }
    // Detect ctx_read build_header corruption (#1323): "filename.ext NNL"
    // followed by " deps " or " exports " on the next line.
    static HEADER_RE: std::sync::LazyLock<regex::Regex> = std::sync::LazyLock::new(|| {
        regex::Regex::new(r"(?m)^\S+\.\w+ \d+L\n (?:deps|exports) ")
            .expect("HEADER_RE is a valid regex pattern")
    });
    static MAP_RE: std::sync::LazyLock<regex::Regex> = std::sync::LazyLock::new(|| {
        regex::Regex::new(r"(?m)(?:@L\d+-\d+|^\s+API:\s*$|^\S+\.\w+ \d+L\n\s+deps:)")
            .expect("MAP_RE is a valid regex pattern")
    });
    HEADER_RE.is_match(content) || MAP_RE.is_match(content)
}

fn extract_write_content(payload: &str) -> Option<String> {
    let json: serde_json::Value = serde_json::from_str(payload).ok()?;
    let input = json
        .get("input")
        .or_else(|| json.get("hookSpecificInput").and_then(|h| h.get("input")))?;

    let mut combined = String::new();

    // Check all common content field names across tool variants.
    // For StrReplace we must check BOTH old_string and new_string:
    // if old_string contains markers, the agent read a compressed file
    // and the resulting write will embed markers in the file. (#1302)
    for key in [
        "content",
        "contents",
        "file_text",
        "text",
        "new_string",
        "new_text",
        "old_string",
        "old_text",
    ] {
        if let Some(text) = input.get(key).and_then(serde_json::Value::as_str) {
            combined.push_str(text);
            combined.push('\n');
        }
    }

    // MultiEdit: check edits array for old_text/new_text
    if let Some(edits) = input.get("edits").and_then(|v| v.as_array()) {
        for edit in edits {
            for key in ["old_text", "oldText", "new_text", "newText"] {
                if let Some(t) = edit.get(key).and_then(serde_json::Value::as_str) {
                    combined.push_str(t);
                    combined.push('\n');
                }
            }
        }
    }

    if combined.is_empty() {
        None
    } else {
        Some(combined)
    }
}

fn print_deny_compression_markers(tool_name: &str) {
    let msg = format!(
        "Blocked {tool_name}: payload contains lean-ctx compression markers \
         ([lean-ctx: omitted ...] or similar). Writing compressed ctx_read \
         output to disk corrupts files. Use ctx_read(raw=true) or ctx_expand \
         to recover full content before editing. \
         Set LEAN_CTX_ALLOW_COMPRESSED_WRITE=1 to override."
    );
    let output = serde_json::json!({
        // Grok PreToolUse decision field.
        "decision": "deny",
        "reason": msg,
        "permission": "deny",
        "user_message": msg
    });
    println!("{output}");
    std::process::exit(2);
}

/// Build a smart deny message that includes the exact ctx_* call with mapped arguments.
/// This reduces cognitive load for the LLM and prevents instruction drift.
fn smart_deny_message(tool_name: &str, payload: &str) -> String {
    let args = extract_tool_args(payload);
    match tool_name {
        "Read" | "read" | "ReadFile" | "read_file" => build_ctx_read_hint(&args),
        "Grep" | "grep" | "Search" => build_ctx_search_hint(&args),
        "Glob" | "glob" | "list_dir" => build_ctx_glob_hint(&args),
        "Shell" | "Bash" | "bash" | "run_terminal_command" => build_ctx_shell_hint(&args),
        _ => "Use the equivalent ctx_* tool — lean-ctx replace mode is active.".to_string(),
    }
}

fn extract_tool_args(payload: &str) -> serde_json::Map<String, serde_json::Value> {
    let Ok(json) = serde_json::from_str::<serde_json::Value>(payload) else {
        return serde_json::Map::new();
    };
    json.get("input")
        .or_else(|| json.get("hookSpecificInput").and_then(|h| h.get("input")))
        .and_then(|v| v.as_object())
        .cloned()
        .unwrap_or_default()
}

fn build_ctx_read_hint(args: &serde_json::Map<String, serde_json::Value>) -> String {
    let mut parts = Vec::new();
    if let Some(path) = args
        .get("path")
        .or_else(|| args.get("file_path"))
        .and_then(serde_json::Value::as_str)
    {
        parts.push(format!("path=\"{path}\""));
    }
    if let Some(start) = args
        .get("offset")
        .or_else(|| args.get("start_line"))
        .and_then(serde_json::Value::as_i64)
    {
        parts.push(format!("start_line={start}"));
    }
    if let Some(limit) = args
        .get("limit")
        .or_else(|| args.get("end_line"))
        .and_then(serde_json::Value::as_i64)
    {
        parts.push(format!("limit={limit}"));
    }
    let call = if parts.is_empty() {
        "ctx_read(path=\"<file>\")".to_string()
    } else {
        format!("ctx_read({})", parts.join(", "))
    };
    format!("[DENIED] Native Read blocked. Use: {call} — lean-ctx replace mode is active.")
}

fn build_ctx_search_hint(args: &serde_json::Map<String, serde_json::Value>) -> String {
    let mut parts = Vec::new();
    if let Some(pat) = args
        .get("pattern")
        .or_else(|| args.get("regex"))
        .and_then(serde_json::Value::as_str)
    {
        parts.push(format!("pattern=\"{pat}\""));
    }
    if let Some(path) = args
        .get("path")
        .or_else(|| args.get("include"))
        .and_then(serde_json::Value::as_str)
    {
        parts.push(format!("path=\"{path}\""));
    }
    if let Some(glob) = args.get("glob").and_then(serde_json::Value::as_str) {
        parts.push(format!("include=\"{glob}\""));
    }
    let call = if parts.is_empty() {
        "ctx_search(pattern=\"<pattern>\")".to_string()
    } else {
        format!("ctx_search({})", parts.join(", "))
    };
    format!(
        "[DENIED] Native Grep blocked. Use: {call} — ctx_search also supports action=symbol, action=semantic."
    )
}

fn build_ctx_glob_hint(args: &serde_json::Map<String, serde_json::Value>) -> String {
    let mut parts = Vec::new();
    if let Some(pat) = args
        .get("pattern")
        .or_else(|| args.get("glob_pattern"))
        .and_then(serde_json::Value::as_str)
    {
        parts.push(format!("pattern=\"{pat}\""));
    }
    if let Some(path) = args
        .get("path")
        .or_else(|| args.get("target_directory"))
        .and_then(serde_json::Value::as_str)
    {
        parts.push(format!("path=\"{path}\""));
    }
    let call = if parts.is_empty() {
        "ctx_glob(pattern=\"<glob>\")".to_string()
    } else {
        format!("ctx_glob({})", parts.join(", "))
    };
    format!("[DENIED] Native Glob blocked. Use: {call} — or ctx_tree for directory overview.")
}

fn build_ctx_shell_hint(args: &serde_json::Map<String, serde_json::Value>) -> String {
    let cmd = args
        .get("command")
        .or_else(|| args.get("cmd"))
        .and_then(serde_json::Value::as_str)
        .unwrap_or("<command>");
    let short_cmd = if cmd.len() > 80 { &cmd[..80] } else { cmd };
    format!(
        "[DENIED] Native Shell blocked. Use: ctx_shell(command=\"{short_cmd}\") — lean-ctx replace mode is active."
    )
}

fn print_smart_deny(tool_name: &str, payload: &str) {
    let msg = smart_deny_message(tool_name, payload);
    let output = serde_json::json!({
        // Grok PreToolUse decision field.
        "decision": "deny",
        "reason": msg,
        "permission": "deny",
        "user_message": msg
    });
    println!("{output}");
    std::process::exit(2);
}

fn print_allow() {
    println!("{{}}");
}

fn read_stdin_with_timeout() -> String {
    let (tx, rx) = std::sync::mpsc::channel();
    std::thread::spawn(move || {
        let mut buf = String::new();
        let _ = std::io::stdin().read_to_string(&mut buf);
        let _ = tx.send(buf);
    });
    rx.recv_timeout(HOOK_STDIN_TIMEOUT).unwrap_or_default()
}

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

    #[test]
    fn is_write_tool_recognizes_all_variants() {
        assert!(is_write_tool("Write"));
        assert!(is_write_tool("write"));
        assert!(is_write_tool("Edit"));
        assert!(is_write_tool("StrReplace"));
        assert!(is_write_tool("MultiEdit"));
        assert!(is_write_tool("EditNotebook"));
        assert!(!is_write_tool("Read"));
        assert!(!is_write_tool("Grep"));
        assert!(!is_write_tool("Shell"));
    }

    #[test]
    fn has_compression_markers_detects_lean_ctx_patterns() {
        assert!(has_compression_markers(
            "some text [lean-ctx: omitted 42 lines] more"
        ));
        assert!(has_compression_markers("... [lean-ctx: archived] ..."));
        assert!(!has_compression_markers("[lean-ctx compressed] tail"));
        assert!(!has_compression_markers(
            "[lean-ctx docs](https://example.com)"
        ));
        assert!(!has_compression_markers(
            "normal file content without markers"
        ));
        assert!(!has_compression_markers("lean-ctx is great"));
        assert!(!has_compression_markers(""));
    }

    #[test]
    fn has_compression_markers_detects_footer_marker() {
        assert!(has_compression_markers("content\n--- lean-ctx: end ---\n"));
    }

    #[test]
    fn has_compression_markers_detects_build_header_corruption() {
        // #1323: ctx_read build_header format "mod.rs 1225L\n deps ..."
        assert!(has_compression_markers(
            "mod.rs 1225L\n deps super::foo,bar\n"
        ));
        assert!(has_compression_markers(
            "server_handler.rs 340L\n exports handle_request\n"
        ));
        // Must NOT trigger on normal Rust content
        assert!(!has_compression_markers("let x = 1225;\n deps: vec![]\n"));
        assert!(!has_compression_markers("// mod.rs has 1225 lines\n"));
    }

    #[test]
    fn detects_map_outline_patterns() {
        assert!(has_compression_markers("class pub Foo @L12-34"));
        assert!(has_compression_markers(
            "fn pub run(id:usize) → bool @L372-383"
        ));
        assert!(has_compression_markers("  API:\n    class pub Bar"));
        assert!(has_compression_markers("events.py 1045L\n  deps: foo, bar"));
    }

    #[test]
    fn allows_normal_code() {
        assert!(!has_compression_markers(
            "fn main() { println!(\"hello\"); }"
        ));
        assert!(!has_compression_markers("let x = @L12;"));
    }

    #[test]
    fn extract_write_content_from_cursor_write() {
        let payload = r#"{"hookSpecificInput":{"toolName":"Write","input":{"path":"test.md","contents":"hello [lean-ctx: omitted 5 lines]"}}}"#;
        let content = extract_write_content(payload).unwrap();
        assert!(content.contains("[lean-ctx:"));
    }

    #[test]
    fn extract_write_content_from_claude_code_edit() {
        let payload = r#"{"tool_name":"Edit","input":{"path":"test.rs","new_text":"fn foo() { [lean-ctx: omitted 10 lines] }"}}"#;
        let content = extract_write_content(payload).unwrap();
        assert!(content.contains("[lean-ctx:"));
    }

    #[test]
    fn extract_write_content_from_multi_edit() {
        let payload = r#"{"tool_name":"MultiEdit","input":{"path":"x.rs","edits":[{"new_text":"[lean-ctx: omitted 3 lines]"}]}}"#;
        let content = extract_write_content(payload).unwrap();
        assert!(content.contains("[lean-ctx:"));
    }

    #[test]
    fn extract_write_content_clean_payload_returns_none_for_markers() {
        let payload =
            r#"{"tool_name":"Write","input":{"path":"test.md","contents":"normal content"}}"#;
        let content = extract_write_content(payload).unwrap();
        assert!(!has_compression_markers(&content));
    }

    #[test]
    fn extract_write_content_no_content_returns_none() {
        let payload = r#"{"tool_name":"Write","input":{"path":"test.md"}}"#;
        assert!(extract_write_content(payload).is_none());
    }

    #[test]
    fn extract_write_content_catches_markers_in_old_string() {
        // #1302: StrReplace with compressed old_string means the agent read a
        // compressed file. The resulting write will embed markers in the file.
        let payload = r#"{"tool_name":"StrReplace","input":{"path":"README.md","old_string":"text [lean-ctx: omitted 5 lines] more","new_string":"clean replacement"}}"#;
        let content = extract_write_content(payload).unwrap();
        assert!(
            has_compression_markers(&content),
            "old_string with markers must trigger the guard"
        );
    }

    #[test]
    fn extract_write_content_clean_str_replace_passes() {
        let payload = r#"{"tool_name":"StrReplace","input":{"path":"README.md","old_string":"old text","new_string":"new text"}}"#;
        let content = extract_write_content(payload).unwrap();
        assert!(
            !has_compression_markers(&content),
            "clean StrReplace must not trigger the guard"
        );
    }

    #[test]
    fn should_allow_lean_ctx_tools() {
        assert!(should_allow("ctx_tree", None));
        assert!(should_allow("ctx_read", Some("/tmp/test.rs")));
        assert!(should_allow("ctx_search", None));
        assert!(should_allow("ctx_shell", None));
        assert!(should_allow("ctx_compose", None));
        assert!(should_allow("shell", None));
    }

    #[test]
    fn is_lean_ctx_tool_checks() {
        assert!(is_lean_ctx_tool("ctx_tree"));
        assert!(is_lean_ctx_tool("ctx_read"));
        assert!(is_lean_ctx_tool("shell"));
        assert!(!is_lean_ctx_tool("Read"));
        assert!(!is_lean_ctx_tool("Grep"));
        assert!(!is_lean_ctx_tool("Shell"));
    }

    #[test]
    fn should_allow_claude_auto_memory_paths() {
        assert!(should_allow(
            "Read",
            Some("/home/jules/.claude/projects/-slug/memory/MEMORY.md")
        ));
        assert!(
            !should_allow("Read", Some("/home/jules/project/src/main.rs")),
            "ordinary project files stay denied under replace deny hooks"
        );
    }

    #[test]
    fn extract_tool_name_windsurf_mcp_format() {
        // #1407: Windsurf/Devin sends MCP tool name in tool_info.mcp_tool_name
        let payload = r#"{"tool_info":{"mcp_tool_name":"ctx_tree","server":"lean-ctx"}}"#;
        assert_eq!(extract_tool_name(payload), "ctx_tree");
    }

    #[test]
    fn extract_tool_name_empty_payload_returns_empty() {
        // #1407: Empty or unparseable payloads must not return a fake tool name
        assert_eq!(extract_tool_name(""), "");
        assert_eq!(extract_tool_name("not json"), "");
        assert_eq!(extract_tool_name("{}"), "");
    }

    #[test]
    fn extract_tool_name_top_level_tool_name_variant() {
        let payload = r#"{"toolName":"ctx_read"}"#;
        assert_eq!(extract_tool_name(payload), "ctx_read");
    }
}