@letsrunit/mcp-server 0.13.3 → 0.14.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.
package/README.md CHANGED
@@ -50,6 +50,17 @@ args = ["-y", "@letsrunit/mcp-server@latest"]
50
50
  }
51
51
  ```
52
52
 
53
+ ## Project-local support files
54
+
55
+ Keep using the same MCP command (`npx -y @letsrunit/mcp-server@latest`).
56
+
57
+ At runtime, letsrunit checks the current project:
58
+
59
+ - If the project has `@letsrunit/mcp-server` installed, it hands off to that project-local server and loads support files/custom steps.
60
+ - If not, it stays in standalone mode and runs built-in letsrunit steps only.
61
+
62
+ So custom steps from `features/support/**` are available when `@letsrunit/mcp-server` is installed in that project.
63
+
53
64
  ## Tools
54
65
 
55
66
  | Tool | Description |
package/dist/index.js CHANGED
@@ -3,581 +3,105 @@ import * as __m from 'node:module';
3
3
  import { createRequire } from 'module';
4
4
  import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
5
5
  import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
6
- import { Controller } from '@letsrunit/controller';
7
- import { MemorySink, Journal } from '@letsrunit/journal';
8
- import { join, dirname, resolve, isAbsolute } from 'path';
9
- import { z } from 'zod';
10
- import { loadConfiguration } from '@cucumber/cucumber/api';
11
- import { registry } from '@letsrunit/bdd';
12
- import { readFileSync, existsSync } from 'fs';
13
- import { mkdir, writeFile, glob } from 'fs/promises';
14
- import { pathToFileURL } from 'url';
15
- import { scrubHtml, screenshotElement, screenshot, unifiedHtmlDiff } from '@letsrunit/playwright';
16
- import { openStore, findLastTest, findArtifacts } from '@letsrunit/store';
17
- import { execSync } from 'child_process';
18
- import { scenarioIdFromGherkin } from '@letsrunit/gherkin';
6
+ import { spawnSync } from 'child_process';
7
+ import { realpathSync, readFileSync } from 'fs';
8
+ import { resolve, dirname } from 'path';
19
9
 
20
10
  __m.createRequire(import.meta.url);
21
- var SESSION_TIMEOUT_MS = 30 * 60 * 1e3;
22
- var BASE_ARTIFACT_DIR = process.env.LETSRUNIT_ARTIFACT_DIR ?? join(process.env.HOME ?? "/tmp", ".letsrunit", "artifacts");
23
- function sessionId() {
24
- return Math.random().toString(36).slice(2, 10) + Date.now().toString(36);
11
+ function resolveProjectRoot() {
12
+ return resolve(process.env.LETSRUNIT_PROJECT_CWD ?? process.cwd());
25
13
  }
26
- var SessionManager = class {
27
- sessions = /* @__PURE__ */ new Map();
28
- timers = /* @__PURE__ */ new Map();
29
- async create(options = {}) {
30
- const id = sessionId();
31
- const artifactDir = join(BASE_ARTIFACT_DIR, id);
32
- const sink = new MemorySink(artifactDir);
33
- const journal = new Journal(sink);
34
- const controller = await Controller.launch({ ...options, journal });
35
- const session = {
36
- id,
37
- controller,
38
- sink,
39
- journal,
40
- artifactDir,
41
- createdAt: Date.now(),
42
- lastActivity: Date.now(),
43
- stepCount: 0
44
- };
45
- this.sessions.set(id, session);
46
- this.resetTimer(id);
47
- return session;
48
- }
49
- get(id) {
50
- const session = this.sessions.get(id);
51
- if (!session) throw new Error(`Session not found: ${id}`);
52
- return session;
53
- }
54
- has(id) {
55
- return this.sessions.has(id);
56
- }
57
- touch(id) {
58
- const session = this.sessions.get(id);
59
- if (session) {
60
- session.lastActivity = Date.now();
61
- this.resetTimer(id);
62
- }
63
- }
64
- list() {
65
- return Array.from(this.sessions.values());
66
- }
67
- async close(id) {
68
- const session = this.sessions.get(id);
69
- if (!session) return;
70
- clearTimeout(this.timers.get(id));
71
- this.timers.delete(id);
72
- this.sessions.delete(id);
73
- await session.controller.close();
74
- }
75
- resetTimer(id) {
76
- clearTimeout(this.timers.get(id));
77
- const timer = setTimeout(() => this.close(id), SESSION_TIMEOUT_MS);
78
- if (typeof timer === "object" && "unref" in timer) timer.unref();
79
- this.timers.set(id, timer);
80
- }
81
- };
82
-
83
- // src/utility/response.ts
84
- function text(content) {
85
- return { content: [{ type: "text", text: content }] };
86
- }
87
- function err(message) {
88
- return { content: [{ type: "text", text: message }], isError: true };
89
- }
90
-
91
- // src/tools/debug.ts
92
- function registerDebug(server2, sessions2) {
93
- server2.registerTool(
94
- "letsrunit_debug",
95
- {
96
- description: "Evaluate JavaScript on the current page via Playwright page.evaluate(). Use for debugging \u2014 not for test logic.",
97
- inputSchema: {
98
- sessionId: z.string().describe("Session ID"),
99
- script: z.string().describe("JavaScript expression or function body to evaluate in the page context")
100
- }
101
- },
102
- async (input) => {
103
- try {
104
- const session = sessions2.get(input.sessionId);
105
- sessions2.touch(input.sessionId);
106
- const result = await session.controller.page.evaluate(input.script);
107
- return text(JSON.stringify({ result }));
108
- } catch (e) {
109
- return text(JSON.stringify({ result: null, error: e.message }));
110
- }
111
- }
112
- );
113
- }
114
- var CUCUMBER_CONFIG_FILES = [
115
- "cucumber.js",
116
- "cucumber.mjs",
117
- "cucumber.cjs",
118
- "cucumber.ts",
119
- "cucumber.mts",
120
- "cucumber.cts"
121
- ];
122
- var loadedProjectRoots = /* @__PURE__ */ new Set();
123
- var loadedSupportEntries = /* @__PURE__ */ new Set();
124
- function toStrings(value) {
125
- if (!Array.isArray(value)) return [];
126
- return value.filter((entry) => typeof entry === "string");
127
- }
128
- function hasGlobMagic(input) {
129
- return /[*?[\]{}]/.test(input);
130
- }
131
- function isPathLike(input) {
132
- return input.startsWith(".") || input.startsWith("/") || /^[A-Za-z]:[\\/]/.test(input);
133
- }
134
- function toAbsolutePath(baseDir, input) {
135
- return isAbsolute(input) ? resolve(input) : resolve(baseDir, input);
136
- }
137
- function normalizeMatch(baseDir, match) {
138
- return isAbsolute(match) ? resolve(match) : resolve(baseDir, match);
139
- }
140
- async function expandPathPatterns(baseDir, patterns) {
141
- const files = /* @__PURE__ */ new Set();
142
- for (const pattern of patterns) {
143
- if (hasGlobMagic(pattern)) {
144
- for await (const match of glob(pattern, { cwd: baseDir, absolute: true, withFileTypes: false })) {
145
- files.add(normalizeMatch(baseDir, match));
146
- }
147
- continue;
148
- }
149
- files.add(toAbsolutePath(baseDir, pattern));
150
- }
151
- return files;
152
- }
153
- async function resolveSupportEntries(baseDir, entries) {
154
- const resolved = [];
155
- for (const entry of entries) {
156
- if (hasGlobMagic(entry)) {
157
- for await (const match of glob(entry, { cwd: baseDir, absolute: true, withFileTypes: false })) {
158
- resolved.push({ kind: "path", value: normalizeMatch(baseDir, match) });
159
- }
160
- continue;
161
- }
162
- if (!isPathLike(entry)) {
163
- resolved.push({ kind: "module", value: entry });
164
- continue;
165
- }
166
- resolved.push({ kind: "path", value: toAbsolutePath(baseDir, entry) });
167
- }
168
- return resolved;
169
- }
170
- function findCucumberConfig(cwd) {
171
- for (const filename of CUCUMBER_CONFIG_FILES) {
172
- const path = resolve(cwd, filename);
173
- if (existsSync(path)) return path;
174
- }
175
- return null;
176
- }
177
- async function loadLetsrunitIgnorePatterns(cwd) {
178
- const configPath = findCucumberConfig(cwd);
179
- if (!configPath) return [];
180
- const configModule = await import(pathToFileURL(configPath).href);
181
- const config = configModule.default ?? configModule;
182
- return toStrings(config.letsrunit?.ignore);
183
- }
184
- function resolveEffectiveCwd(cwd) {
185
- return cwd ?? process.env.LETSRUNIT_PROJECT_CWD ?? process.cwd();
186
- }
187
- function resolveFrom(moduleId, fromPath) {
14
+ function resolveFromProject(moduleId, projectRoot) {
188
15
  try {
189
- const req = createRequire(fromPath);
16
+ const req = createRequire(resolve(projectRoot, "package.json"));
190
17
  return req.resolve(moduleId);
191
18
  } catch {
192
19
  return null;
193
20
  }
194
21
  }
195
- async function collectSupportDiagnostics(cwd) {
196
- const effectiveCwd = resolveEffectiveCwd(cwd);
197
- const projectRoot = resolve(effectiveCwd);
198
- const cucumberConfigPath = findCucumberConfig(projectRoot);
199
- const { useConfiguration } = await loadConfiguration({}, { cwd: projectRoot });
200
- const supportPatterns = [...toStrings(useConfiguration.require), ...toStrings(useConfiguration.import)];
201
- const ignorePatterns = await loadLetsrunitIgnorePatterns(projectRoot);
202
- const ignoredPaths = await expandPathPatterns(projectRoot, ignorePatterns);
203
- const supportEntries = await resolveSupportEntries(projectRoot, supportPatterns);
204
- const serverBddPath = resolveFrom("@letsrunit/bdd", import.meta.url);
205
- const projectBddPath = resolveFrom("@letsrunit/bdd", resolve(projectRoot, "package.json"));
206
- const registryDefinitions = registry.defs.map((def) => ({
207
- type: def.type,
208
- source: def.source,
209
- comment: def.comment
210
- }));
211
- return {
212
- envProjectCwd: process.env.LETSRUNIT_PROJECT_CWD ?? null,
213
- processCwd: process.cwd(),
214
- inputCwd: cwd ?? null,
215
- effectiveCwd,
216
- projectRoot,
217
- cucumberConfigPath,
218
- supportPatterns,
219
- ignorePatterns,
220
- ignoredPaths: [...ignoredPaths].sort(),
221
- supportEntries,
222
- loadedProjectRoots: [...loadedProjectRoots].sort(),
223
- loadedSupportEntries: [...loadedSupportEntries].sort(),
224
- moduleResolution: {
225
- serverBddPath,
226
- projectBddPath,
227
- sameModule: !!serverBddPath && !!projectBddPath && serverBddPath === projectBddPath
228
- },
229
- registry: {
230
- total: registryDefinitions.length,
231
- byType: {
232
- Given: registryDefinitions.filter((d) => d.type === "Given").length,
233
- When: registryDefinitions.filter((d) => d.type === "When").length,
234
- Then: registryDefinitions.filter((d) => d.type === "Then").length
235
- },
236
- definitions: registryDefinitions
237
- }
238
- };
239
- }
240
- async function loadSupportFiles(cwd) {
241
- const projectRoot = resolve(resolveEffectiveCwd(cwd));
242
- if (loadedProjectRoots.has(projectRoot)) return;
243
- const { useConfiguration } = await loadConfiguration({}, { cwd: projectRoot });
244
- const supportPatterns = [...toStrings(useConfiguration.require), ...toStrings(useConfiguration.import)];
245
- if (supportPatterns.length === 0) {
246
- loadedProjectRoots.add(projectRoot);
247
- return;
248
- }
249
- const ignorePatterns = await loadLetsrunitIgnorePatterns(projectRoot);
250
- const ignoredPaths = await expandPathPatterns(projectRoot, ignorePatterns);
251
- const supportEntries = await resolveSupportEntries(projectRoot, supportPatterns);
252
- for (const entry of supportEntries) {
253
- if (entry.kind === "path" && ignoredPaths.has(entry.value)) {
254
- continue;
255
- }
256
- const key = `${entry.kind}:${entry.value}`;
257
- if (loadedSupportEntries.has(key)) continue;
258
- if (entry.kind === "path") {
259
- await import(pathToFileURL(entry.value).href);
260
- } else {
261
- await import(entry.value);
262
- }
263
- loadedSupportEntries.add(key);
264
- }
265
- loadedProjectRoots.add(projectRoot);
266
- }
267
-
268
- // src/tools/diagnostics.ts
269
- function registerDiagnostics(server2) {
270
- server2.registerTool(
271
- "letsrunit_diagnostics",
272
- {
273
- description: "Return runtime diagnostics for MCP support-file loading (cwd resolution, cucumber config path, support entries). Available only when LETSRUNIT_MCP_DIAGNOSTICS=enabled.",
274
- inputSchema: {}
275
- },
276
- async () => {
277
- try {
278
- const diagnostics = await collectSupportDiagnostics();
279
- return text(JSON.stringify(diagnostics));
280
- } catch (e) {
281
- return err(`Diagnostics failed: ${e.message}`);
282
- }
283
- }
284
- );
285
- }
286
- var DEFAULT_DB_PATH = join(process.cwd(), ".letsrunit", "letsrunit.db");
287
- function getDbPath() {
288
- return process.env.LETSRUNIT_DB_PATH ?? DEFAULT_DB_PATH;
289
- }
290
- function resolveAllowedCommits() {
22
+ function toRealpath(path) {
23
+ if (!path) return null;
291
24
  try {
292
- const output = execSync("git log --format=%H", { encoding: "utf8" });
293
- return output.trim().split("\n").filter(Boolean);
25
+ return realpathSync(path);
294
26
  } catch {
295
- return void 0;
27
+ return null;
296
28
  }
297
29
  }
298
- function registerDiff(server2, sessions2) {
299
- server2.registerTool(
300
- "letsrunit_diff",
301
- {
302
- description: "Diff the current live page against the HTML snapshot from the last passing test of a scenario. Pass the scenarioId returned by letsrunit_run. Returns a unified HTML diff and paths to baseline screenshots. By default only considers baseline tests from the current git ancestry (gitTreeOnly: true).",
303
- inputSchema: {
304
- sessionId: z.string().describe("Session ID returned by letsrunit_session_start"),
305
- scenarioId: z.string().describe("Scenario UUID returned by letsrunit_run"),
306
- gitTreeOnly: z.boolean().optional().describe("Restrict baseline to tests from the current git ancestry (default: true)")
307
- }
308
- },
309
- async (input) => {
310
- const dbPath = getDbPath();
311
- const artifactDir = join(dirname(dbPath), "artifacts");
312
- let db;
313
- try {
314
- try {
315
- db = openStore(dbPath);
316
- } catch {
317
- return err("Could not open the letsrunit store. Run cucumber with the store formatter first.");
318
- }
319
- const allowedCommits = input.gitTreeOnly ?? true ? resolveAllowedCommits() : void 0;
320
- const test = findLastTest(db, input.scenarioId, "passed", allowedCommits ?? void 0);
321
- if (!test) {
322
- return err(
323
- allowedCommits ? "No passing test found for this scenario in the current git ancestry. Try gitTreeOnly: false or run cucumber first." : "No passing test found for this scenario."
324
- );
325
- }
326
- const artifacts = findArtifacts(db, test.id);
327
- const htmlArtifact = [...artifacts].reverse().find((a) => a.filename.endsWith(".html"));
328
- if (!htmlArtifact) {
329
- return err("No HTML snapshot found in the baseline test. Ensure the store formatter is configured.");
330
- }
331
- const storedHtml = readFileSync(join(artifactDir, htmlArtifact.filename), "utf-8");
332
- const session = sessions2.get(input.sessionId);
333
- sessions2.touch(input.sessionId);
334
- const diff = await unifiedHtmlDiff({ html: storedHtml, url: "about:blank" }, session.controller.page);
335
- const screenshots = artifacts.filter((a) => a.stepIdx === htmlArtifact.stepIdx && a.filename.endsWith(".png")).map((a) => join(artifactDir, a.filename));
336
- return text(
337
- JSON.stringify({
338
- diff,
339
- baseline: {
340
- testId: test.id,
341
- commit: test.gitCommit,
342
- screenshots
343
- }
344
- })
345
- );
346
- } catch (e) {
347
- return err(`Diff failed: ${e.message}`);
348
- } finally {
349
- db?.close();
350
- }
351
- }
352
- );
353
- }
354
- var stepTypeSchema = z.enum(["Given", "When", "Then"]);
355
- function registerListSteps(server2, sessions2) {
356
- server2.registerTool(
357
- "letsrunit_list_steps",
358
- {
359
- description: "List available step definitions for a session. Optionally filter by step type (Given/When/Then).",
360
- inputSchema: {
361
- sessionId: z.string().describe("Session ID returned by letsrunit_session_start"),
362
- type: stepTypeSchema.optional().describe("Optional step type filter")
363
- }
364
- },
365
- async (input) => {
366
- try {
367
- const session = sessions2.get(input.sessionId);
368
- sessions2.touch(input.sessionId);
369
- const steps = session.controller.listSteps(input.type);
370
- return text(JSON.stringify({ steps }));
371
- } catch (e) {
372
- return err(`List steps failed: ${e.message}`);
373
- }
374
- }
375
- );
376
- }
377
-
378
- // src/tools/list-sessions.ts
379
- function registerListSessions(server2, sessions2) {
380
- server2.registerTool(
381
- "letsrunit_list_sessions",
382
- {
383
- description: "List all active browser sessions.",
384
- inputSchema: {}
385
- },
386
- async () => {
387
- const list = sessions2.list().map((s) => ({
388
- sessionId: s.id,
389
- createdAt: s.createdAt,
390
- lastActivity: s.lastActivity,
391
- stepCount: s.stepCount,
392
- artifactDir: s.artifactDir
393
- }));
394
- return text(JSON.stringify({ sessions: list }));
395
- }
396
- );
30
+ function samePackageRoot(a, b) {
31
+ if (!a || !b) return false;
32
+ return dirname(a) === dirname(b);
397
33
  }
398
-
399
- // src/utility/gherkin.ts
400
- function normalizeGherkin(input) {
401
- const trimmed = input.trim();
402
- if (/^(Feature|Scenario|Background):/im.test(trimmed)) {
403
- return trimmed;
34
+ function resolveBinPath(packageJsonPath) {
35
+ const text = readFileSync(packageJsonPath, "utf8");
36
+ const pkg = JSON.parse(text);
37
+ if (typeof pkg.bin === "string") {
38
+ return resolve(dirname(packageJsonPath), pkg.bin);
404
39
  }
405
- return `Feature: MCP
406
-
407
- Scenario: Steps
408
- ${trimmed.split("\n").join("\n ")}`;
409
- }
410
-
411
- // src/tools/run.ts
412
- function registerRun(server2, sessions2) {
413
- server2.registerTool(
414
- "letsrunit_run",
415
- {
416
- description: "Execute Gherkin steps or a complete feature in the browser. Accepts a single step line, multiple step lines, a full Scenario, or a full Feature. Returns status, steps, reason on failure, and journal entries. Does not return a page snapshot \u2014 call letsrunit_snapshot explicitly if you need the DOM.",
417
- inputSchema: {
418
- sessionId: z.string().describe("Session ID returned by letsrunit_session_start"),
419
- input: z.string().describe(
420
- 'Gherkin text to execute: one or more step lines (e.g. "Given I am on \\"https://example.com\\""), a Scenario block, or a full Feature block.'
421
- )
422
- }
423
- },
424
- async (input) => {
425
- try {
426
- const session = sessions2.get(input.sessionId);
427
- sessions2.touch(input.sessionId);
428
- const feature = normalizeGherkin(input.input);
429
- session.sink.clear();
430
- const result = await session.controller.run(feature);
431
- session.stepCount += result.steps.length;
432
- return text(
433
- JSON.stringify({
434
- status: result.status,
435
- steps: result.steps,
436
- reason: result.reason?.message,
437
- journal: session.sink.getEntries(),
438
- scenarioId: scenarioIdFromGherkin(input.input)
439
- })
440
- );
441
- } catch (e) {
442
- return err(`Run failed: ${e.message}`);
443
- }
444
- }
445
- );
446
- }
447
- function registerScreenshot(server2, sessions2) {
448
- server2.registerTool(
449
- "letsrunit_screenshot",
450
- {
451
- description: "Take a screenshot of the current page. Optionally crop to a specific element (selector) or highlight elements before capturing (mask).",
452
- inputSchema: {
453
- sessionId: z.string().describe("Session ID"),
454
- selector: z.string().optional().describe("CSS selector \u2014 crop screenshot to the bounding box of this element"),
455
- mask: z.array(z.string()).optional().describe("CSS selectors whose matching elements are highlighted (dark overlay, element spotlighted)."),
456
- fullPage: z.boolean().optional().describe("Capture the full scrollable page (default: false)")
457
- }
458
- },
459
- async (input) => {
460
- try {
461
- const session = sessions2.get(input.sessionId);
462
- sessions2.touch(input.sessionId);
463
- const page = session.controller.page;
464
- let file;
465
- if (input.selector) {
466
- file = await screenshotElement(page, input.selector);
467
- } else {
468
- const masks = input.mask?.map((sel) => page.locator(sel)) ?? [];
469
- file = await screenshot(page, {
470
- fullPage: input.fullPage ?? false,
471
- ...masks.length ? { mask: masks } : {}
472
- });
473
- }
474
- await mkdir(session.artifactDir, { recursive: true });
475
- const path = join(session.artifactDir, file.name);
476
- await writeFile(path, await file.bytes());
477
- return text(JSON.stringify({ path, mimeType: "image/png" }));
478
- } catch (e) {
479
- return err(`Screenshot failed: ${e.message}`);
480
- }
481
- }
482
- );
483
- }
484
- function registerSessionClose(server2, sessions2) {
485
- server2.registerTool(
486
- "letsrunit_session_close",
487
- {
488
- description: "Close a browser session and release its resources.",
489
- inputSchema: {
490
- sessionId: z.string().describe("Session ID to close")
491
- }
492
- },
493
- async (input) => {
494
- try {
495
- await sessions2.close(input.sessionId);
496
- return text(JSON.stringify({ closed: true }));
497
- } catch (e) {
498
- return err(`Failed to close session: ${e.message}`);
499
- }
500
- }
501
- );
502
- }
503
- function registerSessionStart(server2, sessions2) {
504
- server2.registerTool(
505
- "letsrunit_session_start",
506
- {
507
- description: `Launch a new browser session. Does not navigate anywhere \u2014 use letsrunit_run with a Given step to navigate. Set baseURL to enable relative paths like "Given I'm on the homepage".`,
508
- inputSchema: {
509
- baseURL: z.string().optional().describe(`Base URL for the session, e.g. "http://localhost:3000". Enables relative paths in Given steps like "Given I'm on the homepage" or "Given I'm on page \\"/login\\""`),
510
- language: z.string().optional().describe("Browser language code, e.g. 'en', 'fr'"),
511
- headless: z.boolean().optional().describe("Run browser in headless mode (default: true)"),
512
- viewportWidth: z.number().int().optional().describe("Viewport width in pixels (default: 1280)"),
513
- viewportHeight: z.number().int().optional().describe("Viewport height in pixels (default: 720)")
514
- }
515
- },
516
- async (input) => {
517
- try {
518
- await loadSupportFiles();
519
- const viewport = input.viewportWidth || input.viewportHeight ? { width: input.viewportWidth ?? 1280, height: input.viewportHeight ?? 720 } : void 0;
520
- const session = await sessions2.create({
521
- baseURL: input.baseURL,
522
- headless: input.headless ?? true,
523
- locale: input.language,
524
- viewport
525
- });
526
- return text(JSON.stringify({ sessionId: session.id }));
527
- } catch (e) {
528
- return err(`Failed to start session: ${e.message}`);
529
- }
40
+ if (pkg.bin && typeof pkg.bin === "object") {
41
+ const named = pkg.bin["letsrunit-mcp"];
42
+ const first = Object.values(pkg.bin)[0];
43
+ const bin = named ?? first;
44
+ if (typeof bin === "string") {
45
+ return resolve(dirname(packageJsonPath), bin);
530
46
  }
531
- );
47
+ }
48
+ throw new Error(`Unable to resolve mcp bin from ${packageJsonPath}`);
532
49
  }
533
- var stripAttributesSchema = z.nativeEnum({
534
- none: 0,
535
- semantic: 1,
536
- aggressive: 2
537
- });
538
- function registerSnapshot(server2, sessions2) {
539
- server2.registerTool(
540
- "letsrunit_snapshot",
541
- {
542
- description: "Get the current page HTML, scrubbed for LLM consumption. Use selector to scope to a DOM subtree.",
543
- inputSchema: {
544
- sessionId: z.string().describe("Session ID"),
545
- selector: z.string().optional().describe("CSS selector \u2014 return only the matching element's outer HTML instead of the full page"),
546
- dropHidden: z.boolean().optional().describe("Remove hidden/inert nodes (default: true)"),
547
- dropHead: z.boolean().optional().describe("Remove the <head> element (default: true)"),
548
- pickMain: z.boolean().optional().describe("Keep only the <main> element (default: auto)"),
549
- stripAttributes: stripAttributesSchema.optional().describe("Attribute allowlist level: 0=none, 1=semantic (default), 2=aggressive")
550
- }
551
- },
552
- async (input) => {
553
- try {
554
- const session = sessions2.get(input.sessionId);
555
- sessions2.touch(input.sessionId);
556
- const page = session.controller.page;
557
- const url = page.url();
558
- const opts = {
559
- dropHidden: input.dropHidden,
560
- dropHead: input.dropHead,
561
- pickMain: input.pickMain,
562
- stripAttributes: input.stripAttributes
563
- };
564
- let html;
565
- if (input.selector) {
566
- const rawHtml = await page.locator(input.selector).first().evaluate((el) => el.outerHTML);
567
- html = await scrubHtml({ html: rawHtml, url }, opts);
568
- } else {
569
- html = await scrubHtml(page, opts);
570
- }
571
- return text(JSON.stringify({ url, html }));
572
- } catch (e) {
573
- return err(`Snapshot failed: ${e.message}`);
574
- }
575
- }
576
- );
50
+ function decideHandoff(currentPackageJsonPath, projectPackageJsonPath, isBootstrapped) {
51
+ if (!projectPackageJsonPath) {
52
+ return { shouldHandoff: false, runtimeMode: "standalone" };
53
+ }
54
+ if (samePackageRoot(currentPackageJsonPath, projectPackageJsonPath)) {
55
+ return { shouldHandoff: false, runtimeMode: "project" };
56
+ }
57
+ if (isBootstrapped) {
58
+ return { shouldHandoff: false, runtimeMode: "standalone" };
59
+ }
60
+ return { shouldHandoff: true, runtimeMode: "project" };
61
+ }
62
+ function runProjectLocalServer(projectPackageJsonPath) {
63
+ const entry = resolveBinPath(projectPackageJsonPath);
64
+ const result = spawnSync(process.execPath, [entry, ...process.argv.slice(2)], {
65
+ stdio: "inherit",
66
+ env: {
67
+ ...process.env,
68
+ LETSRUNIT_MCP_BOOTSTRAPPED: "1",
69
+ LETSRUNIT_MCP_RUNTIME_MODE: "project"
70
+ }
71
+ });
72
+ if (result.error) throw result.error;
73
+ process.exit(result.status ?? 1);
74
+ }
75
+ function bootstrapProjectServer() {
76
+ const projectRoot = resolveProjectRoot();
77
+ const isBootstrapped = process.env.LETSRUNIT_MCP_BOOTSTRAPPED === "1";
78
+ const currentReq = createRequire(import.meta.url);
79
+ const currentPackageJsonPath = toRealpath(currentReq.resolve("../package.json"));
80
+ const projectPackageJsonPath = toRealpath(resolveFromProject("@letsrunit/mcp-server/package.json", projectRoot));
81
+ const decision = decideHandoff(currentPackageJsonPath, projectPackageJsonPath, isBootstrapped);
82
+ if (decision.shouldHandoff && projectPackageJsonPath) {
83
+ runProjectLocalServer(projectPackageJsonPath);
84
+ }
85
+ process.env.LETSRUNIT_MCP_RUNTIME_MODE = decision.runtimeMode;
86
+ return decision.runtimeMode;
577
87
  }
578
88
 
579
89
  // src/index.ts
580
90
  var { version } = createRequire(import.meta.url)("../package.json");
91
+ bootstrapProjectServer();
92
+ var { SessionManager } = await import('./sessions-BYH3NJQG.js');
93
+ var {
94
+ registerDebug,
95
+ registerDiagnostics,
96
+ registerDiff,
97
+ registerListSteps,
98
+ registerListSessions,
99
+ registerRun,
100
+ registerScreenshot,
101
+ registerSessionClose,
102
+ registerSessionStart,
103
+ registerSnapshot
104
+ } = await import('./tools-SAB75FOF.js');
581
105
  var sessions = new SessionManager();
582
106
  var server = new McpServer({
583
107
  name: "letsrunit",