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