Debian Codegraph @

gopls/internal/mcp/context.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 // This file defines the "context" operation, which returns a summary of the
8 // specified package.
9
10 import (
11 "bytes"
12 "context"
13 "fmt"
14 "go/ast"
15 "go/token"
16 "slices"
17 "strings"
18
19 "github.com/modelcontextprotocol/go-sdk/mcp"
20 "golang.org/x/tools/gopls/internal/cache"
21 "golang.org/x/tools/gopls/internal/cache/metadata"
22 "golang.org/x/tools/gopls/internal/cache/parsego"
23 "golang.org/x/tools/gopls/internal/file"
24 "golang.org/x/tools/gopls/internal/golang"
25 "golang.org/x/tools/gopls/internal/protocol"
26 "golang.org/x/tools/internal/astutil"
27 "golang.org/x/tools/internal/packagepath"
28 )
29
30 type ContextParams struct {
31 File string `json:"file" jsonschema:"the absolute path to the file"`
32 }
33
34 func (h *handler) contextHandler(ctx context.Context, req *mcp.CallToolRequest, params ContextParams) (*mcp.CallToolResult, any, error) {
35 countGoContextMCP.Inc()
36 fh, snapshot, release, err := h.fileOf(ctx, params.File)
37 if err != nil {
38 return nil, nil, err
39 }
40 defer release()
41
42 // TODO(hxjiang): support context for GoMod.
43 if snapshot.FileKind(fh) != file.Go {
44 return nil, nil, fmt.Errorf("can't provide context for non-Go file")
45 }
46
47 pkg, pgf, err := golang.NarrowestPackageForFile(ctx, snapshot, fh.URI())
48 if err != nil {
49 return nil, nil, err
50 }
51
52 var result strings.Builder
53
54 fmt.Fprintf(&result, "Current package %q (package %s):\n\n", pkg.Metadata().PkgPath, pkg.Metadata().Name)
55 // Write context of the current file.
56 {
57 fmt.Fprintf(&result, "%s (current file):\n", pgf.URI.Base())
58 result.WriteString("```go\n")
59 if err := writeFileSummary(ctx, snapshot, pgf.URI, &result, false, nil); err != nil {
60 return nil, nil, err
61 }
62 result.WriteString("```\n\n")
63 }
64
65 // Write context of the rest of the files in the current package.
66 {
67 for _, file := range pkg.CompiledGoFiles() {
68 if file.URI == pgf.URI {
69 continue
70 }
71
72 fmt.Fprintf(&result, "%s:\n", file.URI.Base())
73 result.WriteString("```go\n")
74 if err := writeFileSummary(ctx, snapshot, file.URI, &result, false, nil); err != nil {
75 return nil, nil, err
76 }
77 result.WriteString("```\n\n")
78 }
79 }
80
81 // Write dependencies context of current file.
82 if len(pgf.File.Imports) > 0 {
83 // Write import decls of the current file.
84 {
85 fmt.Fprintf(&result, "Current file %q contains this import declaration:\n", pgf.URI.Base())
86 result.WriteString("```go\n")
87 // Add all import decl to output including all floating comment by
88 // using GenDecl's start and end position.
89 for _, decl := range pgf.File.Decls {
90 genDecl, ok := decl.(*ast.GenDecl)
91 if !ok || genDecl.Tok != token.IMPORT {
92 continue
93 }
94
95 text, err := pgf.NodeText(genDecl)
96 if err != nil {
97 return nil, nil, err
98 }
99
100 result.Write(text)
101 result.WriteString("\n")
102 }
103 result.WriteString("```\n\n")
104 }
105
106 var toSummarize []*ast.ImportSpec
107 for _, spec := range pgf.File.Imports {
108 // Skip the standard library to reduce token usage, operating on
109 // the assumption that the LLM is already familiar with its
110 // symbols and documentation.
111 if packagepath.IsStdPackage(spec.Path.Value) {
112 continue
113 }
114 toSummarize = append(toSummarize, spec)
115 }
116
117 // Write summaries from imported packages.
118 if len(toSummarize) > 0 {
119 result.WriteString("The imported packages declare the following symbols:\n\n")
120 for _, spec := range toSummarize {
121 path := metadata.UnquoteImportPath(spec)
122 id := pkg.Metadata().DepsByImpPath[path]
123 if id == "" {
124 continue // ignore error
125 }
126 md := snapshot.Metadata(id)
127 if md == nil {
128 continue // ignore error
129 }
130 if summary := summarizePackage(ctx, snapshot, md); summary != "" {
131 result.WriteString(summary)
132 }
133 }
134 }
135 }
136
137 return textResult(result.String()), nil, nil
138 }
139
140 func summarizePackage(ctx context.Context, snapshot *cache.Snapshot, md *metadata.Package) string {
141 var buf strings.Builder
142 fmt.Fprintf(&buf, "%q (package %s)\n", md.PkgPath, md.Name)
143 for _, f := range md.CompiledGoFiles {
144 fmt.Fprintf(&buf, "%s:\n", f.Base())
145 buf.WriteString("```go\n")
146 if err := writeFileSummary(ctx, snapshot, f, &buf, true, nil); err != nil {
147 return "" // ignore error
148 }
149 buf.WriteString("```\n\n")
150 }
151 return buf.String()
152 }
153
154 // writeFileSummary writes the file summary to the string builder based on
155 // the input file URI.
156 func writeFileSummary(ctx context.Context, snapshot *cache.Snapshot, f protocol.DocumentURI, out *strings.Builder, onlyExported bool, declsToSummarize map[string]bool) error {
157 fh, err := snapshot.ReadFile(ctx, f)
158 if err != nil {
159 return err
160 }
161 pgf, err := snapshot.ParseGo(ctx, fh, parsego.Full)
162 if err != nil {
163 return err
164 }
165
166 // If we're summarizing specific declarations, we don't need to copy the header.
167 if declsToSummarize == nil {
168 // Copy everything before the first non-import declaration:
169 // package decl, imports decl(s), and all comments (excluding copyright).
170 {
171 endPos := pgf.File.FileEnd
172
173 outerloop:
174 for _, decl := range pgf.File.Decls {
175 switch decl := decl.(type) {
176 case *ast.FuncDecl:
177 if decl.Doc != nil {
178 endPos = decl.Doc.Pos()
179 } else {
180 endPos = decl.Pos()
181 }
182 break outerloop
183 case *ast.GenDecl:
184 if decl.Tok == token.IMPORT {
185 continue
186 }
187 if decl.Doc != nil {
188 endPos = decl.Doc.Pos()
189 } else {
190 endPos = decl.Pos()
191 }
192 break outerloop
193 }
194 }
195
196 startPos := pgf.File.FileStart
197 if copyright := golang.CopyrightComment(pgf.File); copyright != nil {
198 startPos = copyright.End()
199 }
200
201 text, err := pgf.PosText(startPos, endPos)
202 if err != nil {
203 return err
204 }
205
206 out.Write(bytes.TrimSpace(text))
207 out.WriteString("\n\n")
208 }
209 }
210
211 // Write func decl and gen decl.
212 for _, decl := range pgf.File.Decls {
213 switch decl := decl.(type) {
214 case *ast.FuncDecl:
215 if declsToSummarize != nil {
216 if _, ok := declsToSummarize[decl.Name.Name]; !ok {
217 continue
218 }
219 }
220 if onlyExported {
221 if !decl.Name.IsExported() {
222 continue
223 }
224
225 if decl.Recv != nil && len(decl.Recv.List) > 0 {
226 _, rname, _ := astutil.UnpackRecv(decl.Recv.List[0].Type)
227 if !rname.IsExported() {
228 continue
229 }
230 }
231 }
232
233 // Write doc comment and func signature.
234 startPos := decl.Pos()
235 if decl.Doc != nil {
236 startPos = decl.Doc.Pos()
237 }
238
239 text, err := pgf.PosText(startPos, decl.Type.End())
240 if err != nil {
241 return err
242 }
243
244 out.Write(text)
245 out.WriteString("\n\n")
246
247 case *ast.GenDecl:
248 if decl.Tok == token.IMPORT {
249 continue
250 }
251
252 // If we are summarizing specific decls, check if any of them are in this GenDecl.
253 if declsToSummarize != nil {
254 found := false
255 for _, spec := range decl.Specs {
256 switch spec := spec.(type) {
257 case *ast.TypeSpec:
258 if _, ok := declsToSummarize[spec.Name.Name]; ok {
259 found = true
260 }
261 case *ast.ValueSpec:
262 for _, name := range spec.Names {
263 if _, ok := declsToSummarize[name.Name]; ok {
264 found = true
265 }
266 }
267 }
268 }
269 if !found {
270 continue
271 }
272 }
273
274 // Dump the entire GenDecl (exported or unexported)
275 // including doc comment without any filtering to the output.
276 if !onlyExported {
277 startPos := decl.Pos()
278 if decl.Doc != nil {
279 startPos = decl.Doc.Pos()
280 }
281 text, err := pgf.PosText(startPos, decl.End())
282 if err != nil {
283 return err
284 }
285
286 out.Write(text)
287 out.WriteString("\n")
288 continue
289 }
290
291 // Write only the GenDecl with exported identifier to the output.
292 var buf bytes.Buffer
293 if decl.Doc != nil {
294 text, err := pgf.NodeText(decl.Doc)
295 if err != nil {
296 return err
297 }
298 buf.Write(text)
299 buf.WriteString("\n")
300 }
301
302 buf.WriteString(decl.Tok.String() + " ")
303 if decl.Lparen.IsValid() {
304 buf.WriteString("(\n")
305 }
306
307 var anyExported bool
308 for _, spec := range decl.Specs {
309 // Captures the full byte range of the spec, including
310 // its associated doc comments and line comments.
311 // This range also covers any floating comments as these
312 // can be valuable for context. Like
313 // ```
314 // type foo struct { // floating comment.
315 // // floating comment.
316 //
317 // x int
318 // }
319 // ```
320 var startPos, endPos token.Pos
321
322 switch spec := spec.(type) {
323 case *ast.TypeSpec:
324 if declsToSummarize != nil {
325 if _, ok := declsToSummarize[spec.Name.Name]; !ok {
326 continue
327 }
328 }
329 // TODO(hxjiang): only keep the exported field of
330 // struct spec and exported method of interface spec.
331 if !spec.Name.IsExported() {
332 continue
333 }
334 anyExported = true
335
336 // Include preceding doc comment, if any.
337 if spec.Doc == nil {
338 startPos = spec.Pos()
339 } else {
340 startPos = spec.Doc.Pos()
341 }
342
343 // Include trailing line comment, if any.
344 if spec.Comment == nil {
345 endPos = spec.End()
346 } else {
347 endPos = spec.Comment.End()
348 }
349
350 case *ast.ValueSpec:
351 if declsToSummarize != nil {
352 found := false
353 for _, name := range spec.Names {
354 if _, ok := declsToSummarize[name.Name]; ok {
355 found = true
356 }
357 }
358 if !found {
359 continue
360 }
361 }
362 // TODO(hxjiang): only keep the exported identifier.
363 if !slices.ContainsFunc(spec.Names, (*ast.Ident).IsExported) {
364 continue
365 }
366 anyExported = true
367
368 if spec.Doc == nil {
369 startPos = spec.Pos()
370 } else {
371 startPos = spec.Doc.Pos()
372 }
373
374 if spec.Comment == nil {
375 endPos = spec.End()
376 } else {
377 endPos = spec.Comment.End()
378 }
379 }
380
381 indent, err := pgf.Indentation(startPos)
382 if err != nil {
383 return err
384 }
385
386 buf.WriteString(indent)
387
388 text, err := pgf.PosText(startPos, endPos)
389 if err != nil {
390 return err
391 }
392
393 buf.Write(text)
394 buf.WriteString("\n")
395 }
396
397 if decl.Lparen.IsValid() {
398 buf.WriteString(")\n")
399 }
400
401 // Only write the summary of the genDecl if there is
402 // any exported spec.
403 if anyExported {
404 out.Write(buf.Bytes())
405 out.WriteString("\n")
406 }
407 }
408 }
409 return nil
410 }