mock-mcp 0.3.1 → 0.5.1

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 (40) hide show
  1. package/README.md +212 -124
  2. package/dist/adapter/index.cjs +875 -0
  3. package/dist/adapter/index.d.cts +142 -0
  4. package/dist/adapter/index.d.ts +142 -0
  5. package/dist/adapter/index.js +835 -0
  6. package/dist/client/connect.cjs +991 -0
  7. package/dist/client/connect.d.cts +218 -0
  8. package/dist/client/connect.d.ts +211 -7
  9. package/dist/client/connect.js +941 -20
  10. package/dist/client/index.cjs +992 -0
  11. package/dist/client/index.d.cts +3 -0
  12. package/dist/client/index.d.ts +3 -2
  13. package/dist/client/index.js +951 -2
  14. package/dist/daemon/index.cjs +717 -0
  15. package/dist/daemon/index.d.cts +62 -0
  16. package/dist/daemon/index.d.ts +62 -0
  17. package/dist/daemon/index.js +678 -0
  18. package/dist/index.cjs +2708 -0
  19. package/dist/index.d.cts +602 -0
  20. package/dist/index.d.ts +602 -11
  21. package/dist/index.js +2651 -53
  22. package/dist/shared/index.cjs +506 -0
  23. package/dist/shared/index.d.cts +241 -0
  24. package/dist/shared/index.d.ts +241 -0
  25. package/dist/shared/index.js +423 -0
  26. package/dist/types-bEGXLBF0.d.cts +190 -0
  27. package/dist/types-bEGXLBF0.d.ts +190 -0
  28. package/package.json +45 -4
  29. package/dist/client/batch-mock-collector.d.ts +0 -111
  30. package/dist/client/batch-mock-collector.js +0 -308
  31. package/dist/client/util.d.ts +0 -1
  32. package/dist/client/util.js +0 -3
  33. package/dist/connect.cjs +0 -400
  34. package/dist/connect.d.cts +0 -82
  35. package/dist/server/index.d.ts +0 -1
  36. package/dist/server/index.js +0 -1
  37. package/dist/server/test-mock-mcp-server.d.ts +0 -73
  38. package/dist/server/test-mock-mcp-server.js +0 -419
  39. package/dist/types.d.ts +0 -45
  40. package/dist/types.js +0 -2
package/dist/index.cjs ADDED
@@ -0,0 +1,2708 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ var fs = require('fs/promises');
5
+ var fssync = require('fs');
6
+ var os = require('os');
7
+ var path = require('path');
8
+ var crypto = require('crypto');
9
+ var child_process = require('child_process');
10
+ var http = require('http');
11
+ var url = require('url');
12
+ var module$1 = require('module');
13
+ var WebSocket2 = require('ws');
14
+ var index_js = require('@modelcontextprotocol/sdk/server/index.js');
15
+ var stdio_js = require('@modelcontextprotocol/sdk/server/stdio.js');
16
+ var types_js = require('@modelcontextprotocol/sdk/types.js');
17
+ var process2 = require('process');
18
+
19
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
20
+
21
+ var fs__default = /*#__PURE__*/_interopDefault(fs);
22
+ var fssync__default = /*#__PURE__*/_interopDefault(fssync);
23
+ var os__default = /*#__PURE__*/_interopDefault(os);
24
+ var path__default = /*#__PURE__*/_interopDefault(path);
25
+ var crypto__default = /*#__PURE__*/_interopDefault(crypto);
26
+ var http__default = /*#__PURE__*/_interopDefault(http);
27
+ var WebSocket2__default = /*#__PURE__*/_interopDefault(WebSocket2);
28
+ var process2__default = /*#__PURE__*/_interopDefault(process2);
29
+
30
+ var __importMetaUrl = (function() {
31
+ if (typeof document !== 'undefined') {
32
+ return document.currentScript && document.currentScript.src || new URL('main.js', document.baseURI).href;
33
+ }
34
+ // Node.js CJS context
35
+ // When this bundle is re-bundled by another tool (e.g., esbuild, webpack),
36
+ // __filename may not be defined or may not be a valid file path.
37
+ // We need to handle these cases gracefully.
38
+ try {
39
+ if (typeof __filename !== 'undefined' && __filename) {
40
+ var url = require('url');
41
+ var path = require('path');
42
+ // Check if __filename looks like a valid file path
43
+ if (path.isAbsolute(__filename) || __filename.startsWith('./') || __filename.startsWith('../')) {
44
+ return url.pathToFileURL(__filename).href;
45
+ }
46
+ }
47
+ } catch (e) {
48
+ // Fallback if pathToFileURL fails
49
+ }
50
+ // Fallback: use process.cwd() as the base URL
51
+ // This is not perfect but allows the code to continue working
52
+ try {
53
+ var url = require('url');
54
+ return url.pathToFileURL(require('path').join(process.cwd(), 'index.cjs')).href;
55
+ } catch (e) {
56
+ return 'file:///unknown';
57
+ }
58
+ })();
59
+
60
+ var __defProp = Object.defineProperty;
61
+ var __getOwnPropNames = Object.getOwnPropertyNames;
62
+ var __esm = (fn, res) => function __init() {
63
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
64
+ };
65
+ var __export = (target, all) => {
66
+ for (var name in all)
67
+ __defProp(target, name, { get: all[name], enumerable: true });
68
+ };
69
+
70
+ // src/shared/discovery.ts
71
+ var discovery_exports = {};
72
+ __export(discovery_exports, {
73
+ cleanupGlobalIndex: () => cleanupGlobalIndex,
74
+ computeProjectId: () => computeProjectId,
75
+ discoverAllDaemons: () => discoverAllDaemons,
76
+ ensureDaemonRunning: () => ensureDaemonRunning,
77
+ getCacheDir: () => getCacheDir,
78
+ getDaemonEntryPath: () => getDaemonEntryPath,
79
+ getGlobalIndexPath: () => getGlobalIndexPath,
80
+ getPaths: () => getPaths,
81
+ healthCheck: () => healthCheck,
82
+ randomToken: () => randomToken,
83
+ readGlobalIndex: () => readGlobalIndex,
84
+ readRegistry: () => readRegistry,
85
+ registerDaemonGlobally: () => registerDaemonGlobally,
86
+ releaseLock: () => releaseLock,
87
+ resolveProjectRoot: () => resolveProjectRoot,
88
+ sleep: () => sleep,
89
+ tryAcquireLock: () => tryAcquireLock,
90
+ unregisterDaemonGlobally: () => unregisterDaemonGlobally,
91
+ writeGlobalIndex: () => writeGlobalIndex,
92
+ writeRegistry: () => writeRegistry
93
+ });
94
+ function debugLog(_msg) {
95
+ }
96
+ function hasValidProjectMarker(dir) {
97
+ try {
98
+ const gitPath = path__default.default.join(dir, ".git");
99
+ try {
100
+ const stat = fssync__default.default.statSync(gitPath);
101
+ if (stat.isDirectory() || stat.isFile()) {
102
+ return true;
103
+ }
104
+ } catch {
105
+ }
106
+ const pkgPath = path__default.default.join(dir, "package.json");
107
+ try {
108
+ fssync__default.default.accessSync(pkgPath, fssync__default.default.constants.F_OK);
109
+ return true;
110
+ } catch {
111
+ }
112
+ return false;
113
+ } catch {
114
+ return false;
115
+ }
116
+ }
117
+ function resolveProjectRoot(startDir = process.cwd()) {
118
+ let current = path__default.default.resolve(startDir);
119
+ const root = path__default.default.parse(current).root;
120
+ while (current !== root) {
121
+ const gitPath = path__default.default.join(current, ".git");
122
+ try {
123
+ const stat = fssync__default.default.statSync(gitPath);
124
+ if (stat.isDirectory() || stat.isFile()) {
125
+ return current;
126
+ }
127
+ } catch {
128
+ }
129
+ const pkgPath = path__default.default.join(current, "package.json");
130
+ try {
131
+ fssync__default.default.accessSync(pkgPath, fssync__default.default.constants.F_OK);
132
+ return current;
133
+ } catch {
134
+ }
135
+ current = path__default.default.dirname(current);
136
+ }
137
+ return path__default.default.resolve(startDir);
138
+ }
139
+ function computeProjectId(projectRoot) {
140
+ const real = fssync__default.default.realpathSync(projectRoot);
141
+ return crypto__default.default.createHash("sha256").update(real).digest("hex").slice(0, 16);
142
+ }
143
+ function getCacheDir(override) {
144
+ if (override) {
145
+ return override;
146
+ }
147
+ const envCacheDir = process.env.MOCK_MCP_CACHE_DIR;
148
+ if (envCacheDir) {
149
+ return envCacheDir;
150
+ }
151
+ const xdg = process.env.XDG_CACHE_HOME;
152
+ if (xdg) {
153
+ return xdg;
154
+ }
155
+ if (process.platform === "win32" && process.env.LOCALAPPDATA) {
156
+ return process.env.LOCALAPPDATA;
157
+ }
158
+ const home = os__default.default.homedir();
159
+ if (home) {
160
+ return path__default.default.join(home, ".cache");
161
+ }
162
+ return os__default.default.tmpdir();
163
+ }
164
+ function getPaths(projectId, cacheDir) {
165
+ const base = path__default.default.join(getCacheDir(cacheDir), "mock-mcp");
166
+ const registryPath = path__default.default.join(base, `${projectId}.json`);
167
+ const lockPath = path__default.default.join(base, `${projectId}.lock`);
168
+ const ipcPath = process.platform === "win32" ? `\\\\.\\pipe\\mock-mcp-${projectId}` : path__default.default.join(base, `${projectId}.sock`);
169
+ return { base, registryPath, lockPath, ipcPath };
170
+ }
171
+ async function readRegistry(registryPath) {
172
+ try {
173
+ const txt = await fs__default.default.readFile(registryPath, "utf-8");
174
+ return JSON.parse(txt);
175
+ } catch (error) {
176
+ debugLog(`readRegistry error for ${registryPath}: ${error instanceof Error ? error.message : String(error)}`);
177
+ return null;
178
+ }
179
+ }
180
+ async function writeRegistry(registryPath, registry) {
181
+ await fs__default.default.writeFile(registryPath, JSON.stringify(registry, null, 2), {
182
+ encoding: "utf-8",
183
+ mode: 384
184
+ // Read/write for owner only
185
+ });
186
+ }
187
+ async function healthCheck(ipcPath, timeoutMs = 2e3) {
188
+ return new Promise((resolve) => {
189
+ const req = http__default.default.request(
190
+ {
191
+ method: "GET",
192
+ socketPath: ipcPath,
193
+ path: "/health",
194
+ timeout: timeoutMs
195
+ },
196
+ (res) => {
197
+ resolve(res.statusCode === 200);
198
+ }
199
+ );
200
+ req.on("error", () => resolve(false));
201
+ req.on("timeout", () => {
202
+ req.destroy();
203
+ resolve(false);
204
+ });
205
+ req.end();
206
+ });
207
+ }
208
+ async function tryAcquireLock(lockPath) {
209
+ try {
210
+ const fh = await fs__default.default.open(lockPath, "wx");
211
+ await fh.write(`${process.pid}
212
+ `);
213
+ return fh;
214
+ } catch {
215
+ return null;
216
+ }
217
+ }
218
+ async function releaseLock(lockPath, fh) {
219
+ await fh.close();
220
+ await fs__default.default.rm(lockPath).catch(() => {
221
+ });
222
+ }
223
+ function randomToken() {
224
+ return crypto__default.default.randomBytes(24).toString("base64url");
225
+ }
226
+ function getDaemonEntryPath() {
227
+ try {
228
+ const cwdRequire = module$1.createRequire(url.pathToFileURL(path__default.default.join(process.cwd(), "index.js")).href);
229
+ const resolved = cwdRequire.resolve("mock-mcp");
230
+ const distDir = path__default.default.dirname(resolved);
231
+ const daemonEntry = path__default.default.join(distDir, "index.js");
232
+ if (fssync__default.default.existsSync(daemonEntry)) {
233
+ return daemonEntry;
234
+ }
235
+ } catch {
236
+ }
237
+ try {
238
+ const packageRoot = resolveProjectRoot(__curDirname);
239
+ const distPath = path__default.default.join(packageRoot, "dist", "index.js");
240
+ if (fssync__default.default.existsSync(distPath)) {
241
+ return distPath;
242
+ }
243
+ } catch {
244
+ }
245
+ if (process.argv[1]) {
246
+ return process.argv[1];
247
+ }
248
+ return path__default.default.join(process.cwd(), "dist", "index.js");
249
+ }
250
+ async function ensureDaemonRunning(opts = {}) {
251
+ let projectRoot = opts.projectRoot ?? resolveProjectRoot();
252
+ if (!hasValidProjectMarker(projectRoot)) {
253
+ const resolved = resolveProjectRoot(projectRoot);
254
+ if (resolved !== projectRoot && hasValidProjectMarker(resolved)) {
255
+ console.error(`[mock-mcp] Warning: projectRoot "${projectRoot}" doesn't look like a project root`);
256
+ console.error(`[mock-mcp] Found .git/package.json at: "${resolved}"`);
257
+ projectRoot = resolved;
258
+ } else {
259
+ console.error(`[mock-mcp] \u26A0\uFE0F WARNING: Could not find a valid project root!`);
260
+ console.error(`[mock-mcp] Current path: "${projectRoot}"`);
261
+ console.error(`[mock-mcp] This path doesn't contain .git or package.json.`);
262
+ console.error(`[mock-mcp] This may cause project mismatch issues.`);
263
+ console.error(`[mock-mcp] `);
264
+ console.error(`[mock-mcp] For MCP adapters, please specify --project-root explicitly:`);
265
+ console.error(`[mock-mcp] mock-mcp adapter --project-root /path/to/your/project`);
266
+ console.error(`[mock-mcp] `);
267
+ console.error(`[mock-mcp] In your MCP client config (Cursor, Claude Desktop, etc.):`);
268
+ console.error(`[mock-mcp] {`);
269
+ console.error(`[mock-mcp] "args": ["-y", "mock-mcp", "adapter", "--project-root", "/path/to/your/project"]`);
270
+ console.error(`[mock-mcp] }`);
271
+ }
272
+ }
273
+ const projectId = computeProjectId(projectRoot);
274
+ const { base, registryPath, lockPath, ipcPath } = getPaths(
275
+ projectId,
276
+ opts.cacheDir
277
+ );
278
+ const timeoutMs = opts.timeoutMs ?? 1e4;
279
+ await fs__default.default.mkdir(base, { recursive: true });
280
+ const existing = await readRegistry(registryPath);
281
+ debugLog(`Registry read result: ${existing ? "Found (PID " + existing.pid + ")" : "Null"}`);
282
+ if (existing) {
283
+ let healthy = false;
284
+ for (let i = 0; i < 3; i++) {
285
+ debugLog(`Checking health attempt ${i + 1}/3 on ${existing.ipcPath}`);
286
+ healthy = await healthCheck(existing.ipcPath);
287
+ if (healthy) break;
288
+ await new Promise((r) => setTimeout(r, 200));
289
+ }
290
+ if (healthy) {
291
+ return existing;
292
+ }
293
+ }
294
+ if (process.platform !== "win32") {
295
+ try {
296
+ await fs__default.default.rm(ipcPath);
297
+ } catch {
298
+ }
299
+ }
300
+ const lock = await tryAcquireLock(lockPath);
301
+ if (lock) {
302
+ try {
303
+ const recheckReg = await readRegistry(registryPath);
304
+ if (recheckReg && await healthCheck(recheckReg.ipcPath)) {
305
+ return recheckReg;
306
+ }
307
+ const token = randomToken();
308
+ const daemonEntry = getDaemonEntryPath();
309
+ const child = child_process.spawn(
310
+ process.execPath,
311
+ [daemonEntry, "daemon", "--project-root", projectRoot, "--token", token],
312
+ {
313
+ detached: true,
314
+ stdio: ["ignore", "pipe", "pipe"],
315
+ env: {
316
+ ...process.env,
317
+ MOCK_MCP_CACHE_DIR: opts.cacheDir ?? ""
318
+ }
319
+ }
320
+ );
321
+ let daemonStderr = "";
322
+ let daemonStdout = "";
323
+ child.stdout?.on("data", (data) => {
324
+ const str = data.toString();
325
+ debugLog(`Daemon stdout: ${str}`);
326
+ });
327
+ child.stderr?.on("data", (data) => {
328
+ daemonStderr += data.toString();
329
+ debugLog(`Daemon stderr: ${data.toString()}`);
330
+ });
331
+ child.on("error", (err) => {
332
+ console.error(`[mock-mcp] Daemon spawn error: ${err.message}`);
333
+ });
334
+ child.on("exit", (code, signal) => {
335
+ if (code !== null && code !== 0) {
336
+ console.error(`[mock-mcp] Daemon exited with code: ${code}`);
337
+ if (daemonStderr) {
338
+ console.error(`[mock-mcp] Daemon stderr: ${daemonStderr.slice(0, 500)}`);
339
+ }
340
+ } else if (signal) {
341
+ console.error(`[mock-mcp] Daemon killed by signal: ${signal}`);
342
+ }
343
+ });
344
+ child.unref();
345
+ const deadline2 = Date.now() + timeoutMs;
346
+ while (Date.now() < deadline2) {
347
+ const reg = await readRegistry(registryPath);
348
+ if (reg && await healthCheck(reg.ipcPath)) {
349
+ return reg;
350
+ }
351
+ await sleep(50);
352
+ }
353
+ console.error("[mock-mcp] Daemon failed to start within timeout");
354
+ if (daemonStderr) {
355
+ console.error(`[mock-mcp] Daemon stderr:
356
+ ${daemonStderr}`);
357
+ }
358
+ throw new Error(
359
+ `Daemon start timeout after ${timeoutMs}ms. Check logs for details.`
360
+ );
361
+ } finally {
362
+ await releaseLock(lockPath, lock);
363
+ }
364
+ }
365
+ const deadline = Date.now() + timeoutMs;
366
+ while (Date.now() < deadline) {
367
+ const reg = await readRegistry(registryPath);
368
+ if (reg && await healthCheck(reg.ipcPath)) {
369
+ return reg;
370
+ }
371
+ await sleep(50);
372
+ }
373
+ throw new Error(
374
+ `Waiting for daemon timed out after ${timeoutMs}ms. Another process may have failed to start it.`
375
+ );
376
+ }
377
+ function sleep(ms) {
378
+ return new Promise((resolve) => setTimeout(resolve, ms));
379
+ }
380
+ function getGlobalIndexPath(cacheDir) {
381
+ const base = path__default.default.join(getCacheDir(cacheDir), "mock-mcp");
382
+ return path__default.default.join(base, "active-daemons.json");
383
+ }
384
+ async function readGlobalIndex(cacheDir) {
385
+ const indexPath = getGlobalIndexPath(cacheDir);
386
+ try {
387
+ const txt = await fs__default.default.readFile(indexPath, "utf-8");
388
+ return JSON.parse(txt);
389
+ } catch {
390
+ return { daemons: [], updatedAt: (/* @__PURE__ */ new Date()).toISOString() };
391
+ }
392
+ }
393
+ async function writeGlobalIndex(index, cacheDir) {
394
+ const indexPath = getGlobalIndexPath(cacheDir);
395
+ const base = path__default.default.dirname(indexPath);
396
+ await fs__default.default.mkdir(base, { recursive: true });
397
+ await fs__default.default.writeFile(indexPath, JSON.stringify(index, null, 2), {
398
+ encoding: "utf-8",
399
+ mode: 384
400
+ });
401
+ }
402
+ async function registerDaemonGlobally(entry, cacheDir) {
403
+ const index = await readGlobalIndex(cacheDir);
404
+ index.daemons = index.daemons.filter((d) => d.projectId !== entry.projectId);
405
+ index.daemons.push(entry);
406
+ index.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
407
+ await writeGlobalIndex(index, cacheDir);
408
+ debugLog(`Registered daemon ${entry.projectId} in global index`);
409
+ }
410
+ async function unregisterDaemonGlobally(projectId, cacheDir) {
411
+ const index = await readGlobalIndex(cacheDir);
412
+ index.daemons = index.daemons.filter((d) => d.projectId !== projectId);
413
+ index.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
414
+ await writeGlobalIndex(index, cacheDir);
415
+ }
416
+ async function cleanupGlobalIndex(cacheDir) {
417
+ const index = await readGlobalIndex(cacheDir);
418
+ const validDaemons = [];
419
+ for (const entry of index.daemons) {
420
+ try {
421
+ process.kill(entry.pid, 0);
422
+ const healthy = await healthCheck(entry.ipcPath, 1e3);
423
+ if (healthy) {
424
+ validDaemons.push(entry);
425
+ } else {
426
+ debugLog(`Removing unhealthy daemon ${entry.projectId} (pid ${entry.pid})`);
427
+ }
428
+ } catch {
429
+ debugLog(`Removing dead daemon ${entry.projectId} (pid ${entry.pid})`);
430
+ }
431
+ }
432
+ if (validDaemons.length !== index.daemons.length) {
433
+ index.daemons = validDaemons;
434
+ index.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
435
+ await writeGlobalIndex(index, cacheDir);
436
+ }
437
+ }
438
+ async function discoverAllDaemons(cacheDir) {
439
+ await cleanupGlobalIndex(cacheDir);
440
+ const index = await readGlobalIndex(cacheDir);
441
+ const results = [];
442
+ for (const entry of index.daemons) {
443
+ const registry = await readRegistry(entry.registryPath);
444
+ if (registry) {
445
+ const healthy = await healthCheck(entry.ipcPath, 2e3);
446
+ results.push({ registry, healthy });
447
+ }
448
+ }
449
+ return results;
450
+ }
451
+ var __curDirname;
452
+ var init_discovery = __esm({
453
+ "src/shared/discovery.ts"() {
454
+ __curDirname = (() => {
455
+ try {
456
+ const metaUrl = __importMetaUrl;
457
+ if (metaUrl && typeof metaUrl === "string" && metaUrl.startsWith("file://")) {
458
+ return path__default.default.dirname(url.fileURLToPath(metaUrl));
459
+ }
460
+ } catch {
461
+ }
462
+ return process.cwd();
463
+ })();
464
+ }
465
+ });
466
+
467
+ // src/shared/protocol.ts
468
+ function isHelloTestMessage(msg) {
469
+ if (!msg || typeof msg !== "object") return false;
470
+ const m = msg;
471
+ return m.type === HELLO_TEST && typeof m.token === "string" && typeof m.runId === "string" && typeof m.pid === "number" && typeof m.cwd === "string";
472
+ }
473
+ function isBatchMockRequestMessage(msg) {
474
+ if (!msg || typeof msg !== "object") return false;
475
+ const m = msg;
476
+ return m.type === BATCH_MOCK_REQUEST && typeof m.runId === "string" && Array.isArray(m.requests);
477
+ }
478
+ function isHeartbeatMessage(msg) {
479
+ if (!msg || typeof msg !== "object") return false;
480
+ const m = msg;
481
+ return m.type === HEARTBEAT && typeof m.runId === "string";
482
+ }
483
+ function isJsonRpcRequest(msg) {
484
+ if (!msg || typeof msg !== "object") return false;
485
+ const m = msg;
486
+ return m.jsonrpc === "2.0" && (typeof m.id === "string" || typeof m.id === "number") && typeof m.method === "string";
487
+ }
488
+ var HELLO_TEST, HELLO_ACK, BATCH_MOCK_REQUEST, BATCH_MOCK_RESULT, HEARTBEAT, HEARTBEAT_ACK, RPC_GET_STATUS, RPC_LIST_RUNS, RPC_CLAIM_NEXT_BATCH, RPC_PROVIDE_BATCH, RPC_RELEASE_BATCH, RPC_GET_BATCH, RPC_ERROR_METHOD_NOT_FOUND, RPC_ERROR_INTERNAL, RPC_ERROR_NOT_FOUND, RPC_ERROR_UNAUTHORIZED, RPC_ERROR_CONFLICT, RPC_ERROR_EXPIRED;
489
+ var init_protocol = __esm({
490
+ "src/shared/protocol.ts"() {
491
+ HELLO_TEST = "HELLO_TEST";
492
+ HELLO_ACK = "HELLO_ACK";
493
+ BATCH_MOCK_REQUEST = "BATCH_MOCK_REQUEST";
494
+ BATCH_MOCK_RESULT = "BATCH_MOCK_RESULT";
495
+ HEARTBEAT = "HEARTBEAT";
496
+ HEARTBEAT_ACK = "HEARTBEAT_ACK";
497
+ RPC_GET_STATUS = "getStatus";
498
+ RPC_LIST_RUNS = "listRuns";
499
+ RPC_CLAIM_NEXT_BATCH = "claimNextBatch";
500
+ RPC_PROVIDE_BATCH = "provideBatch";
501
+ RPC_RELEASE_BATCH = "releaseBatch";
502
+ RPC_GET_BATCH = "getBatch";
503
+ RPC_ERROR_METHOD_NOT_FOUND = -32601;
504
+ RPC_ERROR_INTERNAL = -32603;
505
+ RPC_ERROR_NOT_FOUND = -32e3;
506
+ RPC_ERROR_UNAUTHORIZED = -32001;
507
+ RPC_ERROR_CONFLICT = -32002;
508
+ RPC_ERROR_EXPIRED = -32003;
509
+ }
510
+ });
511
+
512
+ // src/daemon/daemon.ts
513
+ var daemon_exports = {};
514
+ __export(daemon_exports, {
515
+ MockMcpDaemon: () => exports.MockMcpDaemon
516
+ });
517
+ exports.MockMcpDaemon = void 0; var RpcError;
518
+ var init_daemon = __esm({
519
+ "src/daemon/daemon.ts"() {
520
+ init_discovery();
521
+ init_protocol();
522
+ exports.MockMcpDaemon = class {
523
+ logger;
524
+ opts;
525
+ server;
526
+ wss;
527
+ sweepTimer;
528
+ idleTimer;
529
+ startedAt;
530
+ // State management
531
+ runs = /* @__PURE__ */ new Map();
532
+ batches = /* @__PURE__ */ new Map();
533
+ pendingQueue = [];
534
+ // batchIds in order
535
+ batchSeq = 0;
536
+ constructor(options) {
537
+ this.logger = options.logger ?? console;
538
+ this.opts = {
539
+ projectRoot: options.projectRoot,
540
+ token: options.token,
541
+ version: options.version,
542
+ cacheDir: options.cacheDir,
543
+ logger: this.logger,
544
+ defaultLeaseMs: options.defaultLeaseMs ?? 3e4,
545
+ sweepIntervalMs: options.sweepIntervalMs ?? 5e3,
546
+ idleShutdownMs: options.idleShutdownMs ?? 6e5
547
+ };
548
+ }
549
+ // ===========================================================================
550
+ // Lifecycle
551
+ // ===========================================================================
552
+ async start() {
553
+ const projectId = computeProjectId(this.opts.projectRoot);
554
+ const { base, registryPath, ipcPath } = getPaths(projectId, this.opts.cacheDir);
555
+ await fs__default.default.mkdir(base, { recursive: true });
556
+ if (process.platform !== "win32") {
557
+ try {
558
+ await fs__default.default.rm(ipcPath);
559
+ } catch {
560
+ }
561
+ }
562
+ const server = http__default.default.createServer((req, res) => this.handleHttp(req, res));
563
+ this.server = server;
564
+ const wss = new WebSocket2.WebSocketServer({ noServer: true });
565
+ this.wss = wss;
566
+ server.on("upgrade", (req, socket, head) => {
567
+ if (!req.url?.startsWith("/test")) {
568
+ socket.destroy();
569
+ return;
570
+ }
571
+ wss.handleUpgrade(req, socket, head, (ws) => {
572
+ wss.emit("connection", ws, req);
573
+ });
574
+ });
575
+ wss.on("connection", (ws, req) => this.handleWsConnection(ws, req));
576
+ await new Promise((resolve, reject) => {
577
+ server.once("error", reject);
578
+ server.listen(ipcPath, () => {
579
+ this.logger.error(`\u{1F680} Daemon listening on ${ipcPath}`);
580
+ resolve();
581
+ });
582
+ });
583
+ this.startedAt = Date.now();
584
+ const registry = {
585
+ projectId,
586
+ projectRoot: this.opts.projectRoot,
587
+ ipcPath,
588
+ token: this.opts.token,
589
+ pid: process.pid,
590
+ startedAt: (/* @__PURE__ */ new Date()).toISOString(),
591
+ version: this.opts.version
592
+ };
593
+ await writeRegistry(registryPath, registry);
594
+ const globalEntry = {
595
+ projectId,
596
+ projectRoot: this.opts.projectRoot,
597
+ ipcPath,
598
+ registryPath,
599
+ pid: process.pid,
600
+ startedAt: registry.startedAt,
601
+ version: this.opts.version
602
+ };
603
+ await registerDaemonGlobally(globalEntry, this.opts.cacheDir);
604
+ this.sweepTimer = setInterval(() => this.sweepExpiredClaims(), this.opts.sweepIntervalMs);
605
+ this.sweepTimer.unref?.();
606
+ this.resetIdleTimer();
607
+ this.logger.error(`\u2705 Daemon ready (project: ${projectId}, pid: ${process.pid})`);
608
+ }
609
+ async stop() {
610
+ if (this.sweepTimer) {
611
+ clearInterval(this.sweepTimer);
612
+ this.sweepTimer = void 0;
613
+ }
614
+ if (this.idleTimer) {
615
+ clearTimeout(this.idleTimer);
616
+ this.idleTimer = void 0;
617
+ }
618
+ for (const run of this.runs.values()) {
619
+ run.ws.close(1001, "Daemon shutting down");
620
+ }
621
+ this.runs.clear();
622
+ this.wss?.close();
623
+ await new Promise((resolve) => {
624
+ if (!this.server) {
625
+ resolve();
626
+ return;
627
+ }
628
+ this.server.close(() => resolve());
629
+ });
630
+ this.batches.clear();
631
+ this.pendingQueue.length = 0;
632
+ const projectId = computeProjectId(this.opts.projectRoot);
633
+ await unregisterDaemonGlobally(projectId, this.opts.cacheDir);
634
+ this.logger.error("\u{1F44B} Daemon stopped");
635
+ }
636
+ // ===========================================================================
637
+ // HTTP Handler (/health, /control)
638
+ // ===========================================================================
639
+ async handleHttp(req, res) {
640
+ try {
641
+ if (req.method === "GET" && req.url === "/health") {
642
+ res.writeHead(200, { "content-type": "application/json" });
643
+ res.end(
644
+ JSON.stringify({
645
+ ok: true,
646
+ pid: process.pid,
647
+ version: this.opts.version,
648
+ projectId: computeProjectId(this.opts.projectRoot)
649
+ })
650
+ );
651
+ return;
652
+ }
653
+ if (req.method === "POST" && req.url === "/control") {
654
+ const token = req.headers["x-mock-mcp-token"];
655
+ if (token !== this.opts.token) {
656
+ res.writeHead(401, { "content-type": "application/json" });
657
+ res.end(JSON.stringify({ error: "Unauthorized" }));
658
+ return;
659
+ }
660
+ const body = await this.readBody(req);
661
+ let rpcReq;
662
+ try {
663
+ rpcReq = JSON.parse(body);
664
+ } catch {
665
+ res.writeHead(400, { "content-type": "application/json" });
666
+ res.end(JSON.stringify({ error: "Invalid JSON" }));
667
+ return;
668
+ }
669
+ if (!isJsonRpcRequest(rpcReq)) {
670
+ res.writeHead(400, { "content-type": "application/json" });
671
+ res.end(JSON.stringify({ error: "Invalid JSON-RPC request" }));
672
+ return;
673
+ }
674
+ const rpcRes = await this.handleRpc(rpcReq);
675
+ res.writeHead(200, { "content-type": "application/json" });
676
+ res.end(JSON.stringify(rpcRes));
677
+ return;
678
+ }
679
+ res.writeHead(404, { "content-type": "text/plain" });
680
+ res.end("Not Found");
681
+ } catch (e) {
682
+ this.logger.error("HTTP handler error:", e);
683
+ res.writeHead(500, { "content-type": "text/plain" });
684
+ res.end(e instanceof Error ? e.message : String(e));
685
+ }
686
+ }
687
+ readBody(req) {
688
+ return new Promise((resolve, reject) => {
689
+ let buf = "";
690
+ req.on("data", (chunk) => buf += chunk);
691
+ req.on("end", () => resolve(buf));
692
+ req.on("error", reject);
693
+ });
694
+ }
695
+ // ===========================================================================
696
+ // WebSocket Handler (/test)
697
+ // ===========================================================================
698
+ handleWsConnection(ws, _req) {
699
+ let authed = false;
700
+ let runId = null;
701
+ const helloTimeout = setTimeout(() => {
702
+ if (!authed) {
703
+ ws.close(1008, "HELLO timeout");
704
+ }
705
+ }, 5e3);
706
+ ws.on("message", (data) => {
707
+ let msg;
708
+ try {
709
+ msg = JSON.parse(data.toString());
710
+ } catch {
711
+ this.logger.warn("Invalid JSON from test process");
712
+ return;
713
+ }
714
+ if (!authed) {
715
+ if (!isHelloTestMessage(msg)) {
716
+ ws.close(1008, "Expected HELLO_TEST");
717
+ return;
718
+ }
719
+ if (msg.token !== this.opts.token) {
720
+ ws.close(1008, "Invalid token");
721
+ return;
722
+ }
723
+ authed = true;
724
+ clearTimeout(helloTimeout);
725
+ runId = msg.runId;
726
+ const runState = {
727
+ runId,
728
+ pid: msg.pid,
729
+ cwd: msg.cwd,
730
+ startedAt: (/* @__PURE__ */ new Date()).toISOString(),
731
+ lastSeen: Date.now(),
732
+ testMeta: msg.testMeta,
733
+ ws
734
+ };
735
+ this.runs.set(runId, runState);
736
+ const ack = { type: HELLO_ACK, runId };
737
+ ws.send(JSON.stringify(ack));
738
+ this.logger.error(`\u{1F50C} Test run connected: ${runId} (pid: ${msg.pid})`);
739
+ this.resetIdleTimer();
740
+ return;
741
+ }
742
+ if (isBatchMockRequestMessage(msg)) {
743
+ this.handleBatchRequest(runId, msg.requests, ws);
744
+ return;
745
+ }
746
+ if (isHeartbeatMessage(msg)) {
747
+ const run = this.runs.get(msg.runId);
748
+ if (run) {
749
+ run.lastSeen = Date.now();
750
+ }
751
+ const ack = { type: HEARTBEAT_ACK, runId: msg.runId };
752
+ ws.send(JSON.stringify(ack));
753
+ return;
754
+ }
755
+ });
756
+ ws.on("close", () => {
757
+ clearTimeout(helloTimeout);
758
+ if (runId) {
759
+ this.cleanupRun(runId);
760
+ }
761
+ });
762
+ ws.on("error", (err) => {
763
+ this.logger.error("WebSocket error:", err);
764
+ if (runId) {
765
+ this.cleanupRun(runId);
766
+ }
767
+ });
768
+ }
769
+ handleBatchRequest(runId, requests, ws) {
770
+ const batchId = `batch:${runId}:${++this.batchSeq}`;
771
+ const batch = {
772
+ batchId,
773
+ runId,
774
+ requests,
775
+ createdAt: Date.now(),
776
+ status: "pending"
777
+ };
778
+ this.batches.set(batchId, batch);
779
+ this.pendingQueue.push(batchId);
780
+ this.logger.error(
781
+ [
782
+ `\u{1F4E5} Received ${requests.length} request(s) (${batchId})`,
783
+ ...requests.map(
784
+ (req, i) => ` ${i + 1}. ${req.method} ${req.endpoint} (${req.requestId})`
785
+ )
786
+ ].join("\n")
787
+ );
788
+ this.logger.error("\u23F3 Awaiting mock data from MCP adapter...");
789
+ }
790
+ cleanupRun(runId) {
791
+ const run = this.runs.get(runId);
792
+ if (!run) return;
793
+ this.runs.delete(runId);
794
+ for (const [batchId, batch] of this.batches) {
795
+ if (batch.runId === runId) {
796
+ this.batches.delete(batchId);
797
+ }
798
+ }
799
+ for (let i = this.pendingQueue.length - 1; i >= 0; i--) {
800
+ const bid = this.pendingQueue[i];
801
+ if (!this.batches.has(bid)) {
802
+ this.pendingQueue.splice(i, 1);
803
+ }
804
+ }
805
+ this.logger.error(`\u{1F50C} Test run disconnected: ${runId}`);
806
+ this.resetIdleTimer();
807
+ }
808
+ // ===========================================================================
809
+ // JSON-RPC Handler
810
+ // ===========================================================================
811
+ async handleRpc(req) {
812
+ try {
813
+ this.sweepExpiredClaims();
814
+ const params = req.params ?? {};
815
+ switch (req.method) {
816
+ case RPC_GET_STATUS:
817
+ return this.rpcSuccess(req.id, this.getStatus());
818
+ case RPC_LIST_RUNS:
819
+ return this.rpcSuccess(req.id, this.listRuns());
820
+ case RPC_CLAIM_NEXT_BATCH:
821
+ return this.rpcSuccess(req.id, this.claimNextBatch(params));
822
+ case RPC_PROVIDE_BATCH:
823
+ return this.rpcSuccess(req.id, await this.provideBatch(params));
824
+ case RPC_RELEASE_BATCH:
825
+ return this.rpcSuccess(req.id, this.releaseBatch(params));
826
+ case RPC_GET_BATCH:
827
+ return this.rpcSuccess(req.id, this.getBatch(params));
828
+ default:
829
+ return this.rpcError(req.id, RPC_ERROR_METHOD_NOT_FOUND, `Unknown method: ${req.method}`);
830
+ }
831
+ } catch (e) {
832
+ const msg = e instanceof Error ? e.message : String(e);
833
+ const code = this.getErrorCode(e);
834
+ return this.rpcError(req.id, code, msg);
835
+ }
836
+ }
837
+ getErrorCode(e) {
838
+ if (e instanceof RpcError) {
839
+ return e.code;
840
+ }
841
+ return RPC_ERROR_INTERNAL;
842
+ }
843
+ rpcSuccess(id, result) {
844
+ return { jsonrpc: "2.0", id, result };
845
+ }
846
+ rpcError(id, code, message) {
847
+ return { jsonrpc: "2.0", id, error: { code, message } };
848
+ }
849
+ // ===========================================================================
850
+ // RPC Methods
851
+ // ===========================================================================
852
+ getStatus() {
853
+ const pending = this.pendingQueue.filter((bid) => {
854
+ const b = this.batches.get(bid);
855
+ return b && b.status === "pending";
856
+ }).length;
857
+ const claimed = Array.from(this.batches.values()).filter(
858
+ (b) => b.status === "claimed"
859
+ ).length;
860
+ return {
861
+ version: this.opts.version,
862
+ projectId: computeProjectId(this.opts.projectRoot),
863
+ projectRoot: this.opts.projectRoot,
864
+ pid: process.pid,
865
+ uptime: this.startedAt ? Date.now() - this.startedAt : 0,
866
+ runs: this.runs.size,
867
+ pending,
868
+ claimed,
869
+ totalBatches: this.batches.size
870
+ };
871
+ }
872
+ listRuns() {
873
+ const runs = Array.from(this.runs.values()).map((r) => {
874
+ const pendingBatches = Array.from(this.batches.values()).filter(
875
+ (b) => b.runId === r.runId && b.status === "pending"
876
+ ).length;
877
+ return {
878
+ runId: r.runId,
879
+ pid: r.pid,
880
+ cwd: r.cwd,
881
+ startedAt: r.startedAt,
882
+ lastSeen: r.lastSeen,
883
+ pendingBatches,
884
+ testMeta: r.testMeta
885
+ };
886
+ });
887
+ return { runs };
888
+ }
889
+ claimNextBatch(params) {
890
+ const { adapterId, runId, leaseMs = this.opts.defaultLeaseMs } = params;
891
+ if (!adapterId) {
892
+ throw new RpcError(RPC_ERROR_UNAUTHORIZED, "adapterId required");
893
+ }
894
+ for (let i = 0; i < this.pendingQueue.length; i++) {
895
+ const batchId = this.pendingQueue[i];
896
+ const batch = this.batches.get(batchId);
897
+ if (!batch || batch.status !== "pending") {
898
+ continue;
899
+ }
900
+ if (runId && batch.runId !== runId) {
901
+ continue;
902
+ }
903
+ this.pendingQueue.splice(i, 1);
904
+ batch.status = "claimed";
905
+ batch.claim = {
906
+ adapterId,
907
+ claimToken: crypto__default.default.randomUUID(),
908
+ leaseUntil: Date.now() + leaseMs
909
+ };
910
+ this.logger.error(`\u{1F512} Batch ${batchId} claimed by adapter ${adapterId.slice(0, 8)}...`);
911
+ return {
912
+ batchId: batch.batchId,
913
+ runId: batch.runId,
914
+ requests: batch.requests,
915
+ claimToken: batch.claim.claimToken,
916
+ leaseUntil: batch.claim.leaseUntil
917
+ };
918
+ }
919
+ return null;
920
+ }
921
+ async provideBatch(params) {
922
+ const { adapterId, batchId, claimToken, mocks } = params;
923
+ const batch = this.batches.get(batchId);
924
+ if (!batch) {
925
+ throw new RpcError(RPC_ERROR_NOT_FOUND, `Batch not found: ${batchId}`);
926
+ }
927
+ if (batch.status !== "claimed" || !batch.claim) {
928
+ throw new RpcError(RPC_ERROR_CONFLICT, `Batch not in claimed state: ${batchId}`);
929
+ }
930
+ if (batch.claim.adapterId !== adapterId) {
931
+ throw new RpcError(RPC_ERROR_UNAUTHORIZED, "Not the owner of this batch");
932
+ }
933
+ if (batch.claim.claimToken !== claimToken) {
934
+ throw new RpcError(RPC_ERROR_UNAUTHORIZED, "Invalid claim token");
935
+ }
936
+ if (batch.claim.leaseUntil <= Date.now()) {
937
+ batch.status = "pending";
938
+ batch.claim = void 0;
939
+ this.pendingQueue.push(batchId);
940
+ throw new RpcError(RPC_ERROR_EXPIRED, "Claim lease expired");
941
+ }
942
+ this.validateMocks(batch, mocks);
943
+ const run = this.runs.get(batch.runId);
944
+ if (!run) {
945
+ this.batches.delete(batchId);
946
+ throw new RpcError(RPC_ERROR_NOT_FOUND, "Run is gone");
947
+ }
948
+ if (run.ws.readyState !== WebSocket2.WebSocket.OPEN) {
949
+ this.batches.delete(batchId);
950
+ throw new RpcError(RPC_ERROR_NOT_FOUND, "Test process disconnected");
951
+ }
952
+ const result = {
953
+ type: BATCH_MOCK_RESULT,
954
+ batchId,
955
+ mocks
956
+ };
957
+ run.ws.send(JSON.stringify(result));
958
+ batch.status = "fulfilled";
959
+ this.batches.delete(batchId);
960
+ this.logger.error(`\u2705 Delivered ${mocks.length} mock(s) for ${batchId}`);
961
+ return { ok: true, message: `Provided ${mocks.length} mock(s) for ${batchId}` };
962
+ }
963
+ validateMocks(batch, mocks) {
964
+ const expectedIds = new Set(batch.requests.map((r) => r.requestId));
965
+ const providedIds = /* @__PURE__ */ new Set();
966
+ for (const mock of mocks) {
967
+ if (!expectedIds.has(mock.requestId)) {
968
+ throw new RpcError(
969
+ RPC_ERROR_CONFLICT,
970
+ `Mock references unknown requestId: ${mock.requestId}`
971
+ );
972
+ }
973
+ if (providedIds.has(mock.requestId)) {
974
+ throw new RpcError(
975
+ RPC_ERROR_CONFLICT,
976
+ `Duplicate mock for requestId: ${mock.requestId}`
977
+ );
978
+ }
979
+ providedIds.add(mock.requestId);
980
+ }
981
+ const missing = Array.from(expectedIds).filter((id) => !providedIds.has(id));
982
+ if (missing.length > 0) {
983
+ throw new RpcError(
984
+ RPC_ERROR_CONFLICT,
985
+ `Missing mocks for requestId(s): ${missing.join(", ")}`
986
+ );
987
+ }
988
+ }
989
+ releaseBatch(params) {
990
+ const { adapterId, batchId, claimToken } = params;
991
+ const batch = this.batches.get(batchId);
992
+ if (!batch) {
993
+ throw new RpcError(RPC_ERROR_NOT_FOUND, `Batch not found: ${batchId}`);
994
+ }
995
+ if (batch.status !== "claimed" || !batch.claim) {
996
+ throw new RpcError(RPC_ERROR_CONFLICT, `Batch not in claimed state: ${batchId}`);
997
+ }
998
+ if (batch.claim.adapterId !== adapterId || batch.claim.claimToken !== claimToken) {
999
+ throw new RpcError(RPC_ERROR_UNAUTHORIZED, "Not the owner of this batch");
1000
+ }
1001
+ batch.status = "pending";
1002
+ batch.claim = void 0;
1003
+ this.pendingQueue.push(batchId);
1004
+ this.logger.error(`\u{1F513} Batch ${batchId} released by adapter`);
1005
+ return { ok: true };
1006
+ }
1007
+ getBatch(params) {
1008
+ const batch = this.batches.get(params.batchId);
1009
+ if (!batch) {
1010
+ throw new RpcError(RPC_ERROR_NOT_FOUND, `Batch not found: ${params.batchId}`);
1011
+ }
1012
+ return {
1013
+ batchId: batch.batchId,
1014
+ runId: batch.runId,
1015
+ requests: batch.requests,
1016
+ status: batch.status,
1017
+ createdAt: batch.createdAt,
1018
+ claim: batch.claim ? { adapterId: batch.claim.adapterId, leaseUntil: batch.claim.leaseUntil } : void 0
1019
+ };
1020
+ }
1021
+ // ===========================================================================
1022
+ // Maintenance
1023
+ // ===========================================================================
1024
+ sweepExpiredClaims() {
1025
+ const now = Date.now();
1026
+ for (const batch of this.batches.values()) {
1027
+ if (batch.status === "claimed" && batch.claim && batch.claim.leaseUntil <= now) {
1028
+ this.logger.warn(`\u23F0 Claim expired for ${batch.batchId}, returning to pending`);
1029
+ batch.status = "pending";
1030
+ batch.claim = void 0;
1031
+ this.pendingQueue.push(batch.batchId);
1032
+ }
1033
+ }
1034
+ }
1035
+ resetIdleTimer() {
1036
+ if (this.idleTimer) {
1037
+ clearTimeout(this.idleTimer);
1038
+ }
1039
+ if (this.runs.size === 0) {
1040
+ this.idleTimer = setTimeout(() => {
1041
+ if (this.runs.size === 0) {
1042
+ this.logger.error("\u{1F4A4} No activity, shutting down daemon...");
1043
+ this.stop().then(() => process.exit(0));
1044
+ }
1045
+ }, this.opts.idleShutdownMs);
1046
+ this.idleTimer.unref?.();
1047
+ }
1048
+ }
1049
+ };
1050
+ RpcError = class extends Error {
1051
+ constructor(code, message) {
1052
+ super(message);
1053
+ this.code = code;
1054
+ this.name = "RpcError";
1055
+ }
1056
+ };
1057
+ }
1058
+ });
1059
+ exports.MultiDaemonClient = void 0;
1060
+ var init_multi_daemon_client = __esm({
1061
+ "src/adapter/multi-daemon-client.ts"() {
1062
+ init_discovery();
1063
+ exports.MultiDaemonClient = class {
1064
+ logger;
1065
+ cacheDir;
1066
+ adapterId;
1067
+ constructor(opts = {}) {
1068
+ this.logger = opts.logger ?? console;
1069
+ this.cacheDir = opts.cacheDir;
1070
+ this.adapterId = crypto__default.default.randomUUID();
1071
+ }
1072
+ // ===========================================================================
1073
+ // Discovery
1074
+ // ===========================================================================
1075
+ /**
1076
+ * Discover all active and healthy daemons.
1077
+ */
1078
+ async discoverDaemons() {
1079
+ return discoverAllDaemons(this.cacheDir);
1080
+ }
1081
+ // ===========================================================================
1082
+ // Aggregated RPC Methods
1083
+ // ===========================================================================
1084
+ /**
1085
+ * Get aggregated status from all daemons.
1086
+ */
1087
+ async getAggregatedStatus() {
1088
+ const daemons = await this.discoverDaemons();
1089
+ const statuses = [];
1090
+ let totalRuns = 0;
1091
+ let totalPending = 0;
1092
+ let totalClaimed = 0;
1093
+ for (const { registry, healthy } of daemons) {
1094
+ if (!healthy) {
1095
+ statuses.push({
1096
+ version: registry.version,
1097
+ projectId: registry.projectId,
1098
+ projectRoot: registry.projectRoot,
1099
+ pid: registry.pid,
1100
+ uptime: 0,
1101
+ runs: 0,
1102
+ pending: 0,
1103
+ claimed: 0,
1104
+ totalBatches: 0,
1105
+ healthy: false
1106
+ });
1107
+ continue;
1108
+ }
1109
+ try {
1110
+ const status = await this.rpc(registry, "getStatus", {});
1111
+ statuses.push({ ...status, healthy: true });
1112
+ totalRuns += status.runs;
1113
+ totalPending += status.pending;
1114
+ totalClaimed += status.claimed;
1115
+ } catch (error) {
1116
+ this.logger.warn(`Failed to get status from daemon ${registry.projectId}: ${error}`);
1117
+ statuses.push({
1118
+ version: registry.version,
1119
+ projectId: registry.projectId,
1120
+ projectRoot: registry.projectRoot,
1121
+ pid: registry.pid,
1122
+ uptime: 0,
1123
+ runs: 0,
1124
+ pending: 0,
1125
+ claimed: 0,
1126
+ totalBatches: 0,
1127
+ healthy: false
1128
+ });
1129
+ }
1130
+ }
1131
+ return { daemons: statuses, totalRuns, totalPending, totalClaimed };
1132
+ }
1133
+ /**
1134
+ * List all runs across all daemons.
1135
+ */
1136
+ async listAllRuns() {
1137
+ const daemons = await this.discoverDaemons();
1138
+ const allRuns = [];
1139
+ for (const { registry, healthy } of daemons) {
1140
+ if (!healthy) continue;
1141
+ try {
1142
+ const result = await this.rpc(registry, "listRuns", {});
1143
+ for (const run of result.runs) {
1144
+ allRuns.push({
1145
+ ...run,
1146
+ projectId: registry.projectId,
1147
+ projectRoot: registry.projectRoot
1148
+ });
1149
+ }
1150
+ } catch (error) {
1151
+ this.logger.warn(`Failed to list runs from daemon ${registry.projectId}: ${error}`);
1152
+ }
1153
+ }
1154
+ return allRuns;
1155
+ }
1156
+ /**
1157
+ * Claim the next available batch from any daemon.
1158
+ * Searches through all daemons in order until finding one with a pending batch.
1159
+ */
1160
+ async claimNextBatch(args) {
1161
+ const daemons = await this.discoverDaemons();
1162
+ for (const { registry, healthy } of daemons) {
1163
+ if (!healthy) continue;
1164
+ try {
1165
+ const result = await this.rpc(registry, "claimNextBatch", {
1166
+ adapterId: this.adapterId,
1167
+ runId: args.runId,
1168
+ leaseMs: args.leaseMs
1169
+ });
1170
+ if (result) {
1171
+ return {
1172
+ ...result,
1173
+ projectId: registry.projectId,
1174
+ projectRoot: registry.projectRoot
1175
+ };
1176
+ }
1177
+ } catch (error) {
1178
+ this.logger.warn(`Failed to claim batch from daemon ${registry.projectId}: ${error}`);
1179
+ }
1180
+ }
1181
+ return null;
1182
+ }
1183
+ /**
1184
+ * Provide mock data for a batch.
1185
+ * Automatically routes to the correct daemon based on batchId.
1186
+ */
1187
+ async provideBatch(args) {
1188
+ const parts = args.batchId.split(":");
1189
+ if (parts.length < 2) {
1190
+ return { ok: false, message: `Invalid batchId format: ${args.batchId}` };
1191
+ }
1192
+ const daemons = await this.discoverDaemons();
1193
+ for (const { registry, healthy } of daemons) {
1194
+ if (!healthy) continue;
1195
+ try {
1196
+ const result = await this.rpc(registry, "provideBatch", {
1197
+ adapterId: this.adapterId,
1198
+ batchId: args.batchId,
1199
+ claimToken: args.claimToken,
1200
+ mocks: args.mocks
1201
+ });
1202
+ return result;
1203
+ } catch (error) {
1204
+ const msg = error instanceof Error ? error.message : String(error);
1205
+ if (msg.includes("not found") || msg.includes("Not found")) {
1206
+ continue;
1207
+ }
1208
+ return { ok: false, message: msg };
1209
+ }
1210
+ }
1211
+ return { ok: false, message: `Batch not found: ${args.batchId}` };
1212
+ }
1213
+ /**
1214
+ * Release a batch.
1215
+ */
1216
+ async releaseBatch(args) {
1217
+ const daemons = await this.discoverDaemons();
1218
+ for (const { registry, healthy } of daemons) {
1219
+ if (!healthy) continue;
1220
+ try {
1221
+ const result = await this.rpc(registry, "releaseBatch", {
1222
+ adapterId: this.adapterId,
1223
+ batchId: args.batchId,
1224
+ claimToken: args.claimToken,
1225
+ reason: args.reason
1226
+ });
1227
+ return result;
1228
+ } catch (error) {
1229
+ const msg = error instanceof Error ? error.message : String(error);
1230
+ if (msg.includes("not found") || msg.includes("Not found")) {
1231
+ continue;
1232
+ }
1233
+ return { ok: false, message: msg };
1234
+ }
1235
+ }
1236
+ return { ok: false, message: `Batch not found: ${args.batchId}` };
1237
+ }
1238
+ /**
1239
+ * Get a specific batch by ID.
1240
+ */
1241
+ async getBatch(batchId) {
1242
+ const daemons = await this.discoverDaemons();
1243
+ for (const { registry, healthy } of daemons) {
1244
+ if (!healthy) continue;
1245
+ try {
1246
+ const result = await this.rpc(registry, "getBatch", { batchId });
1247
+ return result;
1248
+ } catch (error) {
1249
+ const msg = error instanceof Error ? error.message : String(error);
1250
+ if (msg.includes("not found") || msg.includes("Not found")) {
1251
+ continue;
1252
+ }
1253
+ throw error;
1254
+ }
1255
+ }
1256
+ return null;
1257
+ }
1258
+ // ===========================================================================
1259
+ // Internal RPC
1260
+ // ===========================================================================
1261
+ rpc(registry, method, params) {
1262
+ const payload = {
1263
+ jsonrpc: "2.0",
1264
+ id: crypto__default.default.randomUUID(),
1265
+ method,
1266
+ params
1267
+ };
1268
+ return new Promise((resolve, reject) => {
1269
+ const req = http__default.default.request(
1270
+ {
1271
+ method: "POST",
1272
+ socketPath: registry.ipcPath,
1273
+ path: "/control",
1274
+ headers: {
1275
+ "content-type": "application/json",
1276
+ "x-mock-mcp-token": registry.token
1277
+ },
1278
+ timeout: 3e4
1279
+ },
1280
+ (res) => {
1281
+ let buf = "";
1282
+ res.on("data", (chunk) => buf += chunk);
1283
+ res.on("end", () => {
1284
+ try {
1285
+ const response = JSON.parse(buf);
1286
+ if (response.error) {
1287
+ reject(new Error(response.error.message));
1288
+ } else {
1289
+ resolve(response.result);
1290
+ }
1291
+ } catch (e) {
1292
+ reject(e);
1293
+ }
1294
+ });
1295
+ }
1296
+ );
1297
+ req.on("error", (err) => {
1298
+ reject(new Error(`Daemon connection failed: ${err.message}`));
1299
+ });
1300
+ req.on("timeout", () => {
1301
+ req.destroy();
1302
+ reject(new Error("Daemon request timeout"));
1303
+ });
1304
+ req.end(JSON.stringify(payload));
1305
+ });
1306
+ }
1307
+ };
1308
+ }
1309
+ });
1310
+
1311
+ // src/adapter/adapter.ts
1312
+ var adapter_exports = {};
1313
+ __export(adapter_exports, {
1314
+ runAdapter: () => runAdapter
1315
+ });
1316
+ async function runAdapter(opts = {}) {
1317
+ const logger = opts.logger ?? console;
1318
+ const version = opts.version ?? "0.5.0";
1319
+ logger.error("\u{1F50D} Initializing mock-mcp adapter (multi-daemon mode)...");
1320
+ const multiDaemon = new exports.MultiDaemonClient({ logger });
1321
+ const daemons = await multiDaemon.discoverDaemons();
1322
+ if (daemons.length > 0) {
1323
+ logger.error(`\u2705 Found ${daemons.length} active daemon(s):`);
1324
+ for (const d of daemons) {
1325
+ const status = d.healthy ? "healthy" : "unhealthy";
1326
+ logger.error(` - ${d.registry.projectId}: ${d.registry.projectRoot} (${status})`);
1327
+ }
1328
+ } else {
1329
+ logger.error("\u2139\uFE0F No active daemons found. Waiting for test processes to start...");
1330
+ }
1331
+ const server = new index_js.Server(
1332
+ {
1333
+ name: "mock-mcp-adapter",
1334
+ version
1335
+ },
1336
+ {
1337
+ capabilities: { tools: {} }
1338
+ }
1339
+ );
1340
+ server.setRequestHandler(types_js.ListToolsRequestSchema, async () => ({
1341
+ tools: [...TOOLS]
1342
+ }));
1343
+ server.setRequestHandler(types_js.CallToolRequestSchema, async (request) => {
1344
+ const { name, arguments: args } = request.params;
1345
+ try {
1346
+ switch (name) {
1347
+ case "get_status": {
1348
+ const result = await multiDaemon.getAggregatedStatus();
1349
+ return buildToolResponse(formatAggregatedStatus(result));
1350
+ }
1351
+ case "list_runs": {
1352
+ const result = await multiDaemon.listAllRuns();
1353
+ return buildToolResponse(formatExtendedRuns(result));
1354
+ }
1355
+ case "claim_next_batch": {
1356
+ const result = await multiDaemon.claimNextBatch({
1357
+ runId: args?.runId,
1358
+ leaseMs: args?.leaseMs
1359
+ });
1360
+ return buildToolResponse(formatClaimResult(result));
1361
+ }
1362
+ case "get_batch": {
1363
+ if (!args?.batchId) {
1364
+ throw new Error("batchId is required");
1365
+ }
1366
+ const result = await multiDaemon.getBatch(args.batchId);
1367
+ if (!result) {
1368
+ throw new Error(`Batch not found: ${args.batchId}`);
1369
+ }
1370
+ return buildToolResponse(formatBatch(result));
1371
+ }
1372
+ case "provide_batch_mock_data": {
1373
+ if (!args?.batchId || !args?.claimToken || !args?.mocks) {
1374
+ throw new Error("batchId, claimToken, and mocks are required");
1375
+ }
1376
+ const result = await multiDaemon.provideBatch({
1377
+ batchId: args.batchId,
1378
+ claimToken: args.claimToken,
1379
+ mocks: args.mocks
1380
+ });
1381
+ return buildToolResponse(formatProvideResult(result));
1382
+ }
1383
+ case "release_batch": {
1384
+ if (!args?.batchId || !args?.claimToken) {
1385
+ throw new Error("batchId and claimToken are required");
1386
+ }
1387
+ const result = await multiDaemon.releaseBatch({
1388
+ batchId: args.batchId,
1389
+ claimToken: args.claimToken,
1390
+ reason: args?.reason
1391
+ });
1392
+ return buildToolResponse(JSON.stringify(result, null, 2));
1393
+ }
1394
+ default:
1395
+ throw new Error(`Unknown tool: ${name}`);
1396
+ }
1397
+ } catch (error) {
1398
+ const message = error instanceof Error ? error.message : String(error);
1399
+ logger.error(`Tool error (${name}): ${message}`);
1400
+ return buildToolResponse(`Error: ${message}`, true);
1401
+ }
1402
+ });
1403
+ const transport = new stdio_js.StdioServerTransport();
1404
+ await server.connect(transport);
1405
+ logger.error("\u2705 MCP adapter ready (stdio transport)");
1406
+ }
1407
+ function buildToolResponse(text, isError = false) {
1408
+ return {
1409
+ content: [{ type: "text", text }],
1410
+ isError
1411
+ };
1412
+ }
1413
+ function formatAggregatedStatus(status) {
1414
+ if (status.daemons.length === 0) {
1415
+ return `# Mock MCP Status
1416
+
1417
+ No active daemons found. Start a test with \`MOCK_MCP=1\` to begin.
1418
+ `;
1419
+ }
1420
+ const lines = [
1421
+ "# Mock MCP Status\n",
1422
+ "## Summary",
1423
+ `- **Active Daemons**: ${status.daemons.filter((d) => d.healthy).length}`,
1424
+ `- **Total Active Runs**: ${status.totalRuns}`,
1425
+ `- **Total Pending Batches**: ${status.totalPending}`,
1426
+ `- **Total Claimed Batches**: ${status.totalClaimed}`,
1427
+ "",
1428
+ "## Daemons\n"
1429
+ ];
1430
+ for (const daemon of status.daemons) {
1431
+ const healthIcon = daemon.healthy ? "\u2705" : "\u274C";
1432
+ lines.push(`### ${healthIcon} ${daemon.projectRoot}`);
1433
+ lines.push(`- **Project ID**: ${daemon.projectId}`);
1434
+ lines.push(`- **Version**: ${daemon.version}`);
1435
+ lines.push(`- **PID**: ${daemon.pid}`);
1436
+ if (daemon.healthy) {
1437
+ lines.push(`- **Uptime**: ${Math.round(daemon.uptime / 1e3)}s`);
1438
+ lines.push(`- **Runs**: ${daemon.runs}`);
1439
+ lines.push(`- **Pending**: ${daemon.pending}`);
1440
+ lines.push(`- **Claimed**: ${daemon.claimed}`);
1441
+ } else {
1442
+ lines.push(`- **Status**: Not responding`);
1443
+ }
1444
+ lines.push("");
1445
+ }
1446
+ return lines.join("\n");
1447
+ }
1448
+ function formatExtendedRuns(runs) {
1449
+ if (runs.length === 0) {
1450
+ return "No active test runs.\n\nStart a test with `MOCK_MCP=1` to begin.";
1451
+ }
1452
+ const lines = ["# Active Test Runs\n"];
1453
+ const byProject = /* @__PURE__ */ new Map();
1454
+ for (const run of runs) {
1455
+ const key = run.projectRoot;
1456
+ if (!byProject.has(key)) {
1457
+ byProject.set(key, []);
1458
+ }
1459
+ byProject.get(key).push(run);
1460
+ }
1461
+ for (const [projectRoot, projectRuns] of byProject) {
1462
+ lines.push(`## Project: ${projectRoot}
1463
+ `);
1464
+ for (const run of projectRuns) {
1465
+ lines.push(`### Run: ${run.runId}`);
1466
+ lines.push(`- **PID**: ${run.pid}`);
1467
+ lines.push(`- **CWD**: ${run.cwd}`);
1468
+ lines.push(`- **Started**: ${run.startedAt}`);
1469
+ lines.push(`- **Pending Batches**: ${run.pendingBatches}`);
1470
+ if (run.testMeta) {
1471
+ if (run.testMeta.testFile) {
1472
+ lines.push(`- **Test File**: ${run.testMeta.testFile}`);
1473
+ }
1474
+ if (run.testMeta.testName) {
1475
+ lines.push(`- **Test Name**: ${run.testMeta.testName}`);
1476
+ }
1477
+ }
1478
+ lines.push("");
1479
+ }
1480
+ }
1481
+ return lines.join("\n");
1482
+ }
1483
+ function formatClaimResult(result) {
1484
+ if (!result) {
1485
+ return "No pending batches available to claim.\n\nMake sure a test is running with `MOCK_MCP=1` and has pending mock requests.";
1486
+ }
1487
+ const lines = [
1488
+ "# Batch Claimed Successfully\n",
1489
+ `**Batch ID**: \`${result.batchId}\``,
1490
+ `**Claim Token**: \`${result.claimToken}\``,
1491
+ `**Run ID**: ${result.runId}`,
1492
+ `**Project**: ${result.projectRoot}`,
1493
+ `**Lease Until**: ${new Date(result.leaseUntil).toISOString()}`,
1494
+ "",
1495
+ "## Requests\n"
1496
+ ];
1497
+ for (const req of result.requests) {
1498
+ lines.push(`### ${req.method} ${req.endpoint}`);
1499
+ lines.push(`- **Request ID**: \`${req.requestId}\``);
1500
+ if (req.body !== void 0) {
1501
+ lines.push(`- **Body**: \`\`\`json
1502
+ ${JSON.stringify(req.body, null, 2)}
1503
+ \`\`\``);
1504
+ }
1505
+ if (req.headers) {
1506
+ lines.push(`- **Headers**: ${JSON.stringify(req.headers)}`);
1507
+ }
1508
+ if (req.metadata) {
1509
+ lines.push(`- **Metadata**: ${JSON.stringify(req.metadata)}`);
1510
+ }
1511
+ lines.push("");
1512
+ }
1513
+ lines.push("---");
1514
+ lines.push("**Next step**: Call `provide_batch_mock_data` with the batch ID, claim token, and mock data for each request.");
1515
+ return lines.join("\n");
1516
+ }
1517
+ function formatBatch(result) {
1518
+ const lines = [
1519
+ `# Batch: ${result.batchId}
1520
+ `,
1521
+ `**Status**: ${result.status}`,
1522
+ `**Run ID**: ${result.runId}`,
1523
+ `**Created**: ${new Date(result.createdAt).toISOString()}`
1524
+ ];
1525
+ if (result.claim) {
1526
+ lines.push(`**Claimed by**: ${result.claim.adapterId}`);
1527
+ lines.push(`**Lease until**: ${new Date(result.claim.leaseUntil).toISOString()}`);
1528
+ }
1529
+ lines.push("", "## Requests\n");
1530
+ for (const req of result.requests) {
1531
+ lines.push(`### ${req.method} ${req.endpoint}`);
1532
+ lines.push(`- **Request ID**: \`${req.requestId}\``);
1533
+ if (req.body !== void 0) {
1534
+ lines.push(`- **Body**: \`\`\`json
1535
+ ${JSON.stringify(req.body, null, 2)}
1536
+ \`\`\``);
1537
+ }
1538
+ lines.push("");
1539
+ }
1540
+ return lines.join("\n");
1541
+ }
1542
+ function formatProvideResult(result) {
1543
+ if (result.ok) {
1544
+ return `\u2705 ${result.message ?? "Mock data provided successfully."}`;
1545
+ }
1546
+ return `\u274C Failed to provide mock data: ${result.message}`;
1547
+ }
1548
+ var TOOLS;
1549
+ var init_adapter = __esm({
1550
+ "src/adapter/adapter.ts"() {
1551
+ init_multi_daemon_client();
1552
+ TOOLS = [
1553
+ {
1554
+ name: "get_status",
1555
+ description: "Get the current status of the mock-mcp daemon, including active test runs and pending batches.",
1556
+ inputSchema: {
1557
+ type: "object",
1558
+ properties: {},
1559
+ required: []
1560
+ }
1561
+ },
1562
+ {
1563
+ name: "list_runs",
1564
+ description: "List all active test runs connected to the daemon.",
1565
+ inputSchema: {
1566
+ type: "object",
1567
+ properties: {},
1568
+ required: []
1569
+ }
1570
+ },
1571
+ {
1572
+ name: "claim_next_batch",
1573
+ description: `Claim the next pending mock batch for processing. This acquires a lease on the batch.
1574
+
1575
+ You MUST call this before provide_batch_mock_data. The batch will be locked for 30 seconds (configurable via leaseMs).
1576
+ If you don't provide mock data within the lease time, the batch will be released for another adapter to claim.`,
1577
+ inputSchema: {
1578
+ type: "object",
1579
+ properties: {
1580
+ runId: {
1581
+ type: "string",
1582
+ description: "Optional: Filter to only claim batches from a specific test run."
1583
+ },
1584
+ leaseMs: {
1585
+ type: "number",
1586
+ description: "Optional: Lease duration in milliseconds. Default: 30000 (30 seconds)."
1587
+ }
1588
+ },
1589
+ required: []
1590
+ }
1591
+ },
1592
+ {
1593
+ name: "get_batch",
1594
+ description: "Get details of a specific batch by ID (read-only, does not claim).",
1595
+ inputSchema: {
1596
+ type: "object",
1597
+ properties: {
1598
+ batchId: {
1599
+ type: "string",
1600
+ description: "The batch ID to retrieve."
1601
+ }
1602
+ },
1603
+ required: ["batchId"]
1604
+ }
1605
+ },
1606
+ {
1607
+ name: "provide_batch_mock_data",
1608
+ description: `Provide mock response data for a claimed batch.
1609
+
1610
+ You MUST first call claim_next_batch to get the batchId and claimToken.
1611
+ The mocks array must contain exactly one mock for each request in the batch.`,
1612
+ inputSchema: {
1613
+ type: "object",
1614
+ properties: {
1615
+ batchId: {
1616
+ type: "string",
1617
+ description: "The batch ID (from claim_next_batch)."
1618
+ },
1619
+ claimToken: {
1620
+ type: "string",
1621
+ description: "The claim token (from claim_next_batch)."
1622
+ },
1623
+ mocks: {
1624
+ type: "array",
1625
+ description: "Array of mock responses, one for each request in the batch.",
1626
+ items: {
1627
+ type: "object",
1628
+ properties: {
1629
+ requestId: {
1630
+ type: "string",
1631
+ description: "The requestId from the original request."
1632
+ },
1633
+ data: {
1634
+ description: "The mock response data (any JSON value)."
1635
+ },
1636
+ status: {
1637
+ type: "number",
1638
+ description: "Optional HTTP status code. Default: 200."
1639
+ },
1640
+ headers: {
1641
+ type: "object",
1642
+ description: "Optional response headers."
1643
+ },
1644
+ delayMs: {
1645
+ type: "number",
1646
+ description: "Optional delay before returning the mock (ms)."
1647
+ }
1648
+ },
1649
+ required: ["requestId", "data"]
1650
+ }
1651
+ }
1652
+ },
1653
+ required: ["batchId", "claimToken", "mocks"]
1654
+ }
1655
+ },
1656
+ {
1657
+ name: "release_batch",
1658
+ description: "Release a claimed batch without providing mock data. Use this if you cannot generate appropriate mocks.",
1659
+ inputSchema: {
1660
+ type: "object",
1661
+ properties: {
1662
+ batchId: {
1663
+ type: "string",
1664
+ description: "The batch ID to release."
1665
+ },
1666
+ claimToken: {
1667
+ type: "string",
1668
+ description: "The claim token."
1669
+ },
1670
+ reason: {
1671
+ type: "string",
1672
+ description: "Optional reason for releasing."
1673
+ }
1674
+ },
1675
+ required: ["batchId", "claimToken"]
1676
+ }
1677
+ }
1678
+ ];
1679
+ }
1680
+ });
1681
+
1682
+ // src/index.ts
1683
+ init_daemon();
1684
+
1685
+ // src/adapter/index.ts
1686
+ init_adapter();
1687
+ var DaemonClient = class {
1688
+ constructor(ipcPath, token, adapterId) {
1689
+ this.ipcPath = ipcPath;
1690
+ this.token = token;
1691
+ this.adapterId = adapterId;
1692
+ }
1693
+ // ===========================================================================
1694
+ // RPC Methods
1695
+ // ===========================================================================
1696
+ async getStatus() {
1697
+ return this.rpc("getStatus", {});
1698
+ }
1699
+ async listRuns() {
1700
+ return this.rpc("listRuns", {});
1701
+ }
1702
+ async claimNextBatch(args) {
1703
+ return this.rpc("claimNextBatch", {
1704
+ adapterId: this.adapterId,
1705
+ runId: args.runId,
1706
+ leaseMs: args.leaseMs
1707
+ });
1708
+ }
1709
+ async provideBatch(args) {
1710
+ return this.rpc("provideBatch", {
1711
+ adapterId: this.adapterId,
1712
+ batchId: args.batchId,
1713
+ claimToken: args.claimToken,
1714
+ mocks: args.mocks
1715
+ });
1716
+ }
1717
+ async releaseBatch(args) {
1718
+ return this.rpc("releaseBatch", {
1719
+ adapterId: this.adapterId,
1720
+ batchId: args.batchId,
1721
+ claimToken: args.claimToken,
1722
+ reason: args.reason
1723
+ });
1724
+ }
1725
+ async getBatch(batchId) {
1726
+ return this.rpc("getBatch", { batchId });
1727
+ }
1728
+ // ===========================================================================
1729
+ // Internal
1730
+ // ===========================================================================
1731
+ rpc(method, params) {
1732
+ const payload = {
1733
+ jsonrpc: "2.0",
1734
+ id: crypto__default.default.randomUUID(),
1735
+ method,
1736
+ params
1737
+ };
1738
+ return new Promise((resolve, reject) => {
1739
+ const req = http__default.default.request(
1740
+ {
1741
+ method: "POST",
1742
+ socketPath: this.ipcPath,
1743
+ path: "/control",
1744
+ headers: {
1745
+ "content-type": "application/json",
1746
+ "x-mock-mcp-token": this.token
1747
+ },
1748
+ timeout: 3e4
1749
+ },
1750
+ (res) => {
1751
+ let buf = "";
1752
+ res.on("data", (chunk) => buf += chunk);
1753
+ res.on("end", () => {
1754
+ try {
1755
+ const response = JSON.parse(buf);
1756
+ if (response.error) {
1757
+ reject(new Error(response.error.message));
1758
+ } else {
1759
+ resolve(response.result);
1760
+ }
1761
+ } catch (e) {
1762
+ reject(e);
1763
+ }
1764
+ });
1765
+ }
1766
+ );
1767
+ req.on("error", (err) => {
1768
+ reject(new Error(`Daemon connection failed: ${err.message}`));
1769
+ });
1770
+ req.on("timeout", () => {
1771
+ req.destroy();
1772
+ reject(new Error("Daemon request timeout"));
1773
+ });
1774
+ req.end(JSON.stringify(payload));
1775
+ });
1776
+ }
1777
+ };
1778
+
1779
+ // src/adapter/index.ts
1780
+ init_multi_daemon_client();
1781
+
1782
+ // src/client/batch-mock-collector.ts
1783
+ init_discovery();
1784
+ init_protocol();
1785
+
1786
+ // src/client/util.ts
1787
+ var isEnabled = () => {
1788
+ return process.env.MOCK_MCP !== void 0 && process.env.MOCK_MCP !== "0";
1789
+ };
1790
+
1791
+ // src/client/batch-mock-collector.ts
1792
+ var DEFAULT_TIMEOUT = 6e4;
1793
+ var DEFAULT_BATCH_DEBOUNCE_MS = 0;
1794
+ var DEFAULT_MAX_BATCH_SIZE = 50;
1795
+ var DEFAULT_HEARTBEAT_INTERVAL_MS = 15e3;
1796
+ var BatchMockCollector = class {
1797
+ ws;
1798
+ registry;
1799
+ runId = crypto__default.default.randomUUID();
1800
+ pendingRequests = /* @__PURE__ */ new Map();
1801
+ queuedRequestIds = /* @__PURE__ */ new Set();
1802
+ timeout;
1803
+ batchDebounceMs;
1804
+ maxBatchSize;
1805
+ logger;
1806
+ heartbeatIntervalMs;
1807
+ enableReconnect;
1808
+ projectRoot;
1809
+ testMeta;
1810
+ batchTimer = null;
1811
+ heartbeatTimer = null;
1812
+ reconnectTimer = null;
1813
+ requestIdCounter = 0;
1814
+ closed = false;
1815
+ authed = false;
1816
+ readyResolve;
1817
+ readyReject;
1818
+ readyPromise = Promise.resolve();
1819
+ constructor(options = {}) {
1820
+ this.timeout = options.timeout ?? DEFAULT_TIMEOUT;
1821
+ this.batchDebounceMs = options.batchDebounceMs ?? DEFAULT_BATCH_DEBOUNCE_MS;
1822
+ this.maxBatchSize = options.maxBatchSize ?? DEFAULT_MAX_BATCH_SIZE;
1823
+ this.logger = options.logger ?? console;
1824
+ this.heartbeatIntervalMs = options.heartbeatIntervalMs ?? DEFAULT_HEARTBEAT_INTERVAL_MS;
1825
+ this.enableReconnect = options.enableReconnect ?? true;
1826
+ this.testMeta = options.testMeta;
1827
+ this.projectRoot = this.resolveProjectRootFromOptions(options);
1828
+ this.logger.log(`[mock-mcp] BatchMockCollector created`);
1829
+ this.logger.log(`[mock-mcp] runId: ${this.runId}`);
1830
+ this.logger.log(`[mock-mcp] timeout: ${this.timeout}ms`);
1831
+ this.logger.log(`[mock-mcp] batchDebounceMs: ${this.batchDebounceMs}ms`);
1832
+ this.logger.log(`[mock-mcp] maxBatchSize: ${this.maxBatchSize}`);
1833
+ this.logger.log(`[mock-mcp] heartbeatIntervalMs: ${this.heartbeatIntervalMs}ms`);
1834
+ this.logger.log(`[mock-mcp] enableReconnect: ${this.enableReconnect}`);
1835
+ this.logger.log(`[mock-mcp] projectRoot: ${this.projectRoot ?? "(auto-detect)"}`);
1836
+ if (options.filePath) {
1837
+ this.logger.log(`[mock-mcp] filePath: ${options.filePath}`);
1838
+ }
1839
+ this.resetReadyPromise();
1840
+ this.initConnection({
1841
+ timeout: this.timeout
1842
+ });
1843
+ }
1844
+ /**
1845
+ * Resolve projectRoot from options.
1846
+ * Priority: projectRoot (if valid) > filePath > projectRoot (fallback) > undefined (auto-detect)
1847
+ *
1848
+ * A projectRoot is "valid" if it contains .git or package.json. This prevents
1849
+ * accidentally using a wrong directory (e.g., user's home directory) when the
1850
+ * caller mistakenly passes process.cwd() as projectRoot.
1851
+ */
1852
+ resolveProjectRootFromOptions(options) {
1853
+ if (options.projectRoot) {
1854
+ const hasGit = this.hasGitOrPackageJson(options.projectRoot);
1855
+ if (hasGit) {
1856
+ return options.projectRoot;
1857
+ }
1858
+ this.logger.warn(`[mock-mcp] Warning: projectRoot "${options.projectRoot}" doesn't contain .git or package.json`);
1859
+ }
1860
+ if (options.filePath) {
1861
+ let filePath = options.filePath;
1862
+ if (filePath.startsWith("file://")) {
1863
+ try {
1864
+ filePath = url.fileURLToPath(filePath);
1865
+ } catch {
1866
+ filePath = filePath.replace(/^file:\/\//, "");
1867
+ }
1868
+ }
1869
+ const dir = path__default.default.dirname(filePath);
1870
+ const resolved = resolveProjectRoot(dir);
1871
+ this.logger.log(`[mock-mcp] Resolved projectRoot from filePath:`);
1872
+ this.logger.log(`[mock-mcp] filePath: ${options.filePath}`);
1873
+ this.logger.log(`[mock-mcp] dir: ${dir}`);
1874
+ this.logger.log(`[mock-mcp] projectRoot: ${resolved}`);
1875
+ return resolved;
1876
+ }
1877
+ if (options.projectRoot) {
1878
+ this.logger.warn(`[mock-mcp] Warning: Using projectRoot "${options.projectRoot}" despite missing .git/package.json`);
1879
+ return options.projectRoot;
1880
+ }
1881
+ return void 0;
1882
+ }
1883
+ /**
1884
+ * Check if a directory contains .git or package.json
1885
+ */
1886
+ hasGitOrPackageJson(dir) {
1887
+ try {
1888
+ const gitPath = path__default.default.join(dir, ".git");
1889
+ const pkgPath = path__default.default.join(dir, "package.json");
1890
+ try {
1891
+ const stat = fssync__default.default.statSync(gitPath);
1892
+ if (stat.isDirectory() || stat.isFile()) {
1893
+ return true;
1894
+ }
1895
+ } catch {
1896
+ }
1897
+ try {
1898
+ fssync__default.default.accessSync(pkgPath, fssync__default.default.constants.F_OK);
1899
+ return true;
1900
+ } catch {
1901
+ }
1902
+ return false;
1903
+ } catch {
1904
+ return false;
1905
+ }
1906
+ }
1907
+ /**
1908
+ * Ensures the underlying connection is ready for use.
1909
+ */
1910
+ async waitUntilReady() {
1911
+ return this.readyPromise;
1912
+ }
1913
+ /**
1914
+ * Request mock data for a specific endpoint/method pair.
1915
+ */
1916
+ async requestMock(endpoint, method, options = {}) {
1917
+ if (this.closed) {
1918
+ throw new Error("BatchMockCollector has been closed");
1919
+ }
1920
+ await this.waitUntilReady();
1921
+ const requestId = `req-${++this.requestIdCounter}`;
1922
+ const request = {
1923
+ requestId,
1924
+ endpoint,
1925
+ method,
1926
+ body: options.body,
1927
+ headers: options.headers,
1928
+ metadata: options.metadata
1929
+ };
1930
+ let settleCompletion;
1931
+ const completion = new Promise((resolve) => {
1932
+ settleCompletion = resolve;
1933
+ });
1934
+ return new Promise((resolve, reject) => {
1935
+ const timeoutId = setTimeout(() => {
1936
+ this.rejectRequest(
1937
+ requestId,
1938
+ new Error(`Mock request timed out after ${this.timeout}ms: ${method} ${endpoint}`)
1939
+ );
1940
+ }, this.timeout);
1941
+ this.pendingRequests.set(requestId, {
1942
+ request,
1943
+ resolve: (mock) => {
1944
+ settleCompletion({ status: "fulfilled", value: void 0 });
1945
+ resolve(this.buildResolvedMock(mock));
1946
+ },
1947
+ reject: (error) => {
1948
+ settleCompletion({ status: "rejected", reason: error });
1949
+ reject(error);
1950
+ },
1951
+ timeoutId,
1952
+ completion
1953
+ });
1954
+ this.enqueueRequest(requestId);
1955
+ });
1956
+ }
1957
+ /**
1958
+ * Wait for all currently pending requests to settle.
1959
+ */
1960
+ async waitForPendingRequests() {
1961
+ if (!isEnabled()) {
1962
+ return;
1963
+ }
1964
+ const pendingCompletions = Array.from(this.pendingRequests.values()).map(
1965
+ (p) => p.completion
1966
+ );
1967
+ const results = await Promise.all(pendingCompletions);
1968
+ const rejected = results.find(
1969
+ (r) => r.status === "rejected"
1970
+ );
1971
+ if (rejected) {
1972
+ throw rejected.reason;
1973
+ }
1974
+ }
1975
+ /**
1976
+ * Close the connection and fail all pending requests.
1977
+ */
1978
+ async close(code) {
1979
+ this.logger.log(`[mock-mcp] [${this.runId.slice(0, 8)}] close() called with code: ${code ?? "(default)"}`);
1980
+ if (this.closed) {
1981
+ this.logger.log(`[mock-mcp] [${this.runId.slice(0, 8)}] Already closed, returning`);
1982
+ return;
1983
+ }
1984
+ this.closed = true;
1985
+ this.logger.log(`[mock-mcp] [${this.runId.slice(0, 8)}] Cleaning up timers...`);
1986
+ if (this.batchTimer) {
1987
+ clearTimeout(this.batchTimer);
1988
+ this.batchTimer = null;
1989
+ }
1990
+ if (this.heartbeatTimer) {
1991
+ clearInterval(this.heartbeatTimer);
1992
+ this.heartbeatTimer = null;
1993
+ }
1994
+ if (this.reconnectTimer) {
1995
+ clearTimeout(this.reconnectTimer);
1996
+ this.reconnectTimer = null;
1997
+ }
1998
+ const pendingCount = this.pendingRequests.size;
1999
+ const queuedCount = this.queuedRequestIds.size;
2000
+ this.logger.log(`[mock-mcp] [${this.runId.slice(0, 8)}] Pending requests: ${pendingCount}, Queued: ${queuedCount}`);
2001
+ this.queuedRequestIds.clear();
2002
+ const closePromise = new Promise((resolve) => {
2003
+ if (!this.ws) {
2004
+ resolve();
2005
+ return;
2006
+ }
2007
+ this.ws.once("close", () => resolve());
2008
+ });
2009
+ this.logger.log(`[mock-mcp] [${this.runId.slice(0, 8)}] Closing WebSocket...`);
2010
+ this.ws?.close(code);
2011
+ this.failAllPending(new Error("BatchMockCollector has been closed"));
2012
+ await closePromise;
2013
+ this.logger.log(`[mock-mcp] [${this.runId.slice(0, 8)}] \u2705 Connection closed`);
2014
+ }
2015
+ // ===========================================================================
2016
+ // Connection Management
2017
+ // ===========================================================================
2018
+ async initConnection({
2019
+ timeout = 1e4
2020
+ }) {
2021
+ const initStartTime = Date.now();
2022
+ this.logger.log(`[mock-mcp] [${this.runId.slice(0, 8)}] Initializing connection...`);
2023
+ try {
2024
+ this.logger.log(`[mock-mcp] [${this.runId.slice(0, 8)}] Ensuring daemon is running...`);
2025
+ const daemonStartTime = Date.now();
2026
+ this.registry = await ensureDaemonRunning({
2027
+ projectRoot: this.projectRoot,
2028
+ timeoutMs: timeout
2029
+ });
2030
+ const daemonElapsed = Date.now() - daemonStartTime;
2031
+ this.logger.log(`[mock-mcp] [${this.runId.slice(0, 8)}] Daemon ready (${daemonElapsed}ms)`);
2032
+ this.logger.log(`[mock-mcp] [${this.runId.slice(0, 8)}] Project ID: ${this.registry.projectId}`);
2033
+ this.logger.log(`[mock-mcp] [${this.runId.slice(0, 8)}] Daemon PID: ${this.registry.pid}`);
2034
+ this.logger.log(`[mock-mcp] [${this.runId.slice(0, 8)}] IPC Path: ${this.registry.ipcPath}`);
2035
+ this.logger.log(`[mock-mcp] [${this.runId.slice(0, 8)}] Creating WebSocket connection...`);
2036
+ const wsStartTime = Date.now();
2037
+ this.ws = await this.createWebSocket(this.registry.ipcPath);
2038
+ const wsElapsed = Date.now() - wsStartTime;
2039
+ this.logger.log(`[mock-mcp] [${this.runId.slice(0, 8)}] WebSocket created (${wsElapsed}ms)`);
2040
+ this.setupWebSocket();
2041
+ const totalElapsed = Date.now() - initStartTime;
2042
+ this.logger.log(`[mock-mcp] [${this.runId.slice(0, 8)}] Connection initialized (total: ${totalElapsed}ms)`);
2043
+ } catch (error) {
2044
+ const elapsed = Date.now() - initStartTime;
2045
+ this.logger.error(`[mock-mcp] [${this.runId.slice(0, 8)}] Connection init failed after ${elapsed}ms:`, error);
2046
+ this.readyReject?.(error instanceof Error ? error : new Error(String(error)));
2047
+ }
2048
+ }
2049
+ createWebSocket(ipcPath) {
2050
+ return new Promise((resolve, reject) => {
2051
+ this.logger.log(`[mock-mcp] [${this.runId.slice(0, 8)}] Creating WebSocket to IPC: ${ipcPath}`);
2052
+ const agent = new http__default.default.Agent({
2053
+ // @ts-expect-error: Node.js supports socketPath for Unix sockets
2054
+ socketPath: ipcPath
2055
+ });
2056
+ const ws = new WebSocket2__default.default("ws://localhost/test", {
2057
+ agent
2058
+ });
2059
+ ws.once("open", () => {
2060
+ this.logger.log(`[mock-mcp] [${this.runId.slice(0, 8)}] WebSocket opened`);
2061
+ resolve(ws);
2062
+ });
2063
+ ws.once("error", (err) => {
2064
+ this.logger.error(`[mock-mcp] [${this.runId.slice(0, 8)}] WebSocket connection error:`, err);
2065
+ reject(err);
2066
+ });
2067
+ });
2068
+ }
2069
+ setupWebSocket() {
2070
+ if (!this.ws || !this.registry) {
2071
+ this.logger.warn(`[mock-mcp] [${this.runId.slice(0, 8)}] setupWebSocket called but ws or registry is missing`);
2072
+ return;
2073
+ }
2074
+ this.logger.log(`[mock-mcp] [${this.runId.slice(0, 8)}] Setting up WebSocket event handlers...`);
2075
+ this.logger.log(`[mock-mcp] [${this.runId.slice(0, 8)}] Current readyState: ${this.ws.readyState}`);
2076
+ this.ws.on("message", (data) => this.handleMessage(data));
2077
+ this.ws.on("error", (error) => {
2078
+ this.logger.error(`[mock-mcp] [${this.runId.slice(0, 8)}] \u274C WebSocket ERROR:`, error);
2079
+ this.logger.error(`[mock-mcp] [${this.runId.slice(0, 8)}] authed: ${this.authed}`);
2080
+ this.logger.error(`[mock-mcp] [${this.runId.slice(0, 8)}] readyState: ${this.ws?.readyState}`);
2081
+ if (!this.authed) {
2082
+ this.readyReject?.(error instanceof Error ? error : new Error(String(error)));
2083
+ }
2084
+ this.failAllPending(error instanceof Error ? error : new Error(String(error)));
2085
+ });
2086
+ this.ws.on("close", (code, reason) => {
2087
+ this.logger.warn(`[mock-mcp] [${this.runId.slice(0, 8)}] \u{1F50C} WebSocket CLOSE`);
2088
+ this.logger.warn(`[mock-mcp] [${this.runId.slice(0, 8)}] code: ${code}`);
2089
+ this.logger.warn(`[mock-mcp] [${this.runId.slice(0, 8)}] reason: ${reason?.toString() || "(none)"}`);
2090
+ this.logger.warn(`[mock-mcp] [${this.runId.slice(0, 8)}] authed: ${this.authed}`);
2091
+ this.logger.warn(`[mock-mcp] [${this.runId.slice(0, 8)}] closed: ${this.closed}`);
2092
+ this.logger.warn(`[mock-mcp] [${this.runId.slice(0, 8)}] enableReconnect: ${this.enableReconnect}`);
2093
+ this.authed = false;
2094
+ this.stopHeartbeat();
2095
+ this.failAllPending(new Error(`Daemon connection closed (code: ${code})`));
2096
+ if (!this.closed && this.enableReconnect) {
2097
+ this.logger.log(`[mock-mcp] [${this.runId.slice(0, 8)}] Will attempt reconnect...`);
2098
+ this.scheduleReconnect();
2099
+ }
2100
+ });
2101
+ this.logger.log(`[mock-mcp] [${this.runId.slice(0, 8)}] WebSocket event handlers configured`);
2102
+ if (this.ws.readyState === WebSocket2__default.default.OPEN) {
2103
+ this.logger.log(`[mock-mcp] [${this.runId.slice(0, 8)}] \u{1F50C} WebSocket already OPEN - sending HELLO`);
2104
+ this.sendHello();
2105
+ }
2106
+ }
2107
+ sendHello() {
2108
+ if (!this.ws || !this.registry) {
2109
+ this.logger.warn(`[mock-mcp] [${this.runId.slice(0, 8)}] sendHello called but ws or registry is missing`);
2110
+ return;
2111
+ }
2112
+ this.logger.log(`[mock-mcp] [${this.runId.slice(0, 8)}] Sending HELLO handshake...`);
2113
+ this.logger.log(`[mock-mcp] [${this.runId.slice(0, 8)}] runId: ${this.runId}`);
2114
+ this.logger.log(`[mock-mcp] [${this.runId.slice(0, 8)}] pid: ${process.pid}`);
2115
+ this.logger.log(`[mock-mcp] [${this.runId.slice(0, 8)}] cwd: ${process.cwd()}`);
2116
+ if (this.testMeta) {
2117
+ this.logger.log(`[mock-mcp] [${this.runId.slice(0, 8)}] testFile: ${this.testMeta.testFile ?? "(none)"}`);
2118
+ this.logger.log(`[mock-mcp] [${this.runId.slice(0, 8)}] testName: ${this.testMeta.testName ?? "(none)"}`);
2119
+ }
2120
+ const hello = {
2121
+ type: HELLO_TEST,
2122
+ token: this.registry.token,
2123
+ runId: this.runId,
2124
+ pid: process.pid,
2125
+ cwd: process.cwd(),
2126
+ testMeta: this.testMeta
2127
+ };
2128
+ this.ws.send(JSON.stringify(hello));
2129
+ this.logger.log(`[mock-mcp] [${this.runId.slice(0, 8)}] HELLO sent, waiting for HELLO_ACK...`);
2130
+ }
2131
+ handleMessage(data) {
2132
+ let msg;
2133
+ try {
2134
+ msg = JSON.parse(data.toString());
2135
+ } catch {
2136
+ this.logger.error(`[mock-mcp] [${this.runId.slice(0, 8)}] Failed to parse server message`);
2137
+ return;
2138
+ }
2139
+ const msgType = msg?.type;
2140
+ if (this.isHelloAck(msg)) {
2141
+ this.authed = true;
2142
+ this.logger.log(`[mock-mcp] [${this.runId.slice(0, 8)}] \u2705 Received HELLO_ACK - Authenticated!`);
2143
+ this.logger.log(`[mock-mcp] [${this.runId.slice(0, 8)}] Connection is now READY`);
2144
+ this.readyResolve?.();
2145
+ this.startHeartbeat();
2146
+ return;
2147
+ }
2148
+ if (this.isBatchMockResult(msg)) {
2149
+ this.logger.log(
2150
+ `[mock-mcp] [${this.runId.slice(0, 8)}] \u{1F4E6} Received BATCH_MOCK_RESULT`
2151
+ );
2152
+ this.logger.log(
2153
+ `[mock-mcp] [${this.runId.slice(0, 8)}] batchId: ${msg.batchId}`
2154
+ );
2155
+ this.logger.log(
2156
+ `[mock-mcp] [${this.runId.slice(0, 8)}] mocks count: ${msg.mocks.length}`
2157
+ );
2158
+ for (const mock of msg.mocks) {
2159
+ this.logger.log(
2160
+ `[mock-mcp] [${this.runId.slice(0, 8)}] - ${mock.requestId}: status=${mock.status ?? 200}`
2161
+ );
2162
+ this.resolveRequest(mock);
2163
+ }
2164
+ return;
2165
+ }
2166
+ if (msgType === "HEARTBEAT_ACK") {
2167
+ return;
2168
+ }
2169
+ this.logger.warn(`[mock-mcp] [${this.runId.slice(0, 8)}] Received unknown message type: ${msgType}`);
2170
+ }
2171
+ isHelloAck(msg) {
2172
+ return msg !== null && typeof msg === "object" && msg.type === HELLO_ACK;
2173
+ }
2174
+ isBatchMockResult(msg) {
2175
+ return msg !== null && typeof msg === "object" && msg.type === BATCH_MOCK_RESULT && Array.isArray(msg.mocks);
2176
+ }
2177
+ // ===========================================================================
2178
+ // Request Management
2179
+ // ===========================================================================
2180
+ resolveRequest(mock) {
2181
+ const pending = this.pendingRequests.get(mock.requestId);
2182
+ if (!pending) {
2183
+ this.logger.warn(`Received mock for unknown request: ${mock.requestId}`);
2184
+ return;
2185
+ }
2186
+ clearTimeout(pending.timeoutId);
2187
+ this.pendingRequests.delete(mock.requestId);
2188
+ const resolve = () => pending.resolve(mock);
2189
+ if (mock.delayMs && mock.delayMs > 0) {
2190
+ setTimeout(resolve, mock.delayMs);
2191
+ } else {
2192
+ resolve();
2193
+ }
2194
+ }
2195
+ rejectRequest(requestId, error) {
2196
+ const pending = this.pendingRequests.get(requestId);
2197
+ if (!pending) return;
2198
+ clearTimeout(pending.timeoutId);
2199
+ this.pendingRequests.delete(requestId);
2200
+ pending.reject(error);
2201
+ }
2202
+ failAllPending(error) {
2203
+ for (const requestId of Array.from(this.pendingRequests.keys())) {
2204
+ this.rejectRequest(requestId, error);
2205
+ }
2206
+ }
2207
+ // ===========================================================================
2208
+ // Batching
2209
+ // ===========================================================================
2210
+ enqueueRequest(requestId) {
2211
+ this.queuedRequestIds.add(requestId);
2212
+ if (this.batchTimer) {
2213
+ return;
2214
+ }
2215
+ this.batchTimer = setTimeout(() => {
2216
+ this.batchTimer = null;
2217
+ this.flushQueue();
2218
+ }, this.batchDebounceMs);
2219
+ }
2220
+ flushQueue() {
2221
+ const queuedIds = Array.from(this.queuedRequestIds);
2222
+ this.queuedRequestIds.clear();
2223
+ if (queuedIds.length === 0) {
2224
+ return;
2225
+ }
2226
+ for (let i = 0; i < queuedIds.length; i += this.maxBatchSize) {
2227
+ const chunkIds = queuedIds.slice(i, i + this.maxBatchSize);
2228
+ const requests = [];
2229
+ for (const id of chunkIds) {
2230
+ const pending = this.pendingRequests.get(id);
2231
+ if (pending) {
2232
+ requests.push(pending.request);
2233
+ }
2234
+ }
2235
+ if (requests.length > 0) {
2236
+ this.sendBatch(requests);
2237
+ }
2238
+ }
2239
+ }
2240
+ sendBatch(requests) {
2241
+ if (!this.ws || this.ws.readyState !== WebSocket2__default.default.OPEN) {
2242
+ this.logger.error(`[mock-mcp] [${this.runId.slice(0, 8)}] Cannot send batch - WebSocket not open`);
2243
+ this.logger.error(`[mock-mcp] [${this.runId.slice(0, 8)}] ws exists: ${!!this.ws}`);
2244
+ this.logger.error(`[mock-mcp] [${this.runId.slice(0, 8)}] readyState: ${this.ws?.readyState}`);
2245
+ const error = new Error("WebSocket is not open");
2246
+ for (const req of requests) {
2247
+ this.rejectRequest(req.requestId, error);
2248
+ }
2249
+ return;
2250
+ }
2251
+ const payload = {
2252
+ type: BATCH_MOCK_REQUEST,
2253
+ runId: this.runId,
2254
+ requests
2255
+ };
2256
+ this.logger.log(`[mock-mcp] [${this.runId.slice(0, 8)}] \u{1F4E4} Sending BATCH_MOCK_REQUEST`);
2257
+ this.logger.log(`[mock-mcp] [${this.runId.slice(0, 8)}] requests: ${requests.length}`);
2258
+ for (const req of requests) {
2259
+ this.logger.log(`[mock-mcp] [${this.runId.slice(0, 8)}] - ${req.requestId}: ${req.method} ${req.endpoint}`);
2260
+ }
2261
+ this.ws.send(JSON.stringify(payload));
2262
+ }
2263
+ // ===========================================================================
2264
+ // Heartbeat
2265
+ // ===========================================================================
2266
+ startHeartbeat() {
2267
+ if (this.heartbeatIntervalMs <= 0 || this.heartbeatTimer) {
2268
+ return;
2269
+ }
2270
+ let lastPong = Date.now();
2271
+ this.ws?.on("pong", () => {
2272
+ lastPong = Date.now();
2273
+ });
2274
+ this.heartbeatTimer = setInterval(() => {
2275
+ if (!this.ws || this.ws.readyState !== WebSocket2__default.default.OPEN) {
2276
+ return;
2277
+ }
2278
+ const now = Date.now();
2279
+ if (now - lastPong > this.heartbeatIntervalMs * 2) {
2280
+ this.logger.warn("Heartbeat missed; closing socket to trigger reconnect...");
2281
+ this.ws.close();
2282
+ return;
2283
+ }
2284
+ this.ws.ping();
2285
+ }, this.heartbeatIntervalMs);
2286
+ this.heartbeatTimer.unref?.();
2287
+ }
2288
+ stopHeartbeat() {
2289
+ if (this.heartbeatTimer) {
2290
+ clearInterval(this.heartbeatTimer);
2291
+ this.heartbeatTimer = null;
2292
+ }
2293
+ }
2294
+ // ===========================================================================
2295
+ // Reconnection
2296
+ // ===========================================================================
2297
+ scheduleReconnect() {
2298
+ if (this.reconnectTimer) {
2299
+ this.logger.log(`[mock-mcp] [${this.runId.slice(0, 8)}] Reconnect already scheduled, skipping`);
2300
+ return;
2301
+ }
2302
+ if (this.closed) {
2303
+ this.logger.log(`[mock-mcp] [${this.runId.slice(0, 8)}] Client is closed, not reconnecting`);
2304
+ return;
2305
+ }
2306
+ this.logger.log(`[mock-mcp] [${this.runId.slice(0, 8)}] Scheduling reconnect in 1000ms...`);
2307
+ this.reconnectTimer = setTimeout(async () => {
2308
+ this.reconnectTimer = null;
2309
+ this.logger.warn(`[mock-mcp] [${this.runId.slice(0, 8)}] \u{1F504} Attempting reconnect to daemon...`);
2310
+ this.stopHeartbeat();
2311
+ this.resetReadyPromise();
2312
+ this.authed = false;
2313
+ const reconnectStartTime = Date.now();
2314
+ try {
2315
+ this.logger.log(`[mock-mcp] [${this.runId.slice(0, 8)}] Re-discovering daemon...`);
2316
+ this.registry = await ensureDaemonRunning({
2317
+ projectRoot: this.projectRoot
2318
+ });
2319
+ this.logger.log(`[mock-mcp] [${this.runId.slice(0, 8)}] Daemon found, creating new WebSocket...`);
2320
+ this.ws = await this.createWebSocket(this.registry.ipcPath);
2321
+ this.setupWebSocket();
2322
+ const elapsed = Date.now() - reconnectStartTime;
2323
+ this.logger.log(`[mock-mcp] [${this.runId.slice(0, 8)}] \u2705 Reconnect successful (${elapsed}ms)`);
2324
+ } catch (error) {
2325
+ const elapsed = Date.now() - reconnectStartTime;
2326
+ this.logger.error(`[mock-mcp] [${this.runId.slice(0, 8)}] \u274C Reconnection failed after ${elapsed}ms:`, error);
2327
+ this.logger.log(`[mock-mcp] [${this.runId.slice(0, 8)}] Will retry reconnect...`);
2328
+ this.scheduleReconnect();
2329
+ }
2330
+ }, 1e3);
2331
+ this.reconnectTimer.unref?.();
2332
+ }
2333
+ // ===========================================================================
2334
+ // Utilities
2335
+ // ===========================================================================
2336
+ resetReadyPromise() {
2337
+ this.readyPromise = new Promise((resolve, reject) => {
2338
+ this.readyResolve = resolve;
2339
+ this.readyReject = reject;
2340
+ });
2341
+ }
2342
+ buildResolvedMock(mock) {
2343
+ return {
2344
+ requestId: mock.requestId,
2345
+ data: mock.data,
2346
+ status: mock.status,
2347
+ headers: mock.headers,
2348
+ delayMs: mock.delayMs
2349
+ };
2350
+ }
2351
+ // ===========================================================================
2352
+ // Public Getters
2353
+ // ===========================================================================
2354
+ /**
2355
+ * Get the run ID for this collector instance.
2356
+ */
2357
+ getRunId() {
2358
+ return this.runId;
2359
+ }
2360
+ /**
2361
+ * Get the daemon registry information (after connection).
2362
+ */
2363
+ getRegistry() {
2364
+ return this.registry;
2365
+ }
2366
+ };
2367
+
2368
+ // src/client/connect.ts
2369
+ var DisabledMockClient = class {
2370
+ runId = "disabled";
2371
+ async waitUntilReady() {
2372
+ return;
2373
+ }
2374
+ async requestMock() {
2375
+ throw new Error(
2376
+ "[mock-mcp] MOCK_MCP is not enabled. Set MOCK_MCP=1 to enable mock generation."
2377
+ );
2378
+ }
2379
+ async waitForPendingRequests() {
2380
+ return;
2381
+ }
2382
+ async close() {
2383
+ return;
2384
+ }
2385
+ getRunId() {
2386
+ return this.runId;
2387
+ }
2388
+ };
2389
+ var connect = async (options) => {
2390
+ const logger = options?.logger ?? console;
2391
+ const startTime = Date.now();
2392
+ logger.log("[mock-mcp] connect() called");
2393
+ logger.log(`[mock-mcp] PID: ${process.pid}`);
2394
+ logger.log(`[mock-mcp] CWD: ${process.cwd()}`);
2395
+ logger.log(`[mock-mcp] MOCK_MCP env: ${process.env.MOCK_MCP ?? "(not set)"}`);
2396
+ if (!isEnabled()) {
2397
+ logger.log("[mock-mcp] Skipping (set MOCK_MCP=1 to enable)");
2398
+ return new DisabledMockClient();
2399
+ }
2400
+ logger.log("[mock-mcp] Creating BatchMockCollector...");
2401
+ const collector = new BatchMockCollector(options ?? {});
2402
+ const runId = collector.getRunId();
2403
+ logger.log(`[mock-mcp] Run ID: ${runId}`);
2404
+ logger.log("[mock-mcp] Waiting for connection to be ready...");
2405
+ try {
2406
+ await collector.waitUntilReady();
2407
+ const elapsed = Date.now() - startTime;
2408
+ const registry = collector.getRegistry();
2409
+ logger.log("[mock-mcp] ========== Connection Established ==========");
2410
+ logger.log(`[mock-mcp] Run ID: ${runId}`);
2411
+ logger.log(`[mock-mcp] Daemon PID: ${registry?.pid ?? "unknown"}`);
2412
+ logger.log(`[mock-mcp] Project ID: ${registry?.projectId ?? "unknown"}`);
2413
+ logger.log(`[mock-mcp] IPC Path: ${registry?.ipcPath ?? "unknown"}`);
2414
+ logger.log(`[mock-mcp] Connection time: ${elapsed}ms`);
2415
+ logger.log("[mock-mcp] ==============================================");
2416
+ return collector;
2417
+ } catch (error) {
2418
+ const elapsed = Date.now() - startTime;
2419
+ logger.error("[mock-mcp] ========== Connection Failed ==========");
2420
+ logger.error(`[mock-mcp] Run ID: ${runId}`);
2421
+ logger.error(`[mock-mcp] Error: ${error instanceof Error ? error.message : String(error)}`);
2422
+ logger.error(`[mock-mcp] Elapsed time: ${elapsed}ms`);
2423
+ logger.error("[mock-mcp] =========================================");
2424
+ throw error;
2425
+ }
2426
+ };
2427
+
2428
+ // src/index.ts
2429
+ init_discovery();
2430
+ async function runCli() {
2431
+ const args = process2__default.default.argv.slice(2);
2432
+ const command = args[0] ?? "adapter";
2433
+ switch (command) {
2434
+ case "adapter":
2435
+ await runAdapterCommand(args.slice(1));
2436
+ break;
2437
+ case "daemon":
2438
+ await runDaemonCommand(args.slice(1));
2439
+ break;
2440
+ case "status":
2441
+ await runStatusCommand(args.slice(1));
2442
+ break;
2443
+ case "stop":
2444
+ await runStopCommand(args.slice(1));
2445
+ break;
2446
+ case "help":
2447
+ case "--help":
2448
+ case "-h":
2449
+ printHelp();
2450
+ break;
2451
+ case "version":
2452
+ case "--version":
2453
+ case "-v":
2454
+ await printVersion();
2455
+ break;
2456
+ default:
2457
+ await runAdapterCommand();
2458
+ }
2459
+ }
2460
+ async function runAdapterCommand(_args) {
2461
+ const { runAdapter: runAdapter2 } = await Promise.resolve().then(() => (init_adapter(), adapter_exports));
2462
+ await runAdapter2();
2463
+ }
2464
+ async function runDaemonCommand(args) {
2465
+ const { MockMcpDaemon: MockMcpDaemon2 } = await Promise.resolve().then(() => (init_daemon(), daemon_exports));
2466
+ const { resolveProjectRoot: resolveProjectRoot2 } = await Promise.resolve().then(() => (init_discovery(), discovery_exports));
2467
+ let projectRoot;
2468
+ let token;
2469
+ for (let i = 0; i < args.length; i++) {
2470
+ const arg = args[i];
2471
+ if (arg === "--project-root" && args[i + 1]) {
2472
+ projectRoot = args[i + 1];
2473
+ i++;
2474
+ } else if (arg === "--token" && args[i + 1]) {
2475
+ token = args[i + 1];
2476
+ i++;
2477
+ }
2478
+ }
2479
+ projectRoot = projectRoot ?? resolveProjectRoot2();
2480
+ const cacheDir = process2__default.default.env.MOCK_MCP_CACHE_DIR || void 0;
2481
+ if (!token) {
2482
+ console.error("Error: --token is required for daemon mode");
2483
+ process2__default.default.exitCode = 1;
2484
+ return;
2485
+ }
2486
+ const version = await getVersion();
2487
+ const daemon = new MockMcpDaemon2({
2488
+ projectRoot,
2489
+ token,
2490
+ version,
2491
+ cacheDir
2492
+ });
2493
+ await daemon.start();
2494
+ const shutdown = async (signal) => {
2495
+ console.error(`
2496
+ ${signal} received, shutting down...`);
2497
+ await daemon.stop();
2498
+ process2__default.default.exit(0);
2499
+ };
2500
+ process2__default.default.on("SIGINT", () => shutdown("SIGINT"));
2501
+ process2__default.default.on("SIGTERM", () => shutdown("SIGTERM"));
2502
+ }
2503
+ async function runStatusCommand(_args) {
2504
+ const {
2505
+ resolveProjectRoot: resolveProjectRoot2,
2506
+ computeProjectId: computeProjectId2,
2507
+ getPaths: getPaths2,
2508
+ readRegistry: readRegistry3
2509
+ } = await Promise.resolve().then(() => (init_discovery(), discovery_exports));
2510
+ const projectRoot = resolveProjectRoot2();
2511
+ const projectId = computeProjectId2(projectRoot);
2512
+ const { registryPath, ipcPath } = getPaths2(projectId);
2513
+ console.log(`Project Root: ${projectRoot}`);
2514
+ console.log(`Project ID: ${projectId}`);
2515
+ console.log(`IPC Path: ${ipcPath}`);
2516
+ console.log("");
2517
+ const registry = await readRegistry3(registryPath);
2518
+ if (!registry) {
2519
+ console.log("\u274C Daemon is not running (no registry found)");
2520
+ return;
2521
+ }
2522
+ console.log(`Registry PID: ${registry.pid}`);
2523
+ console.log(`Started At: ${registry.startedAt}`);
2524
+ console.log("");
2525
+ try {
2526
+ const status = await getDaemonStatus(ipcPath, registry.token);
2527
+ console.log("\u2705 Daemon is running\n");
2528
+ console.log(`Version: ${status.version}`);
2529
+ console.log(`Uptime: ${Math.round(status.uptime / 1e3)}s`);
2530
+ console.log(`Active Runs: ${status.runs}`);
2531
+ console.log(`Pending Batches: ${status.pending}`);
2532
+ console.log(`Claimed Batches: ${status.claimed}`);
2533
+ } catch (error) {
2534
+ console.log("\u274C Daemon is not responding");
2535
+ console.log(` ${error instanceof Error ? error.message : String(error)}`);
2536
+ }
2537
+ }
2538
+ async function getDaemonStatus(ipcPath, token) {
2539
+ return new Promise((resolve, reject) => {
2540
+ const payload = JSON.stringify({
2541
+ jsonrpc: "2.0",
2542
+ id: "status",
2543
+ method: "getStatus",
2544
+ params: {}
2545
+ });
2546
+ const req = http__default.default.request(
2547
+ {
2548
+ method: "POST",
2549
+ socketPath: ipcPath,
2550
+ path: "/control",
2551
+ headers: {
2552
+ "content-type": "application/json",
2553
+ "x-mock-mcp-token": token
2554
+ },
2555
+ timeout: 5e3
2556
+ },
2557
+ (res) => {
2558
+ let buf = "";
2559
+ res.on("data", (c) => buf += c);
2560
+ res.on("end", () => {
2561
+ try {
2562
+ const result = JSON.parse(buf);
2563
+ if (result.error) {
2564
+ reject(new Error(result.error.message));
2565
+ } else {
2566
+ resolve(result.result);
2567
+ }
2568
+ } catch (e) {
2569
+ reject(e);
2570
+ }
2571
+ });
2572
+ }
2573
+ );
2574
+ req.on("error", reject);
2575
+ req.on("timeout", () => {
2576
+ req.destroy();
2577
+ reject(new Error("Request timeout"));
2578
+ });
2579
+ req.end(payload);
2580
+ });
2581
+ }
2582
+ async function runStopCommand(_args) {
2583
+ const {
2584
+ resolveProjectRoot: resolveProjectRoot2,
2585
+ computeProjectId: computeProjectId2,
2586
+ getPaths: getPaths2,
2587
+ readRegistry: readRegistry3
2588
+ } = await Promise.resolve().then(() => (init_discovery(), discovery_exports));
2589
+ const projectRoot = resolveProjectRoot2();
2590
+ const projectId = computeProjectId2(projectRoot);
2591
+ const { registryPath, ipcPath } = getPaths2(projectId);
2592
+ const registry = await readRegistry3(registryPath);
2593
+ if (!registry) {
2594
+ console.log("Daemon is not running.");
2595
+ return;
2596
+ }
2597
+ try {
2598
+ process2__default.default.kill(registry.pid, "SIGTERM");
2599
+ console.log(`Sent SIGTERM to daemon (PID: ${registry.pid})`);
2600
+ await new Promise((r) => setTimeout(r, 1e3));
2601
+ try {
2602
+ process2__default.default.kill(registry.pid, 0);
2603
+ console.log("Daemon is still running, sending SIGKILL...");
2604
+ process2__default.default.kill(registry.pid, "SIGKILL");
2605
+ } catch {
2606
+ }
2607
+ } catch (error) {
2608
+ console.log(`Daemon process (PID: ${registry.pid}) is not running.`);
2609
+ }
2610
+ try {
2611
+ await fs__default.default.rm(registryPath);
2612
+ console.log("Registry cleaned up.");
2613
+ } catch {
2614
+ }
2615
+ if (process2__default.default.platform !== "win32") {
2616
+ try {
2617
+ await fs__default.default.rm(ipcPath);
2618
+ console.log("Socket cleaned up.");
2619
+ } catch {
2620
+ }
2621
+ }
2622
+ console.log("Done.");
2623
+ }
2624
+ function printHelp() {
2625
+ console.log(`
2626
+ mock-mcp - AI-assisted mock generation for integration tests
2627
+
2628
+ USAGE:
2629
+ mock-mcp [command] [options]
2630
+
2631
+ COMMANDS:
2632
+ adapter Start the MCP adapter (default)
2633
+ This is what you configure in your MCP client.
2634
+ The adapter automatically discovers ALL active daemons
2635
+ across all projects - no configuration needed!
2636
+
2637
+ daemon Start the daemon process
2638
+ Usually auto-started by adapter/test code.
2639
+
2640
+ status Show daemon status for current project
2641
+
2642
+ stop Stop the daemon for current project
2643
+
2644
+ help Show this help message
2645
+
2646
+ version Show version
2647
+
2648
+ EXAMPLES:
2649
+ # In your MCP client configuration (Cursor, Claude Desktop, etc.):
2650
+ # Simple configuration - works across all projects automatically!
2651
+ {
2652
+ "mcpServers": {
2653
+ "mock-mcp": {
2654
+ "command": "npx",
2655
+ "args": ["-y", "mock-mcp", "adapter"]
2656
+ }
2657
+ }
2658
+ }
2659
+
2660
+ # Check daemon status:
2661
+ mock-mcp status
2662
+
2663
+ # Stop daemon:
2664
+ mock-mcp stop
2665
+
2666
+ HOW IT WORKS:
2667
+ 1. Run your tests with MOCK_MCP=1 to start a daemon and make mock requests
2668
+ 2. The MCP adapter discovers all active daemons automatically
2669
+ 3. Use list_runs/claim_next_batch tools from any MCP client to provide mocks
2670
+
2671
+ ENVIRONMENT:
2672
+ MOCK_MCP=1 Enable mock generation in test code
2673
+ MOCK_MCP_CACHE_DIR Override cache directory for daemon files
2674
+
2675
+ For more information, visit: https://github.com/mcpland/mock-mcp
2676
+ `);
2677
+ }
2678
+ async function printVersion() {
2679
+ const version = await getVersion();
2680
+ console.log(`mock-mcp v${version}`);
2681
+ }
2682
+ async function getVersion() {
2683
+ return "0.5.0";
2684
+ }
2685
+ var isCliExecution = (() => {
2686
+ if (typeof process2__default.default === "undefined" || !process2__default.default.argv?.[1]) {
2687
+ return false;
2688
+ }
2689
+ const scriptPath = fssync.realpathSync(process2__default.default.argv[1]);
2690
+ return __importMetaUrl === url.pathToFileURL(scriptPath).href;
2691
+ })();
2692
+ if (isCliExecution) {
2693
+ runCli().catch((error) => {
2694
+ console.error("Error:", error instanceof Error ? error.message : error);
2695
+ process2__default.default.exitCode = 1;
2696
+ });
2697
+ }
2698
+
2699
+ exports.BatchMockCollector = BatchMockCollector;
2700
+ exports.DaemonClient = DaemonClient;
2701
+ exports.cleanupGlobalIndex = cleanupGlobalIndex;
2702
+ exports.computeProjectId = computeProjectId;
2703
+ exports.connect = connect;
2704
+ exports.discoverAllDaemons = discoverAllDaemons;
2705
+ exports.ensureDaemonRunning = ensureDaemonRunning;
2706
+ exports.readGlobalIndex = readGlobalIndex;
2707
+ exports.resolveProjectRoot = resolveProjectRoot;
2708
+ exports.runAdapter = runAdapter;