| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
package mcp |
| 6 |
|
| 7 |
import ( |
| 8 |
"context" |
| 9 |
"fmt" |
| 10 |
"strings" |
| 11 |
|
| 12 |
"github.com/modelcontextprotocol/go-sdk/mcp" |
| 13 |
"golang.org/x/tools/gopls/internal/cache" |
| 14 |
"golang.org/x/tools/gopls/internal/file" |
| 15 |
"golang.org/x/tools/gopls/internal/golang" |
| 16 |
"golang.org/x/tools/gopls/internal/protocol" |
| 17 |
) |
| 18 |
|
| 19 |
type renameSymbolParams struct { |
| 20 |
File string `json:"file" jsonschema:"the absolute path to the file containing the symbol"` |
| 21 |
Symbol string `json:"symbol" jsonschema:"the symbol or qualified symbol"` |
| 22 |
NewName string `json:"new_name" jsonschema:"the new name for the symbol"` |
| 23 |
} |
| 24 |
|
| 25 |
func (h *handler) renameSymbolHandler(ctx context.Context, req *mcp.CallToolRequest, params renameSymbolParams) (*mcp.CallToolResult, any, error) { |
| 26 |
countGoRenameSymbolMCP.Inc() |
| 27 |
fh, snapshot, release, err := h.fileOf(ctx, params.File) |
| 28 |
if err != nil { |
| 29 |
return nil, nil, err |
| 30 |
} |
| 31 |
defer release() |
| 32 |
|
| 33 |
if snapshot.FileKind(fh) != file.Go { |
| 34 |
return nil, nil, fmt.Errorf("can't rename symbols in non-Go files") |
| 35 |
} |
| 36 |
loc, err := symbolLocation(ctx, snapshot, fh.URI(), params.Symbol) |
| 37 |
if err != nil { |
| 38 |
return nil, nil, err |
| 39 |
} |
| 40 |
changes, err := golang.Rename(ctx, snapshot, fh, loc.Range, params.NewName) |
| 41 |
if err != nil { |
| 42 |
return nil, nil, err |
| 43 |
} |
| 44 |
var builder strings.Builder |
| 45 |
if err := formatRenameChanges(ctx, snapshot, &builder, changes); err != nil { |
| 46 |
return nil, nil, err |
| 47 |
} |
| 48 |
return textResult(builder.String()), nil, nil |
| 49 |
} |
| 50 |
|
| 51 |
|
| 52 |
func formatRenameChanges(ctx context.Context, snapshot *cache.Snapshot, w *strings.Builder, changes []protocol.DocumentChange) error { |
| 53 |
w.WriteString("The following changes are necessary to rename the symbol:\n") |
| 54 |
if err := writeUnifiedDiff(ctx, snapshot, w, changes); err != nil { |
| 55 |
return err |
| 56 |
} |
| 57 |
w.WriteString("\n") |
| 58 |
return nil |
| 59 |
} |