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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4945f68
 
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
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
ο»Ώusing System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.IO.Pipes;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using ModelContextProtocol.Server;

namespace ShellMcp
{
    public class Program
    {
        public static async Task Main(string[] args)
        {
            var mode = Environment.GetEnvironmentVariable("SHELL_MCP_MODE") ?? "safe";
            ShellExecutor.Initialize(mode);

            var builder = Host.CreateApplicationBuilder(args);
            
            // CRITICAL: Disable ALL console logging for MCP stdio transport
            // Any stdout output will corrupt the JSON-RPC protocol and cause hangs
            builder.Logging.ClearProviders();
            // Optionally log to a file for debugging:
            // builder.Logging.AddFile("shell-mcp.log");
            
            builder.Services
                .AddMcpServer()
                .WithStdioServerTransport()
                .WithToolsFromAssembly();
            
            await builder.Build().RunAsync();
        }
    }

    // ===============================================
    // SHELL EXECUTOR
    // ===============================================

    public static class ShellExecutor
    {
        private static string _currentDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
        private static string _mode = "safe";
        private static int _defaultTimeout = 30;

        private static readonly HashSet<string> SafeCommands = new(StringComparer.OrdinalIgnoreCase)
        {
            "dir", "ls", "pwd", "cd", "tree",
            "type", "cat", "head", "tail", "more", "less", "find", "findstr", "grep", "where", "which",
            "echo", "date", "time", "whoami", "hostname", "ver",
            "git status", "git log", "git diff", "git branch", "git remote", "git fetch", "git show", "git ls-files", "git stash list",
            "dotnet build", "dotnet run", "dotnet test", "dotnet restore", "dotnet clean", "dotnet --version", "dotnet --list-sdks",
            "npm install", "npm run", "npm test", "npm list", "npm --version", "npm ci", "npm audit",
            "node --version", "yarn --version", "yarn install", "yarn build", "yarn test",
            "cls", "clear", "help", "man",
        };

        private static readonly HashSet<string> DangerousCommands = new(StringComparer.OrdinalIgnoreCase)
        {
            "del", "rm", "rmdir", "rd", "erase",
            "move", "mv", "rename", "ren",
            "copy", "cp", "xcopy", "robocopy",
            "mkdir", "md",
            "git push", "git pull", "git merge", "git rebase", "git reset", "git clean", "git checkout", "git commit", "git add", "git rm", "git stash",
            "taskkill", "kill", "shutdown", "restart",
            "npm install -g", "npm uninstall", "dotnet tool install",
        };

        private static readonly HashSet<string> BlockedCommands = new(StringComparer.OrdinalIgnoreCase)
        {
            "format", "diskpart", "reg", "regedit", "net user", "net localgroup",
            "powershell -enc", "cmd /c", "rm -rf /", "del /s /q c:\\",
        };

        public static void Initialize(string mode)
        {
            _mode = mode.ToLowerInvariant();
            var startDir = Environment.GetEnvironmentVariable("SHELL_MCP_START_DIR");
            if (!string.IsNullOrEmpty(startDir) && Directory.Exists(startDir))
                _currentDirectory = startDir;

            // Set SSH Bridge path from environment
            var bridgePath = Environment.GetEnvironmentVariable("SSH_BRIDGE_PATH");
            if (!string.IsNullOrEmpty(bridgePath))
                SshBridgeClient.SetBridgePath(bridgePath);
        }

        public static string Mode => _mode;
        public static string CurrentDirectory => _currentDirectory;

        public static bool IsCommandAllowed(string command, out string reason)
        {
            reason = "";
            string cmdLower = command.ToLowerInvariant().Trim();
            string firstWord = cmdLower.Split(' ', StringSplitOptions.RemoveEmptyEntries).FirstOrDefault() ?? "";

            foreach (var blocked in BlockedCommands)
            {
                if (cmdLower.Contains(blocked.ToLowerInvariant()))
                {
                    reason = $"Command '{blocked}' is blocked for safety";
                    return false;
                }
            }

            if (_mode == "safe")
            {
                bool isSafe = SafeCommands.Any(safe => 
                    cmdLower.StartsWith(safe.ToLowerInvariant()) ||
                    firstWord == safe.ToLowerInvariant().Split(' ')[0]);

                if (!isSafe)
                {
                    reason = $"Command '{firstWord}' is not in the safe list. Use shell_dangerous for this operation.";
                    return false;
                }
            }
            else if (_mode == "dangerous")
            {
                bool isAllowed = SafeCommands.Any(safe => 
                    cmdLower.StartsWith(safe.ToLowerInvariant()) ||
                    firstWord == safe.ToLowerInvariant().Split(' ')[0]) ||
                    DangerousCommands.Any(dangerous => 
                    cmdLower.StartsWith(dangerous.ToLowerInvariant()) ||
                    firstWord == dangerous.ToLowerInvariant().Split(' ')[0]);

                if (!isAllowed)
                {
                    reason = $"Command '{firstWord}' is not recognized.";
                    return false;
                }
            }

            return true;
        }

        public static CommandResult Execute(string command, int? timeoutSeconds = null)
        {
            var result = new CommandResult { Command = command };
            int timeout = timeoutSeconds ?? _defaultTimeout;

            try
            {
                if (command.Trim().StartsWith("cd ", StringComparison.OrdinalIgnoreCase) ||
                    command.Trim().Equals("cd", StringComparison.OrdinalIgnoreCase))
                {
                    return HandleCd(command);
                }

                if (!IsCommandAllowed(command, out string reason))
                {
                    result.Success = false;
                    result.Stderr = reason;
                    result.ExitCode = -1;
                    return result;
                }

                var psi = new ProcessStartInfo
                {
                    FileName = "cmd.exe",
                    Arguments = $"/c {command}",
                    WorkingDirectory = _currentDirectory,
                    UseShellExecute = false,
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    CreateNoWindow = true,
                    StandardOutputEncoding = Encoding.UTF8,
                    StandardErrorEncoding = Encoding.UTF8,
                };

                using var process = new Process { StartInfo = psi };
                var stdout = new StringBuilder();
                var stderr = new StringBuilder();

                process.OutputDataReceived += (s, e) => { if (e.Data != null) stdout.AppendLine(e.Data); };
                process.ErrorDataReceived += (s, e) => { if (e.Data != null) stderr.AppendLine(e.Data); };

                var sw = Stopwatch.StartNew();
                process.Start();
                process.BeginOutputReadLine();
                process.BeginErrorReadLine();

                bool completed = process.WaitForExit(timeout * 1000);
                sw.Stop();

                if (!completed)
                {
                    try { process.Kill(entireProcessTree: true); } catch { }
                    result.Success = false;
                    result.Stderr = $"Command timed out after {timeout} seconds";
                    result.ExitCode = -1;
                    result.TimedOut = true;
                }
                else
                {
                    result.Success = process.ExitCode == 0;
                    result.ExitCode = process.ExitCode;
                    result.Stdout = stdout.ToString().TrimEnd();
                    result.Stderr = stderr.ToString().TrimEnd();
                }

                result.ExecutionTimeMs = sw.ElapsedMilliseconds;
                result.WorkingDirectory = _currentDirectory;
            }
            catch (Exception ex)
            {
                result.Success = false;
                result.Stderr = $"Execution error: {ex.Message}";
                result.ExitCode = -1;
            }

            return result;
        }

        private static CommandResult HandleCd(string command)
        {
            var result = new CommandResult { Command = command };
            var parts = command.Trim().Split(' ', 2, StringSplitOptions.RemoveEmptyEntries);
            
            if (parts.Length == 1)
            {
                result.Success = true;
                result.Stdout = _currentDirectory;
                result.WorkingDirectory = _currentDirectory;
                return result;
            }

            string targetPath = parts[1].Trim().Trim('"');
            string newPath;

            if (Path.IsPathRooted(targetPath))
                newPath = targetPath;
            else if (targetPath == "..")
                newPath = Path.GetDirectoryName(_currentDirectory) ?? _currentDirectory;
            else if (targetPath == "~")
                newPath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
            else
                newPath = Path.Combine(_currentDirectory, targetPath);

            newPath = Path.GetFullPath(newPath);

            if (Directory.Exists(newPath))
            {
                _currentDirectory = newPath;
                result.Success = true;
                result.Stdout = _currentDirectory;
                result.WorkingDirectory = _currentDirectory;
            }
            else
            {
                result.Success = false;
                result.Stderr = $"Directory not found: {newPath}";
                result.ExitCode = 1;
                result.WorkingDirectory = _currentDirectory;
            }

            return result;
        }

        public static string GetAllowedCommands()
        {
            var sb = new StringBuilder();
            sb.AppendLine($"Mode: {_mode}");
            sb.AppendLine();
            sb.AppendLine("Safe commands (always allowed):");
            foreach (var cmd in SafeCommands.OrderBy(c => c))
                sb.AppendLine($"  - {cmd}");

            if (_mode == "dangerous")
            {
                sb.AppendLine();
                sb.AppendLine("Dangerous commands (available in this mode):");
                foreach (var cmd in DangerousCommands.OrderBy(c => c))
                    sb.AppendLine($"  - {cmd}");
            }

            sb.AppendLine();
            sb.AppendLine("Blocked commands (never allowed):");
            foreach (var cmd in BlockedCommands.OrderBy(c => c))
                sb.AppendLine($"  - {cmd}");

            return sb.ToString();
        }
    }

    public class CommandResult
    {
        public string Command { get; set; } = "";
        public bool Success { get; set; }
        public string Stdout { get; set; } = "";
        public string Stderr { get; set; } = "";
        public int ExitCode { get; set; }
        public long ExecutionTimeMs { get; set; }
        public string WorkingDirectory { get; set; } = "";
        public bool TimedOut { get; set; }

        public override string ToString()
        {
            var sb = new StringBuilder();
            if (!string.IsNullOrEmpty(Stdout))
                sb.AppendLine(Stdout);
            if (!string.IsNullOrEmpty(Stderr))
            {
                if (sb.Length > 0) sb.AppendLine();
                sb.AppendLine($"[stderr] {Stderr}");
            }
            sb.AppendLine();
            sb.AppendLine($"[exit: {ExitCode}] [time: {ExecutionTimeMs}ms] [cwd: {WorkingDirectory}]");
            if (TimedOut)
                sb.AppendLine("[TIMED OUT]");
            return sb.ToString();
        }
    }

    // ===============================================
    // SSH BRIDGE CLIENT
    // ===============================================

    public static class SshBridgeClient
    {
        private const int PORT = 52718;

        private static string? _bridgePath;

        public static void SetBridgePath(string path)
        {
            _bridgePath = path;
        }

        public static string GetStatus()
        {
            try
            {
                return SendCommand("__STATUS__");
            }
            catch
            {
                return "DISCONNECTED";
            }
        }

        public static bool LaunchBridge()
        {
            if (string.IsNullOrEmpty(_bridgePath) || !System.IO.File.Exists(_bridgePath))
                return false;

            try
            {
                System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo
                {
                    FileName = _bridgePath,
                    UseShellExecute = true
                });
                return true;
            }
            catch
            {
                return false;
            }
        }

        public static bool IsBridgeRunning()
        {
            try
            {
                using var client = new System.Net.Sockets.TcpClient();
                client.Connect("127.0.0.1", PORT);
                return true;
            }
            catch
            {
                return false;
            }
        }

        public static string SendCommand(string command)
        {
            using var client = new System.Net.Sockets.TcpClient();
            client.Connect("127.0.0.1", PORT);

            using var stream = client.GetStream();
            using var writer = new StreamWriter(stream, Encoding.UTF8) { AutoFlush = true };
            using var reader = new StreamReader(stream, Encoding.UTF8);

            writer.WriteLine(command);
            var response = reader.ReadLine() ?? "No response";
            // Decode newlines
            return response.Replace("<<CRLF>>", "\r\n").Replace("<<LF>>", "\n").Replace("<<CR>>", "\r");
        }

        public static string Prefill(string host, int port, string user, string? password = null)
        {
            var cmd = $"__PREFILL__:{host}:{port}:{user}";
            if (!string.IsNullOrEmpty(password))
                cmd += $":{password}";
            return SendCommand(cmd);
        }

        public static string TriggerConnect()
        {
            return SendCommand("__CONNECT__");
        }

        public static string GetPenStatus()
        {
            try
            {
                return SendCommand("__PEN_STATUS__");
            }
            catch
            {
                return "BRIDGE_NOT_RUNNING";
            }
        }

        public static string PutPenDown()
        {
            try
            {
                return SendCommand("__PEN_DOWN__");
            }
            catch
            {
                return "BRIDGE_NOT_RUNNING";
            }
        }

        public static string SendAbort()
        {
            try
            {
                return SendCommand("__ABORT__");
            }
            catch
            {
                return "BRIDGE_NOT_RUNNING";
            }
        }

        public static string IsRunning()
        {
            try
            {
                return SendCommand("__IS_RUNNING__");
            }
            catch
            {
                return "BRIDGE_NOT_RUNNING";
            }
        }

        public static string KillPort(int port)
        {
            try
            {
                return SendCommand($"__KILL_PORT__:{port}");
            }
            catch
            {
                return "BRIDGE_NOT_RUNNING";
            }
        }

        public static string SetTimeout(int seconds)
        {
            try
            {
                return SendCommand($"__TIMEOUT__:{seconds}");
            }
            catch
            {
                return "BRIDGE_NOT_RUNNING";
            }
        }

        public static string GetTail()
        {
            try
            {
                return SendCommand("__TAIL__");
            }
            catch
            {
                return "BRIDGE_NOT_RUNNING";
            }
        }

        public static string ListSpawned()
        {
            try
            {
                return SendCommand("__LIST_SPAWNED__");
            }
            catch
            {
                return "BRIDGE_NOT_RUNNING";
            }
        }

        public static string Spawn(string name, string command)
        {
            try
            {
                return SendCommand($"__SPAWN__:{name}:{command}");
            }
            catch
            {
                return "BRIDGE_NOT_RUNNING";
            }
        }

        public static string KillSpawned(string name)
        {
            try
            {
                return SendCommand($"__KILL_SPAWNED__:{name}");
            }
            catch
            {
                return "BRIDGE_NOT_RUNNING";
            }
        }

        public static string WriteFile(string path, string content)
        {
            try
            {
                // Encode newlines for line-based protocol
                var encoded = content
                    .Replace("\r\n", "<<CRLF>>")
                    .Replace("\n", "<<LF>>")
                    .Replace("\r", "<<CR>>");
                return SendCommand($"__WRITE_FILE__:{path}|{encoded}");
            }
            catch
            {
                return "BRIDGE_NOT_RUNNING";
            }
        }

        public static string AppendFile(string path, string content)
        {
            try
            {
                var encoded = content
                    .Replace("\r\n", "<<CRLF>>")
                    .Replace("\n", "<<LF>>")
                    .Replace("\r", "<<CR>>");
                return SendCommand($"__APPEND_FILE__:{path}|{encoded}");
            }
            catch
            {
                return "BRIDGE_NOT_RUNNING";
            }
        }
    }

    // ===============================================
    // MCP TOOLS
    // ===============================================

    [McpServerToolType]
    public static class ShellTools
    {
        [McpServerTool, Description("Execute a shell command. Working directory persists across calls. Use 'cd' to navigate. Check 'shell_info' for allowed commands.")]
        public static string Shell(
            [Description("Command to execute")] string command,
            [Description("Timeout in seconds (default: 30)")] int? timeout = null)
        {
            if (string.IsNullOrWhiteSpace(command))
                return "Error: No command provided";

            var result = ShellExecutor.Execute(command, timeout);
            return result.Success ? result.ToString() : $"❌ Command failed:\n{result}";
        }

        [McpServerTool, Description("Get current working directory")]
        public static string Pwd()
        {
            return ShellExecutor.CurrentDirectory;
        }

        [McpServerTool, Description("Show shell mode and list of allowed commands")]
        public static string ShellInfo()
        {
            var sb = new StringBuilder();
            sb.AppendLine($"Shell MCP - {ShellExecutor.Mode.ToUpperInvariant()} mode");
            sb.AppendLine($"Current directory: {ShellExecutor.CurrentDirectory}");
            sb.AppendLine();
            sb.AppendLine(ShellExecutor.GetAllowedCommands());
            return sb.ToString();
        }

        [McpServerTool, Description("Execute multiple commands in sequence. Stops on first failure unless continue_on_error is true.")]
        public static string ShellBatch(
            [Description("JSON array of commands: [\"cmd1\", \"cmd2\", ...]")] string commands_json,
            [Description("Continue executing even if a command fails")] bool continue_on_error = false,
            [Description("Timeout per command in seconds")] int? timeout = null)
        {
            try
            {
                var commands = JsonSerializer.Deserialize<List<string>>(commands_json);
                if (commands == null || commands.Count == 0)
                    return "Error: No commands provided";

                var sb = new StringBuilder();
                int succeeded = 0, failed = 0;

                foreach (var cmd in commands)
                {
                    sb.AppendLine($"$ {cmd}");
                    var result = ShellExecutor.Execute(cmd, timeout);
                    sb.AppendLine(result.ToString());

                    if (result.Success)
                        succeeded++;
                    else
                    {
                        failed++;
                        if (!continue_on_error)
                        {
                            sb.AppendLine($"❌ Batch stopped. {succeeded} succeeded, {failed} failed, {commands.Count - succeeded - failed} skipped.");
                            return sb.ToString();
                        }
                    }
                }

                sb.AppendLine($"βœ… Batch complete: {succeeded} succeeded, {failed} failed");
                return sb.ToString();
            }
            catch (Exception ex)
            {
                return $"Error parsing commands: {ex.Message}";
            }
        }

        [McpServerTool, Description("Execute a command on a remote server via SSH Bridge. Requires SSH Bridge app to be running and connected.")]
        public static string SshCommand(
            [Description("Command to execute on the remote server")] string command)
        {
            if (string.IsNullOrWhiteSpace(command))
                return "Error: No command provided";

            try
            {
                // Check if bridge is running, launch if not
                if (!SshBridgeClient.IsBridgeRunning())
                {
                    if (SshBridgeClient.LaunchBridge())
                    {
                        return "πŸš€ SSH Bridge launched!\n\nPlease:\n1. Enter host, user, and password in the window that just opened\n2. Click Connect\n3. Try this command again";
                    }
                    else
                    {
                        return "❌ SSH Bridge not running and could not auto-launch.\n\nPlease run ssh-bridge.exe manually, or set SSH_BRIDGE_PATH in your Claude config.";
                    }
                }

                var status = SshBridgeClient.GetStatus();
                if (status == "DISCONNECTED")
                {
                    return "⚠️ SSH Bridge is open but not connected.\n\nPlease:\n1. Enter host, user, and password\n2. Click Connect\n3. Try this command again";
                }

                var result = SshBridgeClient.SendCommand(command);
                return $"πŸ“‘ {status}\n\n{result}";
            }
            catch (Exception ex)
            {
                return $"❌ SSH error: {ex.Message}";
            }
        }

        [McpServerTool, Description("Check if SSH Bridge is connected")]
        public static string SshStatus()
        {
            try
            {
                if (!SshBridgeClient.IsBridgeRunning())
                {
                    return "❌ SSH Bridge not running";
                }

                var status = SshBridgeClient.GetStatus();
                if (status.StartsWith("CONNECTED:"))
                {
                    return $"βœ… {status.Replace("CONNECTED:", "Connected to ")}";
                }
                return "⚠️ SSH Bridge open but not connected";
            }
            catch
            {
                return "❌ SSH Bridge not running";
            }
        }

        [McpServerTool, Description("Pre-fill SSH Bridge connection details. Launches SSH Bridge if not running, fills in host/port/user, optionally password. User must click Connect or you can call with auto_connect=true.")]
        public static string SshPrefill(
            [Description("SSH host/IP address")] string host,
            [Description("SSH username")] string user,
            [Description("SSH port (default: 22)")] int port = 22,
            [Description("SSH password (optional - user can enter manually for security)")] string? password = null,
            [Description("Automatically click Connect after prefilling")] bool auto_connect = false)
        {
            try
            {
                // Launch bridge if not running
                if (!SshBridgeClient.IsBridgeRunning())
                {
                    if (!SshBridgeClient.LaunchBridge())
                    {
                        return "❌ Could not launch SSH Bridge. Set SSH_BRIDGE_PATH in your Claude config.";
                    }
                    // Wait for it to start
                    Thread.Sleep(1000);
                }

                // Prefill the fields
                var result = SshBridgeClient.Prefill(host, port, user, password);
                if (result != "PREFILLED")
                {
                    return $"❌ Prefill failed: {result}";
                }

                if (auto_connect && !string.IsNullOrEmpty(password))
                {
                    Thread.Sleep(200);
                    SshBridgeClient.TriggerConnect();
                    Thread.Sleep(2000); // Wait for connection
                    var status = SshBridgeClient.GetStatus();
                    if (status.StartsWith("CONNECTED:"))
                    {
                        return $"βœ… Connected to {user}@{host}:{port}";
                    }
                    return $"⚠️ Connection initiated. Status: {status}";
                }

                if (string.IsNullOrEmpty(password))
                {
                    return $"πŸ“ SSH Bridge prefilled with {user}@{host}:{port}\n\nPlease enter password and click Connect.";
                }
                return $"πŸ“ SSH Bridge prefilled with {user}@{host}:{port}\n\nClick Connect when ready.";
            }
            catch (Exception ex)
            {
                return $"❌ Error: {ex.Message}";
            }
        }

        [McpServerTool, Description("Check if user has lifted the pen (paused command execution). When pen is lifted, commands will be blocked until pen is put back down.")]
        public static string SshPenStatus()
        {
            try
            {
                if (!SshBridgeClient.IsBridgeRunning())
                {
                    return "❌ SSH Bridge not running";
                }

                var status = SshBridgeClient.GetPenStatus();
                return status switch
                {
                    "PEN_LIFTED" => "βœ‹ Pen is LIFTED - User has paused command execution. Wait for user or call SshPenDown to request resumption.",
                    "PEN_DOWN" => "✏️ Pen is DOWN - Commands will execute normally.",
                    _ => $"⚠️ Unknown status: {status}"
                };
            }
            catch
            {
                return "❌ SSH Bridge not running";
            }
        }

        [McpServerTool, Description("Request to put the pen back down (resume command execution). Only works if pen was lifted. User can also click the button manually.")]
        public static string SshPenDown()
        {
            try
            {
                if (!SshBridgeClient.IsBridgeRunning())
                {
                    return "❌ SSH Bridge not running";
                }

                var result = SshBridgeClient.PutPenDown();
                return result switch
                {
                    "PEN_LOWERED" => "✏️ Pen lowered - Command execution resumed.",
                    "PEN_ALREADY_DOWN" => "✏️ Pen was already down - Commands executing normally.",
                    _ => $"⚠️ Unexpected response: {result}"
                };
            }
            catch
            {
                return "❌ SSH Bridge not running";
            }
        }

        [McpServerTool, Description("Send Ctrl+C (abort signal) to the currently running command. Use this when a command is taking too long or appears stuck.")]
        public static string SshAbort()
        {
            try
            {
                if (!SshBridgeClient.IsBridgeRunning())
                {
                    return "❌ SSH Bridge not running";
                }

                var result = SshBridgeClient.SendAbort();
                return result switch
                {
                    "ABORT_SENT" => "πŸ›‘ Abort signal (Ctrl+C) sent to running command.",
                    "NO_COMMAND_RUNNING" => "ℹ️ No command currently running.",
                    _ => $"⚠️ Response: {result}"
                };
            }
            catch
            {
                return "❌ SSH Bridge not running";
            }
        }

        [McpServerTool, Description("Check if a command is currently running on the SSH connection.")]
        public static string SshIsRunning()
        {
            try
            {
                if (!SshBridgeClient.IsBridgeRunning())
                {
                    return "❌ SSH Bridge not running";
                }

                var result = SshBridgeClient.IsRunning();
                return result switch
                {
                    "RUNNING" => "⚑ A command is currently running.",
                    "IDLE" => "βœ… No command running - ready for new commands.",
                    _ => $"⚠️ Status: {result}"
                };
            }
            catch
            {
                return "❌ SSH Bridge not running";
            }
        }

        [McpServerTool, Description("Kill process listening on a specific port. Useful for freeing up ports or killing hung services.")]
        public static string SshKillPort(
            [Description("Port number to kill (1-65535)")] int port)
        {
            try
            {
                if (!SshBridgeClient.IsBridgeRunning())
                {
                    return "❌ SSH Bridge not running";
                }

                if (port < 1 || port > 65535)
                {
                    return "❌ Invalid port number. Must be 1-65535.";
                }

                var result = SshBridgeClient.KillPort(port);
                return $"πŸ”« Kill port {port}:\n{result}";
            }
            catch
            {
                return "❌ SSH Bridge not running";
            }
        }

        [McpServerTool, Description("Set timeout for the next SSH command. Useful for long-running operations like large downloads.")]
        public static string SshSetTimeout(
            [Description("Timeout in seconds (1-3600)")] int seconds)
        {
            try
            {
                if (!SshBridgeClient.IsBridgeRunning())
                {
                    return "❌ SSH Bridge not running";
                }

                if (seconds < 1 || seconds > 3600)
                {
                    return "❌ Invalid timeout. Must be 1-3600 seconds.";
                }

                var result = SshBridgeClient.SetTimeout(seconds);
                return $"⏱️ {result}";
            }
            catch
            {
                return "❌ SSH Bridge not running";
            }
        }

        [McpServerTool, Description("Get the last 50 lines of output from the SSH Bridge terminal. Useful for checking progress of background tasks.")]
        public static string SshTail()
        {
            try
            {
                if (!SshBridgeClient.IsBridgeRunning())
                {
                    return "❌ SSH Bridge not running";
                }

                var result = SshBridgeClient.GetTail();
                return $"πŸ“œ Recent output:\n{result}";
            }
            catch
            {
                return "❌ SSH Bridge not running";
            }
        }

        [McpServerTool, Description("List all tracked background processes spawned via SshSpawn.")]
        public static string SshListSpawned()
        {
            try
            {
                if (!SshBridgeClient.IsBridgeRunning())
                {
                    return "❌ SSH Bridge not running";
                }

                var result = SshBridgeClient.ListSpawned();
                return $"πŸ“‹ Background processes:\n{result}";
            }
            catch
            {
                return "❌ SSH Bridge not running";
            }
        }

        [McpServerTool, Description("Spawn a background process with a trackable name. Use SshListSpawned to see status and SshKillSpawned to terminate.")]
        public static string SshSpawn(
            [Description("Name to identify this background process")] string name,
            [Description("Command to run in background")] string command)
        {
            try
            {
                if (!SshBridgeClient.IsBridgeRunning())
                {
                    return "❌ SSH Bridge not running";
                }

                var result = SshBridgeClient.Spawn(name, command);
                return $"πŸš€ {result}";
            }
            catch
            {
                return "❌ SSH Bridge not running";
            }
        }

        [McpServerTool, Description("Kill a background process by name (spawned via SshSpawn or matching window title).")]
        public static string SshKillSpawned(
            [Description("Name of the background process to kill")] string name)
        {
            try
            {
                if (!SshBridgeClient.IsBridgeRunning())
                {
                    return "❌ SSH Bridge not running";
                }

                var result = SshBridgeClient.KillSpawned(name);
                return $"πŸ”« {result}";
            }
            catch
            {
                return "❌ SSH Bridge not running";
            }
        }

        [McpServerTool, Description("Write content to a file on the remote system without shell escaping. Perfect for batch files, configs, etc.")]
        public static string SshWriteFile(
            [Description("Full path to file (e.g., C:\\scripts\\run.bat)")] string path,
            [Description("Content to write - characters like & | < > will NOT be escaped")] string content)
        {
            try
            {
                if (!SshBridgeClient.IsBridgeRunning())
                {
                    return "❌ SSH Bridge not running";
                }

                var result = SshBridgeClient.WriteFile(path, content);
                return $"πŸ“ {result}";
            }
            catch
            {
                return "❌ SSH Bridge not running";
            }
        }

        [McpServerTool, Description("Append content to a file on the remote system without shell escaping.")]
        public static string SshAppendFile(
            [Description("Full path to file")] string path,
            [Description("Content to append - characters like & | < > will NOT be escaped")] string content)
        {
            try
            {
                if (!SshBridgeClient.IsBridgeRunning())
                {
                    return "❌ SSH Bridge not running";
                }

                var result = SshBridgeClient.AppendFile(path, content);
                return $"πŸ“ {result}";
            }
            catch
            {
                return "❌ SSH Bridge not running";
            }
        }
    }
}