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
@@ -0,0 +1,672 @@
1
+ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
2
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
3
+ import { ListToolsRequestSchema, CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js';
4
+ import crypto2 from 'crypto';
5
+ import http from 'http';
6
+ import fs from 'fs/promises';
7
+ import fssync from 'fs';
8
+ import os from 'os';
9
+ import path from 'path';
10
+ import { spawn } from 'child_process';
11
+ import { fileURLToPath, pathToFileURL } from 'url';
12
+ import { createRequire } from 'module';
13
+
14
+ // src/adapter/adapter.ts
15
+ var DaemonClient = class {
16
+ constructor(ipcPath, token, adapterId) {
17
+ this.ipcPath = ipcPath;
18
+ this.token = token;
19
+ this.adapterId = adapterId;
20
+ }
21
+ // ===========================================================================
22
+ // RPC Methods
23
+ // ===========================================================================
24
+ async getStatus() {
25
+ return this.rpc("getStatus", {});
26
+ }
27
+ async listRuns() {
28
+ return this.rpc("listRuns", {});
29
+ }
30
+ async claimNextBatch(args) {
31
+ return this.rpc("claimNextBatch", {
32
+ adapterId: this.adapterId,
33
+ runId: args.runId,
34
+ leaseMs: args.leaseMs
35
+ });
36
+ }
37
+ async provideBatch(args) {
38
+ return this.rpc("provideBatch", {
39
+ adapterId: this.adapterId,
40
+ batchId: args.batchId,
41
+ claimToken: args.claimToken,
42
+ mocks: args.mocks
43
+ });
44
+ }
45
+ async releaseBatch(args) {
46
+ return this.rpc("releaseBatch", {
47
+ adapterId: this.adapterId,
48
+ batchId: args.batchId,
49
+ claimToken: args.claimToken,
50
+ reason: args.reason
51
+ });
52
+ }
53
+ async getBatch(batchId) {
54
+ return this.rpc("getBatch", { batchId });
55
+ }
56
+ // ===========================================================================
57
+ // Internal
58
+ // ===========================================================================
59
+ rpc(method, params) {
60
+ const payload = {
61
+ jsonrpc: "2.0",
62
+ id: crypto2.randomUUID(),
63
+ method,
64
+ params
65
+ };
66
+ return new Promise((resolve, reject) => {
67
+ const req = http.request(
68
+ {
69
+ method: "POST",
70
+ socketPath: this.ipcPath,
71
+ path: "/control",
72
+ headers: {
73
+ "content-type": "application/json",
74
+ "x-mock-mcp-token": this.token
75
+ },
76
+ timeout: 3e4
77
+ },
78
+ (res) => {
79
+ let buf = "";
80
+ res.on("data", (chunk) => buf += chunk);
81
+ res.on("end", () => {
82
+ try {
83
+ const response = JSON.parse(buf);
84
+ if (response.error) {
85
+ reject(new Error(response.error.message));
86
+ } else {
87
+ resolve(response.result);
88
+ }
89
+ } catch (e) {
90
+ reject(e);
91
+ }
92
+ });
93
+ }
94
+ );
95
+ req.on("error", (err) => {
96
+ reject(new Error(`Daemon connection failed: ${err.message}`));
97
+ });
98
+ req.on("timeout", () => {
99
+ req.destroy();
100
+ reject(new Error("Daemon request timeout"));
101
+ });
102
+ req.end(JSON.stringify(payload));
103
+ });
104
+ }
105
+ };
106
+ function debugLog(_msg) {
107
+ }
108
+ var __curDirname = (() => {
109
+ try {
110
+ const metaUrl = import.meta.url;
111
+ if (metaUrl && typeof metaUrl === "string" && metaUrl.startsWith("file://")) {
112
+ return path.dirname(fileURLToPath(metaUrl));
113
+ }
114
+ } catch {
115
+ }
116
+ return process.cwd();
117
+ })();
118
+ function resolveProjectRoot(startDir = process.cwd()) {
119
+ let current = path.resolve(startDir);
120
+ const root = path.parse(current).root;
121
+ while (current !== root) {
122
+ const gitPath = path.join(current, ".git");
123
+ try {
124
+ const stat = fssync.statSync(gitPath);
125
+ if (stat.isDirectory() || stat.isFile()) {
126
+ return current;
127
+ }
128
+ } catch {
129
+ }
130
+ const pkgPath = path.join(current, "package.json");
131
+ try {
132
+ fssync.accessSync(pkgPath, fssync.constants.F_OK);
133
+ return current;
134
+ } catch {
135
+ }
136
+ current = path.dirname(current);
137
+ }
138
+ return path.resolve(startDir);
139
+ }
140
+ function computeProjectId(projectRoot) {
141
+ const real = fssync.realpathSync(projectRoot);
142
+ return crypto2.createHash("sha256").update(real).digest("hex").slice(0, 16);
143
+ }
144
+ function getCacheDir(override) {
145
+ if (override) {
146
+ return override;
147
+ }
148
+ const envCacheDir = process.env.MOCK_MCP_CACHE_DIR;
149
+ if (envCacheDir) {
150
+ return envCacheDir;
151
+ }
152
+ const xdg = process.env.XDG_CACHE_HOME;
153
+ if (xdg) {
154
+ return xdg;
155
+ }
156
+ if (process.platform === "win32" && process.env.LOCALAPPDATA) {
157
+ return process.env.LOCALAPPDATA;
158
+ }
159
+ const home = os.homedir();
160
+ if (home) {
161
+ return path.join(home, ".cache");
162
+ }
163
+ return os.tmpdir();
164
+ }
165
+ function getPaths(projectId, cacheDir) {
166
+ const base = path.join(getCacheDir(cacheDir), "mock-mcp");
167
+ const registryPath = path.join(base, `${projectId}.json`);
168
+ const lockPath = path.join(base, `${projectId}.lock`);
169
+ const ipcPath = process.platform === "win32" ? `\\\\.\\pipe\\mock-mcp-${projectId}` : path.join(base, `${projectId}.sock`);
170
+ return { base, registryPath, lockPath, ipcPath };
171
+ }
172
+ async function readRegistry(registryPath) {
173
+ try {
174
+ const txt = await fs.readFile(registryPath, "utf-8");
175
+ return JSON.parse(txt);
176
+ } catch (error) {
177
+ debugLog(`readRegistry error for ${registryPath}: ${error instanceof Error ? error.message : String(error)}`);
178
+ return null;
179
+ }
180
+ }
181
+ async function healthCheck(ipcPath, timeoutMs = 2e3) {
182
+ return new Promise((resolve) => {
183
+ const req = http.request(
184
+ {
185
+ method: "GET",
186
+ socketPath: ipcPath,
187
+ path: "/health",
188
+ timeout: timeoutMs
189
+ },
190
+ (res) => {
191
+ resolve(res.statusCode === 200);
192
+ }
193
+ );
194
+ req.on("error", () => resolve(false));
195
+ req.on("timeout", () => {
196
+ req.destroy();
197
+ resolve(false);
198
+ });
199
+ req.end();
200
+ });
201
+ }
202
+ async function tryAcquireLock(lockPath) {
203
+ try {
204
+ const fh = await fs.open(lockPath, "wx");
205
+ await fh.write(`${process.pid}
206
+ `);
207
+ return fh;
208
+ } catch {
209
+ return null;
210
+ }
211
+ }
212
+ async function releaseLock(lockPath, fh) {
213
+ await fh.close();
214
+ await fs.rm(lockPath).catch(() => {
215
+ });
216
+ }
217
+ function randomToken() {
218
+ return crypto2.randomBytes(24).toString("base64url");
219
+ }
220
+ function getDaemonEntryPath() {
221
+ try {
222
+ const cwdRequire = createRequire(pathToFileURL(path.join(process.cwd(), "index.js")).href);
223
+ const resolved = cwdRequire.resolve("mock-mcp");
224
+ const distDir = path.dirname(resolved);
225
+ const daemonEntry = path.join(distDir, "index.js");
226
+ if (fssync.existsSync(daemonEntry)) {
227
+ return daemonEntry;
228
+ }
229
+ } catch {
230
+ }
231
+ try {
232
+ const packageRoot = resolveProjectRoot(__curDirname);
233
+ const distPath = path.join(packageRoot, "dist", "index.js");
234
+ if (fssync.existsSync(distPath)) {
235
+ return distPath;
236
+ }
237
+ } catch {
238
+ }
239
+ if (process.argv[1]) {
240
+ return process.argv[1];
241
+ }
242
+ return path.join(process.cwd(), "dist", "index.js");
243
+ }
244
+ async function ensureDaemonRunning(opts = {}) {
245
+ const projectRoot = opts.projectRoot ?? resolveProjectRoot();
246
+ const projectId = computeProjectId(projectRoot);
247
+ const { base, registryPath, lockPath, ipcPath } = getPaths(
248
+ projectId,
249
+ opts.cacheDir
250
+ );
251
+ const timeoutMs = opts.timeoutMs ?? 1e4;
252
+ await fs.mkdir(base, { recursive: true });
253
+ const existing = await readRegistry(registryPath);
254
+ debugLog(`Registry read result: ${existing ? "Found (PID " + existing.pid + ")" : "Null"}`);
255
+ if (existing) {
256
+ let healthy = false;
257
+ for (let i = 0; i < 3; i++) {
258
+ debugLog(`Checking health attempt ${i + 1}/3 on ${existing.ipcPath}`);
259
+ healthy = await healthCheck(existing.ipcPath);
260
+ if (healthy) break;
261
+ await new Promise((r) => setTimeout(r, 200));
262
+ }
263
+ if (healthy) {
264
+ return existing;
265
+ }
266
+ }
267
+ if (process.platform !== "win32") {
268
+ try {
269
+ await fs.rm(ipcPath);
270
+ } catch {
271
+ }
272
+ }
273
+ const lock = await tryAcquireLock(lockPath);
274
+ if (lock) {
275
+ try {
276
+ const recheckReg = await readRegistry(registryPath);
277
+ if (recheckReg && await healthCheck(recheckReg.ipcPath)) {
278
+ return recheckReg;
279
+ }
280
+ const token = randomToken();
281
+ const daemonEntry = getDaemonEntryPath();
282
+ const child = spawn(
283
+ process.execPath,
284
+ [daemonEntry, "daemon", "--project-root", projectRoot, "--token", token],
285
+ {
286
+ detached: true,
287
+ stdio: ["ignore", "pipe", "pipe"],
288
+ env: {
289
+ ...process.env,
290
+ MOCK_MCP_CACHE_DIR: opts.cacheDir ?? ""
291
+ }
292
+ }
293
+ );
294
+ let daemonStderr = "";
295
+ let daemonStdout = "";
296
+ child.stdout?.on("data", (data) => {
297
+ const str = data.toString();
298
+ debugLog(`Daemon stdout: ${str}`);
299
+ });
300
+ child.stderr?.on("data", (data) => {
301
+ daemonStderr += data.toString();
302
+ debugLog(`Daemon stderr: ${data.toString()}`);
303
+ });
304
+ child.on("error", (err) => {
305
+ console.error(`[mock-mcp] Daemon spawn error: ${err.message}`);
306
+ });
307
+ child.on("exit", (code, signal) => {
308
+ if (code !== null && code !== 0) {
309
+ console.error(`[mock-mcp] Daemon exited with code: ${code}`);
310
+ if (daemonStderr) {
311
+ console.error(`[mock-mcp] Daemon stderr: ${daemonStderr.slice(0, 500)}`);
312
+ }
313
+ } else if (signal) {
314
+ console.error(`[mock-mcp] Daemon killed by signal: ${signal}`);
315
+ }
316
+ });
317
+ child.unref();
318
+ const deadline2 = Date.now() + timeoutMs;
319
+ while (Date.now() < deadline2) {
320
+ const reg = await readRegistry(registryPath);
321
+ if (reg && await healthCheck(reg.ipcPath)) {
322
+ return reg;
323
+ }
324
+ await sleep(50);
325
+ }
326
+ console.error("[mock-mcp] Daemon failed to start within timeout");
327
+ if (daemonStderr) {
328
+ console.error(`[mock-mcp] Daemon stderr:
329
+ ${daemonStderr}`);
330
+ }
331
+ throw new Error(
332
+ `Daemon start timeout after ${timeoutMs}ms. Check logs for details.`
333
+ );
334
+ } finally {
335
+ await releaseLock(lockPath, lock);
336
+ }
337
+ }
338
+ const deadline = Date.now() + timeoutMs;
339
+ while (Date.now() < deadline) {
340
+ const reg = await readRegistry(registryPath);
341
+ if (reg && await healthCheck(reg.ipcPath)) {
342
+ return reg;
343
+ }
344
+ await sleep(50);
345
+ }
346
+ throw new Error(
347
+ `Waiting for daemon timed out after ${timeoutMs}ms. Another process may have failed to start it.`
348
+ );
349
+ }
350
+ function sleep(ms) {
351
+ return new Promise((resolve) => setTimeout(resolve, ms));
352
+ }
353
+
354
+ // src/adapter/adapter.ts
355
+ var TOOLS = [
356
+ {
357
+ name: "get_status",
358
+ description: "Get the current status of the mock-mcp daemon, including active test runs and pending batches.",
359
+ inputSchema: {
360
+ type: "object",
361
+ properties: {},
362
+ required: []
363
+ }
364
+ },
365
+ {
366
+ name: "list_runs",
367
+ description: "List all active test runs connected to the daemon.",
368
+ inputSchema: {
369
+ type: "object",
370
+ properties: {},
371
+ required: []
372
+ }
373
+ },
374
+ {
375
+ name: "claim_next_batch",
376
+ description: `Claim the next pending mock batch for processing. This acquires a lease on the batch.
377
+
378
+ You MUST call this before provide_batch_mock_data. The batch will be locked for 30 seconds (configurable via leaseMs).
379
+ If you don't provide mock data within the lease time, the batch will be released for another adapter to claim.`,
380
+ inputSchema: {
381
+ type: "object",
382
+ properties: {
383
+ runId: {
384
+ type: "string",
385
+ description: "Optional: Filter to only claim batches from a specific test run."
386
+ },
387
+ leaseMs: {
388
+ type: "number",
389
+ description: "Optional: Lease duration in milliseconds. Default: 30000 (30 seconds)."
390
+ }
391
+ },
392
+ required: []
393
+ }
394
+ },
395
+ {
396
+ name: "get_batch",
397
+ description: "Get details of a specific batch by ID (read-only, does not claim).",
398
+ inputSchema: {
399
+ type: "object",
400
+ properties: {
401
+ batchId: {
402
+ type: "string",
403
+ description: "The batch ID to retrieve."
404
+ }
405
+ },
406
+ required: ["batchId"]
407
+ }
408
+ },
409
+ {
410
+ name: "provide_batch_mock_data",
411
+ description: `Provide mock response data for a claimed batch.
412
+
413
+ You MUST first call claim_next_batch to get the batchId and claimToken.
414
+ The mocks array must contain exactly one mock for each request in the batch.`,
415
+ inputSchema: {
416
+ type: "object",
417
+ properties: {
418
+ batchId: {
419
+ type: "string",
420
+ description: "The batch ID (from claim_next_batch)."
421
+ },
422
+ claimToken: {
423
+ type: "string",
424
+ description: "The claim token (from claim_next_batch)."
425
+ },
426
+ mocks: {
427
+ type: "array",
428
+ description: "Array of mock responses, one for each request in the batch.",
429
+ items: {
430
+ type: "object",
431
+ properties: {
432
+ requestId: {
433
+ type: "string",
434
+ description: "The requestId from the original request."
435
+ },
436
+ data: {
437
+ description: "The mock response data (any JSON value)."
438
+ },
439
+ status: {
440
+ type: "number",
441
+ description: "Optional HTTP status code. Default: 200."
442
+ },
443
+ headers: {
444
+ type: "object",
445
+ description: "Optional response headers."
446
+ },
447
+ delayMs: {
448
+ type: "number",
449
+ description: "Optional delay before returning the mock (ms)."
450
+ }
451
+ },
452
+ required: ["requestId", "data"]
453
+ }
454
+ }
455
+ },
456
+ required: ["batchId", "claimToken", "mocks"]
457
+ }
458
+ },
459
+ {
460
+ name: "release_batch",
461
+ description: "Release a claimed batch without providing mock data. Use this if you cannot generate appropriate mocks.",
462
+ inputSchema: {
463
+ type: "object",
464
+ properties: {
465
+ batchId: {
466
+ type: "string",
467
+ description: "The batch ID to release."
468
+ },
469
+ claimToken: {
470
+ type: "string",
471
+ description: "The claim token."
472
+ },
473
+ reason: {
474
+ type: "string",
475
+ description: "Optional reason for releasing."
476
+ }
477
+ },
478
+ required: ["batchId", "claimToken"]
479
+ }
480
+ }
481
+ ];
482
+ async function runAdapter(opts = {}) {
483
+ const logger = opts.logger ?? console;
484
+ const version = opts.version ?? "0.4.0";
485
+ logger.error("\u{1F50D} Connecting to mock-mcp daemon...");
486
+ const registry = await ensureDaemonRunning();
487
+ const adapterId = crypto2.randomUUID();
488
+ const daemon = new DaemonClient(registry.ipcPath, registry.token, adapterId);
489
+ logger.error(`\u2705 Connected to daemon (project: ${registry.projectId})`);
490
+ const server = new Server(
491
+ {
492
+ name: "mock-mcp-adapter",
493
+ version
494
+ },
495
+ {
496
+ capabilities: { tools: {} }
497
+ }
498
+ );
499
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({
500
+ tools: [...TOOLS]
501
+ }));
502
+ server.setRequestHandler(CallToolRequestSchema, async (request) => {
503
+ const { name, arguments: args } = request.params;
504
+ try {
505
+ switch (name) {
506
+ case "get_status": {
507
+ const result = await daemon.getStatus();
508
+ return buildToolResponse(formatStatus(result));
509
+ }
510
+ case "list_runs": {
511
+ const result = await daemon.listRuns();
512
+ return buildToolResponse(formatRuns(result));
513
+ }
514
+ case "claim_next_batch": {
515
+ const result = await daemon.claimNextBatch({
516
+ runId: args?.runId,
517
+ leaseMs: args?.leaseMs
518
+ });
519
+ return buildToolResponse(formatClaimResult(result));
520
+ }
521
+ case "get_batch": {
522
+ if (!args?.batchId) {
523
+ throw new Error("batchId is required");
524
+ }
525
+ const result = await daemon.getBatch(args.batchId);
526
+ return buildToolResponse(formatBatch(result));
527
+ }
528
+ case "provide_batch_mock_data": {
529
+ if (!args?.batchId || !args?.claimToken || !args?.mocks) {
530
+ throw new Error("batchId, claimToken, and mocks are required");
531
+ }
532
+ const result = await daemon.provideBatch({
533
+ batchId: args.batchId,
534
+ claimToken: args.claimToken,
535
+ mocks: args.mocks
536
+ });
537
+ return buildToolResponse(formatProvideResult(result));
538
+ }
539
+ case "release_batch": {
540
+ if (!args?.batchId || !args?.claimToken) {
541
+ throw new Error("batchId and claimToken are required");
542
+ }
543
+ const result = await daemon.releaseBatch({
544
+ batchId: args.batchId,
545
+ claimToken: args.claimToken,
546
+ reason: args?.reason
547
+ });
548
+ return buildToolResponse(JSON.stringify(result, null, 2));
549
+ }
550
+ default:
551
+ throw new Error(`Unknown tool: ${name}`);
552
+ }
553
+ } catch (error) {
554
+ const message = error instanceof Error ? error.message : String(error);
555
+ logger.error(`Tool error (${name}):`, message);
556
+ return buildToolResponse(`Error: ${message}`, true);
557
+ }
558
+ });
559
+ const transport = new StdioServerTransport();
560
+ await server.connect(transport);
561
+ logger.error("\u2705 MCP adapter ready (stdio transport)");
562
+ }
563
+ function buildToolResponse(text, isError = false) {
564
+ return {
565
+ content: [{ type: "text", text }],
566
+ isError
567
+ };
568
+ }
569
+ function formatStatus(status) {
570
+ return `# Mock MCP Daemon Status
571
+
572
+ - **Version**: ${status.version}
573
+ - **Project ID**: ${status.projectId}
574
+ - **Project Root**: ${status.projectRoot}
575
+ - **PID**: ${status.pid}
576
+ - **Uptime**: ${Math.round(status.uptime / 1e3)}s
577
+
578
+ ## Batches
579
+ - **Pending**: ${status.pending}
580
+ - **Claimed**: ${status.claimed}
581
+ - **Active Runs**: ${status.runs}
582
+ `;
583
+ }
584
+ function formatRuns(result) {
585
+ if (result.runs.length === 0) {
586
+ return "No active test runs.";
587
+ }
588
+ const lines = ["# Active Test Runs\n"];
589
+ for (const run of result.runs) {
590
+ lines.push(`## Run: ${run.runId}`);
591
+ lines.push(`- **PID**: ${run.pid}`);
592
+ lines.push(`- **CWD**: ${run.cwd}`);
593
+ lines.push(`- **Started**: ${run.startedAt}`);
594
+ lines.push(`- **Pending Batches**: ${run.pendingBatches}`);
595
+ if (run.testMeta) {
596
+ if (run.testMeta.testFile) {
597
+ lines.push(`- **Test File**: ${run.testMeta.testFile}`);
598
+ }
599
+ if (run.testMeta.testName) {
600
+ lines.push(`- **Test Name**: ${run.testMeta.testName}`);
601
+ }
602
+ }
603
+ lines.push("");
604
+ }
605
+ return lines.join("\n");
606
+ }
607
+ function formatClaimResult(result) {
608
+ if (!result) {
609
+ return "No pending batches available to claim.";
610
+ }
611
+ const lines = [
612
+ "# Batch Claimed Successfully\n",
613
+ `**Batch ID**: \`${result.batchId}\``,
614
+ `**Claim Token**: \`${result.claimToken}\``,
615
+ `**Run ID**: ${result.runId}`,
616
+ `**Lease Until**: ${new Date(result.leaseUntil).toISOString()}`,
617
+ "",
618
+ "## Requests\n"
619
+ ];
620
+ for (const req of result.requests) {
621
+ lines.push(`### ${req.method} ${req.endpoint}`);
622
+ lines.push(`- **Request ID**: \`${req.requestId}\``);
623
+ if (req.body !== void 0) {
624
+ lines.push(`- **Body**: \`\`\`json
625
+ ${JSON.stringify(req.body, null, 2)}
626
+ \`\`\``);
627
+ }
628
+ if (req.headers) {
629
+ lines.push(`- **Headers**: ${JSON.stringify(req.headers)}`);
630
+ }
631
+ if (req.metadata) {
632
+ lines.push(`- **Metadata**: ${JSON.stringify(req.metadata)}`);
633
+ }
634
+ lines.push("");
635
+ }
636
+ lines.push("---");
637
+ lines.push("**Next step**: Call `provide_batch_mock_data` with the batch ID, claim token, and mock data for each request.");
638
+ return lines.join("\n");
639
+ }
640
+ function formatBatch(result) {
641
+ const lines = [
642
+ `# Batch: ${result.batchId}
643
+ `,
644
+ `**Status**: ${result.status}`,
645
+ `**Run ID**: ${result.runId}`,
646
+ `**Created**: ${new Date(result.createdAt).toISOString()}`
647
+ ];
648
+ if (result.claim) {
649
+ lines.push(`**Claimed by**: ${result.claim.adapterId}`);
650
+ lines.push(`**Lease until**: ${new Date(result.claim.leaseUntil).toISOString()}`);
651
+ }
652
+ lines.push("", "## Requests\n");
653
+ for (const req of result.requests) {
654
+ lines.push(`### ${req.method} ${req.endpoint}`);
655
+ lines.push(`- **Request ID**: \`${req.requestId}\``);
656
+ if (req.body !== void 0) {
657
+ lines.push(`- **Body**: \`\`\`json
658
+ ${JSON.stringify(req.body, null, 2)}
659
+ \`\`\``);
660
+ }
661
+ lines.push("");
662
+ }
663
+ return lines.join("\n");
664
+ }
665
+ function formatProvideResult(result) {
666
+ if (result.ok) {
667
+ return `\u2705 ${result.message ?? "Mock data provided successfully."}`;
668
+ }
669
+ return `\u274C Failed to provide mock data: ${result.message}`;
670
+ }
671
+
672
+ export { DaemonClient, runAdapter };