agentleFS
jmrplensjmrplens/gitlab-mcp-server/CLAUDE.md

gitlab-mcp-server

CLAUDE.md43 starsChanged 6 months agoMITView on GitHub

This file provides comprehensive context for AI assistants working on this project. All project artifacts must be written in English. Conversations may be in any language. No AI attribution in anything published under the maintainer's name. Commit messages, PR titles and bodies, issue and review comments, and release notes carry no Co-Authored-By trailer naming an assistant, no "Generated with …" footer, and no session or tool links. This overrides any default template that adds one. A PR body is not…

  • Reads credentials
  • Sends data out

The file

We split this CLAUDE.md into the rules it gives an agent

11 rules. About 0 are common, 2 are distinctive, and 9 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈2

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 9

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Create internal/tools/{domain}/ sub-package directory, with a doc.go holding the package comment (every package keeps it there.

    line 235
  2. Very specific:

    Create {domain}_test.go with table-driven tests using testutil.NewTestClient and httptest.

    line 237
  3. Very specific:

    Add or update domain-local ActionSpecs so the action has one canonical route, owner package, metadata, compatibility policy, individual …

    line 238
  4. Distinctive:

    If the domain is new, update the generated/audited catalog aggregation path rather than adding ad hoc root registration calls.

    line 239
  5. Very specific:

    Add markdown formatters in the sub-package markdown.go init() function using toolutil.RegisterMarkdown[T] with appropriate content …

    line 240
  6. Very specific:

    Add clickable text links in Markdown table columns where applicable (MRs, issues, pipelines, etc.)

    line 242
  7. Very specific:

    Update docs/reference/tools/{domain}.md and docs/reference/tools/README.md

    line 244
  8. Very specific:

    After completing a test-focused tool implementation phase, run go run ./cmd/gen_testing_docs/ or make gen-testing-docs to refresh …

    line 245
  9. Distinctive:

    When adding a transport-level behavior, put its test here rather than in a unit test that reassembles the handler chain: a test that builds …

    line 354
  10. Very specific:

    All tests use httptest to mock GitLab API responses.

    line 360
  11. Very specific:

    Test-file naming: a _test.go exists only under the name of a module it tests (register.go → register_test.go).

    line 373

≈ “Common” is an estimate: at least 1 in 5 of the 12,729 CLAUDE.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
CLAUDE.md

gitlab-mcp-server — AI Development Context

This file provides comprehensive context for AI assistants working on this project. All project artifacts must be written in English. Conversations may be in any language.

No AI attribution in anything published under the maintainer's name. Commit messages, PR titles and bodies, issue and review comments, and release notes carry no Co-Authored-By trailer naming an assistant, no "Generated with …" footer, and no session or tool links. This overrides any default template that adds one. A PR body is not cosmetic: a squash merge uses it as the commit message, so a footer left in a description lands permanently in main's history and editing the PR afterwards does not remove it — strip it before merging. Ordinary technical mentions are unaffected: model IDs in evaluator config and https://claude.ai as a client origin in CORS examples are content, not attribution.

For the same reason a description never carries a command GitHub reads as a request to skip workflows (a bracketed skip ci or one of the four other commands GitHub documents, or a skip-checks trailer), not even quoted in backticks: the squash commit of #1094 carried one, and main ran no CI and the v3.1.0 tag on it no release. make check-pr-description refuses it.

Project Overview

gitlab-mcp-server is a Model Context Protocol (MCP) server written in Go that exposes GitLab REST API v4 and GraphQL operations as MCP tools for AI assistants. It runs as a local binary communicating via stdio or HTTP transport.

AttributeValue
LanguageGo 1.27.1
MCP SDKgithub.com/modelcontextprotocol/go-sdk/mcp v1.8.0
GitLab Clientgitlab.com/gitlab-org/api/client-go/v3 v3.14.0
Transportstdio (primary), HTTP (optional)
PlatformsWindows, Linux & macOS, amd64 & arm64
Version3.1.0

Scale

MetricCount
MCP Tools (individual)By instance tier: ~868 Free/CE; ~1022 Premium; ~1088 Ultimate (self-managed) / ~1094 on GitLab.com Ultimate with Orbit
Catalog groupsBy instance tier: 29 Free/CE; 35 Premium; 46 Ultimate
Meta-mode tools34 base (Free/CE) / 40 Premium / 51 self-managed Ultimate / 52 GitLab.com Ultimate (Orbit); gitlab_server is served on every one of them and is counted here
Dynamic-mode tools2 dynamic tools (gitlab_find_action, gitlab_execute_action) — see Dynamic toolset mode below
MCP Resources45 across dynamic/full, meta/full, and individual/full modes; gitlab://tools adapts to the active surface
MCP Prompts37 (12 core + 4 cross-project + 4 team + 5 project-reports + 4 analytics + 4 milestone-label + 2 git-workflow + 2 audit)
Completion argument names18
MCP Capabilities4 (progress, elicitation, completions, resource subscriptions)
MCP Icons51 icons (50 domain + brand mark), each a 3-entry []mcp.Icon: one SVG (base64 data URI, Sizes: ["any"], currentColor) plus light/dark 16×16 lossless WebP fallbacks (Theme-tagged, cmd/gen_icon_webp) for clients that reject SVG. The brand mark is the generated "fan-out" (cmd/gen_brand → brandmark_gen.go), original artwork replacing the former tanuki
Source files (tools)779 non-test Go files under internal/tools/
Test files (tools)473 test files under internal/tools/
Go packages297 in the module (go list ./...); the README's 314 counts directories holding tracked .go files, so it adds the seventeen go list leaves out: sixteen testdata fixture packages (the two stand-in programs, the coverage audit's planted trees and the stand-in module the SDK route reader's tests read) and test/e2e/modeleval/internal/provider, whose every file sits behind a build tag. 181 under internal/tools/... (the root package plus 180 sub-packages)

Orbit live tests

The six read-only gitlab_orbit_* tools (status, schema, tools, dsl, query, graph_status) target GitLab.com's experimental Knowledge Graph API. They have an orbitlive-gated live test suite at test/e2e/orbit/live_test.go (4 suites, 45 subtests) that exercises the real https://gitlab.com/api/v4/orbit/* endpoints. The live test fixtures (kg-fixtures, security-fixtures) live under test/fixtures/orbit/ and are provisioned by scripts/setup-orbit-fixtures.sh. End-to-end orchestration is exposed as make test-e2e-gitlab-com (runs setup, waits for the indexer, runs the live tests, then re-records the answers with make gen-orbit-record). See Orbit live test fixtures for fixture contents, namespace configuration, and the indexer caveat.

What the six routes answer is also the oracle R-PATH holds the Orbit output types to, because no self-managed GitLab serves Orbit and GitLab's generated reference gives its routes no response schema. cmd/gen_orbit_record calls each handler through a recording proxy on the loopback interface, reads only, and writes docs/development/orbit-responses.json: per call, the action, the output type its handler returned, the parameter names the request carried and the key tree of the answer (every path with the JSON kinds seen there, never a value, a subtree whose keys are data kept as its root). A re-recording refuses a fixture namespace the indexer has not reached, prints every key added, dropped or changed against the record committed at HEAD (read through git, not from the file it rewrites), and exits 1 on every run until a changed record is committed; make check-orbit-record is the offline gate in CI's generated-artifacts job and step 24 of make analyze, and only a holder of an Orbit-entitled GitLab.com token and the fixture namespace can refresh the record before the provenance window closes. The recording is what found that orbit.schema sent its format as format, which Grape reserves and GitLab.com answers 406 to, that every Orbit route taking a response format refuses json (/orbit/tools takes none), and that the llm DSL grammar arrives as a JSON string, which orbit.dsl now publishes as its text.

Project Structure

gitlab-mcp-server/
├── cmd/
│   ├── server/                  # MCP server entry point and --shutdown support
│   ├── audit_1to1/              # Consolidated 1:1 SDK↔API parity audit (R-INPUT/R-OUTPUT/R-ACTION/R-META/R-ENUM + merge; R-PATH's `shapes.sent` and `shapes.typed.unsurfaced` list the fields GitLab sends that we do not publish, each with the entity condition and license tier read from `gitlab-api-live.json`, the list the field-by-field review reads, and `sent_declarations.go` answers the ones the record lists and the endpoint does not send; R-PAGE's `pagination.unpaginated` lists the actions that hand a model a list and no way to ask for the rest of it, judged against the 318 routes the same record says GitLab pages, and `pagination_declarations.go` answers the ones whose own route declares no `per_page` and whose handler does not page; -scope=sdk gates the service universe, the raw-GraphQL exemptions and the enum values; -scope=paths is R-PATH, the only rule that reads the request a handler builds rather than the surface it publishes; see Request paths below)
│   ├── audit_action_ids/        # Holds every canonical action ID the server publishes to a model against the IDs the catalog builds: the `RelatedActions` of an `ActionSpec`, the first argument of every `toolutil.HintAction` call, and a dotted ID spelled inside a `Usage` line or an individual tool's `Description`. Loaded through `cmd/internal/goprogram` and folded by the type checker rather than matched as text, because the IDs are package-local constants, fifty packages keep them in a metadata table with a lowercase `related` field, one keeps that table as a map to an anonymous struct, several hand the list in as a parameter, and two build an ID by concatenating a domain constant onto a name; a value it cannot fold is named rather than passed over. The oracle is `cmd/internal/actionids`, shared with the documentation gate: the catalog built at Ultimate twice, self-managed and GitLab.com, since Orbit's group is contributed only for GitLab.com and one build alone reports its six IDs as dead. `-check` demands the **canonical ID and not mere resolvability**: an ID that resolves only as a registered alias fails too, because `gitlab_execute_action` resolves one while `gitlab_find_action` publishes IDs, so such a cross-link works when a model follows it and can be found in no listing. The sixty spellings in that bucket were individual tool names in a `RelatedActions` list, and demanding resolvability would have left every one. A site the type checker could not fold fails as well, since a gate whose blind spot is silent is one a new site steps into, and a declaration that excuses nothing fails like every declaration table here; both declaration tables are judged only by a whole-tree run. It answers whether an ID resolves and never whether it is the right one, which is a permanent limit: being the right ID is a claim about the object an action reaches, and no set of names carries it. A fourth kind of site is read and gated too: the corrective prose a handler hands a model through `WrapErrWithHint`, `WrapErrWithStatusHint` and `NotFoundResult`, plus the struct fields a hint reaches those helpers through, since nineteen domains write it into one of their own. A `gitlab_*` tool name there is a finding whatever surface registers it, because the default dynamic surface registers none and meta registers only the bare domain tools, so the name is right for one surface of three. It opened at 785 findings in 137 packages over 1327 hints and was staged until the tree was clean; `-fix-hints` closed 712 of them mechanically, rewriting a literal only where its text is part of a folded hint (which keeps an individual tool's `Description` out: a name is correct in its `See also:` clause, the one part the manifests rewrite per surface, and one elsewhere in it is rewritten by hand) and only where the literal has a space in it (a literal without one is a name, and the rule's absence renamed the tools on the first run). Its unfoldable sites are counted apart and still fail nothing, deliberately unlike the other three rules: a published ID nobody can read is unreadable, while an unfoldable hint is a sentence a reader still reads. Issue 910 widened that rule to the rest of the served prose, where the class had moved: the message of an error a handler returns (`errors.New`, a whole `fmt.Errorf`, `toolutil.ErrorResult`, `toolutil.CancelledResult`) and a message-named field where what is written folds, the next steps `WriteHints`, `WriteListFooter` and `Card.End` write and a `NextSteps` field, `ParameterGuidance`'s `ValueSource` and `CommonConfusions`, every schema description (a `jsonschema` tag, and the `description` entry of a schema written as a map, which is what an input schema override is), and the tool names of a `Usage` line, folded as a sentence where it is assembled at run time, whose IDs stay the published-ID rule's. The sinks are a table keyed by the function's full name (`proseSinks`), and a sink's own prose parameters are never followed back out, which is what keeps a hint `WrapErrWithHint` forwards to a format from being filed under whichever kind the walk met first. A format folds to its format as written with its constant arguments after it, the verbs masked only in the judged text so the fixer still finds the literal; an argument that is a value the sentence reports (an ID, a path, GitLab's message, the error it wraps) is passed over and counted (`values_passed_over`) rather than listed, the rule's one deliberate exception to naming its blind spots, since with some four hundred formats the list would be GitLab data from end to end. `declaredSurfaceToolMentions` lets `internal/tools/dynamic` alone name its own two tools, and a declaration of either served-prose table that excuses nothing fails the run, which it used not to. The widening run found 328 over 9671 sentences, and the tree was rewritten in the change below the rule, so the gate turned on green: `-fix-hints` did the mechanical majority and `-fix-hints-tests` now also moves a test literal that pins a sentence (a rendered bullet, a whole card), read as it will be written. `internal/prompts` is outside the load, so the review prompt's action IDs are held to the catalog by a test of its own; the rule's other limits (a `WrapErr*` or `ErrRequired*` operation label, a bare meta action name such as `Use action 'list'`) are listed in `docs/development/cmd-utilities.md`. A fifth kind is the e2e suite's own quotation of that prose, because a quotation of a tool name passes against a defective hint and breaks the day the hint is fixed, which is what issue 901 was: the substrings `assertMentions`, `mentionsAny` and `containsAny` assert and the `contains` of `harness.ExpectToolError` are read out of `./test/e2e/gitlab/...` in a second load under the `e2e` tag the command states itself, found by parameter name in the callee's signature and held to the same three spellings in a section of their own (`e2e_assertions`); a predicate is judged only where its negation is the failure, so an absence check may spell a tool name; and the helper table (`servedTextAssertions`) is held to the suite, so a renamed helper or parameter fails rather than going unread. Only a run over the whole suite judges that table whole, the bare run (which loads both trees), one naming `./test/e2e/gitlab/...` itself, or one naming a wildcard that encloses it (`./...`, `./test/...`), since the suite patterns are compared once those a wildcard of the same list encloses are set aside, and any other run says it did not (`helpers_judged: false`), naming the suite's three packages one by one included; a run naming `./internal/tools/...` reads no suite (make audit-action-ids, make check-action-ids)
│   ├── audit_catalog_first/     # Enforces catalog-first registration invariants (ADR-0004), and holds every exported `ActionSpecs` under `internal/tools` to something that aggregates it: a package whose specs no production file calls publishes usage lines, aliases, tags and parameter guidance no surface serves, which is how twenty-three packages came to carry a second copy of the `gitlab_admin` metadata that had drifted from the served one word for word. The join is the call, resolved through the type checker (`cmd/internal/goprogram`), and never `OwnerPackage`: an admin action's owner is the domain package its handler lives in, so all twenty-three read healthy by that field while their own specs reached nothing. A text scan is wrong in both directions here, missing `groups` (imported as `grouptools`) and inventing `settings` (a substring of `mrapprovalsettings`), and it misses a reference that is not a call, which is what made `health` look orphaned. A package deliberately in that state is declared in `declarations.go`, where a declaration matching nothing is itself a finding; the table is empty, which is the healthy state for it (make audit-catalog-first, and step 18 of make analyze)
│   ├── audit_dead_consts/       # The half of `unused` staticcheck cannot reach: it judges a const group as one unit, so a member sharing a declaration with a member that is read is never looked at, and no `unused` setting changes it under golangci-lint v2. That group is the prevailing shape here (the action-ID block every domain keeps, the assertion-message block beside it in the tests), and the first run found twenty-five constants nothing reads. It loads `./internal/...` and `./cmd/...` through `cmd/internal/goprogram` with the test variants, since a constant a test reads is read and forty-odd packages hand their whole ID block to the catalog test through an `export_test.go`, which is also its one blind spot, a block exported wholesale being read wholesale. Exported constants are out of scope, because one may be read from a package behind a build tag this load leaves out; the packages carrying a GOOS- or GOARCH-constrained file are read again under each operating system and architecture pair the release builds, because a constant only the Windows half reads is read and so is one only the arm64 half reads, and setting the operating system alone would keep the host's architecture and leave an `_arm64.go` file out on amd64. A constant kept although nothing reads it is declared in `declarations.go` with its reason, keyed `package:name` at package scope, `package:Func.name` or `package:Type.Method.name` inside a function, and `package:func.name` inside a function literal no function declaration encloses (a package-level `var f = func() { const x ... }`), so an entry for the one never excuses a local constant sharing its name; the stale judgement is scoped to the packages the run loaded (make check-dead-consts, step 4 of `make analyze`)
│   ├── audit_discovery_completeness/ # Audits discovery metadata (aliases/usage/related/param-guidance/sibling-cluster; input-enum candidates) — META-001
│   ├── audit_doc_coverage/      # Audits docs/reference/tools/*.md vs canonical action catalog (DOC-002); reads doc-ownership.json
│   ├── audit_doc_tool_names/    # Checks every name the documentation teaches against what the server serves: the `gitlab_*` names against the ones it registers, and the `domain.action` IDs against the catalog, through the same `cmd/internal/actionids` the source gate reads. The ID half was added because the tool regex matches `gitlab_[a-z0-9_]+` and an ID carries no such prefix, so a page could pair the right tool name with an ID no surface resolves and stay green; eight did, a whole `pipeline_schedule.` family among them. Three shapes pass the dotted test and are not IDs: a file name whose stem is a domain (judged by its tail, since a page writes file names), a meta-surface manifest entry whose left half the tool rule already checks, and a short table of attributes, document paths and other software's names (make check-doc-tool-names)
│   ├── audit_dynamic_aliases/   # Audits dynamic discovery aliases
│   ├── audit_e2e_coverage/      # What the e2e suite covered, from the calls it recorded and the actions the server dispatched: every runtime x surface x mode x action classified, the levels L1 to L3, the non-tool capabilities each at the grain it varies along; `-static` is the push gate over typed action ids, and `-record`/`-check-record`/`-check-record-page` commit the per-runtime summary and gate it offline; `-check-skips` fails a complete Docker run on a skip `skip_declarations.go` does not declare for its runtime, with a category, a fragment of the printed reason and a reason, and on a declaration no skip of the run matched, read from the run's `go test -json` stream (make audit-e2e-coverage, make audit-e2e-gaps, make check-e2e-static, make e2e-coverage-record, make check-e2e-coverage-record, make check-e2e-coverage-page; make test-e2e-ce and make test-e2e-ee apply `-check-skips`)
│   ├── audit_edition_tier/      # Audits doc-grounded edition tier gating (Free/Premium/Ultimate)
│   ├── audit_gateway_chars/     # Audits served descriptions/titles for characters MCP gateway validators reject (make check-gateway-chars)
│   ├── audit_graphql_documents/ # The standalone gate over `cmd/internal/graphqldocs`: fails when a raw GraphQL document in the source is one the pinned GitLab schema refuses, naming the file and line; it loads the program with go/packages so a document assembled from a shared fragment is judged as the string GitLab receives, and reads `.graphql` files too since a go:embed var folds to nothing (make check-graphql-documents). `-live <endpoint>` introspects an instance now and judges by what it serves, refusing an answer too short to be a GitLab schema, and reports where the pin and that instance disagree about a type, field or argument one of our documents touches (make check-graphql-documents-live; `-schema` does the same against an SDL file on disk). It reads `./internal/...` only: the 42 documents client-go builds are judged by `audit_1to1 -scope=paths`, through `graphqldocs.SDKDocuments`, which reads the module directory instead and reports rather than gates. `audit_1to1 -scope=paths` folds the same result into R-PATH; two commands because this one answers a question a reader asks on its own and is what CI and the Makefile already point at
│   ├── audit_graphql_shapes/    # The other half of the exchange: pairs every GraphQL document with the struct it is decoded into (the Do call's pointer, through local variables, wrapper parameters and generic wrappers) and walks the validated selection set against it under encoding/json's rules; fails on a Go kind that cannot hold what the schema says GitLab sends, on a Go field the document never selects (always empty), on a scalar its table has no serialization for, and on a document it cannot pair; a selection no Go field reads is reported and does not fail (make check-graphql-shapes). Found the class the licensed run hit: startLine as String in the schema and int in two decoders. The same walk answers the reverse question, the one R-PATH asks of REST and nothing asked of GraphQL: `-report` writes the fields the schema offers at an object one of our decoders reads that no document of the decoding package selects (make audit-graphql-sent), which is the only dimension the eleven GraphQL-only domains appear in at all. It reads `./internal/...` like its sibling, so the operations client-go builds are outside it and the report names that set from the request inventory
│   ├── audit_install_buttons/  # Decodes every one-click install payload (base64 or percent-encoded JSON) and holds the buttons to one configuration per command (make check-install-buttons)
│   ├── audit_binary_vulns/      # Builds every target `.goreleaser.yml` names (each `goos` crossed with each `goarch`, since the operating system decides the module set) and holds each binary to the Go vulnerability database at module grain, with govulncheck's scanner run in process at the version `go.mod` pins. That is the question every scanner reading a shipped binary or its SBOM asks, and the source scan (`make govulncheck`) answered a different one, which passed on 3.0.0 and 3.1.0 while each binary carried `golang.org/x/crypto` and was reported for GO-2026-5932. A finding fails unless `declarations.go` accepts it by advisory and module with a category and a reason, and a declaration no finding matches fails too; the table is empty (make check-binary-vulns, step 25 of `make analyze`, a step of CI's govulncheck job, and the release workflow's `binary-vulns` job, which stands in front of `docker` so it never runs after an image push)
│   ├── godoc_tool/              # Consolidated Go doc auditor + fixer (was audit_godocs + add_docs)
│   ├── audit_md_escaping/       # Fails when a Markdown formatter interpolates a GitLab-authored value into a table cell, heading, list item or link without EscapeMdTableCell/EscapeMdHeading/MdTitleLink, and when one lands inside a code fence the formatter wrote by hand rather than through MarkdownFencedBlock/MarkdownCodeFence; the fence context is decided by the writes before the hole rather than by its line, since a block opens on one line and closes on another; `Card.Markdown` and `CardTable.Row` are judged at the call site like `MarkdownTableRow`; `//gitlab:allow-unescaped <expr>: <reason>` declares a value that needs none; the gate holds `internal/toolutil` to no unresolved value (make check-md-escaping). Two staged rules report without gating (`-contexts all,card,bool-time`, `make audit-md-escaping`): `card` lists every one-object card row written by hand instead of through `toolutil.Card`, and `bool-time` every flag or timestamp printed without BoolEmoji/FormatTime, excused by `//gitlab:allow-raw <expr>: <reason>`
│   ├── audit_metrics/           # Audits MCP tool/resource/prompt metrics
│   ├── audit_readonly_graphql/  # Fails when an action classified ReadOnly can reach a GraphQL mutation, which `--read-only` and a read_api token's narrowed surface would both keep (make check-readonly-graphql). The documents are `cmd/internal/graphqldocs`' inventory, the same one the schema gate judges, so a document moved into a `.graphql` file is seen here too, and the rule that says which of them carries a mutation is the inventory's as well (`graphqldocs.DefinesMutation` beside `LooksLikeDocument`), so this gate cannot judge a narrower set than the one it prints; what stays its own is what reaching a mutation means for an action classified ReadOnly. A document that inventory holds and this gate can tie to no handler, having no defining object and no literal in a body, is itself a finding rather than a silence. Which actions there are and which functions each one runs are `cmd/internal/actionrequests`' answer, shared with the derivation of what each action requests: the catalog built at Ultimate for a self-managed instance and for GitLab.com with the standalone actions, so Orbit's six reads and `discover_project.resolve` are judged too, joined to their construction sites on the canonical ID; a read-only action that meets two sites is a finding rather than a union of two actions' handlers
│   ├── audit_sdk_context/       # Fails when a call into client-go does not hand the SDK the caller's context. client-go takes it only as the `gl.WithContext(ctx)` request option and builds the request from `context.Background()` without one, so neither the action deadline nor an abandoned HTTP POST reaches it and its outbound span starts a trace of its own; `noctx` and `contextcheck` cannot see an option-carried context, and fourteen calls in four packages had shipped that way after `uploads` was fixed for it once. Every call whose callee takes request options (read from the type checker's signature, so method values, function-typed parameters and our own helpers count, under any import name) must pass `gl.WithContext` of a context that can end, a variable ever assigned one, or a request-option parameter of the enclosing function or of one around it, handed on even if reassigned (forwarding, which moves the judgement to that function's callers); a request from `NewRequest`, `NewRequestToURL` or `UploadRequest` may instead be rebound with `req.WithContext(ctx)`, and go-retryablehttp's own `NewRequest` and `NewRequestWithContext` are judged by the same rule, since `(*gl.Client).Do` sends whatever it is handed. `context.Background()` and `context.TODO()` passed directly count as none, and a `gl.WithContext` of either is reported wherever it sits among a call's options, since client-go applies them in order and a later one replaces the caller's. None of the rules reads control flow (an assignment or a rebinding counts wherever it sits), a limit the command states and a fixture pins. It loads `./internal/...` and `./cmd/...` through `cmd/internal/goprogram` **without test files**, which is its stated blind spot and includes every e2e scenario package; a build-constrained non-test file importing client-go that the load left out of a package it reached is reported as unjudged rather than skipped in silence, while a directory every file of which a constraint leaves out is not seen at all (none exists under the patterns). Exemptions are declared in `declarations.go`, keyed `package:Func`, with a category and a reason, and a declaration that excuses nothing fails; the table is empty (make check-sdk-context, step 22 of `make analyze`)
│   ├── audit_tenancy/           # Holds the tenant policy register (`internal/tenancy`, ADR-0023) to the code that enforces it, through `cmd/internal/goprogram` over `./cmd/server` and `./internal/...` less the test-support packages the server never links, loaded as `linux/amd64` whatever the host is so the verdict is the same on every machine. Fourteen rules: every site of every row, key derivation and failure resolves (G1); an Alias site is a reference to its register constant and a const keeps its typedness (G2); an Arg site's calls pass it at their index, as many times as declared (G3); a Pin keeps a literal equal in value and type (G4); an Enforce site reads what it names and a row's register functions are called (G5); no register value goes unread, and no declared alias is read only by other aliases, so an alias whose every reader has gone back to a literal fails, while one reader going back as another still reads it passes G6 and fails only where it writes the literal straight into a listed limit constructor or options literal (G10), is itself a declared Alias (G2), changed a call a declared Arg names at its index (G3), or is an Enforce site declared to read that constant (G5, none today) (G6); every refusal the authentication failure table's functions return matches one row and is charged exactly when the charge helper precedes it in its own block or an enclosing one, only the helpers spend a budget, and each failure agrees with its row's refusal on whether it is charged (G7); a refusal's stable text, status, code, `Retry-After` source and challenge are where its row says, and every gate literal of a function holding a declared gate refusal is carried by one of them (G8); a quoted reason is still in its comment (G9); nothing shaped like a limit (a listed constructor or options type outside a declared Enforce site, a refusal literal with a policy code or a 429 or 503, or such a status written with `http.Error` or `WriteHeader`, that no refusal declared in its function carries, a package-level name with a limit word in a package holding an Alias, Arg, Pin or Enforce site of a row that is not a request bound) escapes a declared site or a reasoned exemption (G10); the register's validators accept it (G11); the register stays a leaf the server links for free, with no package-level variable and no init function (G12); no number on a mintable key is called a share (G13); every variable a row names is read through the configuration package (G14), the last two unless the row carries the finding that records the departure, and a row carrying one needlessly is reported. `declarations.go` holds the exemption table (`notADecision`, 65 entries with a category and a reason each), and a stale exemption is a finding; every rule applies to every row, since the `pending` list that deferred G2, G3 and G6 while the values of issue 565 moved was deleted when the last of them had. `-compare-binaries A B` exits non-zero unless every allocated ELF section but `.gopclntab` is byte-identical, which is how a change that moves a value proves it moved no code, compared against its parent with the change's own imports of the register added as blank imports (see Adding or changing a limit) (make audit-tenancy, make check-tenancy, step 23 of `make analyze`, make tenancy-code-identity)
│   ├── audit_supply_chain/      # Audits five release-configuration invariants: SHA-pinned uses:, credentialed jobs that run no run-time-resolved code, stated Dependabot cooldowns, a current SECURITY.md, signature-verifying installers (make check-supply-chain)
│   ├── audit_surface_quality/   # Consolidated surface audit: metadata violations + output quality (was audit_tools + audit_output), plus the report-only result-envelope section driving every registered Markdown formatter with a zero and a populated fixture. `-check` makes it a gate over every rule that reads the served surface (make check-surface-quality, step 21 of make analyze); the envelope section is excluded and stays a report, since a nil render of a zero value is a guard and its ten duplicate registrations are a backlog. Two rules came with the exit code: `edition-tier` holds the tier an individual tool's description states against the lowest tier the surface serves it at, read by listing at Free, Premium and Ultimate rather than off an ActionSpec's Edition field, which the catalog aggregation overwrites per domain so a spec can disagree with its own description and nothing observes it; and `constant-index` reports a list formatter that renders the head of a slice in every element's place, which is readable at all only because the audit fills its fixtures through its own text function, spelling the whole field path rather than the field's name so the two elements of a slice of structs differ
│   ├── audit_test_goroutines/   # Audits testing.T aborts made off the test goroutine (A/B categories, --check gate)
│   ├── audit_test_names/        # Audits test function naming compliance; -check-files gates test-file naming (make check-test-file-names)
│   ├── audit_test_subtests/     # Audits case loops that assert without a t.Run subtest; -fix rewrites the unambiguous ones (make check-test-subtests)
│   ├── audit_tokens/            # Audits token usage for model-facing surfaces (+ --compare-schemas sizing spike)
│   ├── bench_resources/         # Measures what the server costs to run (CPU, memory) and draws the charts the docs publish (make bench-resources); the concurrency series steps one HTTP process up to a thousand credentials, profiling it through --pprof-addr, and -no-render measures on a host with no checkout. `-fairness <bound>` (make bench-fairness) is a separate mode: two populations of credentials driven differently, measured with the bound in force and without it, reporting the quiet population's served and refused counts apart and able to answer that the bound helped nobody; a bound no switch turns off, the OAuth verification ceiling (`oauth-verification`, register row `ADM-014`), is compared against a second build of the checkout with the one declaration that sizes it replaced through the go command's `-overlay`, driven by a flood of invented tokens against a stand-in GitLab. It writes bench/fairness.json, which is not committed, and draws nothing, so it never touches the record or the charts `-check` compares. `-held <counts>` (make bench-held) is another mode of its own: a ladder of tools/call held open at once against a stand-in GitLab that holds every project read, sampling at each step the server's descriptors (from `/proc/<pid>/fd`), goroutines, live heap, resident set and whether `/health` still answers, then how every call ended once released; `-held-nofile` starts the server under a hard descriptor limit through `/bin/sh` and `ulimit -n`, since Go raises its soft limit to the hard one at startup, and `-held-credentials` spreads the calls. It writes bench/held.json, which is not committed, and is the measurement register row `HLD-011`'s derivation was sized from. `-sessions <counts>` (make bench-sessions) is a mode of its own for the `--stateless=false` transport: a ladder of sessions, each an `initialize` on 2025-11-25 and `notifications/initialized`, spread round robin over `-sessions-credentials`, with `-sessions-stream` holding each one's standalone GET open; each step is settled and sampled as a held step is, the sessions the server still holds are counted by pinging each (stopping at the first ping nobody answered), and every open is filed as opened, refused or failed. `-sessions-nofile` starts the server under a hard descriptor limit as `-held-nofile` does. It writes bench/sessions.json, not committed, and is the measurement register row `HLD-010` was sized from
│   ├── gen_model_corpus/        # Renders the model evaluation corpus breadth ledger: which catalog actions, domains and tiers the corpus asks a model to reach, counted against the catalog this tree builds. Breadth and never coverage
│   ├── gen_model_results/       # The fold: a model evaluation run's observation shards into the committed record, scored here and not there, and the record into the published pages and README blocks. A run writes observation and no verdict, so a scoring rule corrected today re-scores a past run from its shards without spending a token (`-refold`, each dropped row named); a second fold of a run already published is refused rather than replacing it, and a run whose shards were not kept cannot be re-scored at all. `-check` is the offline gate
│   ├── format_md_tables/        # Formats Markdown pipe tables in README.md and docs/
│   ├── gen_action_catalog_manifest/ # Generates audited action catalog manifest
│   ├── gen_api_live/            # The one oracle here that is **evaluated rather than parsed**: boots a released `gitlab-ee` image, asks the loaded Rails application what its REST API is through one `gitlab-rails runner` script, and writes `docs/development/gitlab-api-live.json` (make gen-api-live). It carries every Grape entity with the fields it exposes, the entity each field renders with and the condition gating it **with that condition's text read back from inside the image**; every mounted route with the entity its `desc` annotates and its params with type, requiredness and default; and the licensed-feature table evaluated. An exposure declared `merge: true` is marked, and `apilive` resolves it into the keys it contributes instead of a key of its own: it sends its child's keys on the parent and none of its own, so reading it literally inverted both directions of the comparison at once (a member "carrying" a `user` object it never sends, while the nine `UserBasic` keys it does send read as invented by us), which cost 34 phantom findings and hid 16 real ones. `-check` gates the committed record with no Docker and no network (make check-api-live), refusing a record too small to have come from a GitLab, one holding an entity that refused to describe itself, one holding a condition that carries neither text, hash nor symbol (schema version 2 recorded all 41 hash and symbol conditions of 19.3.1-ee as their kind alone, so the fields they gate read as sent on every response; the generator refuses to write such a record too), or one past the shared staleness window. It needs **no licence and no fixtures**, because a licence gates `feature_available?` when a request is served and not when a class is defined. Why it exists: a scan of the same Ruby cannot see a name that is not written down, and `GeoSiteStatus` exposes ~600 fields by iterating a constant assembled from two method calls, so the source says "expose the loop variable"; measured against the scanned record with inheritance resolved, 551 of 582 entities agree and the 31 that do not hold 1935 fields the scan never saw. Since schema version 4 the same boot records what a fine-grained token needs (issue 952): each route's `authorization` key for key, the `granular` vocabulary (every assignable permission with its raw expansion and GitLab's words for it, the assignable GitLab names for each raw permission and the first one a token can be granted, and the anonymous policy evaluated on an unsaved public project and group with every feature and licence available), and `graphql_authz` (each object type's enforcement, directives and object-typed field signatures, every union and interface with its members, every mutation, and the undeclared set computed with GitLab's own todo rule, held to the `authorization_todo.txt` the image ships); a route with no `authorization` now declares nothing rather than going unrecorded, which is why the version moved, and `-check` refuses either block missing or holding a shape a reader would misread, and a `source` block whose figures are not what the content gives
│   ├── gen_action_grants/       # Derives what every catalog action sends from its handlers (`cmd/internal/actionrequests` for the handlers, `cmd/internal/sdkroutes` for what each client-go method sends, the statements read as sequences, alternatives and optional requests, a `//gitlab:request mandatory|optional|alternatives: <reason>` directive where the syntax is wrong) and joins each request to what `gitlab-api-live.json` declares a fine-grained personal access token needs for it (REST routes with their primary and additional scopes; GraphQL positions along the answer spine, a non-null chain carried onto it, an abstract position judged as its worst member, an undeclared mutation refused and an undeclared payload committed and answered null), writing `docs/development/action-requests.json`, `internal/tools/actiongrants/table_gen.go` (keyed literals of constants, so the server runs no code to build it) and `docs/reference/fine-grained-permissions.md` (make gen-action-grants). Requests keep the order the handler makes them, which decides the refusal a path reports: a lookup no token passes stops the write after it, so the write never commits. What the walk or the record cannot answer is declared with a category and a reason (`request_declarations.go`, `grant_declarations.go`, the epic positions GitLab declares at the project boundary only among them), and a declaration that answers nothing is a finding. It loads the program and builds itself with `table_gen.go` replaced by `table_stub.go.txt`, so a table a type change broke cannot stop its own regeneration. `-check-derivation` fails on any finding and on three gates (a second request on a path no directive qualifies, a denial naming something the record does not hold, a way of running that sends nothing) and is never deferred (make check-action-grants-derivation, step 26 of make analyze); `-check` compares the three artifacts (make check-action-grants, step 27)
│   ├── gen_brand/               # Emits every vector brand asset from one parametric geometry (mark, favicon, banner/OG/social cards, in-binary svgBrand)
│   ├── gen_graphql_schema/      # Pins a GitLab GraphQL schema by introspecting a live instance, writing internal/graphqlschema/gitlab-schema.graphql (SDL as text, so a re-pin is a readable diff) and source.json (make gen-graphql-schema); --check gates the committed pair without network, refusing a pin of another instance, a truncated answer, a record whose type count is not what the schema beside it loads with, an unrecorded version, a retrieval date nothing can read or that has not happened, or a pin past the staleness window `cmd/internal/provenance` records (make check-graphql-schema)
│   ├── gen_icon_webp/           # Regenerates light/dark WebP icon fallbacks from icons.go (maintainer-only, requires rsvg-convert + cwebp)
│   ├── gen_orbit_record/        # Records what GitLab.com's six Orbit routes answer the requests the handlers build, through a recording proxy on the loopback interface, reads only, with GITLAB_COM_TOKEN: docs/development/orbit-responses.json holds per call the action, the output type returned, the parameter names sent and the answer's key tree with its kinds and never a value (make gen-orbit-record, run by make test-e2e-gitlab-com). A recording refuses a fixture namespace the indexer has not reached; a re-recording prints every key added, dropped or changed against the record committed at HEAD, read through git, and exits 1 on every run until a changed record is committed; -check gates the committed record offline: GitLab.com, a version and a namespace, every expected call once and answered 200, a tree that hangs together and holds only key names, the provenance window, and the canonical form (make check-orbit-record)
│   ├── gen_lhm_manifest/        # Generates the capability arrays in lhm.plugin.json (LobeHub)
│   ├── gen_llms/                # Generates llms.txt and llms-full.txt for LLM discovery
│   ├── gen_request_inventory/   # Merges the request shards the unit suite records into docs/development/request-inventory.json, the committed answer to what this server sends GitLab (make gen-request-inventory); -check gates it, -v names the packages the catalog owns actions in that issued nothing
│   ├── gen_stats/               # Generates README stats section from codebase metrics
│   ├── gen_testing_docs/        # Generates docs/development/testing/testing.md
│   ├── gen_third_party_notices/ # Writes THIRD_PARTY_NOTICES at release time: the license, notice and patent texts of the Go standard library and of every module the release binaries link, read from each binary's own build information (`debug/buildinfo`, the list `go version -m` prints) and the module cache, merged across targets with a module only some targets link said so, plus the license files in the directory of every package a binary links and of each parent of one below its module root, listed per binary with `go list -deps` under the settings it records (issue 1137); refuses binaries of different builds, a target list other than `-targets`, a package listing that disagrees with a binary's build information in either direction, a module the cache lacks, one replaced by a local directory and one publishing no license file. GoReleaser runs it as the `third-party-notices` entry of `sboms`, after the builds and before `checksums.txt` is signed; the Dockerfile's builder runs it against the image's binary and `make mcpb` against the binaries it builds
│   └── internal/                # Helpers shared by the commands: actionrequests (which functions run when a catalog action is called and what they put on the wire: every `ActionSpec` construction resolved to its action name, its individual tool name and its handlers, joined to the catalog on the canonical ID, then walked with no depth bound through function literals, the function a route helper was handed, and package-level variable initializers, recording per body the GraphQL documents named, whether it reaches the GraphQL transport, and the client-go service methods it names; `cmd/audit_readonly_graphql` reads it and so does the fine-grained permission derivation of issue 952), sdkroutes (the one reader of which request each client-go service method sends, the verb and path of a REST method and the documents of a GraphQL one, keyed as actionrequests records them, following delegation into helpers with the constants a caller hands them and folding a legacy `NewRequest` path; R-PATH cuts its route views from it), actionids (the one reader of the canonical action IDs this repository publishes, and through `Catalogs` of the two catalog builds those IDs come from, and the one rule for spotting one inside prose: the catalog built at Ultimate for a self-managed instance and for GitLab.com together, the aliases that resolve to one of those IDs kept apart from the IDs themselves, and the test that decides which dotted token in a sentence is offered as an ID, which is that either half is one the catalog uses. Two gates ask the same question of two corpora, `cmd/audit_action_ids` of the source and `cmd/audit_doc_tool_names` of the documentation, and a spelling one accepts cannot be one the other refuses), apidocs (GitLab API doc fetcher, and the doc/api page listing R-PATH reads through it), apilive (the shape of the record a booted GitLab produces, and the one reader of it: entities keyed by their Ruby name, the routes indexed by the entity each renders, the tier a set of licensed features resolves to under the same highest-rank-wins rule the scanned record uses, and the translation to the OpenAPI record's own spelling so a reader holding one entity name can look up the other), auditshared, docgen (the one way a generated artifact is written and the one way a gate reports it stale: the write-or-check pair every generator calls, the containment the write happens under, the file mode that convention settled on, and the newline normalization two commands used to hold the same bytes to in their own copies; the managed-section replacement stays beside it and writes with the same mode, which never applies to the file it rewrites), graphqldocs (reads every raw GraphQL document out of the source, `.graphql` files included, and judges it against a schema for the two of its four callers that ask for that; `cmd/audit_readonly_graphql` takes the inventory and the one rule that says which of its documents carries a mutation, `DefinesMutation`, made of the same reading as `LooksLikeDocument` so no caller can judge a narrower set than the one it reads, and `cmd/audit_graphql_shapes` takes it to name a document no decoder pairing of its own carries. `SDKDocuments` points the same walk at client-go's own module for R-PATH, with the environment a module-cache load needs and the rule that tells a template shell from sendable text), graphqlintrospect (one introspection and SDL conversion for gen_graphql_schema and the live re-probe), golist (the row shape the two commands that enumerate packages through `go list` ask for and parse back, and the GOROOT-joined `go` binary they run rather than a PATH lookup; each keeps its own patterns, tags, bound and runner. `audit_binary_vulns` (`go build`) and `gen_third_party_notices` (`go env`, and `go list -deps` with a row format of its own, naming each package's module rather than its directory) run that binary too), goprogram (the one go/packages front end for the ten packages that type-check this repository's own source without NeedDeps, `audit_tenancy` the latest of them: the load mode, the config, the overlay their fixtures need, the test variants four of them ask for and the build tags two of them pass, the environment the one load of somebody else's module states, and the rule that a package which did not type-check stops the run), mcpsurface (the one reader of the served surface: the per-surface listings, the offline stub client, the served-schema chain and the memo behind them), orbitrecord (the committed record of what GitLab.com's Orbit routes answered, its canonical form, the offline problems check and the key-tree diff, shared by `cmd/gen_orbit_record` and R-PATH), provenance (the age verdict the three commands that pin an external truth pass on their committed record, whose arithmetic two more read: the retrieval date's arithmetic, the default clock, the three ways a date fails, and the one staleness window with its one recorded reason, which is stated there and nowhere else; each command keeps its own Source type, floor, identity checks and dialect), requestinventory (the committed record of what this server sends GitLab, and the one definition of which catalog actions it covers), testsource (one "is this a Go test" predicate, one test-name classifier and one walk policy for the five commands that read `_test.go` files, the not-our-source half of it delegated to `internal/sourcewalk`; discovery stays with each of them)
├── internal/
│   ├── cachehints/              # SEP-2549 cache hints (ttlMs/cacheScope) on MCP results
│   ├── capguard/                # Keeps the methods answered in step with the capabilities declared
│   ├── clientcompat/            # Per-client response compatibility profiles (GITLAB_MCP_CLIENT_COMPAT)
│   ├── cmdutil/                 # Shared helpers for the repository commands (Must at the leaf)
│   ├── config/                  # Configuration loading (dotenv files, flags, env vars, HTTP env overlay)
│   ├── edition/                 # Licensing tier model (Free/Premium/Ultimate) used to gate tools
│   ├── finegrained/             # What a fine-grained personal access token needs for each action (issue 952): the table types the generated table is written in (permissions and the words GitLab grants and refuses them by, assignables with their boundaries, groups, operations, GraphQL elements on and off the answer spine, one requirement per action with its paths or the denial that withholds it), `Judge` and `Evaluate`, which decide what a token is worth from its grant (phase B) or without it (phase A, with the reason it fell back), `Decide` and `Lists` for the call and the listing, the withheld text a model is told, the grant decoder, and `Describe`, the one wording of a requirement that the `fine_grained` block of `gitlab://tools/{id}` and the reference page share. A leaf the server links, importing nothing of this repository but `internal/tenancy`, whose `CoverableAt` (row `AUT-008`) says what one granted scope covers
│   ├── freshness/               # The one reader of `GITLAB_MCP_TEST_SNAPSHOT_PARITY`: whether this run compares a committed generated artifact or leaves it to the run that refreshes it. Test-only, like `internal/testutil`, and named beside it in `TestDependencies_TestSupport_NeverReachesTheServerBinary`
│   ├── gatewaycompat/           # Description/title rewriting for strict MCP gateway validators
│   ├── gitlab/                  # GitLab API client wrapper (client.GL() accessor)
│   ├── graphqlschema/           # The pinned GitLab GraphQL schema (embedded SDL as text + source.json provenance) and Validate(); loaded once per process behind a sync.Once. Validate walks the variables itself for enum case, since gqlparser compares enum values with EqualFold and GitLab does not
│   ├── mcpotel/                 # OpenTelemetry instrumentation of MCP request handling (API only, no SDK)
│   ├── oauth/                   # OAuth HTTP mode: token cache, GitLab verifier, header middleware, RFC 9728 metadata
│   ├── serverpool/              # HTTP mode: bounded LRU pool of per-token+URL MCP servers (with observability metrics)
│   ├── sourcewalk/              # The one answer to which directories below a walk root are this repository's own source, for everything that walks the tree, the audit commands and the repository-sweeping tests alike: a name rule pruning dot-directories, which is Go's own rule for `./...`, and a marker rule pruning any directory holding a `.git` entry, which is what a linked worktree and a clone both carry. The second exists because the parallel-agent tooling puts a complete worktree of this repository per running agent under `.claude/worktrees/`, and a walk that reads one folds another branch's files into its answer without saying so: the crash when a worktree vanished mid-walk was the benign half, and a guardrail in `internal/toolutil` that swept two hundred copies of the tree into a ten-minute timeout was the loud one. Under `internal/` rather than `cmd/internal/` because Go confines the latter to importers under `cmd/`, and three of the walkers are tests in `internal/config`, `internal/toolutil` and `test/e2e/internal/harness`; a second copy for them is the drift this package exists to end. `SkipDirBelowRoot` is the rule over native paths and `SkipDirBelowRootFS` the same rule over an `fs.FS`, for a sweep that scoped itself with `os.Root` and must not step outside it to probe the marker. Each walker keeps its own extra names, since those say what that walk is not interested in rather than what is not ours; every rule judges a directory a walk descends into and never the root it was pointed at, because the repository root holds `.git` and a walker applying the marker rule to its own root would walk nothing and report a clean tree
│   ├── subscriptions/          # resources/subscribe: polled watchers, cadence, leases (ADR-0015)
│   ├── tenancy/                 # The tenant policy register (ADR-0023): the key vocabulary with what each key costs a caller to mint, one row per requirement of `docs/development/tenant-policy-spec.md` with its key, class, value source, zero meaning, capacity behavior, refusals and sites, the policy values and refusal codes the layers read, the authentication failure table, the carried-channel matrix, and `Validate`, which refuses a share on any mintable key, a per-caller ceiling on a process resource with no process partner and a refusal on a channel its method cannot carry. It decides and never enforces; a leaf importing only `errors`, `fmt`, `strings` and `time`, with no package-level variable and no init function, so importing it adds no initialization work and a layer that aliases one of its constants compiles to the same instructions and data. Five rules are promoted into it and called by the layers (`MeterFor`, `Busy`, `BudgetOn`, `EscalationOn`, `TransportSourceBudgetOn`), each held by an oracle test and a fuzz target to the code it replaced; see Adding or changing a limit
│   ├── telemetry/               # The one place that knows the OpenTelemetry SDK: exporters, identity policy, metric views
│   ├── toolutil/                # Shared tool utilities (errors, pagination, markdown, logging)
│   ├── testutil/                # Shared test helpers (NewTestClient, RespondJSON)
│   ├── tools/                   # Tool orchestration layer + 180 internal/tools packages
│   │   ├── action_catalog.go    # Builds the canonical action catalog from domain ActionSpecs (pruneSchemaFieldsByTier)
│   │   ├── actiongrants/        # The generated fine-grained table (`table_gen.go`, written by `cmd/gen_action_grants`, never edited) and its two readers, `Table()` and `Requirement(id)`; the catalog sets each action's `FineGrained` from it by canonical ID, and a test holds that the table compiles to data with no init work
│   │   ├── catalog_filter.go    # FilterActionCatalog: read-only, token-scope and --exclude-tools filters, with what each removed
│   │   ├── scope_filter.go      # MetaToolScopes and FilterScopeFilteredCatalog: the PAT scopes a catalog group needs, applied to the catalog before registration so one map reaches all three surfaces (see PAT scope filtering below)
│   │   ├── register.go          # RegisterAll() — projects individual tools from the canonical action catalog
│   │   ├── register_meta.go     # RegisterAllMeta() — registers catalog-backed meta groups and standalone surfaces
│   │   ├── dynamic/             # Low-token dynamic find/execute surface over catalog routes
│   │   ├── dynamiccatalog/      # Build(): the dynamic catalog assembled the way the server assembles it (cmd/server and the e2e suite alike)
│   │   ├── toolvisibility/      # Apply(): the pass over the tools registered outside the catalog (exclusions, read-only removal, safe-mode wrapping with the catalog-backed dispatchers exempt), run after registration by cmd/server and by the surface evaluator alike
│   │   ├── markdown.go          # Thin delegator to the type-based Markdown registry (toolutil.MarkdownForResult)
│   │   ├── meta_tool.go         # Route wrappers (wrapAction, wrapVoidAction, routeAction) and the meta parameter-schema mode; AddMetaTool/AddReadOnlyMetaTool live in toolutil/meta_tool.go
│   │   ├── achievements/        # Achievement definitions and their awards (GraphQL, cursor-paginated)
│   │   ├── branches/            # Branch & protected branch tools
│   │   ├── cilint/              # CI lint tools
│   │   ├── civariables/         # CI variable tools
│   │   ├── commits/             # Commit tools
│   │   ├── dependencyfirewall/  # Dependency Firewall package evaluation (Premium, flag-gated)
│   │   ├── deployments/         # Deployment tools
│   │   ├── elicitationtools/    # Interactive creation flows (MCP elicitation)
│   │   ├── environments/        # Environment tools
│   │   ├── files/               # Repository file tools
│   │   ├── groups/              # Group tools
│   │   ├── health/              # Health/version check tools
│   │   ├── integrations/        # Project and group integration tools (incl. group Datadog)
│   │   ├── issuelinks/          # Issue link tools
│   │   ├── issuenotes/          # Issue note tools
│   │   ├── issues/              # Issue CRUD tools
│   │   ├── jobs/                # CI job tools
│   │   ├── labels/              # Label tools
│   │   ├── members/             # Project member tools
│   │   ├── mergerequests/       # Merge request CRUD tools
│   │   ├── milestones/          # Milestone tools
│   │   ├── mrapprovals/         # MR approval tools
│   │   ├── mrchanges/           # MR changes/diff tools
│   │   ├── mrdiscussions/       # MR discussion tools
│   │   ├── mrdraftnotes/        # MR draft note tools
│   │   ├── mrnotes/             # MR note tools
│   │   ├── packages/            # Package registry tools
│   │   ├── pipelines/           # Pipeline tools
│   │   ├── pipelineschedules/   # Pipeline schedule tools
│   │   ├── projects/            # Project CRUD tools
│   │   ├── releaselinks/        # Release link tools
│   │   ├── releases/            # Release tools
│   │   ├── repository/          # Repository tree/compare tools
│   │   ├── search/              # Search tools (code, MRs, issues, etc.)
│   │   ├── projectdiscovery/   # Git remote URL to GitLab project resolution
│   │   ├── tags/                # Tag tools
│   │   ├── todos/               # Todo tools
│   │   ├── uploads/             # Project upload tools
│   │   ├── users/               # User tools
│   │   └── wikis/               # Wiki tools
│   ├── resources/               # 45 MCP resource implementations
│   ├── prompts/                 # 37 MCP prompt implementations
│   ├── completions/             # 18 argument completion types
│   ├── progress/                # MCP progress notifications
│   ├── elicitation/             # MCP elicitation capability
├── docs/                        # Project documentation (Diátaxis framework, audience-first)
│   ├── getting-started.md       # First run
│   ├── guides/                  # How-to: installation, IDE configuration, OAuth app setup, fine-grained tokens, HTTP server mode, remote deployment, enterprise deployment, telemetry, client compatibility, examples/
│   ├── reference/               # Reference: cli.md, configuration.md, env.md, output-format.md, resources.md, prompts.md, fine-grained-permissions.md (generated), tools/ (per-domain), capabilities/, benchmarks/
│   ├── concepts/                # Explanation: architecture, dynamic tools, meta-tools, error handling, GraphQL, security
│   └── development/             # Contributor docs: adr/ (Architectural Decision Records), testing/ (generated), static analysis, cmd utilities, tool surfaces
├── test/e2e/                    # End-to-end integration tests
│   ├── http/                    # HTTP transport module (`httpe2e`): cross-origin, preflight, auth modes, rate limiting, nginx layer, and a balancer layer (nginx + HAProxy in Docker) for affinity, drain-window ejection and fleet digest agreement. Needs no GitLab
│   ├── stdio/                   # stdio transport module (`stdioe2e`): drives the real binary over pipes. Needs no GitLab
│   ├── collector/               # OTLP collector acceptance module (`collectore2e` tag): a real receiver accepts what the server exports (make test-e2e-collector)
│   ├── orbit/                   # `orbitlive`-gated live tests against GitLab.com's Knowledge Graph API
│   ├── docker-compose.yml       # Ephemeral GitLab CE + Runner + fixture service for Docker mode
│   ├── .env.docker              # Docker mode environment variables
│   ├── README.md                # E2E documentation
│   ├── scripts/                 # E2E provisioning scripts (setup, runner, wait, Bitbucket, EE activation)
│   ├── internal/harness/        # The one route from a test to a server: the binary, the session, the fixtures, the ledger, the waits, the surfaces and the coverage shards. Carries `e2e`, so only the packages below can import it
│   └── gitlab/                  # The suite that drives the real binary against a real GitLab, one package per runtime
│       ├── common/              # What any instance serves (171 test files)
│       ├── ce/                  # What only an unlicensed instance does (4)
│       └── ee/                  # Premium and Ultimate (46)
├── plan/                        # Untracked working area for plans and audit reports: ignored by git and never committed. `make check-plan-untracked` (a CI step beside the em dash check) fails on a file force-added there
├── mcpb/                        # Claude Desktop extension (.mcpb) manifest, icon, platform.jq (which derives the manifest of each per-OS bundle from the universal one) and linux/launch.sh, the Linux entry point that picks the amd64 or arm64 binary by uname -m (packed, measured and checked by scripts/build-mcpb.sh, one bundle per operating system plus the universal one; tests in scripts/mcpb_launch_sh_test.py for the launcher, scripts/mcpb_manifest_test.py for the manifest and its derivation and scripts/build_mcpb_sh_test.py for the build script's checks, size limits and the files it packs from both dist/ layouts)
├── .github/                     # AI assistance infrastructure
│   ├── copilot-instructions.md  # GitHub Copilot context (auto-loaded by VS Code)
│   ├── agents/                  # 7 specialized AI agents
│   ├── skills/                  # 18 reusable skill templates
│   └── instructions/            # 8 coding standard instruction files
├── Makefile                     # Build, test, lint targets
└── VERSION                      # Semantic version (3.1.0)

Editing files

Change existing files with the Edit tool and create them with Write. Do not edit files by writing Python, sed or perl scripts, and not even when an automatic mode suggests preferring shell commands for file work.

Edit verifies that the target text still matches before writing, and applies atomically, so a stale assumption fails loudly instead of corrupting the file. A script does neither: an anchor that no longer matches will delete or duplicate a declaration and leave a file that does not parse. Shell commands stay right for running, searching and generating; a script is justified only for a bulk mechanical rewrite across many files, and the result must be verified to build.

Key Development Patterns

Adding a New MCP Tool

  1. Create internal/tools/{domain}/ sub-package directory, with a doc.go holding the package comment (every package keeps it there; go run ./cmd/godoc_tool/ audit reports one anywhere else)
  2. Create {domain}.go with typed input/output structs (no domain prefix — package provides namespace). A multi-word name separates its words with underscores in the file only: merge_requests.go in package mergerequests, since Go's convention and the stylecheck/revive naming rules refuse underscores in package identifiers and directories follow the package
  3. Create {domain}_test.go with table-driven tests using testutil.NewTestClient and httptest; the test file carries the module's name, underscores included (merge_requests_test.go)
  4. Add or update domain-local ActionSpecs so the action has one canonical route, owner package, metadata, compatibility policy, individual projection metadata, and tests.
  5. If the domain is new, update the generated/audited catalog aggregation path rather than adding ad hoc root registration calls.
  6. Add markdown formatters in the sub-package markdown.go init() function using toolutil.RegisterMarkdown[T] with appropriate content annotations (ContentList, ContentDetail, ContentMutate)
  7. For list formatters: add toolutil.HintPreserveLinks as the first hint in WriteHints() to instruct the LLM to preserve clickable links
  8. Add clickable [text](url) links in Markdown table columns where applicable (MRs, issues, pipelines, etc.)
  9. Meta-tools automatically get next_steps in JSON via enrichWithHints() — no extra work needed
  10. Update docs/reference/tools/{domain}.md and docs/reference/tools/README.md
  11. After completing a test-focused tool implementation phase, run go run ./cmd/gen_testing_docs/ or make gen-testing-docs to refresh docs/development/testing/testing.md, then verify with go run ./cmd/gen_testing_docs/ --check
  12. Write an end-to-end scenario for the action under test/e2e/gitlab/, and declare its ID as a typed harness.ActionID constant in that package's actions_test.go — common for an action any instance serves, ce for one only an unlicensed instance does, ee for Premium or Ultimate. This is a gate, not a suggestion: make check-e2e-static (cmd/audit_e2e_coverage -static, run by make analyze and by CI's compile job) fails on a catalog action no scenario names. An action nothing on a Docker instance can run is declared in cmd/audit_e2e_coverage/exemptions.go with a category and a reason, and a declaration that stops describing the tree is itself a finding. A string literal at the call site is invisible to the gate, which reads typed constants out of the type checker's record

See docs/reference/output-format.md for the complete response format specification.

Tool naming convention

A tool's runtime name depends on the surface, and on the individual surface it is declared, not derived — IndividualTool.Name in the domain's ActionSpec — so never infer one from a formula.

  • Individual surface (GITLAB_MCP_TOOL_SURFACE=individual): the prevailing form is domain-first gitlab_{domain}_{action} — issue.list is gitlab_issue_list, project.get is gitlab_project_get, branch.create is gitlab_branch_create. A large legacy set is verb-first instead (gitlab_list_issue_discussions, gitlab_get_issue_statistics, gitlab_add_ssh_key), and both forms are real. New actions take the domain-first form.
  • Meta surface (GITLAB_MCP_TOOL_SURFACE=meta): mostly the bare domain — gitlab_issue, gitlab_project, gitlab_group — with the operation in the action argument, alongside a few standalone tools (gitlab_discover_project, gitlab_server, the gitlab_interactive_* elicitation flows). A domain without a meta-tool of its own is a set of routes on a base one, not a tool: epics, labels, milestones, boards, members, wikis and releases at group scope are actions on gitlab_group; issue discussions and statistics are actions on gitlab_issue; todos are actions on gitlab_user.
  • Dynamic surface (the default): only gitlab_find_action and gitlab_execute_action, which take the canonical catalog ID directly — {"action": "issue.list", "params": {…}}. This is the portable form for an example, because it does not depend on GITLAB_MCP_TOOL_SURFACE.

Every documentation example must name a tool the surface it shows actually registers, and say which surface that is: an individual-tool example without GITLAB_MCP_TOOL_SURFACE=individual is wrong twice over, since the default surface registers neither. go run ./cmd/audit_doc_tool_names/ checks every gitlab_* mention and every domain.action ID across docs/, site/src/content/docs/, README.md and this file against the names the server registers and the catalog it builds; --check makes it a gate. The same demand holds inside the server's own output: make check-action-ids fails when a RelatedActions entry, a toolutil.HintAction argument or a dotted ID in a Usage line is not a canonical catalog ID, an alias included, and when any sentence the server serves (an error hint or message, a refusal, a next step, parameter guidance, a schema description in a jsonschema tag or a schema map, a Usage line, or an individual tool Description) names a gitlab_* tool. Two places may name one: internal/tools/dynamic, its own two tools, and the See also: clause of a domain action's individual tool Description, the one part gitlab://tools rewrites into each surface's names; the rest of a constant Description is read like a Usage line, and one assembled at run time is held to the same by TestToolManifest_ServedDescriptions_NameNoToolOutsideTheirSeeAlsoClause in internal/resources, since gitlab://tools serves a domain action's Description verbatim on the dynamic and meta surfaces as well. A standalone surface tool's description is not one of them: the guided flows and discover_project.resolve are registered on meta and individual and served as their Usage on dynamic, so each writes its one text as its Usage as well, where the rule reads it. The rule's limits are stated in docs/development/cmd-utilities.md (The rule over served prose): it does not read the operation label a WrapErr* or ErrRequired* call prefixes an error with, which is sometimes spelled as a tool name, a value a format reports, a bare meta action name (Use action 'list'), or internal/prompts and internal/resources, which are outside its load.

Error handling in tool handlers

Four error wrapping functions in internal/toolutil/errors.go, used across the 180 packages under internal/tools/:

  • WrapErr(op, err) — read-only operations (list, get, search). Generic classification only.
  • WrapErrWithMessage(op, err) — mutating operations (create, update, delete). Includes GitLab-specific error detail via ExtractGitLabMessage.
  • WrapErrWithHint(op, err, hint): when a specific corrective action is known (e.g., "use branch.unprotect first", naming the action by its canonical ID). Includes detail + actionable suggestion.
  • WrapErrWithStatusHint(op, err, code, hint) — combines IsHTTPStatus check + WrapErrWithHint in a single call. Use when the hint applies only to a specific HTTP status code; returns WrapErrWithMessage for all other codes.
  • NotFoundResult(resource, identifier, hints...): for get handlers when IsHTTPStatus(err, 404). Returns an informational CallToolResult with IsError: true and domain-specific hints instead of a Go error. Logged at INFO level. Used by the get handlers of 22 domains, each through a helper in its markdown.go, whose route is wrapped with ActionRoute.WrapNotFound, which hands the output's builder the arguments with the documented aliases resolved as the handler read them, and names the identifier through toolutil.ParamText so a numeric id reads as the caller wrote it. Defined in internal/toolutil/not_found.go.

Use IsHTTPStatus(err, code) and ContainsAny(err, substrs...) for status-specific branching before calling WrapErrWithHint. A hint that names a role, a license or an owner is keyed on IsPermissionRefusal(err) instead of a status: GitLab refuses a missing permission with 401 at the routes of entry 55, so a hint scoped to 403 is never shown there, and a hint keyed on 401 alone would follow the verdict that the token itself was refused. The predicate is true for a REST 401 or 403 whose body carries no RFC 6750 error code and does not refuse the account itself, as the API guard's plain 403 for a blocked or deactivated account does (gitlabclient.RefusalMayBePermission), and a route whose 403 means something else pairs it with IsHTTPStatus. A refusal of a fine-grained token's grant is neither: ClassifyError describes it with the permission GitLab names, IsPermissionRefusal is false for it, and WrapErrWithHint drops the handler's hint from it, so a 403-keyed hint never follows it either. A GraphQL mutation handler decodes its payload as a pointer beside the top-level errors, because a refused mutation answers with the payload null and its reason there, and returns GraphQLTopLevelError when the payload is absent. For get handlers, check IsHTTPStatus(err, 404) before LogToolCallAll and return NotFoundResult with nil error to log at INFO instead of ERROR. See ADR-0007 and Error Handling.

Every client-go call carries the handler's context

client-go takes the caller's context only as a request option and builds the request from context.Background() without one, so every SDK call passes gl.WithContext(ctx), and a request built with NewRequest, NewRequestToURL or UploadRequest carries it among its options or is rebound with req = req.WithContext(ctx) before it is sent. A call without it compiles, answers correctly and passes its tests, while the action deadline, an abandoned HTTP POST and the outbound trace all lose it; that shipped in five packages before anything checked. make check-sdk-context (cmd/audit_sdk_context, step 22 of make analyze and a CI step) is the gate, and testutil.CancelOnArrival is the fixture that proves a handler passes it: its context ends when the first request reaches the mock, so a handler returns context.Canceled promptly only if that first request carried the context, and any request that sits out the mock's hold, having been sent without it, fails the test at cleanup (a later request carrying the context would be refused by the transport and read as the cancellation, so the return value alone proves only the first).

Adding or changing a limit

Every decision about who a caller is and what it may hold, spend or be told (a ceiling, a rate, a budget, a lifetime, what zero means for a setting, a refusal with its channel and code) is decided in the tenant policy register, internal/tenancy (ADR-0023), and enforced where the resource is counted: the register decides and never enforces, and the layer applies the answer it reads there. A limit written as a literal in the layer that enforces it is the shape issue 565 retired, because the question that decides the hardest of them, whether a caller can mint another value of the key the limit is counted on, had to be rediscovered by hand every time. The procedure:

  1. Write the row in the family file of internal/tenancy for the question it answers (decisions_identify.go, decisions_admit.go, decisions_authorize.go, decisions_allow.go, decisions_end.go, or decisions_request.go for a bound on one request), and its values in values.go (a refusal code in codes.go), each with the typedness of the literal the layer would have written. Choose its Key from key.go; a key that is not there is added there with its mint cost, its unit and its evidence, which amends the specification's key table (docs/development/tenant-policy-spec.md).
  2. Pin the value and name the requirement. The constant gets its pin in the table TestValues_HoldTheirPins reads, and the row's ID joins specRequirementIDs, which TestDecisions_EveryRequirementHasOneRow holds one for one against the register. Both lists started as the decisions and values the code held at cb6379f53 and are the current pins now, so a new limit adds its lines to them in the same change.
  3. Run go test ./internal/tenancy. Validate holds the row to what issues 540 and 561 each had to discover, in the three ways the specification's invariants list rule by rule. Some it refuses with no exception: a share on any key a caller can mint, the tenant included; a charge to anything but a budget before admission; a refusal on a channel its method cannot carry, or with a status, a code (one in the range MCP reserves and does not define among them), a Retry-After or a challenge the channel forbids; a process partner that is configurable or not keyed on the process, and a reason about the process on a row that does not say it protects one; a valued row that does not say what zero means; a variable without the GITLAB_MCP_ prefix, or a configurable value with no flag, variable or malformed-value policy. Two pass with a recorded decision: a holding taken across keys, and a process partner switched off with the per-key row it stands beside, where the row's OffWithBy names the decision and Decided records it (RTC-007 follows RTC-003, issue 951). The rest pass only by carrying the finding recorded for the invariant: a per-caller number protecting a process resource with no process partner; a code in the legacy -32000 range; a second in-band code for "retry later"; any other zero that does not mean off; a reason whose unit differs from the key or misstates its own; a structure keyed on a mintable value with no capacity; a value only an environment variable or a Go option reaches; a ceiling nothing bounds. tenancy.FindingIssue names that finding's issue; the finding is fixed in its issue, never on the way.
  4. Make the layer read the constant, and declare its sites on the row (Alias, Arg, Pin, Enforce, Refuse, Reason, Charge, Derive, each a symbol and never a line). make check-tenancy is the gate (cmd/audit_tenancy, step 23 of make analyze and a CI step), and every one of its fourteen rules applies to every row: it refuses a literal handed to a limit constructor, a constructor or options literal outside a declared Enforce site, a -42900 or -32000 refusal or a 429 or 503 gate failure (or status write) that no refusal declared in its function carries, a package-level name that reads as a limit and no row or exemption declares in a package holding an Alias, Arg, Pin or Enforce site of a row that is not a request bound, a declared site that matches nothing, a register value nothing reads and an alias only other aliases read, a refusal whose text, status, code or headers differ from its row, an authentication refusal charged where its row says it is not or the reverse, a number on a mintable key called fair, and a variable a row names that is missing from prefixedNames or read by anything but internal/config. Among what it does not see, two things are yours to check on every change: a place that stops reading the constant while another place still reads its alias, which fails only where it writes the literal straight into a listed constructor or options literal (G10), is itself a declared Alias (G2), changes the call a declared Arg names at its index (G3), or is an Enforce site declared to read the constant that no longer refers to it or a declared alias of it anywhere (G5). To hold one such place, make it a declared Alias when it is a package-level value, or read the constant in a call a declared Arg names at its index, since G2 judges every declared alias and G3 every such call; an Enforce site declared to read the constant holds only the last reference left in its body, and G10 needs no declaration, since it fails a literal written into a listed constructor or options literal wherever it is written. The other is a new limit built with none of the listed constructors or options types that refuses through a refusal its function already declares, or by calling a function whose refusal a row declares, and is named where the name rule does not read it: with no limit word, in a package that holds no Alias, Arg, Pin or Enforce site of a row that is not a request bound, or as a value local to a function. The full list, with G8's reading of a switched sentinel and the rest, is in cmd-utilities.md under What it cannot see.
  5. Answer the rest in the pull request: the specification's validation checklist, of which VAL-010 (telemetry carries the reason only) and VAL-012 (a measurement, make bench-fairness, when the limit claims to protect one population from another) cannot be declared in a row.

What proves the change depends on what it is. A change of value is a change of policy and is its own pull request: the constant and its frozen pin, two lines in one package. A change that claims to move policy without changing it is proved by make tenancy-code-identity, and the base it is compared against is the whole of that proof: its parent (BASE=<ref>) when it inserts no line into the server's source and gives the register no new importer, and otherwise its parent with the change's own import lines of internal/tenancy added as blank imports at the same positions, exported and passed as BASE_TREE=<dir>. The import alone moves sections: the inserted lines resize the line table, which can move what the linker lays out after it, and a new importer changes where the linker places read-only data. Every value layer of issue 565 failed against its parent and was byte-identical to that base. A change to the register's own rows or text is a third case: code the server never reaches still changes the package's object and so where the linker places read-only data, and it is compared against its parent with internal/tenancy replaced by its own, which proves nothing outside the register moved. A rule moves into the register only when it is a pure function of values the enforcing site already holds, calling it changes neither what is evaluated nor in what order, its inputs can be enumerated or fuzzed, and the site's allocation and lock profile stays the same; it is proved by an oracle test and a fuzz target against a verbatim copy of the code it replaced, with its allocations pinned, never by the binary, since a layer now calls it (MeterFor, Busy and the three budget switches, whose measured cost is in the ADR's NEG-006).

encoding/json/v2: selectively, never as a migration

Go 1.27 has the v2 engine in its baseline, so every json.Marshal here already runs on it without a line changing and there is no performance case for adopting the API. What the explicit API buys is per-call options, and that is the only reason to reach for it.

Never migrate a package wholesale to v2 semantics. Under v2, omitempty means "empty in JSON" rather than "the Go zero", so an int at 0 and a bool at false stop being omitted: measured on this tree, 535 fields in internal/tools/ would start appearing in responses (the 834 pointers to a scalar and the 3044 strings would not). That moves the published surface, breaks the golden snapshots, and enlarges what a model pays tokens to read.

Adopt it one call at a time, with v1's own semantics restored, so what a valid document decodes to is exactly what it decoded to before and the only thing that changes is the option you named:

jsonv2.UnmarshalRead(r, out, json.DefaultOptionsV1(), jsontext.AllowDuplicateNames(false))

internal/oauth.decodeInstanceJSON is the worked example. It refuses a body that names an object member twice, because encoding/json v1 keeps the last occurrence and reports nothing: an instance answering {"id":1,"id":999} used to admit the token under whichever id the reader happened to keep, and the identity is what every later decision is attributed to.

The condition for using it is the caller's failure branch, not the document's origin. It belongs where refusing is the safe answer. fetchIntrospection in the same file deliberately keeps encoding/json: a nil return there means "the endpoint did not answer", and introspectToken treats that as an instance it could not ask and assumes api, so refusing an ambiguous body would resolve it to more authority than either copy carries. Strictness on a fail-open path is a weakening, and it reads like a hardening, which is what makes it worth writing down.

The package exists because jsonv2 is in Go 1.27's baseline experiment set, which is the toolchain's default and which nothing here configures. Turning it off is possible and would stop the import compiling, but no workflow, image or script in this repository sets GOEXPERIMENT at all, so it is a property of the dependency rather than something to guard against.

Fields client-go does not model

A field GitLab sends that client-go's struct does not carry is read from the captured response rather than from a request of the handler's own (ADR-0021): wrap the context with gitlabclient.WithResponseCapture, pass it to the SDK call as always, and decode the capture into a small type naming the field as GitLab spells it. The transport hands the SDK the same bytes, so the route, the options, the retries, the pagination and the request inventory stay exactly what client-go makes them; a body that does not decode into the handler's type is an error the handler returns. The invites pattern (a client.GL().NewRequest of the handler's own) stays for an endpoint client-go has no method for at all. Each such gap is recorded in docs/development/upstream-bugs.md with the handler that carries it, since an upstream contribution retires it.

Transport end-to-end modules

Two modules start the real binary and drive it the way a client does, both without GitLab or credentials, and both run on every CI push:

  • test/e2e/http (httpe2e) — the HTTP handler chain: cross-origin decisions, preflight, authentication modes, rate limiting, the JSON-RPC shape of a rejection, and the flags that restrict them.
  • test/e2e/stdio (stdioe2e) — the stdio transport: pipes, process lifetime, stdout carrying nothing but JSON-RPC, logs on stderr, and the environment variables stdio configuration actually uses.

They exist because the GitLab suite asks a different question. test/e2e/gitlab drives the same real binary, and drives it against a real instance, so what it can answer is what a tool call does to GitLab. It reaches the transport only as the pipe its own session happens to use: it never starts the process twice, never reads stderr apart from stdout, never passes a flag, and could not tell a listener that answers a preflight from one that does not. These three need no GitLab at all and ask only about the process: how it is started, what it writes where, what it accepts on a socket, and how it ends. Both drive the binary; only these three are about the binary.

stdio is the primary transport and nothing drove it until test/e2e/stdio existed. Two defects shipped through that gap: a nil dereference that killed the process on an ordinary eliciting tool call, and a keepalive ping that closed the session of any client speaking 2026-07-28 after 45 idle seconds — the second held in place by a unit test asserting the ping ought to be there. Both were found by hand against a binary, which is what these modules automate.

The two modules also hold a second kind of case: pins of what the go-sdk the module is built against does with this server's answers today, where that is a defect recorded in docs/development/upstream-bugs.md (rows 10 and 68 are held by test/e2e/stdio/listen_end_test.go and test/e2e/http/session_not_found_test.go). They fail on a dependency bump rather than on a change of ours, with a message naming the entry and every page that has to change with it, and a new pin of that kind belongs in one of these modules rather than in a unit test, because what it holds is the SDK meeting the real binary. A defect this server works around is the exception, since the real binary no longer shows it: row 66, a tool result a middleware makes going out with no resultType, is labeled by toolutil.LabelForRevision, its pin is a unit test on a bare SDK server (TestSDK_MiddlewareToolResult_GoesOutUnlabeled in internal/toolutil), and test/e2e/http/result_type_test.go holds the answer the binary gives with the workaround in place.

When adding a transport-level behavior, put its test here rather than in a unit test that reassembles the handler chain: a test that builds its own copy of the thing under test is testing the copy.

Test infrastructure

All tests use httptest to mock GitLab API responses. Shared helpers in internal/testutil/:

  • testutil.NewTestClient() — creates a mock GitLab client pointing to httptest server
  • testutil.RespondJSON() — responds with JSON body
  • testutil.RespondJSONWithPagination() — responds with pagination headers
  • testutil.CancelOnArrival(t, respond): a context cancelled when the first request reaches the mock, and a client whose mock holds each request until the client abandons it; a handler returns context.Canceled promptly only if its first request carried the context, and a request that sits out the hold, sent without it, fails the test at cleanup, which is what holds a handler's later requests to the same rule. A context cancelled up front cannot show this in a handler that checks ctx.Err() before it builds anything, as the handlers it was written for do
  • The mock refuses what GitLab refuses. NewTestClient wraps the handler it is given, and every POST to /api/graphql has its document and its variables validated against the pinned GitLab schema in internal/graphqlschema before the mock answers. Until this existed no GraphQL test could fail for the reason that matters: the handler returned whatever the test wrote, so a green test proved our code agreed with our own fixture and nothing about GitLab, and four registered tools shipped documents no current instance accepts. The document half catches an unknown field, an argument the field does not take and a variable typed as something the argument is not; the variables half catches a variable sent that the operation never declared, which is what let eight domains advertise a backward pagination no operation asked for. A query carrying a file is read out of the operations part of its multipart body and judged the same way: it used to be waved through for not being the JSON envelope, which exempted the one mutation this server sends with a file attached (an achievement's avatar) and so the one whose variables the SDK rewrites on the way out. A refusal is reported with t.Errorf and the request still proceeds, so the test's own assertions report too, and never with t.Fatal, which would abort the httptest server's goroutine. testutil.AllowInvalidGraphQL(t) exempts a test that deliberately sends a malformed document and belongs nowhere else. A document no test drives is covered by make check-graphql-documents instead. See GraphQL Integration
  • The mock records what the request was. The same wrapper writes down every request a test issues: the method, the path with its identifiers replaced by placeholders named after the collection in front of them (/projects/:project_id/issues/:issue_id/notes), the query parameter names, the top-level field names of a JSON body, and for GraphQL the operation and the variables the document declares, an upload's operations part included. It also counts, per row and per placeholder, how many distinct raw values it templated away, which is the one thing the fold discards that a reader needs back: with a single fixture value a handler that reads the caller's project and one with that id written into it produce the same row. The count is running rather than final, since the recorder has no shutdown hook to write a total from, so a new value costs one more line and the merge takes the highest; the values themselves never leave the test process. Recording is off unless GITLAB_MCP_TEST_INVENTORY_DIR names an absolute directory, make gen-request-inventory runs the suite with it set, and cmd/gen_request_inventory merges the shards into docs/development/request-inventory.json. It exists because all five dimensions of the 1:1 audit describe the surface and none of them looks at the request a handler builds, which is how nine registered tools shipped unable to work. A row's names are a union over the calls that package made, never one call's set, so the file says which parameters an endpoint was sent and not which of them were sent together. The attribution is the package that built the client and the test that built it, never the action: nothing on the wire names an action, and the httptest server answers on its own goroutine where the calling test is not on the stack. CI records during the coverage job and gates the artifact with go run ./cmd/gen_request_inventory/ -check; the race job records too, since the recorder is the one concurrent thing the test transport has
  • A document's cost is held to what GitLab measured. GitLab refuses a query whose complexity exceeds 250 for an authenticated user (300 for an administrator) before it runs anything, and the schema says nothing about cost, so the transport cannot see it. testutil.GitLabQueryComplexity runs GitLab's computation over the pinned schema, with the per-field costs GitLab's Ruby sets (Gitaly surcharges, per-item multipliers, free fields) in a table that holds only what a measurement needed, so a test holds the estimate equal to a figure GitLab reported for the same document and under the limit: a change to the selection changes the estimate and sends whoever made it to measure again, which needs no credential (the refusal names the figure, and below 200 a queryComplexity { score } selection does). The epic notes and discussions list documents are held at 220; see GraphQL Integration
  • Never t.Fatal/FailNow off the test goroutine (httptest handlers, go statements, MCP handlers): follow the six-rule contract in .github/instructions/test-goroutines.instructions.md — t.Errorf + deterministic response + return, or record with atomics and assert afterwards. make check-test-goroutines detects violations; make audit-test-goroutines writes the work list
  • Every case table runs under t.Run: a range over a slice or map literal that asserts must open one subtest per case, named by a name field, the string element, or the map key. go run ./cmd/audit_test_subtests/ -fix rewrites the unambiguous shapes; // sequential: <reason> on the line above a loop declares dependent steps rather than cases; make check-test-subtests gates it in CI
  • A test that compares a committed generated artifact calls freshness.SkipIfDeferred(t) first, before it reads or measures anything. That is the one reader of GITLAB_MCP_TEST_SNAPSHOT_PARITY (internal/freshness), which CI answers from FRESHNESS, and it is what lets a stacked layer leave the artifacts stale on purpose and refresh them once at the top. Guard the comparison and nothing else: a test that also asserts something about the surface keeps that half running (cmd/gen_llms guards one subtest per committed file, not the whole test), and a test driving a replica in a t.TempDir is not a freshness comparison and is never deferred, which is what keeps a stale artifact failing the checker itself on every run
  • Test naming: TestToolName_Scenario_ExpectedResult
  • Test-file naming: a _test.go exists only under the name of a module it tests (register.go → register_test.go); export_test.go, build-constrained qualifiers (file_utils_unix_test.go), external-package qualifiers (kind_integration_test.go), and test/e2e/ are the codified exemptions. make check-test-file-names gates it in CI

Request paths (R-PATH)

The sixth dimension of the 1:1 audit, go run ./cmd/audit_1to1/ -scope=paths, and the only one that reads the request a handler builds. The other five compare what we publish against what the SDK and the API documentation offer, which is why all five were green while nine registered tools could not work: a perfect input struct, a perfect output struct, a registered action, complete enums, and a request GitLab refuses. Its input is docs/development/request-inventory.json, recorded by the test transport and committed by cmd/gen_request_inventory.

Seven checks, three of which gate. Six need no network and no suite run (make audit-1to1-paths, run by make analyze and by CI's generated-artifacts job); the endpoint one needs 250 documentation pages, so it runs only when asked for (make audit-1to1-paths-endpoints) and nothing schedules it. Five of them read the inventory as a list of endpoints and parameter names, which is what the recording keeps of a request; the last two read values, because names alone leave two whole classes invisible:

  • Has the path ever been observed. An action whose owning package issued no request has never had its request seen by anything. Held at package grain, because nothing on the wire names an action, and the report says so beside the number (actions_observed_grain): 1085 of 1085 means 1085 actions whose owner issued something, which is a regression guard and not per-action assurance. A silent package means either that nothing drives it or that the inventory is stale, and the finding cannot tell those apart. A package silent for a reason is held to a declaration with a category and a reason in cmd/audit_1to1/internal/paths/declarations.go, and a declaration that no longer describes the tree is itself a finding. No package is declared today: internal/tools/adminspecs was the one entry, for declaring 92 specs whose handlers live in other packages, until each of those actions was given the domain package its route names as its owner. Naming the owner where the handler lives is the better answer of the two, because a declaration excuses a join that cannot be made while a true owner makes it, and the sharper join is what put admin.system_hook_list on R-PAGE's list below. An action whose owner names no package fails too: nothing in the catalog validates that field, and such an action used to be classified unmapped, which the gate ignored and -gaps-only dropped, so it could be neither counted nor seen. The owner tools is the catalog's own exception, for the orchestration package rather than a domain under it, and resolves to internal/tools. An owner that names a real package and the wrong one is a lie no version of this can catch, since the recording joins on that name and nothing else.

    The grain sharpens to the action where an end-to-end run speaks (e2e_observation, make audit-1to1-paths-e2e). The unit recording cannot name an action because the httptest server answers on its own goroutine; a Docker run can, because the harness stamps a trace id into each MCP call, the server's span carries it back with the route the dispatcher actually chose, and every GitLab request the handler made is a child of that span. The receiver counts those children per trace and the harness writes the count on the dispatch line it already emits (e2ecalls.Dispatch.Requests), so -e2e-calls <dir> answers, per action, which were seen issuing a request and which ran and issued none. It reports and never gates, and both halves of that are about what a missing record means: the shards are a byproduct of a run CI does not schedule and never commits, so failing on their absence would fail every push, and the counts are floors, since the batching span processor drops silently when its queue overflows. A positive claim is therefore solid and a negative one is a lead. A dispatch carrying a refusal reason is kept off the lead list, because the server declining to run something is not a handler that could not build a request.

  • Does the document validate. Every raw GraphQL document in the source against the pinned schema, through cmd/internal/graphqldocs, shared with make check-graphql-documents. It judges the document and never the values: four of the nine broken tools sent a document the schema refuses and the other five sent an accepted document carrying a value GitLab does not have, and the second half is caught by internal/testutil's validating transport, which checks the variables with the document on every request a test drives. Neither substitutes for the other.

    The other half of the GraphQL surface is judged here too (sdk_graphql). client-go builds 42 documents inside its own module, for the achievement, work item, saved view, security attribute, security category, scan profile, target branch rule and Terraform state services, and every one of them reaches GitLab through this server while being judged by nothing but whichever of them a unit test happens to drive. graphqldocs.SDKDocuments reads them out of the module directory structs.CollectOutputPairings already resolves, which needs no GitLab and no network, only GOWORK=off and -mod=readonly (client-go ships a go.work naming a directory its module zip does not carry, and a module cache is read-only). Six of the 42 are counted apart rather than refused: the work item documents are text/template shells and the Terraform state queries are printf format strings, so what the type checker folds carries a placeholder where a value belongs and no schema can judge it — and a refusal list with permanent entries in it is a list a reader learns to skip. The remaining 36 the pinned schema accepts. It reports and never gates, for a reason unlike the usual one: the pin is what GitLab serves, so a refusal there is real, but the answer is an upstream merge request and a version bump rather than an edit here, and that is not a state to fail a build on.

  • Does the endpoint exist. -check-endpoints compares every recorded REST endpoint with GitLab's own API documentation and fails on one no declaration accounts for. What makes that safe is declaredUndocumentedEndpoints in cmd/audit_1to1/internal/paths/endpoint_declarations.go, where each shape the oracle cannot express carries a category and a reason: a deprecated-but-working alias (/services/ for the integrations endpoints, /-/search for the scoped search, bridges for trigger_jobs), an endpoint documented under doc/user rather than doc/api (the generic package registry, Terraform state), one whose only mention is a sentence (/usage_data/track_events), a method the documentation never spells (HEAD on a raw file), and a path client-go builds wrongly (//sidekiq/*). A declaration that stops matching anything is a finding too. The page listing comes from the repository tree rather than api_resources.md, because many pages under doc/api are not linked from that index or from rest/_index.md (101 of 253 when the listing moved to the tree), and against the index alone the comparison would report roughly five times as many as against all 246 readable pages (81 undocumented of 1399 recorded today, every one of them declared); the report counts the pages it could not read, since a hole in the corpus produces findings that are only about the hole.
  • Does GitLab say it sends what we publish. The one check here whose oracle is GitLab itself: docs/development/gitlab-api-live.json (cmd/gen_api_live, taken from a booted GitLab). It reports and never gates, and it asks the question at two grains, both published so a reader can see which findings the sharper one keeps. One record answers both halves of it, what an endpoint sends and what gates each field, which is why a finding can always say when GitLab sends the field it names.

    Package grain (shapes.unpublished) joins the inventory: a package's recorded endpoints are unioned and every top-level *Output type of that package is held against the union. Three deliberate concessions each lose findings so that none is invented: the inventory names a package and never an action, so the union is exact for a package with one endpoint and weaker as the package grows; a route the record names no response entity for, 698 of the 2152, silences its package rather than condemning it; and a nested output type is skipped here, being comparable only against the object it sits under, which the type grain does and this grain cannot. It finds 689 fields across 131 packages, and most of them are not phantoms: our own wrappers around a JSON array (ListOutput.users, SSHKeyListOutput.keys), our own answers to a 204 and to a not-found (DeleteOutput.deleted, userNotFoundOutput.identifier), and an endpoint the document gives no schema for sitting in a package where another endpoint has one (files.Output, whose 12 fields are reported because files calls 32 endpoints and one of them declares a response). The join itself is published beside the findings (shapes.join: 977 of 1555 REST rows exact, 496 after accepting one untemplated fixture segment, 82 unmatched) because a package whose rows all miss would otherwise have its whole output condemned by a lookup failure, and the untemplated segments go with it, which measures this repository's own recording rather than the server.

    Type grain (shapes.typed) asks only about the endpoints a type actually models, along a chain that consults the inventory nowhere: a converter pairs an output type with a client-go struct (structs.CollectOutputPairings, the same pass the R-OUTPUT field diff runs over), client-go's service methods say which endpoints answer with that struct (readSDKRoutes, cut from cmd/internal/sdkroutes, which parses the route() templates and withMethod options out of the SDK source the handlers compile against and follows a method into the helpers it delegates to with the constants it hands them, so the award emoji routes keep the collection their caller names and the custom attribute routes are reached at all), and the document says what those endpoints send. What decides whether a type is judged here is the envelope it sits in, not whether some struct names it as a field. This grain used to pass over every type named as a tagged field, and that rule selected exactly the types that model the responses: the convention here is a one-key envelope, so badges.GetProjectOutput is {badge: BadgeItem}, the envelope carries no pairing and was counted a skip, and BadgeItem (which a converter pairs with gl.ProjectBadge, whose service methods name the endpoints) was passed over for being named as its field. No finding about that endpoint's response could be made here at all. The rule now distinguishes the two shapes that used to look alike, in envelopePayload: a struct carrying one object and nothing else beside it (a list's pagination aside, which is this server's framing rather than GitLab's) is packaging, and its payload is judged against the endpoint; a struct carrying other content of its own names a reference, and that reference stays out. Both halves matter, and the second is the one whose absence bites harder: jobs.ProjectObject is a project reference inside a job, and judging it against the endpoints that answer with a whole project reported all 85 fields of one as missing from it. Together with the compact projections below, the rules take the comparison from 26 types to 239 (summary.typed_types_compared, of which typed_compared_inner are reached through an envelope) and the sent list from 63 fields to 1999, 1583 of them unconditional, across 51 types. That list is also the honest one: the package grain reports 45 user fields against health, whose only claim on the user entity is the /user call that checks a token, and declares every one of them, 44 as a read for the package's own use and custom_attributes as an entity option no endpoint passes, while this grain reports none. The three skip counters now name the types behind them (shapes.typed.skipped), because a figure alone says how much was declined and nothing about whether declining was right, which is the only question a reader has: the 401 that no converter paired were described as wrappers on the strength of the counter alone, and 256 of them were plain *Output types. With every envelope now judged through its payload the counter reads 126, and each of them is a plain *Output type or an envelope around another tools package's row, which that package judges; orbit.DSLOutput left it for the Orbit record (below). A type's published fields are what encoding/json would write, an untagged embed's promoted into it, and a type is nested when any struct of its package names it as a tagged field's type, output type or not; an embed names nothing nested, since its fields are promoted rather than placed under a key, and the embedded type stays a response of its own. The shapes internal/toolutil shares are read once and resolved wherever a package names, embeds or aliases one, the hints type aside; an alias is nested when the shape is named under either name or by another shared shape, unless an exported function of the package returns it. An alias of another tools package's type (type Output = labeldata.Output, which is how the project and group labels and iterations publish their responses) resolves the same way, and at package grain a package is credited with the fields of the types its responses name one level down, so a shared row such as diffs: []toolutil.DiffOutput counts as the package's the way a row it declares does; without either, those five packages read as publishing no field of the entity every route of theirs answers with. A row another tools package declares, named by a field of one of the package's types (commits: []commits.Output), is credited in that direction as well, as a borrowed type the type grain and the unpublished direction pass over, since its own package judges it; without it a merge request's commits and pipelines, a runner's jobs, a repository's commits and a package's release link reported 55 fields they publish as missing. A type a handler returns whole, with no field naming it, is not borrowed, because the guided creation flows return four domains' outputs as they are and would be held to every answer those domains give. The first reading of this walk held a details type to be missing every field of the row type it embeds, held the user under the row of a list of uploads to the endpoints answering with a whole user, and saw nothing of a package whose only user object is the shared one. Each of those silences is counted rather than judged, and an empty response list means the document does not say rather than that GitLab sends nothing. Since schema version 2 of the record it asks the same question one level down, holding a nested output type against the properties the document gives the response property it sits under, and only where the document describes an object there: 42 nested types compared and none reported, the 25 fields it first found in issuelinks and pipelinetriggers having left those outputs. summary.typed_undeclared_fields reads 0 at both levels: the 88 the wider comparison first opened were removed from the outputs that published them without GitLab sending them (issue 964) or answered in the declaration table below where the record is incomplete (issue 965), and each of the 50 typed_unpublished_fields left carries a declaration. Four of them are keys the context commit list sends and its annotation does not name (GET .../context_commits is annotated Commit and presents CommitWithLink, upstream-bugs row 77, issue 1025). The two discussion packages and the shared note shape were on this list until the notes review read the note and discussion entities: the four fields the shape published that GitLab's note does not carry are gone, and the four it lacked are read from the captured response (ADR-0021). A finding at this grain can be answered rather than fixed, because the oracle is generated and is not always complete, so cmd/audit_1to1/internal/paths/shape_declarations.go records such an answer with a category and its evidence, and a declaration that matches nothing is itself reported stale. The confirmed phantom of issue 580 is the case it was built against, and is the fixture that proves it: mrapprovals.ConfigOutput as it stood before the fix produces exactly the twenty findings the fix removed, and as it stands now produces none.

    A compact projection is paired too, and judged per endpoint. A converter is not the only way an output type is filled: a milestone's issue rows, a resource group's job queue and the group's project list are built in a composite literal inside the handler, or in a helper it calls, each field read off the client-go struct the handler ranged over, and nothing paired them, so their gaps reached only the package grain. structs.CollectProjections reads those literals from the same typed load: the struct most of the literal's fields are read off (the receiver of the outermost field selection, so mr.Author.Username is read off the author) and the service methods answering with it that the function holding the literal references, or the package's functions calling it, up to three calls up. The type is then judged against the endpoints of those methods alone, cut per method from the same reader by readSDKMethodRoutes, because a compact row comes from one endpoint and a finding about it has to name that one; a type a converter pairs keeps its converter's endpoints, and the field diff does not read these pairings at all. They are listed in shapes.typed.projections (typed_types_compared_through_projection). The wrapper around a paired payload, a one-key envelope or a struct that publishes nothing of its own and embeds its payload (GetOutput{HintableOutput; PlanLimitItem}), is judged under the payload's name and, once every payload was compared, listed in shapes.typed.envelopes (typed_envelopes_judged_through_payload) instead of being counted among the types without a pairing, which read as a response nobody judged while its payload was judged a line below. A payload that is paired and still skipped, for want of a route or of a response schema, takes its envelope into the same skip, since the response was judged no more than the payload was.

    Each sent finding says which of two backlogs it belongs to. Every rule here compares this server with something: the field diff holds our type against client-go's struct, and the join above holds our type against what GitLab sends. Between them nothing ever holds client-go against GitLab, which is the question that decides where a fix goes. It is asked now, from the same pairing, by carrying the SDK struct's own json names (structs.OutputPairing.SDKFields, flattened exactly as the field diff flattens them) and marking each finding sdk_models. False means client-go does not model the field either, so surfacing it is an upstream contribution or a captured response (ADR-0021) and the finding is evidence for the merge request; true means the SDK already carries it and only this server does not, which is a local edit. Measured on the pinned record: of 1999 sent fields, 1396 are absent from client-go too, and 995 of those are two Geo structs (GeoSite 603, GeoSiteStatus 392) whose fields GitLab generates per replicable resource and which therefore appear in no source a scanner or a hand-written struct could have read; all 995 are declared. The 603 client-go does model came with the compact projections, whose rows leave most of an entity to the detail action on purpose: 385 are declared that way, 140 as published by another type and 49 as the part of a write's answer its confirmation leaves to the detail action. None of the 1999 is answered by no declaration: issue 971 took the last 153, in 19 types, to 0, surfacing what a caller needs (a share's shared_with_groups, the job token allowlist's whole basic project, a package file's pipelines, a failed import's relations) and declaring the rest one key at a time. The package grain reaches 0 undeclared as well, its three noise classes included: the reads a package makes only to probe or resolve an object are declared as such, and the application settings, which settings publishes whole as a map, by one entry. summary.typed_unsurfaced_not_in_sdk is the counter; a route whose desc annotation names the wrong entity inflates it, which is what the declaration table is for.

    The Orbit output types are held to a recording instead (shapes.orbit). No self-managed GitLab serves Orbit, so the live record carries its routes with no response entity, and GitLab's generated reference gives them no response schema; the type grain skipped all six outputs. docs/development/orbit-responses.json (cmd/gen_orbit_record, above under Orbit live tests) names for each recorded call the output type its handler returned, so the join infers nothing: the calls of one type are unioned and the type is walked field by field to every depth, both directions asked, and a third question the other records cannot answer, since this one keeps the JSON kind of every value, asked in two halves: whether the client-go struct a converter fills the output type from decodes each recorded kind at the key it declares, which is what fails a handler at run time, and whether the output type carries each kind to the caller as it came, a null only as a null or as the key left out (behind a pointer, as a nil slice or map, in an interface, or in a scalar tagged omitempty). The converter between the two is read by neither, and the question is of kinds, never of values. A field published as any passes through whatever is below it and is not judged there, a subtree the record kept verbatim shields what a type models inside it while a body kept whole shields nothing of its carrier, a finding is reported at the top of what is missing, and a bare array answer is compared with the one field of the type that wraps it. Against the first recording it compares 6 output types and 12 nested ones and finds 10 fields GitLab does not send, no key it sends unpublished, and no kind refused, the published half put at 58 places and the decoder half at 37 across the three client-go structs it can judge (OrbitStatus and OrbitTools decode their whole body themselves and are listed as unjudged, and DSLOutput has no decoder); all 10 are answered in cmd/audit_1to1/internal/paths/orbit_declarations.go, a table keyed by the path under the output, under three categories of its own: a key GitLab never sends where client-go puts it (the five flat status keys OrbitStatus.UnmarshalJSON copies up from system), a key sent only under a condition the recording did not meet (system.error, raw_query_strings), and a body carried whole (the DSL, the query's text/plain llm answer). It reports in its own section with orbit_* summary counters (orbit_kinds_compared, orbit_decoder_kinds_compared, orbit_mismatched_kinds, orbit_decoder_mismatched_kinds, orbit_kinds_unjudged and orbit_decoder_kinds_unjudged among them), a kind finding named by its path with one element marker per depth and answered in the same table under a kind or decoder-kind direction, and gates only through the stale list, a declaration that answers nothing and a recorded type the tree no longer declares; the seven types the type grain skipped are listed in typed.compared_against_orbit_record instead of its skip lists.

    The same question of GraphQL is asked in cmd/audit_graphql_shapes, not here (make audit-graphql-sent, written to plan/graphql-sent.json). It belongs there because that command already holds the three things the question needs and this one holds none of them: the pinned schema, the document as GitLab receives it, and the Go struct the answer is decoded into, all at the same position of one walk. Folding it in here would mean loading the whole program with go/packages, which audit_1to1 deliberately does not do. What it buys is measured: the eleven GraphQL-only domains (vulnerabilities, securityfindings, securityattributes, securitycategories, the four epic domains, branchrules, cicatalog, customemoji) contribute zero findings to everything above, because their output types pair with no client-go struct and GitLab's REST record says nothing about them, so the sent question was never asked of them at all. Asked now, across the 41 document-and-decoder pairings, it reports 1156 fields the schema offers that no document of their package selects, every one of them answered by one of 134 declarations, and the list was not noise: it named a branch rule that never said who may push, a DAST location's hostname, param and requestMethod (the decoder read the SAST and container-scanning members of that union and not the rest), an epic note's internal flag and a note mutation payload's quickActionsStatus. All of those are published now (issues 969, 967 and 968), and every row left is declared.

    The claim is package-wide and is computed that way. A package sends several documents at one object and they differ on purpose, so a per-document answer is false of the package a reader would act on: branchrules expresses a licensing tier as a CE document that omits codeOwnerApprovalRequired and an EE document that selects it, and epicissues sends a query that reads a work item beside a mutation whose payload can echo little more than an id. Judging each document alone reported the sibling's selections as gaps: 3 of 19 findings in branchrules and 8 of 44 in epicissues were false that way. The walk therefore records what each document did select and decode alongside what it did not, and reports a field only where no document of the package does both; the document a finding names is the witness, not the extent of the claim. Decoding is part of the evidence because the claim being cancelled is that the package surfaces the value: a document that asks GitLab for a field and drops it on the floor surfaces exactly as little as one that never asked, and counting it would repeat this same error one level down, where it is harder to see. A finding is filed against the package whose struct decodes the object, which is not the package the call is in wherever a shared wrapper sends the document: every epic note and discussion mutation goes through toolutil.ExecGraphQLNoteMutation and is decoded into the domain's own struct, and filing it against the wrapper named a package that publishes nothing and made all 29 of its same-name annotations wrong. That annotation is same_name_in_package and is deliberately named as the lead it is rather than as an answer: nothing here pairs a GraphQL type with an output type, so the match is over a package's output types flattened together, and a hit may be the same value under another spelling or a different object's field sharing a name. Spelled published_as, it invited a triager to skip the row, and one of the rows it was covering was vulnerabilities, which declared web_url and filled it nowhere because no document selected webUrl. That one is fixed (the documents select webUrl and the list card links it), which is what the annotation was renamed for: the row it hid was real.

    What the question was put to, and what it was not. The report publishes a coverage breakdown rather than one number: 394 object positions reached, 236 asked about, 82 skipped for being traversed rather than read, 76 skipped because the pairing had already been asked about that schema type (a later position selecting strictly less is skipped too), and three silences counted so they are visible: an object selection no Go field decodes stops the walk before anything under it (1 today), an object decoded into a map has no fields to judge and no package to file against (and is the one place the mutation-errors gate is not applied), and a type that unmarshals itself is walked no further (0 each today). Beyond the walk entirely: like check-graphql-documents, it reads ./internal/... and so sees only documents this repository's source writes. The report names what that leaves out, read from the request inventory: 38 GraphQL operations in 7 packages whose documents client-go builds (achievements 12, workitems 7, epics 6, workitemsavedviews 6, projects 3, securityscanprofiles 3, terraformstates 1), where the document text and the decoder are both inside the SDK's module. R-PATH can see the documents now, since graphqldocs.SDKDocuments folds them out of the module source and puts them to the pinned schema (sdk_graphql), so what is left here is the decoder half: pairing each of them with the struct that reads the answer, which this walk does by resolving a Do call in source it loads and which would mean loading client-go's program too.

    It reports and does not gate, for a different reason than the REST joins: the pin is exactly what GitLab serves, so the oracle is not incomplete, but a field GitLab offers is a candidate for the surface rather than a defect in it, GitLab adds fields weekly, and this dimension has no tier oracle and no deprecation oracle: the schema declares no tier (GitLab gates a GraphQL field at resolve time) and the pin carries no @deprecated, because cmd/internal/graphqlintrospect drops the directives and descriptions on decode. Both blind spots are stated on the report rather than silently absorbed, and both are closed by one sidecar record written from the introspection fetch that already carries the data. Nine of the eleven domains are Premium or Ultimate surfaces, so most of these findings sit on licensed ground: a tier is omitted from a finding rather than emitted empty, since an empty field would read as a condition that was checked and found absent. The one sub-class that does gate, and on every run, is a mutation payload whose errors no field of the decoder reads, which drops GitLab's account of a refused mutation and reports success; the condition is the decoder and not the document, because a payload that selects its errors and decodes none loses them just as completely, while the reverse is already a hard failure of the always-empty leg. A finding is answered by an entry in cmd/audit_graphql_shapes/sent_declarations.go, keyed by package, schema type and field, and a stale declaration fails the run on the terms every declaration table here is held to; two of the 134 answer the work item a notes query names only to reach its notes widget, which is 68 rows. The record is deliberately uncommitted and not freshness-gated: a schema re-pin would churn it every time.

  • Does a list say where it ends. R-PAGE, added because a blind spot was found by accident and every dimension above was green on it: internal/tools/impersonationtokens answered user.list_impersonation_tokens with a bare array of tokens while GitLab serves twenty at a time, so a caller could not tell it had one page and could not ask for the second. None of the six could see it, because all six compare a published field against the SDK struct, the documentation or the entity record, and GitLab's pagination is a field of no entity: an offset page arrives in the X-Page, X-Next-Page, X-Per-Page, X-Total and X-Total-Pages response headers, and a keyset page in a Link. The oracle is the same live record read through its params rather than its entities: 318 of its 2152 routes declare per_page, 311 with page beside it (offset) and 7 with a cursor or page_token instead (keyset, counted apart and raising no finding, since a page-and-total block is the wrong shape for one; none is reached by a recorded request today). An action is judged when its output is a collection envelope (exactly one content field, a list of objects, with this server's own framing taken out), which is where "the route declares the params but the action reads a single object" is answered structurally rather than one declaration at a time: a project carrying shared_with_groups is a single-object read, and admitting those turned 24 findings into 79. Of 266 collection-reading actions, 243 publish a pagination block, 17 sit in a package no paginated endpoint was recorded for, and 6 are findings, every one of them declared: the 15 that were not (issue 963) now offer page and per_page and publish the block GitLab answers with, ten of them through toolutil.PaginationRequestOption because their client-go method takes no options struct to carry a page in, and merge_request.approval_rules through a gl.ListOptions the package's own raw request encodes. admin.system_hook_list was the last of those to be found and shows what the join costs when an owner is coarse: it was in the not-asked-about count while its owner was adminspecs, which records nothing, and naming systemhooks as its owner put it against the one paginated endpoint that package records, GET /hooks, which is the endpoint the action itself calls. The join is the package, like the observation check's, and pagination_endpoint_grain says so beside the number; the 6 findings that matched a sibling's endpoint are declared in cmd/audit_1to1/internal/paths/pagination_declarations.go with the route the record holds for each (GET /runners/:id/managers declares neither param and its handler presents the managers without paginate; GET /projects/:id/languages answers with an object rather than an array; project.target_branch_rule_list is read over GraphQL and has no REST route at all), and there is deliberately no category for "GitLab pages this and we have decided not to": that is the finding. What the params cannot say is what the handler does: GitLab's paginator reads page and per_page from every parameter a request carries, so a handler ending in paginate(...) pages a route that declares neither, and four declarations stood on that misreading until issue 1024 (an issue's participants, a merge request's participants, reviewers and pipelines), with a fifth list, a merge request's context commits, never asked about at all; reading the not-asked-about lists against their handlers found a sixth, attestation.list, and the same class over GraphQL, admin.terraform_state_list, which reads a connection GitLab caps at 100 nodes with no pageInfo and is not fixed. A declaration in the endpoint-declares-no-page category has to cite the handler's body as well as the record; that is its author's obligation, since nothing in R-PAGE reads GitLab's source. It reports and does not gate: a finding is a surface change, and request_paginates on each says whether the fix is one output field or an input that has to offer page and per_page first. Its declaration table gates like every other one here.
  • Is a param sent that the caller never asked to send. The first of the two checks that read values, and the reason both exist: the recorder writes down that a body carried package_name_pattern and nothing about what was in it, so a field this server sends as null on every call reads exactly like one a caller filled in. client-go's option structs say which keys encoding/json writes whatever the handler set (no omitempty and no omitzero, read transitively through nested option structs and named the way Grape declares a nested param, position[position_type]), and the live record says which params GitLab marks optional on the route receiving them. A key written unconditionally whose param GitLab requires is correct; one whose param GitLab lets a caller leave out is a value nobody can decline to send. On the pinned record that separates 11 findings from 37 always-sent fields GitLab requires (two of them, both on POST /groups/:id/share, charged to packages that send the omitempty options of Groups.ShareGroupWithGroup, since the check pairs option types by route) (and 2 whose route does not declare them at all), over 243 option types and 276 recorded body-carrying endpoints, with no declaration table doing any of the work, and the 11 include the case it was built against: package.protection_rule_update sends "package_name_pattern": null on a PATCH where GitLab marks it optional, while the POST beside it requires the same field and is right to send it always. Two blind spots are stated rather than absorbed: a GET is never judged, since client-go encodes its options as a query string where a nil pointer is left out whatever the tag says; and a field whose type is a plain struct carrying omitempty is still written on every call, because under v1 semantics a struct is never empty (client-go has none today, since its nullable values are Nullable[T], a map, which omitempty does omit). It reports and does not gate: the tag belongs to client-go, so almost every fix is an upstream merge request, and whether GitLab minds a null in a given position is per endpoint.
  • Was the path ever built out of anything but the fixture. The other value check, and the one paid for in the recorder. Templating /projects/1/issues into /projects/:project_id/issues is what makes a row an endpoint, and it is also what hides a hard-coded identifier: with one fixture value a handler that reads the caller's project and one with the fixture's id written into it produce the same row, which is why the class had to be found by hand in runnercontrollers, snippetdiscussions, repository, runnercontrollerscopes and securityscanprofiles. The recorder now counts, per row and per placeholder, how many distinct raw values it templated away (a running count, written as a new line whenever it rises, since the recorder has no shutdown hook; the merge takes the highest), and this reads it back: a placeholder seen with exactly one value is a lead, never a verdict, because a fixture that makes one project and drives forty endpoints against it produces forty innocent ones. The leads are printed sharpest first (a row where another placeholder did vary) and capped at 50, with the true count beside them. It reports and will keep reporting: what would make it gateable is fixtures that vary their identifiers wherever they can, which is a change to hundreds of tests rather than to this rule, and there is deliberately no cheap static form, since a lint over numeric literals in test files would fire on every fixture in the tree.

What none of it can do is check that GitLab answers a specific request the way our output struct expects: the shape check reads what GitLab's document says an endpoint returns, never what an instance returned for a call we made, Orbit aside, whose recording is exactly that and only for the twelve calls it makes. The layers stack: the pinned schema and the inventory catch a request that cannot work, a real instance catches a response we misread, and the other five rules keep catching the surface we failed to expose. One more limit is worth knowing because it hid a defect: the inventory records which parameter names an endpoint was sent, never which of them were sent together, so a combination GitLab refuses is invisible here. gitlab_get_catalog_resource was in that state (id and full_path are both optional and GitLab accepts exactly one), and the answer to that class is a handler that refuses the combination and a schema that says so, not an inventory of every combination the fixtures happen to use.

None of that machinery may reach the server binary. internal/graphqlschema embeds the pinned schema, close to a megabyte of SDL text, for two readers, the test transport and the audit, and neither runs in the server; internal/testutil carries it plus net/http/httptest. Both stay out today only because nothing in the import graph happens to reach them, and TestDependencies_TestSupport_NeverReachesTheServerBinary in cmd/server/main_test.go makes that hold on purpose by asking the toolchain for go list -deps, since an indirect import through any of the 250 packages in between is exactly what a source scan would miss.

Fine-grained grants (R-GRANT)

The seventh dimension asks of every action what a fine-grained personal access token has to be granted for it to work, in GitLab's own words, and which actions no grant can make work at all (issue 952, ADR-0024). It is the one dimension whose answer the server enforces: the table it holds to GitLab is the one the binary compiles in and judges every fine-grained session by. Three facts with three owners are kept apart and joined by a generator. What each action requests is this repository's: cmd/gen_action_grants loads the program, resolves each action's handlers through cmd/internal/actionrequests and what each client-go method sends through cmd/internal/sdkroutes, reads the statements as sequences, alternatives and optional requests, and writes docs/development/action-requests.json, so a handler change shows as a reviewable diff. What GitLab demands of each route and GraphQL element is GitLab's, recorded from a booted 19.4.1 into schema 4 of docs/development/gitlab-api-live.json (cmd/gen_api_live). How an action's requests combine is the handler author's, declared at the call site with //gitlab:request mandatory|optional|alternatives: <reason> where the syntax reads it wrongly, or in request_declarations.go where the walk cannot reach (a client-go template, a fmt.Sprintf path, the redirect GitLab answers a permalink with). The join is internal/tools/actiongrants/table_gen.go (keyed literals of constants, so the server runs no code to build it) and the generated docs/reference/fine-grained-permissions.md. A REST requirement is GitLab's route declaration, primary and additional scopes; a GraphQL one is judged along the answer spine, the objects from the root field down to the first that selects more than one field, because a wrong "yes" on GraphQL is silent (a null, an emptied connection) where on REST it is GitLab's own 403: an undeclared type on the spine, an undeclared mutation, a payload type that declares nothing (the write commits and answers null) and an object that never resolves to its declared boundary each make the action denied, a non-null chain carries a denial onto the spine, an abstract position is judged as its worst member, and anything denied off the spine is a part served empty. What the walk or the record cannot answer is declared with a category and a reason (grant_declarations.go: the epic positions GitLab declares at the project boundary only, the raw file HEAD the probes measured), and a declaration that answers nothing is a finding. Three gates sit in make analyze: step 26, make check-action-grants-derivation (every action derived or declared, a second mandatory request on a path qualified, every denial naming an element the record holds, a mandatory request on every way that sends anything; never deferred, since it derives from the tree); step 27, make check-action-grants (the three artifacts fresh, under the FRESHNESS deferral like every committed artifact); and step 28, make audit-1to1-grants (go run ./cmd/audit_1to1/ -scope=grants -gaps-only, which loads no program and holds the committed table to the live record and the catalog: the release, the vocabulary, the public sets, every denial's element, every REST operation's route declaration, and one row per action of both Ultimate builds with the standalone actions). make audit-1to1-grants-report writes the rest to plan/1to1-grants.json and gates nothing: per action the permissions and the directive or declaration that shaped them, the phase A set by cause (58 of 1098 actions at 19.4.1, all through GraphQL), the parts served empty, the REST operations a public project or group serves with nothing granted, issue 1055's worklist of the 23 GraphQL types and mutations GitLab declares nothing for with their REST leads, and the derivation held to the request inventory and, with -e2e-calls, to the route of every client span a Docker run's traces reached, which is the one per-action oracle for a request the derivation missed. A change to a finegrained type regenerates the table in the same change: the generator builds itself and loads the program with table_gen.go replaced by table_stub.go.txt through -overlay, so a table a type change broke cannot stop its own regeneration.

Build & test commands

go build ./...                           # Build all
go build -o dist/gitlab-mcp-server ./cmd/server  # Build binary
go test ./internal/... -count=1          # Run all unit tests
go test ./internal/tools/branches/ -count=1 -v  # Run domain tests verbose
go test ./internal/tools/ -run TestBranch -count=1  # Run specific tests
make golangci-lint                       # Consolidated Go formatting and linting

# End-to-end tests. The suite drives the real binary, so it is staged first;
# every target below does that for you through e2e-server-binary.
make test-e2e                                          # self-hosted GitLab from .env (alias of test-e2e-gitlab)
make test-e2e-ce                                       # ephemeral GitLab CE + runner + fixtures (Docker; GitLab peaks ~7.5 GiB, capped at 12 GiB)
make test-e2e-ee                                       # ephemeral GitLab EE, licensed; runs the common and ee packages
make test-e2e-harness                                  # the harness library's own tests: no GitLab
make test-e2e-http                                     # HTTP transport module: no GitLab, no credentials
make test-e2e-stdio                                    # stdio transport module: no GitLab, no credentials
make test-e2e-collector                                # telemetry into a real OTLP collector (Docker; skips without it)

# Compile-only check. The runtime is decided by the package, not a build tag,
# so all three are compiled together under the one `e2e` tag.
go test -tags e2e -c -o NUL ./test/e2e/gitlab/...          # Windows
go test -tags e2e -c -o /dev/null ./test/e2e/gitlab/...    # Linux

# Orbit live tests against GitLab.com (requires GITLAB_COM_TOKEN; auto-provisions fixtures)
GITLAB_COM_TOKEN=glpat-... go test -tags orbitlive -count=1 -v ./test/e2e/orbit/
make test-e2e-gitlab-com                                # Orchestrated: ensure token, setup fixtures, wait indexer, run live tests

# Model evaluation: the corpus put to a model against the real binary and a
# real GitLab. It asks a paid provider, so nothing schedules it.
MODELEVAL_MODELS=fake:perfect make modeleval-ce          # rehearse the whole pipe, no provider call, no cost
MODELEVAL_SPEND=yes MODELEVAL_BUDGET_USD=25 \
  MODELEVAL_MODELS='anthropic:claude-haiku-4-5-20251001' make modeleval-ce
MODELEVAL_SPEND=yes MODELEVAL_MODELS='...' make modeleval-ee   # the licensed half of the corpus
MODELEVAL_PROBE=yes make modeleval-probe                 # does each provider accept the request we build

# A run writes observation and scores nothing; the numbers are computed on the fold.
make model-results-record MODELEVAL_SHARDS=dist/modeleval/ce
make model-results-refold MODELEVAL_SHARDS=dist/modeleval/ce   # re-score under today's rules
make check-model-results                                        # the offline gate

MODELEVAL_CASES narrows a run to named case IDs, which is how one corrected case is re-run and re-folded without the other 257. Keep the shards under dist/modeleval/: the committed record holds scored columns, a redraw scores nothing, and a run whose shards were discarded can never be re-scored.

Release process

Major-version policy: the server's major tracks client-go's major — when client-go moves to v3, this project moves to v3 in that same dependency bump (removing the deprecated compatibility fields kept during v2, e.g. the flat copies in the dual-shape group Datadog output). All other dependency updates ship as minor/patch.

Rehearse before tagging. gh workflow run release.yml --ref <branch> releases the dispatched tree, as the version its VERSION file carries, without publishing anything (an optional -f tag=v<VERSION> states the version explicitly, and preflight holds the two to each other as it does for a real tag): the E2E gate boots a GitLab, GoReleaser builds every binary as a snapshot carrying that version (snapshot.version_template in .goreleaser.yml), the image is built for both platforms, smoke-tested and exported to an OCI layout so the digest server.json is stamped with is the real index digest, and the publishers take that build from a workflow artifact (REHEARSAL_ARCHIVE in scripts/fetch-release-assets.sh), validate it and run their publish commands dry. Skipped is exactly what cannot be undone: the image push and signatures, the GitHub release and attestations, the npm, PyPI and NuGet uploads, the tap push, the registry publish, the commit to main, winget; verify-published has nothing to read and says so. The NuGet login step is deliberately not skipped: it mints a key and pushes nothing, so a rehearsal proves the nuget.org trusted publishing policy still matches this repository, workflow file and environment. A dispatch is always a rehearsal; there is no input that makes it publish. The tree is the dispatched ref, never the tag: the publisher jobs were added after 2.7.5, and the first rehearsal, run against that tag's tree, found half the scripts the workflow calls missing.

When creating a new release and uploading binaries to GitHub Releases:

  1. Build cross-platform binaries with make release (uses GoReleaser locally, flattens dist/ to match GitHub Release asset names). In CI, GoReleaser creates the GitHub release as a draft and a dedicated staging step copies each binary from its per-target subdirectory to dist/<release-asset-name> (driven by dist/artifacts.json), and the npm steps read those paths. The draft is published (gh release edit --draft=false) only after the bundles are attached and every artifact is attested with actions/attest-build-provenance, so no installer observes a partial release. Each release also ships one SPDX SBOM per binary (<asset>.sbom.json, listed in checksums.txt before cosign signs it as checksums.txt.sigstore.json), and THIRD_PARTY_NOTICES, the license, notice and patent texts of every module the binaries link, which cmd/gen_third_party_notices writes as the third-party-notices entry of GoReleaser's sboms (the one hook placed after the builds and before the checksums and signing), so the file is a release asset in the signed checksums.txt and a generation that fails fails the release. Every package carries it: scripts/fetch-release-assets.sh requires it among the default patterns, the npm, PyPI and NuGet builders verify it against checksums.txt and their validators hold each copy to the digest the builder recorded, scripts/build-mcpb.sh packs it from dist/ into every bundle, and the image's builder generates its own from the image's binary into /usr/share/licenses/gitlab-mcp-server/ beside LICENSE, which scripts/smoke-test-image.sh checks. The Linux binaries are PIE and so name a loader in PT_INTERP, which Go's linker otherwise picks by stat-ing whatever host builds them; .goreleaser.yml names the glibc loaders in per-target overrides (/lib64/ld-linux-x86-64.so.2, /lib/ld-linux-aarch64.so.1, the values every Linux channel promises), and scripts/check_elf_interp.py holds both staged binaries to them right after GoReleaser, once for every channel that ships them (tested by scripts/check_elf_interp_test.py, which also holds its table to the overrides).
  2. Release link names MUST be exact filenames (e.g. checksums.txt.sigstore.json, gitlab-mcp-server-linux-amd64). Never add descriptive suffixes like (GPG signature) — the Homebrew formula, winget, the installers and scripts/fetch-release-assets.sh look assets up by exact name and will not find a decorated one
  3. The tag-triggered release workflow also publishes derived artifacts automatically:
    • gitlab-mcp-server-darwin-all — macOS universal (fat) binary from GoReleaser universal_binaries
    • gitlab-mcp-server-darwin.mcpb, gitlab-mcp-server-windows.mcpb and gitlab-mcp-server-linux.mcpb: the Claude Desktop extension, one bundle per operating system, each carrying only its own system's server, LICENSE, and a manifest listing only its own platform (derived from mcpb/manifest.json by mcpb/platform.jq). Built by scripts/build-mcpb.sh, which prints each bundle's download and unpacked size, fails on Claude Desktop's own limits (512 MiB per entry, 2048 MiB unpacked, 50 times the archive's size, 100,000 entries) and warns when a declared bundle passes 50 MiB to download or 256 MiB unpacked, the sizes past which directories stop reading a bundle (3.1.0's single bundle, at 73 and 285 MiB, lost its provenance, licence and maintenance signals on verifymcp.io that way). Validate with make check-mcpb, build locally with make mcpb
    • gitlab-mcp-server.mcpb: the universal bundle, all three systems' servers in one file, built from the same outputs and uploaded under the name it always had so that links outside this repository keep working. It is attested like the others and declared nowhere
    • Homebrew formula update pushed to jmrplens/homebrew-tap by scripts/update-homebrew-tap.sh (secret TAP_DEPLOY_KEY_B64)
    • winget version PR to microsoft/winget-pkgs via winget-releaser (secret WINGET_TOKEN)
    • Version stamping of server.json, plugin.json (Agent Plugins), .plugin/plugin.json (legacy Open Plugins), mcpb/manifest.json, and lhm.plugin.json (LobeHub Marketplace) committed back to main by scripts/update-server-json-sha.sh, which also pins the OCI image tag and re-derives each mcpb entry's hash from the per-OS bundles passed, comma-separated, as its third argument
  4. LobeHub Marketplace is a manual publish step. The stamping script keeps lhm.plugin.json's version current on every release, but the LobeHub CLI (@lobehub/market-cli) has no non-interactive publish path (browser OIDC login + GitHub connect are required once), so it cannot run in CI. After a release, run make publish-lobehub from a machine with lhm login + lhm github connect already completed (the target runs lhm plugin update; the CLI's plugin publish <gitUrl> verb is for first-time listings only). The listing is jmrplens-gitlab-mcp-server.
  5. The manifest's capability arrays are generated, its version is not. LobeHub derives the listing's capability badges from the tools, prompts, and resources arrays in lhm.plugin.json — its scanner cannot introspect a server shipped as a binary or an image, so a manifest without them advertises zero tools. make gen-lhm-manifest rewrites those three arrays from a live tools/list + prompts/list + resources/list round-trip and leaves every other field, version included, to the release stamp. make check-lhm-manifest gates freshness in CI and runs before make publish-lobehub.

    The generator declares the default surface: it pins dynamic and talks to an in-process stub client instead of reading GITLAB_MCP_TOOL_SURFACE, GITLAB_URL or GITLAB_TOKEN. Anything a generator reads from the environment ships in the committed file, so a developer machine with GITLAB_MCP_TOOL_SURFACE=individual exported would otherwise publish a different manifest than CI checks. New environment-sensitive inputs belong in cmd/internal/mcpsurface, pinned there once for every generator, not read at the call site.

  6. npm publishes automatically via an OIDC trusted publisher, with no stored token. The distribution is a launcher package (@jmrp.io/gitlab-mcp-server) plus six per-platform packages that each carry a release binary, the esbuild/biome model, so npx works, --ignore-scripts works, and nothing is downloaded at install time. The release job's Publish to npm step runs right after GoReleaser, reading the same dist/ binaries the mcpb step uses. It authenticates through npm trusted publishing: the job's id-token: write lets npm mint an OIDC token, and npm ≥ 11.5.1 (the step upgrades the setup-node 22 default) performs the exchange, so no secret is stored anywhere and provenance is attached automatically (no --provenance flag). scripts/build-npm.mjs assembles the packages from dist/ (Node's win32/x64 names mapped to Go's windows/amd64 in one table there); scripts/publish-npm.sh publishes the platform packages first, then the launcher (that order matters, or an install racing the publish resolves optional dependencies not on the registry yet), and it skips any version already published so re-running a release job does not die on npm's 409. scripts/validate-npm.mjs runs before the publish step (a published npm version is permanent): it packs all seven tarballs and checks their file set, the binary's executable bit and platform magic number, a size floor, and the os/cpu/name/version, then installs the launcher plus the host-native platform package and drives a real MCP handshake asserting stdout is pure JSON-RPC (--no-install stops after the structural checks, for scripts/validate_npm_test.py), and on Linux starts that package through npx twice, in stdio mode and with --http, and requires a SIGTERM sent to the npx process alone to end the server within ten seconds. That is the launcher's (npm/gitlab-mcp-server/cli.js) job: npm passes the signal only to the sh -c it runs the launcher through, so the launcher passes SIGTERM, SIGINT and SIGHUP on to the server and, when npm started it, sends the server SIGTERM once its parent changes; up to 3.1.0 it blocked in spawnSync and an HTTP server started with npx kept its port. scripts/npm_cli_js_test.py holds the launcher to that against a stand-in binary. Every one of the seven tarballs carries the repository's LICENSE, held to it byte for byte: build-npm.mjs copies it into each platform package and into the checked-in launcher directory, where the copy is git-ignored so the text has one source. make validate-npm NPM_BINARIES=dist runs it in a clean node:22 container so a developer's machine is never touched; the release job runs make validate-npm-local on the ephemeral runner. Bootstrap constraint: a package cannot have a trusted publisher configured until it exists, so the first version (v2.7.5) was created by a one-time tokened make publish-npm; the trusted publisher on npmjs.com is then configured per package (all seven) naming this repo, the workflow file release.yml, and the release environment (the job sets environment: release), after which the token is removed and every later tag publishes with no credential. The launcher's version and its optionalDependency pins move together via build-npm.mjs --sync-only, wired into scripts/update-server-json-sha.sh so the committed npm/gitlab-mcp-server/package.json stays current with the release stamp. For an out-of-band publish, make publish-npm NPM_BINARIES=dist from a machine with an npm token (rehearse with make publish-npm-dry). The unscoped name gitlab-mcp-server was already taken on npm, hence the scope.
  7. PyPI publishes right after npm, from the same staged dist/ binaries. The distribution is six platform wheels (scripts/build_pypi.py, standard library only) with the native binary in the wheel's .data/scripts directory, the uv/ruff model, so the installer places it on the scripts path as the gitlab-mcp-server command itself and no Python runs on the hot path (uvx jmrplens-gitlab-mcp-server works via a console-script wrapper named after the distribution, and the installed command stays gitlab-mcp-server; a gitlab_mcp_server module remains for python -m and programmatic lookup). Two traps the validator (scripts/validate_pypi.py, run before every upload because a published PyPI file name is burned forever) pins: the binary's zip entry needs S_IFREG in external_attr (pip's zip_item_is_executable requires S_ISREG before honoring the 0o111 bits; permission bits alone install it non-executable), and the manylinux_2_17 tag is verified against the binary's actual glibc symbol demands (none: Go internal linking). The wheel METADATA embeds pypi/README.md, which must keep the mcp-name: io.github.jmrplens/gitlab-mcp-server token the MCP Registry validates for pypi ownership. The licence is declared as core metadata 2.4 defines it (PEP 639): License-Expression: MIT and a License-File for each text the wheel carries under .dist-info/licenses/, with neither the legacy License field nor a License :: classifier, since the specification makes the field and the expression mutually exclusive and PyPI refuses a file carrying both; the validator holds each text to the repository's own file byte for byte and runs twine check --strict when twine is installed. METADATA also links the issue tracker and the security policy under the well-known Issues and Security labels. The distribution name is jmrplens-gitlab-mcp-server: the unprefixed PyPI name is an empty registration held by an unrelated account, under a PEP 541 reclamation request; when reclaimed, the rename is DIST_NAME in scripts/build_pypi.py and scripts/validate_pypi.py, the server.json identifier, and the docs. CI publishes via pypa/gh-action-pypi-publish under the OIDC trusted publisher (configured on pypi.org naming this repo, release.yml, environment release) with skip-existing, so re-runs are safe and PEP 740 attestations attach automatically; make publish-pypi PYPI_BINARIES=dist is the tokened out-of-band path (PYPI_TOKEN), and make validate-pypi PYPI_BINARIES=dist runs the whole check in a clean python:3.14-slim container.
  8. A server.json remotes URL must be globally unique across the whole MCP Registry, and the comparison is on the literal string. The registry refuses a publish whose remote URL any other server already claims — templates included. This repository used to declare https://{host}:{port}/ as a self-hosted form; the sibling libgen-mcp copied that pattern and its v1.5.2 publish was rejected with remote URL https://{host}:{port}/ is already used by server io.github.jmrplens/gitlab-mcp-server. Checking that nothing claims your hostname is not the check — the string is. Generic templates are therefore not worth claiming: the self-hosted HTTP mode they advertise is documented in the guides anyway, and holding one blocks every other server you publish. make check-server-json validates the schema only; uniqueness is a registry-side property no local gate can see.
  9. server.json's packages array says what a client should install, and almost nothing about it is schema-checkable. The package entries declared are the Claude Desktop bundles (one per operating system from the first release that builds them; main declares the single universal bundle until then), the ghcr.io image, the Docker Hub image, the npm launcher, the pypi distribution, and the nuget tool. Three traps, each of which passed make check-server-json while being wrong:

    • registryType: "mcpb" means the bundle, not a binary. Up to v2.7.5 the manifest declared six mcpb packages pointing at the raw per-platform executables (7f 45 4c 46) while the real bundle (50 4b 03 04) shipped in the same release, undeclared. Every directory that scores a server by installing what it declares scored the raw ELF.
    • The mcpb entries are written by the stamp, one per bundle, and never by hand. A registry entry has no platform field, so a client cannot choose between bundles by system; what tells them apart is the compatibility.platforms list inside each one, which also makes Claude Desktop refuse a bundle opened on the wrong system. scripts/update-server-json-sha.sh takes the bundles as a comma-separated third argument and rebuilds the mcpb entries from them, copying the first mcpb entry's transport and environment variables and giving each its own identifier and fileSha256; it refuses, before writing anything, a set that does not serve darwin, win32 and linux exactly once each, which keeps the universal bundle out. Editing the entries by hand ahead of a release would declare URLs that 404 until it exists and hashes nobody can know, and check-server-json-packages runs on every push to main.
    • The OCI entry must declare no packageArguments at all. Any argument after the image name replaces CMD wholesale, so an entry that names one is opting out of whatever the image's command does. While CMD was --http --http-addr 0.0.0.0:8080, opting out was exactly what the entry wanted: a client running docker run -i with no argument override got an HTTP listener and hung at initialize forever, and the entry carried packageArguments: [{"type": "positional", "value": "--http=false"}] to undo it. CMD is now --transport auto --http-addr 0.0.0.0:8080, which reads the transport off file descriptor 0, so the -i implied by the entry's stdio transport hint is enough on its own and an argument would only take the --http-addr away with it. scripts/validate-server-json-packages.sh therefore accepts an argument-free entry only when CMD reaches stdio by itself, and still demands an explicit stdio argument from any entry that declares arguments at all. It reads that CMD from the image the entry pins, which is a published image and so lags this repository by a release; when the published one predates the inference it falls back to the Dockerfile here and says so, the same transitional shape the npm branch uses for mcpName. A Dockerfile regressed to a bare --http fails either way.
    • An OCI entry must NOT carry version, registryBaseUrl or fileSha256. The registry rejects them at mcp-publisher publish, server-side, long after the schema check passed. Its version lives in the image reference, which scripts/update-server-json-sha.sh pins separately from the URL rewrite. Ownership is validated through the image's io.modelcontextprotocol.server.name label, which the Dockerfile sets.
    • The image is pinned as <repo>:<tag>@sha256:<digest>, the third form the registry's OCI validator accepts. The tag stays readable and matches every doc; the digest is what a client actually resolves, so re-pushing a published version tag cannot change what gets installed — it was the last mutable pointer in the manifest (the bundle has fileSha256, an npm version is immutable). The digest comes from the docker job's docker-push output, which is why release depends on docker; the stamper takes it as a fourth argument and refuses to stamp a digest-pinned identifier without one, since pinning the new tag beside the previous release's digest would be worse than either alone.
    • There are two OCI entries, ghcr.io and Docker Hub, and they carry the same digest. The multi-platform build is pushed once to both registries, so both hold the byte-identical index and one docker-push digest pins both; the ownership label the registry validates is the same label on the same image. That is why the stamper rewrites each OCI identifier inside jq, per entry, instead of computing one identifier in the shell and assigning it to every OCI entry, which is what it did while there was only one and which would have republished the ghcr.io reference under the Docker Hub entry. Docker Hub is a declared channel rather than a mirror: it is documented as an install route, its repository description is pushed from this repository on every release, and the image is signed and attested there on the same terms as ghcr.io. Two mechanical differences, both handled in the gate and in the workflow: Docker Hub's registry API is not on the hostname the reference names (https://docker.io/v2/ redirects to the marketing site, and both the gate and actions/attest canonicalize to registry-1.docker.io), and its token endpoint is a separate host taking a service parameter. The registry's own validator pulls the image anonymously, so a Docker Hub anonymous-pull 429 is possible; it fails closed with "please retry shortly", which the publish job's retry loop already matches.
    • A cosign signature is not build provenance. The signature over the image index has an empty in-toto predicate: it says the release workflow pushed this index, not which commit or run produced it. actions/attest-build-provenance answers the second question and runs three times per registry with push-to-registry: true, over the index and each of the two platform manifests it lists, so every attestation is a referrer on its subject as well as a record in GitHub's attestation store, which a scanner reading a registry cannot see. The platform manifests are attested because verifiers disagree about which digest the image is: gh attestation verify oci:// resolves a tag to the index, while a scanner that pulls the image for its own platform resolves the index to one manifest and reads that digest's referrers (verifymcp.io's scan of 3.0.0 reports the linux/amd64 manifest as its subject, and found the cosign signature there only because cosign sign --recursive signs every manifest the index lists). It changes the subjects' referrers and never the subjects, so the digest server.json pins is unaffected and no re-stamp is needed. cosign-release is pinned on all ten cosign-installer steps for a related reason: the cosign major decides how a signature is attached, and a 2.x client reports "no signatures found" on an image a 3.x client verifies. None of this runs in the job that builds the image. sign-attest holds the two cosign signatures and all twelve attestations, and release names it in needs so that a signature or attestation that fails still stops every publisher, which the old arrangement got for free by living inside docker. docker keeps packages: write and loses id-token: the build is not byte-reproducible (BuildKit's own provenance: true attestation carries timestamps whatever the build args say), so a re-run of the build job pushes a new index under the same 3.0.0 and latest tags and orphans the one already signed, which server.json is by then pinning. With the split, a failed attestation costs a re-run of three minutes of signing against the published image and no tag moves. The GitHub release being immutable does not cover this: what moves is a registry tag. The SBOMs are still generated in docker and cross as an artifact, because a rehearsal has no pushed image to scan and does have the two smoke images in that job's daemon.
    • The image's SBOM is published twice, on purpose. sbom: true on the build writes an SPDX document into the index as an attestation manifest, one per platform, and a client reading the registry's referrers never sees it: those unknown/unknown manifests are part of the index rather than referrers of anything. actions/attest publishes the same information as a referrer, so both readers are served and neither document replaces the other; it is the action itself rather than the deprecated actions/attest-sbom wrapper, pinned to the version the provenance wrapper delegates to, so all twelve attestation steps run one credential lookup. It is given predicate-type and predicate-path rather than sbom-path, because sbom-path derives the predicate type from the document's spdxVersion and emits https://spdx.dev/Document/v2.3, while Trivy matches the unversioned https://spdx.dev/Document by exact string equality and finds nothing under the versioned spelling; the in-toto specification lists both Type URIs, so the unversioned one is passed explicitly. It runs six times, over the index and each platform manifest on each registry, which reverses an earlier reading that an SBOM over an index would be a document about nothing. That reading is right about an index having no contents of its own and wrong about what a scanner does: trivy image <repo>:<tag> resolves the tag to the index and reads that digest's referrers and nowhere else, so an index carrying no SBOM reads as a server that publishes none. The index attestation carries the amd64 document by convention; the platform attestations are what a reader that already resolved a platform for itself finds. gh attestation verify oci://…:<tag> --predicate-type https://spdx.dev/Document therefore answers on the tag as well as on a platform digest. The same documents are attached a second time with oras attach as bare application/spdx+json referrers, because what actions/attest writes is a sigstore bundle and a reader looking for the plain media type does not match it; those sit beside the attestations and replace neither. syft is fetched by hand in the docker job for the same reason the release job fetches it that way, its bytes pinned by SHA256 and its provenance checked with cosign, since anchore/sbom-action downloads an install script from a branch head and this job holds the OIDC identity the attestation store trusts. A generated document listing no packages fails the step rather than attesting an empty claim. A rehearsal runs the install, the scan and that guard against the two smoke images the daemon already holds, since it pushes nothing to scan; only the attest steps stay skipped.

    make check-server-json-packages (scripts/validate-server-json-packages.sh) gates all of this by downloading each declared artifact: it hashes each bundle, opens it as a zip, checks every path its manifest names, holds the declared bundles to serving darwin, win32 and linux exactly once each between them, checks each image tag resolves on its own registry and its ownership label matches, and rejects the fields the registry rejects. CI runs it on pushes to main only, since the bundles are about 75 MB to download in all. A bundle's SHA256 cannot come from GoReleaser's checksums.txt: the bundles are not GoReleaser artifacts, and appending them there would invalidate the cosign signature over it, checksums.txt.sigstore.json. The release workflow therefore builds the bundles before the stamp and passes the three per-OS ones as the stamper's third argument. scripts/fetch-release-assets.sh holds every bundle it fetches to its own build-provenance attestation, and its default patterns fetch the binaries by operating system (gitlab-mcp-server-<os>-*) precisely so that they leave the per-OS bundles, which a plain gitlab-mcp-server-* matches, to the jobs that ask for them.

    The npm entry declares the launcher (@jmrp.io/gitlab-mcp-server, runtimeHint: "npx"). The registry validates npm ownership through an mcpName field in the published package.json; the field is committed in npm/gitlab-mcp-server/package.json, and release.yml publishes npm before mcp-publisher runs, so the version the registry fetches always carries it. The gate's npm branch checks the identifier/mcpName/version lockstep against the committed launcher and warns (rather than fails) while the published version still predates mcpName. Like the OCI entry, the npm entry must not carry fileSha256; unlike it, a version is required and the stamp's step 2 bumps it with every release.

    The NuGet entry declares the tool (registryType: "nuget", identifier gitlab-mcp-server, runtimeHint: "dnx", registryBaseUrl exactly https://api.nuget.org/v3/index.json, which the registry demands for that type). Ownership is validated the way pypi's is: the registry reads the published version's README through the v3 feed's readme resource and looks for mcp-name: io.github.jmrplens/gitlab-mcp-server on a boundary (whitespace, a tag, or an HTML comment close; the token in nuget/README.md sits inside an HTML comment). The gate's nuget branch downloads the pointer package and checks that README, the tool manifest and .mcp/server.json, and notes rather than fails while nuget.org does not list the version, since the gate runs on main before the release that publishes it. The stamp's step 2 bumps its version with the others.

  10. NuGet publishes beside npm and PyPI, from the same staged dist/ binaries, with no stored credential. The distribution is the .NET 10 SDK's layout for a tool whose entry point is a native executable (tool manifest version 2): a pointer package gitlab-mcp-server (package types DotnetTool and McpServer, carrying tools/net10.0/any/DotnetToolSettings.xml that maps each runtime identifier to a package, the README with the ownership token, and an .mcp/server.json derived from server.json and stamped with the build's version, since the repository file is stamped only after the packages are pushed) plus six gitlab-mcp-server.<rid> packages (linux-x64, linux-arm64, osx-x64, osx-arm64, win-x64, win-arm64; package type DotnetToolRidPackage) that each carry the binary at tools/any/<rid>/ as an EntryPoint with Runner="executable", zip mode 0755. All seven carry the repository's LICENSE at their root beside the nuspec's MIT expression, a plain file rather than <license type="file">, since a nuspec declares one licence form or the other; the validator holds each copy to the repository's text byte for byte. Nothing in the packages is .NET code and no SDK is needed to pack: scripts/build_nuget.py (standard library only) writes the OPC container by hand, verifying every binary against the release's cosign-signed checksums.txt first. scripts/validate_nuget.py runs before every push, because a pushed NuGet version can be unlisted but never replaced: OPC skeleton, nuspec ids, versions and package types, the pointer's runtime map, the ownership token on the boundary the registry accepts, .mcp/server.json, the binary's magic number and machine per RID, the executable bit, a size floor and the digest recorded at pack time, an archive layout nuget.org's repository signature leaves intact (no entry with a data descriptor, nothing in zip64 form, no archive comment, no .signature.p7s already in it, any of which would leave the attested digest one no verifier recovers), then a real dotnet tool install from the packages and a dotnet dnx run, each driven through an MCP initialize handshake asserting stdout is pure JSON-RPC. make validate-nuget NUGET_BINARIES=dist runs all of it in the SDK container pinned by digest (10.0.401, because dnx's behaviour is an SDK property); the release job runs make validate-nuget-local after actions/setup-dotnet installs that same exact version. The job then attests all seven .nupkg files with actions/attest-build-provenance (subject-path: nuget/dist/*.nupkg, skipped in a rehearsal like every other attestation) before the NuGet login, so no package is pushed unattested. nuget.org adds its own repository signature (.signature.p7s) to every package it serves, so the served file's digest is never the attested one: a verifier removes that entry the way NuGet defines an unsigned package and looks up the SHA-256 of what is left, which is the attested file byte for byte. Up to 3.1.0 only the binaries inside the runtime packages were attested, through checksums.txt, which no NuGet verifier reads, since the package also carries the nuspec, the pointer's DotnetToolSettings.xml (what runs) and .mcp/server.json. scripts/publish-nuget.sh pushes the six runtime packages before the pointer that names them (the npm ordering rule, for the same reason) with dotnet nuget push --skip-duplicate, so a re-run lands on already-pushed versions without failing. CI authenticates through nuget.org trusted publishing: NuGet/login exchanges the job's OIDC token for a one-hour API key under the account-level policy recorded in docs/development/repository-settings.md (owner jmrplens, repository gitlab-mcp-server, workflow release.yml, environment release, scope "push new packages and package versions", glob gitlab-mcp-server*), so the first release creates the seven ids with no bootstrap token, unlike npm and PyPI; the login step runs in a rehearsal too, pushing nothing, which proves the policy still matches. make publish-nuget NUGET_BINARIES=dist with NUGET_API_KEY is the only tokened path, for an out-of-band push from a machine with the SDK. Two dnx facts the docs rely on, both verified against 10.0.400 and again against 10.0.401: dnx parses its own options anywhere on the line, so arguments for the server go after -- (dnx gitlab-mcp-server -- --version); and it installs without asking when stdin is not a terminal, so a client configuration is dnx gitlab-mcp-server with configuration in env (Microsoft's docs show --yes, which both accept though their help does not list it). dnx also resolves the version against the feed on every launch, cached or not, and @latest is not a NuGet version. scripts/verify_published_packages.py reads the six runtime packages back from the flat container after the push and compares each binary with the signed checksums.txt, and, handed the seven digests the nuget job attested (its nupkg_sha256 output, through --nuget-digests), removes nuget.org's repository signature from all seven packages the way NuGet defines an unsigned package and holds each to its attested digest, which is the lookup a verifier makes and needs neither gh nor a new permission; the registry's nuget validator answers "wait for validation to complete" while nuget.org is still validating a fresh push, which the mcp-registry job's retry loop treats as lag.

Post-implementation verification

After making changes, run targeted verification on the changed files/packages only (not the entire project):

# Go files — run on affected packages
go test ./internal/tools/branches/ -count=1    # tests on changed package
golangci-lint run --build-tags e2e ./internal/tools/branches/ # lint changed package

# Markdown files — run on specific changed files
npx markdownlint-cli2 docs/guides/ci-cd.md README.md  # lint specific .md files
npx markdownlint-cli2 --fix docs/guides/ci-cd.md      # auto-fix specific .md files

# README.md/docs tables — normalize pipe tables, or verify with --check
go run ./cmd/format_md_tables/
go run ./cmd/format_md_tables/ --check

# MCP Inspector (interactive tool testing UI at http://127.0.0.1:6274)
make inspector                             # compile + launch Inspector via stdio
make inspector-stop                        # stop Inspector and clean up

# Full project analysis (use sparingly — for pre-commit or CI)
make analyze                               # all analysis gates, full project
make analyze-fix                           # auto-fix what can be fixed
make analyze-report                        # generate LLM-consumable report

Static analysis tools (3 consolidated gates): golangci-lint (v2, 25+ linters plus goimports, gofumpt, and gci formatters), govulncheck, and markdownlint-cli2. Configuration: .golangci.yml, .markdownlint-cli2.jsonc. Full docs: docs/development/static-analysis.md.

Markdown table formatter: When creating or editing pipe tables in README.md or docs/, run go run ./cmd/format_md_tables/ to normalize source-readable padding and left/right/center alignment markers, then verify with go run ./cmd/format_md_tables/ --check before markdownlint.

Formatting tools: Before committing, always run make analyze-fix to apply configured Go formatters: goimports (import cleanup), gofumpt (stricter gofmt-compatible formatting), and gci (deterministic import section grouping).

Environment variables

Settings this project defines are read as GITLAB_MCP_<NAME> and under no other spelling; config.Getenv and config.TrimmedGetenv in internal/config/env_name.go are the one way to read one. A new setting is added to prefixedNames there and read through those helpers, never through os.Getenv.

Every variable this server defines carries the prefix, with no exception for a name that already began with GITLAB_: the switches that did (GITLAB_TIER, GITLAB_READ_ONLY, GITLAB_SAFE_MODE, GITLAB_IGNORE_SCOPES, GITLAB_SKIP_TLS_VERIFY) and YOLO_MODE were renamed in 2.8.0, and their old spellings were removed in 3.1.0. config.RetiredEnvUses finds one still set in the environment so a deployment is told rather than quietly reconfigured, and splits its answer: GITLAB_READ_ONLY, GITLAB_SAFE_MODE and EXCLUDE_TOOLS (config.protectionNames, the three settings register row AUT-004 decides) refuse startup, because ignoring one in silence serves writes, or the actions an operator removed, on a deployment that asked for neither, and every other retired name is a warning. The condition is what ignoring one would cost, not where it came from: the refusal reads the name and never its value, and a bare EXCLUDE_TOOLS refuses even though another tool in the same shell could own it, since the server cannot tell whose it is and guessing that it is somebody else's is the guess that serves what was removed. Only three groups stay bare, because prefixing them would be wrong rather than churn: GITLAB_URL and GITLAB_TOKEN (GitLab's own convention, and what a user already has in the environment, so they are never spelled twice), every OTEL_* variable (owned by the OpenTelemetry specification and read by the exporters themselves), and AUTOPILOT (a convention other agent tooling sets, honored as an alias of GITLAB_MCP_YOLO_MODE and never warned about). The model evaluation's MODELEVAL_* and the test transport's GITLAB_MCP_TEST_INVENTORY_DIR are developer-only, driven by make targets, read by test code that cmd/server never links, and out of scope: they configure the harness rather than the server, and there is no legacy spelling of either to warn anybody about.

VariableRequiredDescription
GITLAB_URLStdioGitLab instance URL (e.g., https://gitlab.example.com). In HTTP mode it is --gitlab-url, which is required unless --allow-any-gitlab-url is passed, and the count decides the header's meaning: none (with the escape hatch) lets GITLAB-URL select freely per request, and a request that omits it is refused rather than resolved to https://gitlab.com; exactly one fixes the instance and the header is ignored; several publish an allow-list among which the header is required, since choosing for the caller would send their token to an instance they never named. A comma-separated value spells the list
GITLAB_TOKENStdioPersonal Access Token (glpat-...): a classic one, or a fine-grained one whose grant decides what it is served (guide)
GITLAB_MCP_SKIP_TLS_VERIFYNoSkip TLS verification for self-signed certs (true)
GITLAB_MCP_ENV_FILENoOne dotenv file to load besides ~/.gitlab-mcp-server.env, resolved once from the process environment before any loaded file could rewrite it, so a file this server loads cannot nominate another. Precedence, highest first: the process environment, this file, the home file. A working-directory .env is not loaded at all, only found and named at WARN with the keys it wanted to set. Give an absolute path: a relative one follows the client into every workspace it opens, which is the load this replaced, and startup says so. internal/config.EnvFileVar; the --env-file flag sets the same thing and wins over it
GITLAB_MCP_STDIO_MAX_LINE_BYTESNoLongest stdio message assembled, in bytes (default 4 MiB, matching the SDK's own HTTP body default so both transports refuse the same messages). A longer line is refused and answered rather than accumulated. A value that is missing, unparseable or non-positive warns and keeps the default, because a mistyped number should not take the client down with the server. cmd/server.stdioMaxLineBytesEnv
GITLAB_MCP_MAX_LISTEN_STREAMSNoConcurrent subscriptions/listen streams one credential may hold open (default 64; 0 removes the per-credential ceiling and nothing else: the same counter is what tells the pool a credential is holding a stream open, so removing the ceiling must not make a listening credential look idle). A second ceiling of 512 per process is deliberately not configurable: the per-credential one multiplies by however many tokens a caller holds, so only the process-wide one bounds the process. MaxWatchers does not cover this, since a listen asking only for list-changed notifications creates no watcher. Both transports. cmd/server.maxListenStreamsEnv
GITLAB_MCP_TOOL_SURFACENoExplicit tool catalog selector: dynamic, meta, or individual; dynamic when unset
GITLAB_MCP_CAPABILITY_SURFACENoResource and prompt catalog selector: full or minimal; minimal keeps the surface-aware gitlab://tools manifest
GITLAB_MCP_META_PARAM_SCHEMANoMeta-tool input-schema strategy: opaque (default), compact (~8.7x), or full (~18.3x). Independent of GITLAB_MCP_TOOL_SURFACE. Per-action call shapes and input schemas are discoverable through gitlab://tools and gitlab://tools/{id} for every surface
GITLAB_MCP_READ_ONLYNoRead-only mode: removes mutating operations per action; reads keep working on every surface (false default)
GITLAB_MCP_SAFE_MODENoSafe mode: intercepts mutating operations per action and returns a preview card naming the action and echoing its arguments (toolutil.FormatSafeModePreviewMarkdown, read back by ParseSafeModePreview); reads keep working (false default)
GITLAB_MCP_TIERNoLicensing tier selector: free/ce (Free), premium, or ultimate. When set, the tier is used verbatim with no license check. When unset, the tier is detected in two steps, because neither answers for every deployment: GET /license carries the instance plan and is admin-only on self-managed and unavailable to anyone on GitLab.com, and GET /namespaces carries a plan per namespace the caller administers, which is the real subscription on GitLab.com and always default on self-managed, a subscription being a GitLab.com concept. Measured 2026-09-22 against a licensed EE 19.3.1 and against GitLab.com. default and an absent plan both mean the question went unanswered rather than that the answer is Free, which is what keeps a GitLab.com account on the free plan from being warned at every startup about a tier that is correct. Where neither answers the tier is free, and an enterprise build says so once at WARN naming this variable, while a CE build stays silent because Free is the truth there. Several paid namespaces resolve to the highest, on ADR-0018's asymmetry: a tier resolved too low silently removes tools, one resolved too high surfaces as GitLab's own refusal on the one call that needed it. The namespace listing is paged, stopping at the first ultimate (nothing later can raise the answer) and after namespacePlanMaxPages of namespacePlanPageSize either way, so an account administering more than a thousand namespaces whose only paid one sits past that bound resolves lower than it holds; reading one page alone was the first shape and resolved Free for exactly that caller. A page that fails after an earlier one answered keeps that answer. In HTTP mode use --tier; when omitted the tier is detected per token+URL pool entry. Enterprise/Premium tools are gated when the resolved tier is Premium or Ultimate
GITLAB_MCP_IGNORE_SCOPESNoSkip the scope filter and the read-only narrowing and register every tool the tier allows (false default). Flag --ignore-scopes. The token's scopes are still read, so a token carrying neither read_api nor api is still refused, on stdio with every catalog method answered -40300 (issue 952), and a fine-grained token's grant still decides what it is shown
GITLAB_MCP_EMBEDDED_RESOURCESNoEmbed the canonical gitlab:// resource URI in get-style tool results (true default). Flag --embedded-resources
GITLAB_MCP_EXCLUDE_TOOLSNoComma-separated tool names, group names or canonical action IDs removed from registration; they leave both the served surface and the withheld-action lists, since the operator asked for them not to exist. One rule on every surface, the standalone utilities included: gitlab_interactive removes the four guided flows and interactive.issue_create one of them, because surfaces.ExcludedToolSpecs asks the catalog's own matcher rather than keeping a copy (issue 911). An entry naming nothing is a WARN from tools.ExcludeFromCatalog, never a refusal, since one file is reused across tiers; it is written whenever a shared catalog is built, once per catalog key (tier, instance class and the scopes that narrow the catalog): at startup on stdio, and the first time each key is built in HTTP mode, where the tier is detected per pool entry unless pinned. It can therefore repeat, and an entry reported as naming nothing for one tier may still remove actions for another. The WARN also names the dynamic surface's own gitlab_find_action and gitlab_execute_action, although that surface removes them by name, because the function knows no surface. Flag --exclude-tools
GITLAB_MCP_UPLOAD_MAX_FILE_SIZENoLargest local file an upload or file-read tool accepts: a byte count or a KB/MB/GB suffix (2GB default, 1 TB upper bound). Flag --upload-max-file-size
GITLAB_MCP_MAX_HTTP_CLIENTSNoHTTP mode: maximum unique (token, GitLab URL) server entries kept in the pool (100 default, upper bound 10000). Flag --max-http-clients. It bounds entries, not what an entry holds: the calls held open at once are bounded across the process by its descriptor limit (register row HLD-011, issue 951; 192 under a hard limit of 1024, 229120 under 524288), and on --stateless=false the sessions kept at half that (HLD-010; 96 under 1024); no flag moves either, and a call or an initialize past them is refused as busy
GITLAB_MCP_SESSION_TIMEOUTNoHTTP mode: idle MCP session timeout, --stateless=false only (30m default, max 24h). Flag --session-timeout. A session no client deletes holds one of the process's stateful session slots, and the held-call slot reserved for its stream, until it expires, and with 0 until the pool evicts its credential (after --pool-idle-timeout without a request, or to make room at --max-http-clients), which startup warns about: the process keeps at most half as many sessions as it may hold calls across every credential (register row HLD-010, issue 951; 96 under a hard descriptor limit of 1024), not configurable, and refuses the next initialize in the gate as busy
GITLAB_MCP_SESSION_REVALIDATE_INTERVALNoHTTP mode: token re-validation interval (15m default, 0 stops the periodic check, max 24h). Flag --revalidate-interval
GITLAB_MCP_YOLO_MODE / AUTOPILOTNoSkip the confirmation prompt on destructive actions when truthy (1, true, yes). GITLAB_MCP_YOLO_MODE decides whenever it is set; AUTOPILOT is the alias consulted only when it is not, so an inherited AUTOPILOT=true can be overridden. internal/toolutil.IsYOLOMode; flag --yolo-mode
GITLAB_MCP_ALLOWED_UPLOAD_DIRSNoExtra directories a tool may READ a local file from (every file_path and directory_path input), separated by the OS path-list separator. The working directory (unless it is the filesystem root or the user's home directory, which are dropped as implicit roots) and the OS temp directory are always allowed; a path is canonicalized through symlinks before the check. internal/toolutil.UploadDirAllowlistEnv
GITLAB_MCP_ALLOWED_DOWNLOAD_DIRSNoExtra directories a tool may WRITE a downloaded file into (output_path), same syntax and same always-allowed roots. Checked twice, once before creating the parent directories and once after, so the second call resolves a parent that now exists. The bytes go to a temporary file beside the destination, renamed over it only once complete, so a failed or cancelled download leaves output_path as it was; toolutil.WriteDownloadOutputFile is the one way a download reaches a caller-named path, and does both checks itself. internal/toolutil.DownloadDirAllowlistEnv
GITLAB_MCP_ALLOWED_IMPORT_DIRSNoExtra directories a project or group import archive may be read from, same syntax and same always-allowed roots. internal/toolutil.ImportArchiveAllowlistEnv
GITLAB_MCP_ALLOW_PRIVATE_INSTANCESNoPermit a destination the operator did not choose to be a private, loopback, CGNAT, link-local, unique-local or unspecified address (false default). Two destinations are not the operator's choice: an instance a caller named in the GITLAB-URL header under --allow-any-gitlab-url, and a redirect hop that left the configured instance's own host. An address --gitlab-url or GITLAB_URL named is never checked, whatever it resolves to, which is what keeps GitLab on localhost, on 10.x or behind a VPN working with nothing set; and a redirect to a private address is allowed anyway when the instance the operator configured itself resolves private, which is the self-managed object store; an instance a caller named never qualifies, and needs --allow-private-instances. The cloud metadata addresses (169.254.169.254, 169.254.170.2, fd00:ec2::254, 100.100.100.200) are refused on every hop this process dials for every client, and behind a proxy on every hop whose URL spells one, and this does not permit them. Enforced at the dialer, after DNS resolution, so it covers the first request and every redirect alike; behind HTTP_PROXY or HTTPS_PROXY the dialer sees only the proxy, which gets tier A alone, and the destination is judged per request in destinationTransport as far as its URL spells it (NEG-004 of ADR-0022). Flag --allow-private-instances; both transports. internal/gitlab/destination.go, ADR-0022
GITLAB_MCP_AUTH_MODENoHTTP mode auth: legacy (default) or oauth (RFC 9728 Bearer verification)
GITLAB_MCP_PUBLIC_URLNoExternally reachable https origin; required with GITLAB_MCP_AUTH_MODE=oauth (RFC 9728 resource identifier; flag --public-url)
GITLAB_MCP_TRUSTED_ORIGINSNoComma-separated absolute origins allowed to make cross-origin browser requests; * accepts any origin and disables the protection; empty adds none, though a configured GITLAB_MCP_PUBLIC_URL origin is trusted regardless (flag --trusted-origins)
GITLAB_MCP_OAUTH_CACHE_TTLNoOAuth token identity cache TTL (15m default, range 1m to 2h). The cache holds at most 10000 identities whatever the TTL and, when full, drops an expired one or else the one used least recently (register row ADM-005, issue 950); at most 16 tokens it does not hold are verified at once across the process, a new one waits up to 5 s for a slot and is then refused 503 -50300 with Retry-After, uncharged, in the words a verification with no verdict gets (ADM-014). Neither bound is configurable, and the ceiling bounds concurrency, not rate
GITLAB_MCP_OAUTH_CLIENT_UIDNoComma-separated GitLab OAuth application uids whose tokens are admitted (flag --oauth-client-uid). Empty (default) admits any credential the instance accepts; setting it refuses personal access tokens, which belong to no application. RFC 8707 audience binding is unavailable — GitLab publishes no resource_indicators_supported — so this is the specification's "otherwise verify" alternative (ADR-0019)
GITLAB_MCP_POOL_IDLE_TIMEOUTNoHTTP mode: reclaim a pooled per-token-and-URL credential entry after this long unused (1h default, 0 disables, max 24h). An entry with a live subscription is never idle by this measure, and size pressure prefers an entry that is not, so a quiet subscriber is only evicted when every entry is one
GITLAB_MCP_ACTION_TIMEOUTNoCancel an action still running after this long, in both transports (65m default, 0 disables, max 24h). Applied in the four toolutil.WrapAction functions every action is registered through, so it ends a handler whose client is still waiting; the transports already cancel a call whose client went away. The two void variants were skipping it until 2.8.0, which left deletes, cancels and retries unbounded. Above the longest wait any action offers (a pipeline wait caps itself at 3600 s). It reaches GitLab only through a request that carries the handler's context (gl.WithContext(ctx)), and so it bounds a file transfer too: an upload or download still running at the limit ends with its action. Flag --action-timeout in HTTP mode
GITLAB_MCP_DRAIN_DELAYNoHTTP mode: after SIGTERM, keep the listener open and answer /health with 503 draining (Cache-Control: no-store) for this long before closing it, so a balancer that polls /health removes the instance before the close (0 default, max 5m). Set it to at least one probe interval. /health also carries build (closest release plus short commit, .dirty when the tree had changes; cmd/server/health.go) and config_digest (twelve hex over tool surface, capability surface, meta parameter schema, tier and whether it was pinned or is detected, scope detection, read-only, safe mode and excluded tools; a comparison fingerprint, not a secret) so the instances behind one balancer can be compared. Flag --drain-delay
GITLAB_MCP_RATE_LIMIT_RPSNoPer-credential rate limit, in req/s, on every call that reaches GitLab (tools/call, resources/read, resources/subscribe, subscriptions/listen, prompts/get) (0 = disabled). The bucket lives on the pool entry, so each token and URL pair is limited on its own, whatever server shape serves it. tools/list is charged too, on a bucket of its own refilled a tenth as fast, for the opposite reason to the rest: it reaches no GitLab, and instead spends the processor every tenant of the process is waiting for (about 3.2 MB marshalled per listing on the individual surface). Its burst is the configured one, undivided, so a fleet of clients sharing one credential can still all discover at once; the refill is what bounds a client listing in a loop. Keeping the buckets apart is what lets a drained tool-call bucket still answer a client's discovery. A listing is charged first to a bucket the whole process shares, counted in the tools a listing carries (3000 tools a second, 48000 in hand; register row RTC-007), because a credential's bucket multiplies by however many tokens a caller holds and the processor does not; it is not configurable, is off with the rest of the limiter at 0, and refuses in the credential's own words, the log line alone naming it (scope=process). On stdio this variable is the only switch, since stdio ignores --rate-limit-rps and says so at startup (issue 1045), and its default of 0 is issue 959's position on MCP's "Rate limit tool invocations": met by default in HTTP mode, off by default on stdio, where one process serves one person (test/e2e/stdio/rate_limit_test.go holds both halves)
GITLAB_MCP_RATE_LIMIT_BURSTNoToken-bucket burst size when RPS > 0 (40 default)
GITLAB_MCP_AUTH_FAILURE_LIMITNoFailed authentications one address may produce inside the failure window before it is blocked (10 default, max 100000). 0 turns the budget off, and that is the one value it must not be read literally on: the limiter blocks once a record reaches its limit, so a zero would block an address after a single failure, which is the harshest setting there is reached by typing the figure every other budget here reads as "none". cmd/server.authFailureLimiter returns nil instead, and every consulting site already tolerates that
GITLAB_MCP_AUTH_FAILURE_WINDOWNoWindow the failure budget counts in (1m default, max 24h), and the step the distinct-credential escalation is built from: one window, then ten, then sixty, reset after sixty of silence. Deriving the ladder rather than giving it four more settings is what lets a test set this to a second and watch the whole thing in seconds
GITLAB_MCP_AUTH_DISTINCT_TOKEN_LIMITNoDistinct credentials one address may have refused inside the distinct window before it is blocked, for longer each time (50 default, max 100000, 0 disables). It asks a different question from the failure budget, and that is what makes it safe to escalate on: ten failures in a minute is a stuck client as much as an attack, while fifty distinct invalid tokens is only an attack, since a person has one token and a fleet behind a NAT has one each. Credentials are held as truncated SHA-256 digests, never in the clear
GITLAB_MCP_AUTH_DISTINCT_TOKEN_WINDOWNoWindow the distinct-credential budget counts in (10m default, max 24h)
GITLAB_MCP_CLIENT_COMPATNoPer-client response compatibility (auto default): Codex sessions get float priority in annotations rounded to 0/1; off disables. Choosing a response from clientInfo departs from MCP 2026-07-28's SHOULD NOT on purpose (issue 959, register row IDN-013): it only changes how one number is written, never who a caller is or what it may do, and it retires with row 17 of docs/development/upstream-bugs.md. It reaches only a session that knows its client: a Codex client on protocol 2025-11-25 or earlier over the default stateless HTTP transport is sent the fraction, since no later POST's session saw its initialize (test/e2e/http pins that). Read from the process environment in both stdio and HTTP modes; the --client-compat flag writes the same variable. See internal/clientcompat and docs/guides/client-compatibility.md
GITLAB_MCP_DESCRIPTION_SUBSTITUTIONSNoRewrite listed catalog text for strict MCP gateway validators: comma-separated old=new pairs applied in order to every listed description and title (backslash escapes \, \= \\). Covers tools (all surfaces, schema-embedded descriptions included), prompts, resources, and resource templates; never names, URIs, pattern, const, enum values, or tool-call payloads. Malformed values refuse startup. Flag --description-substitutions; both modes. The served surface itself stays pure ASCII with no semicolons (make check-gateway-chars); verify a config with go run ./cmd/audit_gateway_chars/ -apply -check. See internal/gatewaycompat and docs/guides/client-compatibility.md
GITLAB_MCP_TELEMETRYNoExport OpenTelemetry traces, metrics and logs over OTLP (false default). Off for privacy: telemetry goes to a collector the operator configures, never to the maintainer; the exporters' only default is their own localhost. Endpoint, credentials, sampling and batching all come from the standard OTEL_EXPORTER_OTLP_* variables the exporters read themselves. OTEL_SDK_DISABLED=true vetoes it regardless. Flag --telemetry. See docs/guides/telemetry.md
GITLAB_MCP_TELEMETRY_IDENTITYNoHow much telemetry records about who made a call: none (default, records nobody), pseudonymous (a per-process HMAC digest that correlates one caller's calls without naming them), or full (user.id and user.name). Identity never reaches a metric under any policy. Flag --telemetry-identity
GITLAB_MCP_TELEMETRY_IDENTITY_KEYNoSecret the pseudonymous policy derives its pseudonymisation keys from (HKDF-SHA256, one key for callers and one for resource URIs). Empty (default) generates one per process, so a digest identifies a caller within one process and nowhere else. Set it when several replicas must agree, or when a distinct-user count has to survive a restart; it then never rotates here, because a key the operator supplied is theirs to rotate. Setting it makes the pseudonym a person pseudonym in EDPB terms, and the key is Article 4(5) "additional information": keep it away from wherever the telemetry lands, since GitLab user ids are small enough to enumerate against a known key. No flag on purpose: process arguments are readable through /proc by any local principal
GITLAB_MCP_TELEMETRY_IDENTITY_ROTATIONNoHow long a generated pseudonymisation key lives, e.g. 24h. Empty or 0 (default) keeps it for the life of the process; maximum 30 days. Ignored when GITLAB_MCP_TELEMETRY_IDENTITY_KEY is set, with a warning at startup. Off by default because replicas start at different moments and would rotate out of phase, churning a distinct-user count nobody asked to churn. Flag --telemetry-identity-rotation
GITLAB_MCP_TELEMETRY_TOOL_NAMENoWhether gen_ai.tool.name is a metric dimension: auto (default), on or off. Auto keeps it on the dynamic and meta surfaces and drops it on individual, where ~1094 tools would exhaust the SDK's 2000-series cardinality limit and collapse the long tail into one otel.metric.overflow bucket, first-come-wins under cumulative temporality. Implemented as a metric View, because filtering runs before the limit is counted. Flag --telemetry-tool-name
GITLAB_MCP_LOG_LEVELNoLogging verbosity (debug, info, warn, error). Flag --log-level
GITLAB_MCP_PPROF_ADDRNoServe Go's profiling handlers (net/http/pprof) on this address, on an http.Server of their own that starts before the transport and stops with the process, so a CPU profile of startup can be taken. Loopback only (127.0.0.1:port, [::1]:port, localhost:port): anything else is refused at startup, because a heap profile is a copy of the process's memory and the handlers take no credential. Empty (default) serves nothing. Both transports; flag --pprof-addr. cmd/server/pprof.go; the benchmark's concurrency series starts the server with it
MODELEVAL_MODELSNotest/e2e/modeleval: comma-separated provider:model;key=value specs a run asks. fake:perfect replays each case's own answer key through the whole pipe with no provider call, which is the rehearsal; folding a fake run publishes nothing and refuses every row by name
MODELEVAL_SPENDNotest/e2e/modeleval: the consent a run asking a real provider needs (yes, true, 1). Empty is no. A misspelled value is refused rather than read as no, because a run refused for a typo costs a moment and a run started by one costs money
MODELEVAL_BUDGET_USDNotest/e2e/modeleval: the ceiling in US dollars a run stops at. MODELEVAL_UNPRICED lets a run start with a model the price table has no figure for, which otherwise refuses
MODELEVAL_SURFACESNotest/e2e/modeleval: surfaces to measure (dynamic,meta by default). Individual is left out by cost, not by disinterest: its tools/list is 682,878 tokens at Ultimate, so it can only be put to a model on a deterministic slice, and MODELEVAL_SLICE (128) is that budget
MODELEVAL_CASESNotest/e2e/modeleval: comma-separated case IDs; empty asks every case. This is how one corrected case is re-run and re-folded on its own
MODELEVAL_MODE, MODELEVAL_TIER, MODELEVAL_META_PARAM_SCHEMA, MODELEVAL_REPEAT, MODELEVAL_PARALLEL, MODELEVAL_PROBENotest/e2e/modeleval: the protective mode, the tier pin, the meta schema mode served, how many times each attempt runs, how many are in flight, and the consent the provider contract probe needs. Each counted setting has a ceiling, so a mistyped figure is a refusal rather than a bill
GITLAB_MCP_TEST_INVENTORY_DIRNointernal/testutil: absolute directory the test transport records every request it sees into, one shard per test process, merged by cmd/gen_request_inventory. Empty (default) records nothing. A relative path is refused rather than resolved, because a test binary runs in its own package directory and would scatter a shard under each of 178 of them
GITLAB_MCP_TEST_SNAPSHOT_PARITYNoEvery unit test that compares a committed, generated artifact with what the tree generates now: deferred skips it with a message saying why, through the one reader, internal/freshness. Five packages read it: internal/tools (the golden snapshots: TestToolSnapshots_* and the two GoldenSnapshotParity tests), cmd/audit_tokens (the token footprint targets), cmd/gen_llms (one subtest per committed llms file, and only those: the surface facts asserted beside them are not about a committed artifact and keep running), cmd/audit_metrics (site/src/data/stats.json) and cmd/gen_lhm_manifest (lhm.plugin.json). CI sets it from FRESHNESS in ci.yml, in the coverage job and the cross-platform matrix alike, which is deferred on every layer of a GitHub stack below its top (told by github.event.pull_request.stack.position, since a stacked layer is tested as the stack merged into main and github.base_ref is main for all of them) and on a pull request outside a stack whose base is not main, and checked at the top of a stack, on a pull request to main and on a push to main: every freshness gate (stats, llms, footprint, testing reference, manifests, request inventory, snapshots) compares a committed artifact with what the tree generates now, and a stack refreshes those once at its top. Empty (default) compares, which is also what the race workflow and a developer's machine do. A test that pins the value to checked must therefore compare no committed artifact, or it fails on exactly the layer the deferral exempts

None of the three GITLAB_MCP_ALLOWED_*_DIRS allow-lists applies in HTTP mode: a server reached over HTTP refuses every caller-supplied local path, since the caller has no files on the machine the server runs on and content_base64 is the remote form. The transport is inferred from the process arguments in internal/toolutil/file_utils.go, so a deployment that never heard of this policy still gets the right answer.

In HTTP mode, configuration is resolved in three layers: an explicitly passed flag, then the environment variable with the same meaning (internal/config/http_overlay.go reads only the variables actually present, validated with the same parsers and bounds as stdio), then the built-in default. A variable exported without its flag is therefore honored, and an invalid value fails startup rather than falling back silently. Every flag in this table but the four telemetry ones, which both transports read, lands in httpConfig, which a stdio run never reads, so a stdio run given one names it at startup and ignores it (cmd/server/http_only_flags.go, issue 1045): one WARN line listing each with the variable stdio reads instead (--max-request-body-bytes names GITLAB_MCP_STDIO_MAX_LINE_BYTES, the line ceiling that bounds the same message). Under --transport=auto, whose command line serves either transport, a flag stdio has no setting for at all (the image's own --http-addr, the pool, the authentication gate) is named at INFO instead, and a setting stdio has a variable for stays at WARN. The condition for refusing rather than naming is what ignoring the value would cost, the rule config.RetiredEnvUses applies to the retired names, and two kinds refuse the start in either case: --read-only, --safe-mode or --exclude-tools asking to withhold something (register row AUT-004's three), since ignoring one serves it, and a --gitlab-url naming no instance a stdio run connects to, since stdio sends GITLAB_TOKEN to the one GITLAB_URL names, https://gitlab.com when it is unset. A flag is refused even when its variable already asks for the same thing, as a retired name is beside its replacement. httpOnlyFlags is held to the registrations into httpConfig by a test that reads the source, each variable it names to what stdio reads and, through the HTTP environment overlay, to the field its flag writes, and test/e2e/stdio/http_only_flags_test.go holds the lines and both refusals against the binary, the second with an instance counting that no request reached it:

FlagDefaultDescription
--gitlab-url—GitLab instance URL. Required in HTTP mode unless --allow-any-gitlab-url is passed: a deployment that names no instance makes requests to whatever host a caller puts in GITLAB-URL, with whatever token that caller supplied. Repeatable/comma-separated: all are published in RFC 9728 authorization_servers, and GITLAB-URL then selects among them. With several published the header is required in both auth modes (400 without it), and a value outside the list is refused rather than ignored (400 from the legacy gate, 403 from the oauth bearer guard). The refusal names the published instances only in oauth mode, where RFC 9728 metadata already serves that same set unauthenticated; legacy mode publishes no metadata and rejects before the credential is judged, so it says to ask the operator rather than let any non-empty token enumerate the operator's hostnames
--allow-any-gitlab-urlfalseStart with no instance published, letting GITLAB-URL name any host. For a single-user local deployment where the operator is the caller, and refused anywhere else: --http-addr must bind a loopback address or a unix socket, since on a listener anyone else can reach the hatch is the request forgery of GHSA-fcj2-hj27-hj26 opted into. It warns at startup even on loopback. cmd/server.listenerIsHostLocal
--skip-tls-verifyfalseSkip TLS verification for self-signed certs
--tool-surface(empty)Explicit tool catalog selector: meta, individual, or dynamic; empty serves the default dynamic surface
--capability-surfacefullResource and prompt catalog selector: full or minimal
--meta-param-schemaopaqueMeta-tool input-schema mode: opaque, compact or full (same setting as GITLAB_MCP_META_PARAM_SCHEMA)
--tier(empty)Force licensing tier: free, ce, premium, or ultimate. When set, used verbatim with no license check; when omitted, the tier is detected per token+URL pool entry by the same two steps GITLAB_MCP_TIER describes, the instance license then the namespace plans, falling back to free with a warning on an enterprise build
--read-onlyfalseRead-only mode: removes mutating operations per action; reads keep working
--safe-modefalseSafe mode: intercepts mutating operations per action, returns preview
--embedded-resourcestrueEmbed canonical MCP resource URIs in get-style tool results
--exclude-tools(empty)Comma-separated tool names, group names or canonical action IDs to exclude, on every surface
--ignore-scopesfalseSkip the scope filter and the read-only narrowing and register every tool the tier allows; the token's scopes are still read, so a token carrying neither read_api nor api is still refused (issue 952), and a fine-grained token's grant still decides what it is shown
--max-http-clients100Maximum unique (token, GitLab URL) server entries kept in the pool; bounds pooled entries, not sessions or the calls they hold, which the process bounds on its own by its descriptor limit (HLD-011: an eighth spare, one descriptor per listen stream at its 512, two per held call; 192 held calls under a hard limit of 1024; not configurable) and, on --stateless=false, at half that for sessions (HLD-010, 96). Positive and at most 10000, checked by validateHTTPPoolAndRateBounds in cmd/server/main.go along with the rate-limit ceilings: HTTP mode never runs (*config.Config).validate, so those documented bounds went unenforced there until 2.8.0 and a non-positive value fell back to the pool's own default of 100 without saying so
--session-timeout30mIdle MCP session timeout; applies to --stateless=false only, since under the default stateless transport each POST's session ends with its response. A session nobody deletes holds one of the process's session slots (HLD-010, 96 under a hard descriptor limit of 1024) until it expires, and with 0 until the pool evicts its credential, which startup warns about
--http-idle-timeout0 (disabled)HTTP server idle connection timeout; 0 (default) disables idle closure so --session-timeout is the effective lifetime; set a positive duration to recycle idle connections sooner
--statelesstrueSessionless streamable HTTP (SEP-2567 / protocol 2026-07-28; default): no Mcp-Session-Id tracking, every POST is self-contained, GET/DELETE return 405; synchronous server-initiated requests are unavailable, but protocol 2026-07-28 clients keep elicitation through MRTR. Use --stateless=false for legacy stateful sessions. Stateful sessions are capped across the process at half the held-call ceiling (HLD-010), and each session reserves a held-call slot (HLD-011) for its standalone GET stream when it opens, so a session the process keeps is never refused its stream; a POST on protocol 2026-07-28 or later takes no slot, since the stateful transport answers it with the revisions it serves
--json-responsefalseReturn application/json response bodies instead of text/event-stream (SSE)
--max-request-body-bytes0Maximum streamable HTTP request body size in bytes; 0 uses the SDK default (4 MiB)
--http-addr:8080Listen address. host:port binds TCP; a value containing a path separator binds a unix socket instead. Host-local: a same-host proxy connects through it and the TCP hop between them disappears rather than being encrypted; remote clients still arrive via that proxy
--http-socket-mode0660Octal permission mode for a unix socket named by --http-addr
--tls-cert / --tls-key—PEM certificate and key; serves HTTPS on the listener itself, for a proxy that does not share the machine. Both or neither, TLS 1.2 floor. Served through tls.Config.GetCertificate (cmd/server/tls_reload.go), which stats both files on each handshake and re-reads the pair when either changed, so a rotation is two file writes and no restart; a half-written or unreadable pair keeps the previous certificate and warns once. The first load is still strict and stops startup. ServeTLS is deliberately given no filenames, since net/http would replace the callback's certificate with one startup load of the named files
--auth-modelegacyAuthentication mode: legacy or oauth (RFC 9728 Bearer verification)
--public-url(empty)Externally reachable https origin; required with --auth-mode=oauth (RFC 9728 resource identifier and metadata-URL derivation)
--resource-documentation(empty)https URL published as RFC 9728 resource_documentation; point it at a page describing your own OAuth application. Empty publishes this project's HTTP server mode page
--resource-policy-uri(empty)https URL published as RFC 9728 resource_policy_uri; your own page on what this deployment does with the data reached through it. Empty omits the field, which is the right default: a link to a page that does not exist would land on a consent screen
--resource-tos-uri(empty)https URL published as RFC 9728 resource_tos_uri; your own terms of service. Empty omits the field
--oauth-cache-ttl15mOAuth token identity cache TTL (range 1m to 2h); the cache holds at most 10000 identities, an expired one or else the least recently used dropped first, and verification runs at most 16 at a time (ADM-005, ADM-014)
--oauth-client-uid(empty)Comma-separated GitLab OAuth application uids whose tokens are admitted; empty admits any credential the instance accepts
--pool-idle-timeout1hReclaim a pooled per-token-and-URL credential entry after this long unused; 0 keeps entries until the pool size bound evicts them (upper bound: 24h). An entry with a live subscription is never idle by this measure
--action-timeout65mCancel an action still running after this long; 0 disables it (upper bound: 24h). Falls back to GITLAB_MCP_ACTION_TIMEOUT
--drain-delay0After SIGTERM, keep the listener open and answer /health with 503 draining for this long before closing it, so a balancer that polls /health removes the instance before the close (upper bound: 5m); 0 closes at once. Falls back to GITLAB_MCP_DRAIN_DELAY
--revalidate-interval15mToken re-validation interval; 0 stops the periodic check, but an entry whose credential is older than 1h is still rebuilt, which re-runs the probe. Upper bound 24h
--trusted-proxies(empty)Comma-separated addresses or CIDR ranges of the reverse proxies whose --trusted-proxy-header is believed (e.g. 127.0.0.1,10.0.0.0/8). From any other peer the header is ignored and the peer itself is charged, so a caller who reaches the listener directly cannot choose the address its failures count against. For X-Forwarded-For the value is read from the right, skipping hops that are themselves listed, so the first hop nobody in the list vouches for is the client; a hop that is not an address charges the peer. Required with --trusted-proxy-header, and refused without it. cmd/server/client_ip.go
--trusted-proxy-header(empty)HTTP header with real client IP for rate limiting behind proxies (e.g. CF-Connecting-IP, X-Forwarded-For); believed only on a connection from an address in --trusted-proxies, which it requires
--rate-limit-rps10Per-credential rate limit, in req/s, on every call that reaches GitLab (tools/call, resources/read, resources/subscribe, subscriptions/listen, prompts/get) (0 disables it), plus tools/list on a separate bucket refilled a tenth as fast, with the same burst, charged because it spends the shared processor rather than because it reaches GitLab. The bucket lives on the pool entry, not on the shared server, so each token and URL pair is limited on its own. A listing is also charged, first, to one bucket the whole process shares, in tools listed (3000 a second, 48000 in hand, not configurable, RTC-007), which is what bounds the processor however many credentials list, and which 0 turns off with the rest. On by default in HTTP mode; the GITLAB_MCP_RATE_LIMIT_RPS env var used by stdio still defaults to 0
--rate-limit-burst40Token-bucket burst size when --rate-limit-rps > 0
--auth-failure-limit10Failed authentications one address may produce inside --auth-failure-window before it is blocked (0 disables the budget rather than blocking on the first failure)
--auth-failure-window1mWindow the failure budget counts in, and the step the distinct-credential escalation is built from. A 429 announces in Retry-After the longest block actually holding the request rather than this window, since one failure can raise the minute-long lockout and an hour-long escalated block together and announcing the shorter one would tell a client to come back while it is still refused (longestAuthBlock in cmd/server/auth_gate.go)
--auth-distinct-token-limit50Distinct credentials one address may have refused inside --auth-distinct-token-window before it is blocked, for longer each time (0 disables). The admitted-credential exemption applies here too: a credential the pool already holds is still served from a blocked address
--auth-distinct-token-window10mWindow the distinct-credential budget counts in
--telemetryfalseExport OpenTelemetry traces, metrics and logs over OTLP. Applies to both transports. Endpoint and credentials come from the standard OTEL_EXPORTER_OTLP_* environment
--telemetry-identitynoneWhat telemetry records about the caller: none, pseudonymous or full
--telemetry-tool-nameautoWhether gen_ai.tool.name is a metric dimension: auto, on or off
--telemetry-identity-rotation(empty)How long a generated pseudonymisation key lives, e.g. 24h; ignored when a key is configured

General flags (both stdio and HTTP modes):

FlagDefaultDescription
--httpfalseServe HTTP instead of stdio
--transport(empty)stdio, http or auto; empty defers to --http. auto serves HTTP only when stdin is /dev/null (a container started without -i) and stdio for the pipe every MCP client provides. cmd/server/transport.go
--env-file(empty)Dotenv file to load besides ~/.gitlab-mcp-server.env; the same setting as GITLAB_MCP_ENV_FILE, and wins over it
--tool-search(empty)Search the canonical action catalog by ID, tool name, alias, tag or description and exit. It searches the catalog, not a server's registered tools, because the default dynamic surface registers two and every other query used to answer "No tools found"; the actions found are therefore the same on every surface, and the surface decides only how each row names the call (individual tool, meta group tool plus action=, or the canonical ID gitlab_execute_action takes). Surface and tier come from --tool-surface and --tier when passed and otherwise from GITLAB_MCP_TOOL_SURFACE and GITLAB_MCP_TIER, so a stdio deployment searches what it serves. No credentials needed
--versionfalsePrint version and exit
--help / -hfalseCurated help with flags, env vars and examples (both spellings give the same output)
--allow-private-instances(empty)true permits a destination the operator did not choose to be a private, loopback or CGNAT address: an instance a caller named in GITLAB-URL under --allow-any-gitlab-url, or a redirect hop that left the configured instance. Cloud metadata addresses stay refused whatever it says, and an address --gitlab-url named is never checked. Writes GITLAB_MCP_ALLOW_PRIVATE_INSTANCES; both transports. ADR-0022
--log-level, --client-compat, --upload-max-file-size, --yolo-mode, --description-substitutions, --pprof-addr(empty)Flags for settings whose only home used to be an environment variable. Each writes its variable (the GITLAB_MCP_ spelling, or GITLAB_MCP_YOLO_MODE) before anything reads it, so there stays one reader per setting and an explicitly passed flag beats the environment. GITLAB_TOKEN deliberately has no flag: a token on a command line is readable through ps and shell history. cmd/server/env_flags.go
--shutdownfalseTerminate all running instances of this binary and exit. Used by external updaters (pe-agnostic-store) before replacing the binary on disk.
--probefalseAsk the running instance's /health and exit 0 when it answers 200; the image's HEALTHCHECK. With no argument it finds the other instances of this binary (the same lookup as --shutdown), reads --http-addr, --tls-cert, --transport and --http off their command lines, and probes where they listen: another port, a unix socket, or HTTPS pinned to the certificate --tls-cert names (a given https:// target takes the pin from the probe's own --tls-cert, and the standard verification without one). --transport auto is settled the way the server settled it, by reading the instance's file descriptor 0 from procfs; an instance serving stdio has nothing to probe and is reported healthy while it runs. A URL, unix:<path> or host:port after the flag probes that instead. Exit 1 when nothing answered, 2 for a target that does not parse. cmd/server/probe.go

AI Assistance Infrastructure

This project includes a comprehensive set of AI agents, skills, and instruction files in .github/ to support development workflows. All are oriented toward development tasks, not end-user usage.

Instructions (Auto-loaded by File Pattern)

Instruction files in .github/instructions/ are automatically applied when editing matching files:

InstructionApplies toPurpose
go.instructions.md**/*.go, **/go.mod, **/go.sumIdiomatic Go practices, naming, error handling, package rules
go-mcp-server.instructions.md**/*.go, **/go.mod, **/go.sumMCP server patterns: tool registration, typed I/O, annotations, transport
mcp-best-practices.instructions.md**/*.goProtocol-level tool design, response formats, pagination, security
test-goroutines.instructions.md**/*_test.goThe six-rule contract for assertions off the test goroutine (make check-test-goroutines)
security-and-owasp.instructions.md*OWASP Top 10, input validation, secrets management, injection prevention
code-review-generic.instructions.md**Code review priorities (Critical/Important/Suggestion), checklist
context-engineering.instructions.md**Project structure principles for AI-readable code
self-explanatory-code-commenting.instructions.md**Comment only WHY, not WHAT; avoid redundant comments

Agents (7 Specialized AI Agents)

Agents are invoked explicitly for specific development tasks. Each agent has a focused role:

Core Development

AgentFileWhen to Use
Go MCP Server Expertgo-mcp-expert.agent.mdImplementing new MCP tools, fixing tool handlers, MCP SDK questions. The primary coding agent for this project. Has Context7 integration for up-to-date library docs.
Debug Modedebug.agent.mdSystematic bug investigation: reproduce → hypothesize → fix → verify. 4-phase workflow.

Testing

AgentFileWhen to Use
Test Experttest-expert.agent.mdWriting, analyzing, and improving Go tests. Covers new test development, existing test analysis, coverage analysis to 90%+, false-pass detection, edge case identification, mandatory test documentation, and refreshing docs/development/testing/testing.md with cmd/gen_testing_docs at phase completion. Uses Context7 for up-to-date Go testing docs.

Planning & Architecture

AgentFileWhen to Use
Plan Expertplan-expert.agent.mdStrategic planning for features, refactoring, architecture, tests, bugs, docs, and upgrades. 7 planning modes with structured output to plan/. Uses Context7 for dependency research. Does NOT generate code.

Documentation

AgentFileWhen to Use
Documentation Writerdocumentation-writer.agent.mdGenerate project documentation (architecture, references, guides). Uses Diátaxis framework + Mermaid diagrams. Uses Context7 and web fetch for up-to-date external references, specs, and protocol docs. Validates output with markdownlint-cli2.
Go Source Documentergo-source-documenter.agent.mdAdd godoc-compliant doc comments to Go source and test files. Covers file headers, package comments, functions, types, interfaces, tests (detailed what/how/expected/why), benchmarks, fuzz tests, examples, deprecation notices, and BUG/TODO annotations. Uses Context7 for up-to-date Go doc conventions.

Security & Architecture

AgentFileWhen to Use
SE: Reviewerse-reviewer.agent.mdSecurity review (OWASP Top 10, LLM security, Zero Trust) and architecture review (Well-Architected frameworks, ADRs). Two modes in one agent.

Skills (18 Reusable Task Templates)

Skills are task templates that can be invoked by any agent or directly. They define structured workflows:

Documentation Skills

SkillDirectoryPurpose
Generate Project Documentationgenerate-project-documentation/Full documentation suite (architecture, package docs, tool references, onboarding). Diátaxis framework.
Update Project Documentationupdate-project-documentation/Delta-update docs after code changes. Maps changes to affected documents.
Update Starlight Docsupdate-starlight-docs/Update Astro Starlight user docs (EN/ES) when developer docs change.
Go Source Documentationgo-source-documentation/Add godoc-compliant comments to Go files. 11 documented patterns specific to this project.

Planning & Design Skills

SkillDirectoryPurpose
Create Implementation Plancreate-implementation-plan/Structured plan with phased tasks (TASK-001, etc.). Saves to plan/.
Create ADRcreate-architectural-decision-record/ADR with standardized format (POS-001, NEG-001, etc.). Saves to docs/development/adr.
Create Specificationcreate-specification/Formal spec with requirements (REQ-001), acceptance criteria (Given-When-Then). Saves to spec/.

Quality & Testing Skills

SkillDirectoryPurpose
Increase Test Coverageincrease-test-coverage/Research → Plan → Implement pipeline to reach 90%+ coverage. Uses httptest mocks specific to GitLab API.
Review and Refactorreview-and-refactor/Review code quality + MCP patterns + OWASP, then refactor. Reads all instruction files for context.
Go Testing Patternsgolang-testing/Reference: table-driven tests, subtests, benchmarks, fuzzing, httptest, TDD methodology.
Go Patternsgolang-patterns/Reference: error handling, concurrency, interfaces, structs, memory, anti-patterns.

Evaluation & Operations Skills

SkillDirectoryPurpose
Create MCP Evaluationcreate-mcp-evaluation/Generate 10 Q&A pairs to benchmark MCP server quality. Multi-hop, read-only, verifiable answers.
Generate Release Notesgenerate-release-notes/Categorized release notes between two Git refs (commits + merged MRs) for any GitLab project reachable through the server.
Git Commitgit-commit/Conventional commit with auto-detected type/scope from diff. Follows project's feat:/fix:/docs: convention.

Refactoring Skills

SkillDirectoryPurpose
Go Safe Move Refactorgo-safe-move-refactor/Safely move Go source files between packages with zero compilation downtime. Handles imports, stubs, tests.
Modularize Go Packagemodularize-go-package/Modularize a monolithic Go package into domain sub-packages. Designed for large-scale 50–100+ file refactoring.

MCP Development Skills

SkillDirectoryPurpose
Create MCP Toolcreate-mcp-tool/End-to-end workflow for creating a new MCP tool: sub-package, structs, handler, ActionSpec metadata, markdown, tests, catalog projection, and documentation.
Upstream Contributionupstream-contribution/Contribute fixes to upstream gitlab.com/gitlab-org/api/client-go. Fork → branch → fix → test → MR workflow.

Common Development Workflows

Adding a new GitLab API tool

  1. Plan: Use @Plan Expert agent to define scope and generate implementation plan
  2. Specify: Use create-specification skill if complex
  3. Test: Use @Test Expert to write comprehensive tests (new tests or coverage analysis)
  4. Implement: Use @Go MCP Server Expert to implement the tool
  5. Verify: Run targeted analysis on changed packages (see "Post-implementation verification" above)
  6. Document: Use @Go Source Documenter for code, then update-project-documentation skill for docs
  7. Commit: Use git-commit skill with conventional commit format

Increasing test coverage

  1. Use @Test Expert agent — it runs go test -coverprofile, identifies gaps, detects false passes, generates documented tests, and refreshes docs/development/testing/testing.md with go run ./cmd/gen_testing_docs/ at the end of the test phase
  2. Or use increase-test-coverage skill for the same workflow invoked from any agent

Reviewing code quality

  1. Use review-and-refactor skill — reads all .github/instructions/ files, reviews against them, then refactors
  2. For security or architecture review: Use @SE: Reviewer agent (specify "review security" or "review architecture")

Debugging a failing test or unexpected behavior

  1. Use @Debug Mode agent — systematic 4-phase investigation
  2. Provide the error message, test name, or failing behavior

Checking library documentation

  1. Use @Go MCP Server Expert agent — has Context7 integration, resolves library ID, fetches current docs
  2. Useful for MCP SDK, GitLab client, or any Go dependency questions

Updating documentation after changes

  1. Use update-project-documentation skill — analyzes code delta, maps to affected docs, applies surgical updates
  2. For full regeneration: Use generate-project-documentation skill

Architecture Decisions

ADRs document key decisions in docs/development/adr:

ADRDecisionStatus
ADR-0004Modular sub-packages under internal/tools/{domain}/Accepted (180 internal/tools packages; tools by tier: ~868 Free/CE, ~1022 Premium, ~1088 Ultimate self-managed, ~1094 GitLab.com Ultimate)
ADR-0005Meta-tool consolidation into a compact domain catalogAccepted (refines ADR-0004; its runtime mechanics are superseded by the catalog-first architecture of ADR-0014)
ADR-0006Raw GraphQL.Do() for domains without client-go service wrappersAccepted (7 GraphQL-only domains)
ADR-0007Rich error semantics for LLM-actionable diagnosticsAccepted (WrapErrWithMessage, WrapErrWithHint)
ADR-0008Universal user identity across transport modesAccepted, partially unimplemented (stdio and HTTP OAuth populate it; HTTP legacy does not)
ADR-0009Progressive GraphQL migration strategyAccepted (trigger-based REST→GraphQL migration)
ADR-0010No resource subscribe capabilitySuperseded by ADR-0015
ADR-0011Low-token dynamic toolset modeAccepted (gitlab_find_action + gitlab_execute_action, the default surface)
ADR-0012Action catalog package nameAccepted
ADR-0013Documentation artifact boundariesAccepted (what is generated, what is hand-written, and who owns each)
ADR-0014Catalog-first runtime architectureAccepted (every surface is projected from ActionSpec; cmd/audit_catalog_first enforces it)
ADR-0015Polled resource subscriptions (supersedes ADR-0010)Accepted (26 subscribable kinds, 10 watchers/token and 512 per process, lease demotes rather than stops)
ADR-0016No webhook ingestionAccepted (Reader seam unchanged; no inbound HTTP surface added)
ADR-0017Pull-safe event sources surveyed and declinedAccepted (Events API, ActionCable, ETag probed live; polling stays the only freshness source; revisit triggers recorded)
ADR-0018Authorization admits at the minimum scope; writes gated per actionAccepted (a read_api token is admitted and served a read-only surface; tools/list stays authenticated per the MCP authorization spec)
ADR-0019Audience binding is unavailable at the authorization serverAccepted (GitLab publishes no resource_indicators_supported; --oauth-client-uid is the "otherwise verify" alternative)
ADR-0020One MCP server per configuration shape, owner-filtered deliveryAccepted (HTTP mode shares one server per shape; the credential is bound per request and resource-updated notifications are filtered by pool entry)
ADR-0021A field client-go does not model is read from the captured responseAccepted (gitlabclient.WithResponseCapture in the SDK transport chain; the invites pattern stays for an endpoint client-go has no method for)
ADR-0022An operator-named instance is exempt from the outbound destination guardAccepted (tier A refuses cloud metadata addresses on every hop; tier B refuses private addresses only for a caller-named instance or an off-origin redirect; an address --gitlab-url named is never checked)
ADR-0023Tenant policy is declared once, in a register the layers readAccepted (internal/tenancy holds every decision about who a caller is and what it may hold, Validate holds the rows to the specification's invariants, and the layers keep enforcing)
ADR-0024Fine-grained token authority is evaluated per action from GitLabAccepted (a token whose scope list is granular is unknown authority and never narrowed to read-only by it; phase A withholds what no fine-grained token can reach at the GitLab release the permission table was recorded from, phase B lists what a readable grant reaches; the grant is never a key, and R-GRANT holds the generated table to the live record)

Modular tools sub-packages (ADR-0004)

The internal/tools/ package family is split into 180 packages. Runtime tool surfaces are projected from canonical ActionSpec and surface specs. Package-local RegisterTools functions have been removed for ordinary GitLab API actions; the catalog-first runtime is the exclusive registration model. This provides:

  • Package-level namespace eliminates need for domain prefixes on types (branches.Output vs old BranchOutput)
  • Each sub-package is independently testable with isolated httptest mocks
  • Zero import cycles, which the compiler enforces; it forbids cycles, not imports. A sub-package imports toolutil/ and, where it publishes a row another package owns and judges, that package: a shared data package (labeldata, iterationdata) or a domain (commits.Output in a repository comparison, projects.BasicOutput in the job token allowlist, events.ContributionEventOutput in a user's events). Otherwise a shape two packages both render is mirrored rather than imported, the convention the comments call C-IMPORTS
  • internal/tools/register.go registers individual tools from the canonical action catalog projection
  • Validated by catalog and source guardrails such as TestRegisterAllDoesNotUseDomainRegisterTools and ActionSpec coverage audits

Markdown registry pattern

Markdown formatters use a type-based registry in internal/toolutil/md_registry.go instead of a central dispatch switch. Each sub-package self-registers its formatters via init() functions:

  • toolutil.RegisterMarkdown[T](fn) — registers a formatter for output type T
  • toolutil.RegisterMarkdownResult[T](fn) — registers a formatter for *mcp.CallToolResult types
  • toolutil.MarkdownForResult(result any) — looks up and invokes the registered formatter by reflect.Type
  • internal/tools/markdown.go is a thin delegator (~16 lines) that calls toolutil.MarkdownForResult
  • ~579 registrations across 166 sub-packages, validated by TestAllMarkdownFormattersRegistered

A formatter escapes what it interpolates: toolutil.EscapeMdTableCell on every GitLab-authored string between two pipes of a table row and on every single-line list value, toolutil.EscapeMdHeading on the one value that lands in a heading, and toolutil.MdTitleLink on both halves of a link rather than hand-writing [%s](%s). A code block around GitLab-authored content is built with toolutil.MarkdownFencedBlock, or its fence sized with toolutil.MarkdownCodeFence, never written as three backticks: a fixed fence is closed by the first run of three the body contains, and everything after it renders as Markdown of the response. make check-md-escaping (cmd/audit_md_escaping) is the gate for both; a value that needs none is declared in its own package with //gitlab:allow-unescaped <expression>: <reason>, and a declaration that excuses nothing fails too.

Dynamic toolset mode

GITLAB_MCP_TOOL_SURFACE=dynamic registers only gitlab_find_action and gitlab_execute_action. It is the default when GITLAB_MCP_TOOL_SURFACE is unset. The dynamic registry is built from the canonical action catalog shared with meta-tools and augmented with standalone routes such as project discovery, so execution reuses existing handlers, typed schemas, destructive-action classification, read-only filtering, safe-mode previews, markdown formatters, and scope filtering.

Developers add normal GitLab actions through domain-local ActionSpecs and the audited catalog aggregation path. internal/tools/action_catalog.go builds the canonical catalog from those specs; meta-tools register visible domain dispatchers from it, dynamic mode builds find/execute over it, and individual mode projects one visible tool per action from the same catalog. Do not add package-local RegisterTools functions, duplicate dynamic-only action definitions, or package-level meta registration for ordinary GitLab API operations. See docs/development/tool-surfaces-and-action-core.md for the detailed developer architecture.

Find combines canonical domain.action IDs, domain/action names, aliases, natural-language stopword filtering (removing frequent non-informative words), synonyms, fuzzy matching, and segmented matching for multi-intent prompts. Models should use gitlab_find_action to retrieve exact schemas, then execute the canonical action ID returned by find. See docs/concepts/dynamic-tools.md and ADR-0011.

The related_actions a result carries are narrowed to the session that reads them. The curated lists in the ActionSpecs are written against the whole catalog and every session is served a narrower one, so a Free instance used to be handed cross-links to Premium actions and an --exclude-tools deployment links to actions it had removed. Registry.publishedRelatedActions decides by what following the link would answer: one that resolves here is published under its canonical ID whatever spelling it was written in, one a filter withheld is kept because asking for it produces the narrowing rather than a typo correction (withheldActionMessage), and one neither can explain is dropped, since unknown action plus near-miss suggestions reads as a spelling correction and teaches a model the capability is absent. Measured at the Free tier the dropped set is 4 links in 3 packages, all of them Free actions naming Premium siblings.

What one find call may cost is bounded, in three places that belong together. The query is capped at dynamic.MaxSearchQueryLength (256 characters, published as the schema's maxLength and refused, never truncated), because a search costs the word count times the catalog three times over (lexical, fuzzy, and one pass per segment window) and a request body may be 4 MiB. The scoring passes check the context, so an abandoned POST stops costing and a deadline can end one; a cancelled search returns the error rather than an empty result. And the handler takes toolutil.WithActionDeadline itself, because it is registered directly rather than through one of the WrapAction functions and so passed through no deadline at all. BenchmarkFind_PathologicalQuery is what keeps a scorer change from quietly raising the ceiling.

Enterprise tool gating

GITLAB_MCP_TIER controls access to GitLab Premium/Ultimate features in stdio mode (Enterprise tools are gated when the resolved tier is Premium or Ultimate). In HTTP mode, the --tier flag forces the tier; when omitted, it is detected per token+URL pool entry by the two steps above, the instance license then the namespace plans, falling back to free. The catalog effect is the same in individual and meta-tool modes.

The tier affects tool registration (input/output schemas and tool lists) through pruneSchemaFieldsByTier in internal/tools/action_catalog.go:154 — every registered action has its input schema pruned strictly (lower-tier clients never see higher-tier input fields, even though the SDK type still carries them) and its output schema pruned leniently (lenientExtra=true: higher-tier output fields are kept but omitted from the model-facing schema, so a Premium client reading an Ultimate response sees the data; an Ultimate client reading a Premium response does not). The 3-tier field-level gating is described per-field with tier:"premium" / tier:"ultimate" struct tags throughout internal/tools/*/action_specs.go and internal/tools/*/shapes.go.

Individual mode (GITLAB_MCP_TOOL_SURFACE=individual) — gates Enterprise/Premium actions through catalog metadata:

  • projects (push rules, pull mirroring), mergetrains, auditevents, dorametrics, dependencies, dependencyfirewall, externalstatuschecks, groupscim, memberroles, enterpriseusers, attestations, compliancepolicy, projectaliases, geo, groupstoragemoves, vulnerabilities, securityattributes, securitycategories, securityfindings, securitysettings, groupanalytics, groupcredentials, groupsshcerts, projectiterations, groupiterations, epics, epicissues, epicnotes, epicdiscussions, groupepicboards, groupwikis, groupprotectedbranches, groupprotectedenvs, groupreleases, groupldap, groupsaml, groupserviceaccounts

Meta-tool mode (GITLAB_MCP_TOOL_SURFACE=meta) — gates 17 dedicated Enterprise/Premium catalog groups:

  • gitlab_merge_train, gitlab_audit_event, gitlab_dora_metrics, gitlab_dependency, gitlab_external_status_check, gitlab_group_scim, gitlab_member_role, gitlab_enterprise_user, gitlab_attestation, gitlab_compliance_policy, gitlab_project_alias, gitlab_geo, gitlab_vulnerability, gitlab_security_attribute, gitlab_security_category, gitlab_security_finding, gitlab_security_scan_profile

Plus enterprise-only routes injected into 3 base meta-tools:

  • gitlab_project → push_rule_, pull_mirror_, start_mirroring, security_settings_, dependency_firewall_evaluate (the push mirror routes, mirror_, are Free)
  • gitlab_group → iterations, epics, wikis, protected branches/envs, releases, LDAP, SAML, SSH certs, credentials, analytics, service accounts
  • gitlab_issue → iterations

Dynamic mode (default) — the same catalog gating applies: gitlab_find_action never lists and gitlab_execute_action never runs an action above the resolved tier, so the tier changes which domain.action IDs exist rather than which tools are registered.

OAuth admission, per-action write gating, and HTTP routing

Eight invariants of HTTP mode that are easy to break by touching the wrong layer:

  • One mcp.Server per configuration shape, not per credential (ADR-0020). serverShapeKey in cmd/server/shape.go names what a server is built for: tool surface, capability surface, meta parameter-schema mode, tier and whether it was pinned, GitLab.com or self-managed, read-only including the token-scope narrowing, safe mode, excluded tools, token scopes, statelessness. The instance URL is deliberately not in it, because the client is per credential regardless and two instances of one tier share a catalog. What is per credential is serverpool.Entry: its client, its configuration, its rate-limit bucket, its resource watchers, its listen-stream ceiling and an opaque Owner() token minted from crypto/rand.Text. A shape server registers with gitlabclient.NewUnboundClient, which refuses every request, and each request's own client is installed on the context by credentialStates.bindCredential and read back by (*gitlab.Client).For(ctx) in toolutil.WrapAction and its three siblings, the 38 resource closures, the 37 prompt closures, the completion handler and the elicitation flows. The binding middleware is added after the telemetry, rate-limit, listen-ceiling and subscription middlewares so that it runs before them, and it reads the entry out of the per-POST carrier, which is why carriedMCPHandler wraps the SDK handler inside the gate: with the carrier outside it, the registry recorded the request context as it arrived, before the gate had resolved anything, and every call failed with ErrUnboundClient while every stateful session was refused as somebody else's. Watchers stay per credential because ADR-0015 makes the first read the authorization check; delivery is filtered by sessionOwners.sendingMiddleware, which drops anything untagged or addressed to a session with no recorded owner and forwards the rest with the private owner key removed from _meta. Two things about that middleware are not obvious and both were bugs first: it must read the params, never the request, because the SDK's legacy and 2026-07-28 delivery paths instantiate ServerRequest[P] differently and a type assertion on the request matches one and silently drops the other; and it must put the key back after the send, because the legacy path hands one params value to every subscriber in turn. The _meta map is never mutated: the stripped one is a new map, and the shared one is where the SDK stamps its subscription id. Session ownership is recorded rather than derived, because ServerOptions.GetSessionID takes no request and a per-server tag stops meaning anything once a server serves many credentials. Eviction is the other end of that: an entry whose credential still holds watchers or open subscriptions/listen streams is not idle-evicted (serverpool.WithInUse, consulted on the idle sweep alone, because lastUsed is refreshed by pool hits and a subscription produces none), and an entry evicted anyway has its own streams closed by owner, since Manager.Close fires no OnStop and the client would otherwise be left holding a stream that never speaks again.
  • Admission asks for the minimum, not the deployment's scope. oauth.MinimumScope (read_api) is what the door checks; oauth.RequiredScope is only what the challenge recommends and the first entry of oauth.SupportedScopes. Since issue 952 the legacy door asks the same minimum through the one predicate gitlabclient.MeetsMinimum: a token GitLab accepted that carries neither read_api nor api (the probe answering 403 insufficient_scope, or the token's description naming read_user or other scopes below it) is answered 403, uncharged and remembered in ADM-006's structure, before the tier is asked and under --ignore-scopes too, and an entry later found below it ends with CauseBelowMinimum and its verdict is recorded through ServerPool.RememberBelowMinimum. Scopes nothing answered for (nil) are not below it. On stdio the same predicate reads the process's token at start, under --ignore-scopes too, and a token below it leaves the process answering the handshake while the readiness gate refuses every catalog method with -40300 (readinessGate.markRefused); a version GitLab refuses for want of a scope (gitlabclient.VersionRefusedForScope, what a self_rotate or read_repository token gets) counts as an instance that answered, so the start asks the token's scopes rather than waiting a round for a recovery that never comes, and is a refusal on its own, since that endpoint takes read_user, ai_features, ai_workflows, api and read_api: the process refuses even when the token's description went unanswered. A read_api token is admitted by a deployment that writes and is served a read-only surface: gitlabclient.NarrowToTokenScope sets ServerConfig.ReadOnly when WriteCapable says the token cannot write, per pool entry in HTTP mode and once at startup on stdio, so the write check is the per-action one the catalog already carries. Do not reintroduce a deployment-wide scope demand at the door: that is what refused a read-only OAuth application at initialize. Unknown scopes (nil) mean write-capable: a wrong "no" silently removes tools, a wrong "yes" surfaces as GitLab's own 403. A narrowed surface must say it is narrowed. tools.FilterActionCatalog returns what each filter removed, split into ByTokenScope and ByOperator, and the dynamic registry answers a request for one of those with the cause (dynamic.WithWithheldActions) instead of unknown action … Did you mean …. The dynamic catalog is built by dynamiccatalog.Build, in cmd/server and in the e2e suite alike: the suite used to assemble its own copy without that bookkeeping and was green on the copy. The suggestions in that older message were all real read-only actions, so a model reading it concluded the server lacked the capability rather than that the credential was narrow. Tools removed by name through --exclude-tools stay out of both lists: the operator asked for them not to exist.

    The scope filter is applied to the catalog, never to registered tool names. MetaToolScopes in internal/tools/scope_filter.go maps a catalog group name to the PAT scopes every action in it needs, and FilterScopeFilteredCatalog removes the group before anything is registered: on meta and dynamic that removes the group a caller would name, and on individual it removes every tool that group projects. Both catalog assemblers apply it, SharedMetaCatalog through FilterActionCatalog and SharedIndividualCatalog directly, and both key their shared catalog on catalogRelevantScopes so a caller cannot pin one catalog per scope subset in a cache that never evicts. There is deliberately no second pass over registered names in toolvisibility.Apply (the post-registration pass, shared by cmd/server and the surface evaluator since 3.1.0 so a read-only or safe-mode meta evaluation withdraws or previews the gitlab_interactive_* flows the way the binary does): that is what the individual surface used to be filtered by until 3.0.0, and nothing there is ever called gitlab_admin, so it matched nothing and all 92 admin tools stayed listed for a token with no admin_mode. The calls were refused by GitLab, so it was a listing defect rather than an authorization one, which is the worse half to leave: a model reads tools/list to decide what is possible. Removal is all-or-nothing per group, so a group belongs in the map only when every action in it needs the scopes; gitlab_admin is the one entry that strains that rule, since four of its reads (topics and broadcast messages) are served to any token and go with the rest.

    A fine-grained personal access token is unknown authority, and its grant decides per action (ADR-0024, guide). Its scope list is the single value granular: gitlabclient.FineGrained recognizes exactly that shape, WriteCapable answers true for it and CatalogScopes maps it to nil, so it is never narrowed to read-only, keeps the admin_mode groups, and shares the catalog key of a classic token whose scopes are unknown and never that of a token with none (AUT-001, AUT-002). oauth.SatisfiesMinimum counts it as meeting read_api. A door probe GitLab answers 403 insufficient_granular_scope (the token lacks User: Read) is a fourth verdict, CredentialAcceptedPermissionMissing: both doors answer it 403 -40300, uncharged (INV-007), quoting GitLab's sentence in the body only, filtered and cut at 512 bytes, with a constant error_description in the bearer challenge, and remember it in the rejected-token cache for five minutes (ADM-001, ADM-002, ADM-006), since nothing edits a grant after creation. What a session is shown is an immutable *finegrained.Authority on the credential's client (Client.SetAuthority, gitlabclient.AuthorityFrom(ctx)), built per pool entry (per process on stdio, attached after registration and before the readiness gate opens so the first tools/list is already narrowed) from DetectToken, ReadGrant (1 MiB and 1000 scopes through WithResponseLimit, RQB-011) and the validated /version, taken under a POL-006 probe slot after DetectTier, and replaced whole on every accepted revalidation only by reads that answered (INV-009). A DetectToken that got no answer (anything but GitLab's 403 refusing Personal Access Token: Read) leaves the kind unknown (TokenFacts.KindUnknown, set too when the OAuth verifier admitted the token on its own api assumption, oauth.ScopesAssumedKey): the client carries no authority and the whole catalog is served until the kind is asked again (RedetectToken), on each accepted revalidation, on the stdio timer, and as soon as a degraded stdio start's client recovers (Client.SetOnRecovered); the round that learns a fine-grained token attaches its authority, and the scope narrowing the build decided stays. Phase B (the grant read, the instance on the recorded 19.4 release, every assignable name known) lists what the grant reaches and lets a call through where GitLab would serve it on a public project or group; anything else is phase A, which withholds only the 58 actions no fine-grained token reaches at 19.4.1, and the prerelease of the next minor (GitLab.com's 19.5.0-pre) is phase B for the listing only. A classic token's client carries no authority, so its path and cost are what they were. The grant and the version never reach serverShapeKey, CatalogFilterKey or manifestShareKey (INV-010, TestServerKeys_AGrantReachesNoKey): one shape server serves classic and fine-grained credentials and narrows per request, at toolvisibility.CallMiddleware (added after the argument limit and before the rate limiter, so it answers before validation and spends the call's rate token), the dispatcher check toolutil.FineGrainedRefusal (before confirmation and safe mode on every surface), toolvisibility.ListingMiddleware (right after the rate-limit block, outside the limiter, so RTC-007 keeps charging the shape's full count), find, and gitlab://tools per read; each returns the whole surface under toolutil.IsInternalInspection (AUT-007, AUT-008).

  • Routing happens before authentication, but only stateless GET/DELETE skip the gate. mountMCPEndpoint mounts the MCP handler on /{$}, /mcp, and the --public-url path prefix (for a proxy that forwards its prefix instead of stripping it); everything else is an unauthenticated 404. Non-POST methods bypass the credential check only when --stateless, where the SDK answers 405 whatever they carry: on --stateless=false a GET opens a session's standalone SSE stream and a DELETE terminates the session, so both are resolved and ownership-checked like a POST. The SDK's own server-initiated keepalive ping is off for every HTTP pool entry (withKeepAlive(0)), stateful included — it closes a session on the first unanswered ping, which idle clients fail. Liveness is the SSE keep-alive comment in sseAwareWriter instead, which puts bytes on the wire without asking the client for anything. A catch-all auth gate told every scanner that /.well-known/oauth-authorization-server was a protected document that is not there. securityHeadersMiddleware is the outermost wrapper so even a middleware that answers instead of forwarding (host validation's 403) carries nosniff, CSP, X-Frame-Options and Referrer-Policy.
  • The card routes serve two different documents, and merging them back would undo the point. /server-card and /mcp/server-card answer the SEP-2127 card (cmd/server/discovery_card.go): identity, and a remotes block when --public-url names an address. The extension reserves <streamable-http-url>/server-card, and the endpoint answers at the root and at /mcp, so the card is mounted after both, each again under --public-url's prefix (publicPaths(cfg, serverCardPath, mcpEndpointPath+serverCardPath)); until #533 it was at /server-card alone, so an endpoint published as https://host/mcp answered 404 at the one card URL a client derives from it. publicURLPath returning "" for a path of exactly /mcp is what keeps that mount from being registered twice, which ServeMux refuses with a panic; a path that only ends in /mcp (/gitlab/mcp) is a prefix like any other. It carries no tools, resources, prompts or capabilities, because that extension omits primitives on purpose, so nothing should ever add a tool list there to satisfy a scanner. /.well-known/mcp/server-card.json keeps the enumerating SEP-1649 document buildServerCard produces, which is the unauthenticated answer to what the server can do and the one a scanner wants. Only the legacy route runs the build-once-in-the-background machinery, because only that document registers a catalog; the SEP-2127 card is rendered from constants and flags at mount time. Until 3.1.0 both paths answered the enumerating document and differed only in Content-Type, which left the older shape at the location SEP-2127 reserves and forced the public deployment to shadow /server-card with a static file in nginx. TestDiscoveryCard_AgreesWithServerJSON is what stops the card's identity constants drifting from server.json; isRequired is deliberately excluded from that comparison, since the card schema defines it as whether the input is needed for the connection to succeed while the registry schema surrounds it with fields about configuration a user is prompted for. /.well-known/ai-catalog.json is deliberately not served (the catch-all's unauthenticated 404): an AI Catalog lists everything a host publishes, which only the deployment knows, so the HTTP server mode guide carries the entry (url = <--public-url>/server-card, no displayName or description) and an nginx location serving it with types { } plus default_type application/ai-catalog+json.

    Both cards and the RFC 9728 document carry an ETag (cmd/server/etag.go), so a client holding a copy revalidates instead of downloading 137 KB again; http.ServeContent does the conditional handling rather than a comparison of our own, because If-None-Match is a list, * is a value of its own, the function a GET uses is the weak one, and a compressing proxy forwards the tag weakened. The tag is a hash of the document's own bytes and of nothing about the process, which is the property the whole thing rests on for a fleet: replicas serving one configuration publish one tag, so a client revalidating against a different replica than answered it is still told 304, and TestServerCard_TwoReplicasPublishTheSameValidator holds that by starting two binaries. A per-process tag — a start instant, a random string, the build digest — would miss on nearly every conditional request and would do it silently, since the 200 it produces is still correct. /health deliberately has none: uptime_seconds makes its body differ on every probe. The metadata document is the one this package publishes without rendering, so capturedResponse buffers what the SDK handler wrote and hashes exactly those bytes rather than re-marshaling the struct to hash a copy.

  • There is one Host guard, and it is ours. cmd/server/host_guard.go decides which Host a deployment answers: the loopback names, the host --http-addr binds when it names one, and the host --public-url advertises, plus anything forwarded by a peer listed in --trusted-proxies. A wildcard bind declares no host and falls back to the rule the SDK used to apply for the MCP endpoint alone: refuse a non-loopback Host on a connection accepted over loopback. StreamableHTTPOptions.DisableLocalhostProtection is therefore set, and must stay set: the SDK's copy cannot see either flag, so with it on, every reverse proxy in the deployment guide is answered 403 (they all preserve the client Host and connect to 127.0.0.1) and --public-url cannot help. A request carrying no Host at all is served, because a balancer health check sends none and no browser omits it.
  • The instance is chosen from an allow-list, and verification follows it. --gitlab-url is repeatable; serverpool.ResolveRequestOptionsFor refuses a GITLAB-URL header naming an unpublished instance instead of ignoring it, oauth.NewGitLabVerifierFor verifies against the instance the request selected, and oauth.TokenCache keys on instance and token. Keying that cache on the token alone would let a credential verified against one published instance pass as identity on another. oauth.TokenCache is bounded at tenancy.OAuthCacheCapacity (10000, held equal to PoolSizeMax by the values test) and makes room by dropping an expired identity or else the least recently used one, a take across keys issue 950 decided (ADM-005); the verifier's round trips run under tenancy.OAuthVerifications (16) slots of its own, not the pool's probe slots (ADM-014), and a request refused for want of a slot is answered from the same return and in the same words as a verification with no verdict (bearerGuard.classify), so the wording adds nothing to the one bit INV-019 accepts.
  • Held calls are counted where the SDK dispatches them, and the gate counts only what its headers prove. heldRequestsMiddleware (HLD-011) takes one of processHeldRequests' slots for every call that reaches GitLab (MeterFor's tool-call and completion buckets, a subscriptions/listen aside) arriving on an HTTP POST, so each call of a JSON-RPC batch counts and a client's response to an elicitation never does; it runs before the rate limit, and refuses the way the rate limit refuses the same method. On protocol 2026-07-28 or later, where the SDK holds Mcp-Method to the body and refuses batches, mcpServerGate.middleware takes the slot itself after admission and hands it to the call through the carrier (gateHeldSlot), refusing with a 503 that closes its connection. The ceiling is heldRequestsFor(descriptors), read once at startup from RLIMIT_NOFILE, which the Go runtime has already raised to the hard limit. A held call makes no pool entry busy (POL-003), and an entry evicted while it holds one leaves the call running. On --stateless=false the gate also takes one of processStatefulSessions' slots (HLD-010, half the held-call ceiling) and one held-call slot for the session's standalone stream (mcpServerGate.takeSessionSlot) for every POST carrying no Mcp-Session-Id on a revision before 2026-07-28, after admission and before the SDK creates a session, and refuses it past either ceiling with the held-call ceiling's 503 word for word; the first request dispatched on the new session keeps both slots through the carrier (claimSessionSlot, statefulSessionsMiddleware) and a goroutine waiting on ServerSession.Wait gives them back, while a POST whose session did not survive it gives them back as the gate returns. The standalone GET takes no slot of its own, so a session the process keeps is never refused its stream: the go-sdk client never asks again for a stream it was refused, and would lose every message the server sends outside a response. processSlots is the one count type both ceilings use. Issue 951 decided what stands beside them, which is nothing: no per-credential ceiling beside either and no metering of initialize (RTC-004), because the credential is a key a caller can mint and a number or a price on it multiplies with every token a caller mints, so one credential can fill either ceiling; and no memory cap, fixed or derived, since the memory limit the process runs under (a container's, or a systemd unit's MemoryMax) bounds memory where the descriptor limit is large. Windows, which has no descriptor limit to read, is sized as 1024 rather than left unbounded.
  • The POST is the lifetime of the calls it carries, and the handler learns that through a header. requestCarriers in cmd/server/carrier.go stamps every POST to the MCP endpoint with a minted token, registers that request's context under it, and an mcp.Middleware binds each incoming call to it, so abandoning the POST cancels the handler and with it client-go's retries. The handler context does not descend from the HTTP request (the SDK ignores req.Context().Done() on purpose, for resumability), and StreamableHTTPOptions.PropagateRequestCancellation only covers protocol 2026-07-28, which is exactly the revision that can already send notifications/cancelled. The header is the mechanism because it is the only per-request channel the SDK exposes (mcp.RequestExtra.Header): a context value would work in stateless mode, where the session is connected with the POST's own context, and be wrong in stateful mode, where it is connected with the initialize POST's. Notifications are deliberately exempt, since no POST waits for one and their handlers can outlive the carrier. This is exact rather than a bound because no EventStore is configured, so a response whose POST is gone can never be delivered; adding one would make it a heuristic and this decision would have to be revisited.

Nothing here should need a reverse proxy to be correct: the binary answers its own CORS preflights, its own 404s, its own security headers, and can terminate TLS or listen on a unix socket itself.

Resource subscriptions (ADR-0015)

resources/subscribe is honored by polling, on GITLAB_MCP_CAPABILITY_SURFACE=full only. internal/subscriptions/ owns the watchers and knows nothing about MCP; cmd/server/subscriptions.go is the bridge.

  • What is subscribable — a whitelist of 26 kinds in kind.go — single objects plus three single-parent lists (a pipeline's jobs, an MR's discussions and notes) — parsed segment by segment. Open-ended top-level collections are excluded on purpose. Two drift guards round-trip the real resource registry, so a new template must be classified and a renamed one cannot leave a stale decision behind.
  • Reads go through the registered handler — internal/resources.HandlerIndex captures the same handlers resources/read dispatches to, so "the content changed" means "what a client would read changed". NewHandlerIndex exists because mcp.ServerOptions must be built before mcp.NewServer returns.
  • The session is the subscriber identity — Manager[S comparable] holds a set of subscribers per watcher, not a count, so a duplicate subscribe is idempotent and one session cannot release another's watch. sessionBridge passes *mcp.ServerSession as that identity, and waits on ServerSession.Wait() to call UnsubscribeAll: the SDK drops a disconnected session from its subscriber table without ever calling UnsubscribeHandler.
  • The manager is per credential, the shape around it is per configuration (ADR-0020). A watcher polls with a token and its first read is the authorization check, so a subscriptionRuntime belongs to one pool entry while the subscriptionShape holding the polling options, the listen-stream registry and the handler index belongs to the server they share. Two credentials watching one URI have one watcher each, which is why MaxWatchers (10) cannot bound the process: subscriptions.WatcherGate, injected by newSubscriptionShape as cmd/server.processWatchers at maxWatchersPerProcess (512, not configurable for the reason the stream ceiling is not), is what does. It refuses and never evicts across credentials, and the manager keeps one removal point, dropWatcherLocked, so a new way for a watcher to end cannot leak a slot. Delivery cannot be per session in the SDK, so each notification is stamped with its entry's owner and filtered on the way out; a stream records its owner too, so one credential's watch retiring closes only that credential's streams. Eviction ends what a credential owned: its watchers stop, its listen streams are completed, and the sessions no stream ended are terminated, which is the only ending a session-era resources/subscribe can be given.
  • A joiner waits for the first read — the watcher's ready channel carries the outcome of the initial read (which is the authorization check), so a second subscriber is never told "subscribed" while the only read anyone attempted is still in flight or has already failed.
  • Renewal happens after the handler, not before it — a subscribe request is itself activity, so renewing first would un-demote every watcher a moment before that same request looked for a demoted one to evict, and eviction at the cap could never fire.
  • The lease demotes, it does not stop — 30 minutes without traffic drops a watch to a 10-minute poll; any request that reaches the server restores it (renewOnActivity middleware). From protocol 2026-07-28 a client may answer tools/list or a repeated resources/read from its own cache, so those never renew. Only MaxLifetime (24h), a 401/403/404, or eviction at the cap stop one without the client acting; resources/unsubscribe and session disconnect stop one from the client side.
  • Stateless HTTP refuses the legacy path, and only that path — each stateless POST gets its own session that closes with the response, so resources/subscribe is answered with an error rather than accepted and left undeliverable. The capability bit stays on because subscriptions/listen does work there. That last sentence is load-bearing and was false for a while: the SDK routes both methods through the one SubscribeHandler (subscriptionsListen calls it per resource URI and returns the first error before acknowledging anything), so a refusal written for the legacy method killed every listen carrying a resource, and took a mixed listen's list-changed half with it. The listen path is marked in listenStreams.middleware and subscribeUnlessStateless consults that mark. A handler-level test cannot see this class of defect — the handler is correct in isolation and wrong only because of who else calls it — so the regression lives in test/e2e/http/subscriptions_test.go, on the wire.
  • Ending a watch closes the client's stream: on protocol 2026-07-28 a subscription is an open subscriptions/listen request. A SubscriptionsListenResult application code builds is sent only when a middleware returns it in place of the SDK's handler, before anything is subscribed or acknowledged (TestSubscriptionsListenResult_BuiltByApplicationCode_AnswersOnlyInPlaceOfTheSDKHandler in internal/tenancy holds that), so a stream the handler has acknowledged can only be ended from outside it: listenStreams cancels the SDK handler's context, which makes the SDK emit its own result. A stream is only closed when every URI it carries has stopped, and never if it also carries list-changed subscriptions.

Do not use synctest for tests that need a real HTTP backend: an httptest server's goroutines block on I/O, which is not a durable block, so the fake clock never advances and the test hangs until its timeout. The manager's own tests use fakes and synctest; the wiring tests use real time with short intervals injected through withSubscriptionOptions.


Debugging Tips (Development)

MCP transport debugging

The server communicates via stdio (JSON-RPC over stdin/stdout). To debug:

# Run with debug logging
GITLAB_MCP_LOG_LEVEL=debug ./gitlab-mcp-server 2>debug.log

# HTTP mode for easier debugging with curl
./gitlab-mcp-server --http --http-addr=localhost:8080
curl -X POST http://localhost:8080/mcp -H "Content-Type: application/json" -H "Accept: application/json, text/event-stream" -H "GITLAB-URL: $GITLAB_URL" -H "PRIVATE-TOKEN: $GITLAB_TOKEN" -d '{"jsonrpc":"2.0","method":"tools/list","id":1}'

Common issues

  • TLS errors: Set GITLAB_MCP_SKIP_TLS_VERIFY=true for self-signed certs
  • Tool not found: Check the action's ActionSpec, catalog aggregation, action_catalog.go, and docs/development/tool-surfaces-and-action-core.md for surface ownership rules
  • Meta-tools disabled: GITLAB_MCP_TOOL_SURFACE decides; unset it for the default dynamic surface, set individual for one tool per action, or meta when meta-tools are what you want. The META_TOOLS boolean it replaced was removed in 3.0.0
  • Dynamic mode shows only two tools: this is expected by default. Use gitlab_find_action and gitlab_execute_action; set GITLAB_MCP_TOOL_SURFACE=meta to use meta-tools.
  • Pagination missing: Ensure the list handler applies toolutil.ApplyListOptions to the request and fills its output with toolutil.PaginationFromResponse (plus AdjustPagination when the page was filtered locally)
  • Test mocking: All tests use httptest.NewServer — check URL routing in mock handler

Running specific test domains

go test ./internal/tools/ -run TestBranch -count=1 -v    # Branch tools
go test ./internal/tools/ -run TestMR -count=1 -v         # Merge request tools
go test ./internal/tools/ -run TestPipeline -count=1 -v   # Pipeline tools
go test ./internal/resources/ -count=1 -v                  # Resources
go test ./internal/prompts/ -count=1 -v                    # Prompts

Running E2E tests

The suite drives the real cmd/server binary over stdio against a real GitLab, so a tool call crosses a process boundary and then the network. Nothing about it is in memory: the suite this replaced built the server in the test process and drove an in-memory transport, which is why no defect of the binary's own startup, middleware chain or shutdown could ever fail it.

It is one build and three packages under test/e2e/gitlab, and the package decides the runtime, not a build tag: common for what any instance serves (171 test files), ce for what only an unlicensed one does (4), ee for Premium and Ultimate (46). Every test file carries e2e alone and each package's doc.go carries no constraint (the harness's race seam pair under test/e2e/internal carries e2e && race and e2e && !race), so one compile and one analysis pass see all three. Read test/e2e/README.md before changing any of it; it holds the reasoning this summary leaves out.

Self-hosted needs a .env with GITLAB_URL and GITLAB_TOKEN, for a user who may create and delete projects. Docker boots an ephemeral instance with a CI runner and the fixture services, which is what makes pipeline, job, webhook, custom-emoji and mirror scenarios deterministic. Every target stages the binary first, so none of them is a bare go test:

make test-e2e        # self-hosted, from .env; a package the instance cannot serve skips
make test-e2e-ce     # ephemeral GitLab CE + runner + fixtures: common and ce
make test-e2e-ee     # ephemeral GitLab EE, licensed: common and ee

A test is named for what it exercises rather than for a surface (TestAccessTokens_Project_Lifecycle_ThroughSelfRotation, TestCommitCreate_PathAlreadyInTheBranch_RefusedWithTheCommitActionHint), because one scenario runs on all three surfaces: harness.SurfacesWith builds the fixture once on the parent and runs the body again per surface as a subtest, so the dynamic, meta and individual paths are held to the same assertions instead of to three hand-written families that could drift apart.

What the run covered is recorded rather than declared. The harness writes one shard per test process naming the action each call asked for, the server's own telemetry span says which route the dispatcher ran, and cmd/audit_e2e_coverage joins the two. make check-e2e-static is the gate that keeps it honest: a catalog action no scenario names fails it, and an action nothing on a Docker instance can run is declared in cmd/audit_e2e_coverage/exemptions.go with a category and a reason.

make test-e2e-ce and make test-e2e-ee are the complete runs, and a skip nobody declared fails them. The runs of de1ab3b49 ended with eleven skipped tests in seven test functions on CE and ten in five on EE (issue 1014), and nothing read them: the CE run passed and the EE run failed for other reasons. run-docker-e2e.sh holds the GitLab and runner images to the ones their tags name today: it asks the registry for the digest without pulling (under a sixty-second timeout where the host has one), pulls only when that is not the image the daemon holds, removes the image a pull replaced when no tag or container holds it, keeps the local image with a warning when the registry cannot be reached, and prints the GitLab release the run tested; GITLAB_IMAGE still pins a release. Both runtimes start the Bitbucket fixture. The two targets set E2E_GATE_SKIPS=true unless the caller did, which turns E2E_EXTERNAL_NETWORK on unless the caller set it (the environment, the file E2E_ENV_FILE names or the repository .env), so the importers that call a public URL run, and refuses to start a run whose external network or Bitbucket fixture the caller turned off; an offline host runs with E2E_GATE_SKIPS=false, which is not a complete run. After the tests the script hands the go test -json stream to cmd/audit_e2e_coverage -check-skips, which fails on a skip cmd/audit_e2e_coverage/skip_declarations.go does not declare for the runtime and on a declaration no skip matched; it decides the status only of a run whose tests passed. The table is empty. It held the saved view lifecycle on each runtime until the exceptions log the teardown saves into the reports (e2e-<runtime>-gitlab-exceptions.json, before the volume goes) named the 500 behind it: GitLab 19.4 locks a token caller's user row while sign-in tracking has left it unsaved (upstream-bugs entry 72), so the scenario now asserts what that leaves rather than skipping. A scenario that cannot run on one runtime asserts what that runtime does rather than skipping where it can: on CE the tier pin holds the server to Free and the work item lifecycle pins client-go's refusal (upstream-bugs entry 45). The CI job is not a complete run (no Bitbucket fixture, no importer credentials) and keeps its -check floors. The decisions live in test/e2e/scripts/docker-images.sh, skip-gate.sh and gitlab-exceptions.sh, tested by scripts/e2e_docker_images_test.py, scripts/e2e_skip_gate_test.py and scripts/e2e_gitlab_exceptions_test.py; test/e2e/README.md (A complete run) has the reasoning.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.