Debian Codegraph @

gopls/internal/mcp/mcp.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 "context"
9 _ "embed"
10 "fmt"
11 "io"
12 "log"
13 "net"
14 "net/http"
15 "os"
16 "strings"
17 "sync"
18
19 "github.com/google/jsonschema-go/jsonschema"
20 "github.com/modelcontextprotocol/go-sdk/mcp"
21 "golang.org/x/tools/gopls/internal/cache"
22 "golang.org/x/tools/gopls/internal/cache/metadata"
23 "golang.org/x/tools/gopls/internal/file"
24 "golang.org/x/tools/gopls/internal/protocol"
25 "golang.org/x/tools/gopls/internal/settings"
26 "golang.org/x/tools/gopls/internal/util/moremaps"
27 )
28
29 //go:embed instructions.md
30 var Instructions string
31
32 // A handler implements various MCP tools for an LSP session.
33 type handler struct {
34 session *cache.Session
35 lspServer protocol.Server
36 }
37
38 // Sessions is the interface used to access gopls sessions.
39 type Sessions interface {
40 Session(id string) (*cache.Session, protocol.Server)
41 FirstSession() (*cache.Session, protocol.Server)
42 SetSessionExitFunc(func(string))
43 }
44
45 // Serve starts an MCP server serving at the input address.
46 //
47 // The server receives LSP session events on the specified channel, which the
48 // caller is responsible for closing. The server runs until the context is
49 // canceled.
50 //
51 // The rootsHandler callback is invoked immediately after initialization and
52 // subsequently whenever the MCP client signals a change to the workspace roots.
53 // It is passed the list roots result returned by the MCP client, or an error
54 // if the roots could not be retrieved. rootsHandler may be called concurrently.
55 func Serve(ctx context.Context, address string, sessions Sessions, isDaemon bool, rootsHandler func(*mcp.ListRootsResult, error)) error {
56 if strings.HasPrefix(address, ":") {
57 return fmt.Errorf("address %s implicitly binds all network interfaces; please use an explicit host such as 0.0.0.0 (all interfaces) or localhost (safer)", address)
58 }
59 log.Printf("Gopls MCP server: starting up on http")
60 listener, err := net.Listen("tcp", address)
61 if err != nil {
62 return err
63 }
64 defer listener.Close()
65
66 // TODO(hxjiang): expose the MCP server address to the LSP client.
67 if isDaemon {
68 log.Printf("Gopls MCP daemon: listening on address %s...", listener.Addr())
69 }
70 defer log.Printf("Gopls MCP server: exiting")
71
72 svr := http.Server{
73 Handler: HTTPHandler(sessions, isDaemon, rootsHandler),
74 BaseContext: func(net.Listener) context.Context {
75 return ctx
76 },
77 }
78
79 // Run the server until cancellation.
80 go func() {
81 <-ctx.Done()
82 svr.Close() // ignore error
83 }()
84 log.Printf("mcp http server listening")
85 return svr.Serve(listener)
86 }
87
88 // StartStdIO starts an MCP server over stdio.
89 func StartStdIO(ctx context.Context, session *cache.Session, server protocol.Server, rpcLog io.Writer, rootsHandler func(*mcp.ListRootsResult, error)) error {
90 s := NewServer(session, server, rootsHandler)
91 if rpcLog != nil {
92 return s.Run(ctx, &mcp.LoggingTransport{
93 Transport: &mcp.StdioTransport{},
94 Writer: rpcLog,
95 })
96 } else {
97 return s.Run(ctx, &mcp.StdioTransport{})
98 }
99
100 }
101
102 func HTTPHandler(sessions Sessions, isDaemon bool, rootsHandler func(*mcp.ListRootsResult, error)) http.Handler {
103 var (
104 mu sync.Mutex // lock for mcpHandlers.
105 mcpHandlers = make(map[string]*mcp.SSEHandler) // map from lsp session ids to MCP sse handlers.
106 )
107 mux := http.NewServeMux()
108
109 // In daemon mode, gopls serves mcp server at ADDRESS/sessions/$SESSIONID.
110 // Otherwise, gopls serves mcp server at ADDRESS.
111 if isDaemon {
112 mux.HandleFunc("/sessions/{id}", func(w http.ResponseWriter, r *http.Request) {
113 sessionID := r.PathValue("id")
114
115 mu.Lock()
116 handler, ok := mcpHandlers[sessionID]
117 if !ok {
118 if s, svr := sessions.Session(sessionID); s != nil {
119 handler = mcp.NewSSEHandler(func(request *http.Request) *mcp.Server {
120 return NewServer(s, svr, rootsHandler)
121 }, nil)
122 mcpHandlers[sessionID] = handler
123 }
124 }
125 mu.Unlock()
126
127 if handler == nil {
128 http.Error(w, fmt.Sprintf("session %s not established", sessionID), http.StatusNotFound)
129 return
130 }
131
132 handler.ServeHTTP(w, r)
133 })
134 } else {
135 // TODO(hxjiang): should gopls serve only at a specific path?
136 mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
137 mu.Lock()
138 // When not in daemon mode, gopls has at most one LSP session.
139 _, handler, ok := moremaps.Arbitrary(mcpHandlers)
140 if !ok {
141 s, svr := sessions.FirstSession()
142 handler = mcp.NewSSEHandler(func(request *http.Request) *mcp.Server {
143 return NewServer(s, svr, rootsHandler)
144 }, nil)
145 mcpHandlers[s.ID()] = handler
146 }
147 mu.Unlock()
148
149 if handler == nil {
150 http.Error(w, "session not established", http.StatusNotFound)
151 return
152 }
153
154 handler.ServeHTTP(w, r)
155 })
156 }
157 sessions.SetSessionExitFunc(func(sessionID string) {
158 mu.Lock()
159 defer mu.Unlock()
160 // TODO(rfindley): add a way to close SSE handlers (and therefore
161 // close their transports). Otherwise, we leak JSON-RPC goroutines.
162 delete(mcpHandlers, sessionID)
163 })
164 return mux
165 }
166
167 func NewServer(session *cache.Session, lspServer protocol.Server, rootsHandler func(*mcp.ListRootsResult, error)) *mcp.Server {
168 h := handler{
169 session: session,
170 lspServer: lspServer,
171 }
172 opts := &mcp.ServerOptions{}
173 mcpServer := mcp.NewServer(&mcp.Implementation{Name: "gopls", Version: "v1.0.0"}, opts)
174
175 defaultTools := []string{
176 "go_workspace",
177 "go_package_api",
178 "go_diagnostics",
179 "go_rename_symbol",
180 "go_symbol_references",
181 "go_search",
182 "go_file_context",
183 "go_vulncheck"}
184 disabledTools := append(defaultTools,
185 // The fileMetadata tool is redundant with fileContext.
186 []string{"go_file_metadata",
187 // The context tool returns context for all imports, which can consume a
188 // lot of tokens. Conservatively, rely on the model selecting the imports
189 // to summarize using the outline tool.
190 "go_context",
191 // The fileDiagnosticsTool only returns diagnostics for the current file,
192 // but often changes will cause breakages in other tools. The
193 // workspaceDiagnosticsTool always returns breakages, and supports running
194 // deeper diagnostics in selected files.
195 "go_file_diagnostics",
196 // The references tool requires a location, which models tend to get wrong.
197 // The symbolic variant seems to be easier to get right, albeit less
198 // powerful.
199 "go_references",
200 }...)
201 var toolConfig map[string]bool // non-default settings
202 // For testing, poke through to the gopls server to access its options,
203 // and enable some of the disabled tools.
204 if hasOpts, ok := lspServer.(interface{ Options() *settings.Options }); ok {
205 toolConfig = hasOpts.Options().MCPTools
206 }
207 var tools []string
208 for _, tool := range defaultTools {
209 if enabled, ok := toolConfig[tool]; !ok || enabled {
210 tools = append(tools, tool)
211 }
212 }
213 // Disabled tools must be explicitly enabled.
214 for _, tool := range disabledTools {
215 if toolConfig[tool] {
216 tools = append(tools, tool)
217 }
218 }
219 for _, tool := range tools {
220 addToolByName(mcpServer, h, tool)
221 }
222
223 // Subscribe to the roots change.
224 if rootsHandler != nil {
225 mcpServer.AddReceivingMiddleware(func(next mcp.MethodHandler) mcp.MethodHandler {
226 return func(ctx context.Context, method string, req mcp.Request) (mcp.Result, error) {
227 result, err := next(ctx, method, req)
228
229 // Read roots list after initialized once and every time roots
230 // list changes and pass them to handler.
231 //
232 // See MCP spec:
233 //
234 // The server SHOULD NOT send requests other than pings
235 // and logging before receiving the initialized notification.
236 //
237 // https://modelcontextprotocol.info/specification/2024-11-05/basic/lifecycle/#initialization
238 if method == "notifications/initialized" || method == "notifications/roots/list_changed" {
239 go func() {
240 var session *mcp.ServerSession
241 for s := range mcpServer.Sessions() {
242 if s.ID() == req.GetSession().ID() {
243 session = s
244 break
245 }
246 }
247
248 if session == nil { // session terminated.
249 return
250 }
251
252 if session.InitializeParams().Capabilities.RootsV2 == nil {
253 return // client does not support roots
254 }
255
256 roots, err := session.ListRoots(context.Background(), &mcp.ListRootsParams{})
257 rootsHandler(roots, err)
258 }()
259 }
260
261 return result, err
262 }
263 })
264 }
265
266 return mcpServer
267 }
268
269 func addToolByName(mcpServer *mcp.Server, h handler, name string) {
270 switch name {
271 case "go_context":
272 mcp.AddTool(mcpServer, &mcp.Tool{
273 Name: "go_context",
274 Description: "Provide context for a region within a Go file",
275 }, h.contextHandler)
276 case "go_diagnostics":
277 mcp.AddTool(mcpServer, &mcp.Tool{
278 Name: "go_diagnostics",
279 Description: `Provides Go workspace diagnostics.
280
281 Checks for parse and build errors across the entire Go workspace. If provided,
282 "files" holds absolute paths for active files, on which additional linting is
283 performed.
284 `,
285 }, h.workspaceDiagnosticsHandler)
286 case "go_file_context":
287 mcp.AddTool(mcpServer, &mcp.Tool{
288 Name: "go_file_context",
289 Description: "Summarizes a file's cross-file dependencies",
290 }, h.fileContextHandler)
291 case "go_file_diagnostics":
292 mcp.AddTool(mcpServer, &mcp.Tool{
293 Name: "go_file_diagnostics",
294 Description: "Provides diagnostics for a Go file",
295 }, h.fileDiagnosticsHandler)
296 case "go_file_metadata":
297 mcp.AddTool(mcpServer, &mcp.Tool{
298 Name: "go_file_metadata",
299 Description: "Provides metadata about the Go package containing the file",
300 }, h.fileMetadataHandler)
301 case "go_package_api":
302 mcp.AddTool(mcpServer, &mcp.Tool{
303 Name: "go_package_api",
304 Description: "Provides a summary of a Go package API",
305 }, h.outlineHandler)
306 case "go_references":
307 mcp.AddTool(mcpServer, &mcp.Tool{
308 Name: "go_references",
309 Description: "Provide the locations of references to a given object",
310 }, h.referencesHandler)
311 case "go_rename_symbol":
312 mcp.AddTool(mcpServer, &mcp.Tool{
313 Name: "go_rename_symbol",
314 Description: `Renames a symbol in the Go workspace
315
316 For example, given arguments {"file": "/path/to/foo.go", "symbol": "Foo", "new_name": "Bar"},
317 go_rename_symbol returns the edits necessary to rename the symbol "Foo" (located in the file foo.go) to
318 "Bar" across the Go workspace.`,
319 }, h.renameSymbolHandler)
320 case "go_search":
321 mcp.AddTool(mcpServer, &mcp.Tool{
322 Name: "go_search",
323 Description: `Search for symbols in the Go workspace.
324
325 Search for symbols using case-insensitive fuzzy search, which may match all or
326 part of the fully qualified symbol name. For example, the query 'foo' matches
327 Go symbols 'Foo', 'fooBar', 'futils.Oboe', 'github.com/foo/bar.Baz'.
328
329 Results are limited to 100 symbols.
330 `,
331 }, h.searchHandler)
332 case "go_symbol_references":
333 mcp.AddTool(mcpServer, &mcp.Tool{
334 Name: "go_symbol_references",
335 Description: `Provides the locations of references to a (possibly qualified)
336 package-level Go symbol referenced from the current file.
337
338 For example, given arguments {"file": "/path/to/foo.go", "name": "Foo"},
339 go_symbol_references returns references to the symbol "Foo" declared
340 in the current package.
341
342 Similarly, given arguments {"file": "/path/to/foo.go", "name": "lib.Bar"},
343 go_symbol_references returns references to the symbol "Bar" in the imported lib
344 package.
345
346 Finally, symbol references supporting querying fields and methods: symbol
347 "T.M" selects the "M" field or method of the "T" type (or value), and "lib.T.M"
348 does the same for a symbol in the imported package "lib".
349 `,
350 }, h.symbolReferencesHandler)
351 case "go_workspace":
352 mcp.AddTool(mcpServer, &mcp.Tool{
353 Name: "go_workspace",
354 Description: "Summarize the Go programming language workspace",
355 InputSchema: &jsonschema.Schema{
356 Type: "object",
357 Properties: map[string]*jsonschema.Schema{},
358 },
359 }, h.workspaceHandler)
360 case "go_vulncheck":
361 mcp.AddTool(mcpServer, &mcp.Tool{
362 Name: "go_vulncheck",
363 Description: `Runs a vulnerability check on the Go workspace.
364
365 The check is performed on a given package pattern within a specified directory.
366 If no directory is provided, it defaults to the workspace root.
367 If no pattern is provided, it defaults to "./...".`,
368 }, h.vulncheckHandler)
369 }
370 }
371
372 // snapshot returns the best default snapshot to use for workspace queries.
373 func (h *handler) snapshot() (*cache.Snapshot, func(), error) {
374 views := h.session.Views()
375 if len(views) == 0 {
376 return nil, nil, fmt.Errorf("No active builds.")
377 }
378 return views[0].Snapshot()
379 }
380
381 // fileOf is like [cache.Session.FileOf], but does a sanity check for file
382 // changes. Currently, it checks for modified files in the transitive closure
383 // of the file's narrowest package.
384 //
385 // This helps avoid stale packages, but is not a substitute for real file
386 // watching, as it misses things like files being added to a package.
387 func (h *handler) fileOf(ctx context.Context, file string) (file.Handle, *cache.Snapshot, func(), error) {
388 uri := protocol.URIFromPath(file)
389 fh, snapshot, release, err := h.session.FileOf(ctx, uri)
390 if err != nil {
391 return nil, nil, nil, err
392 }
393 md, err := snapshot.NarrowestMetadataForFile(ctx, uri)
394 if err != nil {
395 release()
396 return nil, nil, nil, err
397 }
398 fileEvents, err := checkForFileChanges(ctx, snapshot, md.ID)
399 if err != nil {
400 release()
401 return nil, nil, nil, err
402 }
403 if len(fileEvents) == 0 {
404 return fh, snapshot, release, nil
405 }
406 release() // snapshot is not latest
407
408 // We detect changed files: process them before getting the snapshot.
409 if err := h.lspServer.DidChangeWatchedFiles(ctx, &protocol.DidChangeWatchedFilesParams{
410 Changes: fileEvents,
411 }); err != nil {
412 return nil, nil, nil, err
413 }
414 return h.session.FileOf(ctx, uri)
415 }
416
417 // checkForFileChanges checks for file changes in the transitive closure of
418 // the given package, by checking file modification time. Since it does not
419 // actually read file contents, it may miss changes that occur within the mtime
420 // resolution of the current file system (on some operating systems, this may
421 // be as much as a second).
422 //
423 // It also doesn't catch package changes that occur due to added files or
424 // changes to the go.mod file.
425 func checkForFileChanges(ctx context.Context, snapshot *cache.Snapshot, id metadata.PackageID) ([]protocol.FileEvent, error) {
426 var events []protocol.FileEvent
427
428 seen := make(map[metadata.PackageID]struct{})
429 var checkPkg func(id metadata.PackageID) error
430 checkPkg = func(id metadata.PackageID) error {
431 if _, ok := seen[id]; ok {
432 return nil
433 }
434 seen[id] = struct{}{}
435
436 mp := snapshot.Metadata(id)
437 for _, uri := range mp.CompiledGoFiles {
438 fh, err := snapshot.ReadFile(ctx, uri)
439 if err != nil {
440 return err // context cancelled
441 }
442
443 mtime, mtimeErr := fh.ModTime()
444 fi, err := os.Stat(uri.Path())
445 switch {
446 case err != nil:
447 if mtimeErr == nil {
448 // file existed, and doesn't anymore, so the file was deleted
449 events = append(events, protocol.FileEvent{URI: uri, Type: protocol.Deleted})
450 }
451 case mtimeErr != nil:
452 // err == nil (from above), so the file was created
453 events = append(events, protocol.FileEvent{URI: uri, Type: protocol.Created})
454 case !mtime.IsZero() && fi.ModTime().After(mtime):
455 events = append(events, protocol.FileEvent{URI: uri, Type: protocol.Changed})
456 }
457 }
458 for _, depID := range mp.DepsByPkgPath {
459 if err := checkPkg(depID); err != nil {
460 return err
461 }
462 }
463 return nil
464 }
465 return events, checkPkg(id)
466 }
467
468 func textResult(text string) *mcp.CallToolResult {
469 return &mcp.CallToolResult{
470 Content: []mcp.Content{&mcp.TextContent{Text: text}},
471 }
472 }