@mcpjam/vitest 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,133 @@
1
+ # @mcpjam/vitest
2
+
3
+ Run MCPJam eval suites inside vitest. One test per eval case, plus a gate test
4
+ that fails the build when the run breaches your policy.
5
+
6
+ ```bash
7
+ npm install -D @mcpjam/vitest vitest
8
+ ```
9
+
10
+ ## The flagship: gate a hosted corpus in CI
11
+
12
+ Pull your hosted suite once with `mcpjam eval pull`, commit the lock, and run
13
+ it locally on every change. The lock is the reproducibility record — the same
14
+ cases, graded the same way, until you pull again.
15
+
16
+ ```ts
17
+ // evals/refunds.test.ts
18
+ import { readFile } from "node:fs/promises";
19
+ import { loadCorpusFromLock } from "@mcpjam/sdk";
20
+ import { describeEvalSuite } from "@mcpjam/vitest";
21
+ import { buildExecutor } from "./support/executor.js";
22
+
23
+ const lock = JSON.parse(await readFile("mcpjam-evals.lock.json", "utf8"));
24
+ const corpus = loadCorpusFromLock(lock);
25
+
26
+ describeEvalSuite("refund flows", corpus.toEvalSuite(), {
27
+ factory: () => buildExecutor(),
28
+ run: { iterations: 25 },
29
+ gate: {
30
+ minimumPassRate: 0.9,
31
+ maximumP95LatencyMs: 30_000,
32
+ noGatingScoreErrors: true,
33
+ },
34
+ });
35
+ ```
36
+
37
+ `vitest run` then reports one test per hosted case, titled with its dashboard
38
+ id:
39
+
40
+ ```
41
+ ✓ refund flows > refunds a duplicate charge [case_8Kd2]
42
+ ✓ refund flows > refuses a refund past the window [case_9Fa1]
43
+ × refund flows > eval gate
44
+ → Gate: FAILED (score integrity: valid)
45
+ PASS minimumPassRate: 47/50 iterations passed [threshold 0.9]
46
+ FAIL maximumP95LatencyMs: p95 e2e latency 41200ms [threshold 30000]
47
+ ```
48
+
49
+ ## API
50
+
51
+ ### `describeEvalSuite(name, suite, options)`
52
+
53
+ Registers a `describe` containing one `it` per eval case, and — when `gate` is
54
+ given — a final `it` for the policy.
55
+
56
+ | option | meaning |
57
+ | --- | --- |
58
+ | `executor` | A ready `HostExecutor`. |
59
+ | `factory` | Builds one inside `beforeAll`, for an executor that must connect first. Mutually exclusive with `executor`. |
60
+ | `run` | `EvalTestRunOptions`: `iterations`, `concurrency`, `timeoutMs`, `mcpjam`, … |
61
+ | `gate` | A `GatePolicy`. Omit to register no gate test. |
62
+ | `hookTimeoutMs` | Timeout for the whole suite run. Default 300000. |
63
+
64
+ ### `testEval(test, options)`
65
+
66
+ The single-test seat, for a file that owns one eval and wants no suite.
67
+
68
+ ```ts
69
+ import { EvalTest } from "@mcpjam/sdk";
70
+ import { mintCaseId } from "@mcpjam/sdk/contract";
71
+ import { testEval } from "@mcpjam/vitest";
72
+
73
+ // `id` is the case's identity and is required. Mint it ONCE (`mintCaseId()`
74
+ // prints one) and commit the literal — a case renamed from "Refund flow" to
75
+ // "Refunds" keeps its history because the id, not the name, is what history
76
+ // joins on. Never call `mintCaseId()` inline: an id regenerated on every run
77
+ // is not an identity.
78
+ testEval(
79
+ new EvalTest({
80
+ id: "c_V1StGXR8Z5jdHi6Bmy",
81
+ name: "refunds a duplicate charge",
82
+ test: async (executor) => {
83
+ const result = await executor.run("refund the duplicate charge");
84
+ return result.hasToolCall("create_refund");
85
+ },
86
+ }),
87
+ { factory: () => buildExecutor(), run: { iterations: 25 } }
88
+ );
89
+ ```
90
+
91
+ ### `planEvalSuite(suite, options)`
92
+
93
+ Pure. Returns the titles that *would* be registered — useful for asserting your
94
+ own naming, or for building a different harness on the same rules. Each entry
95
+ also carries `caseId` (the case's declared id) so a custom reporter can key on
96
+ identity rather than on a title that gets renamed.
97
+
98
+ ### `runAndAssertCase(run, testName, failureReport?)` · `gateFailureMessage(error)`
99
+
100
+ The two pure pieces the generated tests are built from, exported so you can
101
+ assert the failing path from an ordinary test.
102
+
103
+ ## How it works, and why
104
+
105
+ **One run, many tests.** `suite.run()` is called once, in `beforeAll`. That is
106
+ not an optimization: the suite uploads a single hosted run, computes one
107
+ aggregate evaluation-config hash, and executes cases sequentially. Calling it
108
+ per test would produce N hosted runs and N aggregate hashes. Each `it` is an
109
+ assertion over that one already-computed result, so per-test timeouts are
110
+ irrelevant — the timeout that matters is `hookTimeoutMs`.
111
+
112
+ **A wrapper, not a reporter.** A vitest Reporter observes tests; it cannot
113
+ decide what a test *is*. Evals need the opposite, so failures land on named
114
+ tests in every vitest UI, watch mode and CI annotation that already exists. A
115
+ reporter would also have no seat for the gate, which is a verdict over the
116
+ whole run rather than any one case.
117
+
118
+ **The gate is its own test.** A run where every case passed can still breach a
119
+ latency or score-integrity gate. Giving the policy a named test means CI shows
120
+ *which* question failed instead of a bare non-zero exit.
121
+
122
+ **Scenario ids are explicit.** A case's title gets ` [caseId]` only when the
123
+ test carries an `externalCaseId` — never inferred from the test name. The
124
+ declared `id` is deliberately *not* what the suffix shows: that suffix is the
125
+ handle people grep the hosted dashboard with, so it keeps carrying
126
+ `externalCaseId`. The declared id is exposed on `planEvalSuite`'s `caseId`
127
+ instead.
128
+
129
+ ## Supported vitest versions
130
+
131
+ Declared as a peer dependency: `>=3.2.0 <4`. Tested against **3.2.4**, and the
132
+ packaged tarball is exercised against it in CI on every run. **Vitest 4 is
133
+ unvalidated** — the peer range excludes it deliberately rather than optimistically.
@@ -0,0 +1,122 @@
1
+ import { HostExecutor, EvalTestRunOptions, GatePolicy, EvalSuite, EvalRunResult, EvalTest } from '@mcpjam/sdk';
2
+
3
+ /**
4
+ * Run MCPJam eval suites inside vitest.
5
+ *
6
+ * --- A wrapper, not a reporter ---
7
+ *
8
+ * The obvious alternative was a custom vitest Reporter. This is deliberately
9
+ * not that. A reporter observes tests; it cannot decide what a test IS. Evals
10
+ * need the opposite: one `it` per eval case so failures land on named tests in
11
+ * every vitest UI, watch mode and CI annotation that already exists, with no
12
+ * bespoke output for anyone to learn. A reporter would also have no seat for
13
+ * the gate, which is a verdict over the whole run rather than any one case.
14
+ *
15
+ * --- One run, many tests ---
16
+ *
17
+ * `suite.run()` is called ONCE, in `beforeAll`. That is not an optimization:
18
+ * the suite uploads a single hosted run, computes one aggregate evaluation
19
+ * config hash, and executes its cases sequentially. Calling it per `it` would
20
+ * produce N hosted runs, N aggregate hashes, and a concurrency pattern the
21
+ * suite explicitly avoids. The `it`s then read that one result.
22
+ *
23
+ * So an eval case's `it` is an ASSERTION over an already-computed result, not
24
+ * the thing that runs it. Vitest timeouts on those tests are therefore
25
+ * irrelevant; the timeout that matters is the hook's, which is why it defaults
26
+ * to five minutes and is configurable.
27
+ *
28
+ * --- The gate is its own test ---
29
+ *
30
+ * The per-case tests answer "did this case pass". The gate answers "does this
31
+ * run satisfy the policy", which is a different question with a different
32
+ * failure mode — a run where every case passed can still breach a latency or
33
+ * score-integrity gate. Giving it a named `it` means CI shows WHICH question
34
+ * failed instead of a bare non-zero exit.
35
+ */
36
+
37
+ /** Five minutes. An eval suite is not a unit test. */
38
+ declare const DEFAULT_HOOK_TIMEOUT_MS = 300000;
39
+ /** The vitest test title used for the policy gate. */
40
+ declare const GATE_TEST_TITLE = "eval gate";
41
+ type EvalCasePlan = {
42
+ /** The vitest test title. */
43
+ title: string;
44
+ /** The suite key this case's result is recorded under. */
45
+ testName: string;
46
+ /** The hosted case id, when this case came from a hosted corpus. */
47
+ scenarioId?: string;
48
+ /**
49
+ * The case's DECLARED id (`EvalTestConfig.id`).
50
+ *
51
+ * Surfaced so a CI reporter can key a case by its identity rather than by a
52
+ * title that gets renamed. Deliberately NOT used in the vitest title: the
53
+ * `[scenarioId]` suffix is the hosted-dashboard grep handle and still rides
54
+ * `externalCaseId`, so changing what the suffix carries would break the greps
55
+ * that exist.
56
+ */
57
+ caseId?: string;
58
+ };
59
+ type EvalSuitePlan = {
60
+ cases: EvalCasePlan[];
61
+ /** Present only when a gate policy was supplied. */
62
+ gateTestTitle?: string;
63
+ };
64
+ /**
65
+ * Decide the vitest titles for a suite, without registering anything.
66
+ *
67
+ * Pure and exported so the naming rules are testable on their own. A hosted
68
+ * case's id is appended so a test title is greppable back to the dashboard row
69
+ * it came from — explicitly, never inferred from the test name.
70
+ */
71
+ declare function planEvalSuite(suite: EvalSuite, options?: {
72
+ gate?: GatePolicy;
73
+ }): EvalSuitePlan;
74
+ /**
75
+ * Turn one case's recorded result into a pass or a thrown failure.
76
+ *
77
+ * Exported so the RED path is testable inside an ordinary `it` — a generated
78
+ * failing test cannot be asserted on from within the same run without failing
79
+ * the run itself.
80
+ */
81
+ declare function runAndAssertCase(run: EvalRunResult | undefined, testName: string, failureReport?: () => string): void;
82
+ /**
83
+ * Render a gate failure for a test message.
84
+ *
85
+ * Duck-typed as well as `instanceof`-checked. A published wrapper can end up
86
+ * beside a second copy of `@mcpjam/sdk` — a mismatched transitive range, a
87
+ * pnpm layout — and `instanceof` silently fails across copies. Falling back to
88
+ * the message would drop the per-gate table, which is the whole reason the
89
+ * error carries a report.
90
+ */
91
+ declare function gateFailureMessage(error: unknown): string;
92
+ type EvalSuiteVitestOptions = {
93
+ /** A ready executor. Mutually exclusive with `factory`. */
94
+ executor?: HostExecutor;
95
+ /** Built inside `beforeAll` — for an executor that must connect first. */
96
+ factory?: () => HostExecutor | Promise<HostExecutor>;
97
+ run: EvalTestRunOptions;
98
+ /** Omit to register no gate test. */
99
+ gate?: GatePolicy;
100
+ hookTimeoutMs?: number;
101
+ };
102
+ /**
103
+ * Register a vitest `describe` for an eval suite: one test per case, plus the
104
+ * gate test when a policy is given.
105
+ */
106
+ declare function describeEvalSuite(name: string, suite: EvalSuite, options: EvalSuiteVitestOptions): void;
107
+ type EvalTestVitestOptions = EvalSuiteVitestOptions;
108
+ /**
109
+ * The single-test seat, for a file that owns one eval and wants no suite.
110
+ *
111
+ * Not implemented by wrapping the test in a throwaway `EvalSuite`: a suite
112
+ * aggregates and uploads as a unit, so a synthetic one would change what is
113
+ * reported for a case that is not part of any suite.
114
+ *
115
+ * `gate` is honoured here exactly as in `describeEvalSuite` — via
116
+ * `gateInputFromRunResult` rather than the suite variant. Accepting the option
117
+ * and ignoring it would be the worst outcome available: a policy that reports
118
+ * green because nothing evaluated it.
119
+ */
120
+ declare function testEval(test: EvalTest, options: EvalTestVitestOptions): void;
121
+
122
+ export { DEFAULT_HOOK_TIMEOUT_MS, type EvalCasePlan, type EvalSuitePlan, type EvalSuiteVitestOptions, type EvalTestVitestOptions, GATE_TEST_TITLE, describeEvalSuite, gateFailureMessage, planEvalSuite, runAndAssertCase, testEval };
package/dist/index.js ADDED
@@ -0,0 +1,136 @@
1
+ import { describe, beforeAll, it } from 'vitest';
2
+ import { formatGateReport, assertGate, gateInputFromSuiteResult, gateInputFromRunResult } from '@mcpjam/sdk';
3
+
4
+ // src/index.ts
5
+ var DEFAULT_HOOK_TIMEOUT_MS = 3e5;
6
+ var GATE_TEST_TITLE = "eval gate";
7
+ function planEvalSuite(suite, options = {}) {
8
+ const cases = suite.getAll().map((test) => {
9
+ const testName = test.getName();
10
+ const config = test.getConfig();
11
+ const scenarioId = config.externalCaseId;
12
+ const caseId = config.id;
13
+ const declared = caseId === void 0 ? {} : { caseId };
14
+ if (scenarioId === void 0) {
15
+ return { title: testName, testName, ...declared };
16
+ }
17
+ const suffix = ` [${scenarioId}]`;
18
+ return {
19
+ title: testName.endsWith(suffix) ? testName : `${testName}${suffix}`,
20
+ testName,
21
+ scenarioId,
22
+ ...declared
23
+ };
24
+ });
25
+ return {
26
+ cases,
27
+ ...options.gate ? { gateTestTitle: GATE_TEST_TITLE } : {}
28
+ };
29
+ }
30
+ function runAndAssertCase(run, testName, failureReport) {
31
+ if (!run) {
32
+ throw new Error(
33
+ `No result was recorded for eval case "${testName}". The suite ran, but this case was not part of it.`
34
+ );
35
+ }
36
+ if (run.failures === 0) return;
37
+ let detail = "";
38
+ try {
39
+ detail = failureReport?.() ?? "";
40
+ } catch {
41
+ detail = "";
42
+ }
43
+ const summary = `${testName}: ${run.failures} of ${run.iterations} ${run.iterations === 1 ? "iteration" : "iterations"} failed.`;
44
+ throw new Error(detail ? `${summary}
45
+
46
+ ${detail}` : summary);
47
+ }
48
+ function gateFailureMessage(error) {
49
+ const report = error?.report;
50
+ if (report && typeof report === "object" && "outcome" in report) {
51
+ return formatGateReport(report);
52
+ }
53
+ return error instanceof Error ? error.message : String(error);
54
+ }
55
+ async function resolveExecutor(options) {
56
+ if (options.executor && options.factory) {
57
+ throw new Error(
58
+ "Pass either `executor` or `factory` to describeEvalSuite, not both."
59
+ );
60
+ }
61
+ if (options.executor) return options.executor;
62
+ if (options.factory) return await options.factory();
63
+ throw new Error(
64
+ "describeEvalSuite needs an `executor` or a `factory` to build one."
65
+ );
66
+ }
67
+ function describeEvalSuite(name, suite, options) {
68
+ const plan = planEvalSuite(suite, options);
69
+ const testsByName = new Map(
70
+ suite.getAll().map((test) => [test.getName(), test])
71
+ );
72
+ describe(name, () => {
73
+ let result;
74
+ beforeAll(async () => {
75
+ const executor = await resolveExecutor(options);
76
+ result = await suite.run(executor, options.run);
77
+ }, options.hookTimeoutMs ?? DEFAULT_HOOK_TIMEOUT_MS);
78
+ for (const entry of plan.cases) {
79
+ it(entry.title, () => {
80
+ const test = testsByName.get(entry.testName);
81
+ runAndAssertCase(
82
+ result?.tests.get(entry.testName),
83
+ entry.testName,
84
+ () => test ? test.getFailureReport() : ""
85
+ );
86
+ });
87
+ }
88
+ if (plan.gateTestTitle) {
89
+ it(plan.gateTestTitle, () => {
90
+ if (!result) {
91
+ throw new Error("The eval suite did not run, so it cannot be gated.");
92
+ }
93
+ try {
94
+ assertGate(gateInputFromSuiteResult(result), options.gate);
95
+ } catch (error) {
96
+ throw new Error(gateFailureMessage(error));
97
+ }
98
+ });
99
+ }
100
+ });
101
+ }
102
+ function testEval(test, options) {
103
+ const scenarioId = test.getConfig().externalCaseId;
104
+ const name = test.getName();
105
+ const suffix = scenarioId === void 0 ? "" : ` [${scenarioId}]`;
106
+ const title = name.endsWith(suffix) ? name : `${name}${suffix}`;
107
+ describe(title, () => {
108
+ let run;
109
+ beforeAll(async () => {
110
+ const executor = await resolveExecutor(options);
111
+ run = await test.run(executor, options.run);
112
+ }, options.hookTimeoutMs ?? DEFAULT_HOOK_TIMEOUT_MS);
113
+ it(title, () => {
114
+ runAndAssertCase(run, name, () => test.getFailureReport());
115
+ });
116
+ if (options.gate) {
117
+ it(GATE_TEST_TITLE, () => {
118
+ if (!run) {
119
+ throw new Error("The eval did not run, so it cannot be gated.");
120
+ }
121
+ try {
122
+ assertGate(
123
+ gateInputFromRunResult(run),
124
+ options.gate
125
+ );
126
+ } catch (error) {
127
+ throw new Error(gateFailureMessage(error));
128
+ }
129
+ });
130
+ }
131
+ });
132
+ }
133
+
134
+ export { DEFAULT_HOOK_TIMEOUT_MS, GATE_TEST_TITLE, describeEvalSuite, gateFailureMessage, planEvalSuite, runAndAssertCase, testEval };
135
+ //# sourceMappingURL=index.js.map
136
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts"],"names":[],"mappings":";;;;AAmDO,IAAM,uBAAA,GAA0B;AAGhC,IAAM,eAAA,GAAkB;AAkCxB,SAAS,aAAA,CACd,KAAA,EACA,OAAA,GAAiC,EAAC,EACnB;AACf,EAAA,MAAM,QAAQ,KAAA,CAAM,MAAA,EAAO,CAAE,GAAA,CAAI,CAAC,IAAA,KAAuB;AACvD,IAAA,MAAM,QAAA,GAAW,KAAK,OAAA,EAAQ;AAC9B,IAAA,MAAM,MAAA,GAAS,KAAK,SAAA,EAAU;AAC9B,IAAA,MAAM,aAAa,MAAA,CAAO,cAAA;AAI1B,IAAA,MAAM,SAAU,MAAA,CAA2B,EAAA;AAC3C,IAAA,MAAM,WAAW,MAAA,KAAW,MAAA,GAAY,EAAC,GAAI,EAAE,MAAA,EAAO;AACtD,IAAA,IAAI,eAAe,MAAA,EAAW;AAC5B,MAAA,OAAO,EAAE,KAAA,EAAO,QAAA,EAAU,QAAA,EAAU,GAAG,QAAA,EAAS;AAAA,IAClD;AAGA,IAAA,MAAM,MAAA,GAAS,KAAK,UAAU,CAAA,CA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eAAA,CAAgB,OAAO,CAAA;AAC9C,MAAA,GAAA,GAAM,MAAM,IAAA,CAAK,GAAA,CAAI,QAAA,EAAU,QAAQ,GAAG,CAAA;AAAA,IAC5C,CAAA,EAAG,OAAA,CAAQ,aAAA,IAAiB,uBAAuB,CAAA;AAEnD,IAAA,EAAA,CAAG,OAAO,MAAM;AACd,MAAA,gBAAA,CAAiB,GAAA,EAAK,IAAA,EAAM,MAAM,IAAA,CAAK,kBAAkB,CAAA;AAAA,IAC3D,CAAC,CAAA;AAED,IAAA,IAAI,QAAQ,IAAA,EAAM;AAChB,MAAA,EAAA,CAAG,iBAAiB,MAAM;AACxB,QAAA,IAAI,CAAC,GAAA,EAAK;AACR,UAAA,MAAM,IAAI,MAAM,8CAA8C,CAAA;AAAA,QAChE;AACA,QAAA,IAAI;AACF,UAAA,UAAA;AAAA,YACE,uBAAuB,GAAG,CAAA;AAAA,YAC1B,OAAA,CAAQ;AAAA,WACV;AAAA,QACF,SAAS,KAAA,EAAO;AACd,UAAA,MAAM,IAAI,KAAA,CAAM,kBAAA,CAAmB,KAAK,CAAC,CAAA;AAAA,QAC3C;AAAA,MACF,CAAC,CAAA;AAAA,IACH;AAAA,EACF,CAAC,CAAA;AACH","file":"index.js","sourcesContent":["/**\n * Run MCPJam eval suites inside vitest.\n *\n * --- A wrapper, not a reporter ---\n *\n * The obvious alternative was a custom vitest Reporter. This is deliberately\n * not that. A reporter observes tests; it cannot decide what a test IS. Evals\n * need the opposite: one `it` per eval case so failures land on named tests in\n * every vitest UI, watch mode and CI annotation that already exists, with no\n * bespoke output for anyone to learn. A reporter would also have no seat for\n * the gate, which is a verdict over the whole run rather than any one case.\n *\n * --- One run, many tests ---\n *\n * `suite.run()` is called ONCE, in `beforeAll`. That is not an optimization:\n * the suite uploads a single hosted run, computes one aggregate evaluation\n * config hash, and executes its cases sequentially. Calling it per `it` would\n * produce N hosted runs, N aggregate hashes, and a concurrency pattern the\n * suite explicitly avoids. The `it`s then read that one result.\n *\n * So an eval case's `it` is an ASSERTION over an already-computed result, not\n * the thing that runs it. Vitest timeouts on those tests are therefore\n * irrelevant; the timeout that matters is the hook's, which is why it defaults\n * to five minutes and is configurable.\n *\n * --- The gate is its own test ---\n *\n * The per-case tests answer \"did this case pass\". The gate answers \"does this\n * run satisfy the policy\", which is a different question with a different\n * failure mode — a run where every case passed can still breach a latency or\n * score-integrity gate. Giving it a named `it` means CI shows WHICH question\n * failed instead of a bare non-zero exit.\n */\n\nimport { beforeAll, describe, it } from \"vitest\";\nimport {\n assertGate,\n formatGateReport,\n gateInputFromRunResult,\n gateInputFromSuiteResult,\n type EvalRunResult,\n type EvalSuite,\n type EvalSuiteResult,\n type EvalTest,\n type EvalTestRunOptions,\n type GatePolicy,\n type GateReport,\n type HostExecutor,\n} from \"@mcpjam/sdk\";\n\n/** Five minutes. An eval suite is not a unit test. */\nexport const DEFAULT_HOOK_TIMEOUT_MS = 300_000;\n\n/** The vitest test title used for the policy gate. */\nexport const GATE_TEST_TITLE = \"eval gate\";\n\nexport type EvalCasePlan = {\n /** The vitest test title. */\n title: string;\n /** The suite key this case's result is recorded under. */\n testName: string;\n /** The hosted case id, when this case came from a hosted corpus. */\n scenarioId?: string;\n /**\n * The case's DECLARED id (`EvalTestConfig.id`).\n *\n * Surfaced so a CI reporter can key a case by its identity rather than by a\n * title that gets renamed. Deliberately NOT used in the vitest title: the\n * `[scenarioId]` suffix is the hosted-dashboard grep handle and still rides\n * `externalCaseId`, so changing what the suffix carries would break the greps\n * that exist.\n */\n caseId?: string;\n};\n\nexport type EvalSuitePlan = {\n cases: EvalCasePlan[];\n /** Present only when a gate policy was supplied. */\n gateTestTitle?: string;\n};\n\n/**\n * Decide the vitest titles for a suite, without registering anything.\n *\n * Pure and exported so the naming rules are testable on their own. A hosted\n * case's id is appended so a test title is greppable back to the dashboard row\n * it came from — explicitly, never inferred from the test name.\n */\nexport function planEvalSuite(\n suite: EvalSuite,\n options: { gate?: GatePolicy } = {}\n): EvalSuitePlan {\n const cases = suite.getAll().map((test): EvalCasePlan => {\n const testName = test.getName();\n const config = test.getConfig();\n const scenarioId = config.externalCaseId;\n // Read defensively: a user can end up with `@mcpjam/vitest` beside an older\n // `@mcpjam/sdk` copy, where `id` does not exist yet. An absent `caseId` is\n // a missing convenience; a thrown TypeError would be a broken test run.\n const caseId = (config as { id?: string }).id;\n const declared = caseId === undefined ? {} : { caseId };\n if (scenarioId === undefined) {\n return { title: testName, testName, ...declared };\n }\n // A corpus already suffixes `[id]` onto cases whose titles collide, so\n // appending unconditionally would render `Title [id] [id]`.\n const suffix = ` [${scenarioId}]`;\n return {\n title: testName.endsWith(suffix) ? testName : `${testName}${suffix}`,\n testName,\n scenarioId,\n ...declared,\n };\n });\n\n return {\n cases,\n ...(options.gate ? { gateTestTitle: GATE_TEST_TITLE } : {}),\n };\n}\n\n/**\n * Turn one case's recorded result into a pass or a thrown failure.\n *\n * Exported so the RED path is testable inside an ordinary `it` — a generated\n * failing test cannot be asserted on from within the same run without failing\n * the run itself.\n */\nexport function runAndAssertCase(\n run: EvalRunResult | undefined,\n testName: string,\n failureReport?: () => string\n): void {\n if (!run) {\n // Reachable if a case was added to the suite after the plan was taken.\n throw new Error(\n `No result was recorded for eval case \"${testName}\". The suite ran, but ` +\n `this case was not part of it.`\n );\n }\n if (run.failures === 0) return;\n\n let detail = \"\";\n try {\n detail = failureReport?.() ?? \"\";\n } catch {\n // A missing detail report must not replace the real failure with a\n // secondary one about formatting it.\n detail = \"\";\n }\n\n const summary =\n `${testName}: ${run.failures} of ${run.iterations} ` +\n `${run.iterations === 1 ? \"iteration\" : \"iterations\"} failed.`;\n throw new Error(detail ? `${summary}\\n\\n${detail}` : summary);\n}\n\n/**\n * Render a gate failure for a test message.\n *\n * Duck-typed as well as `instanceof`-checked. A published wrapper can end up\n * beside a second copy of `@mcpjam/sdk` — a mismatched transitive range, a\n * pnpm layout — and `instanceof` silently fails across copies. Falling back to\n * the message would drop the per-gate table, which is the whole reason the\n * error carries a report.\n */\nexport function gateFailureMessage(error: unknown): string {\n const report = (error as { report?: GateReport } | null)?.report;\n if (report && typeof report === \"object\" && \"outcome\" in report) {\n return formatGateReport(report);\n }\n return error instanceof Error ? error.message : String(error);\n}\n\nexport type EvalSuiteVitestOptions = {\n /** A ready executor. Mutually exclusive with `factory`. */\n executor?: HostExecutor;\n /** Built inside `beforeAll` — for an executor that must connect first. */\n factory?: () => HostExecutor | Promise<HostExecutor>;\n run: EvalTestRunOptions;\n /** Omit to register no gate test. */\n gate?: GatePolicy;\n hookTimeoutMs?: number;\n};\n\nasync function resolveExecutor(\n options: EvalSuiteVitestOptions\n): Promise<HostExecutor> {\n if (options.executor && options.factory) {\n throw new Error(\n \"Pass either `executor` or `factory` to describeEvalSuite, not both.\"\n );\n }\n if (options.executor) return options.executor;\n if (options.factory) return await options.factory();\n throw new Error(\n \"describeEvalSuite needs an `executor` or a `factory` to build one.\"\n );\n}\n\n/**\n * Register a vitest `describe` for an eval suite: one test per case, plus the\n * gate test when a policy is given.\n */\nexport function describeEvalSuite(\n name: string,\n suite: EvalSuite,\n options: EvalSuiteVitestOptions\n): void {\n const plan = planEvalSuite(suite, options);\n // Captured BEFORE the run so a case's detailed report is reachable by name\n // without re-walking the suite inside every test.\n const testsByName = new Map<string, EvalTest>(\n suite.getAll().map((test) => [test.getName(), test])\n );\n\n describe(name, () => {\n let result: EvalSuiteResult | undefined;\n\n beforeAll(async () => {\n const executor = await resolveExecutor(options);\n result = await suite.run(executor, options.run);\n }, options.hookTimeoutMs ?? DEFAULT_HOOK_TIMEOUT_MS);\n\n for (const entry of plan.cases) {\n it(entry.title, () => {\n const test = testsByName.get(entry.testName);\n runAndAssertCase(result?.tests.get(entry.testName), entry.testName, () =>\n test ? test.getFailureReport() : \"\"\n );\n });\n }\n\n if (plan.gateTestTitle) {\n it(plan.gateTestTitle, () => {\n if (!result) {\n throw new Error(\"The eval suite did not run, so it cannot be gated.\");\n }\n try {\n // `assertGate` throws on `incomplete` too: a gate that could not be\n // decided has not been satisfied.\n assertGate(gateInputFromSuiteResult(result), options.gate as GatePolicy);\n } catch (error) {\n throw new Error(gateFailureMessage(error));\n }\n });\n }\n });\n}\n\nexport type EvalTestVitestOptions = EvalSuiteVitestOptions;\n\n/**\n * The single-test seat, for a file that owns one eval and wants no suite.\n *\n * Not implemented by wrapping the test in a throwaway `EvalSuite`: a suite\n * aggregates and uploads as a unit, so a synthetic one would change what is\n * reported for a case that is not part of any suite.\n *\n * `gate` is honoured here exactly as in `describeEvalSuite` — via\n * `gateInputFromRunResult` rather than the suite variant. Accepting the option\n * and ignoring it would be the worst outcome available: a policy that reports\n * green because nothing evaluated it.\n */\nexport function testEval(\n test: EvalTest,\n options: EvalTestVitestOptions\n): void {\n const scenarioId = test.getConfig().externalCaseId;\n const name = test.getName();\n const suffix = scenarioId === undefined ? \"\" : ` [${scenarioId}]`;\n const title = name.endsWith(suffix) ? name : `${name}${suffix}`;\n\n describe(title, () => {\n let run: EvalRunResult | undefined;\n\n beforeAll(async () => {\n const executor = await resolveExecutor(options);\n run = await test.run(executor, options.run);\n }, options.hookTimeoutMs ?? DEFAULT_HOOK_TIMEOUT_MS);\n\n it(title, () => {\n runAndAssertCase(run, name, () => test.getFailureReport());\n });\n\n if (options.gate) {\n it(GATE_TEST_TITLE, () => {\n if (!run) {\n throw new Error(\"The eval did not run, so it cannot be gated.\");\n }\n try {\n assertGate(\n gateInputFromRunResult(run),\n options.gate as GatePolicy\n );\n } catch (error) {\n throw new Error(gateFailureMessage(error));\n }\n });\n }\n });\n}\n"]}
package/package.json ADDED
@@ -0,0 +1,39 @@
1
+ {
2
+ "name": "@mcpjam/vitest",
3
+ "version": "0.1.0",
4
+ "description": "Run MCPJam eval suites inside vitest: one test per eval case, plus a gate test that fails the build on a policy breach.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "main": "dist/index.js",
8
+ "module": "dist/index.js",
9
+ "types": "dist/index.d.ts",
10
+ "files": [
11
+ "dist"
12
+ ],
13
+ "exports": {
14
+ ".": {
15
+ "types": "./dist/index.d.ts",
16
+ "import": "./dist/index.js",
17
+ "default": "./dist/index.js"
18
+ }
19
+ },
20
+ "scripts": {
21
+ "build": "tsup",
22
+ "typecheck": "tsc --noEmit",
23
+ "test": "vitest run",
24
+ "test:packaging": "node tests/packaging.e2e.mjs",
25
+ "prepack": "npm run build",
26
+ "prepublishOnly": "npm run build"
27
+ },
28
+ "peerDependencies": {
29
+ "vitest": ">=3.2.0 <4"
30
+ },
31
+ "dependencies": {
32
+ "@mcpjam/sdk": "^5.0.0"
33
+ },
34
+ "devDependencies": {
35
+ "tsup": "^8.3.5",
36
+ "typescript": "^5",
37
+ "vitest": "^3.2.4"
38
+ }
39
+ }