-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcoverage.html
More file actions
2652 lines (2198 loc) · 121 KB
/
coverage.html
File metadata and controls
2652 lines (2198 loc) · 121 KB
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
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>gocreate: Go Coverage Report</title>
<style>
body {
background: black;
color: rgb(80, 80, 80);
}
body, pre, #legend span {
font-family: Menlo, monospace;
font-weight: bold;
}
#topbar {
background: black;
position: fixed;
top: 0; left: 0; right: 0;
height: 42px;
border-bottom: 1px solid rgb(80, 80, 80);
}
#content {
margin-top: 50px;
}
#nav, #legend {
float: left;
margin-left: 10px;
}
#legend {
margin-top: 12px;
}
#nav {
margin-top: 10px;
}
#legend span {
margin: 0 5px;
}
.cov0 { color: rgb(192, 0, 0) }
.cov1 { color: rgb(128, 128, 128) }
.cov2 { color: rgb(116, 140, 131) }
.cov3 { color: rgb(104, 152, 134) }
.cov4 { color: rgb(92, 164, 137) }
.cov5 { color: rgb(80, 176, 140) }
.cov6 { color: rgb(68, 188, 143) }
.cov7 { color: rgb(56, 200, 146) }
.cov8 { color: rgb(44, 212, 149) }
.cov9 { color: rgb(32, 224, 152) }
.cov10 { color: rgb(20, 236, 155) }
</style>
</head>
<body>
<div id="topbar">
<div id="nav">
<select id="files">
<option value="file0">gocreate/main.go (0.0%)</option>
<option value="file1">gocreate/tools/config/config.go (0.0%)</option>
<option value="file2">gocreate/tools/config/get_config.go (0.0%)</option>
<option value="file3">gocreate/tools/config/set_config_value.go (0.0%)</option>
<option value="file4">gocreate/tools/edit/edit.go (0.0%)</option>
<option value="file5">gocreate/tools/edit/precise_edit.go (0.0%)</option>
<option value="file6">gocreate/tools/filesystem/create_directory.go (0.0%)</option>
<option value="file7">gocreate/tools/filesystem/get_file_info.go (0.0%)</option>
<option value="file8">gocreate/tools/filesystem/list_directory.go (0.0%)</option>
<option value="file9">gocreate/tools/filesystem/move_file.go (0.0%)</option>
<option value="file10">gocreate/tools/filesystem/read_file.go (0.0%)</option>
<option value="file11">gocreate/tools/filesystem/read_multiple_files.go (0.0%)</option>
<option value="file12">gocreate/tools/filesystem/search_files.go (0.0%)</option>
<option value="file13">gocreate/tools/filesystem/write_file.go (0.0%)</option>
<option value="file14">gocreate/tools/process/execute_command.go (0.0%)</option>
<option value="file15">gocreate/tools/process/kill_process.go (0.0%)</option>
<option value="file16">gocreate/tools/process/list_processes.go (0.0%)</option>
<option value="file17">gocreate/tools/search/search_code.go (81.9%)</option>
<option value="file18">gocreate/tools/search/search_files.go (0.0%)</option>
<option value="file19">gocreate/tools/terminal/execute_in_terminal.go (0.0%)</option>
<option value="file20">gocreate/tools/terminal/manager.go (0.0%)</option>
<option value="file21">gocreate/tools/terminal/terminal.go (0.0%)</option>
</select>
</div>
<div id="legend">
<span>not tracked</span>
<span class="cov0">not covered</span>
<span class="cov8">covered</span>
</div>
</div>
<div id="content">
<pre class="file" id="file0" style="display: none">package main
import (
"log"
"log/slog"
"os"
"gocreate/tools/config"
"gocreate/tools/edit"
"gocreate/tools/filesystem"
"gocreate/tools/process"
"gocreate/tools/search"
"gocreate/tools/terminal"
"github.com/localrivet/gomcp/server"
)
func main() <span class="cov0" title="0">{
// Create a logger
logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
Level: slog.LevelError,
}))
// Create a new server
s := server.NewServer("GoCreate",
server.WithLogger(logger),
).AsStdio()
// Register tools using the API
// Configuration tools
s.Tool("get_config", "Get the complete server configuration as JSON.",
config.HandleGetConfig)
s.Tool("set_config_value", "Set a specific configuration value by key.",
config.HandleSetConfigValue)
// Filesystem tools
s.Tool("read_file", "Read the contents of a file. Supports optional start_line and end_line parameters for paging.",
filesystem.HandleReadFile)
s.Tool("read_multiple_files", "Read the contents of multiple files simultaneously.",
filesystem.HandleReadMultipleFiles)
s.Tool("write_file", "Completely replace file contents.",
filesystem.HandleWriteFile)
s.Tool("create_directory", "Create a new directory or ensure a directory exists.",
filesystem.HandleCreateDirectory)
s.Tool("list_directory", "Get a detailed listing of all files and directories in a specified path.",
filesystem.HandleListDirectory)
s.Tool("move_file", "Move or rename files and directories.",
filesystem.HandleMoveFile)
s.Tool("search_files", "Finds files by name using a case-insensitive substring matching.",
filesystem.HandleSearchFiles)
s.Tool("get_file_info", "Retrieve detailed metadata about a file or directory.",
filesystem.HandleGetFileInfo)
s.Tool("search_code", "Search for text/code patterns within file contents using pure Go implementation.",
search.HandleSearchCode)
s.Tool("edit_block", "Apply surgical text replacements to files.",
edit.HandleEditBlock)
s.Tool("precise_edit", "Precisely edit file content based on start and end line numbers.",
edit.HandlePreciseEdit)
// Terminal tools
s.Tool("execute_command", "Execute a terminal command with timeout.",
terminal.HandleExecuteCommand)
s.Tool("read_output", "Read new output from a running terminal session.",
terminal.HandleReadOutput)
s.Tool("force_terminate", "Force terminate a running terminal session.",
terminal.HandleForceTerminate)
s.Tool("list_sessions", "List all active terminal sessions.",
terminal.HandleListSessions)
s.Tool("execute_in_terminal", "Execute a command in the terminal (client-side execution).",
terminal.HandleExecuteInTerminal)
// Process tools
s.Tool("list_processes", "List all running processes.",
process.HandleListProcesses)
s.Tool("kill_process", "Terminate a running process by PID.",
process.HandleKillProcess)
// Start the server
logger.Info("Starting GoCreate MCP server...")
if err := s.Run(); err != nil </span><span class="cov0" title="0">{
log.Fatalf("Server exited with error: %v", err)
}</span>
<span class="cov0" title="0">logger.Info("Server shutdown complete.")</span>
}
</pre>
<pre class="file" id="file1" style="display: none">package config
import (
"encoding/json"
"fmt"
"os"
"path/filepath" // Keep for potential DefaultShell logic later
"sync"
"github.com/localrivet/gomcp/server"
)
// Path to the configuration file relative to the server executable
const configDir = "config"
const configFileName = "config.json"
// Configuration struct to match config.json
type ServerConfig struct {
BlockedCommands []string `json:"blockedCommands"`
DefaultShell *string `json:"defaultShell,omitempty"` // Pointer to distinguish between empty string and not set
AllowedDirectories []string `json:"allowedDirectories,omitempty"` // Use omitempty; nil slice means not set, empty slice means allow all
TelemetryEnabled *bool `json:"telemetryEnabled,omitempty"` // Pointer for explicit true/false/not set
}
var currentConfig *ServerConfig
var loadConfigOnce sync.Once
var loadConfigErr error
// For testing purposes
var testConfigDir string
// loadConfig loads the configuration from file or creates default. Used internally.
func loadConfig(ctx *server.Context) (*ServerConfig, error) <span class="cov0" title="0">{
loadConfigOnce.Do(func() </span><span class="cov0" title="0">{
configPath, err := getConfigPath()
if err != nil </span><span class="cov0" title="0">{
loadConfigErr = fmt.Errorf("failed to get config path: %w", err)
return
}</span>
<span class="cov0" title="0">content, err := os.ReadFile(configPath)
if err != nil </span><span class="cov0" title="0">{
if os.IsNotExist(err) </span><span class="cov0" title="0">{
ctx.Logger.Info("Config file not found at %s, creating default for internal use", "configPath", configPath)
cfg := ServerConfig{
BlockedCommands: defaultBlockedCommands, // Use var from get_config.go
}
// Attempt to write default file, but proceed even if write fails
configJson, marshalErr := json.MarshalIndent(cfg, "", " ")
if marshalErr == nil </span><span class="cov0" title="0">{
_ = os.MkdirAll(filepath.Dir(configPath), 0755) // Ignore error
_ = os.WriteFile(configPath, configJson, 0644) // Ignore error
}</span> else<span class="cov0" title="0"> {
ctx.Logger.Info("Error marshalling default config for write", "error", marshalErr)
}</span>
<span class="cov0" title="0">currentConfig = &cfg</span> // Use in-memory default
} else<span class="cov0" title="0"> {
loadConfigErr = fmt.Errorf("error reading config file %s: %w", configPath, err)
return
}</span>
} else<span class="cov0" title="0"> {
var cfg ServerConfig
if err := json.Unmarshal(content, &cfg); err != nil </span><span class="cov0" title="0">{
loadConfigErr = fmt.Errorf("error unmarshalling config file %s: %w", configPath, err)
return
}</span>
// Ensure BlockedCommands is not nil if file exists but key is missing
<span class="cov0" title="0">if cfg.BlockedCommands == nil </span><span class="cov0" title="0">{
cfg.BlockedCommands = []string{} // Initialize to empty slice
}</span>
<span class="cov0" title="0">currentConfig = &cfg</span>
}
})
<span class="cov0" title="0">return currentConfig, loadConfigErr</span>
}
// GetCurrentConfig provides access to the loaded configuration.
func GetCurrentConfig(ctx *server.Context) (*ServerConfig, error) <span class="cov0" title="0">{
return loadConfig(ctx)
}</span>
// getConfigPath returns the absolute path to the configuration file.
func getConfigPath() (string, error) <span class="cov0" title="0">{
if testConfigDir != "" </span><span class="cov0" title="0">{
return filepath.Join(testConfigDir, configFileName), nil
}</span>
<span class="cov0" title="0">exePath, err := os.Executable()
if err != nil </span><span class="cov0" title="0">{
return "", fmt.Errorf("failed to get executable path: %w", err)
}</span>
<span class="cov0" title="0">exeDir := filepath.Dir(exePath)
return filepath.Join(exeDir, configDir, configFileName), nil</span>
}
</pre>
<pre class="file" id="file2" style="display: none">package config
import (
"encoding/json"
"os"
"path/filepath"
"github.com/localrivet/gomcp/server"
)
// Define default blocked commands (more comprehensive list)
var defaultBlockedCommands = []string{
// File Protection
"rm",
// Disk/Partition
"mkfs", "format", "mount", "umount", "fdisk", "dd", "parted", "diskpart",
// System Admin/User
"sudo", "su", "passwd", "adduser", "useradd", "usermod", "groupadd", "chsh", "visudo",
// System Control
"shutdown", "reboot", "halt", "poweroff", "init",
// Network/Security
"iptables", "firewall", "netsh",
// Windows Specific
"sfc", "bcdedit", "reg", "net", "sc", "runas", "cipher", "takeown",
}
// GetConfigArgs defines the arguments for the get_config tool.
type GetConfigArgs struct{}
// SetConfigValueArgs defines the arguments for the set_config_value tool.
type SetConfigValueArgs struct {
Key string `json:"key" description:"The configuration key to set." required:"true"`
Value interface{} `json:"value" description:"The value to set for the key." required:"true"`
}
// HandleGetConfig implements the logic for the get_config tool using the new API.
func HandleGetConfig(ctx *server.Context, args GetConfigArgs) (string, error) <span class="cov0" title="0">{
ctx.Logger.Info("Handling get_config tool call")
configPath, err := getConfigPath()
if err != nil </span><span class="cov0" title="0">{
ctx.Logger.Info("Error getting config path", "error", err)
return "Error getting configuration file path", err
}</span>
// Read the config file
<span class="cov0" title="0">content, err := os.ReadFile(configPath)
if err != nil </span><span class="cov0" title="0">{
// If the file doesn't exist, create it with default BlockedCommands and return that
if os.IsNotExist(err) </span><span class="cov0" title="0">{
ctx.Logger.Info("Config file not found at %s, creating with default BlockedCommands", "configPath", configPath)
// Only set BlockedCommands in the default config written to file
defaultConfig := ServerConfig{
BlockedCommands: defaultBlockedCommands,
// DefaultShell, AllowedDirectories, TelemetryEnabled remain nil/zero
}
configJson, marshalErr := json.MarshalIndent(defaultConfig, "", " ")
if marshalErr != nil </span><span class="cov0" title="0">{
ctx.Logger.Info("Error marshalling default config", "error", marshalErr)
return "Error generating default config output", marshalErr
}</span>
// Create the config directory if it doesn't exist
<span class="cov0" title="0">configDirPath := filepath.Join(filepath.Dir(configPath))
if err := os.MkdirAll(configDirPath, 0755); err != nil </span><span class="cov0" title="0">{
ctx.Logger.Info("Error creating config directory", "configDirPath", configDirPath, "error", err)
return "Error creating configuration directory", err
}</span>
<span class="cov0" title="0">if writeErr := os.WriteFile(configPath, configJson, 0644); writeErr != nil </span><span class="cov0" title="0">{
ctx.Logger.Info("Error writing default config file", "configPath", configPath, "error", writeErr)
return "Error writing default configuration file", writeErr
}</span>
<span class="cov0" title="0">return string(configJson), nil</span>
}
<span class="cov0" title="0">ctx.Logger.Info("Error reading config file", "configPath", configPath, "error", err)
return "Error reading configuration file", err</span>
}
<span class="cov0" title="0">var config ServerConfig
if err := json.Unmarshal(content, &config); err != nil </span><span class="cov0" title="0">{
ctx.Logger.Info("Error unmarshalling config file", "configPath", configPath, "error", err)
return "Error parsing configuration file", err
}</span>
<span class="cov0" title="0">configJson, err := json.MarshalIndent(config, "", " ")
if err != nil </span><span class="cov0" title="0">{
ctx.Logger.Info("Error marshalling config", "error", err)
return "Error generating config output", err
}</span>
<span class="cov0" title="0">return string(configJson), nil</span>
}
</pre>
<pre class="file" id="file3" style="display: none">package config
import (
"encoding/json"
"os"
"github.com/localrivet/gomcp/server"
)
// HandleSetConfigValue implements the set_config_value tool using the new API
func HandleSetConfigValue(ctx *server.Context, args SetConfigValueArgs) (string, error) <span class="cov0" title="0">{
ctx.Logger.Info("Handling set_config_value tool call")
configPath, err := getConfigPath()
if err != nil </span><span class="cov0" title="0">{
ctx.Logger.Info("Error getting config path", "error", err)
return "Error getting configuration file path", err
}</span>
// Read the current config
<span class="cov0" title="0">content, err := os.ReadFile(configPath)
if err != nil </span><span class="cov0" title="0">{
// If the file doesn't exist, start with a default empty config
if os.IsNotExist(err) </span><span class="cov0" title="0">{
ctx.Logger.Info("Config file not found, starting with default empty config for set operation", "configPath", configPath)
content = []byte("{}") // Start with an empty JSON object
}</span> else<span class="cov0" title="0"> {
ctx.Logger.Info("Error reading config file for set_config_value", "configPath", configPath, "error", err)
return "Error reading configuration file for update", err
}</span>
}
<span class="cov0" title="0">var config map[string]interface{} // Use a map to handle arbitrary keys
if err := json.Unmarshal(content, &config); err != nil </span><span class="cov0" title="0">{
ctx.Logger.Info("Error unmarshalling config file for set_config_value", "configPath", configPath, "error", err)
return "Error parsing configuration file for update", err
}</span>
// Update the specific key
<span class="cov0" title="0">config[args.Key] = args.Value
// Marshal the updated config
updatedConfigJson, err := json.MarshalIndent(config, "", " ")
if err != nil </span><span class="cov0" title="0">{
ctx.Logger.Info("Error marshalling updated config", "error", err)
return "Error generating updated config", err
}</span>
// Write the updated config back to the file
<span class="cov0" title="0">if err := os.WriteFile(configPath, updatedConfigJson, 0644); err != nil </span><span class="cov0" title="0">{
ctx.Logger.Info("Error writing updated config file", "configPath", configPath, "error", err)
return "Error writing configuration file", err
}</span>
<span class="cov0" title="0">ctx.Logger.Info("Configuration value set successfully", "key", args.Key)
return "Configuration value set successfully.", nil</span>
}
</pre>
<pre class="file" id="file4" style="display: none">package edit
import (
"fmt"
"os"
"strings"
"github.com/localrivet/gomcp/server"
"github.com/sergi/go-diff/diffmatchpatch"
)
const maxEditFileSize = 100 * 1024 * 1024 // 100 MB limit
// Go structs for tool arguments
type EditBlockArgs struct {
FilePath string `json:"file_path" description:"The path to the file to edit." required:"true"`
OldString string `json:"old_string" description:"The exact block of text to find and replace." required:"true"`
NewString string `json:"new_string" description:"The new block of text to insert." required:"true"`
ExpectedReplacements *int `json:"expected_replacements,omitempty" description:"Optional. If provided, the exact number of replacements expected. Defaults to 1."`
}
// HandleEditBlock implements the edit_block tool using the new API
func HandleEditBlock(ctx *server.Context, args EditBlockArgs) (string, error) <span class="cov0" title="0">{
ctx.Logger.Info("Handling edit_block tool call")
// --- File Size Check ---
fileInfo, err := os.Stat(args.FilePath)
if err != nil </span><span class="cov0" title="0">{
// Handle file not found or other stat errors
if os.IsNotExist(err) </span><span class="cov0" title="0">{
ctx.Logger.Info("File not found", "filePath", args.FilePath)
return "Error: File not found.", err
}</span>
<span class="cov0" title="0">ctx.Logger.Info("Error getting file info", "filePath", args.FilePath, "error", err)
return "Error accessing file information.", err</span>
}
<span class="cov0" title="0">if fileInfo.Size() > maxEditFileSize </span><span class="cov0" title="0">{
errorMsg := fmt.Sprintf("Error: File size (%d bytes) exceeds the %d MB limit for this editing tool due to memory constraints. Please use a different tool or method for editing very large files. If this is a source code file, consider splitting it into smaller modules/files if appropriate for the language.", fileInfo.Size(), maxEditFileSize/(1024*1024))
ctx.Logger.Info(errorMsg)
return errorMsg, nil
}</span>
// --- End File Size Check ---
// Read the file (now known to be within size limit)
<span class="cov0" title="0">content, err := os.ReadFile(args.FilePath)
if err != nil </span><span class="cov0" title="0">{
// This error should be less likely now after Stat, but handle anyway
ctx.Logger.Info("Error reading file", "filePath", args.FilePath, "error", err)
return "Error reading file for editing", err
}</span>
<span class="cov0" title="0">originalContent := string(content)
var modifiedContent string
// --- Perform Context-Aware Replacement ---
replacementsMade := 0
expected := 1 // Default expectation
if args.ExpectedReplacements != nil </span><span class="cov0" title="0">{
expected = *args.ExpectedReplacements
if expected <= 0 </span><span class="cov0" title="0">{
return "expected_replacements must be positive", nil
}</span>
// --- Handle Multiple Replacements (Using strings.Replace for now) ---
<span class="cov0" title="0">actualOccurrences := strings.Count(originalContent, args.OldString)
if actualOccurrences < expected </span><span class="cov0" title="0">{
msg := fmt.Sprintf("Expected %d replacements, but only found %d occurrences of the old string.", expected, actualOccurrences)
ctx.Logger.Info(msg, "filePath", args.FilePath)
return msg, nil
}</span>
<span class="cov0" title="0">modifiedContent = strings.Replace(originalContent, args.OldString, args.NewString, expected)
if modifiedContent == originalContent && expected > 0 && actualOccurrences > 0 </span><span class="cov0" title="0">{
msg := fmt.Sprintf("Replacement failed unexpectedly for %d expected replacements despite %d occurrences.", expected, actualOccurrences)
ctx.Logger.Info(msg, "filePath", args.FilePath)
return msg, nil
}</span>
<span class="cov0" title="0">replacementsMade = expected</span>
} else<span class="cov0" title="0"> {
// --- Handle Single Replacement (Default) ---
index := strings.Index(originalContent, args.OldString)
if index == -1 </span><span class="cov0" title="0">{
// Old string not found, generate near-miss diff if possible
ctx.Logger.Info("Old string block not found in file", "filePath", args.FilePath)
// --- Generate Diff for Near Miss ---
dmp := diffmatchpatch.New()
bestMatchIndex := dmp.MatchMain(originalContent, args.OldString, 0)
var errorMsg string
if bestMatchIndex != -1 </span><span class="cov0" title="0">{
// Found a potential near miss location
endIndex := bestMatchIndex + len(args.OldString)
if endIndex > len(originalContent) </span><span class="cov0" title="0">{
endIndex = len(originalContent)
}</span>
<span class="cov0" title="0">closestMatchBlock := originalContent[bestMatchIndex:endIndex]
// Generate diff between expected OldString and the actual block found
diffs := dmp.DiffMain(args.OldString, closestMatchBlock, false)
diffText := dmp.DiffPrettyText(diffs)
diffText = strings.ReplaceAll(diffText, "\\n", "\n")
diffText = strings.ReplaceAll(diffText, "%", "%%")
errorMsg = fmt.Sprintf("Failed to apply edit. Found a potential match near character %d with differences:\n---\n%s\n---", bestMatchIndex, diffText)
ctx.Logger.Info("Near miss found for edit_block", "filePath", args.FilePath)</span>
} else<span class="cov0" title="0"> {
// Couldn't find a reasonable match, just show the expected block
ctx.Logger.Info("Near miss check failed to find any likely match for edit_block", "filePath", args.FilePath)
diffsNotFound := dmp.DiffMain(args.OldString, "", false)
diffText := dmp.DiffPrettyText(diffsNotFound)
diffText = strings.ReplaceAll(diffText, "\\n", "\n")
diffText = strings.ReplaceAll(diffText, "%", "%%")
errorMsg = fmt.Sprintf("Failed to apply edit. Old string block not found/matched exactly. Expected block looked like:\n---\n%s\n---", diffText)
}</span>
<span class="cov0" title="0">return errorMsg, nil</span>
} else<span class="cov0" title="0"> {
// Old string found, perform the replacement
modifiedContent = originalContent[:index] + args.NewString + originalContent[index+len(args.OldString):]
replacementsMade = 1
}</span>
}
// This check is slightly redundant now but kept as a safeguard
<span class="cov0" title="0">if replacementsMade == 0 && expected > 0 </span><span class="cov0" title="0">{
ctx.Logger.Info("Replacement logic failed unexpectedly", "filePath", args.FilePath)
return "Internal error during replacement.", nil
}</span>
// Write the modified content back to the file
<span class="cov0" title="0">if err := os.WriteFile(args.FilePath, []byte(modifiedContent), 0644); err != nil </span><span class="cov0" title="0">{
ctx.Logger.Info("Error writing file after edit_block", "filePath", args.FilePath, "error", err)
return "Error writing file after editing", err
}</span>
<span class="cov0" title="0">return "File edited successfully.", nil</span>
}
</pre>
<pre class="file" id="file5" style="display: none">package edit
import (
"fmt"
"os"
"strings"
"github.com/localrivet/gomcp/server"
)
// const maxEditFileSize = 100 * 1024 * 1024 // Defined in edit.go
// Go structs for tool arguments - Updated for line-based editing
type PreciseEditArgs struct {
FilePath string `json:"file_path" description:"The path to the file to edit." required:"true"`
StartLine int `json:"start_line" description:"The 1-indexed line number where the edit begins (inclusive)." required:"true"`
EndLine int `json:"end_line" description:"The 1-indexed line number where the block to be replaced ends (inclusive). For insertion before start_line, use end_line = start_line - 1." required:"true"`
NewContent string `json:"new_content" description:"The new content (potentially multi-line) to insert or replace the specified lines with." required:"true"`
}
// HandlePreciseEdit performs line-based editing on a file using the new API
func HandlePreciseEdit(ctx *server.Context, args PreciseEditArgs) (string, error) <span class="cov0" title="0">{
ctx.Logger.Info("Handling precise_edit tool call (line-based editing, in-memory)")
// --- Input Validation ---
if args.StartLine <= 0 </span><span class="cov0" title="0">{
msg := "start_line must be positive and 1-indexed"
ctx.Logger.Info(msg)
return msg, nil
}</span>
// Allow end_line to be start_line - 1 for insertion
<span class="cov0" title="0">if args.EndLine < args.StartLine-1 </span><span class="cov0" title="0">{
msg := "end_line cannot be less than start_line - 1"
ctx.Logger.Info(msg)
return msg, nil
}</span>
// --- File Size Check ---
<span class="cov0" title="0">fileInfo, err := os.Stat(args.FilePath)
fileExists := !os.IsNotExist(err)
if err != nil && fileExists </span><span class="cov0" title="0">{ // Handle stat errors only if file exists
ctx.Logger.Info("Error getting file info", "filePath", args.FilePath, "error", err)
return "Error accessing file information.", err
}</span>
// Allow file not found only if inserting at the beginning of a new file
<span class="cov0" title="0">if !fileExists && !(args.StartLine == 1 && args.EndLine == 0) </span><span class="cov0" title="0">{
ctx.Logger.Info("File does not exist and cannot perform edit", "filePath", args.FilePath)
return "Error: File not found.", nil
}</span>
// Check size only if the file exists
<span class="cov0" title="0">if fileExists && fileInfo.Size() > maxEditFileSize </span><span class="cov0" title="0">{
errorMsg := fmt.Sprintf("Error: File size (%d bytes) exceeds the %d MB limit for this editing tool due to memory constraints. Please use a different tool or method for editing very large files. If this is a source code file, consider splitting it into smaller modules/files if appropriate for the language.", fileInfo.Size(), maxEditFileSize/(1024*1024))
ctx.Logger.Info(errorMsg)
return errorMsg, nil
}</span>
// --- End File Size Check ---
// --- Read File ---
<span class="cov0" title="0">var contentBytes []byte
if fileExists </span><span class="cov0" title="0">{
contentBytes, err = os.ReadFile(args.FilePath)
if err != nil </span><span class="cov0" title="0">{
// This error should be less likely now after Stat, but handle anyway
ctx.Logger.Info("Error reading file for precise_edit", "filePath", args.FilePath, "error", err)
return "Error reading file for patching", err
}</span>
} else<span class="cov0" title="0"> {
// File doesn't exist, but we are inserting at start
ctx.Logger.Info("File does not exist, creating new file for insertion", "filePath", args.FilePath)
contentBytes = []byte{} // Start with empty content
}</span>
<span class="cov0" title="0">originalContent := string(contentBytes)
// Detect line endings, default to \n
lineEnding := "\n"
if strings.Contains(originalContent, "\r\n") </span><span class="cov0" title="0">{
lineEnding = "\r\n"
}</span>
<span class="cov0" title="0">lines := strings.Split(originalContent, lineEnding)
// Handle potential trailing newline splitting issue
// If the file ends with a newline, Split leaves an empty string at the end.
if len(originalContent) > 0 && strings.HasSuffix(originalContent, lineEnding) && len(lines) > 0 </span><span class="cov0" title="0">{
// Keep the empty string unless the file was *only* the line ending(s)
if len(lines) == 1 && lines[0] == "" </span><span class="cov0" title="0">{
lines = []string{""} // File was empty or just newline(s)
}</span>
// Otherwise, the empty string from split is handled correctly by len(lines) below
} else<span class="cov0" title="0"> if originalContent == "" </span><span class="cov0" title="0">{
lines = []string{} // If the original file was completely empty
}</span>
<span class="cov0" title="0">numLines := len(lines)
// Correct numLines if the split resulted in [""] for an empty file
if numLines == 1 && lines[0] == "" </span><span class="cov0" title="0">{
numLines = 0
}</span>
// --- Line Number Validation ---
// Allow insertion *after* the last line
<span class="cov0" title="0">if args.StartLine > numLines+1 </span><span class="cov0" title="0">{
msg := fmt.Sprintf("start_line (%d) exceeds the number of lines (%d) + 1", args.StartLine, numLines)
ctx.Logger.Info(msg)
return msg, nil
}</span>
// EndLine must be within bounds or StartLine-1 for insertion
<span class="cov0" title="0">if args.EndLine > numLines || args.EndLine < args.StartLine-1 </span><span class="cov0" title="0">{
if !(args.EndLine == 0 && args.StartLine == 1 && numLines == 0) </span><span class="cov0" title="0">{ // Allow insert into empty file
msg := fmt.Sprintf("end_line (%d) is out of bounds [0..%d] or invalid relative to start_line (%d)", args.EndLine, numLines, args.StartLine)
ctx.Logger.Info(msg)
return msg, nil
}</span>
}
// --- Construct New Content ---
<span class="cov0" title="0">var newLines []string
// 1. Add lines before the start line (adjust index to 0-based)
startIdx := args.StartLine - 1
if startIdx > 0 && startIdx <= numLines </span><span class="cov0" title="0">{ // Ensure startIdx is valid
newLines = append(newLines, lines[0:startIdx]...)
}</span>
// 2. Add the new content (split if multi-line)
<span class="cov0" title="0">if args.NewContent != "" </span><span class="cov0" title="0">{
// Use the detected line ending for splitting NewContent as well
newContentLines := strings.Split(args.NewContent, lineEnding)
// Handle potential trailing newline in NewContent causing extra empty string
if len(args.NewContent) > 0 && strings.HasSuffix(args.NewContent, lineEnding) && len(newContentLines) > 0 </span><span class="cov0" title="0">{
// If NewContent ends with newline, Split adds an empty string. We usually want that empty string
// to represent the line break *after* the last line of actual content.
newLines = append(newLines, newContentLines...)
}</span> else<span class="cov0" title="0"> {
newLines = append(newLines, newContentLines...)
}</span>
}
// 3. Add lines after the end line (adjust index to 0-based)
// endIdx is the line number *after* the last line to be replaced/skipped
<span class="cov0" title="0">endIdx := args.EndLine + 1
if endIdx <= numLines </span><span class="cov0" title="0">{ // Check if endIdx is within the bounds of original lines
newLines = append(newLines, lines[endIdx-1:]...) // Add from the line *after* EndLine
}</span>
// --- Write File ---
// Join lines with the original line ending
<span class="cov0" title="0">finalContent := strings.Join(newLines, lineEnding)
// Ensure trailing newline if the original had one and the edit didn't remove the last line
// Or if the original was empty and new content was added.
if (len(originalContent) > 0 && strings.HasSuffix(originalContent, lineEnding) && endIdx <= numLines) ||
(len(originalContent) == 0 && len(finalContent) > 0) </span><span class="cov0" title="0">{
if !strings.HasSuffix(finalContent, lineEnding) </span><span class="cov0" title="0">{
finalContent += lineEnding
}</span>
}
// Get original file info for permissions
<span class="cov0" title="0">fileMode := os.FileMode(0644) // Default permission
if fileExists </span><span class="cov0" title="0">{
fileInfo, infoErr := os.Stat(args.FilePath)
if infoErr == nil </span><span class="cov0" title="0">{
fileMode = fileInfo.Mode()
}</span> else<span class="cov0" title="0"> { // Log if error is something other than NotExist (already handled)
ctx.Logger.Info("Warning: Could not get file info, using default permissions", "filePath", args.FilePath, "error", infoErr)
}</span>
}
// Write the patched content back to the original file path (truncates existing)
<span class="cov0" title="0">if err := os.WriteFile(args.FilePath, []byte(finalContent), fileMode); err != nil </span><span class="cov0" title="0">{
ctx.Logger.Info("Error writing patched file", "filePath", args.FilePath, "error", err)
return "Error writing patched file", err
}</span>
<span class="cov0" title="0">ctx.Logger.Info("File edited successfully using precise_edit (in-memory)", "filePath", args.FilePath)
return "File edited successfully.", nil</span>
}
</pre>
<pre class="file" id="file6" style="display: none">package filesystem
import (
"os"
"github.com/localrivet/gomcp/server"
)
// CreateDirectoryArgs defines the arguments for the create_directory tool.
type CreateDirectoryArgs struct {
Path string `json:"path" description:"The path of the directory to create." required:"true"`
}
// HandleCreateDirectory implements the logic for the create_directory tool using the new API.
func HandleCreateDirectory(ctx *server.Context, args CreateDirectoryArgs) (string, error) <span class="cov0" title="0">{
ctx.Logger.Info("Handling create_directory tool call")
// Create the directory and any necessary parent directories. 0755 is a common permission for directories.
if err := os.MkdirAll(args.Path, 0755); err != nil </span><span class="cov0" title="0">{
ctx.Logger.Info("Error creating directory", "path", args.Path, "error", err)
return "Error creating directory", err
}</span>
<span class="cov0" title="0">return "Directory created successfully.", nil</span>
}
</pre>
<pre class="file" id="file7" style="display: none">package filesystem
import (
"encoding/json"
"os"
"time"
"github.com/localrivet/gomcp/server"
)
// GetFileInfoArgs defines the arguments for the get_file_info tool.
type GetFileInfoArgs struct {
Path string `json:"path" description:"The path of the file or directory to get information for." required:"true"`
}
// HandleGetFileInfo implements the get_file_info tool using the new API
func HandleGetFileInfo(ctx *server.Context, args GetFileInfoArgs) (string, error) <span class="cov0" title="0">{
ctx.Logger.Info("Handling get_file_info tool call")
fileInfo, err := os.Stat(args.Path)
if err != nil </span><span class="cov0" title="0">{
ctx.Logger.Info("Error getting file info", "path", args.Path, "error", err)
return "Error getting file info", err
}</span>
// Format the file info
<span class="cov0" title="0">info := map[string]interface{}{
"name": fileInfo.Name(),
"size": fileInfo.Size(),
"is_dir": fileInfo.IsDir(),
"mode": fileInfo.Mode().String(),
"mod_time": fileInfo.ModTime().Format(time.RFC3339),
}
// Marshal the file info into JSON
infoJson, marshalErr := json.MarshalIndent(info, "", " ")
if marshalErr != nil </span><span class="cov0" title="0">{
ctx.Logger.Info("Error marshalling file info", "error", marshalErr)
return "Error generating file info output", marshalErr
}</span>
<span class="cov0" title="0">return string(infoJson), nil</span>
}
</pre>
<pre class="file" id="file8" style="display: none">package filesystem
import (
"encoding/json"
"os"
"github.com/localrivet/gomcp/server"
)
// ListDirectoryArgs defines the arguments for the list_directory tool.
type ListDirectoryArgs struct {
Path string `json:"path" description:"The path of the directory to list." required:"true"`
}
// HandleListDirectory implements the list_directory tool using the new API
func HandleListDirectory(ctx *server.Context, args ListDirectoryArgs) (string, error) <span class="cov0" title="0">{
ctx.Logger.Info("Handling list_directory tool call")
files, err := os.ReadDir(args.Path)
if err != nil </span><span class="cov0" title="0">{
ctx.Logger.Info("Error reading directory", "path", args.Path, "error", err)
return "Error reading directory", err
}</span>
<span class="cov0" title="0">var fileList []string
for _, file := range files </span><span class="cov0" title="0">{
fileType := "[FILE]"
if file.IsDir() </span><span class="cov0" title="0">{
fileType = "[DIR]"
}</span>
<span class="cov0" title="0">fileList = append(fileList, fileType+" "+file.Name())</span>
}
// Marshal the file list into JSON
<span class="cov0" title="0">fileListJson, err := json.MarshalIndent(fileList, "", " ")
if err != nil </span><span class="cov0" title="0">{
ctx.Logger.Info("Error marshalling file list for list_directory", "error", err)
return "Error generating file list output", err
}</span>
<span class="cov0" title="0">return string(fileListJson), nil</span>
}
</pre>
<pre class="file" id="file9" style="display: none">package filesystem
import (
"os"
"github.com/localrivet/gomcp/server"
)
// MoveFileArgs defines the arguments for the move_file tool.
type MoveFileArgs struct {
Source string `json:"source" description:"The source path of the file or directory." required:"true"`
Destination string `json:"destination" description:"The destination path for the file or directory." required:"true"`
}
// HandleMoveFile implements the move_file tool using the new API
func HandleMoveFile(ctx *server.Context, args MoveFileArgs) (string, error) <span class="cov0" title="0">{
ctx.Logger.Info("Handling move_file tool call")
// Perform the move/rename operation
if err := os.Rename(args.Source, args.Destination); err != nil </span><span class="cov0" title="0">{
ctx.Logger.Info("Error moving/renaming file", "source", args.Source, "destination", args.Destination, "error", err)
return "Error moving/renaming file", err
}</span>
<span class="cov0" title="0">return "File moved/renamed successfully.", nil</span>
}
</pre>
<pre class="file" id="file10" style="display: none">package filesystem
import (
"fmt"
"os"
"strings"
"github.com/localrivet/gomcp/server"
)
// Go structs for tool arguments
type ReadFileArgs struct {
FilePath string `json:"file_path" description:"The path to the file to read." required:"true"`
StartLine *int `json:"start_line,omitempty" description:"Optional starting line number (1-indexed) for paging."`
EndLine *int `json:"end_line,omitempty" description:"Optional ending line number (1-indexed, inclusive) for paging."`
}
// HandleReadFile implements the read_file tool using the new API
func HandleReadFile(ctx *server.Context, args ReadFileArgs) (string, error) <span class="cov0" title="0">{
ctx.Logger.Info("Handling read_file tool call")
// Read the file
content, err := os.ReadFile(args.FilePath)
if err != nil </span><span class="cov0" title="0">{
ctx.Logger.Info("Error reading file", "file_path", args.FilePath, "error", err)
return "Error reading file", err
}</span>
<span class="cov0" title="0">fileContent := string(content)
// If no line range specified, return the entire file
if args.StartLine == nil && args.EndLine == nil </span><span class="cov0" title="0">{
return fileContent, nil
}</span>
// Handle line-based paging
<span class="cov0" title="0">lines := strings.Split(fileContent, "\n")
totalLines := len(lines)
startLine := 1
if args.StartLine != nil </span><span class="cov0" title="0">{
startLine = *args.StartLine
}</span>
<span class="cov0" title="0">endLine := totalLines
if args.EndLine != nil </span><span class="cov0" title="0">{
endLine = *args.EndLine
}</span>
// Validate line numbers
<span class="cov0" title="0">if startLine < 1 </span><span class="cov0" title="0">{
startLine = 1
}</span>
<span class="cov0" title="0">if endLine > totalLines </span><span class="cov0" title="0">{
endLine = totalLines
}</span>
<span class="cov0" title="0">if startLine > endLine </span><span class="cov0" title="0">{
return "Invalid line range: start_line must be <= end_line", nil
}</span>
// Extract the requested lines (convert to 0-based indexing)
<span class="cov0" title="0">selectedLines := lines[startLine-1 : endLine]
result := strings.Join(selectedLines, "\n")
// Add line number information
info := fmt.Sprintf("Lines %d-%d of %d total lines:\n%s", startLine, endLine, totalLines, result)
return info, nil</span>
}