62159
Sy
symb / files
symb / internal / mcptools / edit.go
10.1 KB
1package mcptools 2 3import ( 4 "context" 5 "encoding/json" 6 "fmt" 7 "os" 8 "path/filepath" 9 "strings" 10 "time" 11 12 "github.com/xonecas/symb/internal/delta" 13 "github.com/xonecas/symb/internal/hashline" 14 "github.com/xonecas/symb/internal/lsp" 15 "github.com/xonecas/symb/internal/mcp" 16 "github.com/xonecas/symb/internal/treesitter" 17) 18 19const ( 20 // windowThreshold is the minimum line count to trigger windowed output. 21 windowThreshold = 50 22 // windowContext is the number of lines shown above/below the edit region. 23 windowContext = 20 24) 25 26// editRegion describes which lines (1-indexed, inclusive) were affected in the new file. 27type editRegion struct { 28 start int // first affected line 29 end int // last affected line 30} 31 32// EditArgs represents arguments for the Edit tool (flat schema). 33type EditArgs struct { 34 File string `json:"file"` 35 Operation string `json:"operation"` 36 Start string `json:"start,omitempty"` // "line:hash" anchor 37 End string `json:"end,omitempty"` // "line:hash" anchor 38 After string `json:"after,omitempty"` // "line:hash" anchor (insert) 39 Content string `json:"content,omitempty"` // text content 40} 41 42// NewEditTool creates the Edit tool definition. 43func NewEditTool() mcp.Tool { 44 return mcp.Tool{ 45 Name: "Edit", 46 Description: `Edit a file using hash-anchored operations. You MUST Read the file first to get line hashes. 47Each line from Read is tagged as "linenum:hash|content". Use "line:hash" strings as anchors. 48Exactly one operation per call: replace, insert, delete, or create. 49If a hash does not match, the file changed since you read it — re-Read and retry. 50After each edit you receive fresh hashes — use those for subsequent edits, not the old ones. 51Never use Shell to write files — always use Edit. 52 53Operations: 54- replace: replace lines from start anchor to end anchor with content 55- insert: insert content after the 'after' anchor line 56- delete: delete lines from start anchor to end anchor 57- create: create a new file with content (fails if file exists; no anchors needed)`, 58 InputSchema: json.RawMessage(`{ 59 "type": "object", 60 "properties": { 61 "file": {"type": "string", "description": "Path to the file to edit"}, 62 "operation": {"type": "string", "enum": ["replace", "insert", "delete", "create"], "description": "The edit operation to perform"}, 63 "start": {"type": "string", "description": "Start anchor as 'line:hash' (replace, delete)"}, 64 "end": {"type": "string", "description": "End anchor as 'line:hash' (replace, delete)"}, 65 "after": {"type": "string", "description": "Insert-after anchor as 'line:hash' (insert)"}, 66 "content": {"type": "string", "description": "Text content (replace, insert, create)"} 67 }, 68 "required": ["file", "operation"] 69 }`), 70 } 71} 72 73// EditHandler handles Edit tool calls. 74type EditHandler struct { 75 tracker *FileReadTracker 76 lspManager *lsp.Manager 77 tsIndex *treesitter.Index 78 deltaTracker *delta.Tracker 79 rootDir string 80} 81 82// NewEditHandler creates a handler for the Edit tool. 83func NewEditHandler(tracker *FileReadTracker, lspManager *lsp.Manager, dt *delta.Tracker) *EditHandler { 84 return &EditHandler{tracker: tracker, lspManager: lspManager, deltaTracker: dt} 85} 86 87// SetTSIndex sets the tree-sitter index for incremental updates on edit. 88func (h *EditHandler) SetTSIndex(idx *treesitter.Index) { h.tsIndex = idx } 89 90// SetRootDir overrides the base directory for path validation. 91func (h *EditHandler) SetRootDir(root string) { h.rootDir = root } 92 93// Handle implements the mcp.ToolHandler interface. 94func (h *EditHandler) Handle(ctx context.Context, arguments json.RawMessage) (*mcp.ToolResult, error) { 95 var args EditArgs 96 if err := json.Unmarshal(arguments, &args); err != nil { 97 return toolError("Invalid arguments: %v", err), nil 98 } 99 if args.File == "" { 100 return toolError("file is required"), nil 101 } 102 if args.Operation == "" { 103 return toolError("operation is required (replace, insert, delete, or create)"), nil 104 } 105 106 var absPath string 107 var err error 108 if h.rootDir != "" { 109 absPath, err = validatePathWithRoot(args.File, h.rootDir) 110 } else { 111 absPath, err = validatePath(args.File) 112 } 113 if err != nil { 114 return toolError("%v", err), nil 115 } 116 117 if args.Operation == "create" { 118 return h.handleCreate(ctx, absPath, args.File, args.Content) 119 } 120 121 if !h.tracker.WasRead(absPath) { 122 return toolError("You must Read the file before editing it. Use Read on %s first — you need the line hashes.", args.File), nil 123 } 124 125 return h.applyEdit(ctx, absPath, args) 126} 127 128// applyEdit reads the file, applies the edit operation, writes it back, and returns fresh hashes. 129func (h *EditHandler) applyEdit(ctx context.Context, absPath string, args EditArgs) (*mcp.ToolResult, error) { 130 content, err := os.ReadFile(absPath) 131 if err != nil { 132 return toolError("Failed to read file: %v", err), nil 133 } 134 lines := strings.Split(string(content), "\n") 135 136 var result string 137 var region editRegion 138 switch args.Operation { 139 case "replace": 140 result, region, err = applyReplace(lines, args) 141 case "insert": 142 result, region, err = applyInsert(lines, args) 143 case "delete": 144 result, region, err = applyDelete(lines, args) 145 default: 146 return toolError("unknown operation %q: use replace, insert, delete, or create", args.Operation), nil 147 } 148 if err != nil { 149 return toolError("%v", err), nil 150 } 151 152 if h.deltaTracker != nil { 153 h.deltaTracker.RecordModify(absPath, content) 154 } 155 156 if err := os.WriteFile(absPath, []byte(result), 0600); err != nil { 157 return toolError("Failed to write file: %v", err), nil 158 } 159 160 tagged := hashline.TagLines(result, 1) 161 text := formatEditResponse(args.File, tagged, region) 162 163 if h.lspManager != nil { 164 diags := h.lspManager.NotifyAndWait(ctx, absPath, 5*time.Second) 165 text += lsp.FormatDiagnostics(args.File, diags) 166 } 167 if h.tsIndex != nil { 168 h.tsIndex.UpdateFile(absPath) 169 } 170 171 return &mcp.ToolResult{ 172 Content: []mcp.ContentBlock{{Type: "text", Text: text}}, 173 }, nil 174} 175 176func (h *EditHandler) handleCreate(ctx context.Context, absPath, displayPath, content string) (*mcp.ToolResult, error) { 177 // Fail if file already exists 178 if _, err := os.Stat(absPath); err == nil { 179 return toolError("File already exists: %s (use replace/insert/delete to modify)", displayPath), nil 180 } 181 182 // Create parent directories 183 dir := filepath.Dir(absPath) 184 if err := os.MkdirAll(dir, 0755); err != nil { 185 return toolError("Failed to create directories: %v", err), nil 186 } 187 188 if h.deltaTracker != nil { 189 h.deltaTracker.RecordCreate(absPath) 190 } 191 192 if err := os.WriteFile(absPath, []byte(content), 0600); err != nil { 193 return toolError("Failed to create file: %v", err), nil 194 } 195 196 tagged := hashline.TagLines(content, 1) 197 taggedOutput := hashline.FormatTagged(tagged) 198 199 text := fmt.Sprintf("Created %s (%d lines):\n\n%s", displayPath, len(tagged), taggedOutput) 200 201 // Closed-loop LSP diagnostics for newly created file. 202 if h.lspManager != nil { 203 diags := h.lspManager.NotifyAndWait(ctx, absPath, 5*time.Second) 204 text += lsp.FormatDiagnostics(displayPath, diags) 205 } 206 if h.tsIndex != nil { 207 h.tsIndex.UpdateFile(absPath) 208 } 209 210 return &mcp.ToolResult{ 211 Content: []mcp.ContentBlock{{Type: "text", Text: text}}, 212 }, nil 213} 214 215// formatEditResponse builds the response text, using windowed output for large files. 216func formatEditResponse(displayPath string, tagged []hashline.TaggedLine, region editRegion) string { 217 total := len(tagged) 218 if total <= windowThreshold { 219 return fmt.Sprintf("Edited %s (%d lines):\n\n%s", displayPath, total, hashline.FormatTagged(tagged)) 220 } 221 222 // Clamp window bounds. 223 winStart := region.start - windowContext 224 if winStart < 1 { 225 winStart = 1 226 } 227 winEnd := region.end + windowContext 228 if winEnd > total { 229 winEnd = total 230 } 231 232 window := tagged[winStart-1 : winEnd] // tagged is 0-indexed, line nums are 1-indexed 233 return fmt.Sprintf("Edited %s (%d lines, showing %d–%d):\n\n%s", 234 displayPath, total, winStart, winEnd, hashline.FormatTagged(window)) 235} 236 237func applyReplace(lines []string, args EditArgs) (string, editRegion, error) { 238 start, err := hashline.ParseAnchor(args.Start) 239 if err != nil { 240 return "", editRegion{}, fmt.Errorf("replace start: %w", err) 241 } 242 end, err := hashline.ParseAnchor(args.End) 243 if err != nil { 244 return "", editRegion{}, fmt.Errorf("replace end: %w", err) 245 } 246 if err := hashline.ValidateRange(lines, &start, &end); err != nil { 247 return "", editRegion{}, fmt.Errorf("replace: %w", err) 248 } 249 250 inserted := strings.Split(args.Content, "\n") 251 newLines := make([]string, 0, len(lines)) 252 newLines = append(newLines, lines[:start.Num-1]...) 253 newLines = append(newLines, inserted...) 254 newLines = append(newLines, lines[end.Num:]...) 255 256 region := editRegion{ 257 start: start.Num, 258 end: start.Num + len(inserted) - 1, 259 } 260 return strings.Join(newLines, "\n"), region, nil 261} 262 263func applyInsert(lines []string, args EditArgs) (string, editRegion, error) { 264 after, err := hashline.ParseAnchor(args.After) 265 if err != nil { 266 return "", editRegion{}, fmt.Errorf("insert after: %w", err) 267 } 268 if err := after.Validate(lines); err != nil { 269 return "", editRegion{}, fmt.Errorf("insert: after anchor: %w", err) 270 } 271 272 inserted := strings.Split(args.Content, "\n") 273 newLines := make([]string, 0, len(lines)+len(inserted)) 274 newLines = append(newLines, lines[:after.Num]...) 275 newLines = append(newLines, inserted...) 276 newLines = append(newLines, lines[after.Num:]...) 277 278 region := editRegion{ 279 start: after.Num + 1, 280 end: after.Num + len(inserted), 281 } 282 return strings.Join(newLines, "\n"), region, nil 283} 284 285func applyDelete(lines []string, args EditArgs) (string, editRegion, error) { 286 start, err := hashline.ParseAnchor(args.Start) 287 if err != nil { 288 return "", editRegion{}, fmt.Errorf("delete start: %w", err) 289 } 290 end, err := hashline.ParseAnchor(args.End) 291 if err != nil { 292 return "", editRegion{}, fmt.Errorf("delete end: %w", err) 293 } 294 if err := hashline.ValidateRange(lines, &start, &end); err != nil { 295 return "", editRegion{}, fmt.Errorf("delete: %w", err) 296 } 297 298 newLines := make([]string, 0, len(lines)) 299 newLines = append(newLines, lines[:start.Num-1]...) 300 newLines = append(newLines, lines[end.Num:]...) 301 302 // The "region" is where the deletion happened — show surrounding context. 303 regionLine := start.Num - 1 304 if regionLine < 1 { 305 regionLine = 1 306 } 307 region := editRegion{ 308 start: regionLine, 309 end: regionLine, 310 } 311 return strings.Join(newLines, "\n"), region, nil 312}