| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
package mcp |
| 6 |
|
| 7 |
import ( |
| 8 |
"context" |
| 9 |
"fmt" |
| 10 |
"maps" |
| 11 |
"slices" |
| 12 |
"strings" |
| 13 |
|
| 14 |
"github.com/modelcontextprotocol/go-sdk/mcp" |
| 15 |
"golang.org/x/tools/gopls/internal/cache" |
| 16 |
"golang.org/x/tools/gopls/internal/cache/metadata" |
| 17 |
"golang.org/x/tools/gopls/internal/protocol" |
| 18 |
) |
| 19 |
|
| 20 |
type workspaceDiagnosticsParams struct { |
| 21 |
Files []string `json:"files,omitempty" jsonschema:"absolute paths to active files, if any"` |
| 22 |
} |
| 23 |
|
| 24 |
func (h *handler) workspaceDiagnosticsHandler(ctx context.Context, req *mcp.CallToolRequest, params workspaceDiagnosticsParams) (*mcp.CallToolResult, any, error) { |
| 25 |
countGoDiagnosticsMCP.Inc() |
| 26 |
var ( |
| 27 |
snapshot *cache.Snapshot |
| 28 |
release func() |
| 29 |
err error |
| 30 |
) |
| 31 |
if len(params.Files) > 0 { |
| 32 |
_, snapshot, release, err = h.fileOf(ctx, params.Files[0]) |
| 33 |
if err != nil { |
| 34 |
return nil, nil, err |
| 35 |
} |
| 36 |
} else { |
| 37 |
views := h.session.Views() |
| 38 |
if len(views) == 0 { |
| 39 |
return nil, nil, fmt.Errorf("No active builds.") |
| 40 |
} |
| 41 |
snapshot, release, err = views[0].Snapshot() |
| 42 |
if err != nil { |
| 43 |
return nil, nil, err |
| 44 |
} |
| 45 |
} |
| 46 |
defer release() |
| 47 |
|
| 48 |
pkgMap := snapshot.WorkspacePackages() |
| 49 |
var ids []metadata.PackageID |
| 50 |
for id := range pkgMap.All() { |
| 51 |
ids = append(ids, id) |
| 52 |
} |
| 53 |
slices.Sort(ids) |
| 54 |
|
| 55 |
diagnostics, err := snapshot.PackageDiagnostics(ctx, ids...) |
| 56 |
if err != nil { |
| 57 |
return nil, nil, fmt.Errorf("diagnostics failed: %v", err) |
| 58 |
} |
| 59 |
|
| 60 |
fixes := make(map[*cache.Diagnostic]*protocol.CodeAction) |
| 61 |
for _, file := range params.Files { |
| 62 |
uri := protocol.URIFromPath(file) |
| 63 |
|
| 64 |
fileDiagnostics, fileFixes, err := h.diagnoseFile(ctx, snapshot, uri) |
| 65 |
if err != nil { |
| 66 |
return nil, nil, fmt.Errorf("diagnostics failed: %v", err) |
| 67 |
} |
| 68 |
diagnostics[uri] = fileDiagnostics |
| 69 |
maps.Insert(fixes, maps.All(fileFixes)) |
| 70 |
} |
| 71 |
|
| 72 |
keys := slices.Sorted(maps.Keys(diagnostics)) |
| 73 |
var b strings.Builder |
| 74 |
for _, uri := range keys { |
| 75 |
diags := diagnostics[uri] |
| 76 |
if len(diags) > 0 { |
| 77 |
fmt.Fprintf(&b, "File `%s` has the following diagnostics:\n", uri.Path()) |
| 78 |
if err := summarizeDiagnostics(ctx, snapshot, &b, diags, fixes); err != nil { |
| 79 |
return nil, nil, err |
| 80 |
} |
| 81 |
fmt.Fprintln(&b) |
| 82 |
} |
| 83 |
} |
| 84 |
|
| 85 |
if b.Len() == 0 { |
| 86 |
return textResult("No diagnostics."), nil, nil |
| 87 |
} |
| 88 |
|
| 89 |
return textResult(b.String()), nil, nil |
| 90 |
} |