Debian Codegraph @

gopls/internal/mcp/vulncheck.go

raw symbols SCIP
1 // Copyright 2025 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package mcp
6
7 import (
8 "bytes"
9 "context"
10 "fmt"
11 "maps"
12 "slices"
13 "sort"
14
15 "github.com/modelcontextprotocol/go-sdk/mcp"
16 "golang.org/x/tools/gopls/internal/vulncheck/scan"
17 )
18
19 type vulncheckParams struct {
20 Dir string `json:"dir,omitempty" jsonschema:"directory to run the vulnerability check within"`
21 Pattern string `json:"pattern,omitempty" jsonschema:"package pattern to check"`
22 }
23
24 type GroupedVulnFinding struct {
25 ID string `json:"id"`
26 Details string `json:"details"`
27 AffectedPackages []string `json:"affectedPackages"`
28 }
29
30 type VulncheckResultOutput struct {
31 Findings []GroupedVulnFinding `json:"findings,omitempty"`
32 Logs string `json:"logs,omitempty"`
33 }
34
35 func (h *handler) vulncheckHandler(ctx context.Context, req *mcp.CallToolRequest, params *vulncheckParams) (*mcp.CallToolResult, *VulncheckResultOutput, error) {
36 countGoVulncheckMCP.Inc()
37 snapshot, release, err := h.snapshot()
38 if err != nil {
39 return nil, nil, err
40 }
41 defer release()
42
43 dir := params.Dir
44 if dir == "" && len(h.session.Views()) > 0 {
45 dir = h.session.Views()[0].Root().Path()
46 }
47
48 pattern := params.Pattern
49 if pattern == "" {
50 pattern = "./..."
51 }
52
53 var logBuf bytes.Buffer
54 result, err := scan.RunGovulncheck(ctx, pattern, snapshot, dir, &logBuf)
55 if err != nil {
56 return nil, nil, fmt.Errorf("running govulncheck failed: %v\nLogs:\n%s", err, logBuf.String())
57 }
58
59 groupedPkgs := make(map[string]map[string]struct{})
60 for _, finding := range result.Findings {
61 if osv := result.Entries[finding.OSV]; osv != nil {
62 if _, ok := groupedPkgs[osv.ID]; !ok {
63 groupedPkgs[osv.ID] = make(map[string]struct{})
64 }
65 pkg := finding.Trace[0].Package
66 if pkg == "" {
67 pkg = "Go standard library"
68 }
69 groupedPkgs[osv.ID][pkg] = struct{}{}
70 }
71 }
72
73 var output VulncheckResultOutput
74 if len(groupedPkgs) > 0 {
75 output.Findings = make([]GroupedVulnFinding, 0, len(groupedPkgs))
76 for id, pkgsSet := range groupedPkgs {
77 pkgs := slices.Sorted(maps.Keys(pkgsSet))
78
79 output.Findings = append(output.Findings, GroupedVulnFinding{
80 ID: id,
81 Details: result.Entries[id].Details,
82 AffectedPackages: pkgs,
83 })
84 }
85 sort.Slice(output.Findings, func(i, j int) bool {
86 return output.Findings[i].ID < output.Findings[j].ID
87 })
88 }
89
90 if logBuf.Len() > 0 {
91 output.Logs = logBuf.String()
92 }
93
94 var summary bytes.Buffer
95 fmt.Fprintf(&summary, "Vulnerability check for pattern %q complete. Found %d vulnerabilities.", pattern, len(output.Findings))
96 if output.Logs != "" {
97 fmt.Fprintf(&summary, "\nLogs are available in the structured output.")
98 }
99
100 return nil, &output, nil
101 }