@drak-marketing/mcp-test-harness 0.2.2

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.
Files changed (53) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +101 -0
  3. package/dist/helpers/pack.d.ts +9 -0
  4. package/dist/helpers/pack.js +57 -0
  5. package/dist/helpers/source-lint.d.ts +17 -0
  6. package/dist/helpers/source-lint.js +61 -0
  7. package/dist/helpers/spawn.d.ts +21 -0
  8. package/dist/helpers/spawn.js +44 -0
  9. package/dist/index.d.ts +13 -0
  10. package/dist/index.js +65 -0
  11. package/dist/suites/backward-compat.d.ts +3 -0
  12. package/dist/suites/backward-compat.js +28 -0
  13. package/dist/suites/build-integrity.d.ts +3 -0
  14. package/dist/suites/build-integrity.js +43 -0
  15. package/dist/suites/concurrent.d.ts +3 -0
  16. package/dist/suites/concurrent.js +25 -0
  17. package/dist/suites/config-loading.d.ts +3 -0
  18. package/dist/suites/config-loading.js +38 -0
  19. package/dist/suites/credential-security.d.ts +3 -0
  20. package/dist/suites/credential-security.js +36 -0
  21. package/dist/suites/cross-platform.d.ts +3 -0
  22. package/dist/suites/cross-platform.js +43 -0
  23. package/dist/suites/dependency-health.d.ts +3 -0
  24. package/dist/suites/dependency-health.js +45 -0
  25. package/dist/suites/ender-strategic.d.ts +3 -0
  26. package/dist/suites/ender-strategic.js +155 -0
  27. package/dist/suites/graceful-shutdown.d.ts +3 -0
  28. package/dist/suites/graceful-shutdown.js +31 -0
  29. package/dist/suites/input-sanitization.d.ts +3 -0
  30. package/dist/suites/input-sanitization.js +26 -0
  31. package/dist/suites/mayhem-adversarial.d.ts +3 -0
  32. package/dist/suites/mayhem-adversarial.js +175 -0
  33. package/dist/suites/mcp-protocol.d.ts +3 -0
  34. package/dist/suites/mcp-protocol.js +65 -0
  35. package/dist/suites/network-failures.d.ts +3 -0
  36. package/dist/suites/network-failures.js +49 -0
  37. package/dist/suites/observability.d.ts +3 -0
  38. package/dist/suites/observability.js +33 -0
  39. package/dist/suites/output-contract.d.ts +3 -0
  40. package/dist/suites/output-contract.js +34 -0
  41. package/dist/suites/ralph-chaos.d.ts +3 -0
  42. package/dist/suites/ralph-chaos.js +122 -0
  43. package/dist/suites/smoke.d.ts +3 -0
  44. package/dist/suites/smoke.js +50 -0
  45. package/dist/suites/stdout-purity.d.ts +3 -0
  46. package/dist/suites/stdout-purity.js +128 -0
  47. package/dist/suites/token-lifecycle.d.ts +3 -0
  48. package/dist/suites/token-lifecycle.js +64 -0
  49. package/dist/suites/version-publish.d.ts +3 -0
  50. package/dist/suites/version-publish.js +34 -0
  51. package/dist/types.d.ts +50 -0
  52. package/dist/types.js +15 -0
  53. package/package.json +50 -0
@@ -0,0 +1,43 @@
1
+ import { describe, it, expect } from "vitest";
2
+ import path from "path";
3
+ import { walk, findMatches, formatViolations } from "../helpers/source-lint.js";
4
+ export function crossPlatformSuite(config) {
5
+ describe("cross-platform portability", () => {
6
+ const srcDir = path.join(config.repoRoot, config.srcDir ?? "src");
7
+ const files = walk(srcDir);
8
+ const ignorePatterns = config.sourceLintIgnore ?? [];
9
+ const opts = { baseDir: srcDir, ignorePatterns };
10
+ it("no exec/execSync/spawn/spawnSync in source (use npm modules)", () => {
11
+ const v = findMatches(files, /\b(exec|execSync|execFile|execFileSync|spawn|spawnSync)\s*\(/, {
12
+ ...opts,
13
+ exempt: new Set(["platform.ts", "auth-cli.ts"]),
14
+ });
15
+ expect(v, formatViolations("no exec/spawn", v)).toEqual([]);
16
+ });
17
+ it("no Mac-specific command literals", () => {
18
+ const v = findMatches(files, /["'`](open|pbcopy|pbpaste|osascript|say|defaults|security|launchctl)\s/, opts);
19
+ expect(v, formatViolations("no Mac-only commands", v)).toEqual([]);
20
+ });
21
+ it("no hardcoded Unix absolute paths", () => {
22
+ const v = findMatches(files, /["'`](\/(Users|home|tmp|var|etc|opt|usr\/local|private\/tmp)\/)/, opts);
23
+ expect(v, formatViolations("no hardcoded Unix paths", v)).toEqual([]);
24
+ });
25
+ it("no tilde-expansion in string literals", () => {
26
+ const v = findMatches(files, /["'`]~\//, opts);
27
+ expect(v, formatViolations("no ~/", v)).toEqual([]);
28
+ });
29
+ it("MCP server index.ts never writes to stdout", () => {
30
+ const v = findMatches(files.filter((f) => path.basename(f) === "index.ts"), /\bconsole\.log\s*\(|process\.stdout\.write\s*\(/, opts);
31
+ expect(v, formatViolations("no stdout writes in MCP server", v)).toEqual([]);
32
+ });
33
+ it("ESM files don't use CommonJS require()", () => {
34
+ const tsFiles = files.filter((f) => f.endsWith(".ts"));
35
+ const v = findMatches(tsFiles, /\brequire\s*\(/, opts);
36
+ expect(v, formatViolations("no require() in ESM", v)).toEqual([]);
37
+ });
38
+ it("no new URL(import.meta.url).pathname (broken on Windows)", () => {
39
+ const v = findMatches(files, /new\s+URL\s*\(\s*import\.meta\.url\s*\)\s*\.\s*pathname/, opts);
40
+ expect(v, formatViolations("use fileURLToPath instead", v)).toEqual([]);
41
+ });
42
+ });
43
+ }
@@ -0,0 +1,3 @@
1
+ import type { McpServerConfig } from "../types.js";
2
+ export declare function dependencyHealthSuite(config: McpServerConfig): void;
3
+ //# sourceMappingURL=dependency-health.d.ts.map
@@ -0,0 +1,45 @@
1
+ import { describe, it, expect } from "vitest";
2
+ import { execSync } from "child_process";
3
+ import path from "path";
4
+ import { walk, findMatches, formatViolations } from "../helpers/source-lint.js";
5
+ export function dependencyHealthSuite(config) {
6
+ describe("dependency health", () => {
7
+ it("no critical npm audit vulnerabilities", () => {
8
+ try {
9
+ const result = execSync("npm audit --json 2>/dev/null", {
10
+ cwd: config.repoRoot,
11
+ encoding: "utf-8",
12
+ timeout: 30_000,
13
+ });
14
+ const audit = JSON.parse(result);
15
+ const criticals = audit.metadata?.vulnerabilities?.critical ?? 0;
16
+ const highs = audit.metadata?.vulnerabilities?.high ?? 0;
17
+ expect(criticals, `${criticals} critical npm audit vulnerabilities found`).toBe(0);
18
+ // High is a warning, not a blocker
19
+ if (highs > 0) {
20
+ process.stderr.write(`[warning] ${highs} high npm audit vulnerabilities\n`);
21
+ }
22
+ }
23
+ catch {
24
+ // npm audit may fail for various reasons (no package-lock, etc.)
25
+ // Skip rather than fail
26
+ }
27
+ // Must exceed the execSync budget above. Without it this runs under
28
+ // vitest's 5s default, so a slow-but-healthy `npm audit` is killed by the
29
+ // runner before the subprocess can time out and be skipped by the catch
30
+ // — turning a check designed never to fail into a hard CI failure.
31
+ // Observed 2026-09-03: 10.7s on every ubuntu GitHub runner, 30.0s
32
+ // locally, while all three Windows legs passed. tests/
33
+ // dependency-health-timeout.test.ts pins the two numbers in agreement.
34
+ }, 35_000);
35
+ it("no require() in ESM source files", () => {
36
+ const srcDir = path.join(config.repoRoot, config.srcDir ?? "src");
37
+ const files = walk(srcDir).filter((f) => f.endsWith(".ts"));
38
+ const v = findMatches(files, /\brequire\s*\(/, {
39
+ baseDir: srcDir,
40
+ ignorePatterns: config.sourceLintIgnore ?? [],
41
+ });
42
+ expect(v, formatViolations("no require() in ESM", v)).toEqual([]);
43
+ });
44
+ });
45
+ }
@@ -0,0 +1,3 @@
1
+ import type { McpServerConfig } from "../types.js";
2
+ export declare function enderStrategicSuite(config: McpServerConfig): void;
3
+ //# sourceMappingURL=ender-strategic.d.ts.map
@@ -0,0 +1,155 @@
1
+ /**
2
+ * Ender Wiggin strategic tests.
3
+ * "The enemy's gate is down." -- finds systemic weaknesses.
4
+ */
5
+ import { describe, it, expect } from "vitest";
6
+ import path from "path";
7
+ import { existsSync, readFileSync } from "fs";
8
+ import { spawnCli } from "../helpers/spawn.js";
9
+ import { walk } from "../helpers/source-lint.js";
10
+ export function enderStrategicSuite(config) {
11
+ describe("ender: strategic (systemic weaknesses)", () => {
12
+ const entry = config.serverEntry ?? "dist/index.js";
13
+ const srcDir = path.join(config.repoRoot, config.srcDir ?? "src");
14
+ // ----------------------------------------------------------------
15
+ // CLI consistency: every MCP must have identical CLI contract
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
+ it("--version output is ONLY the semver string (no decoration)", () => {
27
+ const result = spawnCli(config, entry, ["--version"]);
28
+ const output = (result.stdout + result.stderr).trim();
29
+ // Should be just the version number, possibly with a trailing newline
30
+ const lines = output.split("\n").filter((l) => l.trim());
31
+ const versionLine = lines[lines.length - 1]?.trim() ?? "";
32
+ expect(versionLine, `--version should output clean semver, got: "${versionLine}"`).toMatch(/^\d+\.\d+\.\d+/);
33
+ });
34
+ it("--help and --version exit with code 0", () => {
35
+ const helpResult = spawnCli(config, entry, ["--help"]);
36
+ const versionResult = spawnCli(config, entry, ["--version"]);
37
+ expect(helpResult.exitCode, "--help should exit 0").toBe(0);
38
+ expect(versionResult.exitCode, "--version should exit 0").toBe(0);
39
+ });
40
+ // ----------------------------------------------------------------
41
+ // Cold start latency budget
42
+ // ----------------------------------------------------------------
43
+ it("--help responds within 3 seconds (cold start budget)", () => {
44
+ const start = Date.now();
45
+ spawnCli(config, entry, ["--help"], undefined, 5_000);
46
+ const elapsed = Date.now() - start;
47
+ expect(elapsed, `--help took ${elapsed}ms. Cold start should be <3000ms.`).toBeLessThan(3000);
48
+ });
49
+ // ----------------------------------------------------------------
50
+ // Error state recovery: after a failure, server should still work
51
+ // ----------------------------------------------------------------
52
+ it("error handler doesn't crash the server process", () => {
53
+ const entryPath = path.resolve(config.repoRoot, entry);
54
+ if (!existsSync(entryPath))
55
+ return;
56
+ const src = readFileSync(entryPath, "utf-8");
57
+ // Check that tool call errors are caught and returned as isError responses
58
+ // (not thrown and crashing the process)
59
+ const hasTryCatch = src.includes("try {") && src.includes("catch");
60
+ const hasIsError = src.includes("isError");
61
+ expect(hasTryCatch && hasIsError, "Tool call handler should wrap in try/catch and return isError, not crash the process").toBe(true);
62
+ });
63
+ // ----------------------------------------------------------------
64
+ // Upgrade path: credential version checking
65
+ // ----------------------------------------------------------------
66
+ it("credential files include version field for forward compat", () => {
67
+ if (!config.hasCredentials)
68
+ return;
69
+ const credPath = path.join(srcDir, "credentials.ts");
70
+ if (!existsSync(credPath))
71
+ return;
72
+ const src = readFileSync(credPath, "utf-8");
73
+ expect(src.includes("version"), "Credential files should include a version field for schema evolution").toBe(true);
74
+ });
75
+ // ----------------------------------------------------------------
76
+ // Tool removal regression: unknown tool gives helpful error
77
+ // ----------------------------------------------------------------
78
+ it("server source handles unknown tool names gracefully", () => {
79
+ const entryPath = path.resolve(config.repoRoot, entry);
80
+ if (!existsSync(entryPath))
81
+ return;
82
+ const src = readFileSync(entryPath, "utf-8");
83
+ // Check for a default/else branch in the tool switch
84
+ const hasDefaultCase = src.includes("default:") ||
85
+ src.includes("Unknown tool") ||
86
+ src.includes("unknown tool") ||
87
+ src.includes(`else`);
88
+ expect(hasDefaultCase, "Tool handler should have a default case for unknown tool names").toBe(true);
89
+ });
90
+ // ----------------------------------------------------------------
91
+ // Consistent error response shape
92
+ // ----------------------------------------------------------------
93
+ it("error responses include error_type and message fields", () => {
94
+ const entryPath = path.resolve(config.repoRoot, entry);
95
+ if (!existsSync(entryPath))
96
+ return;
97
+ const src = readFileSync(entryPath, "utf-8");
98
+ if (src.includes("catch") && src.includes("isError")) {
99
+ const hasErrorType = src.includes("error_type") || src.includes("error.name");
100
+ const hasMessage = src.includes("message") || src.includes("error.message");
101
+ expect(hasErrorType || hasMessage, "Error responses should include error type/name and message for debugging").toBe(true);
102
+ }
103
+ });
104
+ // ----------------------------------------------------------------
105
+ // No process.exit in tool handlers (kills the whole server)
106
+ // ----------------------------------------------------------------
107
+ it("no process.exit() inside request handlers", () => {
108
+ const files = walk(srcDir);
109
+ const entryFile = files.find((f) => path.basename(f) === "index.ts");
110
+ if (!entryFile)
111
+ return;
112
+ const src = readFileSync(entryFile, "utf-8");
113
+ const handlerIdx = src.indexOf("setRequestHandler");
114
+ if (handlerIdx === -1)
115
+ return;
116
+ const handlerCode = src.slice(handlerIdx);
117
+ // Remove signal handler blocks (SIGTERM/SIGINT/SIGPIPE) -- those are
118
+ // legitimate shutdown paths, not tool call error paths
119
+ const withoutSignals = handlerCode
120
+ .replace(/process\.on\s*\(\s*["']SIG\w+["'][\s\S]*?}\s*\)/g, "");
121
+ const exitCalls = [...withoutSignals.matchAll(/process\.exit\s*\(/g)];
122
+ expect(exitCalls.length, `Found ${exitCalls.length} process.exit() calls inside request handlers. ` +
123
+ `This kills the server on any tool error instead of returning an error response.`).toBe(0);
124
+ });
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
+ });
155
+ }
@@ -0,0 +1,3 @@
1
+ import type { McpServerConfig } from "../types.js";
2
+ export declare function gracefulShutdownSuite(config: McpServerConfig): void;
3
+ //# sourceMappingURL=graceful-shutdown.d.ts.map
@@ -0,0 +1,31 @@
1
+ import { describe, it, expect } from "vitest";
2
+ import path from "path";
3
+ import { existsSync, readFileSync } from "fs";
4
+ import { spawnServer, sendSignalAndWait } from "../helpers/spawn.js";
5
+ export function gracefulShutdownSuite(config) {
6
+ describe("graceful shutdown", () => {
7
+ // Only run shutdown tests if we have startup env (otherwise server exits immediately on missing creds)
8
+ const canStart = config.startupEnv && Object.keys(config.startupEnv).length > 0;
9
+ it.skipIf(!canStart)("SIGTERM causes clean exit within 3 seconds", async () => {
10
+ const proc = spawnServer(config, config.startupEnv);
11
+ // Give server a moment to start
12
+ await new Promise((r) => setTimeout(r, 1000));
13
+ const result = await sendSignalAndWait(proc, "SIGTERM", 3000);
14
+ expect(result.signal, "server did not exit within 3s of SIGTERM").not.toBe("TIMEOUT");
15
+ });
16
+ it.skipIf(!canStart)("SIGINT causes clean exit within 3 seconds", async () => {
17
+ const proc = spawnServer(config, config.startupEnv);
18
+ await new Promise((r) => setTimeout(r, 1000));
19
+ const result = await sendSignalAndWait(proc, "SIGINT", 3000);
20
+ expect(result.signal, "server did not exit within 3s of SIGINT").not.toBe("TIMEOUT");
21
+ });
22
+ it("SIGPIPE handler exists in source", () => {
23
+ const indexPath = path.join(config.repoRoot, config.serverEntry ?? "dist/index.js");
24
+ if (!existsSync(indexPath))
25
+ return;
26
+ const src = readFileSync(indexPath, "utf-8");
27
+ const hasSigpipe = src.includes("SIGPIPE") || src.includes("onPosixSignal");
28
+ expect(hasSigpipe, "server should handle SIGPIPE to avoid crash on broken pipe").toBe(true);
29
+ });
30
+ });
31
+ }
@@ -0,0 +1,3 @@
1
+ import type { McpServerConfig } from "../types.js";
2
+ export declare function inputSanitizationSuite(config: McpServerConfig): void;
3
+ //# sourceMappingURL=input-sanitization.d.ts.map
@@ -0,0 +1,26 @@
1
+ import { describe, it, expect } from "vitest";
2
+ import path from "path";
3
+ import { walk, findMatches, formatViolations } from "../helpers/source-lint.js";
4
+ export function inputSanitizationSuite(config) {
5
+ describe("input sanitization", () => {
6
+ const srcDir = path.join(config.repoRoot, config.srcDir ?? "src");
7
+ const files = walk(srcDir);
8
+ const opts = { baseDir: srcDir, ignorePatterns: config.sourceLintIgnore ?? [] };
9
+ it("no template literals in SQL/GAQL query construction", () => {
10
+ // Matches: `SELECT ... ${variable}` which is SQL/GAQL injection
11
+ // Exempt index.ts (error messages may contain interpolated user values)
12
+ // and tools.ts (descriptions contain example queries)
13
+ const v = findMatches(files, /`[^`]*(?:SELECT|INSERT|UPDATE|DELETE)\s[^`]*\$\{/i, { ...opts, exempt: new Set(["tools.ts", "index.ts"]) });
14
+ expect(v, formatViolations("template literals in query construction", v)).toEqual([]);
15
+ });
16
+ it("no unsanitized path.join with user input", () => {
17
+ // Matches path.join/resolve with direct args.* access (potential traversal)
18
+ // This is a heuristic -- not all such usages are bad
19
+ const v = findMatches(files, /path\.(join|resolve)\s*\([^)]*args\./, opts);
20
+ // This is informational -- violations are logged but not failed
21
+ if (v.length > 0) {
22
+ process.stderr.write(`[info] ${v.length} path.join/resolve calls use raw args -- verify no path traversal\n`);
23
+ }
24
+ });
25
+ });
26
+ }
@@ -0,0 +1,3 @@
1
+ import type { McpServerConfig } from "../types.js";
2
+ export declare function mayhemAdversarialSuite(config: McpServerConfig): void;
3
+ //# sourceMappingURL=mayhem-adversarial.d.ts.map
@@ -0,0 +1,175 @@
1
+ /**
2
+ * Mayhem adversarial tests.
3
+ * Tries to break things with edge cases, race conditions, and resource limits.
4
+ */
5
+ import { describe, it, expect } from "vitest";
6
+ import path from "path";
7
+ import { existsSync, readFileSync, writeFileSync, unlinkSync } from "fs";
8
+ import { tmpdir } from "os";
9
+ import { walk, findMatches, formatViolations } from "../helpers/source-lint.js";
10
+ export function mayhemAdversarialSuite(config) {
11
+ describe("mayhem: adversarial (break everything)", () => {
12
+ const entry = config.serverEntry ?? "dist/index.js";
13
+ const srcDir = path.join(config.repoRoot, config.srcDir ?? "src");
14
+ // ----------------------------------------------------------------
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
+ // Unicode in credential paths
36
+ // ----------------------------------------------------------------
37
+ it("credential path handling works with unicode characters", async () => {
38
+ if (!config.hasCredentials)
39
+ return;
40
+ try {
41
+ const mod = await import(path.join(config.repoRoot, "dist", "credentials.js"));
42
+ const readFn = mod.readStoredCredentials;
43
+ if (!readFn)
44
+ return;
45
+ const unicodePath = path.join(tmpdir(), `mcp-tst-ünïcödé-${Date.now()}.json`);
46
+ writeFileSync(unicodePath, JSON.stringify({ version: 1, refresh_token: "test" }));
47
+ try {
48
+ const result = readFn(unicodePath);
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 { }
57
+ }
58
+ }
59
+ catch {
60
+ // Module may not be requireable -- skip
61
+ }
62
+ });
63
+ // ----------------------------------------------------------------
64
+ // Concurrent credential writes don't corrupt
65
+ // ----------------------------------------------------------------
66
+ it("credential write is atomic (single writeFileSync, not stream)", () => {
67
+ if (!config.hasCredentials)
68
+ return;
69
+ const credPath = path.join(srcDir, "credentials.ts");
70
+ if (!existsSync(credPath))
71
+ return;
72
+ const src = readFileSync(credPath, "utf-8");
73
+ // writeFileSync is atomic on most OS (single syscall). createWriteStream is not.
74
+ const usesAtomicWrite = src.includes("writeFileSync");
75
+ const usesStreamWrite = src.includes("createWriteStream") || src.includes("write(") && !src.includes("writeFileSync");
76
+ expect(usesAtomicWrite, "Credential writes should use writeFileSync (atomic) not streams (race-prone)").toBe(true);
77
+ });
78
+ // ----------------------------------------------------------------
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
+ // JSON-RPC before ready: startup code completes before accepting calls
108
+ // ----------------------------------------------------------------
109
+ it("server validates auth BEFORE connecting transport (fail-fast)", () => {
110
+ const entryPath = path.resolve(config.repoRoot, entry);
111
+ if (!existsSync(entryPath))
112
+ return;
113
+ const src = readFileSync(entryPath, "utf-8");
114
+ const connectIdx = src.indexOf("server.connect") ?? src.indexOf("transport");
115
+ const authIdx = Math.max(src.indexOf("validateCredentials"), src.indexOf("resolveCredentials"), src.indexOf("resolveOAuthCredentials"), src.indexOf("META_ACCESS_TOKEN"), src.indexOf("GOOGLE_ADS_"), src.indexOf("loadConfig"));
116
+ if (authIdx >= 0 && connectIdx >= 0) {
117
+ expect(authIdx < connectIdx, "Auth/config validation should happen BEFORE server.connect(transport). " +
118
+ "Otherwise a tool call can arrive before credentials are loaded.").toBe(true);
119
+ }
120
+ });
121
+ // ----------------------------------------------------------------
122
+ // No eval() or Function() in source (code injection risk)
123
+ // ----------------------------------------------------------------
124
+ it("no eval() or new Function() in source code", () => {
125
+ const files = walk(srcDir);
126
+ const opts = { baseDir: srcDir, ignorePatterns: config.sourceLintIgnore ?? [] };
127
+ const v = findMatches(files, /\b(eval\s*\(|new\s+Function\s*\()/, opts);
128
+ expect(v, formatViolations("no eval() or new Function()", v)).toEqual([]);
129
+ });
130
+ // ----------------------------------------------------------------
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
+ // Credential file isn't world-readable after write
150
+ // ----------------------------------------------------------------
151
+ it("credential writes enforce restrictive permissions", () => {
152
+ if (!config.hasCredentials)
153
+ return;
154
+ const credPath = path.join(srcDir, "credentials.ts");
155
+ if (!existsSync(credPath))
156
+ return;
157
+ const src = readFileSync(credPath, "utf-8");
158
+ const enforcePerms = src.includes("0o600") ||
159
+ src.includes("0600") ||
160
+ src.includes("chmodSync") ||
161
+ src.includes("chmod");
162
+ expect(enforcePerms, "Credential files must be written with 0o600 permissions (owner-only read/write)").toBe(true);
163
+ });
164
+ // ----------------------------------------------------------------
165
+ // No synchronous network calls at module scope (blocks import)
166
+ // ----------------------------------------------------------------
167
+ it("no synchronous HTTP/fetch calls at module top level", () => {
168
+ const files = walk(srcDir);
169
+ const opts = { baseDir: srcDir, ignorePatterns: config.sourceLintIgnore ?? [] };
170
+ // Top-level fetch or http.get would block module loading
171
+ const v = findMatches(files, /^(?:const|let|var)\s+\w+\s*=\s*(?:fetch|http\.get|https\.get|axios\.get)\s*\(/m, opts);
172
+ expect(v, formatViolations("synchronous network calls at module scope", v)).toEqual([]);
173
+ });
174
+ });
175
+ }
@@ -0,0 +1,3 @@
1
+ import type { McpServerConfig } from "../types.js";
2
+ export declare function mcpProtocolSuite(config: McpServerConfig): void;
3
+ //# sourceMappingURL=mcp-protocol.d.ts.map
@@ -0,0 +1,65 @@
1
+ import { describe, it, expect } from "vitest";
2
+ import path from "path";
3
+ export function mcpProtocolSuite(config) {
4
+ describe("MCP protocol conformance", () => {
5
+ let tools = [];
6
+ it("can import tools from dist/tools.js", async () => {
7
+ try {
8
+ const toolsModule = await import(path.join(config.repoRoot, "dist", "tools.js"));
9
+ tools = toolsModule.tools ?? toolsModule.TOOLS ?? toolsModule.default ?? [];
10
+ expect(Array.isArray(tools), "tools export should be an array").toBe(true);
11
+ }
12
+ catch (err) {
13
+ // Some repos export tools differently (e.g., inline in index.ts)
14
+ // This is acceptable -- skip remaining protocol tests
15
+ tools = [];
16
+ }
17
+ });
18
+ it(`has at least ${config.minTools} tools`, () => {
19
+ if (tools.length === 0)
20
+ return; // tools not importable separately
21
+ expect(tools.length).toBeGreaterThanOrEqual(config.minTools);
22
+ });
23
+ it("all required tools are present", () => {
24
+ if (tools.length === 0)
25
+ return;
26
+ const names = new Set(tools.map((t) => t.name));
27
+ for (const required of config.requiredTools) {
28
+ expect(names.has(required), `required tool "${required}" not found`).toBe(true);
29
+ }
30
+ });
31
+ it(`all tool names start with "${config.toolPrefix}"`, () => {
32
+ if (tools.length === 0)
33
+ return;
34
+ const bad = tools.filter((t) => !t.name.startsWith(config.toolPrefix));
35
+ expect(bad.map((t) => t.name), `tools missing prefix "${config.toolPrefix}"`).toEqual([]);
36
+ });
37
+ it("all tools have non-empty descriptions", () => {
38
+ if (tools.length === 0)
39
+ return;
40
+ const bad = tools.filter((t) => !t.description || t.description.length < 10);
41
+ expect(bad.map((t) => t.name), "tools with missing/short descriptions").toEqual([]);
42
+ });
43
+ it("all tool inputSchemas have type: object", () => {
44
+ if (tools.length === 0)
45
+ return;
46
+ const bad = tools.filter((t) => t.inputSchema && t.inputSchema.type !== "object");
47
+ expect(bad.map((t) => t.name), "tools with non-object inputSchema").toEqual([]);
48
+ });
49
+ it("all required fields exist in properties", () => {
50
+ if (tools.length === 0)
51
+ return;
52
+ const bad = [];
53
+ for (const tool of tools) {
54
+ const required = tool.inputSchema?.required ?? [];
55
+ const props = tool.inputSchema?.properties ?? {};
56
+ for (const field of required) {
57
+ if (!(field in props)) {
58
+ bad.push(`${tool.name}: required field "${field}" not in properties`);
59
+ }
60
+ }
61
+ }
62
+ expect(bad, "required fields missing from properties").toEqual([]);
63
+ });
64
+ });
65
+ }
@@ -0,0 +1,3 @@
1
+ import type { McpServerConfig } from "../types.js";
2
+ export declare function networkFailuresSuite(config: McpServerConfig): void;
3
+ //# sourceMappingURL=network-failures.d.ts.map
@@ -0,0 +1,49 @@
1
+ import { describe, it, expect } from "vitest";
2
+ import path from "path";
3
+ export function networkFailuresSuite(config) {
4
+ describe("network failure handling", () => {
5
+ it("resilience module classifies auth errors as non-retryable", async () => {
6
+ try {
7
+ const mod = await import(path.join(config.repoRoot, "dist", "errors.js"));
8
+ const classify = mod.classifyError;
9
+ if (!classify)
10
+ return;
11
+ // 401 should be classified as auth error
12
+ const authErr = classify({ status: 401, message: "Unauthorized" });
13
+ expect(authErr.name).toMatch(/auth/i);
14
+ // 403 should be classified as auth error
15
+ const forbidErr = classify({ status: 403, message: "Forbidden" });
16
+ expect(forbidErr.name).toMatch(/auth/i);
17
+ }
18
+ catch {
19
+ // Module may not export classifyError
20
+ }
21
+ });
22
+ it("resilience module classifies rate limits correctly", async () => {
23
+ try {
24
+ const mod = await import(path.join(config.repoRoot, "dist", "errors.js"));
25
+ const classify = mod.classifyError;
26
+ if (!classify)
27
+ return;
28
+ const rateLimitErr = classify({ status: 429, message: "Too Many Requests" });
29
+ expect(rateLimitErr.name).toMatch(/rate/i);
30
+ }
31
+ catch {
32
+ // skip
33
+ }
34
+ });
35
+ it("resilience module classifies server errors as transient", async () => {
36
+ try {
37
+ const mod = await import(path.join(config.repoRoot, "dist", "errors.js"));
38
+ const classify = mod.classifyError;
39
+ if (!classify)
40
+ return;
41
+ const serverErr = classify({ status: 500, message: "Internal Server Error" });
42
+ expect(serverErr.name).toMatch(/service|server/i);
43
+ }
44
+ catch {
45
+ // skip
46
+ }
47
+ });
48
+ });
49
+ }
@@ -0,0 +1,3 @@
1
+ import type { McpServerConfig } from "../types.js";
2
+ export declare function observabilitySuite(config: McpServerConfig): void;
3
+ //# sourceMappingURL=observability.d.ts.map