Debian Codegraph @

gopls/internal/cmd/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 cmd
6
7 import (
8 "context"
9 "flag"
10 "fmt"
11 "io"
12 "log"
13 "os"
14 "sync"
15
16 "github.com/modelcontextprotocol/go-sdk/mcp"
17 "golang.org/x/tools/gopls/internal/cache"
18 "golang.org/x/tools/gopls/internal/filewatcher"
19 internalmcp "golang.org/x/tools/gopls/internal/mcp"
20 "golang.org/x/tools/gopls/internal/protocol"
21 )
22
23 type headlessMCP struct {
24 app *Application
25
26 Address string `flag:"listen" help:"the address on which to run the mcp server"`
27 Logfile string `flag:"logfile" help:"filename to log to; if unset, logs to stderr"`
28 RPCTrace bool `flag:"rpc.trace" help:"print MCP rpc traces; cannot be used with -listen"`
29 Instructions bool `flag:"instructions" help:"if set, print gopls' MCP instructions and exit"`
30 }
31
32 func (m *headlessMCP) Name() string { return "mcp" }
33 func (m *headlessMCP) Parent() string { return m.app.Name() }
34 func (m *headlessMCP) Usage() string { return "[mcp-flags]" }
35 func (m *headlessMCP) ShortHelp() string { return "start the gopls MCP server in headless mode" }
36
37 func (m *headlessMCP) DetailedHelp(f *flag.FlagSet) {
38 fmt.Fprint(f.Output(), `
39 Starts the gopls MCP server in headless mode, without needing an LSP client.
40 Starts the server over stdio or sse with http, depending on whether the listen flag is provided.
41
42 Examples:
43 $ gopls mcp -listen=localhost:3000
44 $ gopls mcp //start over stdio
45 `)
46 printFlagDefaults(f)
47 }
48
49 func (m *headlessMCP) Run(ctx context.Context, args ...string) error {
50 if m.Instructions {
51 fmt.Println(internalmcp.Instructions)
52 return nil
53 }
54 if m.Address != "" && m.RPCTrace {
55 // There's currently no way to plumb logging instrumentation into the SSE
56 // transport that is created on connections to the HTTP handler, so we must
57 // disallow the -rpc.trace flag when using -listen.
58 return fmt.Errorf("-listen is incompatible with -rpc.trace")
59 }
60 if m.Logfile != "" {
61 f, err := os.Create(m.Logfile)
62 if err != nil {
63 return fmt.Errorf("opening logfile: %v", err)
64 }
65 log.SetOutput(f)
66 defer f.Close()
67 }
68
69 // Start a new in-process gopls session and create a fake client
70 // to connect to it.
71 cli, sess, err := m.app.connect(ctx)
72 if err != nil {
73 return err
74 }
75 defer cli.terminate(ctx)
76
77 var (
78 queueMu sync.Mutex
79 queue []protocol.FileEvent
80 nonempty = make(chan struct{}) // receivable when len(queue) > 0
81 stop = make(chan struct{}) // closed when Run returns
82 )
83 defer close(stop)
84
85 // This goroutine forwards file change events to the LSP server.
86 go func() {
87 for {
88 select {
89 case <-stop:
90 return
91 case <-nonempty:
92 queueMu.Lock()
93 q := queue
94 queue = nil
95 queueMu.Unlock()
96
97 if len(q) > 0 {
98 if err := cli.server.DidChangeWatchedFiles(ctx, &protocol.DidChangeWatchedFilesParams{
99 Changes: q,
100 }); err != nil {
101 log.Printf("failed to notify changed files: %v", err)
102 }
103 }
104
105 }
106 }
107 }()
108
109 errHandler := func(err error) {
110 log.Printf("watch error: %v", err)
111 }
112
113 // TODO(hxjiang): enable file watcher based on the gopls setting.
114 w, err := filewatcher.New("fsnotify", nil, func(events []protocol.FileEvent) {
115 if len(events) == 0 {
116 return
117 }
118
119 // Since there is no promise [protocol.Server.DidChangeWatchedFiles]
120 // will return immediately, we should buffer the captured events and
121 // sent them whenever available in a separate go routine.
122 queueMu.Lock()
123 queue = append(queue, events...)
124 queueMu.Unlock()
125
126 select {
127 case nonempty <- struct{}{}:
128 default:
129 }
130 }, errHandler)
131 if err != nil {
132 return err
133 }
134 defer w.Close()
135
136 // TODO(hxjiang): in LSP's use case, the file watcher should watch for LSP
137 // initial param workspace root.
138
139 // TODO(hxjiang): refactor the queue pattern into a helper function to avoid
140 // repetition.
141 var (
142 watchStop = make(chan struct{}) // closed to broadcast "stop" event
143 watchQueueNonempty = make(chan struct{}) // each send indicates "nonempty"
144 watchQueueMu sync.Mutex
145 watchQueue []string
146 )
147 // The watchStop event occurs when this function returns,
148 // for any reason (cancellation or completion).
149 defer close(watchStop)
150
151 // TODO(hxjiang): memorize the roots and stop watching when the previously
152 // watched roots are removed.
153 // TODO(hxjiang): implement [filewatcher.Watcher]'s method StopWatchDir.
154
155 // watchRoots is the callback triggered when the MCP client reports workspace
156 // roots. We do not call w.WatchDir directly from this callback, but spawn a
157 // goroutine for it because WatchDir performs OS-level filesystem operations
158 // which can be slow. Blocking this callback would block the MCP server's
159 // JSON-RPC message loop and stall the entireconnection.
160 watchRoots := func(res *mcp.ListRootsResult, err error) {
161 if err != nil {
162 errHandler(err)
163 return
164 }
165 watchQueueMu.Lock()
166 for _, r := range res.Roots {
167 uri, err := protocol.ParseDocumentURI(r.URI)
168 if err != nil {
169 // Discard invalid URIs.
170 // Unlike LSP, MCP does not check URI validity during unmarshaling.
171 // Fixes go.dev/issue/74652, crash of May 18 2026.
172 log.Printf("mcp.ListRootsResult[*].Roots[*].URI contains invalid URI: %v", err)
173 continue
174 }
175 watchQueue = append(watchQueue, uri.Path())
176 }
177 watchQueueMu.Unlock()
178
179 select {
180 case watchQueueNonempty <- struct{}{}:
181 default:
182 }
183 }
184 go func() {
185 for {
186 select {
187 case <-watchStop:
188 return
189 case <-watchQueueNonempty:
190 watchQueueMu.Lock()
191 queue := watchQueue
192 watchQueue = nil
193 watchQueueMu.Unlock()
194
195 for _, dir := range queue {
196 if err := w.WatchDir(dir); err != nil {
197 errHandler(err)
198 }
199 }
200 }
201 }
202 }()
203
204 if m.Address != "" {
205 countHeadlessMCPSSE.Inc()
206 return internalmcp.Serve(ctx, m.Address, &staticSessions{sess, cli.server}, false, watchRoots)
207 } else {
208 countHeadlessMCPStdIO.Inc()
209 var rpcLog io.Writer
210 if m.RPCTrace {
211 rpcLog = log.Writer() // possibly redirected by -logfile above
212 }
213 log.Printf("Listening for MCP messages on stdin...")
214 return internalmcp.StartStdIO(ctx, sess, cli.server, rpcLog, watchRoots)
215 }
216 }
217
218 // staticSessions implements the [internalmcp.Sessions] interface for a single gopls
219 // session.
220 type staticSessions struct {
221 session *cache.Session
222 server protocol.Server
223 }
224
225 func (s *staticSessions) SetSessionExitFunc(func(string)) {}
226
227 func (s *staticSessions) FirstSession() (*cache.Session, protocol.Server) {
228 return s.session, s.server
229 }
230
231 func (s *staticSessions) Session(id string) (*cache.Session, protocol.Server) {
232 if s.session.ID() == id {
233 return s.session, s.server
234 }
235 return nil, nil
236 }