Debian Codegraph @

gopls/internal/cmd/mcp_test.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 cmd_test
6
7 import (
8 "bufio"
9 "bytes"
10 "context"
11 "encoding/json"
12 "fmt"
13 "net"
14 "os"
15 "os/exec"
16 "path/filepath"
17 "runtime"
18 "slices"
19 "strconv"
20 "strings"
21 "testing"
22 "time"
23
24 "github.com/modelcontextprotocol/go-sdk/mcp"
25 goplsmcp "golang.org/x/tools/gopls/internal/mcp"
26 "golang.org/x/tools/gopls/internal/test/integration/fake"
27 "golang.org/x/tools/gopls/internal/vulncheck/vulntest"
28 "golang.org/x/tools/internal/testenv"
29 "golang.org/x/tools/txtar"
30 )
31
32 func TestMCPCommandStdio(t *testing.T) {
33 // Test that the headless MCP subcommand works, and recognizes file changes.
34 if !supportsFsnotify(runtime.GOOS) {
35 // See golang/go#74580
36 t.Skipf("skipping on %s; fsnotify is not supported", runtime.GOOS)
37 }
38 testenv.NeedsExec(t) // stdio transport uses execve(2)
39 tree := writeTree(t, `
40 -- go.mod --
41 module example.com
42 go 1.18
43
44 -- a.go --
45 package p
46
47 const A = 1
48
49 -- b.go --
50 package p
51
52 const B = 2
53 `)
54
55 goplsCmd := exec.Command(os.Args[0], "mcp")
56 goplsCmd.Env = append(os.Environ(), "ENTRYPOINT=goplsMain")
57 goplsCmd.Dir = tree
58 goplsCmd.Stderr = t.Output() // to debug https://go.dev/issue/77334
59
60 ctx := t.Context()
61 client := mcp.NewClient(&mcp.Implementation{Name: "client", Version: "v0.0.1"}, nil)
62 mcpSession, err := client.Connect(ctx, &mcp.CommandTransport{Command: goplsCmd}, nil)
63 if err != nil {
64 t.Fatal(err)
65 }
66 defer func() {
67 if err := mcpSession.Close(); err != nil {
68 // TODO(mkalil): Logf instead of Errof is a workaround for a
69 // potential mcp shutdown race:
70 // https://github.com/modelcontextprotocol/go-sdk/issues/855
71 t.Logf("closing MCP connection: %v", err)
72 }
73 }()
74 var (
75 tool = "go_diagnostics"
76 args = map[string]any{"files": []string{filepath.Join(tree, "a.go")}}
77 )
78 // On the first diagnostics call, there should be no diagnostics.
79 {
80 // Match on a substring of the expected output from the context tool.
81 res, err := mcpSession.CallTool(ctx, &mcp.CallToolParams{Name: tool, Arguments: args})
82 if err != nil {
83 t.Fatal(err)
84 }
85 got := resultText(t, res)
86 want := "No diagnostics"
87 if !strings.Contains(got, want) {
88 t.Errorf("CallTool(%s, %v) = %v, want containing %q", tool, args, got, want)
89 }
90 }
91 // Now, create a duplicate diagnostic in "b.go", and expect that the headless
92 // MCP server detects the file change. In order to guarantee that the change
93 // is detected, sleep long to ensure a different mtime.
94 time.Sleep(100 * time.Millisecond)
95 newContent := "package p\n\nconst A = 2\n"
96 if err := os.WriteFile(filepath.Join(tree, "b.go"), []byte(newContent), 0666); err != nil {
97 t.Fatal(err)
98 }
99 {
100 res, err := mcpSession.CallTool(ctx, &mcp.CallToolParams{Name: tool, Arguments: args})
101 if err != nil {
102 t.Fatal(err)
103 }
104 got := resultText(t, res)
105 want := "redeclared"
106 if !strings.Contains(got, want) {
107 t.Errorf("CallTool(%s, %v) = %v, want containing %q", tool, args, got, want)
108 }
109 }
110 }
111
112 func TestMCPCommandLogging(t *testing.T) {
113 // Test that logging flags for headless MCP subcommand work as intended.
114 if !supportsFsnotify(runtime.GOOS) {
115 // See golang/go#74580
116 t.Skipf("skipping on %s; fsnotify is not supported", runtime.GOOS)
117 }
118 testenv.NeedsExec(t) // stdio transport uses execve(2)
119
120 tests := []struct {
121 logFile string // also the subtest name
122 trace bool
123 want string
124 dontWant string
125 }{
126 // The log "initialize" appears at least twice in the RPC logs, first as
127 // an "initialize" request and then as a notification
128 // "notifications/initialized". Waiting for the initialized notification
129 // could result in a race, so instead verify we see the initialize
130 // request log.
131 {"notrace.log", false, "stdin", "initialize"},
132 {"trace.log", true, "initialize", ""},
133 }
134
135 dir := t.TempDir()
136 for _, test := range tests {
137 t.Run(test.logFile, func(t *testing.T) {
138 tree := writeTree(t, `
139 -- go.mod --
140 module example.com
141 go 1.18
142
143 -- a.go --
144 package p
145 `)
146
147 logFile := filepath.Join(dir, test.logFile)
148 args := []string{"mcp", "-logfile", logFile}
149 if test.trace {
150 args = append(args, "-rpc.trace")
151 }
152 goplsCmd := exec.Command(os.Args[0], args...)
153 goplsCmd.Env = append(os.Environ(), "ENTRYPOINT=goplsMain")
154 goplsCmd.Dir = tree
155 goplsCmd.Stderr = t.Output() // to debug https://go.dev/issue/77334
156
157 ctx := t.Context()
158 client := mcp.NewClient(&mcp.Implementation{Name: "client", Version: "v0.0.1"}, nil)
159 mcpSession, err := client.Connect(ctx, &mcp.CommandTransport{Command: goplsCmd}, nil)
160 if err != nil {
161 t.Fatal(err)
162 }
163 defer func() {
164 if err := mcpSession.Close(); err != nil {
165 // TODO(mkalil): Logf instead of Errof is a workaround for a
166 // potential mcp shutdown race:
167 // https://github.com/modelcontextprotocol/go-sdk/issues/855
168 t.Logf("closing MCP connection: %v", err)
169 }
170 }()
171 logs, err := os.ReadFile(logFile)
172 if err != nil {
173 t.Fatal(err)
174 }
175 if test.want != "" && !bytes.Contains(logs, []byte(test.want)) {
176 t.Errorf("logs do not contain expected %q", test.want)
177 }
178 if test.dontWant != "" && bytes.Contains(logs, []byte(test.dontWant)) {
179 t.Errorf("logs contain unexpected %q", test.dontWant)
180 }
181 if t.Failed() {
182 t.Logf("Logs:\n%s", string(logs))
183 }
184 })
185 }
186 }
187
188 func TestMCPCommandHTTP(t *testing.T) {
189 if !supportsFsnotify(runtime.GOOS) {
190 // See golang/go#74580
191 t.Skipf("skipping on %s; fsnotify is not supported", runtime.GOOS)
192 }
193 testenv.NeedsExec(t)
194 tree := writeTree(t, `
195 -- go.mod --
196 module example.com
197 go 1.18
198 -- a.go --
199 package a
200
201 import "example.com/b"
202
203 -- b/b.go --
204 package b
205
206 func MyFun() {}
207 `)
208 port := strconv.Itoa(getRandomPort())
209 addr := "localhost:" + port
210 goplsCmd := exec.Command(os.Args[0], "-v", "mcp", "-listen="+addr)
211 goplsCmd.Env = append(os.Environ(), "ENTRYPOINT=goplsMain")
212 goplsCmd.Dir = tree
213 goplsCmd.Stdout = os.Stderr
214
215 // Pipe stderr to a scanner, so that we can wait for the log message that
216 // tells us the server has started.
217 stderr, err := goplsCmd.StderrPipe()
218 if err != nil {
219 t.Fatal(err)
220 }
221 // forward stdout to test output
222 if err := goplsCmd.Start(); err != nil {
223 t.Fatalf("starting gopls: %v", err)
224 }
225 defer func() {
226 if err := goplsCmd.Process.Kill(); err != nil {
227 t.Fatalf("killing gopls: %v", err)
228 }
229 // Wait for the gopls process to exit before we return and the test framework
230 // attempts to clean up the temporary directory.
231 // We expect an error because we killed the process.
232 goplsCmd.Wait()
233 }()
234
235 // Wait for the MCP server to start listening. The referenced log occurs
236 // after the connection is opened via net.Listen and the HTTP handlers are
237 // set up.
238 ready := make(chan bool)
239 go func() {
240 // Copy from the pipe to stderr, keeping an eye out for the "mcp http
241 // server listening" string.
242 scan := bufio.NewScanner(stderr)
243 for scan.Scan() {
244 line := scan.Text()
245 if strings.Contains(line, "mcp http server listening") {
246 ready <- true
247 }
248 fmt.Fprintln(os.Stderr, line)
249 }
250 if err := scan.Err(); err != nil {
251 t.Logf("reading from pipe: %v", err)
252 }
253 }()
254
255 <-ready
256 client := mcp.NewClient(&mcp.Implementation{Name: "client", Version: "v0.0.1"}, nil)
257 ctx := t.Context()
258 mcpSession, err := client.Connect(ctx, &mcp.SSEClientTransport{Endpoint: "http://" + addr}, nil)
259 if err != nil {
260 t.Fatalf("connecting to server: %v", err)
261 }
262 defer func() {
263 if err := mcpSession.Close(); err != nil {
264 // TODO(mkalil): Logf instead of Errof is a workaround for a
265 // potential mcp shutdown race:
266 // https://github.com/modelcontextprotocol/go-sdk/issues/855
267 t.Logf("closing MCP connection: %v", err)
268 }
269 }()
270
271 var (
272 tool = "go_file_context"
273 args = map[string]any{"file": filepath.Join(tree, "a.go")}
274 )
275 res, err := mcpSession.CallTool(ctx, &mcp.CallToolParams{Name: tool, Arguments: args})
276 if err != nil {
277 t.Fatal(err)
278 }
279 got := resultText(t, res)
280 want := "example.com"
281 if !strings.Contains(got, want) {
282 t.Errorf("CallTool(%s, %v) = %+v, want containing %q", tool, args, got, want)
283 }
284 }
285
286 func TestMCPVulncheckCommand(t *testing.T) {
287 if !supportsFsnotify(runtime.GOOS) {
288 // See golang/go#74580
289 t.Skipf("skipping on %s; fsnotify is not supported", runtime.GOOS)
290 }
291 testenv.NeedsTool(t, "go")
292 const proxyData = `
293 -- example.com/[email protected]/go.mod --
294 module example.com/vulnmod
295 go 1.18
296 -- example.com/[email protected]/vuln.go --
297 package vulnmod
298
299 // VulnFunc is a vulnerable function.
300 func VulnFunc() {}
301 `
302 const vulnData = `
303 -- GO-TEST-0001.yaml --
304 modules:
305 - module: example.com/vulnmod
306 versions:
307 - introduced: "1.0.0"
308 packages:
309 - package: example.com/vulnmod
310 symbols:
311 - VulnFunc
312 `
313 proxyArchive := txtar.Parse([]byte(proxyData))
314 proxyFiles := make(map[string][]byte)
315 for _, f := range proxyArchive.Files {
316 proxyFiles[f.Name] = f.Data
317 }
318 goproxy, err := fake.WriteProxy(t.TempDir(), proxyFiles)
319 if err != nil {
320 t.Fatal(err)
321 }
322
323 db, err := vulntest.NewDatabase(context.Background(), []byte(vulnData))
324 if err != nil {
325 t.Fatal(err)
326 }
327 defer db.Clean()
328
329 tree := writeTree(t, `
330 -- go.mod --
331 module example.com/user
332 go 1.18
333 require example.com/vulnmod v1.0.0
334 -- main.go --
335 package main
336 import "example.com/vulnmod"
337 func main() {
338 vulnmod.VulnFunc()
339 }
340 `)
341
342 // Update go.sum before running gopls, to avoid load failures.
343 tidyCmd := exec.CommandContext(t.Context(), "go", "mod", "tidy")
344 tidyCmd.Dir = tree
345 tidyCmd.Env = append(os.Environ(), "GOPROXY="+goproxy, "GOSUMDB=off")
346 if output, err := tidyCmd.CombinedOutput(); err != nil {
347 t.Fatalf("go mod tidy failed: %v\n%s", err, output)
348 }
349
350 goplsCmd := exec.Command(os.Args[0], "mcp")
351 goplsCmd.Env = append(os.Environ(),
352 "ENTRYPOINT=goplsMain",
353 "GOPROXY="+goproxy,
354 "GOSUMDB=off",
355 "GOVULNDB="+db.URI(),
356 )
357 goplsCmd.Dir = tree
358 goplsCmd.Stderr = t.Output() // to debug https://go.dev/issue/77334
359
360 ctx := t.Context()
361 client := mcp.NewClient(&mcp.Implementation{Name: "client", Version: "v0.0.1"}, nil)
362 mcpSession, err := client.Connect(ctx, &mcp.CommandTransport{Command: goplsCmd}, nil)
363 if err != nil {
364 t.Fatal(err)
365 }
366 defer func() {
367 if err := mcpSession.Close(); err != nil {
368 // TODO(mkalil): Logf instead of Errof is a workaround for a
369 // potential mcp shutdown race:
370 // https://github.com/modelcontextprotocol/go-sdk/issues/855
371 t.Logf("closing MCP connection: %v", err)
372 }
373 }()
374
375 res, err := mcpSession.CallTool(ctx, &mcp.CallToolParams{Name: "go_vulncheck", Arguments: map[string]any{}})
376 if err != nil {
377 t.Fatal(err)
378 }
379 jsonBytes, err := json.Marshal(res.StructuredContent)
380 if err != nil {
381 t.Fatal(err)
382 }
383
384 var result goplsmcp.VulncheckResultOutput
385 if err := json.Unmarshal(jsonBytes, &result); err != nil {
386 t.Fatal(err)
387 }
388 if len(result.Findings) != 1 {
389 t.Errorf("expected 1 finding, got %d", len(result.Findings))
390 } else {
391 finding := result.Findings[0]
392 if finding.ID != "GO-TEST-0001" {
393 t.Errorf("expected ID 'GO-TEST-0001', got %q", finding.ID)
394 }
395 expectedPackages := []string{"Go standard library", "example.com/vulnmod"}
396 if !slices.Equal(finding.AffectedPackages, expectedPackages) {
397 t.Errorf("expected affected packages %v, got %v", expectedPackages, finding.AffectedPackages)
398 }
399 }
400
401 if result.Logs == "" {
402 t.Errorf("expected logs to be non-empty")
403 } else {
404 t.Logf("Logs:\n%s", result.Logs)
405 }
406 }
407
408 // resultText concatenates the textual content of the given result, reporting
409 // an error if any content values are non-textual.
410 func resultText(t *testing.T, res *mcp.CallToolResult) string {
411 t.Helper()
412
413 var buf bytes.Buffer
414 for _, content := range res.Content {
415 if c, ok := content.(*mcp.TextContent); ok {
416 fmt.Fprintf(&buf, "%s\n", c.Text)
417 } else {
418 t.Errorf("Not text content: %T", content)
419 }
420 }
421 return buf.String()
422 }
423
424 // getRandomPort returns the number of a random available port. Inherently racy:
425 // nothing stops another process from listening on it - but this should be fine
426 // for testing purposes.
427 func getRandomPort() int {
428 listener, err := net.Listen("tcp", "localhost:0")
429 if err != nil {
430 panic(err)
431 }
432 defer listener.Close()
433 return listener.Addr().(*net.TCPAddr).Port
434 }
435
436 // supportsFsnotify returns true if fsnotify supports the os.
437 func supportsFsnotify(os string) bool {
438 return os == "darwin" || os == "linux" || os == "windows"
439 }