aether-mcp-servers 0.4.28

Built-in MCP tool servers for the Aether AI agent framework
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
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
use aether_project::PromptCatalog;
use clap::Parser;
use rmcp::{
    RoleServer, ServerHandler,
    handler::server::{
        router::tool::ToolRouter,
        wrapper::{Json, Parameters},
    },
    model::{
        CreateElicitationRequestParams, ElicitationSchema, EnumSchema, Implementation, ProgressNotificationParam,
        ServerCapabilities, ServerInfo,
    },
    service::RequestContext,
    tool, tool_handler, tool_router,
};
use std::fmt::Write as _;
use std::path::PathBuf;
use std::{
    collections::{HashMap, HashSet},
    sync::Arc,
};
use tokio::{
    fs::try_exists,
    sync::{Mutex, RwLock},
};

pub mod default_tools;
pub mod error;
pub mod prompt_rule_matcher;
pub mod tools;
pub mod tools_trait;

pub use default_tools::DefaultCodingTools;
pub use tools_trait::CodingTools;

use crate::lsp::tools::check_errors::{LspDiagnosticsOutput, LspDiagnosticsRequest, execute_lsp_diagnostics};
use crate::lsp::tools::symbol_lookup::{LspSymbolInput, LspSymbolOutput, execute_lsp_symbol};
use crate::lsp::tools::workspace_search::{
    LspWorkspaceSearchInput, LspWorkspaceSearchOutput, execute_lsp_workspace_search,
};
use crate::{coding::prompt_rule_matcher::PromptRuleMatcher, lsp::registry::LspRegistry};
use crate::{
    error::ServerInitError,
    lsp::tools::rename::{LspRenameInput, LspRenameOutput, execute_lsp_rename},
};
use crate::{
    lsp::tools::document_info::{LspDocumentInput, LspDocumentOutput, execute_lsp_document},
    workspace_paths::WorkspacePaths,
};

use mcp_utils::display_meta::{ToolDisplayMeta, ToolResultMeta, basename, truncate};
use tools::ast_grep::{AstGrepInput, AstGrepOutput, perform_ast_grep};
use tools::bash::{
    BackgroundProcessHandle, BashInput, BashOutput, BashResult, ReadBackgroundBashInput, ReadBackgroundBashOutput,
    execute_command_in_dir, read_background_bash,
};
use tools::edit_file::{EditFileArgs, EditFileResponse, edit_file_contents};
use tools::find::{FindInput, FindOutput, find_files};
use tools::grep::{GrepInput, GrepOutput, perform_grep};
use tools::list_files::{ListFilesArgs, ListFilesResult, list_files};
use tools::read_file::{ReadFileArgs, ReadFileResult, read_file_contents};
use tools::web_fetch::{WebFetchInput, WebFetchOutput, WebFetcher};
use tools::web_search::search_client::BraveSearchClient;
use tools::web_search::{WebSearchInput, WebSearchOutput, WebSearcher};
use tools::write_file::{WriteFileArgs, WriteFileResponse, write_file_contents};

/// Extension trait for converting tool results to MCP format
trait IntoMcpResult<T> {
    fn into_mcp(self) -> Result<Json<T>, String>;
}

impl<T, E: std::fmt::Display> IntoMcpResult<T> for Result<T, E> {
    fn into_mcp(self) -> Result<Json<T>, String> {
        self.map(Json).map_err(|e| e.to_string())
    }
}

#[doc = include_str!("../docs/permission_mode.md")]
#[derive(Debug, Clone, Default, PartialEq, clap::ValueEnum)]
pub enum PermissionMode {
    /// Everything auto-executes (current default behavior).
    #[default]
    AlwaysAllow,
    /// File writes auto-execute; destructive bash commands trigger elicitation.
    Auto,
    /// All write/edit/bash calls trigger elicitation; read-only tools are ungated.
    AlwaysAsk,
}

/// CLI arguments for `CodingMcp` server
#[derive(Debug, Clone, Default, Parser)]
pub struct CodingMcpArgs {
    /// Root directory for path resolution and LSP initialization.
    #[arg(long = "root-dir")]
    pub root_dir: Option<PathBuf>,

    /// Prompt directories to scan for automatic read-triggered rules.
    /// Can be specified multiple times: --rules-dir .aether/skills --rules-dir .claude/rules
    #[arg(long = "rules-dir")]
    pub rules_dirs: Vec<PathBuf>,

    /// Permission mode controlling user approval for tool calls
    #[arg(long = "permission-mode", default_value = "always-allow")]
    pub permission_mode: PermissionMode,

    /// Disable LSP-backed coding tools and daemon connections.
    #[arg(long = "disable-lsp")]
    pub disable_lsp: bool,
}

impl CodingMcpArgs {
    pub fn from_args(args: Vec<String>) -> Result<Self, ServerInitError> {
        let mut full_args = vec!["coding-mcp".to_string()];
        full_args.extend(args);

        Self::try_parse_from(full_args).map_err(ServerInitError::InvalidArgs)
    }
}

#[doc = include_str!("../docs/coding_mcp.md")]
#[derive(Debug)]
pub struct CodingMcp<T: CodingTools = DefaultCodingTools> {
    tool_router: ToolRouter<Self>,
    background_processes: Mutex<HashMap<String, BackgroundProcessHandle>>,
    /// Track files that have been read to enforce read-before-edit safety
    files_read: RwLock<HashSet<String>>,
    tools: T,
    /// Optional LSP operations (enabled with `.with_lsp()`)
    lsp: Option<Arc<LspRegistry>>,
    web_fetcher: WebFetcher,
    web_searcher: Option<WebSearcher<BraveSearchClient>>,
    /// Root directory used for path resolution and tool instructions.
    root_dir: PathBuf,
    /// Read rules discovered from skill files (activated on file reads)
    read_rule_state: prompt_rule_matcher::PromptRuleMatcher,
    /// Configured prompt directories used to build read rules.
    configured_rules_dirs: Vec<PathBuf>,
    /// Permission mode controlling user approval for tool calls
    permission_mode: PermissionMode,
}

fn build_rule_catalog(configured_rules_dirs: &[PathBuf]) -> aether_project::PromptCatalog {
    if configured_rules_dirs.is_empty() {
        return aether_project::PromptCatalog::empty();
    }

    PromptCatalog::from_dirs(configured_rules_dirs)
}

#[tool_handler(router = self.tool_router)]
impl<T: CodingTools + 'static> ServerHandler for CodingMcp<T> {
    fn get_info(&self) -> ServerInfo {
        let instructions = self.build_instructions();
        ServerInfo::new(ServerCapabilities::builder().enable_tools().build())
            .with_server_info(Implementation::new("coding-mcp", "0.1.0"))
            .with_instructions(instructions)
    }
}

impl CodingMcp<DefaultCodingTools> {
    /// Create a new `CodingMcp` with default (local filesystem) tools
    pub fn new() -> Self {
        Self::with_tools(DefaultCodingTools::new())
    }
}

async fn notify_preview(context: &RequestContext<RoleServer>, meta: ToolDisplayMeta) {
    if let Some(token) = context.meta.get_progress_token() {
        let result_meta = ToolResultMeta::from(meta);
        let message = serde_json::to_string(&result_meta).unwrap_or_default();
        let _ = context
            .peer
            .notify_progress(ProgressNotificationParam {
                progress_token: token,
                progress: 0.0,
                total: None,
                message: Some(message),
            })
            .await;
    }
}

/// Returns `true` if the command looks destructive (deletes files, force-pushes, etc.).
///
/// Uses simple substring matching — conservative by design.
fn is_dangerous_cmd(command: &str) -> bool {
    const PATTERNS: &[&str] = &[
        "rm ",
        "rm\t",
        "rmdir ",
        "git push",
        "git reset",
        "git checkout --",
        "git clean",
        "chmod ",
        "chown ",
        "kill ",
        "pkill ",
        "mv ",
        "dd ",
        "--force",
        "--hard",
    ];

    // Check simple substring patterns
    if PATTERNS.iter().any(|p| command.contains(p)) {
        return true;
    }

    // Check redirect operators: only match >/>> that aren't inside quotes or part of =>
    // Simple heuristic: look for "> " or ">> " not preceded by '='
    for (i, _) in command.match_indices("> ") {
        if i == 0 || command.as_bytes()[i - 1] != b'=' {
            return true;
        }
    }

    false
}

#[tool_router]
impl<T: CodingTools + 'static> CodingMcp<T> {
    /// Create a `CodingMcp` with custom tool implementation
    pub fn with_tools(tools: T) -> Self {
        Self {
            tool_router: Self::tool_router(),
            background_processes: Mutex::new(HashMap::new()),
            files_read: RwLock::new(HashSet::new()),
            tools,
            lsp: None,
            web_fetcher: WebFetcher::new(),
            web_searcher: WebSearcher::try_new().ok(),
            root_dir: crate::workspace_paths::current_dir(),
            read_rule_state: prompt_rule_matcher::PromptRuleMatcher::default(),
            configured_rules_dirs: Vec::new(),
            permission_mode: PermissionMode::AlwaysAllow,
        }
    }

    /// Enable LSP code intelligence for the given project root.
    ///
    /// LSP servers for detected project languages are spawned immediately
    /// in the background, allowing indexing to start right away.
    pub fn with_lsp(mut self, root_path: PathBuf) -> Self {
        self.lsp = Some(LspRegistry::new_and_spawn(root_path));
        self
    }

    /// Set the root directory.
    pub fn with_root_dir(mut self, root_dir: PathBuf) -> Self {
        self.root_dir = root_dir;
        self
    }

    /// Set prompt directories used for read-triggered rule activation.
    pub fn with_rules_dirs(mut self, rules_dirs: Vec<PathBuf>) -> Self {
        self.configured_rules_dirs = rules_dirs;
        let catalog = build_rule_catalog(&self.configured_rules_dirs);
        self.read_rule_state = PromptRuleMatcher::new(catalog);
        self
    }

    /// Set the permission mode controlling user approval for tool calls.
    pub fn with_permission_mode(mut self, mode: PermissionMode) -> Self {
        self.permission_mode = mode;
        self
    }

    fn workspace_paths(&self) -> WorkspacePaths {
        WorkspacePaths::new(self.root_dir.clone())
    }

    fn build_instructions(&self) -> String {
        let mut base = String::from(
            r"# Coding MCP Server

File I/O, search, shell, and optional LSP code intelligence tools for coding workflows.

## Quick Reference

- **Text patterns** (TODOs, logs, strings): `grep`
- **Structural code patterns** (AST search): `ast_grep`
- **File names** (find *.test.ts): `find`
- **Read/write/edit** files: `read_file`, `write_file`, `edit_file`
- **Shell commands**: `bash`
",
        );

        if self.lsp.is_some() {
            base.push_str(
                r"- **Errors & warnings** (instant check without build): `lsp_check_errors`
- **Code symbols** (definitions, usages, types): `lsp_symbol`
- **Find symbol across workspace** (don't know the file?): `lsp_workspace_search`
- **File structure** (what's in this file?): `lsp_document`
- **Rename symbol** (refactor across codebase): `lsp_rename`
",
            );
        }

        format!(
            r"{}

When using tools that take file paths, always use absolute paths from:
<workspace-root>{}</workspace-root>",
            base,
            self.root_dir.display()
        )
    }

    /// Prompt the user for approval via elicitation. Always sends the prompt —
    /// callers are responsible for deciding when to call this based on `permission_mode`.
    ///
    /// Returns `Ok(())` if allowed, or `Err` with either a generic decline
    /// message or the user's feedback explaining what to do instead.
    async fn elicit_permission(
        &self,
        context: &RequestContext<RoleServer>,
        tool_name: &str,
        description: &str,
    ) -> Result<(), String> {
        let message = format!("Allow {tool_name}: {description}?");
        let result = context
            .peer
            .create_elicitation(CreateElicitationRequestParams::FormElicitationParams {
                meta: None,
                message,
                requested_schema: ElicitationSchema::builder()
                    .required_enum_schema(
                        "decision",
                        EnumSchema::builder(vec!["allow".into(), "deny".into()])
                            .untitled()
                            .with_default("deny")
                            .unwrap()
                            .build(),
                    )
                    .build()
                    .unwrap(),
            })
            .await
            .map_err(|e| format!("Elicitation failed: {e}"))?;

        let allowed = result.content.as_ref().and_then(|c| c.get("decision")).and_then(|v| v.as_str()) == Some("allow");

        if allowed { Ok(()) } else { Err(format!("Operation declined by user: {tool_name}")) }
    }

    /// Ask the user for permission to run a bash command. In `Auto` mode only
    /// triggers for destructive commands; in `AlwaysAsk` mode triggers always.
    async fn check_bash_permission(&self, context: &RequestContext<RoleServer>, command: &str) -> Result<(), String> {
        match self.permission_mode {
            PermissionMode::AlwaysAllow => Ok(()),
            PermissionMode::AlwaysAsk => self.elicit_permission(context, "bash", command).await,
            PermissionMode::Auto => {
                if is_dangerous_cmd(command) {
                    self.elicit_permission(context, "bash", command).await
                } else {
                    Ok(())
                }
            }
        }
    }

    /// Ask the user for permission to write/edit a file. Only triggers in
    /// `AlwaysAsk` mode; `Auto` and `AlwaysAllow` auto-approve file mutations.
    async fn check_write_permission(
        &self,
        context: &RequestContext<RoleServer>,
        tool_name: &str,
        file_path: &str,
    ) -> Result<(), String> {
        if self.permission_mode == PermissionMode::AlwaysAsk {
            self.elicit_permission(context, tool_name, file_path).await
        } else {
            Ok(())
        }
    }

    fn spawn_diagnostic_refresh(&self, file_path: &str) {
        if let Some(lsp) = &self.lsp {
            let lsp = Arc::clone(lsp);
            let file_path = file_path.to_string();
            tokio::spawn(async move {
                lsp.queue_diagnostic_refresh(&file_path).await;
            });
        }
    }

    /// Resolves a required file-path argument against the root directory,
    /// returning the normalized absolute path as a string.
    fn resolve_file_arg(&self, raw: &str) -> Result<String, String> {
        Ok(self.workspace_paths().resolve_file(raw).map_err(|e| e.to_string())?.to_string_lossy().to_string())
    }

    /// Reads `args.file_path` (already resolved against the root directory),
    /// records it in the read set, and appends any matching read-rule reminders.
    async fn read_and_track(&self, args: ReadFileArgs) -> Result<Json<ReadFileResult>, String> {
        let file_path = args.file_path.clone();
        let mut result = self.tools.read_file(args).await.map_err(|e| e.to_string())?;
        self.files_read.write().await.insert(file_path.clone());

        let total_lines = result.total_lines;
        let matched = self.read_rule_state.get_matched_rules(&self.root_dir, &file_path);
        for rule in &matched {
            write!(result.content, "\n\n<system-reminder>\n{}\n</system-reminder>", rule.body).unwrap();
        }

        if !matched.is_empty() {
            let rule_names: Vec<&str> = matched.iter().map(|r| r.name.as_str()).collect();
            let base = format!("{}, {total_lines} lines", basename(&file_path));
            let value = format!("{base} +rules: {}", rule_names.join(", "));
            result.meta = Some(ToolDisplayMeta::new("Read file", value).into());
        }

        Ok(Json(result))
    }

    /// Read-before-overwrite safety check: an existing file must have been read
    /// first, preventing accidental data loss.
    async fn ensure_read_before_overwrite(&self, file_path: &str) -> Result<(), String> {
        if try_exists(file_path).await.map_err(|e| format!("Failed to check existence of {file_path}: {e}"))?
            && !self.files_read.read().await.contains(file_path)
        {
            return Err(format!(
                "Safety check failed: File '{file_path}' already exists. You must use read_file on it before overwriting. This prevents accidental data loss."
            ));
        }
        Ok(())
    }

    /// Read-before-edit safety check: a file must have been read before editing.
    async fn ensure_read_before_edit(&self, file_path: &str) -> Result<(), String> {
        if !self.files_read.read().await.contains(file_path) {
            return Err(format!(
                "Safety check failed: You must use read_file on '{file_path}' before editing it. This ensures you understand the current file contents before making changes."
            ));
        }
        Ok(())
    }

    #[doc = include_str!("tools/grep/description.md")]
    #[tool(annotations(read_only_hint = true, open_world_hint = false))]
    pub async fn grep(
        &self,
        request: Parameters<GrepInput>,
        context: RequestContext<RoleServer>,
    ) -> Result<Json<GrepOutput>, String> {
        let Parameters(mut args) = request;
        let normalized_path = self.workspace_paths().resolve_dir(args.path.as_deref());
        args.path = Some(normalized_path.to_string_lossy().to_string());
        notify_preview(&context, ToolDisplayMeta::new("Grep", format!("'{}'", args.pattern))).await;
        self.tools.grep(args).await.into_mcp()
    }

    #[doc = include_str!("tools/ast_grep/description.md")]
    #[tool(annotations(read_only_hint = true, open_world_hint = false))]
    pub async fn ast_grep(
        &self,
        request: Parameters<AstGrepInput>,
        context: RequestContext<RoleServer>,
    ) -> Result<Json<AstGrepOutput>, String> {
        let Parameters(mut args) = request;
        let normalized_path = self.workspace_paths().resolve_dir(args.path.as_deref());
        args.path = Some(normalized_path.to_string_lossy().to_string());
        notify_preview(&context, ToolDisplayMeta::new("AST grep", format!("'{}'", args.pattern))).await;
        self.tools.ast_grep(args).await.into_mcp()
    }

    #[doc = include_str!("tools/find/description.md")]
    #[tool(annotations(read_only_hint = true, open_world_hint = false))]
    pub async fn find(
        &self,
        request: Parameters<FindInput>,
        context: RequestContext<RoleServer>,
    ) -> Result<Json<FindOutput>, String> {
        let Parameters(mut args) = request;
        let normalized_path = self.workspace_paths().resolve_dir(args.path.as_deref());
        args.path = Some(normalized_path.to_string_lossy().to_string());
        notify_preview(&context, ToolDisplayMeta::new("Find", format!("'{}'", args.pattern))).await;
        self.tools.find(args).await.into_mcp()
    }

    #[doc = include_str!("tools/read_file/description.md")]
    #[tool(annotations(read_only_hint = true, open_world_hint = false))]
    pub async fn read_file(
        &self,
        request: Parameters<ReadFileArgs>,
        context: RequestContext<RoleServer>,
    ) -> Result<Json<ReadFileResult>, String> {
        let Parameters(mut args) = request;
        args.file_path = self.resolve_file_arg(&args.file_path)?;
        notify_preview(&context, ToolDisplayMeta::new("Read file", basename(&args.file_path))).await;
        self.read_and_track(args).await
    }

    #[doc = include_str!("tools/write_file/description.md")]
    #[tool(annotations(
        read_only_hint = false,
        destructive_hint = true,
        idempotent_hint = false,
        open_world_hint = false
    ))]
    pub async fn write_file(
        &self,
        request: Parameters<WriteFileArgs>,
        context: RequestContext<RoleServer>,
    ) -> Result<Json<WriteFileResponse>, String> {
        let Parameters(mut args) = request;
        args.file_path = self.resolve_file_arg(&args.file_path)?;
        notify_preview(&context, ToolDisplayMeta::new("Write file", basename(&args.file_path))).await;

        self.check_write_permission(&context, "write_file", &args.file_path).await?;
        self.ensure_read_before_overwrite(&args.file_path).await?;

        let response = self.tools.write_file(args).await.map_err(|e| e.to_string())?;

        self.spawn_diagnostic_refresh(&response.file_path);

        Ok(Json(response))
    }

    #[doc = include_str!("tools/edit_file/description.md")]
    #[tool(annotations(
        read_only_hint = false,
        destructive_hint = true,
        idempotent_hint = false,
        open_world_hint = false
    ))]
    pub async fn edit_file(
        &self,
        request: Parameters<EditFileArgs>,
        context: RequestContext<RoleServer>,
    ) -> Result<Json<EditFileResponse>, String> {
        let Parameters(mut args) = request;
        args.file_path = self.resolve_file_arg(&args.file_path)?;
        notify_preview(&context, ToolDisplayMeta::new("Edit file", basename(&args.file_path))).await;

        self.check_write_permission(&context, "edit_file", &args.file_path).await?;
        self.ensure_read_before_edit(&args.file_path).await?;

        let response = self.tools.edit_file(args).await.map_err(|e| e.to_string())?;

        self.spawn_diagnostic_refresh(&response.file_path);

        Ok(Json(response))
    }

    #[doc = include_str!("tools/list_files/description.md")]
    #[tool(annotations(read_only_hint = true, open_world_hint = false))]
    pub async fn list_files(
        &self,
        request: Parameters<ListFilesArgs>,
        context: RequestContext<RoleServer>,
    ) -> Result<Json<ListFilesResult>, String> {
        let Parameters(mut args) = request;
        let normalized_path = self.workspace_paths().resolve_dir(args.path.as_deref());
        let preview_value = basename(&normalized_path.to_string_lossy());
        args.path = Some(normalized_path.to_string_lossy().to_string());
        notify_preview(&context, ToolDisplayMeta::new("List files", preview_value)).await;
        self.tools.list_files(args).await.into_mcp()
    }

    #[doc = include_str!("tools/bash/description.md")]
    #[tool(annotations(
        read_only_hint = false,
        destructive_hint = true,
        idempotent_hint = false,
        open_world_hint = true
    ))]
    pub async fn bash(
        &self,
        request: Parameters<BashInput>,
        context: RequestContext<RoleServer>,
    ) -> Result<Json<BashOutput>, String> {
        let Parameters(args) = request;
        notify_preview(&context, ToolDisplayMeta::new("Run command", truncate(&args.command, 40))).await;

        self.check_bash_permission(&context, &args.command).await?;

        let command = args.command.clone();
        let cwd = self.root_dir.clone();
        let result = self.tools.bash(args, Some(cwd)).await.map_err(|e| e.to_string())?;

        match result {
            BashResult::Completed(output) => Ok(Json(output)),
            BashResult::Background(handle) => {
                let shell_id = handle.shell_id.clone();

                // Store the background process
                self.background_processes.lock().await.insert(shell_id.clone(), handle);

                let display_meta =
                    ToolDisplayMeta::new("Run command", format!("{} (background)", truncate(&command, 40)));

                // Return immediate response with shell_id
                Ok(Json(BashOutput {
                    output: String::new(),
                    exit_code: 0,
                    killed: None,
                    shell_id: Some(shell_id),
                    meta: Some(display_meta.into()),
                }))
            }
        }
    }

    #[doc = include_str!("tools/bash/read_background_description.md")]
    #[tool(annotations(read_only_hint = true, open_world_hint = false))]
    pub async fn read_background_bash(
        &self,
        request: Parameters<ReadBackgroundBashInput>,
    ) -> Result<Json<ReadBackgroundBashOutput>, String> {
        let Parameters(args) = request;

        let handle = self
            .background_processes
            .lock()
            .await
            .remove(&args.bash_id)
            .ok_or_else(|| format!("Shell ID not found: {}", args.bash_id))?;

        let (result, handle_opt) =
            self.tools.read_background_bash(handle, args.filter).await.map_err(|e| e.to_string())?;

        // Put handle back if still running
        if let Some(handle) = handle_opt {
            self.background_processes.lock().await.insert(args.bash_id, handle);
        }

        Ok(Json(result))
    }

    #[doc = include_str!("tools/web_fetch/description.md")]
    #[tool(annotations(read_only_hint = true, open_world_hint = true))]
    pub async fn web_fetch(
        &self,
        request: Parameters<WebFetchInput>,
        context: RequestContext<RoleServer>,
    ) -> Result<Json<WebFetchOutput>, String> {
        let Parameters(args) = request;
        notify_preview(&context, ToolDisplayMeta::new("Fetch URL", truncate(&args.url, 60))).await;
        self.web_fetcher.fetch(args).await.into_mcp()
    }

    #[doc = include_str!("tools/web_search/description.md")]
    #[tool(annotations(read_only_hint = true, open_world_hint = true))]
    pub async fn web_search(
        &self,
        request: Parameters<WebSearchInput>,
        context: RequestContext<RoleServer>,
    ) -> Result<Json<WebSearchOutput>, String> {
        let Parameters(args) = request;
        notify_preview(&context, ToolDisplayMeta::new("Web search", format!("'{}'", args.query))).await;

        let searcher = self.web_searcher.as_ref().ok_or_else(|| {
            "Web search not available: BRAVE_SEARCH_API_KEY environment variable not set. \
                 Get a free API key from https://api.search.brave.com/app/keys"
                .to_string()
        })?;

        let peer = context.peer.clone();
        let progress_token = context.meta.get_progress_token();
        searcher
            .search(args, move |delay| {
                let peer = peer.clone();
                let progress_token = progress_token.clone();
                async move {
                    if let Some(token) = progress_token {
                        let message = format!("Search rate limited; retrying in {} seconds.", delay.as_secs());
                        let _ = peer
                            .notify_progress(ProgressNotificationParam {
                                progress_token: token,
                                progress: 0.0,
                                total: None,
                                message: Some(message),
                            })
                            .await;
                    }
                }
            })
            .await
            .map_err(|e| e.to_string())
            .map(Json)
    }

    #[doc = include_str!("../lsp/tools/symbol_lookup/description.md")]
    #[tool(annotations(read_only_hint = true, open_world_hint = false))]
    pub async fn lsp_symbol(
        &self,
        request: Parameters<LspSymbolInput>,
        context: RequestContext<RoleServer>,
    ) -> Result<Json<LspSymbolOutput>, String> {
        let Parameters(input) = request;
        notify_preview(&context, ToolDisplayMeta::new("LSP symbol", &input.symbol)).await;
        let lsp = self.lsp.as_ref().ok_or("LSP not configured")?;
        execute_lsp_symbol(input, lsp.as_ref()).await.map(Json)
    }

    #[doc = include_str!("../lsp/tools/workspace_search/description.md")]
    #[tool(annotations(read_only_hint = true, open_world_hint = false))]
    pub async fn lsp_workspace_search(
        &self,
        request: Parameters<LspWorkspaceSearchInput>,
        context: RequestContext<RoleServer>,
    ) -> Result<Json<LspWorkspaceSearchOutput>, String> {
        let Parameters(input) = request;
        notify_preview(&context, ToolDisplayMeta::new("LSP search", format!("'{}'", input.query))).await;
        let lsp = self.lsp.as_ref().ok_or("LSP not configured")?;
        execute_lsp_workspace_search(input, lsp.as_ref()).await.map(Json)
    }

    #[doc = include_str!("../lsp/tools/document_info/description.md")]
    #[tool(annotations(read_only_hint = true, open_world_hint = false))]
    pub async fn lsp_document(
        &self,
        request: Parameters<LspDocumentInput>,
        context: RequestContext<RoleServer>,
    ) -> Result<Json<LspDocumentOutput>, String> {
        let Parameters(input) = request;
        notify_preview(&context, ToolDisplayMeta::new("LSP document", basename(&input.file_path))).await;
        let lsp = self.lsp.as_ref().ok_or("LSP not configured")?;
        execute_lsp_document(input, lsp.as_ref()).await.map(Json)
    }

    #[doc = include_str!("../lsp/tools/check_errors/description.md")]
    #[tool(annotations(read_only_hint = true, open_world_hint = false))]
    pub async fn lsp_check_errors(
        &self,
        request: Parameters<LspDiagnosticsRequest>,
        context: RequestContext<RoleServer>,
    ) -> Result<Json<LspDiagnosticsOutput>, String> {
        let Parameters(request) = request;
        let preview_value = request.file_path.as_ref().map_or_else(|| "workspace".to_string(), |path| basename(path));
        notify_preview(&context, ToolDisplayMeta::new("LSP errors", preview_value)).await;
        let lsp = self.lsp.as_ref().ok_or("LSP not configured")?;
        execute_lsp_diagnostics(request, lsp.as_ref()).await.map(Json)
    }

    #[doc = include_str!("../lsp/tools/rename/description.md")]
    #[tool(annotations(
        read_only_hint = false,
        destructive_hint = true,
        idempotent_hint = false,
        open_world_hint = false
    ))]
    pub async fn lsp_rename(
        &self,
        request: Parameters<LspRenameInput>,
        context: RequestContext<RoleServer>,
    ) -> Result<Json<LspRenameOutput>, String> {
        let Parameters(input) = request;
        notify_preview(&context, ToolDisplayMeta::new("LSP rename", &input.symbol)).await;
        let lsp = self.lsp.as_ref().ok_or("LSP not configured")?;
        execute_lsp_rename(input, lsp.as_ref()).await.map(Json)
    }
}

impl Default for CodingMcp<DefaultCodingTools> {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(feature = "test-helpers")]
impl<T: CodingTools + 'static> CodingMcp<T> {
    /// Read a file and track it in the read set (test helper, no MCP context needed).
    pub async fn test_read_file(&self, mut args: ReadFileArgs) -> Result<Json<ReadFileResult>, String> {
        args.file_path = self.resolve_file_arg(&args.file_path)?;
        self.read_and_track(args).await
    }

    /// Write a file with read-before-write safety check (test helper, no MCP context needed).
    pub async fn test_write_file(&self, mut args: WriteFileArgs) -> Result<Json<WriteFileResponse>, String> {
        args.file_path = self.resolve_file_arg(&args.file_path)?;
        self.ensure_read_before_overwrite(&args.file_path).await?;
        self.tools.write_file(args).await.map(Json).map_err(|e| e.to_string())
    }

    /// Edit a file with read-before-edit safety check (test helper, no MCP context needed).
    pub async fn test_edit_file(&self, mut args: EditFileArgs) -> Result<Json<EditFileResponse>, String> {
        args.file_path = self.resolve_file_arg(&args.file_path)?;
        self.ensure_read_before_edit(&args.file_path).await?;
        self.tools.edit_file(args).await.map(Json).map_err(|e| e.to_string())
    }
}

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

    #[test]
    fn args_default_permission_mode_is_always_allow() {
        let args = CodingMcpArgs::from_args(vec![]).unwrap();
        assert_eq!(args.permission_mode, PermissionMode::AlwaysAllow);
    }

    #[test]
    fn args_default_lsp_enabled() {
        let args = CodingMcpArgs::from_args(vec![]).unwrap();
        assert!(!args.disable_lsp);
    }

    #[test]
    fn args_parses_disable_lsp() {
        let args = CodingMcpArgs::from_args(vec!["--disable-lsp".into()]).unwrap();
        assert!(args.disable_lsp);
    }

    #[test]
    fn disabled_lsp_instructions_omit_lsp_tools() {
        let instructions = CodingMcp::new().build_instructions();
        assert!(!instructions.contains("lsp_check_errors"));
        assert!(!instructions.contains("lsp_symbol"));
    }

    #[test]
    fn args_parses_always_allow() {
        let args = CodingMcpArgs::from_args(vec!["--permission-mode".into(), "always-allow".into()]).unwrap();
        assert_eq!(args.permission_mode, PermissionMode::AlwaysAllow);
    }

    #[test]
    fn args_parses_auto() {
        let args = CodingMcpArgs::from_args(vec!["--permission-mode".into(), "auto".into()]).unwrap();
        assert_eq!(args.permission_mode, PermissionMode::Auto);
    }

    #[test]
    fn args_parses_always_ask() {
        let args = CodingMcpArgs::from_args(vec!["--permission-mode".into(), "always-ask".into()]).unwrap();
        assert_eq!(args.permission_mode, PermissionMode::AlwaysAsk);
    }

    #[test]
    fn args_rejects_invalid_permission_mode() {
        assert!(CodingMcpArgs::from_args(vec!["--permission-mode".into(), "yolo".into()]).is_err());
    }

    #[test]
    fn args_parses_repeated_rules_dirs() {
        let args = CodingMcpArgs::from_args(vec![
            "--rules-dir".into(),
            ".aether/skills".into(),
            "--rules-dir".into(),
            ".claude/rules".into(),
        ])
        .unwrap();

        assert_eq!(args.rules_dirs, vec![PathBuf::from(".aether/skills"), PathBuf::from(".claude/rules")]);
    }

    #[test]
    fn with_permission_mode_stores_mode() {
        let mcp = CodingMcp::new().with_permission_mode(PermissionMode::AlwaysAsk);
        assert_eq!(mcp.permission_mode, PermissionMode::AlwaysAsk);
    }

    #[test]
    fn default_permission_mode_is_always_allow() {
        let mcp = CodingMcp::new();
        assert_eq!(mcp.permission_mode, PermissionMode::AlwaysAllow);
    }

    #[test]
    fn detects_rm() {
        assert!(is_dangerous_cmd("rm -rf /tmp/foo"));
        assert!(is_dangerous_cmd("rm\tfoo.txt"));
    }

    #[test]
    fn detects_git_push() {
        assert!(is_dangerous_cmd("git push origin main"));
    }

    #[test]
    fn detects_git_reset() {
        assert!(is_dangerous_cmd("git reset --hard HEAD~1"));
    }

    #[test]
    fn detects_git_checkout_discard() {
        assert!(is_dangerous_cmd("git checkout -- ."));
    }

    #[test]
    fn detects_git_clean() {
        assert!(is_dangerous_cmd("git clean -fd"));
    }

    #[test]
    fn detects_redirect() {
        assert!(is_dangerous_cmd("echo x > file.txt"));
        assert!(is_dangerous_cmd("echo x >> file.txt"));
    }

    #[test]
    fn does_not_flag_fat_arrow() {
        assert!(!is_dangerous_cmd("grep '=> ' file.txt"));
    }

    #[test]
    fn detects_chmod_chown() {
        assert!(is_dangerous_cmd("chmod 777 /etc/passwd"));
        assert!(is_dangerous_cmd("chown root:root /tmp/x"));
    }

    #[test]
    fn detects_kill_signals() {
        assert!(is_dangerous_cmd("kill -9 1234"));
        assert!(is_dangerous_cmd("pkill node"));
    }

    #[test]
    fn does_not_flag_kill_substring() {
        assert!(!is_dangerous_cmd("echo skillset"));
    }

    #[test]
    fn detects_mv() {
        assert!(is_dangerous_cmd("mv old.txt new.txt"));
    }

    #[test]
    fn detects_force_flags() {
        assert!(is_dangerous_cmd("npm install --force"));
        assert!(is_dangerous_cmd("git reset --hard"));
    }

    #[test]
    fn detects_dd() {
        assert!(is_dangerous_cmd("dd if=/dev/zero of=/dev/sda"));
    }

    #[test]
    fn detects_rmdir() {
        assert!(is_dangerous_cmd("rmdir empty_dir"));
    }

    #[test]
    fn does_not_flag_redirect_in_output() {
        assert!(is_dangerous_cmd("> file.txt"));
    }

    #[test]
    fn allows_safe_commands() {
        assert!(!is_dangerous_cmd("ls -la"));
        assert!(!is_dangerous_cmd("cat foo.txt"));
        assert!(!is_dangerous_cmd("git status"));
        assert!(!is_dangerous_cmd("git diff"));
        assert!(!is_dangerous_cmd("cargo test"));
        assert!(!is_dangerous_cmd("grep -r pattern ."));
    }
}