Skip to content
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion docs/content/9.extending.md
Original file line number Diff line number Diff line change
Expand Up @@ -450,7 +450,9 @@ export default defineDoctorConfig({
- **Reports:** `sources` in the JSON report lists each source with its `targets`. The rerun command repeats the flags from `toOptions`, with `secret` values replaced by `<redacted>`.
- **Network:** use the `fetch` from the context, which tests and other runtimes can replace through the run's `fetch` option.

A source's `name` shares one namespace with Runtime Evidence contributors.
A source the run reads can't share its `name` with a Runtime Evidence contributor, because both write `project.runtimeEvidence.<name>`.

Doctor's own [live MCP check](/mcp) is the `mcp` Evidence Source, which is why its flags are `--mcp-url` and `--mcp-header`. In code, pass its input as `sources: { mcp: [{ url, headers }] }`.

## Rule inputs

Expand Down
2 changes: 1 addition & 1 deletion docs/content/9.mcp.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ Source shows the tools as written; a running server shows the tools a client get
pnpm vite-doctor . --mcp-url http://localhost:3000/mcp
```

Run it in an empty directory to check only the server. The text report says `Checked: MCP server <origin>`. JSON and agent reports name the server in `subject.mcpServers`; JSON has `framework: null`, while the agent report has `project: null`. Doctor activates only the MCP Rule Pack and lists the server's origin as that pack's `activatedBy`. Rerun commands keep the original scan directory and repeat `--mcp-url` without adding `--framework`.
Run it in an empty directory to check only the server. The text report says `Checked: MCP server <origin>`. JSON and agent reports name the server in `subject.live`, as `{ source: "mcp", target: "<origin>" }`; JSON has `framework: null`, while the agent report has `project: null`. Doctor activates only the MCP Rule Pack and lists the server's origin as that pack's `activatedBy`. Rerun commands keep the original scan directory and repeat `--mcp-url` without adding `--framework`.

Both flags repeat. Every `--mcp-header` goes to every `--mcp-url`:

Expand Down
5 changes: 5 additions & 0 deletions src/builtin-sources.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import type { EvidenceSource } from "./core/primitives.js";
import { mcpEvidenceSource } from "./mcp/evidence.js";

/** Evidence Sources Doctor ships. The CLI declares their flags so `--help` lists them. */
export const builtinEvidenceSources: readonly EvidenceSource[] = [mcpEvidenceSource];
37 changes: 21 additions & 16 deletions src/cli-main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,17 @@ import {
type DoctorPresentation,
} from "./core/internal/agent-runtime.js";
import { applyDoctorOptions, stringFlag } from "./core/internal/cli.js";
import { evidenceSourceFlags, evidenceSourceInputs } from "./core/internal/evidence-sources.js";
import {
evidenceSourceFlags,
evidenceSourceInputs,
validateEvidenceSources,
} from "./core/internal/evidence-sources.js";
import { githubAnnotations } from "./core/internal/github-annotations.js";
import { readViteConfigDoctor } from "./core/internal/vite-config-doctor.js";
import { findViteConfigFile } from "./core/internal/vite-config-file.js";
import type { DoctorProcessStatus } from "./doctor-process/client.js";
import { DOCTOR_PROCESS_ENV } from "./doctor-process/protocol.js";
import { assertAbsoluteMcpUrl } from "./mcp/evidence.js";
import { builtinEvidenceSources } from "./builtin-sources.js";
import { viteDoctorVersion } from "./version.js";

type MetadataReportFormat = Exclude<DoctorReportFormat, "sarif">;
Expand All @@ -44,8 +48,8 @@ const frameworks = new Set<NonNullable<DoctorRunOptions["framework"]>>([
]);
const severities = new Set<NonNullable<DoctorRunOptions["severity"]>>(["error", "warn", "info"]);
const analyses = new Set(["dead-code", "graph", "dupes", "health"]);
// cac's `type: [String]` fills an absent array option with "undefined" once another one is set.
const repeatableOptions = new Set(["mcpUrl", "mcpHeader"]);
const builtinSourceFlags = evidenceSourceFlags(builtinEvidenceSources);
const builtinSourceFlagNames = new Set(builtinSourceFlags.map(({ flag }) => flag));
const sourceArgumentBoundary = "--doctorSourceArgument=1";

class CliConfigError extends Error {
Expand Down Expand Up @@ -306,7 +310,7 @@ function applyHostExtensions(

function validateSingleValueOptions(cli: ReturnType<typeof cac>): void {
for (const option of [...cli.globalCommand.options, ...(cli.matchedCommand?.options ?? [])]) {
if (option.isBoolean || option.config.type || repeatableOptions.has(option.name)) continue;
if (option.isBoolean || option.config.type) continue;
if (!option.names.some((name) => Array.isArray(cli.options[name]))) continue;
throw new Error(`Option --${kebabFlag(option.name)} may only be provided once.`);
}
Expand All @@ -322,7 +326,7 @@ function splitEvidenceSourceArgs(
for (const command of [cli.globalCommand, ...cli.commands]) {
for (const option of command.options) {
for (const flag of option.rawName.split(/[,\s]+/)) {
if (flag.startsWith("-")) reserved.add(flag);
if (flag.startsWith("-") && !builtinSourceFlagNames.has(flag)) reserved.add(flag);
}
}
}
Expand Down Expand Up @@ -376,7 +380,10 @@ async function applyEvidenceSourceFlags(
known.add(flag);
}
for (const flag of source.keys()) if (!known.has(flag)) throw unknownOption(flag);
const inputs = evidenceSourceInputs(declarations, source);
const inputs = evidenceSourceInputs(
declarations.filter(({ source }) => !builtinEvidenceSources.includes(source)),
source,
);
if (inputs) options.sources = { ...options.sources, ...inputs };
}

Expand Down Expand Up @@ -422,14 +429,6 @@ function addDoctorRunCommand(
.option("--full", "Print the whole text or agent report, without a Report Budget.")
.option("--config <path>", "Explicitly load an executable Doctor config.")
.option("--host-extensions", hostExtensionsHelp)
.option(
"--mcp-url <url>",
"Read tools/list from this MCP server as Runtime Evidence. Repeatable.",
)
.option(
"--mcp-header <header>",
'Request header for every --mcp-url, as "Name: value". Repeatable.',
)
.option("--watch", "Rerun Doctor when project files change.")
.option(
"--server",
Expand Down Expand Up @@ -458,6 +457,11 @@ function addDoctorRunCommand(
applyHostExtensions(runOptions, surface, options);
validateCliRunOptions(runOptions);
validateReportBudget(options, format);
const builtinInputs = evidenceSourceInputs(builtinSourceFlags, evidenceArgs().source);
if (builtinInputs) {
await validateEvidenceSources(builtinEvidenceSources, builtinInputs);
runOptions.sources = builtinInputs;
}
const report = {
cwd,
formatFlag: stringFlag(options.format) as DoctorReportFormat,
Expand Down Expand Up @@ -489,6 +493,8 @@ function addDoctorRunCommand(
// cac defaults negated flags to true, which renders as `(default: true)` on `--no-cache`
// and makes every run look like an explicit `--cache` in rerun commands.
for (const option of command.options) if (option.negated) option.config.default = undefined;
for (const { flag, definition } of builtinSourceFlags)
command.option(`${flag} <${definition.value ?? "value"}>`, definition.help);
}

async function watchDoctorCommand(
Expand Down Expand Up @@ -707,7 +713,6 @@ function validateReportBudget(flags: Record<string, unknown>, format: DoctorRepo
}

function validateCliRunOptions(options: DoctorRunOptions): void {
for (const target of options.mcp ?? []) assertAbsoluteMcpUrl(target.url);
if (options.updateBaseline && !options.baseline)
throw new Error("--update-baseline requires --baseline <file>.");
if (options.framework && !frameworks.has(options.framework)) {
Expand Down
6 changes: 0 additions & 6 deletions src/core/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import type {
ProjectInfo,
RuntimeTarget,
} from "./primitives.js";
import type { McpServerTarget } from "../mcp/evidence.js";
export type {
DoctorConfigOverride,
DoctorRuleConfig,
Expand Down Expand Up @@ -61,11 +60,6 @@ export interface DoctorRunOptions {
*/
hostExtensions?: boolean;
runtimeTarget?: RuntimeTarget;
/**
* MCP servers whose `tools/list` Vite Doctor reads as `mcp` Runtime Evidence. Headers can carry
* tokens, so this stays out of Doctor config files.
*/
mcp?: McpServerTarget[];
/**
* Inputs for Evidence Sources, keyed by source name. A source without an input is not read.
* Inputs can carry tokens, so they stay out of Doctor config files.
Expand Down
34 changes: 0 additions & 34 deletions src/core/internal/cli.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import type { DoctorRunOptions } from "../config.js";
import { isMcpHeaderName } from "@loadsheet/mcp";

export function applyDoctorOptions(
options: DoctorRunOptions,
Expand Down Expand Up @@ -29,39 +28,6 @@ export function applyDoctorOptions(
options.format = (stringFlag(flags.format) as DoctorRunOptions["format"]) ?? options.format;
if (flags.full) options.maxChars = Number.POSITIVE_INFINITY;
if (flags.maxChars !== undefined) options.maxChars = Number(flags.maxChars);
options.mcp = parseMcpFlags(flags.mcpUrl, flags.mcpHeader) ?? options.mcp;
}

/** `--mcp-url` and `--mcp-header` are repeatable; every header applies to every URL. */
function parseMcpFlags(urls: unknown, headers: unknown): DoctorRunOptions["mcp"] {
const urlList = listFlag(urls, "--mcp-url");
const headerList = listFlag(headers, "--mcp-header");
if (!urlList.length) {
if (headerList.length) throw new Error("--mcp-header requires --mcp-url <url>.");
return undefined;
}
const parsed = new Map<string, string>();
for (const header of headerList) {
const colon = header.indexOf(":");
const name = colon === -1 ? "" : header.slice(0, colon).trim();
if (!isMcpHeaderName(name))
throw new Error(
'--mcp-header must look like "Name: value", such as "Authorization: Bearer <token>".',
);
parsed.set(name, header.slice(colon + 1).trim());
}
return urlList.map((url) => ({
url,
...(parsed.size ? { headers: Object.fromEntries(parsed) } : {}),
}));
}

function listFlag(value: unknown, flag: string): string[] {
const values = value === undefined ? [] : Array.isArray(value) ? value : [value];
return values.map((item) => {
if (typeof item !== "string" || !item) throw new Error(`${flag} requires a value.`);
return item;
});
}

function parseExtends(value: string | undefined): DoctorRunOptions["extends"] {
Expand Down
19 changes: 14 additions & 5 deletions src/core/internal/evidence-sources.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,10 +98,10 @@ export async function validateEvidenceSources(
export async function collectEvidenceSources(
project: ProjectInfo,
requested: readonly RequestedSource[],
fetch: typeof globalThis.fetch = globalThis.fetch,
contributeRuntimeEvidence: () => Promise<void>,
fetch: typeof globalThis.fetch = (input, init) => globalThis.fetch(input, init),
): Promise<EvidenceSourceRun[]> {
const runs: EvidenceSourceRun[] = [];
for (const { source, input } of requested) {
async function collect(source: EvidenceSource, input: unknown): Promise<EvidenceSourceRun> {
const { name } = source;
const result = await source.collect(input, { project, fetch });
project.runtimeEvidence = { ...project.runtimeEvidence, [name]: result.evidence };
Expand All @@ -111,12 +111,21 @@ export async function collectEvidenceSources(
...result.gaps.map((gap) => ({ source: name, files: [], ...gap })),
];
}
runs.push({
return {
name,
label: source.label,
targets: result.targets ?? [],
args: sourceArgs(source, input),
});
};
}
const earlyRuns = new Map<string, EvidenceSourceRun>();
for (const { source, input } of requested) {
if (source.beforeRuntimeEvidence) earlyRuns.set(source.name, await collect(source, input));
}
await contributeRuntimeEvidence();
const runs: EvidenceSourceRun[] = [];
for (const { source, input } of requested) {
runs.push(earlyRuns.get(source.name) ?? (await collect(source, input)));
}
return runs;
}
Expand Down
29 changes: 21 additions & 8 deletions src/core/internal/scan-session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -165,9 +165,23 @@ export async function createScanSession(
sessionBase.config = config;
const extensions = [...(config.extensions ?? []), ...(options.extensions ?? [])];
const registry = await collectRulePacks(extensions);
// A source's evidence is stored under its name, next to what contributors return. Only a source
// the run reads can clash, so an Extension may still contribute evidence under a builtin name.
assertUniqueContributors(
[
...registry.runtimeEvidenceContributors,
...registry.sources.filter((source) => options.sources?.[source.name] !== undefined),
],
"Runtime Evidence",
);
const requestedSources = await validateEvidenceSources(registry.sources, options.sources);
await applyProjectContributions(project, registry);
const evidenceSources = await collectEvidenceSources(project, requestedSources, options.fetch);
await applyProjectInventory(project, registry);
const evidenceSources = await collectEvidenceSources(
project,
requestedSources,
() => applyRuntimeEvidence(project, registry),
options.fetch,
);
if (options.affectedFiles && fullRunWhen?.(project)) {
options = { ...options, affectedFiles: undefined };
sessionBase.options = options;
Expand Down Expand Up @@ -425,8 +439,7 @@ export async function collectRulePacks(inputs: readonly DoctorExtensionInput[]):
assertUniqueContributors(inventoryContributors, "Project Inventory");
const sources = extensions.flatMap((extension) => extension.sources ?? []);
assertEvidenceSourceNames(sources);
// A source's evidence is stored under its name, next to what contributors return.
assertUniqueContributors([...runtimeEvidenceContributors, ...sources], "Runtime Evidence");
assertUniqueContributors(sources, "Runtime Evidence");
return {
packs,
rules: packs.flatMap((pack) => pack.rules),
Expand All @@ -449,14 +462,14 @@ function assertUniqueContributors(
}
}

async function applyProjectContributions(
project: ProjectInfo,
registry: RuleRegistry,
): Promise<void> {
async function applyProjectInventory(project: ProjectInfo, registry: RuleRegistry): Promise<void> {
for (const contributor of registry.inventoryContributors) {
const contribution = await contributor.contribute(project);
project.inventory = { ...project.inventory, [contributor.name]: contribution };
}
}

async function applyRuntimeEvidence(project: ProjectInfo, registry: RuleRegistry): Promise<void> {
for (const contributor of registry.runtimeEvidenceContributors) {
const contribution = await contributor.contribute(project);
project.runtimeEvidence = { ...project.runtimeEvidence, [contributor.name]: contribution };
Expand Down
12 changes: 10 additions & 2 deletions src/core/primitives.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1602,6 +1602,8 @@ export interface DoctorRunResult {
rulePacks?: RulePackActivation[];
/** Evidence Sources the run read because it was given an input for them. */
evidenceSources?: EvidenceSourceRun[];
/** Live targets supplied by contributors rather than read through Evidence Sources. */
contributedLiveTargets?: LiveTargetGroup[];
graph?: {
files: number;
importEdges: number;
Expand Down Expand Up @@ -1638,6 +1640,8 @@ export interface EvidenceSource<Input = any> {
name: string;
/** What a target is, such as "MCP server". */
label: string;
/** Collect after Project Inventory but before Runtime Evidence contributors. Defaults to false. */
beforeRuntimeEvidence?: boolean;
/** CLI flags, keyed by option name in camelCase. */
options?: Record<string, EvidenceSourceOption>;
/** Builds the input from CLI flag values, keyed by option name. Throws on a value it can't use. */
Expand Down Expand Up @@ -1681,11 +1685,15 @@ export interface EvidenceSourceResult {
gaps?: Array<{ message: string; instanceKey?: string }>;
}

/** An Evidence Source a Doctor Run read. */
export interface EvidenceSourceRun {
/** Live targets grouped by the name and display label of their source. */
export interface LiveTargetGroup {
name: string;
label: string;
targets: string[];
}

/** An Evidence Source a Doctor Run read. */
export interface EvidenceSourceRun extends LiveTargetGroup {
/** CLI arguments that read the source again, with secret values redacted. */
args: string[];
}
Expand Down
Loading
Loading