{"modulePath":"github.com/codefit-cli/codefit","version":"v0.2.9","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package mcp\n\nPackage mcp implements the MCP server mode: a thin, stateless adapter that exposes the same core sensors as MCP tools (PRD section 10). It reimplements no audit logic — every tool call translates to the same engine the CLI uses — and relies on prompt caching to neutralize the stateless overhead.\n\nStatus: BUILT. NewServer registers the tool set and Serve runs it over the stdio transport; every tool is a thin adapter onto a core handler. The HTTP/SSE transport is the one part still unbuilt — \\`mcp serve --port\\` returns an explicit error rather than falling back silently.\n\n## Constants\n\n```go\nconst (\n\tScopeModeFull    = \"full\"\n\tScopeModePartial = \"partial\"\n)\n```\nThe two scan modes. A response ALWAYS carries one of them: the field's presence is not conditional, so a consumer never has to infer the mode from an absence.\n\n```go\nconst ResponseBudgetBytes = 40_000\n```\nResponseBudgetBytes is the byte budget codefit-scan-all declares for its own serialized response.\n\nWhat is MEASURED (roadmap P0-4): a bisection run against a real MCP client (Claude Code, 2026-08-09), driving the v0.2.6 binary over stdio with controlled-size responses cut from trimmed copies of a real 317-file project. The real ceiling was bracketed, not pinpointed:\n\n\t64 097 bytes  ACCEPTED   \u003c- largest observed acceptance\n\t74 195 bytes  REJECTED   \"exceeds maximum allowed tokens\"\n\n40 000 was CHOSEN inside that bracket, not measured directly: 62% of the largest observed acceptance (64 097), leaving room for roughly a 60% increase in token density before approaching the rejected end (74 195), and it matches an earlier, independent data point — a 40 282-byte response that is known to have arrived (2026-08-04, before this bisection existed).\n\nThe assumption this number rests on, stated plainly: the client's limit is in TOKENS; this budget counts BYTES. The bytes-per-token ratio is content-dependent (identifiers, hex digests and deep paths run denser than prose), so the margin above is NOT fixed — a byte count under budget can still cross a token ceiling the same client would reject. And the measurement is of ONE client, ONE date, ONE content shape: other MCP clients (Cursor, VSCode, OpenCode) have their own limits, unmeasured here.\n\nMeasured consequence of moving this number down (2026-08-09, same real project, fresh baseline): payload 39 962 bytes, 19 of 174 endpoints withheld (5 actionable, 14 frontier\\_pending) — at the old 60 000 this same project fit entirely with 0 withheld. Real mid-sized projects now see a non-zero withheld count where they previously did not; each bucket's \\`count\\` stays the complete number and codefit-scan-endpoint still fetches full detail on request (ADR 0054), but this is a user-visible behaviour change, not a free tightening.\n\nSee ADR 0062 for the full record, including what this number does NOT fix: a byte budget cannot guarantee a token limit. The structural answer — a hard cap on entries per bucket, so response size stops being a function of project size — is roadmap P0-4's declared follow-up, not this change.\n\nThe budget is DECLARED in the response (see BudgetBlock) and enforced by withholding the lowest-ranked endpoints, never by truncating the payload: a clipped response that reads like a complete one is the one outcome forbidden (ADR 0054, same principle as ADR 0048).\n\n## Functions\n\n```go\nfunc NewServer() *mcpsdk.Server\n```\nNewServer builds the codefit MCP server with its tools registered. Each tool is a THIN adapter: it hands the SDK's typed request to the core handler that already exists and is tested, and returns the core's result as structured output. No audit logic lives here — the MCP layer only connects the protocol to the engine (PRD §15). The server is stateless: every tool call is independent and carries everything it needs.\n\n```go\nfunc Serve(ctx context.Context) error\n```\nServe runs the codefit MCP server over the stdio transport until ctx is cancelled. (HTTP/SSE is deferred; the SDK abstracts the transport, so it is added later without a refactor.)\n\n```go\nfunc SupportedLanguageNames() []string\n```\nSupportedLanguageNames returns the canonical, deduplicated, sorted set of language names codefit-scan-all can resolve a security provider for — DERIVED from registry.ExposedForSecurity(), never a hand-written literal. This is the single source the nothing-measurable error message reads (D4/D5): a language and its aliases (ts/tsx) collapse to one canonical name here.\n\n## Types\n\n```go\ntype ActionableSection struct {\n\tCount    int    `json:\"count\"`\n\tWithheld int    `json:\"withheld\"`\n\tNote     string `json:\"note,omitempty\"`\n\t// Endpoints is the rendered prefix of the ranked list: hardest gap kind first\n\t// (affirmed → access → exposure → efficiency), then by certain-concern count.\n\tEndpoints []report.ActionableEndpoint `json:\"endpoints,omitempty\"`\n}\n```\nActionableSection declares the endpoints codefit resolved locally AND found a gap in — the ones the agent acts on. They are NAMED with what it takes to rank them (counts, categories, gap kinds, best certainty, whether an affirmation is present) and their deterministic concerns in full; the surface question and signals text is one codefit-scan-endpoint call away.\n\nCount is the COMPLETE number codefit classified as actionable and never the number rendered — Withheld accounts for the difference. Reading Count off len(Endpoints) is exactly the bug this section's shape exists to make impossible.\n\n```go\ntype BaselineAcceptRequest struct {\n\tRoot         string   `json:\"root\"`\n\tFingerprints []string `json:\"fingerprints\"`\n\tReason       string   `json:\"reason\"`\n}\n```\nBaselineAcceptRequest marks baseline items as acknowledged by a human (a false positive or accepted debt). reason is mandatory. SAFETY: the agent must call this ONLY when the human decided so — codefit records by:\"human\" but cannot verify it; the skill enforces the discipline.\n\n```go\ntype BaselineAcceptResponse struct {\n\tAccepted []string `json:\"accepted\"`\n\tNote     string   `json:\"note\"`\n}\n```\nBaselineAcceptResponse reports which fingerprints were acknowledged.\n\n```go\nfunc HandleBaselineAccept(req BaselineAcceptRequest) (BaselineAcceptResponse, error)\n```\nHandleBaselineAccept records a human's decision to accept items. It only touches the baseline file.\n\n```go\ntype BaselineDelta struct {\n\tNew               int        `json:\"new\"`\n\tChanged           int        `json:\"changed\"`\n\tKnown             int        `json:\"known\"`\n\tAcknowledged      int        `json:\"acknowledged\"`\n\tGone              int        `json:\"gone\"`\n\tAffirmationsShown int        `json:\"affirmations_shown\"`\n\tGoneCandidates    []GoneItem `json:\"gone_candidates,omitempty\"`\n\tNote              string     `json:\"note\"`\n}\n```\nBaselineDelta is scan-all's account of how the current scan compares to the committed baseline. The agent acts on new + changed (and unaccepted affirmations); known surface is silenced but counted.\n\n```go\ntype BaselineListRequest struct {\n\tRoot     string `json:\"root\"`\n\tLanguage string `json:\"language,omitempty\"`\n\tFilter   string `json:\"filter,omitempty\"`\n}\n```\nBaselineListRequest reads the current baseline so the agent can reference items in accept/prune WITHOUT reading the raw .codefit-baseline file. Filter is \"\" (all), \"known\" (not yet accepted), or \"acknowledged\". Language is accepted for tool uniformity but unused — listing reads the file, it does not scan code.\n\n```go\ntype BaselineListResponse struct {\n\tItems        []baseline.Entry       `json:\"items\"`\n\tCount        int                    `json:\"count\"`\n\tAuthzHelpers []baseline.AuthzHelper `json:\"authz_helpers,omitempty\"`\n\tNote         string                 `json:\"note\"`\n}\n```\nBaselineListResponse is the projected baseline: per item just fp+file+category+ state (+reason/date if acknowledged), small enough not to truncate. AuthzHelpers lists the project's registered custom authz helpers (read-only visibility) so the agent can see — and propose unregistering — them without reading the file.\n\n```go\nfunc HandleBaselineList(req BaselineListRequest) (BaselineListResponse, error)\n```\nHandleBaselineList returns the baseline entries. A missing baseline is NOT an error: it returns an empty list with a note pointing to scan-all. Read-only.\n\n```go\ntype BaselinePruneRequest struct {\n\tRoot         string   `json:\"root\"`\n\tLanguage     string   `json:\"language\"`\n\tFingerprints []string `json:\"fingerprints,omitempty\"`\n}\n```\nBaselinePruneRequest removes baseline items that no longer exist in the code (gone). With Fingerprints set it prunes only those (if confirmed gone); empty prunes all confirmed-gone items.\n\n```go\ntype BaselinePruneResponse struct {\n\tPruned []string `json:\"pruned\"`\n\tNote   string   `json:\"note\"`\n}\n```\nBaselinePruneResponse reports which fingerprints were pruned.\n\n```go\nfunc HandleBaselinePrune(req BaselinePruneRequest) (BaselinePruneResponse, error)\n```\nHandleBaselinePrune re-scans to confirm which baseline items are gone, then removes them. Stateless: it recomputes the current surface; it never edits code.\n\n```go\ntype BaselineRegisterAuthzHelperRequest struct {\n\tRoot       string `json:\"root\"`\n\tLanguage   string `json:\"language\"`\n\tHelperName string `json:\"helper_name\"`\n\tReason     string `json:\"reason\"`\n}\n```\nBaselineRegisterAuthzHelperRequest registers a project-specific authz helper so codefit recognizes it on later scans (known\\_authz\\_detected reflects it). reason is mandatory. SAFETY: registering silences the AUTHZ gap on EVERY item that calls the helper — far more reach than accepting one item. The agent must call this ONLY when the human approved it; codefit records by:\"human\" but cannot verify it (the skill enforces the discipline). It does NOT clear the IDOR/ownership gap (ADR 0013, ADR 0006 amended).\n\n```go\ntype BaselineRegisterAuthzHelperResponse struct {\n\tRegistered bool   `json:\"registered\"`\n\tNote       string `json:\"note\"`\n}\n```\nBaselineRegisterAuthzHelperResponse reports the outcome.\n\n```go\nfunc HandleBaselineRegisterAuthzHelper(req BaselineRegisterAuthzHelperRequest) (BaselineRegisterAuthzHelperResponse, error)\n```\nHandleBaselineRegisterAuthzHelper records a human-approved custom authz helper in the baseline. It only touches the baseline file.\n\n```go\ntype BaselineUnregisterAuthzHelperRequest struct {\n\tRoot       string `json:\"root\"`\n\tLanguage   string `json:\"language\"`\n\tHelperName string `json:\"helper_name\"`\n}\n```\nBaselineUnregisterAuthzHelperRequest reverses a registration (the developer's decision is always reversible). The next scan stops recognizing the helper.\n\n```go\ntype BaselineUnregisterAuthzHelperResponse struct {\n\tUnregistered bool   `json:\"unregistered\"`\n\tNote         string `json:\"note\"`\n}\n```\nBaselineUnregisterAuthzHelperResponse reports the outcome.\n\n```go\nfunc HandleBaselineUnregisterAuthzHelper(req BaselineUnregisterAuthzHelperRequest) (BaselineUnregisterAuthzHelperResponse, error)\n```\nHandleBaselineUnregisterAuthzHelper removes a registered helper. It only touches the baseline file.\n\n```go\ntype BudgetBlock struct {\n\tBytes    int    `json:\"bytes\"`\n\tWithheld int    `json:\"withheld\"`\n\tOrdering string `json:\"ordering\"`\n\tNote     string `json:\"note\"`\n}\n```\nBudgetBlock is scan-all's account of its own size. codefit's primary tool has to RETURN: a response an MCP client refuses is worth less than a smaller one that arrives. So the response declares the budget it is written to, and when the endpoint list does not fit it says exactly how many endpoints it is not showing and on what ordering it kept the ones it shows.\n\nWithheld=0 still carries a Note, on purpose. \"No mention of truncation\" and \"nothing was truncated\" must not be the same bytes on the wire: that ambiguity is how a clipped response comes to read like a complete one (ADR 0048).\n\n```go\ntype CheckCVEsRequest struct {\n\tRoot string `json:\"root\"`\n}\n```\nCheckCVEsRequest is the input to codefit-check-cves: a project root. The dependency manifests are auto-detected under it.\n\n```go\ntype CheckCVEsResponse struct {\n\tVulnerable          []VulnerableDependency `json:\"vulnerable\"`\n\tDependenciesScanned int                    `json:\"dependencies_scanned\"`\n\tNotes               []string               `json:\"notes\"`\n}\n```\nCheckCVEsResponse reports the vulnerable dependencies, how many were scanned, and any honest notes (a manifest present without its lockfile, or none found).\n\n```go\nfunc HandleCheckCVEs(req CheckCVEsRequest) (CheckCVEsResponse, error)\n```\nHandleCheckCVEs reads the project's dependency manifests (exact versions from lockfiles / go.mod only), queries OSV.dev for known vulnerabilities, and returns the vulnerable dependencies. A thin adapter: it parses manifests, queries the client, and reshapes the result — no detection logic here. When no version resolves (no lockfile), it returns the honest note WITHOUT querying OSV.\n\n```go\ntype ConfirmSurfaceRequest struct {\n\tConfirmations []surface.Confirmation `json:\"confirmations\"`\n}\n```\nConfirmSurfaceRequest carries the agent's verdicts back to codefit.\n\n```go\ntype ConfirmSurfaceResponse struct {\n\tFindings  []findings.Finding     `json:\"findings\"`\n\tDismissed []surface.Confirmation `json:\"dismissed\"`\n\tUncertain []surface.Confirmation `json:\"uncertain\"`\n\tInvalid   []surface.Confirmation `json:\"invalid\"`\n}\n```\nConfirmSurfaceResponse is the integration result: probabilistic findings plus the traceability buckets. Stateless — built purely from the verdicts sent.\n\n```go\nfunc HandleConfirmSurface(req ConfirmSurfaceRequest) ConfirmSurfaceResponse\n```\nHandleConfirmSurface integrates the agent's verdicts: codefit-confirm-surface. It recomputes each surface id to validate the verdict before integrating, and keeps no session.\n\n```go\ntype CoverageRequest struct {\n\tLanguage string `json:\"language\"`\n\t// Detail names the entries whose full prose the caller wants. Many ids in\n\t// one call: an agent that has to make one round trip per declared limit\n\t// stops asking. Omit it and the answer is the index alone.\n\tDetail []string `json:\"detail,omitempty\"`\n}\n```\nCoverageRequest is the input to codefit-coverage.\n\n```go\ntype CoverageResponse struct {\n\tLanguage string `json:\"language\"`\n\t// Index holds EVERY entry the manifest carries, always. The response budget\n\t// authorizes withholding for scan-all; for coverage it authorizes nothing,\n\t// so an over-budget index is reported as over budget and stays complete.\n\tIndex []coverage.IndexEntry `json:\"index\"`\n\t// Entries, Bytes and IndexBytes let the caller check the facts it would\n\t// otherwise have to take on trust: how many entries arrived, and how large\n\t// this response's payload was on the wire.\n\t//\n\t// Bytes is the WHOLE payload — the index plus any detail that was asked for\n\t// — and never the index alone. It used to be the index alone, which made a\n\t// detail request answer with a size verdict scoped to something smaller than\n\t// what it was returning: a 182,440-byte response declaring 21,951 bytes and\n\t// \"within budget\". A response that misreports its own size is the defect\n\t// PR #128 fixed for scan-all's budget note, and it is not allowed here either.\n\tEntries    int `json:\"entries\"`\n\tBytes      int `json:\"bytes\"`\n\tIndexBytes int `json:\"index_bytes\"`\n\t// Withheld is always zero, and WithheldNote says so in words. \"No mention of\n\t// truncation\" and \"nothing was truncated\" are not the same bytes, and an\n\t// agent cannot tell a complete answer from a quiet one without being told.\n\tWithheld     int    `json:\"withheld\"`\n\tWithheldNote string `json:\"withheld_note\"`\n\t// OverBudget reports that the index exceeded the response budget. Nothing is\n\t// dropped when it does — the instruction is to shorten a claim.\n\tOverBudget bool   `json:\"over_budget,omitempty\"`\n\tBudgetNote string `json:\"budget_note,omitempty\"`\n\t// Detail carries the full prose of the requested entries, byte for byte as\n\t// authored.\n\tDetail []coverage.Entry `json:\"detail,omitempty\"`\n\t// Unrecognized names every requested id that matched no entry. Naming it is\n\t// the point: an empty success would say the entry has nothing to declare,\n\t// which is a different and false answer from \"there is no such entry\".\n\tUnrecognized     []string `json:\"unrecognized,omitempty\"`\n\tUnrecognizedNote string   `json:\"unrecognized_note,omitempty\"`\n\t// Derived is true when the answer was COMPUTED from the provider's\n\t// Capability() rather than served from a hand-written CoverageManifest()\n\t// (R1, docs/specs/declared-partial-language-exposure.md): the derived\n\t// answer is the FLOOR every registered, exposed language gets; a\n\t// hand-written prose manifest (TypeScript today) stays authoritative and\n\t// is never replaced by this.\n\tDerived bool `json:\"derived\"`\n}\n```\nCoverageResponse carries the coverage index: every entry codefit declares for the language, as an id, a one-line claim, its answer class, and whether it has more prose to give. The prose itself is served only when asked for by id.\n\n```go\nfunc HandleCoverage(req CoverageRequest) (CoverageResponse, error)\n```\nHandleCoverage returns the coverage manifest for the language. A provider with a hand-written CoverageManifest() serves it unchanged (Derived: false) — the prose manifest stays authoritative. A registered, resolvable provider with NO prose manifest still gets a truthful, DERIVED answer from its Capability() (Derived: true) — \"no coverage manifest for language X\" is the wrong answer to \"what do you cover\", not the absence of an error. Only a language that resolves NO provider at all (unregistered, or registered but not exposed for security scanning) still errors: there is nothing to derive from.\n\n```go\ntype DBSection struct {\n\tMeasured bool                 `json:\"measured\"`\n\tNote     string               `json:\"note,omitempty\"`\n\tFindings []findings.Finding   `json:\"findings,omitempty\"`\n\tSurface  []surfaceindex.Entry `json:\"surface,omitempty\"`\n\t// Count is the COMPLETE number of surface items this section classifies —\n\t// taken from surfaceindex.Index's own return, computed independently of how\n\t// Surface is built, never from len(Surface) after the fact (design D4/I4:\n\t// reading it back off the rendered index is the self-referential trap the\n\t// coverage-chain archive records, obs #1664).\n\tCount int `json:\"count\"`\n\t// Withheld is always 0: there is no ranking axis across db surface's 18\n\t// disjoint categories (no severity field) to withhold BY — a stated absence\n\t// of a mechanism, not a principle (design D4). WithheldNote says so in\n\t// words, deliberately NOT coverage's sentence (a different reason) and NOT\n\t// the endpoint-bucket pattern (db.surface is never partially rendered).\n\tWithheld     int    `json:\"withheld\"`\n\tWithheldNote string `json:\"withheld_note,omitempty\"`\n\tScore        int    `json:\"score\"`\n}\n```\nDBSection is the database dimension's result inside scan-all. Measured=false with a Note is the honest \"not audited\" state (disabled / no parser / schema read or parse failure) — a db failure is SOFT here, reported but never fatal to the security result (ADR 0020). Findings are affirmations (e.g. DB-050); Surface is the LIGHT index (surfaceindex.Entry, not the full findings.SurfaceItem — design D1/D5) of the questions; both are already filtered by the baseline. Full detail of any named item is one codefit-scan-db call away with \\`detail: \\[ids]\\`.\n\n```go\ntype DBSummary struct {\n\tSchemaSources         int `json:\"schema_sources\"`\n\tDeterministicFindings int `json:\"deterministic_findings\"`\n\tSurfaceItems          int `json:\"surface_items\"`\n}\n```\nDBSummary is the database dimension's own counts.\n\nSchemaSources is the dimension's scale unit — the distinct schema sources this pass READ, the same census scope's denominator takes (one local, shared; two call sites computing one census is how this repo drifts). It is not a new measurement, and under a narrowed scope it shrinks with what was read, exactly like \\`scope\\`.\n\nThere is deliberately NO certain\\_concerns here. The security field of that name counts Deterministic PLUS SurfaceConfirmed concerns (core/report/aggregate.go's countCertain), where SurfaceConfirmed is set from a security-surface structural fact DB items never carry — so it is not a certainty-1.0 count, and a DB sibling under the same name would be the exact same-name-different-definition defect this shape exists to fix. Adding the key later is additive; shipping a differently-defined one now would be breaking. See ADR 0069.\n\n```go\ntype FileInput struct {\n\tPath    string `json:\"path\"`\n\tContent string `json:\"content\"`\n}\n```\nFileInput is one source file a surface tool reasons over (path + content), so the tool stays stateless — the caller passes the bytes, codefit reads nothing.\n\n```go\ntype FrontierPending struct {\n\tCount     int                       `json:\"count\"`\n\tWithheld  int                       `json:\"withheld\"`\n\tNote      string                    `json:\"note,omitempty\"`\n\tEndpoints []report.FrontierEndpoint `json:\"endpoints,omitempty\"`\n}\n```\nFrontierPending declares the endpoints codefit did NOT resolve locally: the data left the handler body, so codefit concluded nothing and the agent must follow it in the code. They are named (not detailed) with a Note explaining why they are not detailed and how to fetch any of them. This is not hiding — it is prioritising while declaring the rest.\n\n```go\ntype GoneItem struct {\n\tFingerprint string `json:\"fingerprint\"`\n\tCategory    string `json:\"category\"`\n\tFile        string `json:\"file\"`\n\tSnippet     string `json:\"snippet,omitempty\"`\n}\n```\nGoneItem names a baseline item no longer present in the code — a prune candidate.\n\n```go\ntype ResolvedClean struct {\n\tCount     int                            `json:\"count\"`\n\tWithheld  int                            `json:\"withheld\"`\n\tNote      string                         `json:\"note,omitempty\"`\n\tEndpoints []report.ResolvedCleanEndpoint `json:\"endpoints,omitempty\"`\n}\n```\nResolvedClean declares the endpoints codefit resolved locally and found clean (controls present, no gap). They are NAMED with a verification fact, not detailed. This is an affirmation — codefit looked and it is clean — not a generic \"not detailed\" bucket; that is why it is separate from FrontierPending.\n\n```go\ntype ScanAllRequest struct {\n\tRoot     string `json:\"root\"`\n\tLanguage string `json:\"language\"`\n\t// ChangedFiles narrows the audit to these project-relative paths (layer 0 of\n\t// the filtering pyramid). codefit does not ask git which files changed — it\n\t// has no power over the user's git, and the calling agent already knows what\n\t// it touched. Absent or empty means a FULL audit, never \"audit nothing\".\n\t//\n\t// A narrowed run declares itself in the response's scope block, cannot mark a\n\t// baseline item in an unopened file as gone, and leaves the DB dimension NOT\n\t// MEASURED unless a configured schema path is in scope.\n\tChangedFiles []string `json:\"changed_files,omitempty\"`\n}\n```\nScanAllRequest is the input to codefit-scan-all: a project root and language. codefit walks the project, runs the deterministic sensor and the surface queries, and returns the complete per-endpoint picture.\n\n```go\ntype ScanAllResponse struct {\n\t// Summary is the per-dimension count block: one sub-block per audit\n\t// dimension plus a derived totals, each count declaring which dimension it\n\t// counted. A null sub-block means that dimension was not measured; see\n\t// ScanAllSummary for why an unqualified count was a defect.\n\tSummary ScanAllSummary `json:\"summary\"`\n\t// Scope declares how much of the project this response describes: mode full or\n\t// partial, how many auditable files were in scope, and which requested paths\n\t// the audit never reached. It is ALWAYS present, so a consumer never infers\n\t// the mode from an absence and never reads a partial `blocked: false` as the\n\t// wider claim it is not.\n\tScope ScopeBlock `json:\"scope\"`\n\t// Score is the per-dimension breakdown plus the weighted global (ADR 0021). It\n\t// is ALWAYS present: by_dimension carries every weighted dimension, with the\n\t// unaudited ones (review/complexity/tests, and db when it did not run) as null —\n\t// an honest statement that the dimension exists but was not measured. The score\n\t// reflects deterministic AFFIRMATIONS only, not mapped surface.\n\tScore    scoring.ScoreSummary `json:\"score\"`\n\tBaseline BaselineDelta        `json:\"baseline\"`\n\t// Budget declares the response's own byte budget and whether anything was\n\t// withheld to meet it. ALWAYS present, including when nothing was withheld: an\n\t// agent must be able to tell a complete list from a cut one by reading the\n\t// response, never by guessing (ADR 0054).\n\tBudget          BudgetBlock       `json:\"budget\"`\n\tActionable      ActionableSection `json:\"actionable\"`\n\tResolvedClean   ResolvedClean     `json:\"resolved_clean\"`\n\tFrontierPending FrontierPending   `json:\"frontier_pending\"`\n\t// Security reports whether the security dimension ran (D3b). It is ALWAYS\n\t// present — deliberately NOT `omitempty`, unlike DB: the db dimension may\n\t// legitimately not apply to a project (no database configured), but security\n\t// applies to every project, so an ABSENT section could only mean an older\n\t// codefit build. Measured=false with a Note is the honest \"no provider for\n\t// this language\" state, mirroring DBSection's own Measured/Note shape.\n\tSecurity SecuritySection `json:\"security\"`\n\t// DB is the parallel database-structure section — the db dimension's findings\n\t// and surface, baseline-filtered. It is NON-endpoint (a table has no route), so\n\t// it is its own section, not one of the three endpoint buckets. Nil when the\n\t// project has no database.schema_paths configured, so a project without a\n\t// database yields a response byte-identical to before db was wired (ADR 0020).\n\tDB *DBSection `json:\"db,omitempty\"`\n}\n```\nScanAllResponse is the agent-first synthesis as an ACTIONABLE summary, not the raw item dump. It has three buckets, one per resolution level, all decided by facts codefit already computes (ADR 0008):\n\n  - Actionable      — resolved locally AND has a gap: full detail, the agent acts.\n  - ResolvedClean   — resolved locally, NO gap: named + a verification fact; codefit checked and the controls are present.\n  - FrontierPending — not resolved locally (the data left the handler body): named; the agent follows it in the code.\n\nResolvedClean and FrontierPending are kept DISTINCT on purpose: one affirms codefit verified the controls, the other states codefit could not conclude — epistemological opposites the agent must distinguish (flattening them would be the old frontier-wording error). Full detail of any named endpoint is always one codefit-scan-endpoint call away. Note on the baseline layer: when a baseline exists, the three buckets are FILTERED to what is not yet tracked (new/changed surface, and unaccepted deterministic affirmations). So on an unchanged re-scan all three buckets can be empty even though Summary.Security.CertainConcerns (computed before filtering) is \u003e 0 — the difference is exactly the \"known\" surface the baseline is silencing.\n\n```go\nfunc HandleScanAll(req ScanAllRequest) (ScanAllResponse, error)\n```\nHandleScanAll runs the full audit over the project and returns the actionable summary plus the named frontier-pending list. It reuses the real security sensor (the deterministic rules plus the three surface queries already run together there), groups the result by endpoint, and partitions by the local-resolution fact — it adds no detection, only the aggregation and the split.\n\n```go\ntype ScanAllSummary struct {\n\t// Security counts the security dimension only. Nil when no provider\n\t// resolved for the language — never a zeroed block, which would read as\n\t// \"codefit looked at the code and found nothing\".\n\tSecurity *SecuritySummary `json:\"security\"`\n\t// DB counts the database dimension only. Nil when the dimension did not\n\t// run (no database.schema_paths configured, or narrowed out of scope) and\n\t// when it ran but could not measure (no parser, unreadable schema) — the\n\t// DBSection.Measured=false state.\n\tDB *DBSummary `json:\"db\"`\n\t// Totals is DERIVED from the non-nil sub-blocks, never written by hand: a\n\t// hand-kept total drifts the first time a dimension is added. It carries\n\t// only COMMENSURABLE units — a deterministic finding and a mapped surface\n\t// item mean the same thing in both dimensions. Endpoints and schema\n\t// sources are each dimension's own scale unit and are summed nowhere: a\n\t// table has no route.\n\tTotals SummaryTotals `json:\"totals\"`\n\t// Note is ALWAYS present, on the BudgetBlock precedent: \"no mention\" and\n\t// \"nothing to mention\" must not be the same bytes on the wire.\n\tNote string `json:\"note\"`\n}\n```\nScanAllSummary is the at-a-glance count, not a judgment — and every count in it DECLARES the dimension it counted.\n\nThe flat shape this replaced had four unqualified fields (endpoints, deterministic\\_findings, surface\\_items, certain\\_concerns) that were all functions of the SECURITY sensor's result while presenting themselves as the response's summary. A DB-heavy project therefore read \\`surface\\_items: 0\\` over a db.surface holding dozens of items: a security-only prefix of the truth, presented unlabelled as the whole (invariant I4 of docs/specs/audit-protocol.md), producing the one thing this project exists to prevent — a zero that means \"nobody looked\" (I2).\n\nA sub-block is a POINTER and deliberately NOT omitempty: the key is always on the wire, and \\`null\\` is the statement \"this dimension was not measured\". That is the shape score.by\\_dimension already ships (\\`\"db\": null\\` beside \\`\"db\": 95\\`); an ABSENT key would be a third state a reader has to guess at.\n\n```go\ntype ScanDBRequest struct {\n\tRoot     string   `json:\"root\"`\n\tLanguage string   `json:\"language\"`\n\tDetail   []string `json:\"detail,omitempty\"`\n}\n```\nScanDBRequest is the input to codefit-scan-db: a project root and language. Detail names surface item ids (from a prior Surface index, or from scan-all's db.surface) whose full findings.SurfaceItem the caller wants — mirrors CoverageRequest.Detail. Omit it and the answer is the index alone.\n\n```go\ntype ScanDBResponse struct {\n\tMeasured     bool                 `json:\"measured\"`\n\tNote         string               `json:\"note,omitempty\"`\n\tFindings     []findings.Finding   `json:\"findings\"`\n\tSurface      []surfaceindex.Entry `json:\"surface\"`\n\tCount        int                  `json:\"count\"`\n\tWithheld     int                  `json:\"withheld\"`\n\tWithheldNote string               `json:\"withheld_note,omitempty\"`\n\tScore        int                  `json:\"score\"`\n\t// Detail carries the full item for every requested id that matched, byte\n\t// for byte the pre-change flat Surface shape.\n\tDetail []findings.SurfaceItem `json:\"detail,omitempty\"`\n\t// Unrecognized names every requested id that matched nothing. Naming it is\n\t// the point: an empty success would say the item has nothing to declare,\n\t// which is a different and false answer from \"there is no such item\".\n\tUnrecognized     []string `json:\"unrecognized,omitempty\"`\n\tUnrecognizedNote string   `json:\"unrecognized_note,omitempty\"`\n\t// Bytes/IndexBytes/OverBudget/BudgetNote declare this response's own size,\n\t// wired only once Detail exists (design D5) — the exact shape that made\n\t// CoverageResponse under-declare its size before it carried Bytes/IndexBytes\n\t// (#1664, closed in S3): bytes is measured LAST, over index + detail.\n\tBytes      int    `json:\"bytes\"`\n\tIndexBytes int    `json:\"index_bytes\"`\n\tOverBudget bool   `json:\"over_budget,omitempty\"`\n\tBudgetNote string `json:\"budget_note,omitempty\"`\n}\n```\nScanDBResponse is the standalone DB-structure result. Measured distinguishes \"audited\" from \"not audited\": when false, Note says why (no schema\\_paths, no schema parser, or the sensor is disabled) and Findings/Surface are empty — it is NOT a \"clean\" result. Score is a plain dimension score (0-100), like codefit-scan-security; this tool does not compute by\\_dimension.\n\nSurface is the LIGHT index (surfaceindex.Entry), always complete — nothing is withheld (Count/Withheld/WithheldNote, mirroring DBSection — design D1/D4). Detail carries the full findings.SurfaceItem for every requested id that matched; Unrecognized names every id that matched nothing, with a note (D3): codefit is stateless and cannot tell \"never existed\" from \"the schema moved\".\n\n```go\nfunc HandleScanDB(req ScanDBRequest) (ScanDBResponse, error)\n```\nHandleScanDB runs the DB sensor over the project and returns its structural findings + surface. A thin adapter: it resolves the provider, loads the config, and delegates to the DB sensor (which reads the schema, runs the core rules, and stamps identity). Standalone — it touches nothing in scan-all.\n\n```go\ntype ScanEndpointRequest struct {\n\tRoot     string `json:\"root\"`\n\tLanguage string `json:\"language\"`\n\tFile     string `json:\"file\"`\n}\n```\nScanEndpointRequest is the input to codefit-scan-endpoint: a project root, language, and the file (relative to root, as it appears in scan-all's File fields) to re-analyse on demand.\n\n```go\ntype ScanEndpointResponse struct {\n\tFile      string                  `json:\"file\"`\n\tFound     bool                    `json:\"found\"`\n\tEndpoints []report.EndpointReport `json:\"endpoints,omitempty\"`\n\tNote      string                  `json:\"note,omitempty\"`\n}\n```\nScanEndpointResponse carries the full per-endpoint detail for one file: every handler in it with all its concerns (signals, reason\\_to\\_review, certainty, fact fields) — the same concern contract as scan-all. Found is false when the file has no auditable concerns (not a route handler, or nothing to enumerate).\n\n```go\nfunc HandleScanEndpoint(req ScanEndpointRequest) (ScanEndpointResponse, error)\n```\nHandleScanEndpoint re-analyses a single file on demand and returns its endpoints with full detail. STATELESS: it re-runs the static analysis over the project and filters to the requested file — it retrieves nothing stored. codefit does not keep the surface items waiting to be asked for; it recomputes the request. Static analysis is cheap, and re-running the same pipeline guarantees the detail here is identical to what scan-all would have shown for that endpoint (ADR 0008).\n\n```go\ntype ScanRequest struct {\n\tRoot     string `json:\"root\"`\n\tLanguage string `json:\"language\"`\n\t// ChangedFiles narrows the audit to these project-relative paths (layer 0 of\n\t// the filtering pyramid). codefit does not ask git which files changed — it\n\t// has no power over the user's git, and the calling agent already knows what\n\t// it touched. Absent or empty means a FULL audit, never \"audit nothing\", and\n\t// a narrowed run declares itself in the response's scope block.\n\tChangedFiles []string `json:\"changed_files,omitempty\"`\n}\n```\nScanRequest is the input to codefit-scan-security: a project root, a language, and optionally the files to narrow the audit to.\n\n```go\ntype ScanResponse struct {\n\tFindings []findings.Finding     `json:\"findings\"`\n\tSurface  []findings.SurfaceItem `json:\"surface\"`\n\tScore    int                    `json:\"score\"`\n\tBlocked  bool                   `json:\"blocked\"`\n\tScope    ScopeBlock             `json:\"scope\"`\n\t// SurfaceCoverage declares which of surface.ProviderCategories this\n\t// language's provider mapped and which it did not (R2,\n\t// docs/specs/declared-partial-language-exposure.md): a project whose\n\t// provider maps a narrow slice of the vocabulary (Go today: authz only)\n\t// must never report surface_items with no statement that the rest was\n\t// never searched for. ALWAYS present — HandleScanSecurity errors before\n\t// reaching this point when no provider resolves, so a returned response\n\t// always has one.\n\tSurfaceCoverage surface.CoverageStatement `json:\"surface_coverage\"`\n}\n```\nScanResponse is the deterministic + surface result over the project (the §11 contract): flat findings and surface, the dimension score, and whether the project is blocked (an unconsented critical security finding). Scope declares how much of the project this result describes. It is ALWAYS present, so \\`blocked: false\\` is never read as a wider claim than it is.\n\n```go\nfunc HandleScanSecurity(req ScanRequest) (ScanResponse, error)\n```\nHandleScanSecurity runs the security sensor over the project and returns the flat findings + surface. A thin adapter: it resolves the provider, runs the sensor (the deterministic rules + the surface queries, already wired there), and returns its result — no detection logic lives here.\n\n```go\ntype ScopeBlock struct {\n\tMode           string   `json:\"mode\"`\n\tRequested      int      `json:\"requested\"`\n\tAudited        int      `json:\"audited\"`\n\tAuditableTotal int      `json:\"auditable_total\"`\n\tUnmatched      []string `json:\"unmatched,omitempty\"`\n\tNote           string   `json:\"note\"`\n}\n```\nScopeBlock is a scan's account of HOW MUCH of the project it looked at. It exists because a partial audit that is indistinguishable from a full one is a lying auditor: the whole point of narrowing is that the narrowing stays visible.\n\n  - Requested is how many distinct files the caller asked for (canonical, so a path spelled twice counts once); 0 under a full scan.\n  - Audited is how many of them the pass actually examined, and AuditableTotal how many it COULD have — the denominator is the whole project, never the scope, or \"3 of 412\" collapses into a self-flattering \"3 of 3\".\n  - Unmatched are the requested paths the audit never reached: deleted, wrong extension, outside the project, inside a skipped directory. Without it an agent that passes three wrong paths gets \"0 findings\" and reads it as clean. Requested always equals Audited + len(Unmatched).\n  - Note is MANDATORY when partial and FORBIDDEN when full (see Validate).\n\n```go\nfunc (s ScopeBlock) Validate() error\n```\nValidate enforces the honesty invariant in BOTH directions: a partial scan must declare itself in prose, and a full scan must not carry a caveat it has no basis for. Handlers call it before returning, so a violation is a loud error rather than an unlabelled partial result an agent would read as a full one — the failure this whole block exists to prevent.\n\n```go\ntype SecuritySection struct {\n\tMeasured bool   `json:\"measured\"`\n\tNote     string `json:\"note,omitempty\"`\n\t// SurfaceCoverage declares which of surface.ProviderCategories this\n\t// language's provider mapped and which it did not (R2,\n\t// docs/specs/declared-partial-language-exposure.md) — the \"1 of 4\"\n\t// statement a bare `surface_items: 1` never made. Present only when\n\t// Measured is true: a pointer, so a DB-only pass (Measured=false, no\n\t// provider resolved) serializes no surface_coverage key at all, rather\n\t// than a zero-valued statement that could be misread as \"nothing\n\t// unmapped\".\n\tSurfaceCoverage *surface.CoverageStatement `json:\"surface_coverage,omitempty\"`\n}\n```\nSecuritySection reports whether the security dimension ran this pass (D3b). Measured=false is SOFT, exactly like DBSection: it never fails scan-all, it is reported. Note is empty when Measured is true (nothing to caveat) and non-empty otherwise, naming why (no provider resolved for the language) and what that means for the rest of the response (the schema may still have been audited; the code was not).\n\n```go\ntype SecuritySummary struct {\n\tEndpoints             int `json:\"endpoints\"`\n\tDeterministicFindings int `json:\"deterministic_findings\"`\n\tSurfaceItems          int `json:\"surface_items\"`\n\tCertainConcerns       int `json:\"certain_concerns\"`\n}\n```\nSecuritySummary is the security dimension's own counts — verbatim the four fields the flat ScanAllSummary carried, so a consumer migrating reads summary.security.\\* for exactly the values it used to read at summary.\\*.\n\n```go\ntype SummaryTotals struct {\n\tDeterministicFindings int `json:\"deterministic_findings\"`\n\tSurfaceItems          int `json:\"surface_items\"`\n}\n```\nSummaryTotals is the cross-dimension roll-up, over commensurable units only. It is a VALUE, not a pointer: totals are always computable (the nothing-measurable guard already refused the response where no dimension ran), and zeros here are backed by at least one non-null sub-block saying who was counted.\n\n```go\ntype SurfaceIDORRequest struct {\n\tFiles []FileInput `json:\"files\"`\n}\n```\nSurfaceIDORRequest is the input to codefit-surface-idor.\n\n```go\ntype SurfaceResponse struct {\n\tSurface []findings.SurfaceItem `json:\"surface\"`\n\t// HelperScope is set ONLY by HandleSurfaceAuthz and HandleSurfaceIDOR: it\n\t// declares that their helper-dependent structural facts (known_authz_detected)\n\t// were computed against codefit's BUILT-IN helper set, never the project's\n\t// registered ones (ADR 0013). Like findings.SurfaceItem.StructuralFacts, this\n\t// is a FACT about what was computed, never a judgment about the result — a\n\t// false structural fact still means \"not seen\", not \"unauthorized\".\n\t// omitempty keeps it entirely ABSENT (not present-and-empty) on\n\t// HandleSurfaceOverfetch/HandleSurfaceNPlus1, whose facts never consult the\n\t// helper set: \"no mention\" and \"nothing to mention\" must not be the same\n\t// bytes.\n\tHelperScope string `json:\"helper_scope,omitempty\"`\n}\n```\nSurfaceResponse is the §11 surface contract: the items the agent must reason.\n\n```go\nfunc HandleSurfaceAuthz(req SurfaceIDORRequest) (SurfaceResponse, error)\n```\nHandleSurfaceAuthz enumerates the broken-authorization surface across the given files. It orders the items so the actionable ones — where no known authz helper was detected — come FIRST, the rest after (where a check exists, the agent verifies sufficiency). It does NOT reduce the list: the complete enumeration is preserved, only reordered, so findings surface instead of being buried in volume. Ordering by a fact is not a severity judgment — codefit does not say \"no check is worse\", it just surfaces the fact for the agent.\n\n```go\nfunc HandleSurfaceIDOR(req SurfaceIDORRequest) (SurfaceResponse, error)\n```\nHandleSurfaceIDOR enumerates the IDOR surface across the given files and returns it in the canonical JSON contract. Files that are not handled by a provider (or carry no IDOR surface) contribute nothing.\n\n```go\nfunc HandleSurfaceNPlus1(req SurfaceIDORRequest) (SurfaceResponse, error)\n```\nHandleSurfaceNPlus1 enumerates the N+1 (DB-201) surface and orders by STRUCTURAL CERTAINTY, reusing the queryable facts — it does NOT filter (ADR 0005): a loop over three literal elements is enumerated exactly like a loop over an unbounded query result.\n\n\t1st  local + sequential await — the worst, most certain shape\n\t2nd  local + Promise.all-wrapped (concurrent) — still N queries\n\t3rd  frontier (a service/repository call — codefit cannot see the query;\n\t     kept last, honest, never dropped)\n\n```go\nfunc HandleSurfaceOverfetch(req SurfaceIDORRequest) (SurfaceResponse, error)\n```\nHandleSurfaceOverfetch enumerates the over-fetching surface and orders by STRUCTURAL CERTAINTY, reusing the queryable facts — it does NOT filter:\n\n\t1st  local find, no select   (structurally confirmed over-fetch — actionable)\n\t2nd  local find, with select (limited)\n\t3rd  frontier (service — codefit cannot see the find; kept last, honest)\n\nThe complete enumeration is preserved; only the order changes, lowering the uncertain (frontier) without dropping them — the unchecked-first principle on the local/frontier axis (ADR 0005). Ordering by a fact is not severity: codefit ranks by what it can assert with most certainty, the agent judges.\n\n```go\ntype Tool string\n```\nTool is the name of an MCP tool codefit exposes. All tools use the codefit- prefix; the codefit-surface-\\* family enumerates surface for the agent to reason about rather than detecting (PRD section 11).\n\n```go\nconst (\n\tToolScanSecurity                  Tool = \"codefit-scan-security\"\n\tToolScanDB                        Tool = \"codefit-scan-db\"\n\tToolCheckCVEs                     Tool = \"codefit-check-cves\"\n\tToolCheckPractices                Tool = \"codefit-check-practices\"\n\tToolScanTests                     Tool = \"codefit-scan-tests\"\n\tToolSurfaceIDOR                   Tool = \"codefit-surface-idor\"\n\tToolSurfaceAuthz                  Tool = \"codefit-surface-authz\"\n\tToolSurfaceOverfetch              Tool = \"codefit-surface-overfetch\"\n\tToolSurfaceNPlus1                 Tool = \"codefit-surface-nplus1\"\n\tToolConfirmSurface                Tool = \"codefit-confirm-surface\"\n\tToolReviewCode                    Tool = \"codefit-review-code\"\n\tToolScanAll                       Tool = \"codefit-scan-all\"\n\tToolScanEndpoint                  Tool = \"codefit-scan-endpoint\"\n\tToolBaselineList                  Tool = \"codefit-baseline-list\"\n\tToolBaselineAccept                Tool = \"codefit-baseline-accept\"\n\tToolBaselinePrune                 Tool = \"codefit-baseline-prune\"\n\tToolBaselineRegisterAuthzHelper   Tool = \"codefit-baseline-register-authz-helper\"\n\tToolBaselineUnregisterAuthzHelper Tool = \"codefit-baseline-unregister-authz-helper\"\n\tToolCoverage                      Tool = \"codefit-coverage\"\n)\n```\n\n```go\ntype VulnerableDependency struct {\n\tName            string              `json:\"name\"`\n\tVersion         string              `json:\"version\"`\n\tEcosystem       string              `json:\"ecosystem\"`\n\tVulnerabilities []cve.Vulnerability `json:\"vulnerabilities\"`\n}\n```\nVulnerableDependency is one dependency that OSV.dev reports as vulnerable, with every vulnerability affecting its exact installed version.\n\n","path":"github.com/codefit-cli/codefit/internal/mcp","name":"mcp","synopsis":"Package mcp implements the MCP server mode: a thin, stateless adapter that exposes the same core sensors as MCP tools (PRD section 10).","isRedistributable":true}
