import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js' // `@basementstudio/qa-engine/run`, not `@basementstudio/qa-engine`: the root barrel re-exports the browser, sharp and // lighthouse, and this server needs none of them. See that barrel's header. import { RunStore, type RunStorage } from '@basementstudio/qa-engine/run' import { FindingKind, SCHEMA_VERSION, Severity } from '@basementstudio/qa-schema' import { z } from 'zod' import { makeRecorder } from './activity-record' import { describeRun, diff, facts, fetchUrl, findings, findingsMarkdown, listRuns, listScreenshots, projects, screenshot, issueDelete, issueWrite, issues, promptFor, setFinished, waive, type ToolContext, schemaPayload, FACT_SECTIONS, } from './tools' /** * `@basementstudio/qa-mcp` — the MCP server over stored runs. * * The premise the whole tool rests on: **Claude is the orchestrator, not a * consumer of a finished report.** This server is how that works in practice. A * run has already happened and its artifact is on disk, so answering "what's * broken on /careers?" or "show me the crop for that overflow" costs a file read * — no browser, no page loads, no tokens spent re-deriving what was already * measured. * * Most tools are read-only. The five that write — `qa_waive`, `qa_issue_write`, * `qa_issue_delete`, `qa_fetch` and `qa_set_finished` — all write in * the direction of *recording a decision* rather than suppressing output, which * is the line this server holds. Four of them write the local artifact; * `qa_fetch` is the only one that reaches the network to do it, and it is bounded * to the site under review; * `qa_set_finished` is the exception and writes one column of the mirror, for * the reason set out on `setFinished` in `tools.ts`. */ export interface ServerOptions { /** * The connection string this server serves, when it has one. * * Only `qa_set_finished` reads it, and only because it was otherwise re-resolving its own — writing * to a different database than the one every read tool on this server answers from. See * `ToolContext.databaseUrl`. */ databaseUrl?: string cwd?: string storeRoot?: string /** Pins every tool to one run, for `qa mcp --run `. */ defaultRunId?: string /** * Where the run's bytes live. Defaults to the filesystem, which is what the stdio server wants. * * Supplied by the HTTP server, whose host may have no writable disk. Every tool reaches the * store through `ToolContext`, so injecting here is enough to redirect all fourteen. */ storage?: RunStorage /** * An already-built store, which **wins over every option above**. * * Added because `storeRoot` + `storage` is two halves of one answer, and a caller that has already * paired them correctly had no way to say so. `neonRunStore()` exists precisely to resolve the root * once and hand the same string to the store and its backend — so making a caller take it apart and * pass the pieces reintroduces the two-callers-agreeing hazard that function was written to remove. * * The bug that forced this: `apps/dashboard/app/mcp/route.ts` passed `storeRoot: * resolveStore().root`, and on the mirror that value is the *label* `neon:.qa` rather than a path. * So the deployed `/mcp` built a filesystem store over a directory literally named `neon:.qa`, * answered `qa_runs` with `[]`, and did it in the same process where the dashboard was rendering * those runs out of Postgres. That is the exact failure that route's own comment says it fixed — * reintroduced one layer down, and silent, because an unreadable store lists as empty. */ store?: RunStore /** * How to reach the **dashboard's** store, resolved on first use rather than at startup. * * Every read tool takes `dashboard: true`; this is what it resolves through. Omit it and that * parameter fails with a message naming the fix, which is the right answer for a host with no * database — better than a server that refuses to start, and better than one that silently serves * the local store when asked for the mirror. * * A thunk, not a store, because the resolution can end at `vercel env pull` — ~2.3s and a * subprocess. Paying that at every session start, for every user, to serve a store most calls do * not want is not a trade worth making. Callers memoise. */ dashboard?: () => Promise } /** JSON as a tool result. The SDK's content blocks are text-based. */ function json(value: unknown) { return { content: [{ type: 'text' as const, text: JSON.stringify(value, null, 2) }] } } /** An error the model should see and act on, rather than a transport failure. */ function failure(e: unknown) { return { content: [{ type: 'text' as const, text: `Error: ${e instanceof Error ? e.message : String(e)}` }], isError: true, } } const RUN_ID = z .string() .optional() .describe('Run id, a unique prefix of one, or "latest". Defaults to the most recent run.') const DASHBOARD = z .boolean() .optional() .describe( 'Read the DASHBOARD instead of this machine — the snapshots `qa push` mirrored to Postgres, which is what a teammate sees at the hosted URL. Use this whenever somebody says "from the dashboard", names a site nobody crawled in this session, or asks about a run that is not in the local store. It is read-only: the five write tools always address the local artifact, deliberately, because the mirror is overwritten by the next push.', ) export function createServer(opts: ServerOptions = {}): McpServer { const ctx: ToolContext = { store: opts.store ?? new RunStore({ ...(opts.cwd ? { cwd: opts.cwd } : {}), ...(opts.storeRoot ? { storeRoot: opts.storeRoot } : {}), ...(opts.storage ? { storage: opts.storage } : {}), }), ...(opts.defaultRunId ? { defaultRunId: opts.defaultRunId } : {}), ...(opts.dashboard ? { dashboard: opts.dashboard } : {}), ...(opts.databaseUrl ? { databaseUrl: opts.databaseUrl } : {}), } /** * Every tool call is recorded, and **nothing asks the agent to help.** * * `registerTool` is wrapped once rather than each of the sixteen handlers being edited, because a * per-handler call is a thing sixteen future registrations can forget — the same reasoning behind * `check-pins` enumerating a directory instead of listing files. What lands in the log is in * `ActivityEvent`; what makes it worth having is that it cannot drift from the work, since the * record *is* the call. * * The recorder itself lives in `activity-record.ts` rather than here, because this wrapper is only one * of two ways a tool gets called and for a while it was the only one that recorded — see that module. * * Timing wraps the handler and not the transport, so `ms` is the tool doing its job rather than the * client's round trip. A refusal is recorded with `ok: false` and its message: failures were 9% of * calls and **64% of tool time** on the one review measured end to end, so dropping them would hide * most of what there is to see. */ const record = makeRecorder(ctx) const registerTool: McpServer['registerTool'] = ((name: string, config: unknown, handler: (...args: never[]) => Promise) => server.registerTool(name as never, config as never, (async (...args: never[]) => { const started = performance.now() try { const out = await handler(...args) /* * A refusal returns normally with `isError` set — every handler catches and calls `failure`, * so almost nothing reaches the `catch` below. Reading the message back out of the content * block is what makes a refused call legible in the log rather than merely counted. */ const failed = Boolean((out as { isError?: boolean } | undefined)?.isError) const text = failed ? String((out as { content?: { text?: string }[] }).content?.[0]?.text ?? '') : undefined record({ tool: name, input: args[0], ok: !failed, ms: performance.now() - started, ...(text ? { error: text } : {}) }) return out } catch (e) { record({ tool: name, input: args[0], ok: false, ms: performance.now() - started, error: e instanceof Error ? e.message : String(e), }) throw e } }) as never)) as never const server = new McpServer( { name: 'qa', version: '0.1.0' }, { instructions: [ 'Launch-readiness QA over stored runs. A run is produced by `qa run ` and lives in', '`.qa/runs//`. Nothing here re-crawls: every answer comes from the stored artifact.', '', 'Start with `qa_runs` then `qa_run` to orient, then `qa_findings` for the slice you care about.', '`qa_findings_md` returns the same document a human reads — already ranked, grouped and deduped —', 'which is usually the cheapest way to get oriented.', '', 'THESE TOOLS ARE HALF THE PRODUCT, AND THIS BLOCK IS THE ONLY THING SOME READERS EVER SEE.', 'If you are doing a full launch-readiness review rather than answering one question about a run,', 'invoke the **`basement-qa:run` skill** — it carries the review loop, the three passes and the', 'stop test, and none of that is in these tool descriptions. Measured: two reviewers given the', 'tools and no skill reached every finding in the run and never learned the brief documents', 'existed, because nothing told them.', '', '`qa brief ` is the other entry point and it is a CLI command rather than a tool here.', 'It prints the exact set of review documents a run needs — N route briefs + 1 site brief,', 'always — and `qa brief --check` proves they cover every finding exactly once. The site', 'brief is the one that owns what no single route does: findings measured once for the origin,', 'plus every cause that fired on several routes. **A fan-out that skips it drops that work on', 'the floor** — one measured arm lost 10 defects that way and another 5, because the reviewer', 'who owned them was never briefed.', '', 'THERE ARE TWO STORES. The default is this machine\'s `.qa`. The other is the **dashboard** — the', 'snapshots `qa push` mirrored to Postgres, which is what teammates see at the hosted URL — and every', 'read tool reaches it with `dashboard: true`. Use it without being told to whenever the request names', 'the dashboard, names a site nobody crawled in this session, or asks for a run the local store does', 'not have. "Grab the xmcp issues from the dashboard" is `qa_projects {dashboard: true}` to find the', 'site, then `qa_issues {runId, dashboard: true}` — do not re-crawl the site to answer it, and do not', 'report the local store being empty as the answer.', '', 'The dashboard is READ-ONLY, and the write tools have no `dashboard` parameter at all. Postgres is a', 'read model that the next `qa push` overwrites, so a judgement recorded there would be lost silently.', 'Review a run where its artifact is, then `qa push` again — which upserts.', '', 'Findings carry no suggestions and no guesses at cause: checks report facts only, because reasoning', 'needs repo and project context a pure function over facts does not have. That reasoning is your job.', '', 'A finding is a record of a rule firing. An **issue** is a unit of work, and `qa_issue_write` is where', 'you author one — citing the findings it covers, naming what the thing actually is, and saying what to', 'change. A run with no issues is a DRAFT: the measurements happened and nobody reasoned about them.', '`cites` is optional, so a nit with nothing but a Slack link is still a first-class issue.', '', '**Issues belong to the run they were authored against, and do not carry forward.**', 'A run artifact is self-contained: it holds only work that run has something to say about. So every run', 'needs its own review pass, and last week\'s write-ups do not re-stamp onto this week\'s findings — a', 'redeploy on the same commit can change env vars and fix things, which makes a carried conclusion an', 'assertion nobody re-measured. Ask what changed with `qa diff`, which answers it deliberately.', 'Waivers are the exception and live outside runs, because accepting something is a decision that has to', 'survive a re-run.', '', 'There is no composite score and no go/no-go verdict, deliberately. Severity is what the check', 'proposed; reclassify per project in conversation with the human rather than treating it as final.', 'When you do, `defaultSeverity` is preserved so the change stays auditable — that auditability is', 'the condition on which overriding is permitted at all.', '', 'Findings can be queried while a run is still in progress — per-page results are written the moment', 'each page finishes. `runStillInProgress: true` means the cross-page checks have not run yet.', '', 'IMPORTANT: not every finding is a defect. `kind` distinguishes them, and only `defect` counts as', 'something to fix — `policy` is a valid choice needing a human decision, `transparency` describes how', 'the page was measured, and `ungraded` could not be checked at all. Use `defectsOnly: true` when you', 'want the work list. Never report a note as a problem, and never present an `ungraded` check as a pass.', ].join('\n'), }, ) registerTool( 'qa_runs', { title: 'List stored QA runs', description: 'List runs newest first, with target, env, git identity and finding counts. Start here when you do not know which run to look at.', inputSchema: { limit: z.number().int().min(1).max(100).optional().describe('Default 20.'), dashboard: DASHBOARD, }, annotations: { readOnlyHint: true }, }, async ({ limit, dashboard }) => { try { return json(await listRuns(ctx, { ...(limit !== undefined ? { limit } : {}), ...(dashboard ? { dashboard } : {}) })) } catch (e) { return failure(e) } }, ) registerTool( 'qa_projects', { title: 'List projects and their snapshots', description: 'Runs grouped into the sites they were taken against — the same two screens the dashboard opens on, and the way to reach a snapshot when you know the site rather than the run id. Each project carries every snapshot newest first with `issues` and `draft` on the row, so you can pick the one somebody actually reviewed: a freshly pushed run has no issues by design, because `qa run --push` mirrors measurements and the review happens after. Then pass the `runId` to `qa_issues` or `qa_findings` — there is one way to address a run and this is how you find it. Projects are derived from the target URL, so a leading `www.` is the same site and a subdomain is a different one.', inputSchema: { limit: z .number() .int() .min(1) .max(200) .optional() .describe( 'How many runs to read, newest first. Default 20. This bounds RUNS, not projects: a project whose runs are all older than the cut will not appear at all, and the result says when it hit the ceiling.', ), dashboard: DASHBOARD, }, annotations: { readOnlyHint: true }, }, async ({ limit, dashboard }) => { try { return json( await projects(ctx, { ...(limit !== undefined ? { limit } : {}), ...(dashboard ? { dashboard } : {}) }), ) } catch (e) { return failure(e) } }, ) registerTool( 'qa_run', { title: 'Describe one run', description: 'Identity (target, git source, runner fingerprint), the page index with per-page finding counts, run errors, and any ungraded checks. Excludes findings — call qa_findings for those. `review` carries what produced the WORK LIST and what it cost — mode, substrate, models, actors, turns, tool calls, the four token classes and a dollar figure frozen at push — with one entry per actor, so a fan-out shows where its cost went. It is ABSENT when nobody recorded it, which is every run from before this existed and every run reviewed on another machine: that is "nobody can say", never "this was free". Read `substrate` before the money — `claude-code` is API-equivalent credit against a subscription allowance and `api` is a bill, and they differ by two orders of magnitude in what the same number means.', inputSchema: { runId: RUN_ID, dashboard: DASHBOARD }, annotations: { readOnlyHint: true }, }, async ({ runId, dashboard }) => { try { return json(await describeRun(ctx, { ...(runId ? { runId } : {}), ...(dashboard ? { dashboard } : {}) })) } catch (e) { return failure(e) } }, ) registerTool( 'qa_findings', { title: 'Query findings', description: 'Findings across a run, blockers first. Filter by route, severity, category, checkId (prefix-matched, so "meta.og" selects the family) or a text search. Returns compact digests unless `full` is set. Waived findings are included by default — they are still findings.', inputSchema: { runId: RUN_ID, route: z.string().optional().describe('Restrict to one page, e.g. "/careers".'), siteOnly: z .boolean() .optional() .describe( 'Only findings that belong to NO route — robots.txt, security headers, caching policy, route discovery, shared components. These are invisible to any per-page reviewer, so under a sharded review somebody has to be handed them explicitly or they go unread with nothing reporting it. Do NOT pass `route: null` for this: that is no filter at all and returns the whole run.', ), defectsOnly: z .boolean() .optional() .describe('Only things to fix. Excludes decisions, measurement notes and ungraded checks.'), /* * The mirror of `defectsOnly`, and it has to be declared here or it does not exist: zod strips * a key the schema does not name, so `notesOnly: true` was silently dropped and the whole run * came back — while `SKILL.md` told every reviewer the filter worked. `queryFindings` refuses * both flags at once rather than returning the empty intersection. */ notesOnly: z .boolean() .optional() .describe( 'Only what a check measured and could not judge: decisions, measurement notes and ungraded checks. The mirror of `defectsOnly` — passing both is an error, not an empty list.', ), kind: z .array(FindingKind) .optional() .describe( 'defect (something is wrong) · policy (a valid choice needing a human decision) · transparency (how the page was measured) · ungraded (could not be checked).', ), severity: z.array(Severity).optional().describe('e.g. ["blocker","major"]. Only meaningful for defects.'), category: z .array(z.string()) .optional() .describe('discovery, meta, seo, layout, a11y, weight, timings, hygiene, interaction, content.'), checkId: z.string().optional().describe('Exact id or a family prefix such as "layout" or "meta.og".'), search: z.string().optional().describe('Substring over title, detail and checkId.'), excludeWaived: z.boolean().optional().describe('Omit findings under an in-force waiver. Off by default.'), limit: z.number().int().min(1).max(500).optional(), full: z .boolean() .optional() .describe('Return whole Finding objects rather than digests. Much more verbose.'), dashboard: DASHBOARD, includeSnippets: z .boolean() .optional() .describe( 'Each mapped finding\'s code excerpt (matched line ±3). ON by default — it is what lets you verify every source ref and read intent from the code without opening a file, and it measures 192B mean per finding. Pass false only for a deliberately wide sweep where you want the leanest possible list.', ), briefing: z .boolean() .optional() .describe( 'The run-shape paragraph in `shape.briefing`. ON for an unfiltered call, OFF once you filter — it is ~1,100 tokens of the same run-wide prose every time, and on a narrow call it dwarfs the answer. Every NUMBER in `shape` is returned either way and is always the whole run, never your filter. Pass true to get the prose back on a filtered call.', ), shape: z .boolean() .optional() .describe( 'The `shape` block itself — the run-wide distribution the briefing narrates. ON by default. Pass false on a call that already has it: measured at 1,155B of a 3,734B route-filtered response — 31% — and identical every time because it describes the run rather than your filter.', ), }, annotations: { readOnlyHint: true }, }, async (input) => { try { return json( await findings(ctx, { ...input, ...(input.category ? { category: input.category } : {}), ...(input.kind ? { kind: input.kind } : {}), }), ) } catch (e) { return failure(e) } }, ) registerTool( 'qa_findings_md', { title: 'Read the rendered findings document', description: 'The Markdown a human reads: ranked, grouped, with evidence inline. Omit `page` for the run-wide document. Often the cheapest way to get oriented on a run.', inputSchema: { runId: RUN_ID, page: z.string().optional().describe('Page slug or route. Omit for the whole run.'), /* * `findingsMarkdown` has always taken this as a synonym for `page`, and it was unreachable: a * key the schema does not name is stripped by zod, so the synonym absorbed nothing. It exists * because the sibling tool's parameter is called `route`, which is what a caller reaches for * second — and being silently ignored returned the whole run's document instead of one page's. */ route: z.string().optional().describe('Synonym for `page`, matching `qa_findings`. Pass either.'), dashboard: DASHBOARD, }, annotations: { readOnlyHint: true }, }, async ({ runId, page, route, dashboard }) => { try { const result = await findingsMarkdown(ctx, { ...(runId ? { runId } : {}), ...(page ? { page } : {}), ...(route ? { route } : {}), ...(dashboard ? { dashboard } : {}), }) // Returned as text rather than JSON: it's a document, and wrapping it in // a JSON string would double every escape for no benefit. return { content: [{ type: 'text' as const, text: result.markdown }] } } catch (e) { return failure(e) } }, ) registerTool( 'qa_diff', { title: 'Compare two runs', description: 'What changed between two runs of the same site — the answer to "did anything ship since last time", which is a diff question and NOT a filter on one run. Nothing here re-crawls. Findings are matched on every identity they answer to, so a defect that collapses into one site-wide finding on a six-page run and reports per route on a one-page run counts as ONE finding in either direction; you do not need the two runs to have the same shape. `disappeared` is deliberately not called `fixed`: a finding present in the first run and absent from the second may have been fixed, or its check may have changed, or the page may not have been audited, or a collector may have broken and emitted nothing — which reads exactly like a clean page. Read `reading` before you cross anything off, and treat `coverage.coverageChanged` as making every disappearance unsafe to call progress. Issues are never diffed; they belong to the run they were authored against.', inputSchema: { runA: z .string() .describe('The earlier run. A run id, a unique id prefix, or `latest`. From `qa_runs`.'), runB: z .string() .optional() .describe('The later run. Defaults to `latest`, which is the common form: `{runA: ""}`.'), dashboard: DASHBOARD, }, annotations: { readOnlyHint: true }, }, async ({ runA, runB, dashboard }) => { try { return json( await diff(ctx, { runA, ...(runB ? { runB } : {}), ...(dashboard ? { dashboard } : {}), }), ) } catch (e) { return failure(e) } }, ) /** * The registration's enum and the reader's allowlist are one list. * * They were two, and the copies had already diverged the moment a section was added: zod * refuses a name `qa_facts` itself accepts, so the MCP surface and `qa mcp` disagree about * what exists — and a zod refusal reads to a caller like the section is not a thing. */ const SECTIONS = FACT_SECTIONS registerTool( 'qa_facts', { title: 'Read collected page facts', description: 'The raw facts behind a page\'s findings. Returns a summary by default — facts.json is the largest file in a run and an 11-viewport probe sweep is most of it. Pass `sections` to fetch specific parts in full, a dotted path to project into one (`a11y.focusables`), or `summarise: true` for a path\'s counts and item keys instead of its contents.', inputSchema: { runId: RUN_ID, page: z.string().describe('Page slug or route.'), /** * `z.string()`, not `z.enum` — a dotted projection is not a member of the enum, and zod * refusing it reads to a caller as *"that section does not exist"*. The names still come from * `FACT_SECTIONS`, in the description rather than in the type, and `facts()` refuses an * unknown one by name with the full list. */ sections: z .array(z.string()) .optional() .describe( `Omit for a summary of what is available. Sections: ${SECTIONS.join(', ')}. ` + 'A dotted path projects into one, e.g. "a11y.focusables".', ), summarise: z .boolean() .optional() .describe('Return each requested path\'s count, bytes and item keys instead of its contents.'), dashboard: DASHBOARD, }, annotations: { readOnlyHint: true }, }, async ({ runId, page, sections, summarise, dashboard }) => { try { return json( await facts(ctx, { ...(runId ? { runId } : {}), page, ...(sections ? { sections } : {}), ...(summarise ? { summarise } : {}), ...(dashboard ? { dashboard } : {}), }), ) } catch (e) { return failure(e) } }, ) registerTool( 'qa_screenshot', { title: 'Read a stored screenshot', description: 'Returns a stored image as an image content block. Use the paths in a finding\'s `screenshots` field, or list them with qa_screenshots. Prefer crops: a full-page capture downscales to roughly 282x1568 on the way in and arrives unreadable.', inputSchema: { runId: RUN_ID, path: z.string().describe('Path relative to the run root, e.g. "pages/home/shots/f-abc123.webp".'), dashboard: DASHBOARD, }, annotations: { readOnlyHint: true }, }, async ({ runId, path, dashboard }) => { try { const result = await screenshot(ctx, { ...(runId ? { runId } : {}), path, ...(dashboard ? { dashboard } : {}), }) return { content: [{ type: 'image' as const, data: result.base64, mimeType: result.mimeType }], } } catch (e) { return failure(e) } }, ) registerTool( 'qa_screenshots', { title: 'List a page\'s stored screenshots', description: 'Paths of every screenshot stored for one page, for use with qa_screenshot.', inputSchema: { runId: RUN_ID, page: z.string().describe('Page slug or route.'), dashboard: DASHBOARD }, annotations: { readOnlyHint: true }, }, async ({ runId, page, dashboard }) => { try { return json( await listScreenshots(ctx, { ...(runId ? { runId } : {}), page, ...(dashboard ? { dashboard } : {}) }), ) } catch (e) { return failure(e) } }, ) registerTool( 'qa_fetch', { title: 'Fetch one URL from the site under review, and record it', description: 'Look at one URL on the audited site and WRITE the answer into the run at `global/fetched/`, so an issue can cite evidence the next reader can check. Use it instead of shelling out to curl: measured across one fan-out, `Bash` was the largest tool category at 208 of 579 calls, and four of one reviewer\'s twelve issues rest on curl output the run holds no trace of — a reader three weeks later cannot verify the claim and `qa diff` cannot say whether it was fixed. Returns status, the response headers with lowercased keys, `contentLength` as the server claimed it, and with `body: true` the bytes that actually arrived plus the document\'s own `rel=canonical`. ONE GET per call, never a HEAD — CDNs answer HEAD with 405 while serving GET fine — and with `body` off the stream is cancelled as soon as the headers arrive, so pointing this at a 40MB asset costs headers and nothing more. SCOPED TO THE SITE UNDER REVIEW: apex, www and first-party subdomains are allowed and a third party is refused by name. `bytes` is what arrived and `contentLength` is what was claimed; neither is derived from the other, and both can be absent. A check over these records replays under `qa recheck`, which is what a curl in a terminal can never do.', inputSchema: { url: z.string().describe('Absolute http(s) URL on the audited site. A path alone is refused as ambiguous.'), body: z .boolean() .optional() .describe( 'Read the body too, bounded by `maxBytes` with the cap reported. Needed for `canonical` and for a real byte count. Default false, which costs headers only.', ), route: z .string() .optional() .describe( 'The route you are reviewing. Set it: the record is attributed to that page, and only route-scoped records reach that page\'s checks on a replay.', ), by: z.string().optional().describe('Who asked — provenance, like an issue\'s `by`.'), timeoutMs: z.number().int().optional().describe('Default 15000.'), maxBytes: z.number().int().optional().describe('Read cap with `body`. Default 5MB, and reported when it bites.'), excerptChars: z .number() .int() .optional() .describe( 'Characters of the body to STORE in the run. Default 16000, which holds a sitemap or a markdown view whole and truncates a full HTML document. The response hands back the entire body regardless — this bounds only what a later reader can check your citation against, so raise it when the evidence you are quoting sits past the default.', ), runId: RUN_ID, }, /* Writes, and never idempotent in the sense the others are: it re-measures the network each call. */ annotations: { readOnlyHint: false, idempotentHint: false }, }, async ({ url, body, route, by, timeoutMs, maxBytes, excerptChars, runId }) => { try { return json( await fetchUrl(ctx, { url, ...(body !== undefined ? { body } : {}), ...(route ? { route } : {}), ...(by ? { by } : {}), ...(timeoutMs !== undefined ? { timeoutMs } : {}), ...(maxBytes !== undefined ? { maxBytes } : {}), ...(excerptChars !== undefined ? { excerptChars } : {}), ...(runId ? { runId } : {}), }), ) } catch (e) { return failure(e) } }, ) registerTool( 'qa_waive', { title: 'Record a waiver for a finding', description: 'Mark a finding as known-and-accepted in `.qa/waivers/`, one file keyed on its stable fingerprint so it persists across runs and environments. The finding keeps appearing in every future run, marked as waived — waivers never hide findings. Confirm with the human before calling this.', inputSchema: { id: z.string().describe('The finding id (fingerprint).'), reason: z.string().min(1).describe('Why this is accepted. Required — an unexplained waiver is unreviewable.'), by: z.string().describe('Who accepted it.'), expiresAt: z .string() .optional() .describe('ISO date. After it, the finding reports at full severity and the lapse is flagged.'), runId: RUN_ID, }, annotations: { readOnlyHint: false, idempotentHint: true }, }, async ({ id, reason, by, expiresAt, runId }) => { try { return json( await waive(ctx, { id, reason, by, ...(expiresAt ? { expiresAt } : {}), ...(runId ? { runId } : {}), }), ) } catch (e) { return failure(e) } }, ) registerTool( 'qa_issues', { title: 'Read the issue list', description: 'The issues authored against THIS RUN, from its own `global/issues/` directory, one file per issue. Read this BEFORE authoring: it is how you fill in `related`, and how you avoid writing an issue somebody already wrote. Empty is the normal state of a fresh run and means nobody has reviewed it — issues do not carry over from the previous run, deliberately, because a re-stamped conclusion asserts something nothing re-measured. `unreviewed` is the count still carrying a title a check produced. `foundByLooking` is the count citing NOTHING — work found by examining the site rather than by reading a finding, and the only number pass 3 has: measured 16 against 5 across two arms of one run where every other metric had converged, and the arm that scored 5 also scored `defectsUncited: 0` while missing nine findings. Read it beside `total` as a ratio, not as a target. Each issue reports `citedTitles` (what the checks called the findings it cites) and `unresolvedCitations` (citations matching nothing in this run, which usually means fixed).', inputSchema: { runId: RUN_ID, unreviewedOnly: z .boolean() .optional() .describe('Only issues still carrying a check-produced title — the work list for a review pass.'), route: z .string() .optional() .describe( 'Only issues about this route, and add per-route coverage counters: `routeDefectsUncited`, `routeUncitedCheckIds`, `routeNotesUncited`. **This is how a per-page reviewer in a sharded review knows it is done.** The run-level `defectsUncited` counts every other shard and the site-level slice too, so it can never reach zero for one route and reads as failure. Site-level findings carry no route and sit outside every route number, deliberately: they belong to the meta pass.', ), siteOnly: z .boolean() .optional() .describe( 'Only issues that belong to no route — the site-level slice, and the mirror of the same flag on `qa_findings`. **This is how the reviewer that owns the route-less half knows whether its own slice is covered.** Without it that reviewer could only read the run-level counter, which every other concurrent writer moves.', ), ids: z .array(z.string()) .optional() .describe( 'Specific issues by id — the companion to `titlesOnly`. Scan compact, then read the prose of only the few you are merging. An id matching nothing comes back in `idsNotFound` rather than being dropped.', ), titlesOnly: z .boolean() .optional() .describe( 'Drop the prose fields — `problem`, `fix`, `why`, `evidence`, `links`, `citedTitles` — and keep what a merge or a ranking decision is made on: `id`, `title`, `route`, `severity`, `kind`, `type`, `category`, `rank`, `where`, `cites`, `related`. **Use this for the meta pass**, which has to read every issue in the run and is the one call guaranteed to be large. What was dropped is named back to you in `issuesShape`.', ), fields: z .array(z.string()) .optional() .describe( 'Explicit projection, when `titlesOnly` is the wrong subset. An unknown field name is an error rather than an empty issue.', ), dashboard: DASHBOARD, }, annotations: { readOnlyHint: true }, }, async (input) => { try { return json( await issues(ctx, { ...(input.runId ? { runId: input.runId } : {}), ...(input.unreviewedOnly ? { unreviewedOnly: input.unreviewedOnly } : {}), ...(input.route ? { route: input.route } : {}), ...(input.siteOnly ? { siteOnly: input.siteOnly } : {}), ...(input.ids?.length ? { ids: input.ids } : {}), ...(input.titlesOnly ? { titlesOnly: input.titlesOnly } : {}), ...(input.fields?.length ? { fields: input.fields } : {}), ...(input.dashboard ? { dashboard: input.dashboard } : {}), }), ) } catch (e) { return failure(e) } }, ) registerTool( 'qa_issue_write', { title: 'Author an issue — the unit of work', description: 'Write an issue into this run\'s `global/issues/`, as its own file. A finding is a record of a rule firing; an issue is a piece of work, and the report renders issues with findings as the evidence underneath. It belongs to the run you author it against and does not carry into the next one — ask `qa diff` what changed instead. Cite the findings it covers by fingerprint — but `cites` is OPTIONAL: "nit: this animation looks wrong", with a Slack permalink in `links`, is a first-class issue. This is the only place a `fix` may be written; checks never write one, because a fix needs the repo and the design intent. `defaultSeverity` is never overwritten — the override stays visible as "was X, now Y (by whom)", and moving severity requires `why`. THE LAW: an issue is one fix, in one place, by one person — so `type` and `where` are required, and REFUSED if (a) the title is still the one the check wrote, (b) the title names this tool\'s machinery (axe, lighthouse, "the check") or leads with a bare count, or (c) the citations resolve to two different places, which means this is two issues.', inputSchema: { /* * Optional at the schema, still required by `issueWrite` for any write that is not a `patch`. * Zod cannot express "required unless patch", and the function's own refusals say more than a * missing-field error would — see the three throws at the top of `issueWrite`. */ title: z .string() .optional() .describe( 'What the work is, in your words. Name the thing and its state in the site\'s vocabulary: "Resource-card titles are unreadable over the book covers". Never a tool, a check id or what an analyser decided; never lead with a count; never restate the rule. Required, except with `patch`.', ), type: z .enum(['decision', 'code', 'content', 'config']) .optional() .describe( 'Who does the work and what kind of change it is — the axis the work list is grouped by, and the first thing a lead routes on. `decision`: a human must choose before anything can start (not a task, and it must not read like one). `code`: a developer edits a file. `content`: an editor changes a CMS document. `config`: one line in a config, a dashboard or an env var. Not inferable from the category — contrast failing in a component is code, contrast failing because an editor chose a pale colour is content.', ), where: z .string() .optional() .describe( 'The single place the change happens: `components/ui/book/index.tsx:174`, `Sanity → navbar → items[3]`, `next.config.ts headers()`. If you cannot name one, say so in words ("not localised: six failures in six unrelated components") — an explicit refusal is information, an empty field is not. If it is hard to name because there are two places, this is two issues.', ), problem: z.string().optional().describe("What is wrong, in the page's own vocabulary."), why: z .string() .optional() .describe('Why it matters here. Required when severity moves off what the check proposed.'), fix: z .string() .optional() .describe( 'What to change. Read the source before writing this — an 8px dot wants a bigger hit area, not a bigger dot.', ), severity: Severity.optional().describe("Defaults to the first cited finding's own proposal."), kind: FindingKind.optional().describe( 'Defaults to "defect". Use "advice" when doing nothing is a legitimate choice — it never counts and never gates. Use "policy" when a decision is required and the site is defaulting into one.', ), cites: z .array(z.string()) .optional() .describe('Finding fingerprints this is the work for. Omit for an issue with no finding behind it.'), related: z.array(z.string()).optional().describe('Other issue ids sharing a cause, component or fix.'), route: z.string().optional().describe('Route this is about. Omit for site-wide.'), category: z .enum(['bugs', 'seo', 'metadata', 'a11y']) .optional() .describe( 'Which report tab this belongs in. REQUIRED WHEN cites IS EMPTY and pointless otherwise: with citations the tab is derived from the cited findings, so passing it could only contradict the evidence. An uncited issue with no category lands in bugs, which is a fallback rather than an answer.', ), rank: z .number() .int() .optional() .describe( 'Reading order. HIGHER GOES FIRST, and it is sparse on purpose — leave gaps, reuse numbers, and set it on nothing you have no opinion about. Severity is a taxonomy, not a scale: a missing sitemap is not "unlaunchable" so it cannot be a blocker and is obviously not a nit, which is how one review produced 18 major items and then listed them alphabetically under a tile reading "Ranked by urgency". Use 9000 for the two things that block everyone, 7000 for the eighteen that can be done in any order after them, and nothing on the rest — ties are a TRUE statement when the order genuinely does not matter, and inventing an order you do not have is worse. An unranked issue sorts after every ranked one and then by severity, so ranking three tickets answers "what do I do first" without re-ranking the other seventeen.', ), origin: z .enum(['check', 'agent', 'human', 'slack']) .optional() .describe('Defaults to "agent". Use "human" only when they actually decided; human outranks agent.'), by: z.string().optional().describe('Who: "agent", a person, or a Slack handle.'), links: z .array(z.object({ label: z.string(), url: z.string() })) .optional() .describe('Slack permalink, Linear ticket, Figma frame.'), source: z .object({ file: z.string(), line: z.number().int().optional(), component: z.string().optional(), confidence: z.enum(['certain', 'likely', 'needs-review']).optional(), }) .optional() .describe( 'Where the code lives — VERIFIED, unlike the heuristic ref on a finding. Defaults to `certain`, so only pass it once you have read the file.', ), sharedLocation: z .string() .optional() .describe( 'ONLY to override the "citations do not share a location" refusal, naming the one real place. Use it when the per-finding source refs are heuristic noise and you have verified they are one fix. Recorded, and re-derived in the report — so an unsupported claim shows up in the artifact rather than being settled here. If in doubt, split the issue instead.', ), patch: z .boolean() .optional() .describe( 'Change only the fields you pass on an issue that already exists — requires `id`, and `title`/`type`/`where` are not needed because the stored record already has them. This is how you set `rank` or `related` on an issue somebody else wrote: the whole-record write loses any field you forget, and re-sending fifteen fields of another agent\'s issue to change one is how a `sharedLocation` was destroyed. Cannot change `cites` or `route`, which derive the id.', ), id: z.string().optional().describe('The issue to patch. Required with `patch`; ids are derived, never chosen.'), runId: RUN_ID, }, annotations: { readOnlyHint: false, idempotentHint: true }, }, async (input) => { try { return json( await issueWrite(ctx, { ...(input.patch ? { patch: true } : {}), ...(input.id ? { id: input.id } : {}), /* * Passed through as given, including absent. `issueWrite` refuses a non-patch write that * lacks any of the three; a patch supplies a delta and the stored record already has them. */ title: input.title as string, ...(input.type ? { type: input.type } : {}), ...(input.where !== undefined ? { where: input.where } : {}), ...(input.sharedLocation ? { sharedLocation: input.sharedLocation } : {}), ...(input.problem ? { problem: input.problem } : {}), ...(input.why ? { why: input.why } : {}), ...(input.fix ? { fix: input.fix } : {}), ...(input.severity ? { severity: input.severity } : {}), ...(input.kind ? { kind: input.kind } : {}), ...(input.cites ? { cites: input.cites } : {}), ...(input.related ? { related: input.related } : {}), ...(input.route ? { route: input.route } : {}), ...(input.category ? { category: input.category } : {}), /** * **This spread is a THIRD explicitly-built object, and `CLAUDE.md` says there are * two.** The count was wrong, not the warning: a new `Issue` field has to be added * here, in `issueWrite`'s `Issue` literal, *and* in `toWireIssue`'s `WireIssue`, or * it is silently dropped with every test still green. A field was lost at two of * these three in consecutive sessions. * * `!== undefined` and not truthiness, because `rank: 0` is a real rank and `0` is * falsy — the same bug class one layer down from the dropped field. */ ...(input.rank !== undefined ? { rank: input.rank } : {}), ...(input.origin ? { origin: input.origin } : {}), ...(input.by ? { by: input.by } : {}), ...(input.links ? { links: input.links } : {}), ...(input.source ? { source: input.source } : {}), ...(input.runId ? { runId: input.runId } : {}), }), ) } catch (e) { return failure(e) } }, ) registerTool( 'qa_issue_delete', { title: 'Retract an issue', description: 'Remove an issue from this run\'s `global/issues/`. An issue id derives from (cites, title, route), so REVISING a conclusion mints a new record and leaves the old one behind — counted, rendered and shaping the headline. Splitting one wrong issue into six right ones leaves seven without this. The reason is required: an issue that vanished with no account of why is indistinguishable from one nobody ever wrote. If the run has already been pushed, push it again — a retraction is the one thing a push deletes, so the published page follows.', inputSchema: { id: z.string().describe('The issue id to retract. From `qa_issues`.'), reason: z .string() .describe('Why it is being withdrawn — "split into six per-component issues", "the cited finding was a false positive".'), runId: RUN_ID, }, annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true }, }, async (input) => { try { return json( await issueDelete(ctx, { id: input.id, reason: input.reason, ...(input.runId ? { runId: input.runId } : {}), }), ) } catch (e) { return failure(e) } }, ) registerTool( 'qa_set_finished', { title: 'Say the review is over', description: 'Mark a pushed run as final, which removes the "still being reviewed" band from its dashboard page. Call this ONCE, at the very end, after the last issue is written — it is a statement that you have stopped, and nothing can infer it for you: after a first pass issues exist and the review is nowhere near done. A streamed run publishes while you work on it, so until you call this every reader is correctly told the numbers are partial. It writes one column and uploads nothing, so it is not a substitute for a final `qa push`; push first if you have written anything since the last one. Fails if the run was never pushed.', inputSchema: { runId: RUN_ID, label: z .string() .optional() .describe('Store label the run was pushed under. Omit — it defaults to the local store\'s own name, which is what `qa push` used.'), }, /* * Not destructive and not read-only. `idempotentHint` is the interesting one: calling it twice is * the same as calling it once, which is what makes a retry after a dropped connection safe. */ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true }, }, async (input) => { try { return json( await setFinished(ctx, { ...(input.runId ? { runId: input.runId } : {}), ...(input.label ? { label: input.label } : {}), }), ) } catch (e) { return failure(e) } }, ) registerTool( 'qa_prompt', { title: 'Build a brief for whoever does the work', description: 'Turns a selection of this run\'s issues into a document you hand to somebody else — a session opened in the site\'s own repo, a Linear description, a PR body, a developer who was not in the review. It carries each issue\'s write-up, the measurements behind it, what this run never looked at, and the `qa run` / `qa diff` pair that proves a fix landed. NOT for your own consumption: you already hold these issues, and a summary of your own conclusions tells you nothing. `types: ["code"]` is the usual cut — a launch review mixes decisions, content edits and code changes, and only one of the three is a developer\'s. Refused when nothing matches, because a brief with no items in it reads exactly like a clean run.', inputSchema: { runId: RUN_ID, issueIds: z .array(z.string()) .optional() .describe('Only these issues. Omit for every work item in the run.'), types: z .array(z.enum(['decision', 'code', 'content', 'config'])) .optional() .describe('Restrict to these issue types. `["code"]` is the common form.'), severities: z .array(Severity) .optional() .describe('Restrict to these severities.'), workOnly: z .boolean() .optional() .describe('The default, and named explicitly. Notes — advice, transparency and ungraded — owe nobody a response.'), all: z .boolean() .optional() .describe( 'Add the reviewer\'s coverage record back: the advice, transparency and ungraded items. They say what was examined rather than asking for work, so a handover holds them back — but they are also what stops a gap reading as a clean bill of health, so read them before deciding a run is done.', ), verifyUrl: z .string() .optional() .describe('The URL the reader will re-measure against, if not the audited one — a dev server, usually.'), }, annotations: { readOnlyHint: true }, }, async (input) => { try { return json( await promptFor(ctx, { ...(input.runId ? { runId: input.runId } : {}), ...(input.issueIds ? { issueIds: input.issueIds } : {}), ...(input.types ? { types: input.types } : {}), ...(input.severities ? { severities: input.severities } : {}), ...(input.workOnly !== undefined ? { workOnly: input.workOnly } : {}), ...(input.all !== undefined ? { all: input.all } : {}), ...(input.verifyUrl ? { verifyUrl: input.verifyUrl } : {}), }), ) } catch (e) { return failure(e) } }, ) registerTool( 'qa_schema', { title: 'Describe the finding and artifact contract', description: 'The schema version, severity and confidence vocabularies, and the artifact layout. Read this if you are unsure what a field means.', inputSchema: {}, annotations: { readOnlyHint: true }, }, async () => { try { return json(schemaPayload()) } catch (e) { return failure(e) } }, ) return server }