#!/usr/bin/env bun import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js' // Type-only, so the native-free `run` barrel is not pulled into this module's runtime graph. import type { RunStore } from '@basementstudio/qa-engine/run' import { createServer, type ServerOptions } from './server' /** * `qa-mcp` — stdio entry point. * * Registered as a Claude Code MCP server so an agent working in a project repo * can query runs that already happened. Reads `.qa` relative to the process cwd * by default, which is what makes it work with zero configuration in a client * repo — the footprint added to that repo stays at nothing. * * **Nothing may be written to stdout.** stdout *is* the protocol transport on * stdio, so a stray `console.log` corrupts the stream and the client sees a parse * error rather than a message. Diagnostics go to stderr. * * ## `--mirror` — serving the snapshots that are on the dashboard * * The default store is the local `.qa`, and that is the right default: it is where `qa run` wrote, it * is where the review loop writes back, and it needs no credential. But work that has been pushed * lives in Postgres and is what a teammate sees on the dashboard — so an agent asked "what are the * open issues for native.security" had no way to reach it without a checkout of somebody else's * audit. `--mirror` points every read at that store instead. * * **It is opt-in, and that is a decision rather than an omission.** Defaulting to the mirror whenever * a `DATABASE_URL` happened to be in the environment would silently change what the plugin answers * with — and worse, the mirror **refuses writes at the seam** (`NeonRunStorage.writeText` throws), so * `qa_issue_write` would start failing for everybody who reviews locally today. Reading somebody * else's store and losing the ability to record a judgement are both fine when asked for and both * unacceptable as a surprise. * * The connection string is resolved through the same ladder `qa push` uses * (`@basementstudio/qa-engine/run/database-url`) — `--db` → `QA_DATABASE_URL` → this checkout's * environment or env file → `vercel env pull`. One ladder for the writer and the reader, because two * would be two answers to one question; the reasons for the order, and the gate that keeps a * teammate's own `DATABASE_URL` out of it, are in that module. * * The resolved endpoint is announced on stderr, host only. Which store is being served is the first * question a wrong answer raises, and "the mirror" and "the `.qa` next to me" are indistinguishable * from the results alone. */ export { createServer } from './server' export * from './http' export * from './tools' export * from './review-payload' export { authoringContract, type AuthoringContractOptions } from './authoring-contract' /* `qa mcp ` needs it too — it calls the tool functions directly and recorded nothing until it did. */ export { KIND_OF_TOOL, actorId, makeRecorder, type CallRecord } from './activity-record' export interface ParsedArgs { opts: ServerOptions /** Serve the Neon mirror rather than a filesystem store. */ mirror?: boolean /** `--db`, passed through to the ladder's first rung. */ databaseUrl?: string /** The `store` label to read — what `qa push --label` wrote under. */ label?: string } /** * Exported for the test, not for callers. * * `--db` and `--label` *imply* `--mirror`, and an implication is exactly the kind of rule that reads * as obvious and regresses silently: dropping it leaves `qa-mcp --db ` serving the local `.qa` * and answering every question about the pushed run with "no runs", which is indistinguishable from * that run never having been pushed. */ export function parseArgs(argv: string[]): ParsedArgs | { help: true } { const parsed: ParsedArgs = { opts: {} } for (let i = 0; i < argv.length; i++) { const arg = argv[i] if (arg === '--help' || arg === '-h') return { help: true } if (arg === '--store' || arg === '--out') { const value = argv[++i] if (value) parsed.opts.storeRoot = value } else if (arg === '--cwd') { const value = argv[++i] if (value) parsed.opts.cwd = value } else if (arg === '--run') { const value = argv[++i] if (value) parsed.opts.defaultRunId = value } else if (arg === '--mirror') { parsed.mirror = true } else if (arg === '--db') { const value = argv[++i] // A connection string is an unambiguous statement of intent, so it implies `--mirror`: asking // for a database and getting the local filesystem read would be a typo, never an intent. if (value) { parsed.databaseUrl = value parsed.mirror = true } } else if (arg === '--label') { const value = argv[++i] if (value) { parsed.label = value parsed.mirror = true } } } return parsed } /** * Build the dashboard-backed store, or explain why it could not. * * Imported lazily for a reason that is not style: `database-url.ts` calls `Bun.which`/`Bun.spawn` and * `neon.ts` pulls `@neondatabase/serverless`, and neither belongs in the import graph of a default * stdio start that is going to read the filesystem. The dashboard imports `./http` from this package * under webpack, where `Bun` is undefined. */ async function mirrorStore(args: ParsedArgs) { const { resolveDatabaseUrl, describeAttempts } = await import('@basementstudio/qa-engine/run/database-url') const { neonRunStore } = await import('@basementstudio/qa-engine/run/neon') const resolved = await resolveDatabaseUrl(args.databaseUrl ? { flag: args.databaseUrl } : {}) if (!resolved) { console.error('[qa-mcp] no database. every place it looked:') for (const line of describeAttempts()) console.error(line) console.error('\n the usual fix is `vercel login`, or pass one outright with --db ') return undefined } for (const note of resolved.notes) console.error(`[qa-mcp] ${note}`) return { store: neonRunStore({ url: resolved.url, ...(args.label ? { store: args.label } : {}) }), /* * Carried so `qa_set_finished` writes to **this** database rather than re-resolving its own. It was * walking the environment ladder independently, so a server started with `--db ` served * every read from the preview and wrote the finish flag to production. See `ToolContext.databaseUrl`. */ url: resolved.url, /* Host only. A connection string is a credential and this line goes into somebody's log. */ description: `neon:${args.label ?? '.qa'} on ${resolved.host} — via ${resolved.detail}`, } } /** * The `dashboard: true` resolver — memoised, and resolved on first use. * * **This is what makes the plugin able to answer "grab the xmcp issues from the dashboard".** * `plugin/.mcp.json` starts this binary with no arguments and always will, so anything reachable only * behind a flag is unreachable to the people the plugin is for. The store is therefore always *offered* * and never *paid for*: nothing here runs until a tool asks for it, so a session that only reads the * local `.qa` never touches Vercel or Postgres. * * Memoised on the promise rather than the value, so two tools in one turn share one resolution instead * of racing two `vercel env pull` subprocesses. A **failure is not cached** — the usual cause is a * Vercel login that is missing, and someone told to run `vercel login` should be able to retry without * restarting the server. */ function dashboardResolver(args: ParsedArgs): () => Promise { let pending: Promise | undefined return () => { if (!pending) { pending = mirrorStore(args).then((resolved) => { if (!resolved) { throw new Error( 'could not reach the dashboard: no connection string resolved. `qa push` and this share one ' + 'resolver — the usual fix is `vercel login`, or start qa-mcp with `--db `. ' + 'The local store is readable without `dashboard`.', ) } console.error(`[qa-mcp] dashboard: ${resolved.description}`) return resolved.store }) pending.catch(() => { pending = undefined }) } return pending } } // Only start a transport when executed directly; importing this module for tests // must not attach one to the test runner's stdio. if (import.meta.main) { const parsed = parseArgs(process.argv.slice(2)) if ('help' in parsed) { console.error(`qa-mcp — MCP server over stored qa runs usage: qa-mcp [--cwd ] [--store ] [--run ] qa-mcp --mirror [--db ] [--label ] [--run ] --cwd project root containing .qa (default: process cwd) --store override the store location entirely --run pin every tool to one run (default: latest) --mirror make the DASHBOARD the default store rather than an option, for a session that is only ever going to read pushed snapshots. Rarely needed: every read tool already takes \`dashboard: true\`, and it costs nothing until something asks for it. --db connection string (implies --mirror). Otherwise resolved from QA_DATABASE_URL, this checkout's env, or \`vercel env pull\`. --label which pushed store to read (implies --mirror; default .qa) Both stores are served with no flags at all. The local .qa is the default; pass \`dashboard: true\` to any read tool for the snapshots on the dashboard. Reads may come from either; the write tools always address the local artifact, because the mirror is overwritten by the next \`qa push\`. read: qa_runs, qa_projects, qa_run, qa_findings, qa_findings_md, qa_diff, qa_facts, qa_screenshot, qa_screenshots, qa_issues, qa_prompt, qa_schema write: qa_issue_write, qa_issue_delete, qa_waive, qa_set_finished, qa_fetch (the only one that reaches the network; scoped to the site under review) `) process.exit(0) } const { opts } = parsed let description = opts.storeRoot ?? `${opts.cwd ?? process.cwd()}/.qa` /* * Always offered, never paid for. Nothing in here runs until a tool passes `dashboard: true`, so a * plugin start costs exactly what it did before — and the dashboard stops being something only a * flag could reach, which is what made it unreachable to everybody using the plugin as it ships. */ opts.dashboard = dashboardResolver(parsed) if (parsed.mirror) { const mirror = await mirrorStore(parsed) /* * Exit rather than fall back to the filesystem. A server *asked* to make the dashboard its default * and quietly serving the local `.qa` would answer every question about another site's audit with * "no runs", which is indistinguishable from that site never having been pushed. Note the contrast * with `dashboard: true`, which fails one call rather than the process: there the local store is * still the useful default, so taking the server down would be the wrong trade. */ if (!mirror) process.exit(1) opts.store = mirror.store opts.databaseUrl = mirror.url description = mirror.description } const server = createServer(opts) await server.connect(new StdioServerTransport()) // stderr, not stdout — stdout is the transport. console.error(`[qa-mcp] serving runs from ${description}`) }