Debian Codegraph @

gopls/internal/mcp/references.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 package mcp
5
6 import (
7 "context"
8 "fmt"
9 "path/filepath"
10 "strings"
11 "unicode"
12
13 "github.com/modelcontextprotocol/go-sdk/mcp"
14 "golang.org/x/tools/gopls/internal/cache"
15 "golang.org/x/tools/gopls/internal/golang"
16 "golang.org/x/tools/gopls/internal/protocol"
17 )
18
19 type findReferencesParams struct {
20 Location protocol.Location `json:"location"`
21 }
22
23 func (h *handler) referencesHandler(ctx context.Context, req *mcp.CallToolRequest, params findReferencesParams) (*mcp.CallToolResult, any, error) {
24 countGoReferencesMCP.Inc()
25 fh, snapshot, release, err := h.session.FileOf(ctx, params.Location.URI)
26 if err != nil {
27 return nil, nil, err
28 }
29 defer release()
30 pos := params.Location.Range.Start
31 refs, err := golang.References(ctx, snapshot, fh, protocol.Range{Start: pos, End: pos}, true)
32 if err != nil {
33 return nil, nil, err
34 }
35 formatted, err := formatReferences(ctx, snapshot, refs)
36 return formatted, nil, err
37 }
38
39 func formatReferences(ctx context.Context, snapshot *cache.Snapshot, refs []protocol.Location) (*mcp.CallToolResult, error) {
40 if len(refs) == 0 {
41 return nil, fmt.Errorf("no references found")
42 }
43 var builder strings.Builder
44 fmt.Fprintf(&builder, "The object has %v references. Their locations are listed below\n", len(refs))
45 for i, r := range refs {
46 fmt.Fprintf(&builder, "Reference %d\n", i+1)
47 fmt.Fprintf(&builder, "Located in the file: %s\n", filepath.ToSlash(r.URI.Path()))
48 refFh, err := snapshot.ReadFile(ctx, r.URI)
49 // If for some reason there is an error reading the file content, we should still
50 // return the references URIs.
51 if err != nil {
52 continue
53 }
54 content, err := refFh.Content()
55 if err != nil {
56 continue
57 }
58 lines := strings.Split(string(content), "\n")
59 var lineContent string
60 if int(r.Range.Start.Line) < len(lines) {
61 lineContent = strings.TrimLeftFunc(lines[r.Range.Start.Line], unicode.IsSpace)
62 } else {
63 continue
64 }
65 fmt.Fprintf(&builder, "The reference is located on line %v, which has content `%s`\n", r.Range.Start.Line, lineContent)
66 builder.WriteString("\n")
67 }
68 return textResult(builder.String()), nil
69 }