@@ -0,0 +1,260 @@
1+package mcptools
2+
3+import (
4+ "bytes"
5+ "context"
6+ "encoding/json"
7+ "fmt"
8+ "io/fs"
9+ "os"
10+ "path/filepath"
11+ "strings"
12+ "time"
13+
14+ "github.com/xonecas/symb/internal/delta"
15+ "github.com/xonecas/symb/internal/mcp"
16+ "github.com/xonecas/symb/internal/shell"
17+)
18+
19+// ShellArgs are the arguments to the Shell tool.
20+type ShellArgs struct {
21+ Command string `json:"command"`
22+ Description string `json:"description"`
23+ Timeout int `json:"timeout,omitempty"` // seconds, default 60
24+}
25+
26+// NewShellTool creates the Shell tool definition.
27+func NewShellTool() mcp.Tool {
28+ return mcp.Tool{
29+ Name: "Shell",
30+ Description: `Execute a shell command in an in-process POSIX interpreter.
31+Commands run inside the project working directory. Shell state (cwd, env vars) persists across calls within the same session.
32+Dangerous commands (network, sudo, package managers, system modification) are blocked.
33+Use this for: running builds, tests, linters, git operations, file manipulation, and inspecting project state.`,
34+ InputSchema: json.RawMessage(`{
35+ "type": "object",
36+ "properties": {
37+ "command": {"type": "string", "description": "The shell command to execute"},
38+ "description": {"type": "string", "description": "Brief description of what this command does (5-10 words)"},
39+ "timeout": {"type": "integer", "description": "Timeout in seconds (default 60)"}
40+ },
41+ "required": ["command", "description"]
42+ }`),
43+ }
44+}
45+
46+// ShellHandler handles Shell tool calls.
47+type ShellHandler struct {
48+ sh *shell.Shell
49+ deltaTracker *delta.Tracker
50+ // OnOutput is called with incremental output chunks for real-time streaming.
51+ // May be nil.
52+ OnOutput func(chunk string)
53+}
54+
55+// NewShellHandler creates a handler for the Shell tool.
56+func NewShellHandler(sh *shell.Shell, dt *delta.Tracker) *ShellHandler {
57+ return &ShellHandler{sh: sh, deltaTracker: dt}
58+}
59+
60+// Handle implements the mcp.ToolHandler interface.
61+func (h *ShellHandler) Handle(ctx context.Context, arguments json.RawMessage) (*mcp.ToolResult, error) {
62+ var args ShellArgs
63+ if err := json.Unmarshal(arguments, &args); err != nil {
64+ return toolError("Invalid arguments: %v", err), nil
65+ }
66+ if args.Command == "" {
67+ return toolError("command is required"), nil
68+ }
69+
70+ timeout := 60
71+ if args.Timeout > 0 {
72+ timeout = args.Timeout
73+ }
74+ if timeout > maxTimeoutSec {
75+ timeout = maxTimeoutSec
76+ }
77+
78+ ctx, cancel := context.WithTimeout(ctx, time.Duration(timeout)*time.Second)
79+ defer cancel()
80+
81+ // Snapshot the shell's working directory for undo — only when the delta
82+ // tracker is active (has a turn), to avoid expensive walks on read-only commands.
83+ shellCwd := h.sh.Dir()
84+ trackDeltas := h.deltaTracker != nil && h.deltaTracker.TurnID() > 0
85+ var preSnap map[string]fileSnapshot
86+ if trackDeltas {
87+ preSnap = snapshotDir(shellCwd)
88+ }
89+
90+ // Execute command with streaming output.
91+ var stdout, stderr bytes.Buffer
92+
93+ var execErr error
94+ if h.OnOutput != nil {
95+ sw := &streamWriter{buf: &stdout, onChunk: h.OnOutput}
96+ execErr = h.sh.ExecStream(ctx, args.Command, sw, &stderr)
97+ } else {
98+ execErr = h.sh.ExecStream(ctx, args.Command, &stdout, &stderr)
99+ }
100+
101+ // Post-execution: diff the *original* cwd to record deltas for undo.
102+ // Always use shellCwd (the pre-exec directory) for both snapshots so a
103+ // `cd` inside the command doesn't cause a cross-directory mismatch.
104+ if trackDeltas {
105+ postSnap := snapshotDir(shellCwd)
106+ recordDeltas(h.deltaTracker, shellCwd, preSnap, postSnap)
107+ }
108+
109+ // Format result.
110+ exitCode := shell.ExitCode(execErr)
111+ output := formatShellOutput(stdout.String(), stderr.String(), exitCode, ctx.Err())
112+
113+ // Ensure non-empty output — some providers reject empty tool results.
114+ if output == "" {
115+ output = "(no output)\n"
116+ }
117+
118+ if len([]rune(output)) > maxOutputChars {
119+ output = truncateMiddle(output, maxOutputChars)
120+ }
121+
122+ if exitCode != 0 {
123+ return &mcp.ToolResult{
124+ Content: []mcp.ContentBlock{{Type: "text", Text: output}},
125+ IsError: true,
126+ }, nil
127+ }
128+ return toolText(output), nil
129+}
130+
131+const maxOutputChars = 30000
132+const maxTimeoutSec = 600 // 10 minutes
133+
134+// streamWriter wraps a bytes.Buffer and calls onChunk for each Write.
135+type streamWriter struct {
136+ buf *bytes.Buffer
137+ onChunk func(string)
138+}
139+
140+func (w *streamWriter) Write(p []byte) (int, error) {
141+ n, err := w.buf.Write(p)
142+ if n > 0 && w.onChunk != nil {
143+ w.onChunk(string(p[:n]))
144+ }
145+ return n, err
146+}
147+
148+func formatShellOutput(stdout, stderr string, exitCode int, ctxErr error) string {
149+ var b strings.Builder
150+ if stdout != "" {
151+ b.WriteString(stdout)
152+ if !strings.HasSuffix(stdout, "\n") {
153+ b.WriteByte('\n')
154+ }
155+ }
156+ if stderr != "" {
157+ b.WriteString(stderr)
158+ if !strings.HasSuffix(stderr, "\n") {
159+ b.WriteByte('\n')
160+ }
161+ }
162+ if ctxErr != nil {
163+ fmt.Fprintf(&b, "[timed out]\n")
164+ }
165+ if exitCode != 0 {
166+ fmt.Fprintf(&b, "[exit code: %d]\n", exitCode)
167+ }
168+ return b.String()
169+}
170+
171+func truncateMiddle(s string, maxChars int) string {
172+ runes := []rune(s)
173+ if len(runes) <= maxChars {
174+ return s
175+ }
176+ half := maxChars / 2
177+ return string(runes[:half]) + "\n\n... [truncated] ...\n\n" + string(runes[len(runes)-half:])
178+}
179+
180+// ---------------------------------------------------------------------------
181+// CWD snapshot for undo
182+// ---------------------------------------------------------------------------
183+
184+// fileSnapshot holds mtime+size+content for change detection and undo.
185+type fileSnapshot struct {
186+ modTime time.Time
187+ size int64
188+ content []byte // pre-read for undo; nil for large files
189+}
190+
191+// maxSnapshotFileSize is the max file size we pre-read for undo (1 MB).
192+const maxSnapshotFileSize = 1 << 20
193+
194+// skipDirs are directories skipped during snapshot walks.
195+var skipDirs = map[string]bool{
196+ ".git": true, "node_modules": true, "__pycache__": true,
197+ ".venv": true, "vendor": true, ".cache": true, ".next": true,
198+ "dist": true, "build": true, "target": true,
199+}
200+
201+// snapshotDir walks root and returns a map of relative path -> fileSnapshot.
202+// Files under maxSnapshotFileSize have their content pre-read for undo.
203+func snapshotDir(root string) map[string]fileSnapshot {
204+ snap := make(map[string]fileSnapshot)
205+ _ = filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
206+ if err != nil {
207+ return nil
208+ }
209+ if d.IsDir() {
210+ if skipDirs[d.Name()] {
211+ return filepath.SkipDir
212+ }
213+ return nil
214+ }
215+ rel, err := filepath.Rel(root, path)
216+ if err != nil {
217+ return nil
218+ }
219+ info, err := d.Info()
220+ if err != nil {
221+ return nil
222+ }
223+ fs := fileSnapshot{modTime: info.ModTime(), size: info.Size()}
224+ if info.Size() <= maxSnapshotFileSize {
225+ fs.content, _ = os.ReadFile(path)
226+ }
227+ snap[rel] = fs
228+ return nil
229+ })
230+ return snap
231+}
232+
233+// recordDeltas compares pre/post snapshots and records deltas for undo.
234+func recordDeltas(dt *delta.Tracker, root string, pre, post map[string]fileSnapshot) {
235+ // New or modified files.
236+ for rel, postInfo := range post {
237+ absPath := filepath.Join(root, rel)
238+ preInfo, existed := pre[rel]
239+ if !existed {
240+ dt.RecordCreate(absPath)
241+ continue
242+ }
243+ if preInfo.modTime != postInfo.modTime || preInfo.size != postInfo.size {
244+ // File was modified — use pre-read content for undo.
245+ dt.RecordModify(absPath, preInfo.content)
246+ }
247+ }
248+ // Deleted files — existed in pre but not in post.
249+ for rel, preInfo := range pre {
250+ if _, exists := post[rel]; !exists {
251+ absPath := filepath.Join(root, rel)
252+ if preInfo.content != nil {
253+ // We have the original content; record as modify so undo restores it.
254+ dt.RecordModify(absPath, preInfo.content)
255+ }
256+ // If content is nil (file was > maxSnapshotFileSize), we can't
257+ // restore it. Skip rather than writing a 0-byte file on undo.
258+ }
259+ }
260+}