@drak-marketing/mcp-test-harness 0.2.3 → 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 +100 -0
- package/README.md +98 -7
- package/dist/helpers/dist-module.d.ts +6 -0
- package/dist/helpers/dist-module.js +26 -0
- package/dist/helpers/hermetic-env.d.ts +18 -0
- package/dist/helpers/hermetic-env.js +89 -0
- package/dist/helpers/jail-marker.d.ts +8 -0
- package/dist/helpers/jail-marker.js +7 -0
- package/dist/helpers/network-jail.d.ts +3 -0
- package/dist/helpers/network-jail.js +85 -0
- package/dist/helpers/spawn.d.ts +11 -3
- package/dist/helpers/spawn.js +19 -7
- package/dist/helpers/stdio-probe.d.ts +58 -0
- package/dist/helpers/stdio-probe.js +234 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +34 -32
- package/dist/suites/dependency-health.js +30 -17
- package/dist/suites/ender-strategic.js +0 -38
- package/dist/suites/graceful-shutdown.js +17 -15
- package/dist/suites/mayhem-adversarial.js +14 -85
- package/dist/suites/mcp-protocol.js +36 -23
- package/dist/suites/network-failures.js +24 -41
- package/dist/suites/ralph-chaos.js +4 -6
- package/dist/suites/smoke.js +12 -0
- package/dist/suites/stdout-purity.d.ts +8 -0
- package/dist/suites/stdout-purity.js +18 -107
- package/dist/suites/token-lifecycle.js +19 -33
- package/dist/types.d.ts +11 -3
- package/package.json +3 -1
- package/dist/suites/concurrent.d.ts +0 -3
- package/dist/suites/concurrent.js +0 -25
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Start a server over piped stdio (non-TTY, as Claude Desktop launches it),
|
|
3
|
+
* send initialize + tools/list, and capture everything it writes.
|
|
4
|
+
*
|
|
5
|
+
* The server gets fake credentials (fakeCredentialEnv) inside the hermetic,
|
|
6
|
+
* jailed env (hermeticEnv), so it can get past credential validation without
|
|
7
|
+
* any real secret or network access.
|
|
8
|
+
*/
|
|
9
|
+
import { spawn } from "child_process";
|
|
10
|
+
import path from "path";
|
|
11
|
+
import { fakeCredentialEnv, hermeticEnv } from "./hermetic-env.js";
|
|
12
|
+
import { JAIL_MARKER } from "./jail-marker.js";
|
|
13
|
+
export const PINO_KEYS = ["level", "time", "pid", "hostname", "msg"];
|
|
14
|
+
/** How long the server gets to answer both requests (spawn + module load + startup). */
|
|
15
|
+
export const PROBE_RESPONSE_DEADLINE_MS = 15_000;
|
|
16
|
+
/** Quiet time after the answers, so late background log lines are caught too. */
|
|
17
|
+
export const PROBE_FLUSH_MS = 1_000;
|
|
18
|
+
/** Grace between SIGTERM and SIGKILL. */
|
|
19
|
+
export const PROBE_KILL_GRACE_MS = 3_000;
|
|
20
|
+
/** The env a server is started with for stdio probes and shutdown checks. */
|
|
21
|
+
export function serverStartEnv(config, extra = {}) {
|
|
22
|
+
return hermeticEnv({ ...fakeCredentialEnv(config), ...extra });
|
|
23
|
+
}
|
|
24
|
+
export async function probeStdio(config, env = serverStartEnv(config, { LOG_LEVEL: "debug" })) {
|
|
25
|
+
const entry = config.serverEntry ?? "dist/index.js";
|
|
26
|
+
const fullPath = path.resolve(config.repoRoot, entry);
|
|
27
|
+
const proc = spawn(process.execPath, [fullPath], {
|
|
28
|
+
cwd: config.repoRoot,
|
|
29
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
30
|
+
env,
|
|
31
|
+
});
|
|
32
|
+
let stdout = "";
|
|
33
|
+
let stderr = "";
|
|
34
|
+
let exited = false;
|
|
35
|
+
let exitCode = null;
|
|
36
|
+
const responses = {};
|
|
37
|
+
let onActivity = () => { };
|
|
38
|
+
proc.stdout?.on("data", (chunk) => {
|
|
39
|
+
stdout += chunk.toString("utf8");
|
|
40
|
+
for (const line of stdout.split("\n")) {
|
|
41
|
+
try {
|
|
42
|
+
const msg = JSON.parse(line);
|
|
43
|
+
if (msg && msg.id !== undefined)
|
|
44
|
+
responses[String(msg.id)] = msg;
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
/* partial or non-JSON line: judged later */
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
onActivity();
|
|
51
|
+
});
|
|
52
|
+
proc.stderr?.on("data", (chunk) => { stderr += chunk.toString("utf8"); });
|
|
53
|
+
proc.stdin?.on("error", () => { });
|
|
54
|
+
const exitPromise = new Promise((r) => {
|
|
55
|
+
proc.on("exit", (code) => {
|
|
56
|
+
exited = true;
|
|
57
|
+
exitCode = code;
|
|
58
|
+
onActivity();
|
|
59
|
+
r();
|
|
60
|
+
});
|
|
61
|
+
});
|
|
62
|
+
const send = (msg) => proc.stdin?.write(JSON.stringify(msg) + "\n");
|
|
63
|
+
send({
|
|
64
|
+
jsonrpc: "2.0",
|
|
65
|
+
id: 1,
|
|
66
|
+
method: "initialize",
|
|
67
|
+
params: {
|
|
68
|
+
protocolVersion: "2024-11-05",
|
|
69
|
+
capabilities: {},
|
|
70
|
+
clientInfo: { name: "mcp-test-harness", version: "1.0.0" },
|
|
71
|
+
},
|
|
72
|
+
});
|
|
73
|
+
send({ jsonrpc: "2.0", method: "notifications/initialized" });
|
|
74
|
+
send({ jsonrpc: "2.0", id: 2, method: "tools/list" });
|
|
75
|
+
// Wait for both answers, the server exiting, or the deadline.
|
|
76
|
+
await new Promise((resolve) => {
|
|
77
|
+
const deadline = setTimeout(resolve, PROBE_RESPONSE_DEADLINE_MS);
|
|
78
|
+
onActivity = () => {
|
|
79
|
+
if (exited || (responses["1"] && responses["2"])) {
|
|
80
|
+
clearTimeout(deadline);
|
|
81
|
+
resolve();
|
|
82
|
+
}
|
|
83
|
+
};
|
|
84
|
+
onActivity();
|
|
85
|
+
});
|
|
86
|
+
const exitedEarly = exited;
|
|
87
|
+
if (!exited) {
|
|
88
|
+
await new Promise((r) => setTimeout(r, PROBE_FLUSH_MS));
|
|
89
|
+
proc.kill("SIGTERM");
|
|
90
|
+
await Promise.race([
|
|
91
|
+
exitPromise,
|
|
92
|
+
new Promise((r) => setTimeout(() => { proc.kill("SIGKILL"); r(); }, PROBE_KILL_GRACE_MS)),
|
|
93
|
+
]);
|
|
94
|
+
}
|
|
95
|
+
const lines = stdout.split("\n").filter((l) => l.trim().length > 0);
|
|
96
|
+
return { stdout, stderr, lines, responses, exitedEarly, exitCode };
|
|
97
|
+
}
|
|
98
|
+
const probeCache = new WeakMap();
|
|
99
|
+
/** One default probe per config, shared by the suites that need a live server. */
|
|
100
|
+
export function probeStdioOnce(config) {
|
|
101
|
+
let p = probeCache.get(config);
|
|
102
|
+
if (!p) {
|
|
103
|
+
p = probeStdio(config);
|
|
104
|
+
probeCache.set(config, p);
|
|
105
|
+
}
|
|
106
|
+
return p;
|
|
107
|
+
}
|
|
108
|
+
/** The tools array from the probe's tools/list answer, or [] if there was none. */
|
|
109
|
+
export function probedTools(probe) {
|
|
110
|
+
const tools = probe.responses["2"]?.result?.tools;
|
|
111
|
+
return Array.isArray(tools) ? tools : [];
|
|
112
|
+
}
|
|
113
|
+
function stderrTail(probe, n = 15) {
|
|
114
|
+
return probe.stderr.split("\n").filter((l) => l.trim()).slice(-n).join("\n") || "(empty)";
|
|
115
|
+
}
|
|
116
|
+
/** Title of the smoke test that checks the server starts. Other failures point at it. */
|
|
117
|
+
export const STARTUP_TEST_TITLE = "server starts with fake credentials and answers initialize and tools/list";
|
|
118
|
+
/** Where the README explains how to get a server started with fakes. */
|
|
119
|
+
const README_SECTION = 'the harness README, "Starting the server with fake credentials"';
|
|
120
|
+
/**
|
|
121
|
+
* Why the server did not answer `initialize` and `tools/list`, or [] if it
|
|
122
|
+
* answered both. A server that exits at credential validation used to pass
|
|
123
|
+
* every spawn-based check by never being exercised; this names the failure.
|
|
124
|
+
* Lists the names (never the values) of the fakes the server was given.
|
|
125
|
+
*/
|
|
126
|
+
export function startupProblems(probe, config) {
|
|
127
|
+
const initOk = Boolean(probe.responses["1"]?.result);
|
|
128
|
+
const listOk = Array.isArray(probe.responses["2"]?.result?.tools);
|
|
129
|
+
if (initOk && listOk)
|
|
130
|
+
return [];
|
|
131
|
+
const unanswered = !initOk && !listOk
|
|
132
|
+
? "initialize and tools/list were not answered"
|
|
133
|
+
: !initOk
|
|
134
|
+
? "initialize was not answered"
|
|
135
|
+
: "tools/list was not answered";
|
|
136
|
+
const how = probe.exitedEarly
|
|
137
|
+
? `the server exited by itself (code ${probe.exitCode})`
|
|
138
|
+
: `the server was still running after ${PROBE_RESPONSE_DEADLINE_MS}ms`;
|
|
139
|
+
const faked = Object.keys(fakeCredentialEnv(config));
|
|
140
|
+
const given = faked.length > 0
|
|
141
|
+
? `It was started with fake values for: ${faked.join(", ")}.`
|
|
142
|
+
: "It was started with no fake credentials: requiredEnvVars and startupEnv are both empty.";
|
|
143
|
+
const lines = [
|
|
144
|
+
`${unanswered}: ${how}. ${given}`,
|
|
145
|
+
"To get it started, read its stderr below, then:",
|
|
146
|
+
" - a missing env var: add it to requiredEnvVars (the harness passes fake-<name>);",
|
|
147
|
+
" - a value whose format it checks, or a var it needs but does not list: set a well-formed fake in startupEnv;",
|
|
148
|
+
" - a config or key file it cannot find: point its path env var at a fixture file via startupEnv (HOME is an empty directory).",
|
|
149
|
+
];
|
|
150
|
+
const refusals = probe.stderr.split("\n").filter((l) => l.includes(`[${JAIL_MARKER}]`)).length;
|
|
151
|
+
if (refusals > 0) {
|
|
152
|
+
lines.push(` - the jail refused ${refusals} network or Keychain call${refusals === 1 ? "" : "s"} at startup (see stderr). ` +
|
|
153
|
+
"If a fatal startup check is what stopped it, give the server a skip flag and set it in startupEnv.");
|
|
154
|
+
}
|
|
155
|
+
lines.push(`See ${README_SECTION}.`, `server stderr:\n${stderrTail(probe)}`);
|
|
156
|
+
return [lines.join("\n")];
|
|
157
|
+
}
|
|
158
|
+
/** Every stdout line that is not a clean JSON-RPC 2.0 frame (pino output, console.log, ...). */
|
|
159
|
+
export function stdoutLineProblems(probe) {
|
|
160
|
+
const problems = [];
|
|
161
|
+
for (const line of probe.lines) {
|
|
162
|
+
let parsed;
|
|
163
|
+
try {
|
|
164
|
+
parsed = JSON.parse(line);
|
|
165
|
+
}
|
|
166
|
+
catch {
|
|
167
|
+
problems.push(`non-JSON on stdout: ${line.slice(0, 200)}`);
|
|
168
|
+
continue;
|
|
169
|
+
}
|
|
170
|
+
if (parsed.jsonrpc !== "2.0") {
|
|
171
|
+
const keys = Object.keys(parsed).join(",");
|
|
172
|
+
problems.push(`stdout line missing jsonrpc:"2.0" (keys: ${keys}): ${line.slice(0, 200)}`);
|
|
173
|
+
continue;
|
|
174
|
+
}
|
|
175
|
+
for (const k of PINO_KEYS) {
|
|
176
|
+
if (k in parsed) {
|
|
177
|
+
problems.push(`stdout line has top-level pino key "${k}": ${line.slice(0, 200)}`);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
return problems;
|
|
182
|
+
}
|
|
183
|
+
/**
|
|
184
|
+
* Everything wrong with what the server wrote to stdout. Empty means pure AND
|
|
185
|
+
* exercised: an empty stdout is a failure, because a server that never
|
|
186
|
+
* answered tells us nothing about its logger.
|
|
187
|
+
*/
|
|
188
|
+
export function stdoutPurityProblems(probe) {
|
|
189
|
+
const problems = stdoutLineProblems(probe);
|
|
190
|
+
if (probe.lines.length === 0) {
|
|
191
|
+
const how = probe.exitedEarly
|
|
192
|
+
? `it exited by itself (code ${probe.exitCode}) before answering`
|
|
193
|
+
: `it did not answer within ${PROBE_RESPONSE_DEADLINE_MS}ms`;
|
|
194
|
+
problems.push(`server produced no stdout: ${how}, so its stdout was never exercised. ` +
|
|
195
|
+
`The "${STARTUP_TEST_TITLE}" failure says how to get it started.` +
|
|
196
|
+
"\nserver stderr:\n" + stderrTail(probe));
|
|
197
|
+
return problems;
|
|
198
|
+
}
|
|
199
|
+
const init = probe.responses["1"];
|
|
200
|
+
if (!init || !init.result) {
|
|
201
|
+
problems.push(`no initialize result on stdout (id 1). server stderr:\n${stderrTail(probe)}`);
|
|
202
|
+
}
|
|
203
|
+
const list = probe.responses["2"];
|
|
204
|
+
if (!list || !Array.isArray(list.result?.tools)) {
|
|
205
|
+
problems.push(`no tools/list result on stdout (id 2). server stderr:\n${stderrTail(probe)}`);
|
|
206
|
+
}
|
|
207
|
+
return problems;
|
|
208
|
+
}
|
|
209
|
+
const PINO_FIX_HINT = "Fix: in your logger module, pass `pino.destination(2)` as the " +
|
|
210
|
+
"SECOND argument to `pino(...)` unconditionally. Do not gate it on " +
|
|
211
|
+
"`process.stderr.isTTY`: Claude Desktop spawns the server with pipes, " +
|
|
212
|
+
"not a TTY, and pino will silently default to stdout when no " +
|
|
213
|
+
"destination is specified.";
|
|
214
|
+
/**
|
|
215
|
+
* The stdout purity test's failure message, or null if stdout was clean and
|
|
216
|
+
* exercised. The logger fix is offered only when something other than
|
|
217
|
+
* JSON-RPC actually reached stdout: a server that never started has a
|
|
218
|
+
* credential problem, not a logger problem.
|
|
219
|
+
*/
|
|
220
|
+
export function purityFailure(probe) {
|
|
221
|
+
const problems = stdoutPurityProblems(probe);
|
|
222
|
+
if (problems.length === 0)
|
|
223
|
+
return null;
|
|
224
|
+
const offending = stdoutLineProblems(probe).length;
|
|
225
|
+
const preview = problems.slice(0, 5).join("\n - ");
|
|
226
|
+
const more = problems.length > 5 ? `\n ... and ${problems.length - 5} more` : "";
|
|
227
|
+
if (offending === 0) {
|
|
228
|
+
return ("stdout purity was not exercised: the server did not answer both initialize and tools/list, " +
|
|
229
|
+
`so there was nothing to judge. See the "${STARTUP_TEST_TITLE}" failure.\n - ${preview}${more}`);
|
|
230
|
+
}
|
|
231
|
+
return (`stdout contains non-JSON-RPC output (${offending} offending line${offending === 1 ? "" : "s"}):\n - ${preview}${more}` +
|
|
232
|
+
`\n\nstderr tail (for context):\n${probe.stderr.split("\n").slice(-10).join("\n")}` +
|
|
233
|
+
`\n\n${PINO_FIX_HINT}`);
|
|
234
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -9,5 +9,8 @@
|
|
|
9
9
|
export type { McpServerConfig } from "./types.js";
|
|
10
10
|
export { CONFIG_DEFAULTS } from "./types.js";
|
|
11
11
|
import type { McpServerConfig } from "./types.js";
|
|
12
|
+
type Suite = (config: McpServerConfig) => void;
|
|
13
|
+
/** The suites registered for a config, in order. Exported for the harness's own tests. */
|
|
14
|
+
export declare function suitesFor(config: McpServerConfig): Array<[string, Suite]>;
|
|
12
15
|
export declare function registerMcpTests(config: McpServerConfig): void;
|
|
13
16
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.js
CHANGED
|
@@ -22,44 +22,46 @@ import { configLoadingSuite } from "./suites/config-loading.js";
|
|
|
22
22
|
import { tokenLifecycleSuite } from "./suites/token-lifecycle.js";
|
|
23
23
|
import { outputContractSuite } from "./suites/output-contract.js";
|
|
24
24
|
import { stdoutPuritySuite } from "./suites/stdout-purity.js";
|
|
25
|
-
import { concurrentSuite } from "./suites/concurrent.js";
|
|
26
25
|
import { networkFailuresSuite } from "./suites/network-failures.js";
|
|
27
26
|
import { backwardCompatSuite } from "./suites/backward-compat.js";
|
|
28
27
|
import { ralphChaosSuite } from "./suites/ralph-chaos.js";
|
|
29
28
|
import { enderStrategicSuite } from "./suites/ender-strategic.js";
|
|
30
29
|
import { mayhemAdversarialSuite } from "./suites/mayhem-adversarial.js";
|
|
31
|
-
|
|
32
|
-
|
|
30
|
+
/** The suites registered for a config, in order. Exported for the harness's own tests. */
|
|
31
|
+
export function suitesFor(config) {
|
|
32
|
+
const suites = [
|
|
33
33
|
// Always run
|
|
34
|
-
buildIntegritySuite
|
|
35
|
-
smokeSuite
|
|
36
|
-
crossPlatformSuite
|
|
37
|
-
mcpProtocolSuite
|
|
38
|
-
dependencyHealthSuite
|
|
39
|
-
versionPublishSuite
|
|
40
|
-
observabilitySuite
|
|
41
|
-
inputSanitizationSuite
|
|
42
|
-
outputContractSuite
|
|
43
|
-
stdoutPuritySuite
|
|
44
|
-
concurrentSuite(config);
|
|
34
|
+
["build-integrity", buildIntegritySuite],
|
|
35
|
+
["smoke", smokeSuite],
|
|
36
|
+
["cross-platform", crossPlatformSuite],
|
|
37
|
+
["mcp-protocol", mcpProtocolSuite],
|
|
38
|
+
["dependency-health", dependencyHealthSuite],
|
|
39
|
+
["version-publish", versionPublishSuite],
|
|
40
|
+
["observability", observabilitySuite],
|
|
41
|
+
["input-sanitization", inputSanitizationSuite],
|
|
42
|
+
["output-contract", outputContractSuite],
|
|
43
|
+
["stdout-purity", stdoutPuritySuite],
|
|
45
44
|
// Character suites (always run)
|
|
46
|
-
ralphChaosSuite
|
|
47
|
-
enderStrategicSuite
|
|
48
|
-
mayhemAdversarialSuite
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
45
|
+
["ralph-chaos", ralphChaosSuite],
|
|
46
|
+
["ender-strategic", enderStrategicSuite],
|
|
47
|
+
["mayhem-adversarial", mayhemAdversarialSuite],
|
|
48
|
+
];
|
|
49
|
+
// Conditional on capabilities
|
|
50
|
+
if (config.hasCredentials) {
|
|
51
|
+
suites.push(["credential-security", credentialSecuritySuite], ["token-lifecycle", tokenLifecycleSuite], ["backward-compat", backwardCompatSuite]);
|
|
52
|
+
}
|
|
53
|
+
if (config.hasResilience)
|
|
54
|
+
suites.push(["network-failures", networkFailuresSuite]);
|
|
55
|
+
if (config.requiredEnvVars.length > 0)
|
|
56
|
+
suites.push(["config-loading", configLoadingSuite]);
|
|
57
|
+
// Always: the server is started with fakes derived from requiredEnvVars
|
|
58
|
+
// (plus startupEnv), so this no longer depends on startupEnv being set.
|
|
59
|
+
suites.push(["graceful-shutdown", gracefulShutdownSuite]);
|
|
60
|
+
return suites;
|
|
61
|
+
}
|
|
62
|
+
export function registerMcpTests(config) {
|
|
63
|
+
describe(`${config.name} shared harness`, () => {
|
|
64
|
+
for (const [, suite] of suitesFor(config))
|
|
65
|
+
suite(config);
|
|
64
66
|
});
|
|
65
67
|
}
|
|
@@ -4,33 +4,46 @@ import path from "path";
|
|
|
4
4
|
import { walk, findMatches, formatViolations } from "../helpers/source-lint.js";
|
|
5
5
|
export function dependencyHealthSuite(config) {
|
|
6
6
|
describe("dependency health", () => {
|
|
7
|
-
it("no critical npm audit vulnerabilities", () => {
|
|
7
|
+
it("no critical npm audit vulnerabilities", (ctx) => {
|
|
8
|
+
// `npm audit` exits non-zero whenever it finds anything, so its JSON is
|
|
9
|
+
// read from the thrown error too. Before 0.3.0 the catch swallowed both
|
|
10
|
+
// that exit and the expect() below, so this test could never fail.
|
|
11
|
+
let out = "";
|
|
8
12
|
try {
|
|
9
|
-
|
|
13
|
+
out = execSync("npm audit --json 2>/dev/null", {
|
|
10
14
|
cwd: config.repoRoot,
|
|
11
15
|
encoding: "utf-8",
|
|
12
16
|
timeout: 30_000,
|
|
13
17
|
});
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
const
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
18
|
+
}
|
|
19
|
+
catch (err) {
|
|
20
|
+
const stdout = err.stdout;
|
|
21
|
+
out = typeof stdout === "string" ? stdout : "";
|
|
22
|
+
}
|
|
23
|
+
let criticals;
|
|
24
|
+
let highs;
|
|
25
|
+
try {
|
|
26
|
+
const audit = JSON.parse(out);
|
|
27
|
+
criticals = audit.metadata?.vulnerabilities?.critical;
|
|
28
|
+
highs = audit.metadata?.vulnerabilities?.high;
|
|
22
29
|
}
|
|
23
30
|
catch {
|
|
24
|
-
|
|
25
|
-
|
|
31
|
+
/* fall through to the skip */
|
|
32
|
+
}
|
|
33
|
+
// npm audit could not run (offline, no lockfile, timeout): skip visibly.
|
|
34
|
+
if (typeof criticals !== "number")
|
|
35
|
+
return ctx.skip();
|
|
36
|
+
expect(criticals, `${criticals} critical npm audit vulnerabilities found`).toBe(0);
|
|
37
|
+
// High is a warning, not a blocker
|
|
38
|
+
if (typeof highs === "number" && highs > 0) {
|
|
39
|
+
process.stderr.write(`[warning] ${highs} high npm audit vulnerabilities\n`);
|
|
26
40
|
}
|
|
27
41
|
// Must exceed the execSync budget above. Without it this runs under
|
|
28
42
|
// vitest's 5s default, so a slow-but-healthy `npm audit` is killed by the
|
|
29
|
-
// runner before the subprocess can time out
|
|
30
|
-
//
|
|
31
|
-
//
|
|
32
|
-
//
|
|
33
|
-
// dependency-health-timeout.test.ts pins the two numbers in agreement.
|
|
43
|
+
// runner before the subprocess can time out. Observed 2026-09-03: 10.7s
|
|
44
|
+
// on every ubuntu GitHub runner, 30.0s locally, while all three Windows
|
|
45
|
+
// legs passed. tests/dependency-health-timeout.test.ts pins the two
|
|
46
|
+
// numbers in agreement.
|
|
34
47
|
}, 35_000);
|
|
35
48
|
it("no require() in ESM source files", () => {
|
|
36
49
|
const srcDir = path.join(config.repoRoot, config.srcDir ?? "src");
|
|
@@ -14,15 +14,6 @@ export function enderStrategicSuite(config) {
|
|
|
14
14
|
// ----------------------------------------------------------------
|
|
15
15
|
// CLI consistency: every MCP must have identical CLI contract
|
|
16
16
|
// ----------------------------------------------------------------
|
|
17
|
-
it("--help prints to stderr (not stdout, which is reserved for JSON-RPC)", () => {
|
|
18
|
-
const result = spawnCli(config, entry, ["--help"]);
|
|
19
|
-
// stdout should be empty or minimal -- help goes to stderr
|
|
20
|
-
// Some servers may write help to stdout (acceptable but not ideal)
|
|
21
|
-
if (result.stdout.length > 0 && result.stderr.length === 0) {
|
|
22
|
-
process.stderr.write(`[warning] ${config.name}: --help writes to stdout instead of stderr. ` +
|
|
23
|
-
`stdout is reserved for JSON-RPC in MCP.\n`);
|
|
24
|
-
}
|
|
25
|
-
});
|
|
26
17
|
it("--version output is ONLY the semver string (no decoration)", () => {
|
|
27
18
|
const result = spawnCli(config, entry, ["--version"]);
|
|
28
19
|
const output = (result.stdout + result.stderr).trim();
|
|
@@ -122,34 +113,5 @@ export function enderStrategicSuite(config) {
|
|
|
122
113
|
expect(exitCalls.length, `Found ${exitCalls.length} process.exit() calls inside request handlers. ` +
|
|
123
114
|
`This kills the server on any tool error instead of returning an error response.`).toBe(0);
|
|
124
115
|
});
|
|
125
|
-
// ----------------------------------------------------------------
|
|
126
|
-
// Env var collision detection
|
|
127
|
-
// ----------------------------------------------------------------
|
|
128
|
-
it("env var prefix is unique (no collision with other MCPs)", () => {
|
|
129
|
-
// Known MCP env var prefixes -- if this test fails, two MCPs share a prefix
|
|
130
|
-
const knownPrefixes = [
|
|
131
|
-
"GOOGLE_ADS_",
|
|
132
|
-
"BING_ADS_",
|
|
133
|
-
"LINKEDIN_ADS_",
|
|
134
|
-
"REDDIT_",
|
|
135
|
-
"GA4_",
|
|
136
|
-
"GOOGLE_GSC_",
|
|
137
|
-
"META_",
|
|
138
|
-
];
|
|
139
|
-
// Check that this MCP's required env vars don't START with another MCP's prefix
|
|
140
|
-
// (pollution risk)
|
|
141
|
-
for (const envVar of config.requiredEnvVars) {
|
|
142
|
-
for (const prefix of knownPrefixes) {
|
|
143
|
-
if (prefix === config.envPrefix)
|
|
144
|
-
continue; // skip our own prefix
|
|
145
|
-
if (envVar.startsWith(prefix)) {
|
|
146
|
-
process.stderr.write(`[warning] ${config.name}: env var "${envVar}" starts with another MCP's prefix "${prefix}". ` +
|
|
147
|
-
`Risk of env var pollution if both MCPs are installed.\n`);
|
|
148
|
-
}
|
|
149
|
-
}
|
|
150
|
-
}
|
|
151
|
-
// This is advisory -- always passes but logs warnings
|
|
152
|
-
expect(true).toBe(true);
|
|
153
|
-
});
|
|
154
116
|
});
|
|
155
117
|
}
|
|
@@ -2,23 +2,25 @@ import { describe, it, expect } from "vitest";
|
|
|
2
2
|
import path from "path";
|
|
3
3
|
import { existsSync, readFileSync } from "fs";
|
|
4
4
|
import { spawnServer, sendSignalAndWait } from "../helpers/spawn.js";
|
|
5
|
+
import { fakeCredentialEnv } from "../helpers/hermetic-env.js";
|
|
5
6
|
export function gracefulShutdownSuite(config) {
|
|
6
7
|
describe("graceful shutdown", () => {
|
|
7
|
-
//
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
8
|
+
// Started with fake credentials (requiredEnvVars + startupEnv) so it gets
|
|
9
|
+
// past credential validation. A server that still exits on its own fails
|
|
10
|
+
// with ALREADY_EXITED rather than passing or timing out.
|
|
11
|
+
for (const signal of ["SIGTERM", "SIGINT"]) {
|
|
12
|
+
it(`${signal} causes clean exit within 3 seconds`, async () => {
|
|
13
|
+
const proc = spawnServer(config, fakeCredentialEnv(config));
|
|
14
|
+
let stderr = "";
|
|
15
|
+
proc.stderr?.on("data", (c) => { stderr += c.toString("utf8"); });
|
|
16
|
+
// Give server a moment to start
|
|
17
|
+
await new Promise((r) => setTimeout(r, 1000));
|
|
18
|
+
const result = await sendSignalAndWait(proc, signal, 3000);
|
|
19
|
+
expect(result.signal, `server exited (code ${result.exitCode}) before ${signal} was sent, so shutdown was never tested. ` +
|
|
20
|
+
`Give it fake credentials via requiredEnvVars or startupEnv.\nstderr:\n${stderr.slice(-1500)}`).not.toBe("ALREADY_EXITED");
|
|
21
|
+
expect(result.signal, `server did not exit within 3s of ${signal}`).not.toBe("TIMEOUT");
|
|
22
|
+
}, 10_000);
|
|
23
|
+
}
|
|
22
24
|
it("SIGPIPE handler exists in source", () => {
|
|
23
25
|
const indexPath = path.join(config.repoRoot, config.serverEntry ?? "dist/index.js");
|
|
24
26
|
if (!existsSync(indexPath))
|
|
@@ -7,57 +7,32 @@ import path from "path";
|
|
|
7
7
|
import { existsSync, readFileSync, writeFileSync, unlinkSync } from "fs";
|
|
8
8
|
import { tmpdir } from "os";
|
|
9
9
|
import { walk, findMatches, formatViolations } from "../helpers/source-lint.js";
|
|
10
|
+
import { importDistModule, pickFn } from "../helpers/dist-module.js";
|
|
10
11
|
export function mayhemAdversarialSuite(config) {
|
|
11
12
|
describe("mayhem: adversarial (break everything)", () => {
|
|
12
13
|
const entry = config.serverEntry ?? "dist/index.js";
|
|
13
14
|
const srcDir = path.join(config.repoRoot, config.srcDir ?? "src");
|
|
14
15
|
// ----------------------------------------------------------------
|
|
15
|
-
// Massive response handling: safeResponse or equivalent exists
|
|
16
|
-
// ----------------------------------------------------------------
|
|
17
|
-
it("has response size limiting for large API responses", () => {
|
|
18
|
-
const entryPath = path.resolve(config.repoRoot, entry);
|
|
19
|
-
if (!existsSync(entryPath))
|
|
20
|
-
return;
|
|
21
|
-
const src = readFileSync(entryPath, "utf-8");
|
|
22
|
-
const hasSizeLimit = src.includes("safeResponse") ||
|
|
23
|
-
src.includes("MAX_RESPONSE") ||
|
|
24
|
-
src.includes("truncat") ||
|
|
25
|
-
src.includes("slice(0,") ||
|
|
26
|
-
src.includes(".slice(");
|
|
27
|
-
if (!hasSizeLimit) {
|
|
28
|
-
process.stderr.write(`[warning] ${config.name}: no response size limiting detected. ` +
|
|
29
|
-
`Large API responses may exceed MCP transport limits and crash the client.\n`);
|
|
30
|
-
}
|
|
31
|
-
// Advisory for now -- log warning but don't fail
|
|
32
|
-
expect(true).toBe(true);
|
|
33
|
-
});
|
|
34
|
-
// ----------------------------------------------------------------
|
|
35
16
|
// Unicode in credential paths
|
|
36
17
|
// ----------------------------------------------------------------
|
|
37
|
-
it("credential path handling works with unicode characters", async () => {
|
|
18
|
+
it("credential path handling works with unicode characters", async (ctx) => {
|
|
38
19
|
if (!config.hasCredentials)
|
|
39
20
|
return;
|
|
21
|
+
const readFn = pickFn(await importDistModule(config, "credentials"), "readStoredCredentials");
|
|
22
|
+
if (!readFn)
|
|
23
|
+
return ctx.skip();
|
|
24
|
+
const unicodePath = path.join(tmpdir(), `mcp-tst-ünïcödé-${Date.now()}.json`);
|
|
25
|
+
writeFileSync(unicodePath, JSON.stringify({ version: 1, refresh_token: "test" }));
|
|
40
26
|
try {
|
|
41
|
-
|
|
42
|
-
const
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
writeFileSync(unicodePath, JSON.stringify({ version: 1, refresh_token: "test" }));
|
|
27
|
+
// Must not throw (it used to be swallowed); a parse or a null are both fine.
|
|
28
|
+
const result = readFn(unicodePath);
|
|
29
|
+
expect(result === null || typeof result === "object").toBe(true);
|
|
30
|
+
}
|
|
31
|
+
finally {
|
|
47
32
|
try {
|
|
48
|
-
|
|
49
|
-
// Should either parse successfully or return null -- not throw
|
|
50
|
-
expect(result === null || typeof result === "object").toBe(true);
|
|
51
|
-
}
|
|
52
|
-
finally {
|
|
53
|
-
try {
|
|
54
|
-
unlinkSync(unicodePath);
|
|
55
|
-
}
|
|
56
|
-
catch { }
|
|
33
|
+
unlinkSync(unicodePath);
|
|
57
34
|
}
|
|
58
|
-
|
|
59
|
-
catch {
|
|
60
|
-
// Module may not be requireable -- skip
|
|
35
|
+
catch { }
|
|
61
36
|
}
|
|
62
37
|
});
|
|
63
38
|
// ----------------------------------------------------------------
|
|
@@ -76,34 +51,6 @@ export function mayhemAdversarialSuite(config) {
|
|
|
76
51
|
expect(usesAtomicWrite, "Credential writes should use writeFileSync (atomic) not streams (race-prone)").toBe(true);
|
|
77
52
|
});
|
|
78
53
|
// ----------------------------------------------------------------
|
|
79
|
-
// ENOSPC handling: disk full on credential write
|
|
80
|
-
// ----------------------------------------------------------------
|
|
81
|
-
it("credential write function has error handling", () => {
|
|
82
|
-
if (!config.hasCredentials)
|
|
83
|
-
return;
|
|
84
|
-
const credPath = path.join(srcDir, "credentials.ts");
|
|
85
|
-
if (!existsSync(credPath))
|
|
86
|
-
return;
|
|
87
|
-
const src = readFileSync(credPath, "utf-8");
|
|
88
|
-
// Find the write function and check it has try/catch or at least doesn't
|
|
89
|
-
// let errors propagate silently
|
|
90
|
-
const writeSection = src.slice(src.indexOf("writeStored") || 0);
|
|
91
|
-
const firstFunctionEnd = writeSection.indexOf("\n}\n");
|
|
92
|
-
const writeFn = writeSection.slice(0, firstFunctionEnd + 3);
|
|
93
|
-
// chmod is often in a try/catch (best-effort on POSIX). The write itself
|
|
94
|
-
// may throw and that's OK -- it should propagate to the caller.
|
|
95
|
-
// What's NOT OK is swallowing write errors silently.
|
|
96
|
-
const swallowsWriteError = writeFn.includes("try") &&
|
|
97
|
-
writeFn.includes("writeFileSync") &&
|
|
98
|
-
writeFn.includes("catch") &&
|
|
99
|
-
!writeFn.includes("chmod"); // if try/catch only wraps chmod, that's fine
|
|
100
|
-
if (swallowsWriteError) {
|
|
101
|
-
process.stderr.write(`[warning] ${config.name}: writeStoredCredentials may swallow write errors. ` +
|
|
102
|
-
`ENOSPC or permission errors should propagate to the caller.\n`);
|
|
103
|
-
}
|
|
104
|
-
expect(true).toBe(true);
|
|
105
|
-
});
|
|
106
|
-
// ----------------------------------------------------------------
|
|
107
54
|
// JSON-RPC before ready: startup code completes before accepting calls
|
|
108
55
|
// ----------------------------------------------------------------
|
|
109
56
|
it("server validates auth BEFORE connecting transport (fail-fast)", () => {
|
|
@@ -128,24 +75,6 @@ export function mayhemAdversarialSuite(config) {
|
|
|
128
75
|
expect(v, formatViolations("no eval() or new Function()", v)).toEqual([]);
|
|
129
76
|
});
|
|
130
77
|
// ----------------------------------------------------------------
|
|
131
|
-
// No hardcoded API endpoints (should be constants, not scattered)
|
|
132
|
-
// ----------------------------------------------------------------
|
|
133
|
-
it("API base URLs are defined as constants, not scattered", () => {
|
|
134
|
-
const files = walk(srcDir);
|
|
135
|
-
const opts = {
|
|
136
|
-
baseDir: srcDir,
|
|
137
|
-
ignorePatterns: [...(config.sourceLintIgnore ?? []), "auth-cli.ts"],
|
|
138
|
-
exempt: new Set(["errors.ts", "tools.ts"]),
|
|
139
|
-
};
|
|
140
|
-
// Count how many files contain raw API URL strings
|
|
141
|
-
const v = findMatches(files, /["'`]https:\/\/(graph\.facebook|googleads\.googleapis|api\.linkedin|ads-api\.reddit|searchconsole\.googleapis|analyticsdata\.googleapis)/, opts);
|
|
142
|
-
if (v.length > 3) {
|
|
143
|
-
process.stderr.write(`[warning] ${config.name}: API base URLs appear in ${v.length} locations. ` +
|
|
144
|
-
`Consider centralizing as constants for easier rotation.\n`);
|
|
145
|
-
}
|
|
146
|
-
expect(true).toBe(true);
|
|
147
|
-
});
|
|
148
|
-
// ----------------------------------------------------------------
|
|
149
78
|
// Credential file isn't world-readable after write
|
|
150
79
|
// ----------------------------------------------------------------
|
|
151
80
|
it("credential writes enforce restrictive permissions", () => {
|