agentleFS
txn2txn2/mcp-data-platform/CLAUDE.md

mcp-data-platform

CLAUDE.md12 starsChanged 4 months agoApache-2.0View on GitHub

This file provides guidance to Claude Code when working with this project. mcp-data-platform is a semantic data platform MCP server that composes txn2 MCP libraries (mcp-trino, mcp-s3) with its own data catalog as the semantic layer. The key differentiator is bidirectional cross-enrichment where tool responses automatically include critical context from other services. Cross-enrichment requires a semantic provider: with a database it is the platform catalog (pkg/catalog, internal/platform/catalogstore, docs/server/catalog.md), and semantic.provider: noop turns it off. The rest of the platform does…

  • Reads credentials
  • Installs packages

The file

Show its rules and text

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

27 rules. About 0 are common, 17 are distinctive, and 10 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈17

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 10

    Very specific

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

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Semantic-first: All data access includes business context from the semantic layer

    line 12
  2. Distinctive:

    Trino → catalog: When describing or querying a table in Trino, the response includes the platform catalog's curation (description, owners, …

    line 60
  3. Distinctive:

    Never pad or embellish: If you made two fixes, describe two fixes.

    line 72
  4. Distinctive:

    Uncertainty must be explicit: Use "I believe," "possibly," or "I haven't verified" when uncertain.

    line 74
  5. Distinctive:

    When reviewing, verify claims against evidence: Treat PR descriptions and commit messages as claims to be fact-checked, not trusted context.

    line 76
  6. Distinctive:

    every documented promise the change must keep (write-only secrets, redaction on read, encryption at rest), checked against the docs, not …

    line 88
  7. Very specific:

    Idiomatic Go: All code must follow idiomatic Go patterns and conventions.

    line 98
  8. Very specific:

    New code must have >80% coverage: Run go test -coverprofile=coverage.out ./...

    line 101
  9. Very specific:

    Use go tool cover -func=coverage.out | grep <function_name> to check specific functions

    line 102
  10. Very specific:

    Testing Definition: When asked to "test" or "testing" the code, this means running make verify, which executes the full CI-equivalent suite:

    line 105
  11. Distinctive:

    All checks must pass locally before considering code "tested"

    line 134
  12. Distinctive:

    CRITICAL - Coverage Verification Before Completion: Before declaring ANY implementation task complete:

    line 154
  13. Very specific:

    Run go test -coverprofile=coverage.out ./...

    line 155
  14. Distinctive:

    If you cannot write a full integration test (e.g., requires external services), document exactly what manual verification steps the human …

    line 165
  15. Distinctive:

    CRITICAL - Acceptance Criteria Before Implementation: Before writing code for any feature or fix:

    line 167
  16. Distinctive:

    Write the test assertions FIRST, then implement the code to make them pass

    line 169
  17. Distinctive:

    If you find yourself testing that "function X returns Y when given Z" but never testing that "Z actually arrives from the real system," the …

    line 172
  18. Very specific:

    gofmt: All code must be formatted with gofmt

    line 182
  19. Very specific:

    go vet: No issues from go vet

    line 183
  20. Distinctive:

    gocyclo: All functions must have cyclomatic complexity ≤10

    line 184
  21. Distinctive:

    golint: No lint issues

    line 185
  22. Distinctive:

    ineffassign: No ineffectual assignments

    line 186
  23. Distinctive:

    misspell: No spelling errors in comments/strings

    line 188
  24. Very specific:

    Diagrams: Use Mermaid for all diagrams.

    line 190
  25. Distinctive:

    Pinned Dependencies: All external dependencies must be pinned to specific versions with SHA digests for reproducibility and security:

    line 192
  26. Very specific:

    Documentation Updates: When modifying documentation in docs/, also update the LLM-readable files:

    line 199
  27. Very specific:

    Before adding a package under pkg/, note that TestPublicSurfacePolicy (#1076) refuses a package that is outside the supported import …

    line 214

≈ “Common” is an estimate: at least 1 in 5 of the 28,633 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

CLAUDE.md

This file provides guidance to Claude Code when working with this project.

Project Overview

mcp-data-platform is a semantic data platform MCP server that composes txn2 MCP libraries (mcp-trino, mcp-s3) with its own data catalog as the semantic layer. The key differentiator is bidirectional cross-enrichment where tool responses automatically include critical context from other services.

Cross-enrichment requires a semantic provider: with a database it is the platform catalog (pkg/catalog, internal/platform/catalogstore, docs/server/catalog.md), and semantic.provider: noop turns it off. The rest of the platform does not need one: createSemanticProvider returns a noop with no database or for noop, and createQueryProvider one for an empty or noop provider, so a deployment with no query: block starts normally and the database-backed surfaces (gateways, knowledge, memory, portal, search/fetch) run on PostgreSQL alone. See docs/server/deployment-shapes.md.

Key Design Goals:

  • Semantic-first: All data access includes business context from the semantic layer
  • Composable: Integrates multiple MCP toolkits (Trino, S3, gateways) with its own catalog into a unified platform
  • Secure: OAuth 2.1 authentication, role-based personas, and comprehensive audit logging
  • Extensible: Plugin-based toolkit registry with middleware chain architecture

Architecture

graph TB
    subgraph "MCP Data Platform"
        subgraph "Authentication"
            OIDC[OIDC Provider]
            APIKey[API Keys]
            OAuth[OAuth 2.1 Server]
        end

        subgraph "Authorization"
            Persona[Persona Registry]
            Filter[Tool Filter]
        end

        subgraph "Middleware Chain"
            Auth[Auth Middleware]
            Authz[Authz Middleware]
            Enrich[Semantic Enrichment]
            Audit[Audit Middleware]
        end

        subgraph "Providers"
            Semantic[Semantic Provider]
            Query[Query Provider]
        end

        subgraph "Toolkits"
            Trino[Trino Toolkit]
            Search[search / fetch]
            S3[S3 Toolkit]
        end
    end

    Client --> Auth --> Authz --> Toolkits
    Toolkits --> Enrich --> Audit --> Client
    Enrich --> Semantic
    Enrich --> Query

Cross-Enrichment Pattern

Trino → catalog: When describing or querying a table in Trino, the response includes the platform catalog's curation (description, owners, tags, glossary terms, properties, open incidents, column context).

Catalog → Trino: fetch on a catalog dataset includes query availability (can this be queried, on which connection, how many rows).

CRITICAL - Factual Integrity (No Confabulation)

AI-generated prose (PR descriptions, commit messages, reviews, explanations) is held to the same verification standard as code. Unverified claims are as unacceptable as untested code.

  1. Never assert facts you haven't verified. Before stating that a file contains X, a config is missing Y, or a system behaves in way Z — READ the file, CHECK the config, VERIFY the behavior. If you haven't looked, say "I haven't verified this" or say nothing.
  2. Every claim must be evidence-linked. PR descriptions, commit messages, and work summaries may only include claims that are either: (a) directly visible in the diff, or (b) verified by reading a specific file (cite file:line). No exceptions.
  3. Never pad or embellish. If you made two fixes, describe two fixes. Do not invent a third to make the work look more complete. Do not present hypotheses as confirmed diagnoses.
  4. Uncertainty must be explicit. Use "I believe," "possibly," or "I haven't verified" when uncertain. Never upgrade a guess to a fact.
  5. When reviewing, verify claims against evidence. Treat PR descriptions and commit messages as claims to be fact-checked, not trusted context.
  6. Omission over fabrication. A gap stated honestly is better than a fabricated answer stated confidently. When in doubt, leave it out.

CRITICAL - Security Design Before Code

v1.152.1 shipped a webhook auth mode that stored the secret it verified in every event (#2353), and the review that followed found eight more places a secret reached somewhere it should not (#2355-#2362). Every test was green each time. Tests check what a feature does; none of them asks where a secret goes. That question is answered at design time, written down, and then tested.

  1. Threat model first. Any change that touches untrusted input, a credential or secret, authorization, encryption, or what is stored, logged, served or indexed starts with a threat model written in chat, before the first edit, so it can change the design. It answers:
    • the trust boundaries the change crosses, and who is on each side;
    • every secret the change receives, holds or derives, and every sink it could reach (database rows, object storage, the spool, logs, audit rows, the call catalog, the search and embedding index, script runs and recordings, API responses, error text, span attributes, metric labels), and why it does not reach each one;
    • what an unauthenticated caller, a caller with a weaker persona, and a caller who can write to a table the feature reads can make it do;
    • every documented promise the change must keep (write-only secrets, redaction on read, encryption at rest), checked against the docs, not memory.
  2. Every "never" is a criterion. Each sink the threat model rules out becomes an acceptance criterion that searches that sink, through the real surface, for the secret (as written, base64, hex, URL- and JSON-escaped). A criterion that only checks the feature works does not count.
  3. A separate security review before make verify. After the correctness review, review the diff again as an attacker holding the threat model: what can be read that should not be, what can be opened that was sealed for something else, what an error repeats. A finding a scanner, a reviewer or another agent reports after the PR is recorded as a miss of this review.
  4. No tag while a security finding is open. An issue that reports a secret reaching a sink, an authorization bypass, or a decryption oracle carries the security label, and while any such issue is open scripts/release-tag.py check refuses every tag, candidate or final, in the release workflow and in make release-tag-check (#2550).
  5. One list per rule. What is encrypted at rest, redacted when a connection is read and redacted in the config export all read the encryption layer's key sets (pkg/platform/fieldcrypt), and TestSanitizeParametersCoversEveryEncryptedKey fails when the audit sanitizer would store one of those keys' values. A second hand-kept copy is how session_token was described as encrypted and stored in clear (#2359).

Code Standards

Which rule a gate enforces, and which is a human step, is listed in docs/reference/development-rules.md. TestEveryRuleIsClassified (test/gates/claude_rules_test.go) fails when this file gains a numbered rule or a CRITICAL section the table does not list, when a row names a gate that no longer exists, and on a rule classified as neither (#2550).

  1. Idiomatic Go: All code must follow idiomatic Go patterns and conventions. Use gofmt, follow Effective Go guidelines, and adhere to Go Code Review Comments.
  2. Test Coverage: Project must maintain ≥82% total unit test coverage (COVERAGE_MIN in the Makefile, matched by codecov.yml and the CI workflow). Build mocks where necessary to achieve this. Use table-driven tests where appropriate.
    • New code must have >80% coverage: Run go test -coverprofile=coverage.out ./... and verify new/modified functions meet the threshold
    • Use go tool cover -func=coverage.out | grep <function_name> to check specific functions
    • Framework callbacks (e.g., MCP handlers that require client connections) may be excluded if the actual logic is extracted and tested separately
  3. Testing Definition: When asked to "test" or "testing" the code, this means running make verify, which executes the full CI-equivalent suite:

    • Tools-check (parity gate) — verifies local golangci-lint and gosec versions equal GOLANGCI_LINT_VERSION and GOSEC_VERSION in the Makefile (which mirror .github/workflows/ci.yml), and that no pinned Go tool was built with a newer Go than CI's go-version (scripts/tools-go-check.sh, #2147): CI installs with GOTOOLCHAIN=local, so a pin that needs a newer Go installs locally and fails CI's install. Drifting local tool versions are the most insidious parity gap: a newer local gosec can silently relax a rule that CI's pinned version still enforces, letting a real bug ship to PR. make verify refuses to run until local matches CI. Override with TOOLS_CHECK_STRICT=0 only with explicit reason.
    • One gate, cheapest step first (#1856, #2369) — make verify is the gate, run once when the work is done; there is no pre-gate. Every step before the lanes runs serially in ascending order of measured cost, so the cheapest check that can fail fails first, and each lane runs its steps the same way, a step that reads another's output aside. scripts/verify-steps.tsv holds each step's measured seconds; every step runs through scripts/verify-step.py, which prints [step <name>: <seconds>s ok] as it ends, and TestVerifyRunsTheCheapestStepFirst (test/gates/verify_order_test.go) fails when the Makefile runs a step the table does not list, in another order, or when the table is out of ascending order. When a step's cost moves, update its figure and move it. The steps that rewrite the tree (tools-check, fmt, embed-clean, swagger-check) run first in that order; then acceptance-copy-check, acceptance-check, state-readers-check, builtin-pages-check, portal-surface-check (#2560), apidocs-openapi3-check, e2e-copy-check, security-diff, route-conformance-check (the MSW route conformance test alone, #2186), route-manifest-check, semgrep-diff, dead-code, docs-build, doc-check, semgrep-changed (the p/golang ruleset and the .semgrep/ rules over the changed Go files, #2145, #2339), frontend-lint (#2030), e2e-standalone, dev-smoke-diff, route-template-diff, migrate-check-diff, vet-tags, and the patch-scoped lint, the costliest, last. The Go lane starts with the changed-test schedule lane rather than ending with it. Four steps are scoped to the diff and skip in a tenth of a second when it gives them nothing to do: security-diff runs verify's standalone gosec (which reads #nosec, not //nolint:gosec) over the packages with a changed production Go file, and route-template-diff runs TestEveryRouteReportsItsTemplate_RealDB alone when an added or removed line registers a mux pattern (#2186; scripts/verify-diff.py reads the diff for both, TestVerifyRunsTheLaneGatesFirstOnTheDiff pins them); migrate-check-diff runs migrate-check (pg16 and pg17) when the diff adds or changes a file under pkg/database/migrate/migrations/ (#2239: the RealDB tests run on pg16 alone, and #2169's 000209 passed them and failed on pg17), and the Docker lane then skips its own migrate-check (migrate-check-lane) rather than checking the same migrations twice (TestVerifyChecksMigrationsOnBothMajors); dev-smoke-diff runs make dev-smoke when the diff changes a file under dev/ (#2248): one call through the platform per service the dev stack runs (a managed resource read back by digest from the TLS store, a portal asset, a query on each scratch catalog, a Keycloak sign-in, a search hit on a just-saved asset, a drawn tile), test/acceptance/devsmoke_test.go, failing and saying so when no stack answers (start one with make dev). #2245's store passed the aws CLI over HTTP/1.1 and refused the platform's HTTP/2, failing 368 criteria in a 45-minute run. TestVerifySmokesAChangedDevStack pins it. make preverify was removed (#2369): run before verify, it ran the same cheap gates and lint twice on one tree.
    • Every failing step in one run; a re-run costs what failed (#2548) — the serial steps after the four that rewrite the tree run through verify-step.py --keep-going, so a failed step is recorded and the next one runs, and verify-step.py --report then fails verify listing every failed step with its output before the lanes start; a failure in a step that rewrites the tree still stops the run at once. Each step that passes records a digest of its inputs in build/verify-cache/: the paths in the fifth column of scripts/verify-steps.tsv, plus the Makefile, scripts/, the Go and Node versions, the merge base, DELTA_BASE and the variables make was given. A later run on the same digest skips the step and prints [step <name>: skipped, its inputs passed at ...]; VERIFY_FULL=1 runs every step. A step that reads something outside the tree (a running stack, the vulnerability database, a registry ruleset, recorded acceptance runs), prints what a reader needs when it passes, or costs less than the digest says - and always runs; a step running a Go suite reads ., since a Go test may open any file in the repository. make lint runs lint-run under the key lint, so a lint run by hand and verify's share one record: inputs that passed answer at once, and inputs that failed with findings print that run's findings without running. make dev and air's rebuild run scripts/dev-embed.sh, which builds the embedded portal and tile page when embed-clean emptied them, and dev-smoke's tile check fails at once naming an empty embed rather than waiting 45 seconds. test/gates/verify_step_test.go, dev_embed_test.go and TestVerifyRunsTheCheapestStepFirst pin it.
    • A run after a green one checks the change since it (#2535) — a green make verify records the tree it passed as a commit (.claude/.last-verify-commit, scripts/ci-delta.py record-local), and the next verify sets DELTA_BASE to it: the Go unit run covers the changed packages and their importers (a file outside every package adds ./test/...), the schedule lane, patch coverage, lint, the RealDB lane and every diff-scoped step (security-diff, route-template-diff, semgrep-diff, semgrep-changed, migrate-check-diff, dev-smoke-diff, through the Makefile's diff_base or schedule-lane.py's merge_base; TestDiffScopedStepsReadTheLastGreenTree fails a step that computes its base without DELTA_BASE, and names the branch-scoped checks that ask about the whole pull request, #2660) diff against it, the UI lane, the standalone e2e and the Docker lane's migration check skip when the change does not reach them, and the 82% total is a full run's. A change to go.mod, go.sum, the Makefile, .golangci.yml, ci.yml or the diff scripts runs everything, as does VERIFY_FULL=1. CI narrows a pull request's follow-up push the same way from the last green run's ci-tested artifact, and carries Lint, Test and Build, like the other jobs, when the change since reaches none of their inputs (#2690).
    • The load harness module (make load-test, make load-lint, #2729): test/load is a separate Go module the root build, test and lint never reach; verify builds, vets, tests and lints it (skipped while test/load is unchanged since it passed), and .github/workflows/load.yml runs both on a pull request that changes it. A load report counts each failed operation's failures by what each said (error_reasons).
    • Code formatting (gofmt -s -w .)
    • API description converts to OpenAPI 3 (make apidocs-openapi3-check, #2022) — runs the swagger2openapi conversion npm run generate-api-types runs over internal/apidocs/swagger.json, in verify's serial preamble and in CI's frontend job. swag writes a document the conversion refuses (a path parameter marked optional, on PDF routes that shared one annotation block), and ui/src/api/generated is gitignored, so nothing else converts it.
    • Tagged build (make vet-tags, #1799) — go vet -tags=integration ./..., run in verify's serial preamble before the lanes fan out. Nothing else cheap compiles a file behind //go:build integration: every other consumer of the tag wants a machine (test-realdb Docker and a migrated Postgres, acceptance a dev stack and a renderer, smoke a running server), .golangci.yml sets no build tags, and npm run build is not Go. So a one-character compile error in a tagged file used to be reported by verify-docker after the daemon was up and the migrations had replayed: on #1794 three tagged files referenced two deleted constants, every cheap gate passed, and the Docker lane failed six minutes in. This answers the same question in about a second.
    • Standalone e2e (make e2e-standalone, #2342) — runs in verify's serial preamble and in CI's test job: every test/e2e test except those calling helpers.NeedsServices (they read the PostgreSQL, Trino or SeaweedFS make e2e-up starts, and only the E2E Nightly runs them), about thirty seconds. #2337 changed the admin API's non-admin answer from 401 to 403 deliberately, every gate passed, and TestAdminAPI_AuthEnforcement, which needs no service, failed the next nightly. A new e2e test runs here unless it calls NeedsServices. Separately, a pull request that changes a ticket's test/acceptance/issue_<n>_test.go runs those criteria in CI on a fresh Linux stack with no .env (Acceptance (changed criteria), ACCEPTANCE_TICKETS, #2341): #2179's passed locally with an encryption key the runners never had. That job runs a ticket alone, so every pull request also runs the whole E2E Nightly, and its E2E Nightly (pre-merge) job, required on main, passes only when every nightly job passed on the head commit (#2824): #2823 merged green and failed that night on a deleted GraphQL connection a replica kept serving, a defect only the suite's other criteria set up. TestEveryPullRequestRunsTheNightlyBeforeMerge pins it.
    • Unit tests with race detection (go test -race ./...)
    • Schedule lane (make schedule-lane, #1711, #2039) — the Test functions in every _test.go file changed against main run go test -race -cpu=1,2 -count=5, each package under a ten-minute budget, and a failure prints the command that reproduces it, and, when the binary died with no failing test (a runtime fatal error, an os.Exit, the race runtime giving up), the test it died in and what that test printed; CI runs the same target on every pull request. The unit is the changed test, not its package: the whole-package form ran ten passes of pkg/platform on one core, an hour locally and a timeout in CI, almost all of it tests the change did not touch (#2039). The lane prints each package's measured time per CPU setting. Each package's go test writes its -json stream to a file of its own, never to a pipe read later: the lane starts every package together and collects them one at a time, and a verbose package read late used to block go test on a full pipe until its one-minute WaitDelay reported "Test I/O incomplete after exiting" and dropped the rest of the stream, which read as a binary dying mid-test (#2045; it killed five packages on each of #2046's CI runs and never reproduced alone). make test runs each test once at this machine's CPU count, which is not the schedule a loaded CI runner chooses: TestWithRevocations_WiredLate passed two make verify runs on 18 cores and fails 140 of 300 runs at -cpu=1. The frontend half (make schedule-lane-ui, in place of frontend-test) runs every changed *.test.ts(x) file five times beside the full vitest suite.
    • Coverage verification — total must be ≥82% (hard gate, COVERAGE_MIN)
    • Patch coverage — changed lines vs main must be ≥80% (mirrors codecov patch check). Which paths sit outside it is written twice, in scripts/patch-coverage.sh and in codecov.yml's ignore:, and TestCoverageExclusionsAgree (test/structure/pins_test.go) resolves both against the repository's real Go files and fails when they describe different sets. #1747 read 88.8% here and 64.20% in CI off one diff because they did
    • Linting (golangci-lint run ./... plus --new-from-rev=$MERGE_BASE to mirror CI's only-new-issues: true) — cyclomatic complexity ≤10, cognitive complexity ≤15
    • Security scanning (gosec ./... + govulncheck, whose report is judged against .govulncheck-allow.txt by scripts/govulncheck-gate.py: an advisory with no patched release may be accepted with a written reason, and the gate fails when an accepted advisory gains a fix or stops being reported)
    • Semgrep SAST — p/golang ruleset + custom .semgrep/ rules (unbounded allocations, etc.), plus make semgrep-diff, which runs .semgrep-diff/ against the lines this branch changed. That directory holds the rules that refuse a SHAPE a diff-scoped CI check rejects using reasoning Semgrep does not have: go/allocation-size-overflow rejected make(map[string]any, len(fields)+1) on #1747 after a green local verify, and the syntactic form it refuses appears 55 times in this tree without being a defect once. Scoping those to the diff is what CI already does with them, and what make lint does with --new-from-patch
    • Real-Postgres gate (make test-realdb, in the Docker lane) — every test named *RealDB* against a migrated database, including the statement gate internal/sqlgate added by #1512: each SQL statement in the module is handed to PostgreSQL to parse and plan. sqlmock matches a statement as a string and returns rows the test supplies, so it rubber-stamps SQL the database rejects; #1506 shipped an ambiguous column reference with 100% patch coverage and a green CI. The lane's server is started with REALDB_MAX_CONNECTIONS, set from the connections the packages open, and every run prints its peak and the packages holding the most (scripts/realdb-connections.py, #2249). Beside that server it starts a PostgreSQL 17 and an 18 (REALDB_APPDB_IMAGES), named to the tests in APPDB_TARGET_DSNS: every application-database RealDB test in pkg/toolkits/postgres runs once on each through onTargets, as a subtest named by the major, and fails when none is named, since 17 is the oldest server the appdb kind accepts (#2447). A statement assembled at run time has no text to prepare, so its package renders it through SQLSamples (see pkg/resource/sqlsamples_integration.go) or is recorded in internal/sqlgate/templated_pending.txt — a package that does neither fails rather than being skipped.
    • Documentation check — warns when documentation-worthy changes lack doc updates (soft warning)
    • Acceptance check (make acceptance-check) — warns when production Go under pkg/, internal/ or cmd/ changed against main and no test/acceptance/*_test.go changed (soft warning; blocking for AI agents, see rule 6), and FAILS when an acceptance file did change and its criteria have no passing run recorded at build/<n>/acceptance.jsonl (in a file mixing plain criteria with criteria an environment of test/acceptance/environments.txt holds, the plain ones; that environment's run proves the rest, #2637), when the diff registers a tool no criterion calls, or when an acceptance file the diff leaves alone calls a tool the diff changes within the package registering it (#2693: a changed function, type, field or constant counts only when the tool's handler reaches it through a command, action or operation the file names as a literal, or through the code every command runs, where a dispatch entry, its key included, is its command's and a package-qualified name is not a field read (#2696); a change it cannot place, such as an init or the registration, keeps the package rule, and the check names the change that reached each stale ticket), or calls (directly or through another helper) a helper whose declaration the diff changes in another acceptance file, and has no passing run newer than the change (#2543, #2627; the pull request job Acceptance (changed criteria) runs those files too, in up to eight jobs, so since #2709 a stale file the diff leaves alone is listed and left to that job rather than failing the local check, and ACCEPTANCE_STALE_STRICT=1 asks for it locally; a ticket whose acceptance file the diff changes is still recorded locally before verify; the tool map comes from the tools AddTool registers, read against test/toolsurface, and the helpers from the diff ACCEPTANCE_DIFF_RANGE names)
    • State-readers check (make state-readers-check, #1709) — warns when a json:"..." field on a struct under internal/admin, internal/httpserver, pkg/admin, pkg/portal or internal/portal was added, removed or retyped, or internal/apidocs/swagger.json changed (a route or definition, its description included), and nothing under ui/src changed (soft warning; blocking for AI agents). It lists the changes either way; the PR names the readers it checked for each under "Readers of this state". #1676 changed only a route description and left the Schema card behind (#1689) along with the other replica (#1703)
    • Built-in pages check (make builtin-pages-check, #2200) — warns when the diff changes a source path internal/platform/knowledgebuiltin/covers.txt lists for a built-in knowledge page and the page did not change (soft warning; blocking for AI agents). Every deployment serves those pages as the platform's own word on its next start, and nothing compiles their prose; read the page against the change and update it, or leave it when the change alters nothing it says. TestCovers_EveryPageNamesPathsThatExist fails when a page lists no path or a path that no longer exists
    • Portal surface check (make portal-surface-check, #2560) — warns when the diff registers an MCP tool the base's tool table lacks (read as acceptance-check reads it, plus the names test/toolsurface gained) or adds a top-level section to the Config struct in pkg/platform/config.go, and nothing under ui/src changed (soft warning; blocking for AI agents). manage_site reached v1.155.0 with no Sites page, and the API gateway's first five pull requests with no way to add an api connection. A tool or section with no portal surface by design is listed in scripts/portal-surface-exempt.txt as tool|config <name> <reason>; an entry naming one the platform no longer has fails
    • Route manifest check (make route-manifest-check, #2055) — runs ui/e2e/screenshots/route-sync.test.ts alone, which fails when a route in AppShell's pageTitles has no entry in the screenshot route manifest. It reads two files in under a second; the full vitest suite inside verify's UI lane was the only thing running it, so a new portal section without its entry failed verify minutes in (the #2048-#2053 branch's Admin > Secrets did)
    • Acceptance copy check (make acceptance-copy-check, #2519) — FAILS when a positive assertion in test/acceptance (!strings.Contains, testify Contains/Equal, != a literal) holds text the diff removed from a production Go string under pkg/, internal/ or cmd/, or when an acceptance file that opens a built-in knowledge page by path holds a literal the diff removed from that page (#2695): equal to a string no production file holds any longer, or a fragment fewer production strings hold after the diff, when none holds it any longer or the criterion and the removed string were written in one commit. Also in CI's test job. A text the platform composes at run time, which no production literal holds (toolwrite's tool action=verb call label), is listed in scripts/acceptance-copy-exempt.txt with its reason, and an entry no criterion asserts any longer fails (#2844). #2498 changed the endpoint refusal issue 2171's criterion asserted; acceptance-check runs only changed acceptance files, the nightly after the merge failed, and v1.153.2's tag was refused
    • E2E copy check (make e2e-copy-check, #1977) — FAILS when a Playwright spec under ui/e2e/interactive or ui/e2e/public-viewer asserts a string or JSX text the diff removed from ui/src and no ui/src source shows any longer, naming the spec line; a text one changed file shows fewer times but another still shows (the Automations filter option beside the Automations heading, #1970) is listed for a look, not failed, and so is a spec literal that still reads a whole text on show (/Open/ against a removed "Open the print dialog" tooltip while an Open button stays, #1983). The Playwright suite runs only inside verify, after the full unit run
    • Dead code analysis
    • GoReleaser dry-run — validates build, Docker, and release config, on an export of the working tree (scripts/release-check-isolated.sh, #2711): its before hook rewrites internal/ui/dist, which the other lanes compile while it runs, and TestNoLaneWritesTheUIEmbedDirectory (test/gates/ui_embed_lanes_test.go) fails a lane step that writes the embed directory in the checkout
    • Local gate time against a budget (#2710) — make acceptance appends each recording's ticket count and minutes to scripts/acceptance-runs.tsv (the newest 20), which also states the budget for verify plus the recordings a change requires; TestLocalGateTimeIsWithinBudget (test/gates/acceptance_budget_test.go) fails, naming each step's minutes, when verify's measured wall clock plus the newest recording exceeds it, and acceptance-check prints how many tickets it requires locally and their estimated minutes
    • All checks must pass locally before considering code "tested"

    CodeQL is deliberately not part of make verify, and this list claimed it was until #1327. The Makefile removed it: ~4 minutes of serial wall clock, more than the whole concurrent phase, on the reasoning that .github/workflows/codeql.yml runs the same suite on every pull request.

    Running make codeql locally is not a substitute, and does not clear you to push. On #1327 GitHub Code Scanning reported go/log-injection (medium) at internal/httpserver/tablehttp/tablehttp.go:179; a local make codeql on the identical unsanitized source produced zero log-injection results and exited 0. The file was in the database (it is listed in the SARIF artifacts), so this is not a coverage gap — the local CLI's bundled query pack does not reproduce what GitHub's scanning reports. Treat local CodeQL as advisory for this class.

    make codeql builds its database from an export of the working tree with one traced go build ./... per module (scripts/codeql-local.sh, #2548), never in the checkout: CodeQL's autobuild runs the Makefile's default goal (the unit suite and the lint, twice) and once removed tracked files under ui/vendor/maplibre from the working tree. make codeql-parity runs both builds over one tree and fails when their findings differ; run it when the script, a module or the CodeQL version changes.

    A GHAS finding is a review comment, not a failing check. gh pr checks showed CodeQL pass on #1427 while go/log-injection was open against the diff. After every push, read gh api repos/<owner>/<repo>/pulls/<n>/comments and look for github-advanced-security[bot]; a green check list does not mean Advanced Security is clean.

    Sanitize every value that reaches a log sink with internal/logsan.SanitizeForLog — including err.Error(), since a wrapped error carries whatever caller-supplied names the layers below put in it.

    Mutation testing (gremlins unleash --threshold-efficacy 60, ≥60% kill rate) is deliberately not part of make verify — it is too slow for a per-commit gate (the Makefile verify target carries a comment forbidding its re-addition). It runs in make verify-release (pre-tag, local, ./pkg/...) and on a weekly schedule in CI via .github/workflows/mutation.yml over ./pkg/... and ./internal/... (MUTATE_PKGS, #2732); gremlins is version-pinned by GREMLINS_VERSION and enforced by tools-check like the other tools. Mutation on the lines a change touches (make mutate-diff, scripts/mutation-diff.py, #2732) runs gremlins with --diff against DELTA_BASE or the merge base on each package under pkg/ and internal/ whose production Go the change touches; a survivor in a package scripts/mutation-security-packages.txt lists fails, elsewhere it is printed. It runs in CI's Mutation (changed lines) job on every pull request and not in make verify: on #2733's diff 14 packages took 413 seconds (internal/hmacsig alone 150) before gremlins' per-worker module copies filled the disk, far past the local budget. Run it by hand on a small diff when a security package changed.

    Every scheduled workflow reports its result (#2730): a report job on main, on success and on failure, with issues: write on that job alone, runs scripts/scheduled_report.py report, which opens or comments on the <workflow name> is failing issue (the run, its commit, the failed jobs and steps, and what failed: tests, fuzz targets, benchmarks, load assertions, surviving mutants) and closes it on the next pass. TestEveryScheduledWorkflowReportsItsResult (test/gates/scheduled_report_test.go) fails a scheduled workflow without one. A criterion that failed and then passed on one tree, or failed in two tracking issues within 14 days, is listed in the Flaky criteria issue, which stays open until each is fixed (#2731).

    Fuzzing (#2713): every Fuzz* target in the module, the parsers of untrusted input under internal/ among them (TestEveryUntrustedParserHasAFuzzTarget names them), is fuzzed daily by .github/workflows/fuzz.yml (make fuzz, scripts/fuzz-all.py, FUZZTIME per target). A failing input lands in the package's testdata/fuzz/<Target>/ and is committed with the fix, so go test replays it. Hot-path allocations (#2716): make bench-allocs (a verify step and the Benchmark allocations job on every pull request) holds the benchmarks on the tool-call chain, persona filtering, SQL table extraction, route templates, secret redaction, the JSON walk and path templates to scripts/bench-allocs.tsv; an intended new allocation updates its row in the same diff (make bench-allocs-update). ns/op is tracked weekly by .github/workflows/bench-trend.yml with benchstat, never gated.

    Parity-gap incident (2026-05-08, PR #377): local gosec 2.26.1 silently dropped the G704 SSRF taint rule that CI's pinned v2.22.0 enforces. make verify passed locally; CI rejected the same diff with a real SSRF bug. The tools-check version pin is the structural fix — discipline alone has been insufficient.

  4. CRITICAL - Coverage Verification Before Completion: Before declaring ANY implementation task complete:
    • Run go test -coverprofile=coverage.out ./... (note: ./... not ./pkg/... — covers cmd/ too)
    • The gate is make patch-coverage: the lines a change touches must be ≥80% covered, as Codecov's patch check requires in CI
    • Per function is a human step on top of it: for every new function or method, run go tool cover -func=coverage.out | grep <function_name>, and add tests to any below 80% (or at 0.0%) before declaring done, since a well-covered change can still carry one untested function
  5. CRITICAL - Integration Tests for Cross-Component Behavior: Unit tests are NOT sufficient for features that span multiple components (middleware chains, provider pipelines, context propagation). Before declaring such work complete:
    • Write an integration test that exercises the real assembled system, not just individual functions with hand-crafted inputs
    • For middleware: wire up the actual mcp.Server with all middleware via AddReceivingMiddleware, send a real request, and assert the end-to-end result (e.g., audit store received a complete event with non-empty fields)
    • For context propagation: verify that values set by one component are actually readable by downstream components through the real call chain
    • For provider enrichment: verify that cross-service enrichment actually produces enriched output, not just that the enrichment function works in isolation
    • A unit test that passes because it manually constructs the correct input does NOT prove the system works. The integration test must prove that component A's output actually reaches component B through the real wiring.
    • If you cannot write a full integration test (e.g., requires external services), document exactly what manual verification steps the human should perform before release, with expected outputs
  6. CRITICAL - Acceptance Criteria Before Implementation: Before writing code for any feature or fix:
    • State the specific, observable acceptance criteria (e.g., "a tool call produces an audit_logs row with non-null user_id, duration_ms, and tool_name")
    • Write the test assertions FIRST, then implement the code to make them pass
    • The acceptance criteria must test the actual user-visible behavior, not internal implementation details
    • The criteria state what a person sees and does in the portal, or why there is nothing to see (#2560). A tool or setting that only an agent can reach is a feature a person cannot find, check or change; make portal-surface-check warns when a change registers a tool or adds a config section with no ui/src change, and scripts/portal-surface-exempt.txt holds the written reason for each that has none by design.
    • If you find yourself testing that "function X returns Y when given Z" but never testing that "Z actually arrives from the real system," the test is incomplete
    • CRITICAL - The criteria are then executed through the real surface, locally, before make verify. Write them as test/acceptance/issue_<n>_test.go: a real MCP client against a running platform, calling the tool or route a user calls, asserting the ticket's acceptance sentences. Run it with the local stack up (make dev; make e2e-up when Trino or S3 are involved) via make acceptance, and make acceptance ISSUE=<n> writes the transcript at build/<n>/acceptance.md from the file's // Wire forms: comment and the run's results (#2541). make verify-release requires a passing recorded run of every ticket changed since the last tag (acceptance-release-check); the whole suite (make acceptance-release, which starts the dev stack for the run when none answers, #1969) runs in the E2E Nightly in eight groups at once, and a tag requires that nightly green (#2218); make verify warns (acceptance-check) when production Go changed with no acceptance file, and for an AI agent that warning is blocking. Production is never the first place a feature runs: 1.126.5 shipped four defects (#1543-#1546) from features whose unit, integration and real-database gates were all green, each found within minutes of the first call through the real surface. Where the platform integrates with an upstream the deployments run (the api-test and mcp-test fixtures, SeaweedFS, Trino, Keycloak), the acceptance test uses that upstream, not a stand-in written for the test.
    • CRITICAL - The acceptance test sends every JSON form the schema admits. MCP is JSON-RPC: tools/call params are JSON, and a parameter whose schema is untyped or any accepts more than one form (api_invoke_endpoint.body takes an object and a string of JSON). #1548 shipped in 1.126.6 with TestIssue1544_* green because every check sent the body as an object and the client sent it as a string. Before writing the test, list each touched parameter and the forms its schema admits; the acceptance test sends each one as literal params and asserts the same result for all. Each acceptance file carries a // Wire forms: comment naming the forms sent, which make acceptance ISSUE=<n> writes as the first line of build/<n>/acceptance.md, failing and naming the file when the comment is missing. make acceptance-check fails when a test/acceptance/issue_<n>_test.go changed and that transcript is absent: no transcript, no check.
    • CRITICAL - A criterion that did not run blocks the PR. It is not a paragraph in the transcript. make acceptance records the run as a go test -json stream at build/<n>/acceptance.jsonl, and make acceptance-check fails unless every func TestIssue<n>_ in each changed test/acceptance/issue_<n>_test.go has a terminal pass event in it — absent, skipped and failed are one verdict. When the acceptance upstream cannot be started, the PR waits for the upstream: unit, integration and real-database coverage are never offered in its place, and neither is a section headed "not executed here". #1663 shipped behind exactly that section and 1.131.0 shipped the tool it covered unknown to every server (#1675). make verify-release applies the same rule to every acceptance file changed since the last tag, and make acceptance ISSUE=<n> records one ticket's run.
    • CRITICAL - Every tool a ticket registers has a criterion that calls it through the real client. #1277 registered three tools and closed with criteria for two, which is how graphql_export reached a release having never been called. make acceptance-check fails when the diff registers a tool name that no changed acceptance file names. On the running side, the platform compares each toolkit's Tools() list with the tools its MCP server holds after WireRuntime and refuses to start on a name it cannot honor, so a dependency wired after registration is a crash at boot rather than a tool listed everywhere and callable nowhere.
  7. Human Review Required: A human must review and approve every line of code before it is committed. Therefore, commits are always performed by a human, not by Claude.
  8. Go Report Card: The project MUST always maintain 100% across all categories on Go Report Card. This includes:
    • gofmt: All code must be formatted with gofmt
    • go vet: No issues from go vet
    • gocyclo: All functions must have cyclomatic complexity ≤10
    • golint: No lint issues
    • ineffassign: No ineffectual assignments
    • license: Valid license file present
    • misspell: No spelling errors in comments/strings
  9. Diagrams: Use Mermaid for all diagrams. Never use ASCII art. TestDocsDrawDiagramsInMermaid (test/gates/claude_rules_test.go) fails on a box drawn in characters in a tracked Markdown file.
  10. Pinned Dependencies: All external dependencies must be pinned to specific versions with SHA digests for reproducibility and security:
    • Docker base images: alpine:3.21@sha256:...
    • Compose service images: trinodb/trino:453@sha256:...
    • GitHub Actions: actions/checkout@<40-hex commit>
    • Go modules are pinned via go.sum
    • TestDependenciesArePinnedByDigest (test/gates/claude_rules_test.go) fails on an action, a Dockerfile FROM (other than scratch) or a compose image without one
  11. Documentation Updates: When modifying documentation in docs/, also update the LLM-readable files:
    • docs/llms.txt - Index of documentation with brief descriptions
    • docs/llms-full.txt - Full documentation content for AI consumption These files follow the llmstxt.org specification.
  12. CRITICAL - Documentation Completeness: make doc-check warns when documentation-worthy changes (new packages, config changes, new toolkits, new CLI flags, new Makefile targets, new migrations) are present but README.md, docs/, docs/llms.txt, and docs/llms-full.txt were not updated. While this is a soft warning for human developers, it is a blocking requirement for AI agents: if make doc-check emits a WARNING, you MUST update the relevant documentation before declaring the task complete.

Project Structure

pkg/ holds 42 top-level packages (all public API). Depth-2 subdirectories are shown where they represent a distinct implementation (a storage backend, an adapter); helper subpackages are omitted for brevity. Regenerate this list with find pkg -mindepth 1 -maxdepth 1 -type d | sort and diff against the packages below when adding or removing a pkg/ directory.

Before adding a package under pkg/, note that TestPublicSurfacePolicy (#1076) refuses a package that is outside the supported import surface named in docs/library/stability.md and has a single first-party importer: that shape is an implementation seam and belongs under internal/.

mcp-data-platform/
├── cmd/mcp-data-platform/          # Entry point (main.go)
├── pkg/                            # PUBLIC API (42 top-level packages)
│   ├── admin/                      # REST API endpoints for administrative operations
│   ├── audit/                      # Audit logging (postgres/ = PostgreSQL implementation)
│   ├── auth/                       # Authentication: OIDC, API keys, claims, middleware
│   ├── authevents/                 # Durable audit history for the OAuth authorization flow
│   ├── blobserve/                  # Raw-content HTTP writer: sanitized type, nosniff, disposition, byte ranges
│   ├── catalog/                    # The platform's own catalog: datasets, columns, glossary, tags, domains, data products, their curation as versioned aspects with rollback, and the mcp:dataset:(kind,connection,path) reference form; its PostgreSQL store is internal/platform/catalogstore (#1917)
│   ├── browsersession/             # Browser-based OIDC authentication (cookie sessions)
│   ├── configstore/                # Granular key/value storage for platform config (postgres/)
│   ├── connoauth/                  # Shared OAuth-to-upstream-MCP implementation across connection kinds
│   ├── connreconcile/              # Shared remove/add reconcile of a DB connection onto live toolkits (admin hot-reload + reload bus)
│   ├── connid/                     # Connection identity: the instance a connection is stored under, the name a call binds it by, the toolkit serving it, and which half of the config owns it — one Resolver, distinct types
│   ├── connview/                   # Builds the list_connections view (configured + discovered)
│   ├── contenttype/                # Media-type detection and normalization for every content write path
│   ├── database/                   # Database utilities (migrate/ = golang-migrate runner + 274 embedded SQL migrations)
│   ├── embedding/                  # Text embedding generation for memory vector search
│   ├── indexjobs/                  # Postgres-backed, source-kind-agnostic background indexer
│   ├── knowledge/                  # Unified read path for platform knowledge (federation/ = live toolkit registry adapter)
│   ├── mcpcontext/                 # Context helpers for MCP session state
│   ├── memory/                     # Persistent memory storage for agent/analyst sessions
│   ├── middleware/                 # MCP protocol middleware chain (auth, authz, enrichment, audit, rules)
│   ├── notification/               # Email-notification domain: event/preference model, store contracts, enqueue path (smtp/ = admin mail-server settings, validation and store; delivery layers live under internal/notification/) — decomposed by #1080
│   ├── oauth/                      # OAuth 2.1 authorization server (postgres/ = storage implementation)
│   ├── observability/              # OpenTelemetry metrics (proxy/ = authenticated PromQL query proxy)
│   ├── oidcdiscovery/              # Shared OIDC discovery-document fetch/parse (used by auth JWKS + oauth broker)
│   ├── persona/                    # Persona-based access control and customization
│   ├── pkcestore/                  # In-flight PKCE state for outbound OAuth (oauth-start → callback)
│   ├── platform/                   # Core orchestration: facade, config, options, lifecycle (fieldcrypt/, instructions/, personastore/ = seams shared with pkg/admin; other facade-internal seams live under internal/platform/)
│   ├── portal/                     # Asset portal HTTP surface + aliases over its seams (knowledgepage/, mention/, shareaccess/, shareguest/, threads/, ...)
│   ├── prompt/                     # Prompt management: versioned store contract, review gate (attachserve/, postgres/)
│   ├── query/                      # Query execution provider abstraction (trino/ = Trino adapter)
│   ├── ratelimit/                  # Shared per-IP token-bucket limiter + trusted-proxy client-IP resolver (portal viewer, OAuth endpoints)
│   ├── registry/                   # Toolkit registration and management
│   ├── resource/                   # Managed resources: human-uploaded reference files
│   ├── script/                     # Managed-script domain: record, typed params, version history, edit funnel (engine + MCP surface live under internal/platform/)
│   ├── searchgate/                 # Per-session discovery signal for the search-first gate (postgres/ = replica-shared backend)
│   ├── semantic/                   # Semantic layer abstraction; the platform catalog implements it (internal/platform/catalogsemantic)
│   ├── session/                    # Session externalization (postgres/ = multi-replica backend)
│   ├── textpatch/                  # Kind-agnostic anchored text editing: outline, locate, patch, unified diff (patchmcp/ = MCP error adapter)
│   ├── toolkit/                    # Shared types for toolkit implementations
│   ├── toolkits/                   # Toolkit adapters registered with the platform:
│   │   ├── apigateway/             #   HTTP API gateway proxy toolkit
│   │   ├── gateway/                #   MCP gateway toolkit (proxies tools from upstream MCP servers)
│   │   ├── graphql/                #   GraphQL connection kind: one endpoint, an introspected schema kept per connection, graphql_discover/query/export
│   │   ├── knowledge/              #   Knowledge capture toolkit
│   │   ├── memory/                 #   memory_manage / memory_capture tools
│   │   ├── portal/                 #   Save/manage-asset toolkit
│   │   ├── postgres/               #   Application database kind appdb (#2400, #2428, #2402, #2404): platform.query/execute/transaction/batch bound directly from the script host to a pgx pool (native binding, typed results, statement cache, pool wait bound, held transactions rolled back with the run), manage_schema's versioned migrations (ledger in the target, advisory-locked apply, plan rolled back, describe), savepoints, cursors read in pages, COPY in and out and structured values (#2452-#2455), the platform's own database refused
│   │   ├── s3/                     #   S3 toolkit
│   │   ├── search/                 #   Universal, topology-free discovery entry point
│   │   ├── tools/                  #   toolsindex/ = tools-discovery indexjobs consumer
│   │   └── trino/                  #   Trino toolkit
│   ├── tuning/                     # AI tuning: prompts, hints, operational rules
│   └── user/                       # Directory of known people keyed by email
├── internal/                       # Non-exported implementation (not part of the supported library surface)
│   ├── catalogscan/                # (under internal/platform) the platform catalog's scan (#1918): Trino/API/GraphQL sources, per-connection exclusions and the interval (platform_settings section "catalog"), each connection's last scan (catalog_scans), the advisory-locked loop; internal/httpserver/catalogwire assembles it from the live toolkits and internal/admin/catalogscanapi serves it
│   ├── catalogsemantic/            # (under internal/platform) the semantic.Provider over the platform catalog (#1919), the only provider on a deployment with a database; resolves a table by the calling connection, else the first connection that catalogs its path; a dataset is named only by its mcp:dataset reference
│   ├── agentinstructions/          # The deployment's customized agent-instruction layer as a policy rather than a config value (#1607): the byte bound and size advisory both its writers enforce, the config-store adapter it is read and written through, and the `mcp:knowledge_page:<slug>` index-entry form BOTH instruction layers point at a page with
│   ├── admin/                      # Admin-API seams built only by pkg/admin: storageapi/ (the storage capacity report and a store's history, #2148), auditapi/ (events + metrics), callapi/ (the call catalog + its review actions), catalogapi/ (OpenAPI spec bundles + embedding jobs), connoauthapi/ (connection OAuth, unified + legacy per-kind), secretapi/ (stored secrets, #2051), mapsapi/ (the maps settings, regions, refresh and size estimate, #2068), graphqlapi/ (a graphql connection's schema: read the state, re-read it from the endpoint, or take the one an operator pastes for an endpoint that disables introspection), migrationsapi/ (an application database's migrations, their state in the target's ledger, their history, and the plan of the pending ones, #2404), notifyapi/ (notification delivery history + status counts), settingsapi/ (SMTP + review-queue-alert settings REST), botcheckapi/ (the named bot checks, #2173, #2259), personarules/ (a persona's API-route rules normalized and its rules and portal levels validated before the admin API stores them), apichangeapi/ (API catalog refresh, watch, change reports and their apply/discard, used-by and upstream warnings, and the api_changes settings, #2469), appdbapi/ (an application database's health, history, drift, adopt, maintenance, cancel/terminate, console and the health settings, admin only and audited, #2406, #2409, #2410, #2427) — extracted by #1078
│   ├── apichange/                  # API catalog specs kept current (#2469): the spec diff (operations added, removed, changed, newly deprecated, info.version), the one Refresher the manual refresh and the scheduled loop check through (conditional fetch, apply, hold for review, an uploaded spec's upstream_url reported and never applied), the watch/change store, the used-by index (scripts by source and by run, endpoints, prompts), upstream warnings (Deprecation, Sunset, removal) recorded from answers upstreamwarn hands it, the audit decorator recording a script run's operations, and the channel notifier (settings section api_changes)
│   ├── apiresponse/                # The API gateway's response rules: which bodies are inlined and which headers reach the caller (extracted for the gateway's size budget)
│   ├── upstreamwarn/               # The process-wide observer the outbound chain hands every api connection answer to, for a request the gateway marked with its catalog operation (#2486)
│   ├── apigwmetrics/               # The api gateway's outbound HTTP instrumentation as an http.RoundTripper: the connection/status labels, and the persona the call was authorized under, read off the request context the tool call carries (#1615). Holds no gateway types, and was extracted when pkg/toolkits/apigateway reached its package-size budget
│   ├── outbound/                   # The one transport chain every HTTP client the platform builds is made from (#1895): the User-Agent, a client span named `{kind} {method}` that continues the caller's trace and carries the W3C traceparent to the upstream (off per connection with `trace_propagation: false`), `http_client_requests_total{kind,connection,status_class}` and its histogram, and `egress_blocked_total{reason}` with one WARN when the egress guard under it refuses. `NewClient(Options)` or `Transport(base, opts)`; the recorder is the platform's one Metrics, installed by internal/platform/obs through `SetDefaultMetrics`, and `Metrics()` is how a retry loop counts beside the requests it issues. `.semgrep/go-outbound-client.yml` refuses an `http.Client` built anywhere else
│   ├── opsobs/                     # The recorder the platform's own operations report through (#1898): installed by internal/platform/obs like outbound's default, read by the authenticator chain (auth_attempts_total), the OIDC JWKS fetch, the HTTP gate's fail-open, browser sign-in and the domain operations (`Start(ctx, Op*)` opens a span under the call and counts domain_operations_total{operation,result}); also the label vocabulary those series use (AuthMethod*, AuthReason*, Denial*, Dependency*, Connection*, Op*, Sink*), kept off pkg/observability's exported surface
│   ├── advisorylock/               # The one session per process every PostgreSQL try-lock held across work is taken on (#2169): the background loops (catalog scan, maps, storage and webhook alerts, retention, capacity, the call catalog and audit sweeps, thumbnail sweeps, catalog import, resource reclassification), connlimit slots and the connoauth refresher. A lock on a pooled connection of its own pinned that connection for the whole pass while the pass drew from the same pool, and four such loops starved a pool of five. `Try(ctx, db, ID(key)|Pair(a,b))` returns a release; a key the process holds is refused, since PostgreSQL would grant it again; the session goes back to the pool with its last lock. `.semgrep/go-advisory-lock.yml` refuses a try-lock taken anywhere else
│   ├── bgloop/                     # The one way the platform runs work in the background (#1897): `Run` (a timer, a wake channel, a stop channel), `Consume` (a channel of events), `Unit` (one claimed unit of work) and `Listen` (a LISTEN connection's state). Every iteration is counted by result, timed and stamped on success (`background_loop_*{loop}`), gets a span whose context its body logs with, and a skip under another replica's lock is `ErrSkipped`; loop names are constants in names.go. `.semgrep/go-background-loop.yml` refuses a ticker or an infinite loop around a select anywhere else
│   ├── objectobs/                  # Every object operation on a bucket the platform owns (#1896): `Do` wraps one put/get/get_range/list/delete in a `storage.<operation>` client span and one `storage_operations_total{purpose,operation,result,reason}` observation, `Reason` reads a failure into access_denied/bucket_missing/quota_exceeded/not_found/other, and `WithPurpose` lets a caller writing through a shared client (the tile worker, an export, a script's output) report under its own purpose. Called by pkg/portal/s3adapter and the webhook objects; records through outbound.Metrics()
│   ├── dbobs/                      # The platform's PostgreSQL pool opened through otelsql (#1896): a `postgres.<operation>` span per statement inside a traced request (none outside one), `db_client_operation_duration_seconds{operation}` and `db_client_slow_statements_total{operation}`, where the operation is the statement keyword, `vector_search` for a pgvector ranking, or the transaction step. The SQL text is on the span only with `OTEL_TRACES_INCLUDE_DB_STATEMENT=true`; the slow threshold is `MCP_PLATFORM_DB_SLOW_STATEMENT_THRESHOLD` (1s)
│   ├── httpobs/                    # What every inbound HTTP request reports (#1889): the route TEMPLATE it matched (never the path), `http_server_request_duration_seconds{route,method,status_class}`, a server span named `{method} {route}` whose traceparent is written back onto the request so the MCP layer's spans nest under it, `http_rate_limited_total{limiter}` for every 429 a limiter marked (`MarkRateLimited`), and the `slow HTTP request` WARN past `server.slow_request_threshold`. `Routed(mux, wrap)` resolves a nested mux's template before the auth layer clones the request and refines it after the mux served; `Detached` keeps an in-process re-entry (the PDF route reading the content route) off the caller's record
│   ├── mcpobs/                     # What every MCP request carries for observation (#1889, #1893): the caller's trace context from params._meta or the HTTP headers, the negotiated protocol version, the MCP semantic-convention attribute keys, and the observer of every method other than tools/call (a span named by the method, `mcp_requests_total{method,status}`), the outermost receiving middleware. pkg/middleware's tools/call tracer reads the same helpers
│   ├── routescan/                  # The platform's HTTP route table read out of its source: every ServeMux pattern, folded from literals, package constants and the mount prefixes a registrar's call sites pass, with the registrations it cannot fold reported rather than skipped. Read by the admin catalog parity gate (#697) and the inbound request observer's gate (#1889, `TestEveryRouteReportsItsTemplate_RealDB`), so the two check one table
│   ├── gqlschema/                  # The GraphQL schema machinery the graphql kind is built on: the compatibility-floor introspection query, introspection JSON rendered to SDL, the namespace descent that walks a schema into dotted operation ids, the runnable skeleton and variables stub a caller edits, and what a document is allowed to be (parse, validate, depth, the operations it invokes). Knows nothing about connections or HTTP, which is what makes descent testable against a hand-authored schema
│   ├── pgtext/                     # The text forms PostgreSQL writes for a range, a multirange, a composite row, an hstore and pgvector's vector, read and written back (#2455); the appdb kind maps each part by its type
│   ├── pglex/                      # PostgreSQL SQL read lexically: where top-level statements end (a BEGIN ATOMIC body kept whole) and where literals, quoted identifiers, dollar bodies and comments start and stop; the appdb kind's statement checks, migration lint and the admin console read SQL through it
│   ├── appdbhealth/                # An application database's health from its statistics views (#2409): sizes, dead tuples, vacuum state, unused/duplicate/invalid indexes, transaction id age, connections, long-running and idle-in-transaction sessions, blocking, replication lag, pg_stat_statements; Summary (numbers only) and manage_schema describe findings
│   ├── appdbdrift/                 # Drift (#2406): the applied migrations built on a throwaway database compared with the live schema per object; adopt: an unmanaged schema rendered from the catalog as a baseline migration, saved and marked applied only when built from zero it matches
│   ├── appdbops/                   # Maintenance of an application database (#2410): analyze, vacuum, vacuum_full, reindex outside a transaction under a lock timeout; index create/drop refused naming manage_schema
│   ├── appdbconsole/               # The administrator's console on an application database (#2427), one transaction READ ONLY by default, and cancel/terminate of a backend of the connection's own roles (#2410)
│   ├── appdbwatch/                 # The one-replica loop sampling every application database's health and drift into appdb_health_samples, the appdb_health settings section, the leveled alerts (family appdb) and the gauges
│   ├── standalone/                 # An HTML or JSX asset as one HTML file that opens offline (#2530): the served runtimes, declared images and fonts and files on other hosts inlined, a JSX asset compiled and bundled with esbuild against /portal/vendor/jsx/, a platform data read refused with the reasons; internal/httpserver/standalonehttp serves it at .../standalone beside the content routes, other hosts through an egress guard admitting no private address
│   ├── contentenc/                 # How the platform sends a file compressed (#2598): which media types compress, the gzip and brotli forms, whether a form saves enough to keep, and which forms Accept-Encoding allows; a site's published files and the portal's own build files share it
│   ├── auditredact/                # The values one request must never leave in an audit row (#2555): an endpoint request's application cookies, carried on its context and replaced by MCPAuditMiddleware wherever they appear in a call's parameters and error, before the call catalog, lineage or the store read the event
│   ├── platform/integration/       # (under internal/platform) integrations (#2659): an operation only the deployment's environment knows how to do handed to a script an administrator chooses (Site routing first, route(req)); the operation registry and contract, integration_bindings/integration_items, the pass that diffs an operation's items against what the script was last handed (statement triggers notify integration_changed; one replica under advisory lock 4713210405; a timer per operation), one run at a time as a queued script run of trigger `integration` whose return is the run's result, and Prepare, which the run worker calls; internal/admin/integrationapi serves Admin > Settings > Integrations and internal/site/siterouting is Site routing's items and the statuses sites show
│   ├── platformfeedback/           # What agents report the platform could not do for them (#2820): manage_feedback topic=platform posts checked (fields, secrets, per-session and per-persona limits), near-duplicates folded onto the open post, sent to the configured channels as document type platform.feedback; the platform_feedback settings section and the admin routes under /api/v1/admin/platform-feedback
│   ├── secretscan/                 # Credentials in text the platform is about to keep or send (#2820): credential shapes (PEM keys, bearer and provider tokens, JWTs, URL credentials, password assignments) and the deployment's own secret values as written and base64-, hex-, URL- and JSON-escaped; a finding names the field and kind, never the value
│   ├── toolhelp/                   # Answers from a tool's advertised input schema (#2811, #2815, #2820): the invalid_arguments refusal naming each unknown property's closest accepted name, each type or enum mismatch and the accepted parameters; help on every command/action tool; the sentence a refusal met twice in a session gains
│   ├── cachescope/                 # The cacheScope every cacheable MCP result carries under 2026-07-28 (#2794): private for the lists filtered by caller and resources/read, public for the template list and discovery; stamped in pkg/middleware's outermost result layer so a result a middleware built is decided too
│   ├── toolschema/                 # A registered tool's advertised input schema, read from the server's own tools/list over an in-process session and cached (#2811)
│   ├── platform/connroute/         # (under internal/platform) a refused call naming a connection of another kind gains which kind it is and the tools that take it (#2812); KindName and ScriptRoute feed platform_info's connection-kinds note
│   ├── platform/toolsearch/        # (under internal/platform) ranks the platform's own tools by what a caller says it wants to do, for search's tools source (#2809)
│   ├── untrusted/                  # Third-party text the platform files (#2247): Clean/Line remove invisible, bidirectional and control runes, and Notice is the sentence a mail event carries beside its "external" object of sender-written fields
│   ├── imapmail/                   # IMAP protocol for a webhook source's imap input (go-imap v2): TLS-only session, EXAMINE, UID SEARCH, BODY.PEEK header and whole-message fetches, MIME bodies to text, HTML to visible text, quoted history collapsed
│   ├── mailtrust/                  # Which messages an imap source files: the sender allowlist and the aligned SPF/DKIM/DMARC pass read from the receiving server's own Authentication-Results
│   ├── textchunk/                  # Cuts a text longer than an embedding provider's input into pieces that each fit, at the boundaries its kind has (a markdown heading, a Starlark definition), then blank lines, words and rune boundaries, so the whole text reaches the model (#1242, #2027). Shared by knowledge pages and managed scripts
│   ├── opranking/                  # The relevance arithmetic both operation-ranking kinds score with: the lexical AND filter, the hybrid blend and its weight, and where a ranked result stops being relevant. Holds no record type — a caller ranks Candidates carrying an opaque id — which is what keeps the OpenAPI operation and the GraphQL operation out of it
│   ├── apigwtls/                   # The TLS material an HTTP upstream connection carries: what its mTLS keypair and CA bundle must satisfy, and the *tls.Config its outbound transport is built with. Knows nothing about API connections — it takes the values one carries, including the kind name its refusals speak in — and is reached through internal/upstreamauth (#1626, #1647)
│   ├── upstreamauth/               # What every HTTP-based connection kind does to reach its upstream, in one copy: the Authenticator and its modes (none, bearer, api_key, basic, oauth, mtls), the operator-owned static headers and the header names a model may not claim, the connect/call timeouts and response read cap, and the TLS material. Owns the config keys those rules belong to and validates them; error text is the caller's, through Config.ErrPrefix. googlekey/ reads a Google service account's JSON key file: the fields the jwt_bearer grant is filled from, the identity shown in place of the redacted file, and the next step for each of Google's refusals (#2061). Extracted from pkg/toolkits/apigateway so a second kind reuses it instead of forking it (#1647). tokengrant/ is what every grant made without a browser shares at a token endpoint: the bounded client, the error scrub, the RFC 6749 section 5.2 refusal reading, and the password grant's token source (#2689), whose API user (oauth_username, oauth_password) is renewed by refresh token and then by password, held in memory only
│   ├── hmacsig/                    # The one definition of a webhook HMAC signature (#1996): the bytes signed (body, timestamp.body, id.timestamp.body), the signature header written and read back (prefix, space-separated signatures, Stripe's t=,v1= format), the Standard Webhooks whsec_ key, and the standard_webhooks/github/stripe/platform presets. Inbound sources verify with it (internal/webhook/whauth) and an outbound auth_mode=hmac connection signs with it (internal/upstreamauth), so the two agree by construction
│   ├── buildinfo/                  # The identity of the running binary: the version, commit and build date the release stamps in through ldflags. The one place those live, so --version, the admin system route and the outbound User-Agent report the same build; it imports nothing first-party because the transport seam needs it and cannot import internal/server (#1679)
│   ├── useragent/                  # The User-Agent the platform presents to an upstream (`mcp-data-platform/<version>`) and the one rule for when it is sent: on every outbound request that does not already carry one, applied as an http.RoundTripper over every client internal/upstreamauth and pkg/connoauth build. A static_headers or per-call value is already on the request and is left alone (#1679) Since #1895 the outbound chain (internal/outbound) is what applies it.
│   ├── sqllineage/                 # (under internal/platform) lineage recorded from the statements the platform runs and from managed-script runs (#1922): an audit decorator turns a trino_execute write (CTAS, INSERT ... SELECT, MERGE, CREATE VIEW) into edges from each table read to the table written; a per-run collector records edges from the tables a script read to the files it exported
│   ├── scratchcatalog/             # The query engine's refusals of the scratch catalog's partition procedures read into the setting that fixes each (#1888): a procedure access control denies the connection's Trino user (add a procedures rule) and register_partition disabled by the catalog (set hive.allow-register-partition-procedure). One copy for the webhook source pre-check and the Trino connection test
│   ├── connprobe/                  # Opening one of a toolkit's connections on request and reporting what its upstream said: the Prober a kind implements, the Result an operator reads, and the scrub that keeps a DSN's password out of it. Its own package rather than a corner of pkg/toolkit, which describes what a toolkit reports about a connection WITHOUT being asked (#1805)
│   ├── connstate/                  # Each connection's state as the calls that used it last found it (#1898): healthy, unreachable, auth_failed. Fed by the outbound chain (api, graphql, mcp), the Trino telemetry (mcp-trino's failure classification) and the S3 toolkit, read by mcp_platform_connections; nothing in it sends a request, and a connection no call has used reads configured
│   ├── jsonwalk/                   # The strings of a decoded JSON value rewritten at any depth, copying only what changed: the walk a recording's arguments are redacted by before they are recorded and renamed by on an application import (#2475, #2476)
│   ├── conntrim/                   # The whitespace a paste brings removed from the connection configuration fields where it is never part of the value (URLs, identifiers and claims, the scope, durations), on every admin API connection save; a secret, a body, a header value and a PEM block are stored as sent (#2467)
│   ├── cfgmap/                     # The typed readers over the map[string]any a connection is stored as: the tolerant String/Duration/Int64/Bool/StringMap that absorb what a JSON round-trip did to an operator's value, in one place so two kinds cannot disagree about what `"call_timeout": 30` means (#1647)
│   ├── reqlog/                     # A failure an HTTP handler met, logged at ERROR while the caller waits and at DEBUG once the request's context is done (#2728): reqlog.Failed sanitizes the error and reports whether the caller has gone; .semgrep/go-request-error-log.yml refuses slog.ErrorContext on a request's context anywhere else
│   ├── httpjson/                   # RFC 9457 Problem Details responder + admin list-query param parsing, shared by the admin/portal decomposition seams (#1078)
│   ├── httpserver/                 # HTTP composition root: mux/route assembly (MCP streamable+SSE, OAuth, admin/portal/resources/gateway/observability REST, portal UI), CORS, drain/shutdown sequencing — extracted from main.go (#895). Subpackages are the adapters it mounts: accessgate/, attachhttp/, catalogapi/ (the portal catalog routes under /api/v1/portal/catalog, #1921: dataset search and browse, a dataset with its columns, curation, lineage and history, aspect writes and rollback, and the glossary, tags, domains and data products; read takes the persona's fetch grant and write its apply_knowledge grant, a dataset only on a connection the persona reaches, and every write is audited as an apply_knowledge call from the portal), catalogwire/ (assembles the catalog scan and the portal catalog routes from the live toolkits), changesethttp/ (the knowledge changesets served to apply_knowledge holders under /api/v1/portal/knowledge/changesets, #2337), corshttp/ (the CORS layer and the webhook path that bypasses it, extracted when the root reached its size budget, #1889), gatewayhttp/, health/, httpauth/, instanceheader/ (the `X-Platform-Instance` response header naming the process that served a request, #1708), mentionhttp/, notifyhttp/ (self-scoped notification prefs), scripthttp/ (managed-script admin + portal routes, including the administrator's owner transfer; its subpackages handlerhttp/ (a script's handlers and Admin > Automations > Handlers, #2435), statehttp/, exclusivehttp/, eventshttp/, granthttp/, outputshttp/, fireshttp/ and connchoicehttp/ serve a script's state, bindinghttp/ its endpoint binding (#2171), whether it runs one at a time (#1986), the webhook source it runs for and how its event runs stand (#2332), its run grants (#1846), the outputs of the caller's runs (#1848) when every visible schedule fires, laid out on the viewer's day, week and three months with each fire expanded by the scheduler's own parse (#1891), and the connections a connection-typed parameter may name (#1361); draftview/ renders what the draft routes report; flowhttp/ serves a version's flow diagram and its comparison with another version (#1906, #1908), a run drawn on it (#1907) and a script's tile (#1909)), sources/, thumbwire/ (assembles and starts the tile worker from the platform's stores, buckets and the assembled mux, #1787), storagewire/ (assembles storage capacity: the settings, the SeaweedFS client, the alert engine and the routes, #2148), maphttp/ (the basemap archives and their listing under /portal/maps/, no session, by range, #2068), mapwire/ (assembles the maps service, #2068), unsubhttp/ (no-login unsubscribe + its tokens), endpointwire/ (mounts /endpoints, /botcheck and the bot check settings, #2170), formwire/ (forms on the server: submissions stored through the webhook receiver, platform.decrypt answered, the viewer key and the submissions reader, #2177-#2180), accessreqwire/ (assembles requests for access, #2090), generalfeedbackwire/ (assembles the General feedback list and mounts its routes, #2603), collectionsweepwire/ (adds the collection item sweep to the retention sweeps, judged by the feedback routes' decision, #2752), personashare/ (the personas a share can name and their members, #2089), resourcelevel/ (a caller's resource claims narrowed to their persona's portal level, #2225), userkeywire/ (the self-scoped API key routes' wiring, extracted for the root's size budget), savegatewire/ (the save gate the portal's script editor and an application import cross, #2476), apichangewire/ (assembles keeping API catalog specs current: the refresher, the scheduled loop, the warnings observer, the routes and the catalog_fetch private prefixes, #2469), appdbwire/ (assembles operating application databases: the health loop, its settings and alerts, the gauges, the admin routes and what manage_schema status and describe add, #2406, #2409), versionhttp/ (#1076, #1080), platformfeedbackwire/ (assembles platform feedback: the settings section, the secret check over the deployment's stored secrets and sealed connection values, the embedder, the channels, manage_feedback topic=platform and the admin routes, #2820)
│   ├── sqlgate/                    # Collects the module's SQL and hands each statement to a real PostgreSQL to parse and plan (#1512); integration-tagged, so it is absent from the default build
│   ├── sqlrank/                    # One PostgreSQL statement ranking a candidate set the caller builds (#2500): every row its stored full-text column matches and every row whose blended semantic score reaches opranking.ScoreFloor, materialized and scored by exact distance (an HNSW scan filters after its nearest-neighbor step), paged with a count of all results. The portal's asset and collection searches rank through it
│   ├── sqltables/                  # The one lexical extractor of the tables a SQL statement reads (enrichment + call targets), and the statement's bounded kind and literal-free summary every Trino and PostgreSQL metric and span is labeled by (#1896)
│   ├── tabletype/                  # The one model of a column type a table is declared with or a typed file is written from (#1833): the Trino types, the parse of the type text Trino reports for a query column, the ordered JSON decode, and the type inference a JSON-lines registration and a script's Parquet export share
│   ├── tableparquet/               # Parquet for registered tables (#1833): a file's columns from its footer alone (read by range), the Parquet-to-Trino mapping and its refusals, and the writer trino_export and platform.export write Parquet through (ordered columns, Dremel levels, ZSTD)
│   ├── tablexlsx/                  # Excel workbooks a script exports (#1849): the sheet/column/type model and its checks (sheet-name rules, 15-significant-digit limit, exact decimal currency, the cell cap), and the deterministic excelize writer
│   ├── tablecsv/                   # CSV inspection and correction for a table registration: the defects a query engine cannot read through, the reason and remedy a refusal names, the corrected version, and the columns a header declares (extracted from tableregister for its size budget)
│   ├── toolnames/                  # Does a piece of written guidance name a tool this deployment does not register? Prefixes are derived from the live inventory plus a floor list, so a retired `api_`/`manage_`/`memory_`/`save_` name is caught as readily as a `trino_` one (#1607). Asked by the startup instructions lint and by the apply_knowledge agent_instructions sink
│   ├── thumbtypes/                 # The one Go definition of which content families get a tile and which need a second dark one; the browser's counterpart is ui/src/lib/thumbnailSupport.ts and a test holds the two together (#1568)
│   ├── rasterfit/                  # A raster image (PNG, JPEG, GIF, WebP, BMP) reduced to fit a box, decoded in the platform under a bound on the memory its pixels take and one image at a time per process (#2697): the tile worker hands the renderer the reduced copy, and an image whose header declares more pixels than the bound is refused before it is decoded
│   ├── headless/                   # The platform's client for the headless Chrome every thumbnail is drawn in (#1787): a hand-written DevTools-protocol client over one WebSocket, and Render, which draws one page in a fresh browser context behind a dead proxy, answers every request the page, its frames and its workers make (its own files in-process, a public URL through internal/egressguard), removes the socket constructors before any script runs, and screenshots it once the page reports itself drawn
│   ├── endpoint/                   # Endpoints (#2170): a managed script bound to /endpoints/{name}/... that answers each request with handle(req), inline. epbinding/ (the binding record, its validation and path template, the store contract, the handle(req) check binding and saving share), epstore/ (script_endpoints and script_endpoint_failures), epcmd/ (the endpoint kind of script handler, #2441: setting, describing, listing, enabling, disabling and deleting a script's endpoint handlers and form_preview, carried out through internal/platform/scripthandler for manage_script's handler_* commands and the portal's handler routes; an administrator's, and a form's owner's for their own form), eprun/ (the runner: the per-version compiled module checked by one stamp read per request, req built and the response read back, a run's limits and identity, one audit row of source endpoint, endpoint_requests_total, failed requests kept 7 days), ephttp/ (the HTTP surface: the authenticated, public and bot_check access modes, an authenticated binding's callers, the named bot check, per-binding CORS, per-replica endpoint and caller rate limits, the body limit, /botcheck/challenge and /botcheck/solver.js), epwire/ (assembles them for the script wiring), epform/ (the form contract: a script defining form_spec and form_submit, the signed spec in form_token, the checks a submission passes, sensitive fields and the viewer token an asset hands an embedded authenticated form, #2176, #2177), epcollect/ (an accepted submission stored as one event of the form's webhook source, sensitive fields sealed with fieldcrypt first, and platform.decrypt for a persona the form names, #2178, #2179), epsource/ (the webhook source made for a form when it is bound, #2178), epsubmit/ (a form's stored submissions read for its owner, decrypted and audited, and their CSV and Excel export, #2180), epformpage/ (the page a form is rendered on, /forms/<endpoint>, framed by a site its binding's allowed_origins list or by an asset carrying the signed embed marker, #2177, #2331), epformcard/ (the card the tile and PDF renderers draw in place of an embedded form, never loading its page, #2431), file fields saved as managed resources once form_submit accepts (#2333)
│   ├── scripttoken/                # Signed tokens a script mints and verifies (#2175): platform.mint_token/verify_token as run bindings answered by an Issuer in a run and from the recording in a test, the HMAC-SHA256 token over a JSON body (claims, the endpoints or script it is bound to, expiry, id, single use), the key derived from a stored secret whose allow_connections lists `script_token` and whose allow_personas is checked against the author's persona, and script_token_uses, the single-use record every replica refuses a second use from
│   ├── botcheck/                   # The named bot checks a bot_check endpoint picks from (#2173, #2259): the platform's proof-of-work challenge (signed with a key derived from the browser-session signing key, bound to one endpoint and one check, difficulty rising with the endpoint's recent rate), Cloudflare Turnstile and hCaptcha verified server side with a stored secret, the used-answer table every replica refuses a replay from, the `bot_checks` table (a check an endpoint names cannot be deleted) and the browser solver script
│   ├── egressguard/                # The SSRF guard for a fetch whose destination a caller or a document chose: resolve, refuse private/loopback/link-local/CGNAT/metadata addresses, dial the address that was checked. Shared by the util connection and the thumbnail renderer (#1787)
│   ├── exporttrunc/                # What an export cut at a row limit or page bound does (#2057): the judgment trino_export, api_export and graphql_export share (a cut the caller asked for is written and flagged, one at the deployment cap or the default page bound is refused unless on_truncation is warn), the truncated/limit_applied/limit_source/limit_unit fields, the count expectations, the version metadata keys and the `_sys-truncated` tag the portal version store keeps in step with the content
│   ├── exportstream/               # The streaming plumbing api_export's page walk writes through: the JSON array written item by item into the pipe a storage upload reads, and the reader that bounds that upload (extracted from pkg/toolkits/apigateway for its size budget, #2057)
│   ├── pagewalk/                   # The api gateway's page walk behind `paginate` (#1535): pagination-signal detection, the address a walk moves (path+query, or the util fetch body url), the follow step, the Retry-After pause, and the loop over a Requester the gateway supplies
│   ├── scriptcallsite/             # Where in a managed script a host call was made (#1907): the line:col of each script frame on the Starlark stack, outermost first, carried on the run's context, on the MCP request's _meta to the audit row (audit_logs.call_site) and on a run output, and read back from a failed run's backtrace. The flow graph records the same positions per card, which is how a run's calls land on the card that made them
│   ├── openrun/                    # The refusal a script set to run one at a time answers with (#1986): the open run a new run collides with, the error naming it (id, what started it, since when) that run_script and the portal return, and the words a skipped fire's reason uses. Its own package so pkg/script's public surface does not carry it
│   ├── runstate/                   # The vocabulary of a managed-script run's queue history (#1859, #1860): how each attempt ended (finished, retried, released, shed, lease_expired, unresponsive), why a failed run failed (script, upstream, memory, worker_lost, platform, state_conflict) and whether a retry is expected to help, a running run's liveness, the heartbeat window and the reclaim default. Its own package so pkg/script's run record carries it without growing that package's public surface
│   ├── scriptdest/                 # Resolves the destination a script names for an output to the address configuration declares; the one resolution the run and validate share
│   ├── upstreamretry/              # The one reading of when an upstream HTTP answer is worth asking again (#1859): 429 any method, 503 to a read, Retry-After in both RFC 9110 forms; the advice the api gateway reports on a result, the host-side wait a script's host makes on it (at most three retries within the deadline), and the upstream_unavailable error code/category. The gateway's page walk pauses by the same Retry-After parse
│   ├── webhook/                    # Inbound webhook sources (#1870): whsource (the source record, its validation and its Postgres store with encrypted secrets), whauth (hmac/header_token/basic/path_token/ed25519/body_token/jwt verification compiled once per source, secret rotation, #2223), whsetup (the sender setup checks a source answers in place of storing: challenge_echo, zoom, discord, graph_validation, #2223), whevent (a request's JSON as events, and the gzipped JSON-lines segment), whlayout (where a source's objects live), jsonpath (the path subset a source names its id/type/key/split with), receiver (POST /hooks/{source}: verify, buffer, write the segment, answer 202 only after), whstore (per-window compaction state, request counts, rejections), whtable (the raw and compacted tables and the view, partition registration), compactor (one Parquet file per compaction window into a managed resource, dedup, retention), whadmin (create/update/delete a source with its tables), whconfig (the `webhooks:` section), whspool (a receiver's local write-ahead spool, #2121: a request is answered once its events are synced to the replica's disk, and drained to object storage under keys named for the spool file, so a re-drain overwrites; VolumeOf reads the filesystem it is on, #2148), whimap (the imap input, #2247: a source whose events are the messages a mailbox receives, polled read-only under an advisory lock, each message from an allowed, authenticated sender written as one event in the raw segments the receiver writes, its attachments saved as managed resources the event names, each folder's place kept in webhook_imap_marks), whalert (the receiver's leveled alerts, #2149: the `webhook_alert` settings, the evaluation of each condition from the spool states and the per-source readings, and the one-replica loop)
│   ├── pmtiles/                    # PMTiles version 3 read and write, and the extract of a bounding box and zoom range from a remote archive by range reads, streamed to any writer with its exact size known first (#2068). Its own copy rather than go-pmtiles, whose Extract reads through http.DefaultClient into a local file and whose one package imports the cloud SDKs
│   ├── maps/                       # Street maps (#2068): the `maps` settings section, the map_regions store, the fetch that extracts a region from the newest Protomaps build (or a mirror) into the operator's bucket under an advisory lock, the scan of maps/uploads/ for archives put there by hand, and what the public archive route and the platform-maps knowledge page read
│   ├── unarchive/                  # The members of a zip, gzip or gzipped tar as streams (#1879): format by magic bytes, zip-slip/encryption/method refusals, the resources.managed.extract limits (member, total, entries, ratio) checked before the first member where the format allows, and a two-block range-read cache so a zip is opened where it is stored. Knows nothing about where members go; resourcewrite.Extractor lands them
│   ├── scriptprintf/               # A managed script's `%` and str.format as Python has them (#2048): printf flags, width, precision and `*`, the format-spec mini-language, and the syntax-tree rewrite scriptdialect.Formatting runs on every module a run compiles; CheckPercent/CheckFormat are what the authoring gates refuse a literal format string with
│   ├── scripthash/                 # The `hash` module a script is given (#2049): md5/sha1/sha256/sha512, the HMACs, crc32 and fnv64, computed in Go; callable, so `hash(x)` stays Starlark's own
│   ├── scriptre/                   # The `re` module a script is given (#2050): Python's re over Go's RE2, patterns cached per run, one step charged per KiB scanned, and Validate for the save gate's invalid-pattern
│   ├── selfcall/                   # A request to the platform's own HTTP API served in process for a caller the tool-call middleware authenticated (#2086): the platform-admin connection hands a saved script's token-less call to the assembled handler with the caller on the request context, which the admin and portal authenticators take as they take a token; also the late-bound Handler the server installs
│   ├── secretref/                  # A stored secret's `{{secret:<name>}}` placeholder (#2051): filling a request's path, headers, query and body at send time, and the Redactor (and the http.RoundTripper over every api connection client) that replaces the values from whatever comes back
│   ├── secretstore/                # Stored secrets (#2051): the record, its validation, the Postgres store (`gateway_secrets`, value encrypted, write-only), the per-call lookup scoped by allow_connections and allow_personas, the read a connection's own configuration goes through (#2066), and an authenticator seed's one-time code issued once per period (#2065)
│   ├── totp/                       # The RFC 6238 one-time code an authenticator app shows (#2065): the seed and its parameters read from an otpauth://totp URI or a bare base32 seed, and the code for a period. A totp secret holds the seed; {{totp:<name>}} is filled with the code
│   ├── connsecretref/              # The save-time half of a connection configuration naming a stored secret as {{secret:<name>}} (#2066): which fields the platform fills as the connection sends a request, and the check the admin API runs before storing one; the fill itself is internal/upstreamauth's and the mcp kind's
│   ├── pathtemplate/               # Matching a request path against an OpenAPI path template, the one rule the api gateway's router, WebDAV matcher and specificity ranking share (extracted from pkg/toolkits/apigateway for its size budget)
│   ├── swagger2/                   # A Swagger 2.0 document (JSON or YAML) converted to the OpenAPI 3 the API gateway reads (#2005): the one conversion a catalog spec saved or refreshed as 2.0 and the platform's own admin API document go through
│   ├── formdata/                   # The multipart/form-data body encoder the api gateway sends an operation that takes form data through (#1296), extracted from pkg/toolkits/apigateway for its size budget
│   ├── procload/                   # How much of the memory and CPU the container allows this process it is using now: Go runtime memory against the cgroup limit or GOMEMLIMIT, getrusage CPU over a one-second window against the cgroup quota or GOMAXPROCS, and "unknown" where either cannot be read. The managed-script run worker's adaptive admission reads it before every claim (#1843)
│   ├── resourcetemplates/          # The three read-only MCP resource templates (schema://, glossary://, availability://) and the URI patterns they are addressed by, which the completion layer also matches on. Answers from the two providers and the URN mapping alone and writes nothing, which is why it needed no part of the platform facade; extracted from pkg/platform for its size budget (#1628)
│   ├── storeresync/                # A replica's live connections and personas made to match the database: the reload bus's peer handlers (a delete without a store read, an upsert that reads and decides, a catalog rebuild) and the full re-read the bus runs when its LISTEN connection comes back, since a notification sent while it was down is lost (#1902)
│   ├── mcptask/                    # The MCP Tasks extension (io.modelcontextprotocol/tasks, revision 2026-07-28; #2009), carried at the protocol level since go-sdk v1.8.0 has none: the per-request declaration check, the task handle and tasks/get answers as result types, the tasks/get, tasks/update and tasks/cancel custom methods, the receiving middleware that answers a declaring client's run_script and export calls with a task, the Claim a tool that keeps its own record accepts with that record's id, and the completion hook the audit layer records a task's call through when its work ends. A task is held by a Source chosen by its id prefix
│   ├── listenbridge/               # Delivers the broadcaster's list_changed events to the `subscriptions/listen` streams 2026-07-28 clients hold on this replica, stamped with each stream's subscription id; records listens from the SDK's acknowledgement in a sending middleware and leaves a gateway tool change to the SDK's own notify (#1967)
│   ├── inprocess/                  # Marks the MCP sessions the platform opens to its own server over an in-memory transport (a script run, the REST shim, the admin console's tool runs, the inventory and tools-index listings), so the shutdown drain's close of live agent sessions leaves them to the work they carry (#2058)
│   ├── shutdown/                   # What a shutdown does with work in flight (#2058): the drains a lifecycle runs from the signal beside the HTTP drain (a managed-script run finishes there instead of being cut off), and the close of live MCP sessions that leaves internal/inprocess sessions to the work they carry
│   ├── pglisten/                   # Shared LISTEN adapter: one goroutine per pg_notify channel waking the workers registered on it (notification delivery, managed-script runs)
│   ├── notification/               # Notification delivery layers built only by internal/platform/notifydelivery, extracted by #1080: notifyprefs/ (preference persistence), notifyqueue/ (queue persistence + LISTEN wakeup), notifyrender/ (branded templates), notifysend/ (SMTP transport), notifyworker/ (send worker)
│   ├── platform/                   # Facade-internal seams composed only by pkg/platform (mwchain, iam, sessionsync, oauthserver, auditwiring (the audit store + delivery writer + call-record decorator + provenance capturer, assembled in one place), callrecord (the call catalog: records, derived outcomes, reuse, promotion), the indexjobs consumers (including datasetindex, the catalog-dataset semantic index, and scriptindex, the managed-script one), mcpapps, connbackfill, reviewalert, the managed-script seams scriptlayer/scriptrun/scriptsession/scriptstore/scriptexec/scriptdraft/scriptauto/scriptadmit/scriptlex (authoring tools, engine, the in-memory MCP session a run's calls go through and the refusal it reads off a failed result, Postgres stores, run worker + script principal + output writer, the one draft-run implementation the `manage_script` tool and the portal editor share, the automatic approval of a personal script for its own owner, how many runs a replica executes at once and the `scripts.worker` capacity settings (#1843), and the lexical source checks `validate` runs over code with strings and comments blanked (#1853)), scriptlint + scriptfmt + scriptexamples (the authoring gates every save of a script's source passes through -- the canonical format, the main() entry point, the structural lint and limits, refusing a script saved before them only for what an edit adds -- and the built-in worked scripts held to them, #1913), scriptrec (every run's and draft's host calls with the answers they were given, and the replay a test and a save are answered from; recstore/ is its Postgres store, #1939), scripttest (a script's test_* functions: the testing and assert modules, statement coverage, and the altered-rows check that refuses a test blind to its data, #1939, #1940), scriptbehavior (what a new version does differently: the replay comparison of recent runs and the reach diff, #1942), scriptsave (the one gate a source save crosses from the tool and the portal: lint, tests, coverage, and a behavior change needing an agreed summary), scripthandler (what starts a script, #2441: the handler kinds endpoint, schedule and webhook, several of each per script, the one service manage_script's handler_* commands and the portal's handler routes carry out, the script_handlers view and the save gate's question of every handler a script holds), scriptevents (the runs a stored webhook event enqueues for the scripts naming its source, bounded by scripts.events.max_queued, and their store; sourcerule/ is who may name which source, #2332), scriptsql (platform.query's parameter binding), scriptstmt (how long a script's statement may run: the scripts.sql ceiling, timeout_seconds, the run's remaining time, and the slowest statement get_run reports, #2073), scripttx (platform.transaction and platform.batch on an application database: the held transaction's calls through the run's call path, the retry on 40001/40P01 and the bindings a retried function may not call, #2402), migrationstore (manage_schema's migrations and their history in appdb_migrations and appdb_migration_events, #2404), scriptcontract (the dialect contract help returns), scriptout (the output serializers platform.export writes through: rows, documents, workbooks, the append=True spool that pages rows into one output (#1861), and the tags=/metadata= reader, #1848/#1849; exportrecord/ is what one export call did and the dict the script is handed back), scriptguard (what stops a run apart from its own logic and what that is recorded as: the per-run memory budget measured over the Starlark values a run can reach at every host call, and the failure cause read from the error's type, #1859/#1861), scriptfail (a failed tool call read the way its tool classified it, #2032: mcp-trino's structuredContent.error made an upstream failure or the script's, the sentence a run's error carries saying which, whether the host issues a read again, and the envelope on_error = "return" hands the script), tooloutput (the output an export tool reports when a script calls it with platform.call, recorded among the run's outputs, #1854), scriptgrant (who other than the owner may run a script, and the binding of a caller.<claim> parameter from the caller's claims, #1846), scriptshare (the functions a save shares with the deployment's libraries and other scripts, reported as shared_code, #2273), scriptflow (the Flow diagram derived from a script's source, #1906; stmtlookup/ reads the statements a call can run through lookups and comprehensions, #2623; scriptdefs/ is every def by a key that tells nested defs of one name apart, the def a name refers to where it is written, and the calls the platform makes, #2848; flowcompare/ marks one version's graph against an older one, #1908, and flowrun/ draws a run on it from its audited calls and outputs, #1907), scripttiles (the script_tiles store the tile worker claims a script's flow tile through, and the reader that serves it, #1909), thumbworker (the tile worker: claims the assets, resources, collections and scripts owed a tile, draws each through internal/headless, records the tile or the reason it could not be drawn; also owns the `thumbnails:` config section), connreach (the one connection enumeration a picker is filled from and an automatic approval is checked against), configwarn (every configuration warning logged and counted in config_validation_warnings_total{code}, the boot checks over personas, connections and agent instructions, and the same persona checks on an admin-API persona write, #1898), startup (initialization as named phases: one `platform initialized` line and a `platform.startup` span with a child per phase), platformstate (mcp_platform_config_info, dependency_up, mcp_platform_connections, mcp_platform_personas and the search index age, probed off the scrape path at most once per `server.state_probe_interval`; never read by /readyz), levelalert (the engine every leveled alert posts through, #2148/#2149: a condition sent at its level each pass under a key carrying the level, a resolution sent once, the state in alert_conditions, and the advisory-locked pass), settingsjson (one platform_settings section as a JSON value of a Go type), storagecap (storage capacity, #2148: the `storage` settings, the SeaweedFS disk read, the samples and their history, the 7/30-day growth and fill date, the findings and the sampling loop), capacity (the database and bucket capacity gauges, #1899: table sizes and row estimates from the catalog, HNSW index sizes and transaction id age, the shared `storage_usage` rows every put and delete moves through `objectobs.DoObject`, and the full listing that resets them and counts orphaned objects and dangling rows under an advisory lock; configured by `MCP_PLATFORM_CAPACITY_*`/`MCP_PLATFORM_STORAGE_*` env, started by platformstate.Wire), the graphql kind's seams graphqlwiring/graphqlstore/graphqlindex (the dependency attachment and first schema read, the Postgres schema store + vector reader, and the indexjobs consumer that embeds a connection's operations), apikeystore, limitsinfo (the `limits` block platform_info reports: export caps with their config keys, trino_query row limits and each page walk's bounds, only for tools the caller reaches, #2057), calltask (a tool call executed apart from its request as an MCP task, #2009: the call_tasks store, the runner that executes an export on a context outliving the request, stamps its heartbeat and reads a cancel from another replica in the same statement, reads a stopped replica's task as failed, and drains on shutdown), taskwiring (assembles the Tasks extension for the facade: the `tasks:` section, middleware, tasks/* methods and their caller, the run and call-task Sources), servercaps (the capabilities the MCP server declares, the Tasks extension among them, taken out of the facade for its size budget), exportlibrary (platform.export's scope=/scope_id= for a "resources" output, #2080: the library, its check, and its static read for validate, kept out of scriptrun for its size budget), retention (the daily sweeps over deleted portal items, archived memory, orphaned producer records, superseded GraphQL embeddings and expired call tasks, each under its own advisory lock, #1904; it also runs assetbucket, the pass that names the portal bucket on asset and version rows an early release wrote with none, ahead of the purge, #1931), ... — moved out of the public surface by #894 and #1076)
│   ├── portal/                     # Portal seams built only by pkg/portal, extracted by #1121: callapi/ (the caller's own call catalog), portaldomain/ (domain types, store contracts, validation, and BuildShare — the one share constructor, also called by the asset toolkit's share action; aliased back so portal.Asset etc. are unchanged), portalstore/ (PostgreSQL asset/share/collection stores + ranked search), portalversions/ (version history store), contenturl/ (the expiring signed URL that reads one asset version without a session, #1848), portalnoop/ (no-database stores), access/ (the authorization core + the User principal), feedbackapi/ (threads, activity, worklists, sign-off, validation, capture-as-insight), assetrefs/ + assetrefstore/ (the managed resources an asset's content references: the URL, the serve-time rewrite, the serving route, the declaration check, and their Postgres store), contentrefs/ (the lexical reading of a document body for references: the ones it names, the ones its asset does not declare, and the ones it uses as a link target, which a write refuses, #1875), portalperm/ (the route-to-area table the persona gate refuses a portal request by, #2225), reachstore/ (a person's reach in SQL, #2500: owned on either identifier, or named by an active share to their id, address or persona on the row or a live collection holding it; the tag and author facets and per-row share permissions over it, held to access.CanViewAsset by a RealDB test), reachapi/ (the search and facet routes over the reach and the per-row description the listings attach, #2500), accessreq/ (a request for access to an item a person cannot open, the owner's answer and the access_requests settings, #2090), generalfeedback/ (who hears about a General feedback post: the general_feedback settings, their seed from portal.feedback.standalone_recipients or the administrator persona, the people and channels they resolve to, #2603), externalfiles/ (External files, #2290: whether a user library belongs to a person whose roles resolve to an external persona, the claims a persona's view or manage level adds, and GET /api/v1/resources/external-folders), the asset organization seams (#2511), each mounted through pkg/portal Deps' Mounts hook by internal/httpserver/assetwire: assetstatus/ (an asset's Draft/Published/Deprecated status, its history of status and verification changes, and the Gate every seam resolves an asset through, #2502), assetverify/ (the Verified badge, the verify_assets permission, the once-only reminder pass a week before expiry, #2503), assetlinks/ (mcp:asset:<id> links recorded on every version write by a version-store wrapper, and Linked from read through the caller's reach, #2432), assetsimilar/ (the one embedding-closeness rule, NearDuplicate, for save-time similar_assets and duplicate groups, #2508, #2509), assetbulk/ (bulk actions acting through each asset's own route, #2507), assettags/ (tag suggestions, admin rename and merge, #2508), library/ and libraryapi/ (favorites, recents, Home's reads, Trash and restore, Unused and Possible duplicates, #2504, #2509), collectionsweep/ (removes each collection item its owner cannot open, run with the retention sweeps under its own lock, a grant through another collection's share followed to a holder who can open the asset without one, each removal recorded in portal_collection_item_removals, #2752), plus portalpurge/ (the hard purge of soft-deleted assets, collections, threads and knowledge pages past portal.deleted_retention_days, objects first, #1904), publicviewer/ (embedded public share templates + CSP), viewerlimit/, sharecache/
│   ├── site/                       # Static sites and browser pages (#2517, #2518, #2559): the site/release/domain/grant/job record (siteconfig/ = the `sites:` section and the run-time settings over it), sitestore/ (Postgres), sitesvc/ (publish, promote, rollback, domains, who may do what, release comparison, background publish and copy), sitetool/ (manage_site), sitegw/ (the Host-routing gateway outside the mux: file serving and cache, an application's page origin and the viewer handoff, the sign-in and per-request access check on a site's own address), sitecrawl/ (the migration crawl), siteenv/ (an environment's status, rename and remove, the new-site name check, a file read for the viewer and the rule that an agent's move of an environment people use waits on a person, #2648), sitestatus/ (the offline and redirect rules), sitetraffic/ (each site's traffic: the per-replica tally, the once-a-minute flush into shared rows and their reads, #2647), siteaddr/ (every hostname the deployment answers on for the ingress rules, with a site domain's role, #2687), siteshared/ (the environments a share to a person's verified email or persona opens, for Home's Sites shared with you, external people included, #2718), sitetypecheck/ (a release type-checked after publish when its _build.json sets typecheck, #2793: the pinned @typescript/typescript-wasip1-wasm compiler run under wazero in a `typecheck-worker` process under a memory limit, dependency types from the lockfile verified by integrity and cached in the portal bucket, one check at a time per replica from site_typechecks, each environment's .tsbuildinfo kept; queued by the publish hook sitesvc calls, and again on request), sitewire/; a site environment's primary domain and its redirect domains (#2687) are siteenv's, answered by sitegw; internal/httpserver/sitehttp mounts it and serves the portal's Sites routes (typecheckhttp/ a release's type checks, #2793), and internal/httpserver/siteportalwire assembles those routes from the platform
│   └── server/                     # Server factory (server.go)
├── configs/                        # Example configurations
│   └── platform.yaml
├── go.mod
├── LICENSE
└── README.md

Key Dependencies

  • github.com/modelcontextprotocol/go-sdk - Official MCP SDK for Go (same as txn2 MCP ecosystem)
  • github.com/txn2/mcp-trino - Trino MCP toolkit
  • github.com/txn2/mcp-s3 - S3 MCP toolkit
  • golang.org/x/crypto - Cryptographic utilities (bcrypt for OAuth)
  • gopkg.in/yaml.v3 - YAML configuration parsing

Building and Running

# Build
go build -o mcp-data-platform ./cmd/mcp-data-platform

# Run with stdio transport (default)
./mcp-data-platform

# Run with config file
./mcp-data-platform --config configs/platform.yaml

# Run with HTTP transport (serves both SSE and Streamable HTTP)
./mcp-data-platform --transport http --address :8080

Configuration Reference

Configuration is loaded from YAML with environment variable expansion (${VAR_NAME}).

Server Configuration

server:
  name: mcp-data-platform
  transport: stdio          # stdio, http
  address: ":8080"

Authentication

auth:
  oidc:
    enabled: true
    issuer: "https://auth.example.com/realms/platform"
    client_id: "mcp-data-platform"
    audience: "mcp-data-platform"
    role_claim_path: "realm_access.roles"
    role_prefix: "dp_"
  api_keys:
    enabled: true
    keys:
      - key: "${API_KEY_ADMIN}"
        name: "admin"
        roles: ["admin"]

Personas

personas:
  analyst:
    display_name: "Data Analyst"
    roles: ["analyst", "data_engineer"]
    tools:
      # Prefer "*" with a targeted deny. An enumerated allow-list silently
      # loses every tool a later upgrade adds, and it drops the tools others
      # depend on: the search-first gate refuses trino_query until "search" is
      # called, and "fetch" is the only tool that dereferences a search result's
      # reference. See docs/personas/overview.md#some-tools-are-a-unit.
      allow: ["*"]
      deny: ["*_delete_*"]
    connections:
      allow: ["*"]
    context:
      description_prefix: "You are helping a data analyst."
  admin:
    display_name: "Administrator"
    roles: ["admin"]
    tools:
      allow: ["*"]
    connections:
      allow: ["*"]

PersonasConfig.Definitions is an inline map (pkg/platform/config.go), so persona names go directly under personas: — not under a definitions: key. Connections are deny-by-default (pkg/persona/filter.go), so every persona needs its own connections: block; personas.default_persona was removed and a config that still sets it is refused at startup (pkg/platform/config.go).

Semantic Layer

With a database, the platform catalog (pkg/catalog, internal/platform/catalogstore, docs/server/catalog.md) is the semantic provider and needs no semantic: block; noop turns the layer off. A configuration that still names DataHub starts (pkg/platform/config_datahub.go, #2124): the DataHub toolkits.datahub names is imported into the catalog after the first catalog scan, once (internal/platform/catalogimport, Admin > Catalog > Import), nothing else of DataHub runs, and the DataHub settings are accepted, strict parsing included, and logged as deprecated_key; the next release refuses them.

semantic:
  provider: noop                   # Optional: turn the semantic layer off

enrichment:
  trino_semantic_enrichment: true
  unwrap_json: true                # Auto-unwrap single-row VARCHAR-of-JSON results (default: true)
  column_context_filtering: true   # Only enrich columns referenced in SQL (default: true)
  lineage_inheritance: true        # Issue #2130: columns borrow upstream curation along catalog lineage (default: true)
  semantic_fallback: false         # Issue #444: fall back to similarity search on a lookup miss (default: false)
  semantic_fallback_top_k: 1       # Suggested matches per miss (default: 1, clamped to [1,10])

Sites and Pages

Static sites and browser pages on hostnames other than the platform's own (#2517, #2518). docs/server/sites.md.

sites:
  pages_domain: pages.example.net   # <app>.<domain> and <site>.<domain>; the seed until Admin > Settings > Sites is saved
  traffic:                          # each site's traffic and latency, recorded by the platform (#2647)
    enabled: true                   # default on
    minute_retention: 24h
    hour_retention: 2160h           # 90 days
  typecheck:                        # type checks a release's _build.json asks for (#2793)
    enabled: true                   # default on; needs the portal bucket
    memory_limit: 0                 # bytes one check's compiler may hold (default a quarter of the container's limit, 512 MiB to 3 GiB, #2828)
    timeout: 5m
    registry: ""                    # default the npm registry
    dir: ""                         # writable directory a check works in; default the temp directory
    compile_cache: false            # keep the compiled compiler (about 177 MiB) in dir between checks; compiling it is minutes at a fractional CPU limit (#2833)

An agent's promote, rollback or public domain on an environment other than dev waits on a person (#2643, internal/site/siteenv): elicitation, or APPROVAL_REQUIRED and a request decided only in the portal, unless an administrator marked the environment agents_may_promote.

Managed Resources

resources:
  managed:
    enabled: true             # auto-enabled when database is available; set false to disable
    uri_scheme: "mcp"         # URI prefix for resource URIs (default: "mcp")
    s3_connection: "primary"  # name of S3 toolkit instance for blob storage
    s3_bucket: "resources"    # S3 bucket for uploaded files
    extract:                  # manage_resource extract limits (#1879); independent of max_upload_bytes
      max_member_bytes: 2147483648  # default 2 GiB
      max_total_bytes: 4294967296   # default 4 GiB
      max_members: 100000
      max_ratio: 500

Export to Asset

portal:
  export:
    enabled: true             # auto-enabled when portal + trino are configured
    max_rows: 100000          # hard row cap per export
    max_bytes: 104857600      # hard byte cap (100 MB)
    default_timeout: "5m"     # default query timeout
    max_timeout: "10m"        # maximum allowed timeout

Audit Logging

Both enabled and log_tool_calls are *bool defaulting to on when a database is available; with no audit: block a DB-backed deployment logs tool calls out of the box. Set enabled: false to disable audit entirely, or log_tool_calls: false to keep audit on but skip per-tool-call rows.

audit:
  enabled: false          # opt out of audit logging
  log_tool_calls: false   # keep audit on but skip per-tool-call rows
  retention_days: 90

database:
  dsn: "${DATABASE_URL}"

Email Notifications

Enabled by default when a database is available (*bool, nil = enabled). The YAML controls only enqueue/delivery; SMTP host/credentials are admin-configured at runtime (portal Admin > Settings or /api/v1/admin/settings/smtp, password encrypted via FieldEncryptor, write-only in the API).

notifications:
  enabled: false        # opt out of email notifications
  digest_hour_utc: 13   # UTC hour (0-23) daily digests are sent

Call Catalog

Nothing here turns the catalog on: it is written from the audit pipeline and exists wherever audit does. What a deployment chooses is how long a call that came to nothing is kept, and whose calls are worth keeping at all. A record an asset or a capture cites, one that was promoted or declined, and one another session re-ran are evidence and are never swept, whatever their age.

calls:
  retention_days: 90   # how long an UNUSED call record is kept (default 90)
  exclude_personas:    # personas whose calls are machinery: audited, not cataloged
    - ingest-service

An automated system driving ingestion through the same tools people use writes a record per fetch that nobody will re-run, and every one of them is embedded (#1614). Naming its persona stops the record being written, and sweeps the ones written before it was named, evidence clauses intact, and withholds the mcp:call:<id> reference such a call would otherwise be told to cite. The audit row, its retention and the API gateway's metrics are untouched, so what an automated system did stays fully visible. Persona is the discriminator because it is the layer an operator already assigns per API key. Empty catalogs every call.

The same rule is a setting on the persona itself (#1980): service_account: true in a file persona, the persona_definitions.service_account column for a database one, and the "Service account" checkbox in the portal persona editor. calls.exclude_personas stays as its file-config form and both apply. The exclusion reads the live persona registry (callrecord.ServiceAccounts) on every call and sweep, never a startup snapshot, and saving a persona marked through the admin API asks the catalog for a sweep at once (PostgresStore.RequestSweep). The sweep deletes in batches of 5,000, each its own statement, and deletes the removed records' index_jobs units of kind calls in the same statement. The admin Indexing page lists the Top callers (GET /api/v1/admin/calls/top-callers, counts cached five minutes) so an operator can see one automated caller holding most of the catalog.

A managed script run's calls are not cataloged either, and that one takes no knob (#1624). The scheduler is the automated system, a run is by construction the re-run, and a run presents its author's persona, so exclude_personas cannot name it: the rule is keyed on the audit event's source being script. The calls are audited in full, the run is handed no mcp:call:<id> reference, and the sweep's third arm (user_id LIKE 'script:%') clears the rows written before this existed. A person's call in the same persona is cataloged as before.

Managed Scripts

The portal names this section Automations (/portal/automations and /portal/admin/automations; the old /portal/scripts paths redirect with the rest of the path intact, #1912). A script is the one kind of automation that exists: the MCP tools, the REST API under /api/v1/*/scripts, mcp:script: references, script: principals, tables, metrics and config keys keep the script name.

Authoring needs no configuration and is available wherever there is a database. A saved script runs: run_script and a schedule execute the latest saved version, presenting the roles its author held at the save, and the persona filter authorizes every call at run time. A script is personal: its owner sees it, edits it, runs it, and schedules it, administrators do all four on every script, and an administrator can move a script to another owner (which re-captures the run identity from the administrator making the move). Its definition -- source and version history, without the authors' roles -- is readable by everyone signed in (#1866), and on the portal so is how it is going -- its cadence and each run's status, timing, cause and error (#1994); acting on it, and what a run was given, printed and wrote, stay the owner's and an administrator's. The knobs are how long the record of a run is kept, whether this replica executes runs at all, and which bucket destinations a script's output may be delivered to.

scripts:
  run_retention_days: 365   # how long a FINISHED run is kept (default 365)
  worker:
    enabled: false          # this replica enqueues runs but never claims them
    concurrency: adaptive   # default; claims while memory/CPU have headroom; a number fixes it, 1 is serial
    run_timeout: 15m        # wall-clock cap for one platform run (lease = timeout + 5m)
    max_run_memory: 50%     # default; what one run may hold: a size, a share of the memory limit, or unlimited
    max_reclaims: 2         # default; take-overs from a dead worker before the run is failed
  sql:
    max_timeout_seconds: 300  # default and maximum; the most a statement's timeout_seconds may be
  destinations:             # named bucket destinations platform.export may write to
    - name: acme-drop
      connection: acme-s3
      bucket: acme-exports
      prefix: weekly

A script carries one JSON object of state between runs (run.state in, platform.save_state out, 64 KiB): applied when the run succeeds, in the transaction that marks it so, under a compare-and-set on the revision the run read at creation; a failed run leaves it alone, the loser of two runs that read one revision fails naming the winner, and the owner or an administrator resets it with manage_script command=state or on the script's page.

A run still pending or running is never swept. The default is far longer than the notification queue's because a scheduled script's run history is its refresh history — product surface, not queue residue. worker.concurrency is adaptive by default (#1843): a replica claims another run only while its memory and CPU are under max_memory_percent/max_cpu_percent of the container's limits, between min_concurrency and max_concurrency, and stops and requeues its newest run past shed_memory_percent, failing the run instead when it is the only one executing (#1861); see docs/scripts/running.md. A run is measured at every host call -- walked whenever the process's heap growth since the last walk could cross the budget, and once more when it ends (#1867) -- and fails with cause memory past max_run_memory; a run whose worker died is taken over at most max_reclaims times, then failed with cause worker_lost (#1860). A failed run records its cause (script, upstream, memory, worker_lost, platform, state_conflict) and whether it is retryable; the platform never re-executes a run on its own (#1859). worker.enabled is a *bool defaulting to on: one process serves and executes unless a deployment splits them, and a worker-off replica still registers run_script, enqueues, and waits on the result a worker deployment produces. A destination is resolved by name at run time, so repointing one here takes effect on the next run; the portal is built in and never declared. See docs/scripts/running.md and docs/scripts/security.md.

Thumbnails

The platform draws every asset, resource and collection tile itself, in a headless Chrome (chromedp/headless-shell, pinned by digest) that runs as a second container in the platform's pod (#1787). Enabled by default (*bool); the default renderer address is the container beside it, so a deployment sets nothing.

thumbnails:
  enabled: false                        # opt out; stored tiles keep serving
  renderer_url: "http://127.0.0.1:9222" # default

The platform dials the renderer and answers every request a page makes (its own routes in-process, public URLs through internal/egressguard); the renderer is never given an address to call. With no renderer answering, tiles keep their content-type icons. A document that cannot be drawn is recorded (thumbnail_failure) and held until it changes or its owner clears the tile. Every claim charges an attempt (thumbnail_attempts); an attempt that does not finish (renderer gone mid-render, stored file unreadable) holds the row back with backoff and, at max_attempts, records it as not drawable (#1868). Pages load with their animation timeline stopped and are settled before capture. concurrency, render_timeout, batch, lease, poll, max_attempts and retry_backoff pace the worker. max_source_bytes (default 1 MB) and large_source_bytes (default 32 MB, PDF/CSV/TSV) bound the document a tile is drawn from; a file past its bound is never claimed and every asset and resource read reports thumbnail_skipped: "over_source_limit" with thumbnail_source_limit (#2072). make dev runs the renderer as the renderer service in dev/docker-compose.yml.

Progress, Client Logging, Icons & Elicitation

All four are enabled by default (*bool field, nil = enabled); set enabled: false to opt out. No block is needed to turn them on.

progress:
  enabled: false        # opt out of Trino query progress notifications

client_logging:
  enabled: false        # opt out of server-to-client log messages

icons:
  enabled: false        # opt out of icon injection middleware

elicitation:
  enabled: false        # opt out of all elicitation (also disables the two below)
  cost_estimation:
    enabled: true       # opt IN: off by default (#2586)
    row_threshold: 1000000
  pii_consent:
    enabled: false      # opt out of PII-access consent prompts

Elicitation is user-facing: with no config at all, PII-consent prompts fire out of the box; the cost prompt is off unless cost_estimation.enabled: true (#2586), and when on it compares the rows a query is estimated to RETURN, capped by its row limit, with row_threshold. A prompt answered with no answer is prompt_unanswered, not user_declined, and the call that issued it is audited as input_required, never a success, and kept out of provenance and the call catalog. The prompts are the Trino toolkit's consent layer (ConsentMiddleware), placed in the tools/call chain after the error contract (mwConsent): a 2026-07-28 client gets them as input requests (resultType: "input_required", stamped by MCPResultTypeMiddleware) and retries with its answers, an older client is asked in band, which only a stateful deployment can do (a stateless server sends no request to a client). Settings are per Trino connection; one added at run time with no elicitation block takes the default connection's (#2052).

Core Interfaces

SemanticMetadataProvider

type Provider interface {
    Name() string
    GetTableContext(ctx context.Context, table TableIdentifier) (*TableContext, error)
    GetColumnContext(ctx context.Context, column ColumnIdentifier) (*ColumnContext, error)
    GetColumnsContext(ctx context.Context, table TableIdentifier) (map[string]*ColumnContext, error)
    GetLineage(ctx context.Context, table TableIdentifier, direction LineageDirection, maxDepth int) (*LineageInfo, error)
    GetGlossaryTerm(ctx context.Context, urn string) (*GlossaryTerm, error)
    SearchTables(ctx context.Context, filter SearchFilter) ([]TableSearchResult, error)
    Close() error
}

QueryExecutionProvider

type Provider interface {
    Name() string
    ResolveTable(ctx context.Context, urn string) (*TableIdentifier, error)
    GetTableAvailability(ctx context.Context, urn string) (*TableAvailability, error)
    GetQueryExamples(ctx context.Context, urn string) ([]QueryExample, error)
    GetExecutionContext(ctx context.Context, urns []string) (*ExecutionContext, error)
    GetTableSchema(ctx context.Context, table TableIdentifier) (*TableSchema, error)
    Close() error
}

Resource Store

type Store interface {
    Insert(ctx context.Context, r Resource) error
    Get(ctx context.Context, id string) (*Resource, error)
    GetByURI(ctx context.Context, uri string) (*Resource, error)
    List(ctx context.Context, filter Filter) ([]Resource, int, error)
    Update(ctx context.Context, id string, u Update) error
    Delete(ctx context.Context, id string) error
}

Toolkit Interface

type Toolkit interface {
    Kind() string
    Name() string
    RegisterTools(server *mcp.Server)
    Tools() []string
    SetSemanticProvider(provider semantic.Provider)
    SetQueryProvider(provider query.Provider)
    Close() error
}

MCP Protocol Middleware

Request processing flows through MCP protocol-level middleware registered via server.AddReceivingMiddleware().

IMPORTANT: AddReceivingMiddleware wraps the current handler — each call makes the new middleware the outermost layer. The LAST middleware added runs FIRST. In finalizeSetup(), middleware is added innermost-first:

Execution order (outermost to innermost): -1. mcpobs.Middleware (internal/mcpobs, #1889) - Outermost: a server span named by the method and mcp_requests_total{method,status} / mcp_request_duration_seconds for every method other than tools/call (tools/list, resources/read, prompts/get, ...). It is outer to the result-type layer and the list decorators so its duration covers them. A tools/call passes through to the observers at 4 and 5. The same package holds the trace-context and protocol-version helpers the tools/call tracer reads (TraceContext, ProtocolVersion, the Attr* convention keys). The HTTP request a message arrives in has its own server span and http_server_request_duration_seconds{route,method,status_class} from internal/httpobs, the outermost layer of the listener, under which this span nests. 0. MCPResultTypeMiddleware - Types every tools/call, prompts/get and resources/read result with the resultType the negotiated protocol revision requires (#1382, #1383). The SDK stamps only the result its own handler returns; a gate's refusal, the error contract's rebuild and the managed resource read are built by the layers below and are typed here. The list decorators (icons, descriptions, visibility, session-handle and purpose schemas, MCPOutputSchemaMiddleware opening every advertised output schema to the platform's keys (#1381)) sit between it and MCPAppsMetadataMiddleware.

  1. MCPAppsMetadataMiddleware - Injects _meta.ui into tools/list responses
  2. MCPToolCallMiddleware - Authenticates user, authorizes tool access, creates PlatformContext
  3. MCPWorkflowGateMiddleware - Search-first hard gate (#787): refuses query tools until search is called in the session, short-circuiting with a SEARCH_REQUIRED error before the handler runs. Default-on; disabled by workflow.require_search: false.
    • Schema gate (internal/platform/schemagate, #2386, #2387), directly inner to it: refuses a SQL statement (trino_query, trino_execute, trino_export) against a table whose columns the session has not read, with SCHEMA_REQUIRED carrying the table's schema; adds the columns of a failed statement's tables to a column or type error. Default-on; the refusal is disabled by workflow.require_schema: false.
  4. MCPAuditMiddleware - Logs tool calls asynchronously (reads PlatformContext from ctx)
  5. MCPSemanticEnrichmentMiddleware - Adds cross-service context to results

All middleware intercepts tools/call requests at the MCP protocol level. MCPToolCallMiddleware must be outer to MCPAuditMiddleware so that PlatformContext (set via context.WithValue) is present in the ctx that MCPAuditMiddleware receives. MCPWorkflowGateMiddleware is inner to MCPToolCallMiddleware (needs PlatformContext and the recorded tool call) and outer to Audit/enrichment so a gated call never reaches them, mirroring the session gate.

Testing

# Run all tests with race detection
go test -race ./...

# Run linter
golangci-lint run ./...

# Run security scan
gosec ./...

# Run specific package tests
go test -race ./pkg/platform/...

# Run dead code analysis (informational)
make dead-code

# Run mutation testing (informational)
make mutate

AI Verification Requirements

When AI (Claude Code or similar) contributes code, the following additional checks apply:

  1. No Tautological Tests: Tests must verify behavior, not struct field assignment. A test that sets x.Field = "value" then asserts x.Field == "value" tests the Go compiler, not the application. Delete such tests on sight.
  2. Integration Tests for Multi-Component Features: Unit tests alone are insufficient for features that span middleware chains, provider pipelines, or context propagation. Require an integration test that wires up the real assembled system (e.g., mcp.Server + AddReceivingMiddleware + in-memory transport + real CallTool).
  3. Mutation Survival Review: After adding tests, run make mutate on the affected packages. Surviving mutants in security-critical paths (auth, audit, encryption) must be addressed with targeted tests. Informational mutants in logging or formatting may be deferred.
  4. Dead Code Audit: make verify prints deadcode's report (make dead-code) and does not fail on it. Reading it is a human step: functions reported as dead are deleted or moved to test files, and public API functions may be false positives (library exports), ignored with justification.
  5. No Vaporware: Every database migration table must have corresponding DML (INSERT/SELECT/UPDATE/DELETE) in non-test Go source code. Every Go package under pkg/ must be imported by at least one non-test file. Every interface with a noop implementation must also have a real (non-noop) implementation. These invariants are enforced by three tests:

    • TestMigrationTablesHaveConsumers (pkg/database/migrate/) — no orphaned migration tables
    • TestNoDeadPackages (test/structure/verify_test.go) — no unimported packages
    • TestNoopOnlyInterfaces (test/structure/verify_test.go) — no interfaces where the only implementation is a noop

    Do not create migrations, packages, or interfaces "for future use" — code that isn't wired into the running application is dead code regardless of whether it has its own unit tests.

    The Noop Loophole: A noop implementation satisfies compile checks, passes tests (returns nil), gets imported (not dead), and wires into the platform — yet does nothing. This is the most insidious form of vaporware because every automated gate reports green. TestNoopOnlyInterfaces closes this loophole by requiring that any interface with a noop also has a real implementation that performs actual work.

  6. Dependency-First Verification: Before implementing features that depend on external system capabilities (writing to DataHub, calling a third-party API, etc.), VERIFY that the dependency actually supports the required operations. If the upstream library lacks the needed functionality, that gap must be surfaced IMMEDIATELY — do not build scaffolding (handlers, stores, migrations, admin APIs) around a capability that doesn't exist. The correct order is:

    1. Verify the external dependency supports the required operations
    2. Implement or extend the client for those operations
    3. Build the feature on top of the working client

    Building top-down from handlers to stores to admin APIs while leaving the actual external integration as a noop is prohibited. If the external system can't do what the feature requires, stop and report the gap instead of building theater around it.

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.