| 1 |
|
| 2 |
|
| 3 |
|
| 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 |
|
| 30 |
var Instructions string |
| 31 |
|
| 32 |
|
| 33 |
type handler struct { |
| 34 |
session *cache.Session |
| 35 |
lspServer protocol.Server |
| 36 |
} |
| 37 |
|
| 38 |
|
| 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 |
|
| 46 |
|
| 47 |
|
| 48 |
|
| 49 |
|
| 50 |
|
| 51 |
|
| 52 |
|
| 53 |
|
| 54 |
|
| 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 |
|
| 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 |
|
| 80 |
go func() { |
| 81 |
<-ctx.Done() |
| 82 |
svr.Close() |
| 83 |
}() |
| 84 |
log.Printf("mcp http server listening") |
| 85 |
return svr.Serve(listener) |
| 86 |
} |
| 87 |
|
| 88 |
|
| 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 |
| 105 |
mcpHandlers = make(map[string]*mcp.SSEHandler) |
| 106 |
) |
| 107 |
mux := http.NewServeMux() |
| 108 |
|
| 109 |
|
| 110 |
|
| 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 |
|
| 136 |
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { |
| 137 |
mu.Lock() |
| 138 |
|
| 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 |
|
| 161 |
|
| 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 |
|
| 186 |
[]string{"go_file_metadata", |
| 187 |
|
| 188 |
|
| 189 |
|
| 190 |
"go_context", |
| 191 |
|
| 192 |
|
| 193 |
|
| 194 |
|
| 195 |
"go_file_diagnostics", |
| 196 |
|
| 197 |
|
| 198 |
|
| 199 |
"go_references", |
| 200 |
}...) |
| 201 |
var toolConfig map[string]bool |
| 202 |
|
| 203 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 230 |
|
| 231 |
|
| 232 |
|
| 233 |
|
| 234 |
|
| 235 |
|
| 236 |
|
| 237 |
|
| 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 { |
| 249 |
return |
| 250 |
} |
| 251 |
|
| 252 |
if session.InitializeParams().Capabilities.RootsV2 == nil { |
| 253 |
return |
| 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 |
|
| 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 |
|
| 382 |
|
| 383 |
|
| 384 |
|
| 385 |
|
| 386 |
|
| 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() |
| 407 |
|
| 408 |
|
| 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 |
|
| 418 |
|
| 419 |
|
| 420 |
|
| 421 |
|
| 422 |
|
| 423 |
|
| 424 |
|
| 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 |
| 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 |
|
| 449 |
events = append(events, protocol.FileEvent{URI: uri, Type: protocol.Deleted}) |
| 450 |
} |
| 451 |
case mtimeErr != nil: |
| 452 |
|
| 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 |
} |