mock-mcp 0.3.0 → 0.5.0

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