Golang Gopls
Samuel BertheCommunityCreated by samberDistributed by Samuel Berthe
- Skill
- Tool integration
- Software development
- MIT
- No issues found
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
The golang-gopls skill provides an agent with deep semantic understanding of Go codebases by leveraging gopls, the official Go language server. Unlike text-based search tools, gopls understands the resolved build, including dependencies, build tags, and interface relationships. It supports three integration modes: a dedicated MCP server for agent-friendly interactions, a native LSP tool for editor-like diagnostics, and a CLI for one-shot tasks. This skill is essential for precise navigation, automated refactoring, and maintaining code quality within a locally resolved Go workspace.
What it does
- Performs semantic navigation like go-to-definition, implementation lookups, and call hierarchy analysis.
- Provides fuzzy workspace symbol searching to locate types, functions, and variables.
- Executes safe refactoring actions including renaming, extracting, and inlining code.
- Generates compiler diagnostics and vulnerability reports based on the local build configuration.
- Handles code formatting and import organization to maintain canonical Go style.
- Offers documentation hovers and signature help for APIs within the workspace.
When to use it
- When you need to understand the structure or dependencies of a local Go project.
- Before performing refactors to ensure interface satisfaction and safe renaming.
- To identify and fix compiler errors or linting issues after modifying code.
- When you need to trace call sites or implementation relationships across a codebase.
- To quickly locate symbols or package APIs within your current workspace.
Advantages
- Provides build-aware intelligence that accounts for build tags and dependency pinning.
- Supports automated, safe refactoring actions that preserve code integrity.
- Offers multiple integration paths to suit different agent workflows and environments.
- Reduces manual verification by providing immediate feedback on code changes via diagnostics.
- Enables deep exploration of internal packages and local dependencies.
Usage examples
- “Find all implementations of the Logger interface in this project.”
- The agent uses the implementation tool to return a list of concrete types that satisfy the Logger interface, allowing for targeted code analysis.
- “Rename the User struct to Account and update all references.”
- The agent executes a safe rename refactor, ensuring that all imports and usages across the workspace are updated without breaking the build.
Install
Download the skill as a ZIP:
https://mp-staging.autogineer.com/agent-skills/samber/golang-gopls/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip golang-gopls.zip -d .agents/skills
Documentation by samber
Persona: You are a Go engineer who reaches for semantic code intelligence instead of grep whenever a question is about the resolved build — grep finds text, gopls finds meaning (types, call graphs, shadowing, implementation relationships).
Dependencies: gopls — go install golang.org/x/tools/gopls@latest (v0.20+). The native LSP tool additionally needs ENABLE_LSP_TOOL=1 and the gopls-lsp@claude-plugins-official marketplace plugin (see references/mcp.md).
gopls is the official Go language server. It only answers questions about your specific, locally resolved build — your workspace plus every dependency exactly as pinned in go.sum, including replace directives. For a package that isn't part of that build (versions, docs, licenses, CVEs of something you haven't added yet), → See samber/cc-skills-golang@golang-pkg-go-dev skill (godig) instead.
Three ways to reach gopls
Not interchangeable — pick by what you already know and what you need back:
gopls's own MCP server (preferred for most tasks) — purpose-built for agents: tools take names, file paths, and fuzzy queries instead of raw cursor positions. Register once per machine:
claude mcp add gopls -- gopls mcp. Runs headless over stdio, no editor attached, only sees files saved to disk — the right default for an agent-only workflow. See references/mcp.md for every tool.The native
LSPtool — Claude Code's built-in editor-style integration. Off by default: setENABLE_LSP_TOOL=1, installgopls, and install the officialgopls-lsp@claude-plugins-officialmarketplace plugin to wire it as the Go language server. Operations (goToDefinition,findReferences,hover,documentSymbol,workspaceSymbol,goToImplementation, call hierarchy) are keyed byline/character, so they're most useful once you already have a location — typically right after a grep or a read. Unique value: compiler diagnostics are pushed into context automatically after every edit, no explicit call needed.The
goplsCLI — same engine, invoked asgopls <command> <file:line:col>. The Go team documents it as experimental and debugging-only — "not efficient, complete, flexible, or officially supported." Use it when neither MCP nor the native tool is wired up, or for a one-shot scripted check. Positions arefile:line:col(1-indexed, UTF-8 bytes) orfile:#offset(0-indexed). See references/cli.md.
Preference order: MCP → native LSP → CLI. MCP tools match how an agent thinks (by name/path, not cursor position); the native tool adds free automatic diagnostics; the CLI is the documented fallback of last resort. Wire as many as are available and let the task pick the tool — a query you already have a line:col for is cheap via LSP, a "where is X" query is cheap via go_search, a quick unattended check is cheap via the CLI.
Capability → CLI → MCP → native LSP
Full mapping of every capability to its CLI command, MCP tool, and native LSP op: references/matrix.md.
Use cases
Navigation — jump to a definition, an implementation, or trace a call graph before touching code you didn't write. Details: references/features.md.
Code discovery — learn a workspace's shape (
go_workspace), fuzzy-search a symbol you can't place exactly (go_search), or read a dependency's public surface (go_package_api) before using it.Documentation — hover for type/doc/size info, signature help while calling a function, or browse rendered package docs (
source.doc, including internal packages pkg.go.dev never sees).Diagnostics & safety — compiler and analyzer errors after every edit (
go_diagnostics/ automatic withLSP), plus a lightweightgo_vulncheckreachability check: once as a baseline right after detecting the workspace, and again after anygo.modchange.Formatting — canonical
gofmt-equivalent formatting and import organization, both scriptable and code-action-driven.Refactoring — safe rename (blocks a change that would break interface satisfaction), extract/inline, and the full
refactor.rewrite.*family (fill struct/switch, invert if, split/join lines, remove unused parameter, add struct tags, implement interface). Full catalog with gotchas: references/features.md.
Efficient workflows
These Read/Edit workflows encode the order that avoids redundant queries and half-applied edits — treat every step as required, not optional, even to save a round trip.
Session start — call
go_workspaceonce to detect whether this is a Go workspace at all; if it is, immediately follow with a baselinego_vulncheckto surface vulnerabilities the workspace already carries. This is unconditional, separate from the edit workflow's later check after a dependency change.
Read workflow (understand before touching anything):
go_workspace— layout (module/workspace/GOPATH); same call as the session-start check above if it hasn't run yet.go_search— fuzzy-locate a type/function/variable by name.go_file_context— right after reading any Go file for the first time, see what it pulls in from the rest of its package; re-run if that file's dependencies change.go_package_api— a third-party dependency's or sibling package's public surface, without reading every file.
Edit workflow (iterate until diagnostics are clean):
Read first (workflow above).
go_symbol_referencesbefore modifying any definition — judge the blast radius, then read every referencing file that needs a matching edit.Make all planned edits, including the reference-site edits, before moving on.
go_diagnosticson every changed file — mandatory after each modification, not an optional cleanup pass.Fix reported errors: review any suggested quick-fix diff before applying, then re-run diagnostics to confirm the fix landed. Ignore hint/info diagnostics unrelated to the task. A diagnostic message can paraphrase the surrounding source rather than quote it verbatim.
Only if
go.moddependencies changed, rungo_vulncheckon the whole workspace — after diagnostics are clean, not before.Run
go test <changed-package-paths>— not./...unless explicitly asked, since a full-repo run slows the iteration loop.
Gotchas worth knowing before you rely on a result:
referencesresults only reflect the build configuration of the queried file — a query onfoo_windows.gowill not surface matches inbar_linux.go; re-run under the relevantGOOS/build tags if a cross-platform result is missing.call_hierarchyonly shows static calls — calls through function values or interface methods are invisible to it; corroborate withreferenceswhen the call site matters.Extract/inline refactors are less rigorous than rename: comments are sometimes dropped, and generated files marked
DO NOT EDITreceive no code actions at all.refactor.rewrite.fillStructsearches only the current file above the cursor and needs the struct's package already imported — runsource.organizeImportsfirst if the type was just typed in.
gopls vs godig vs Context7 vs govulncheck
gopls only reasons about code present and resolvable in the local build:
For anything not tied to that build (version history, license, ecosystem-wide importers, CVEs of a package not yet added) → See
samber/cc-skills-golang@golang-pkg-go-devskill (godig) — it queries pkg.go.dev directly, no local checkout needed.For a comprehensive, whole-tree vulnerability audit (CI gates, periodic sweeps) rather than gopls's lightweight on-demand
go_vulncheck→ Seesamber/cc-skills-golang@golang-securityskill (govulncheck).Context7 remains a fallback for non-Go docs or a Go module not indexed on pkg.go.dev.
The full task-to-tool matrix lives in the samber/cc-skills-golang@golang-how-to skill's "godig vs gopls vs Context7 vs govulncheck" section.
Files
- ATTRIBUTION.mdAdded by AutoGineer893 B
- LICENSELicence file added by AutoGineer1.0 KiB
- SKILL.md9.6 KiB
- references/cli.md9.0 KiB
- references/features.md18.1 KiB
- references/matrix.md3.2 KiB
- references/mcp.md5.2 KiB
- references/settings.md5.3 KiB
references/features.md
gopls feature catalog
Source: tip.golang.org/gopls/features. Each entry names the LSP request or CodeAction kind so a specific behavior can be looked up in the upstream docs by exact term.
Table of contents
Navigation
Passive (always-on)
Diagnostics
Transformation
Web-based features
Non-Go files
Completion
Navigation
Definition (textDocument/definition, CLI gopls definition) — jumps to a symbol's declaration. Handles more than plain identifiers: on an import path it lists the imported package's declarations; on a go:linkname directive it finds the linked symbol; on a go:embed pattern it finds the embedded file; on a doc-comment link it follows the reference; on a non-Go function it can return the assembly implementation; on return it locates the named result variables; on goto/break/continue it finds the target label or block. Already at the declaration → most clients reinterpret the request as "find references" instead.
Type Definition (textDocument/typeDefinition, no CLI equivalent) — jumps to the named type underlying a symbol, unwrapping pointer, array, slice, channel, and map constructors first. For x chan []*T, this reports the definition of T; it works only on symbols, not arbitrary expressions. No agent-invocable path: it is absent from the native LSP tool's fixed operation list (goToDefinition, findReferences, hover, documentSymbol, workspaceSymbol, goToImplementation, call hierarchy), so only a full editor LSP client can reach it.
References (textDocument/references, CLI gopls references) — lists every use of a symbol: for an interface method, this includes concrete implementations; for a package declaration, it includes both direct imports and other files' package clauses; for an embedded field, it reports only field references (use Type Definition to find references to the type itself). Scoping gotcha: results reflect only the build configuration of the queried file — a query issued against foo_windows.go will not surface a match in bar_linux.go. Built-in symbols (int, append) are rejected as too numerous to be useful.
Implementation (textDocument/implementation, CLI gopls implementation) — on an interface, returns concrete implementations and sub-interfaces; on a concrete type, returns interfaces it satisfies; on an interface method, returns the concrete methods satisfying it, and vice versa. Matching uses method sets for types and signatures for functions, with generic types treated as wildcards — a candidate is included if any instantiation would allow one to implement the other, without full unification checking. LSP's built-in bias toward subtypes makes this query directionally asymmetric — for full bidirectional traversal, use Type Hierarchy instead.
Document Symbol (textDocument/documentSymbol, CLI gopls symbols) — outline of a single file's top-level declarations. File-scoped; use Symbol for cross-file search.
Symbol / Workspace Symbol (workspace/symbol, CLI gopls workspace_symbol) — fuzzy search across the whole workspace. Default matcher is fastFuzzy (FZF-inspired), so abbreviations and typos still match — DocSym matches DocumentSymbol. Controlled by the symbolMatcher, symbolStyle, and symbolScope settings (see settings.md); directoryFilters excludes directories from the search.
Selection Range (textDocument/selectionRange, no CLI equivalent) — expands or contracts the current selection along syntactic boundaries (expression → statement → block → function). Useful for selecting exactly the region an Extract refactor needs.
Call Hierarchy (textDocument/prepareCallHierarchy + callHierarchyItem/incomingCalls/outgoingCalls, CLI gopls call_hierarchy) — shows a function's callers and callees as a static graph. Only static calls are included — calls made through a function value or an interface method are invisible, since detecting them isn't analytically tractable. Invoke on the function declaration's name, and corroborate with References when a dynamically-dispatched call site matters.
Type Hierarchy (textDocument/prepareTypeHierarchy + typeHierarchyItem/subtypes/typeHierarchy/supertypes, no CLI equivalent yet) — bidirectional view of the subtyping relation: which types implement an interface, and which interfaces a type satisfies. Resolves the asymmetry Implementation has. Limited to named types (unlike Implementation, which also matches unnamed function types); alias types are excluded; function-local types are visible only within the same package.
Passive (always-on)
These need no explicit invocation — they fire continuously as an editor session progresses. Most degrade if the surrounding package has build errors, since they depend on successful type-checking.
Hover (textDocument/hover) — symbol name/kind/type/value, doc comment (with clickable doc links like [fmt.Printf]), promoted methods from embedded fields, struct field size/offset and wasted-space percentage (flagged at ≥20% waste), expanded //go:embed patterns, //go:linkname targets, and which Go release introduced a given stdlib symbol. Controlled by hoverKind (verbosity) and linkTarget (base URI for doc links).
Signature Help (textDocument/signatureHelp) — parameter names/types/docs for the function being called, with the active parameter highlighted; works even while the cursor sits inside the function name, not just inside the parens.
Document Highlight (textDocument/documentHighlight) — highlights every identifier referring to the same symbol in view, plus related tokens: named results and their return statements, loop control keywords (for/break/continue), switch tokens, a function and its own return statements. Read vs. write references are typically color-coded differently by the client.
Inlay Hint (textDocument/inlayHint) — inline annotations, off by default (visual clutter), toggled per-kind via the hints setting: parameterNames (call-site argument labels), assignVariableTypes, compositeLiteralFields, compositeLiteralTypes, constantValues (including computed iota values), functionTypeParameters (generic instantiations), rangeVariableTypes.
Semantic Tokens (textDocument/semanticTokens) — richer syntax coloring than naive lexing: token types (function, keyword, macro, method, namespace, number, operator, parameter, string, type, typeParameter, variable, …) plus modifiers including a custom shadowing modifier that flags shadowed declarations. Off by default due to type-checking latency (semanticTokens setting); noSemanticString/noSemanticNumber let a client opt out of just those two kinds if it prefers its own lexical highlighting for them.
Folding Range (textDocument/foldingRange) — collapsible regions for large comments, functions, and blocks.
Document Link (textDocument/documentLink) — turns URLs in doc comments and import declarations into clickable links (imports link to their pkg.go.dev page). Controlled by importShortcut and linkTarget.
Diagnostics
Three sources, distinguished by the LSP diagnostic's source field:
Compilation errors — gopls doesn't invoke the real compiler; it runs
go listfor package metadata (source: "go list") then mimics the compiler front-end itself: read, scan, parse, type-check (source: "compiler").Analysis findings — the
go vetanalysis framework plus gopls's own analyzers, each reporting under its own analyzer name assource. Theprintfanalyzer (format-string/argument mismatches) is a representative example.Compiler optimization details — off by default; toggled per-package with the
source.toggleCompilerOptDetailscode action. Surfaces escape-analysis results, nil-check elimination, and inlining decisions. Only available on packages that are otherwise error-free.
Recomputation timing: open-file compile errors update within tens of milliseconds of a keystroke. Workspace-wide analysis diagnostics recompute after roughly a second of idle time, tunable via diagnosticsDelay; diagnosticsTrigger can switch this to save-triggered instead of edit-triggered. Clients can also request diagnostics explicitly (textDocument/diagnostic, "pull diagnostics") if initialized with pullDiagnostics: true — off by default for performance.
Notable quick fixes, offered as code actions attached to a diagnostic:
fillreturns— heuristically completes an incompletereturnstatement.stubMissingInterfaceMethods— generates stub methods when a concrete type doesn't yet satisfy a required interface.StubMissingCalledFunction— creates a stub for an undefined function/method, inferring its signature from the call site.CreateUndeclared— declares a missing variable or function based on how it's used.Fixes marked
source.fixAllare considered unconditionally safe; most editors offer a single shortcut to apply all of them at once.
CLI: gopls check <file> (-severity=hint|info|warning|error, default warning).
Transformation
Three underlying mechanisms: Formatting and Rename are primary LSP requests; most everything else is a CodeAction (requested per-range, returns either a direct edit or a lazily-computed command); a handful of dependency-management actions are CodeLenses instead.
Formatting (textDocument/formatting, CLI gopls format) — canonical Go formatting; client-supplied formatting options are ignored. gofumpt: true switches to mvdan.cc/gofumpt's stricter rules.
Organize Imports (source.organizeImports, CLI gopls imports) — removes unused/duplicate imports, adds missing ones (via workspace-wide heuristics — occasionally surprising), sorts them. The local setting groups a path prefix as "local," matching goimports -local. Most editors run this on save; disable per-language if that's unwanted.
Rename (textDocument/rename, CLI gopls rename) — two-stage: prepareRename reports the current name, then rename applies the change everywhere. Refuses renames that would introduce shadowing or break interface satisfaction. Special positions unlock extra behavior:
Rename a method's receiver declaration → renames the receiver identifier across every method of that type; rename a receiver use → renames only that one variable.
Rename the package name in a
packageclause → moves every file in the package to a new directory (subpackages stay put unlessrenameMovesSubpackagesis set); refused across module boundaries or into an existing package.Rename the
funckeyword of a declaration → lets you edit the whole signature; parameter/result count and types must stay the same (no adding/removing parameters this way — seerefactor.rewrite.removeUnusedParam/moveParamLeft/moveParamRightfor that).
Extract (refactor.extract.*) — replaces a selection with a reference to a new declaration:
refactor.extract.variable/.constant— one new local binding for the selected expression, plus-allvariants that rewrite every occurrence within the enclosing function.refactor.extract.function/.method— turns one or more complete statements into a call to a new function (or method, on the same receiver, if extracted inside a method).refactor.extract.toNewFile(gopls ≥ v0.17.0) — moves selected top-level declarations into a new file, adding imports as needed; the new filename derives from the first declared symbol.
Extract is less rigorous than Rename/Inline: comments are sometimes dropped, and files carrying a DO NOT EDIT generated-code marker receive no code actions at all.
Inline (refactor.inline.*):
refactor.inline.call— replaces a call with the function body, substituting parameters for arguments. Works only for static calls to accessible functions/methods (not through a function value or interface method, not to unexported names outside the package, not intointernalpackages, not for generic functions). Preserves side-effect ordering (introducesvars when an argument must not be duplicated or reordered), keeps qualified references correct (Printf→fmt.Printfwith the import added), keeps implicit conversions explicit, and never drops a variable's last use.deferbodies stay wrapped in a closure since defer semantics are tied to function boundaries.refactor.inline.variable— replaces a local variable's use with its initializer expression; refuses if an identifier in that initializer has been shadowed since the declaration.
Miscellaneous rewrites (refactor.rewrite.*):
removeUnusedParam— theunusedparamsanalyzer offers renaming to_(trivial) or a full signature change that also updates every caller, preserving side-effecting arguments.moveParamLeft/moveParamRight— reorders one parameter, updating every call site.changeQuote— toggles a string literal between raw (`...`) and interpreted ("...") form; idempotent to apply twice.invertIf— negates a plainif/elsecondition (noelse ifchain) and swaps the two blocks.splitLines/joinLines— expands or collapses a bracketed list (composite literal, call arguments, signature) one item per line; skipped for lists that already contain//comments or have fewer than two items.fillStruct— populates missing struct-literal fields, matching field names to in-scope variables/constants/functions where possible, zero value otherwise. Searches only the current file, above the cursor — runsource.organizeImportsfirst if the struct type was just introduced.fillSwitch— adds missing cases for an enum-like set of named constants, or for a type switch (one case per concrete type implementing the interface, plus a default that panics on an unexpected type).eliminateDotImport— removes a dot import and qualifies every reference, offered only when no name collision would result.addTags/removeTags— adds or removes struct field tags (e.g.json); interactive clients can choose the naming transform (camelCase,snake_case,lisp-case,PascalCase,Title Case).implementInterface— adds placeholder method declarations so a named type satisfies a chosen interface (defaults toerror); interactive-dialog only, gopls-specific.
Add Test For Function (source.addTest) — generates a table-driven test for the selected function/method, creating the _test.go file if needed (copying copyright/build-constraint comments), using an external p_test package to encourage testing exported API only, naming results got/got2/…, comparing against want/want2/…, and adding a wantErr bool field when the final result is error. For a method, searches the package for a constructor (preferring NewT for type T). A leading context.Context parameter gets t.Context() on Go 1.24+, context.Background() otherwise.
Web-based features
gopls runs a small localhost web server (LSP window/showDocument) for reports too rich for inline editor UI. Every endpoint URL embeds a random auth token; restarting gopls invalidates old links and shows a disconnected banner on any page still open.
Package Documentation (
source.doc) — a pkgsite-style rendered view of a package's docs, including internal, unpublished packages pkg.go.dev never sees. Symbol links jump the editor to the source declaration; reload without saving to see current edits reflected.Free Symbols (
source.freesymbols) — lists the symbols a selection references but doesn't define itself, grouped as imported (with doc links), local, or package-level — the exact input list an Extract Function/Method refactor would need.Assembly (
source.assembly) — the compiled assembly listing for a function, source-line-linked, recompiled on each reload. Architecture follows the file's build tags (e.g.foo_amd64.go). Not yet supported for generic functions,func init, or functions in test packages.Split Package (
source.splitPackage) — an interactive dependency-graph tool for planning how to break a package into smaller, acyclic components. It visualizes the split but does not yet perform the actual code movement/renaming.
All of these send edits/navigation back to the editor via showDocument, which works even against modified-but-unsaved source.
Non-Go files
Templates (text/template/html/template) — disabled until templateExtensions lists at least one extension (templates have no canonical extension of their own); the editor also needs to associate that extension with the tmpl/gotmpl language ID (e.g. VS Code's files.associations). Inside {{ }} delimiters: diagnostics (parse errors; missing functions are not flagged), full syntax highlighting, definitions and references (all templates share one global scope), and completions. Hover, semantic tokens, symbol search, and document highlight are not yet implemented, and custom delimiters other than {{/}} are not understood.
go.mod / go.work — hover, hints, vulncheck-driven diagnostics, and code lenses (add dependency, upgrade dependency, tidy, run govulncheck) are supported; the upstream page marks the fine-grained behavior of each as still under documentation, so verify current behavior directly against a go.mod file in an editor session rather than relying on an exhaustive list here.
Assembly (.s) files — basic support exists; treat as best-effort.
Completion
Upstream documentation for this feature is a stub as of this writing (tracked as golang/go#62022) — rely on empirical behavior plus these known settings rather than a documented spec: usePlaceholders (fills in placeholder parameter names on completion), completeFunctionCalls (adds trailing parentheses, on by default), completeUnimported and matcher/deepCompletion-style settings shape whether not-yet-imported packages and nested field/method completions are offered. See settings.md for the full settings surface.
Requirements and compatibility
Written for: Claude Code, OpenAI Codex
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Needs: Declares allowed tools, Claude Code frontmatter, Needs an MCP server
The author says: Designed for Claude Code, Codex or similar harness. Requires the gopls binary (go install golang.org/x/tools/gopls@latest) v0.20+ on PATH.
Security
No issues found by our static scan· No issues found
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Created by
- samber
- Publisher
- Samuel Berthe (Community)
- Distributed by
- Samuel Berthe
- Source
- samber/cc-skills-golang · skills/golang-gopls · commit bb1d43d
- Licence
- MIT License (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by samber or Samuel Berthe.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download golang-gopls.zip