@drak-marketing/mcp-test-harness 0.2.2 → 0.3.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/CHANGELOG.md ADDED
@@ -0,0 +1,100 @@
1
+ # Changelog
2
+
3
+ Notable changes to `@drak-marketing/mcp-test-harness`. While the major
4
+ version is 0, a minor bump (0.2 → 0.3) can break consumers, and a `^0.2.x`
5
+ range does not pick it up.
6
+
7
+ ## [0.3.0] - 2026-11-23
8
+
9
+ Checks that passed without exercising anything now run for real, so expect
10
+ real failures when you bump.
11
+
12
+ ### Changed
13
+
14
+ - **stdout purity** fails unless `initialize` and `tools/list` both get clean
15
+ JSON-RPC answers on stdout. An empty stdout used to pass, so a server that
16
+ exited at credential validation was never checked. When nothing reached
17
+ stdout, the failure says "stdout purity was not exercised" and points to the
18
+ startup test; it suggests the pino fix only when non-JSON-RPC output reached
19
+ stdout. (#10, #11)
20
+ - **Spawned servers get fake credentials only.** Every server the harness
21
+ starts runs in a hermetic env:
22
+ - only PATH, TMPDIR, locale and a few OS variables come through from the
23
+ parent;
24
+ - HOME is an empty throwaway directory;
25
+ - each `requiredEnvVars` entry gets `fake-<name>`, with `startupEnv` on top;
26
+ - a preloaded jail refuses non-loopback TCP, the macOS `security` CLI and
27
+ browser launchers.
28
+
29
+ Before this, the "no credentials" tests merged the parent's environment back
30
+ in. (#10)
31
+ - **graceful shutdown** runs for every consumer, not only those that set
32
+ `startupEnv`. A server that exited before the signal reports
33
+ `ALREADY_EXITED` instead of `TIMEOUT`. (#10)
34
+ - **MCP protocol conformance** uses the live `tools/list` when
35
+ `dist/tools.js` exports no tools array, instead of skipping. (#10)
36
+ - **Tests that could not fail now can.** Assertions swallowed by `catch` in
37
+ network failures, token lifecycle, mayhem and `npm audit` are fixed; the
38
+ `npm audit` catch also hid every real finding. `expect(true)` and no-assert
39
+ tests are removed. Token-lifecycle failures report only null or not-null,
40
+ never the value read. (#10)
41
+
42
+ ### Added
43
+
44
+ - Smoke test `server starts with fake credentials and answers initialize and
45
+ tools/list`. On failure it names the unanswered request, says whether the
46
+ server exited, lists the fake variables it set (names only, never values),
47
+ quotes the server's stderr and maps common causes to a config fix. When the
48
+ jail refused a startup call, it suggests a `startupEnv` skip flag. (#11)
49
+ - README section "Starting the server with fake credentials". (#11)
50
+ - This changelog, shipped in the package.
51
+
52
+ ### Release
53
+
54
+ - `publish.yml` publishes only a release tag whose commit is on main, in the
55
+ `npm-publish` environment, with per-job token scopes. (#12)
56
+
57
+ ### Upgrading from 0.2.x
58
+
59
+ Bump the range to `^0.3.0` on purpose, in its own PR, and read what turns red:
60
+
61
+ - a server that exits at startup needs its variables in `requiredEnvVars`, or
62
+ a well-formed fake or skip flag in `startupEnv` (see the README table);
63
+ - a server that logs through pino to stdout needs `pino.destination(2)`;
64
+ - a server with no `SIGPIPE` handler fails graceful shutdown.
65
+
66
+ ## [0.2.3] - 2026-09-08
67
+
68
+ - No code change. Published from CI through npm Trusted Publishing (OIDC) to
69
+ prove that path. (#9)
70
+ - CI: `actions/checkout` and `actions/setup-node` v4 → v7. (#8)
71
+
72
+ ## [0.2.2] - 2026-09-04
73
+
74
+ - First CI, and the Trusted Publishing workflow. (#6)
75
+ - `package-lock.json` version realigned with `package.json`. (#7)
76
+
77
+ ## [0.2.1] - 2026-09-03
78
+
79
+ Not tagged.
80
+
81
+ - stdout purity: the test timeout accounts for the test's own waits. (#4)
82
+ - dependency health: the `npm audit` test timeout exceeds its subprocess
83
+ budget. (#2)
84
+ - stdout purity: SIGKILL fallback, so the test can't hang. (#1)
85
+
86
+ ## [0.2.0] - 2026-04-17
87
+
88
+ - stdout purity suite: the regression guard for the 2026-04-17 incident, where
89
+ pino logs on stdout broke every MCP request.
90
+
91
+ ## [0.1.3] - 2026-09-03
92
+
93
+ - Backport of the `npm audit` timeout fix (#2) to the 0.1.x line. Tagged off
94
+ main.
95
+
96
+ ## [0.1.1] - 2026-04-16
97
+
98
+ - First release: build integrity, smoke, protocol conformance,
99
+ credential security, resilience and adversarial (Ralph, Ender, Mayhem)
100
+ suites.
package/README.md CHANGED
@@ -36,7 +36,9 @@ registerMcpTests({
36
36
  hasPlatform: true,
37
37
  requiredEnvVars: ["EXAMPLE_API_KEY"],
38
38
  envPrefix: "EXAMPLE_",
39
- startupEnv: { EXAMPLE_API_KEY: "fake-key" },
39
+ // Only for fakes the harness can't derive; see "Starting the server with
40
+ // fake credentials" below.
41
+ startupEnv: { EXAMPLE_ACCOUNT_ID: "1234567890" },
40
42
  });
41
43
  ```
42
44
 
@@ -57,10 +59,94 @@ Suites are selected based on the capabilities you declare in the config:
57
59
  backward-compat
58
60
  - **`hasResilience: true`** → network failure scenarios
59
61
  - **`requiredEnvVars.length > 0`** → config loading
60
- - **`startupEnv` provided** → graceful shutdown
61
62
 
62
63
  See [`src/types.ts`](src/types.ts) for the full config shape.
63
64
 
65
+ ## Spawned servers get fake credentials only
66
+
67
+ Every server process the harness starts runs in a hermetic env:
68
+
69
+ - nothing is inherited from your shell except PATH, TMPDIR, locale and a few
70
+ OS variables, so a real token you exported never reaches it;
71
+ - `HOME` is an empty throwaway directory, so credential files under `~` are
72
+ not found;
73
+ - a preloaded jail refuses every non-loopback TCP connection and every call to
74
+ the macOS `security` CLI, with a `[mcp-test-harness jail]` line on stderr.
75
+
76
+ Files inside your repo are not hidden. A server that reads a gitignored
77
+ `config.json` or `.env` from its own directory still finds it, so on a laptop
78
+ that has one it can start with real configuration and pass, while the same
79
+ test fails in CI. The jail still blocks its network and Keychain calls. Treat
80
+ CI, or a fresh clone, as the real check.
81
+
82
+ ## Starting the server with fake credentials
83
+
84
+ The smoke test `server starts with fake credentials and answers initialize and
85
+ tools/list` starts the server the way an MCP client does (piped stdio) and
86
+ fails unless both requests get an answer. Everything else that needs a live
87
+ server depends on it: stdout purity, graceful shutdown, and the tool checks
88
+ when `dist/tools.js` exports no tools array. When the server can't start,
89
+ those fail too and point back to this test.
90
+
91
+ The server's environment is built in this order:
92
+
93
+ 1. the allowlisted system variables above;
94
+ 2. `fake-<name>` for each `requiredEnvVars` entry (`EXAMPLE_API_KEY` gets
95
+ `fake-example-api-key`);
96
+ 3. `startupEnv`, which overrides those fakes and adds variables of its own;
97
+ 4. the throwaway `HOME` and the jail, which your config can't override.
98
+
99
+ When the test fails, read the server's stderr at the end of the failure
100
+ message and find the matching case:
101
+
102
+ | The server's stderr says | What to change in your harness config |
103
+ |---|---|
104
+ | a named env var is missing | Add it to `requiredEnvVars`. |
105
+ | it wants one of several credential sets (an OAuth trio, or a key file) | Put one complete set in `startupEnv`. |
106
+ | a value is malformed (a numeric account id, a URL, JSON) | Put a well-formed fake in `startupEnv`. It overrides the derived `fake-<name>`. |
107
+ | a config or key file is missing | Commit a fixture with fake values under `tests/fixtures/` and point the server's path variable at it in `startupEnv`. `~` is empty, and a gitignored file in the repo isn't there in CI. |
108
+ | `[mcp-test-harness jail] refused …`, then it exits or hangs | A startup check is calling the platform or the Keychain. Give the server a skip flag (an env var that bypasses the check) and set it in `startupEnv`. Don't loosen the jail. |
109
+ | it hangs with nothing useful on stderr | The server is waiting on something before it connects the transport, such as a retry loop. Use a skip flag, as in the row above. |
110
+
111
+ A refused connection to `registry.npmjs.org` is usually an update check and
112
+ doesn't stop the server.
113
+
114
+ ```ts
115
+ registerMcpTests({
116
+ // ...
117
+ requiredEnvVars: ["EXAMPLE_CLIENT_ID", "EXAMPLE_CLIENT_SECRET", "EXAMPLE_REFRESH_TOKEN"],
118
+ startupEnv: {
119
+ EXAMPLE_ACCOUNT_ID: "1234567890", // the server checks it is numeric
120
+ EXAMPLE_SKIP_STARTUP_CHECK: "1", // the startup auth check calls the API
121
+ EXAMPLE_CONFIG_PATH: path.resolve(__dirname, "../tests/fixtures/config.json"),
122
+ },
123
+ });
124
+ ```
125
+
126
+ - **Never put a real value here.** Fakes can appear in test output. The
127
+ harness's own messages name the variables it set but never print their
128
+ values; your server may print them anyway.
129
+ - **`requiredEnvVars` versus `startupEnv`:** list the variables the server
130
+ requires in `requiredEnvVars`. That list also drives the config-loading
131
+ suite, which checks that the no-credentials error names them. Use
132
+ `startupEnv` for everything else.
133
+ - **Check it on its own:**
134
+ `npx vitest run src/harness.test.ts -t "server starts with fake credentials"`.
135
+
136
+ ## What 0.3.0 changes
137
+
138
+ `stdout purity` starts the server, sends `initialize` and `tools/list`, and
139
+ fails unless both are answered with clean JSON-RPC on stdout. Before 0.3.0 an
140
+ empty stdout passed, so a server that exited at credential validation was
141
+ never checked. If the server never answered, the purity failure says so
142
+ ("stdout purity was not exercised") and points to the startup test above,
143
+ instead of suggesting a logger fix. `MCP protocol conformance` falls back to
144
+ the live `tools/list` when `dist/tools.js` exports no tools array, and
145
+ `graceful shutdown` runs for every consumer.
146
+
147
+ Upgrading from 0.2.x: `^0.2.x` will not pick up 0.3.0 on its own. Bump the
148
+ range deliberately and expect real failures to surface.
149
+
64
150
  ## Publishing
65
151
 
66
152
  Publishing happens in CI via npm **Trusted Publishing** (OIDC). **There is no npm
@@ -71,21 +157,26 @@ matched against the Trusted Publisher registered for this package on npmjs.com
71
157
 
72
158
  To publish a new version:
73
159
 
74
- 1. Bump `version` in `package.json` and merge that to `main`.
75
- 2. Cut a GitHub Release on the matching tag — that fires `publish.yml`:
160
+ 1. Bump `version` in `package.json` and `package-lock.json`, add its entry at
161
+ the top of `CHANGELOG.md`, and merge that to `main`.
162
+ `tests/release-metadata.test.ts` fails if the three disagree.
163
+ 2. Cut a GitHub Release on a new tag at that commit. That fires `publish.yml`,
164
+ which publishes only a tag whose commit is on `main`, in the `npm-publish`
165
+ environment:
76
166
 
77
167
  ```
78
- gh release create v0.2.2 --repo mharnett/mcp-test-harness --generate-notes
168
+ gh release create v0.3.0 --repo mharnett/mcp-test-harness --target main \
169
+ --title v0.3.0 --generate-notes --notes-start-tag v0.2.3
79
170
  ```
80
171
 
81
172
  3. Watch the run: `gh run list --repo mharnett/mcp-test-harness --workflow publish.yml`
82
173
 
83
174
  If a Release is created by automation rather than by hand, GitHub suppresses the
84
175
  downstream `release` trigger and the publish silently never runs. Use the manual
85
- fallback in that case:
176
+ fallback in that case, dispatched from `main` with the release tag:
86
177
 
87
178
  ```
88
- gh workflow run publish.yml --repo mharnett/mcp-test-harness -f ref=v0.2.2
179
+ gh workflow run publish.yml --repo mharnett/mcp-test-harness --ref main -f ref=v0.3.0
89
180
  ```
90
181
 
91
182
  Two pins in `publish.yml` are load-bearing and documented inline — `npm@11`
@@ -0,0 +1,6 @@
1
+ import type { McpServerConfig } from "../types.js";
2
+ export declare function importDistModule(config: McpServerConfig, name: string): Promise<Record<string, unknown> | null>;
3
+ export type Fn = (...args: unknown[]) => unknown;
4
+ /** The first of `names` that the module exports as a function. */
5
+ export declare function pickFn(mod: Record<string, unknown> | null, ...names: string[]): Fn | null;
6
+ //# sourceMappingURL=dist-module.d.ts.map
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Import a consumer's built module (dist/<name>.js) for in-process checks.
3
+ *
4
+ * Returns null only when the file does not exist. An import that throws is a
5
+ * real failure and propagates: before 0.3.0 each caller wrapped the import
6
+ * AND its assertions in one try/catch, so a failing expect() was swallowed
7
+ * and the test could never fail.
8
+ */
9
+ import { existsSync } from "fs";
10
+ import path from "path";
11
+ import { pathToFileURL } from "url";
12
+ export async function importDistModule(config, name) {
13
+ const file = path.join(config.repoRoot, "dist", `${name}.js`);
14
+ if (!existsSync(file))
15
+ return null;
16
+ return (await import(pathToFileURL(file).href));
17
+ }
18
+ /** The first of `names` that the module exports as a function. */
19
+ export function pickFn(mod, ...names) {
20
+ if (!mod)
21
+ return null;
22
+ for (const n of names)
23
+ if (typeof mod[n] === "function")
24
+ return mod[n];
25
+ return null;
26
+ }
@@ -0,0 +1,18 @@
1
+ import type { McpServerConfig } from "../types.js";
2
+ /**
3
+ * Fake credential values for a server: one per `requiredEnvVars` entry,
4
+ * then `startupEnv` on top (to override a fake whose format the server
5
+ * checks, or to add a skip flag such as MCP_GA4_SKIP_STARTUP_CHECK).
6
+ */
7
+ export declare function fakeCredentialEnv(config: Pick<McpServerConfig, "requiredEnvVars" | "startupEnv">): Record<string, string>;
8
+ /** URL of the jail module, which sits next to this file in dist/helpers. */
9
+ export declare function jailModuleUrl(): string;
10
+ /** One empty HOME per test process. */
11
+ export declare function sandboxHomeDir(): string;
12
+ /**
13
+ * The full env for a spawned server: allowlisted system vars, then the
14
+ * caller's values, then the sandbox HOME and the jail, which a caller cannot
15
+ * override.
16
+ */
17
+ export declare function hermeticEnv(overrides?: Record<string, string | undefined>): Record<string, string>;
18
+ //# sourceMappingURL=hermetic-env.d.ts.map
@@ -0,0 +1,89 @@
1
+ /**
2
+ * Environment for every server process the harness spawns.
3
+ *
4
+ * Servers under test get fake credentials only:
5
+ * - nothing is inherited from the parent except a short allowlist of system
6
+ * variables, so a real token exported in the developer's shell (or set by
7
+ * a CI secret) never reaches the server;
8
+ * - HOME (and USERPROFILE / XDG_CONFIG_HOME) point at an empty throwaway
9
+ * directory, so file-based credential stores under ~ are not found;
10
+ * - NODE_OPTIONS preloads the jail (network-jail.ts), which refuses any
11
+ * non-loopback TCP connection and any call to the macOS `security` CLI.
12
+ */
13
+ import { mkdtempSync } from "fs";
14
+ import os from "os";
15
+ import path from "path";
16
+ import { fileURLToPath, pathToFileURL } from "url";
17
+ /** System variables a server may need to run at all. Nothing credential-shaped. */
18
+ const PASSTHROUGH = [
19
+ "PATH",
20
+ "Path",
21
+ "PATHEXT",
22
+ "TMPDIR",
23
+ "TEMP",
24
+ "TMP",
25
+ "LANG",
26
+ "LC_ALL",
27
+ "LC_CTYPE",
28
+ "TZ",
29
+ "TERM",
30
+ "SYSTEMROOT",
31
+ "SystemRoot",
32
+ "WINDIR",
33
+ "windir",
34
+ "COMSPEC",
35
+ "ComSpec",
36
+ ];
37
+ /**
38
+ * Fake credential values for a server: one per `requiredEnvVars` entry,
39
+ * then `startupEnv` on top (to override a fake whose format the server
40
+ * checks, or to add a skip flag such as MCP_GA4_SKIP_STARTUP_CHECK).
41
+ */
42
+ export function fakeCredentialEnv(config) {
43
+ const env = {};
44
+ for (const name of config.requiredEnvVars) {
45
+ env[name] = `fake-${name.toLowerCase().replace(/_/g, "-")}`;
46
+ }
47
+ return { ...env, ...(config.startupEnv ?? {}) };
48
+ }
49
+ /** URL of the jail module, which sits next to this file in dist/helpers. */
50
+ export function jailModuleUrl() {
51
+ const self = fileURLToPath(import.meta.url);
52
+ const here = path.dirname(self);
53
+ // The harness's own tests import the .ts sources; the jail is always the
54
+ // built .js in dist/helpers (consumers run from dist already).
55
+ const built = self.endsWith(".ts")
56
+ ? path.join(here, "..", "..", "dist", "helpers", "network-jail.js")
57
+ : path.join(here, "network-jail.js");
58
+ return pathToFileURL(built).href;
59
+ }
60
+ let sandboxHome;
61
+ /** One empty HOME per test process. */
62
+ export function sandboxHomeDir() {
63
+ sandboxHome ??= mkdtempSync(path.join(os.tmpdir(), "mcp-test-harness-home-"));
64
+ return sandboxHome;
65
+ }
66
+ /**
67
+ * The full env for a spawned server: allowlisted system vars, then the
68
+ * caller's values, then the sandbox HOME and the jail, which a caller cannot
69
+ * override.
70
+ */
71
+ export function hermeticEnv(overrides = {}) {
72
+ const env = {};
73
+ for (const name of PASSTHROUGH) {
74
+ const v = process.env[name];
75
+ if (v !== undefined)
76
+ env[name] = v;
77
+ }
78
+ for (const [k, v] of Object.entries(overrides)) {
79
+ if (v !== undefined)
80
+ env[k] = v;
81
+ }
82
+ const home = sandboxHomeDir();
83
+ env.HOME = home;
84
+ env.USERPROFILE = home;
85
+ env.XDG_CONFIG_HOME = path.join(home, ".config");
86
+ env.NODE_OPTIONS = `--import=${JSON.stringify(jailModuleUrl())}`;
87
+ env.MCP_TEST_HARNESS_SANDBOX = "1";
88
+ return env;
89
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * The label the jail (network-jail.ts) puts on every refusal it writes to
3
+ * stderr. Kept in its own module so the harness can recognise refusals in a
4
+ * server's stderr without importing the jail, which patches `net` and
5
+ * `child_process` in whatever process imports it.
6
+ */
7
+ export declare const JAIL_MARKER = "mcp-test-harness jail";
8
+ //# sourceMappingURL=jail-marker.d.ts.map
@@ -0,0 +1,7 @@
1
+ /**
2
+ * The label the jail (network-jail.ts) puts on every refusal it writes to
3
+ * stderr. Kept in its own module so the harness can recognise refusals in a
4
+ * server's stderr without importing the jail, which patches `net` and
5
+ * `child_process` in whatever process imports it.
6
+ */
7
+ export const JAIL_MARKER = "mcp-test-harness jail";
@@ -0,0 +1,3 @@
1
+ import { JAIL_MARKER } from "./jail-marker.js";
2
+ export { JAIL_MARKER };
3
+ //# sourceMappingURL=network-jail.d.ts.map
@@ -0,0 +1,85 @@
1
+ /**
2
+ * Preloaded (`node --import`) into every server the harness spawns.
3
+ *
4
+ * A server started with fake credentials still tries to reach its platform
5
+ * (Bing refreshes its OAuth token before connecting the transport) and the
6
+ * macOS Keychain (several servers read or persist tokens through the
7
+ * `security` CLI). Both are refused here, immediately and with a labelled
8
+ * error, so a harness run can never make a live API call or read a real
9
+ * secret, on a laptop or in CI.
10
+ *
11
+ * Browser launchers (open, xdg-open, wslview) are refused too, so a server
12
+ * that falls into an interactive OAuth flow fails instead of opening one.
13
+ *
14
+ * Loopback and IPC connections are allowed. No arguments of a refused
15
+ * `security` call are printed: a persist call carries the secret in argv.
16
+ */
17
+ import net from "node:net";
18
+ import childProcess from "node:child_process";
19
+ import { syncBuiltinESMExports } from "node:module";
20
+ import { JAIL_MARKER } from "./jail-marker.js";
21
+ export { JAIL_MARKER };
22
+ const LOOPBACK = new Set(["localhost", "127.0.0.1", "::1", "0:0:0:0:0:0:0:1", "::ffff:127.0.0.1"]);
23
+ /** Normalise the three Socket#connect call shapes (and net.connect's pre-normalised array). */
24
+ function targetOf(args) {
25
+ const first = Array.isArray(args[0]) ? args[0][0] : args[0];
26
+ if (first !== null && typeof first === "object") {
27
+ const o = first;
28
+ return { host: o.host, port: o.port, path: o.path };
29
+ }
30
+ if (typeof first === "string" && Number.isNaN(Number(first)))
31
+ return { path: first };
32
+ return { port: first, host: typeof args[1] === "string" ? args[1] : undefined };
33
+ }
34
+ function isAllowed(t) {
35
+ if (t.path)
36
+ return true; // unix socket / named pipe
37
+ const host = (t.host ?? "localhost").replace(/^\[|\]$/g, "").toLowerCase();
38
+ return LOOPBACK.has(host);
39
+ }
40
+ const originalConnect = net.Socket.prototype.connect;
41
+ net.Socket.prototype.connect = function jailedConnect(...args) {
42
+ const t = targetOf(args);
43
+ if (isAllowed(t)) {
44
+ return originalConnect.apply(this, args);
45
+ }
46
+ const where = `${t.host ?? "localhost"}:${String(t.port)}`;
47
+ process.stderr.write(`[${JAIL_MARKER}] refused outbound connection to ${where}\n`);
48
+ const err = Object.assign(new Error(`${JAIL_MARKER}: outbound network blocked (${where})`), {
49
+ code: "ECONNREFUSED",
50
+ });
51
+ process.nextTick(() => this.destroy(err));
52
+ return this;
53
+ };
54
+ /** `security`, `/usr/bin/security`, or a shell string that starts with either. */
55
+ function isSecurityCli(command) {
56
+ return typeof command === "string" && /^\s*(?:\S*\/)?security(?:\s|$)/.test(command);
57
+ }
58
+ /** open / xdg-open / wslview: an interactive OAuth flow trying to open a browser. */
59
+ function isBrowserOpener(command) {
60
+ return typeof command === "string" && /^\s*(?:\S*\/)?(?:open|xdg-open|wslview)(?:\s|$)/.test(command);
61
+ }
62
+ function refuseBrowser() {
63
+ process.stderr.write(`[${JAIL_MARKER}] refused to open a browser (interactive auth flow?)\n`);
64
+ throw Object.assign(new Error(`${JAIL_MARKER}: browser launch blocked`), { code: "EACCES" });
65
+ }
66
+ function refuseKeychain() {
67
+ process.stderr.write(`[${JAIL_MARKER}] refused a call to the macOS security CLI\n`);
68
+ throw Object.assign(new Error(`${JAIL_MARKER}: Keychain access blocked (security CLI)`), {
69
+ code: "EACCES",
70
+ });
71
+ }
72
+ const cp = childProcess;
73
+ for (const name of ["spawn", "spawnSync", "execFile", "execFileSync", "exec", "execSync"]) {
74
+ const original = cp[name];
75
+ cp[name] = function jailed(...args) {
76
+ if (isSecurityCli(args[0]))
77
+ refuseKeychain();
78
+ if (isBrowserOpener(args[0]))
79
+ refuseBrowser();
80
+ return original.apply(this, args);
81
+ };
82
+ }
83
+ // Make `import { execFileSync } from "child_process"` in the server see the
84
+ // jailed functions, not the originals.
85
+ syncBuiltinESMExports();
@@ -9,11 +9,19 @@ export interface SpawnResult {
9
9
  exitCode: number | null;
10
10
  signal: string | null;
11
11
  }
12
- /** Spawn a process synchronously and capture all output */
12
+ /**
13
+ * Spawn a process synchronously and capture all output. `env` is laid over
14
+ * the hermetic base (hermetic-env.ts), never over the parent's environment.
15
+ */
13
16
  export declare function spawnCli(config: McpServerConfig, binPath: string, args?: string[], env?: Record<string, string>, timeoutMs?: number): SpawnResult;
14
- /** Spawn a server process, wait for it to emit something on stderr, then return handle */
17
+ /** Spawn a server process in the hermetic env and return its handle */
15
18
  export declare function spawnServer(config: McpServerConfig, env?: Record<string, string>): ChildProcess;
16
- /** Send a signal to a process and wait for exit within timeout */
19
+ /**
20
+ * Send a signal to a process and wait for exit within timeout.
21
+ * A process that had already exited resolves at once with signal
22
+ * "ALREADY_EXITED" (it never started properly), instead of a misleading
23
+ * "TIMEOUT".
24
+ */
17
25
  export declare function sendSignalAndWait(proc: ChildProcess, signal: NodeJS.Signals, timeoutMs?: number): Promise<{
18
26
  exitCode: number | null;
19
27
  signal: string | null;
@@ -3,12 +3,16 @@
3
3
  */
4
4
  import { spawnSync, spawn } from "child_process";
5
5
  import path from "path";
6
- /** Spawn a process synchronously and capture all output */
6
+ import { hermeticEnv } from "./hermetic-env.js";
7
+ /**
8
+ * Spawn a process synchronously and capture all output. `env` is laid over
9
+ * the hermetic base (hermetic-env.ts), never over the parent's environment.
10
+ */
7
11
  export function spawnCli(config, binPath, args = [], env, timeoutMs = 10_000) {
8
12
  const fullPath = path.resolve(config.repoRoot, binPath);
9
- const result = spawnSync("node", [fullPath, ...args], {
13
+ const result = spawnSync(process.execPath, [fullPath, ...args], {
10
14
  timeout: timeoutMs,
11
- env: { ...process.env, ...env },
15
+ env: hermeticEnv(env),
12
16
  cwd: config.repoRoot,
13
17
  });
14
18
  return {
@@ -18,18 +22,26 @@ export function spawnCli(config, binPath, args = [], env, timeoutMs = 10_000) {
18
22
  signal: result.signal,
19
23
  };
20
24
  }
21
- /** Spawn a server process, wait for it to emit something on stderr, then return handle */
25
+ /** Spawn a server process in the hermetic env and return its handle */
22
26
  export function spawnServer(config, env) {
23
27
  const entry = config.serverEntry ?? "dist/index.js";
24
28
  const fullPath = path.resolve(config.repoRoot, entry);
25
- return spawn("node", [fullPath], {
26
- env: { ...process.env, ...env },
29
+ return spawn(process.execPath, [fullPath], {
30
+ env: hermeticEnv(env),
27
31
  cwd: config.repoRoot,
28
32
  stdio: ["pipe", "pipe", "pipe"],
29
33
  });
30
34
  }
31
- /** Send a signal to a process and wait for exit within timeout */
35
+ /**
36
+ * Send a signal to a process and wait for exit within timeout.
37
+ * A process that had already exited resolves at once with signal
38
+ * "ALREADY_EXITED" (it never started properly), instead of a misleading
39
+ * "TIMEOUT".
40
+ */
32
41
  export function sendSignalAndWait(proc, signal, timeoutMs = 3000) {
42
+ if (proc.exitCode !== null || proc.signalCode !== null) {
43
+ return Promise.resolve({ exitCode: proc.exitCode, signal: "ALREADY_EXITED" });
44
+ }
33
45
  return new Promise((resolve) => {
34
46
  const timer = setTimeout(() => {
35
47
  proc.kill("SIGKILL");
@@ -0,0 +1,58 @@
1
+ import type { McpServerConfig } from "../types.js";
2
+ export declare const PINO_KEYS: readonly ["level", "time", "pid", "hostname", "msg"];
3
+ /** How long the server gets to answer both requests (spawn + module load + startup). */
4
+ export declare const PROBE_RESPONSE_DEADLINE_MS = 15000;
5
+ /** Quiet time after the answers, so late background log lines are caught too. */
6
+ export declare const PROBE_FLUSH_MS = 1000;
7
+ /** Grace between SIGTERM and SIGKILL. */
8
+ export declare const PROBE_KILL_GRACE_MS = 3000;
9
+ export interface JsonRpcMessage {
10
+ jsonrpc?: string;
11
+ id?: number | string;
12
+ result?: Record<string, unknown>;
13
+ error?: unknown;
14
+ [k: string]: unknown;
15
+ }
16
+ export interface StdioProbe {
17
+ stdout: string;
18
+ stderr: string;
19
+ /** Non-empty stdout lines */
20
+ lines: string[];
21
+ /** Parsed JSON-RPC responses by id */
22
+ responses: Record<string, JsonRpcMessage>;
23
+ /** The server exited by itself before the probe stopped it */
24
+ exitedEarly: boolean;
25
+ exitCode: number | null;
26
+ }
27
+ /** The env a server is started with for stdio probes and shutdown checks. */
28
+ export declare function serverStartEnv(config: McpServerConfig, extra?: Record<string, string>): Record<string, string>;
29
+ export declare function probeStdio(config: McpServerConfig, env?: Record<string, string>): Promise<StdioProbe>;
30
+ /** One default probe per config, shared by the suites that need a live server. */
31
+ export declare function probeStdioOnce(config: McpServerConfig): Promise<StdioProbe>;
32
+ /** The tools array from the probe's tools/list answer, or [] if there was none. */
33
+ export declare function probedTools(probe: StdioProbe): unknown[];
34
+ /** Title of the smoke test that checks the server starts. Other failures point at it. */
35
+ export declare const STARTUP_TEST_TITLE = "server starts with fake credentials and answers initialize and tools/list";
36
+ /**
37
+ * Why the server did not answer `initialize` and `tools/list`, or [] if it
38
+ * answered both. A server that exits at credential validation used to pass
39
+ * every spawn-based check by never being exercised; this names the failure.
40
+ * Lists the names (never the values) of the fakes the server was given.
41
+ */
42
+ export declare function startupProblems(probe: StdioProbe, config: Pick<McpServerConfig, "requiredEnvVars" | "startupEnv">): string[];
43
+ /** Every stdout line that is not a clean JSON-RPC 2.0 frame (pino output, console.log, ...). */
44
+ export declare function stdoutLineProblems(probe: StdioProbe): string[];
45
+ /**
46
+ * Everything wrong with what the server wrote to stdout. Empty means pure AND
47
+ * exercised: an empty stdout is a failure, because a server that never
48
+ * answered tells us nothing about its logger.
49
+ */
50
+ export declare function stdoutPurityProblems(probe: StdioProbe): string[];
51
+ /**
52
+ * The stdout purity test's failure message, or null if stdout was clean and
53
+ * exercised. The logger fix is offered only when something other than
54
+ * JSON-RPC actually reached stdout: a server that never started has a
55
+ * credential problem, not a logger problem.
56
+ */
57
+ export declare function purityFailure(probe: StdioProbe): string | null;
58
+ //# sourceMappingURL=stdio-probe.d.ts.map