@auracheck-ai/cli 0.2.2 → 0.2.5

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.
@@ -1,942 +1,2738 @@
1
- import { createRequire } from 'node:module';
2
- import { setTimeout as sleep } from 'node:timers/promises';
3
- import { Server } from '@modelcontextprotocol/sdk/server/index.js';
4
- import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
5
- import { CallToolRequestSchema, ListToolsRequestSchema, } from '@modelcontextprotocol/sdk/types.js';
6
- import { z } from 'zod';
7
- import { ApiError, SixSevenApi, TERMINAL_RUN_STATUSES, } from '../api.js';
8
- import { DEFAULT_EXCLUDE, getToken, resolveContext, } from '../config.js';
9
- import { SourceReader } from '../source-reader.js';
10
- const { version: CLI_VERSION } = createRequire(import.meta.url)('../../package.json');
11
- const tools = [
12
- // ---------- Whitebox: source code ----------
13
- {
14
- name: 'sixseven.read_code',
15
- description: 'Read a text file from the developer repo. Path is relative to repo root and must fall within configured codeRoots. Use to understand routes, components, validators, and fixtures before generating a testcase.',
16
- inputSchema: {
17
- type: 'object',
18
- properties: { path: { type: 'string' } },
19
- required: ['path'],
20
- },
21
- zod: z.object({ path: z.string().min(1) }),
22
- handler: async ({ path }, { reader }) => reader.readFile(path),
23
- },
24
- {
25
- name: 'sixseven.list_dir',
26
- description: 'List entries of a directory inside the developer repo. Path is relative to repo root.',
27
- inputSchema: {
28
- type: 'object',
29
- properties: { path: { type: 'string', default: '.' } },
30
- },
31
- zod: z.object({ path: z.string().default('.') }),
32
- handler: async ({ path }, { reader }) => reader.listDir(path),
33
- },
34
- {
35
- name: 'sixseven.search_code',
36
- description: 'Search developer repo (within codeRoots) for a substring or regex. Returns up to 200 matches with file + line + preview. Use to locate routes, handlers, components by name.',
37
- inputSchema: {
38
- type: 'object',
39
- properties: {
40
- query: { type: 'string' },
41
- regex: { type: 'boolean', default: false },
42
- caseSensitive: { type: 'boolean', default: false },
43
- maxResults: { type: 'number', default: 200 },
44
- },
45
- required: ['query'],
46
- },
47
- zod: z.object({
48
- query: z.string().min(1),
49
- regex: z.boolean().optional(),
50
- caseSensitive: z.boolean().optional(),
51
- maxResults: z.number().int().positive().max(1000).optional(),
52
- }),
53
- handler: async (args, { reader }) => reader.search(args.query, args),
54
- },
55
- // ---------- SixSeven: projects ----------
56
- {
57
- name: 'sixseven.list_projects',
58
- description: 'List the AuraCheck projects this sign-in can reach (id, name, platforms, defaultConfigurationId). Pass a project id as `projectId` to any project tool to work outside the repo-bound project.',
59
- inputSchema: { type: 'object', properties: {} },
60
- zod: z.object({}).passthrough(),
61
- handler: async (_args, { api }) => {
62
- const projects = await api.listProjects();
63
- return projects.map((p) => ({
64
- id: p.id,
65
- name: p.name,
66
- companyId: p.companyId,
67
- platforms: p.platforms,
68
- defaultConfigurationId: p.defaultConfigurationId ?? null,
69
- }));
70
- },
71
- },
72
- // ---------- SixSeven: features ----------
73
- {
74
- name: 'sixseven.list_features',
75
- description: 'List features (groups of testcases) for the bound SixSeven project. Each feature has an id and a name. Pick the most relevant feature id before creating a testcase.',
76
- inputSchema: { type: 'object', properties: {} },
77
- zod: z.object({}).passthrough(),
78
- handler: async (_args, { api, projectId }) => api.listFeatures(projectId),
79
- },
80
- {
81
- name: 'sixseven.create_feature',
82
- description: 'Create a new feature in the bound SixSeven project. Use when no existing feature fits the testcase you are about to create.',
83
- inputSchema: {
84
- type: 'object',
85
- properties: {
86
- name: { type: 'string' },
87
- path: { type: 'string' },
88
- description: { type: 'string' },
89
- prdContent: { type: 'string' },
90
- },
91
- required: ['name'],
92
- },
93
- zod: z.object({
94
- name: z.string().min(1),
95
- path: z.string().optional(),
96
- description: z.string().optional(),
97
- prdContent: z.string().optional(),
98
- }),
99
- handler: async (args, { api, projectId }) => api.createFeature(projectId, args),
100
- },
101
- // ---------- SixSeven: testcases ----------
102
- {
103
- name: 'sixseven.list_testcases',
104
- description: 'List testcases for the bound SixSeven project, optionally filtered by platform (web/android/ios).',
105
- inputSchema: {
106
- type: 'object',
107
- properties: {
108
- platform: { type: 'string', enum: ['web', 'android', 'ios'] },
109
- },
110
- },
111
- zod: z.object({ platform: z.enum(['web', 'android', 'ios']).optional() }),
112
- handler: async (args, { api, projectId }) => api.listTestCasesByProject(projectId, args.platform),
113
- },
114
- {
115
- name: 'sixseven.get_testcase',
116
- description: 'Fetch a single testcase by id. `steps` comes back as the Midscene YAML/JSON string the server stores, not an array — parse it before editing, and pass it back through sixseven.update_testcase in either form.',
117
- inputSchema: {
118
- type: 'object',
119
- properties: { id: { type: 'string' } },
120
- required: ['id'],
121
- },
122
- zod: z.object({ id: z.string().min(1) }),
123
- handler: async ({ id }, { api, projectId }) => api.getTestCase(id, projectId),
124
- },
125
- {
126
- name: 'sixseven.create_testcase',
127
- description: 'Create a new testcase under a SixSeven feature. `steps` is the Midscene flow: pass EITHER an array of flow items (each item is one action, e.g. { aiTap: "Sign in" }, { aiInput: "user@example.com", locate: "Email field" }, { aiAssert: "Dashboard is visible" }) OR a YAML/JSON string already shaped as `tasks: [{ name, flow: [...] }]`. Recognized action keys: aiTap, aiInput, aiAssert, aiQuery, aiHover, aiWaitFor, aiKeyboardPress, aiScroll, aiAction, sleep, javascript, aiUploadFile, aiHumanInput, aiExpectDownload, mailTmInbox, mailTmWaitOtp, mailTmWaitLink, otpInbox, otpWaitOtp. A bare array is auto-wrapped into the required tasks[] structure. If featureId is omitted, the project default from .sixseven/config.json is used.',
128
- inputSchema: {
129
- type: 'object',
130
- properties: {
131
- featureId: { type: 'string' },
132
- name: { type: 'string' },
133
- steps: {
134
- description: 'Array of Midscene flow items (auto-wrapped into tasks[]), or a YAML/JSON string shaped as `tasks: [{ name, flow: [...] }]`.',
135
- oneOf: [
136
- { type: 'array', items: { type: 'object' } },
137
- { type: 'string' },
138
- { type: 'object' },
139
- ],
140
- },
141
- executionType: {
142
- type: 'string',
143
- enum: ['automation', 'manual'],
144
- default: 'automation',
145
- description: 'Whether the automation job runs this case or a human does. Manual cases are excluded from automation runs. Defaults to "automation".',
146
- },
147
- priority: {
148
- type: 'string',
149
- enum: ['low', 'medium', 'high', 'critical'],
150
- default: 'medium',
151
- },
152
- category: { type: 'string', default: 'positive' },
153
- reason: { type: 'string' },
154
- description: { type: 'string' },
155
- expectedResult: { type: 'string' },
156
- platforms: { type: 'array', items: { type: 'string' } },
157
- coveredScenarios: { type: 'array', items: { type: 'string' } },
158
- tags: { type: 'array', items: { type: 'string' } },
159
- },
160
- required: ['name', 'steps'],
161
- },
162
- zod: z.object({
163
- featureId: z.string().optional(),
164
- name: z.string().min(1),
165
- steps: z.union([
166
- z.array(z.record(z.any())).min(1),
167
- z.string().min(1),
168
- z.record(z.any()),
169
- ]),
170
- executionType: z.enum(['automation', 'manual']).default('automation'),
171
- priority: z.enum(['low', 'medium', 'high', 'critical']).optional(),
172
- category: z.string().optional(),
173
- reason: z.string().optional(),
174
- description: z.string().optional(),
175
- expectedResult: z.string().optional(),
176
- platforms: z.array(z.string()).optional(),
177
- coveredScenarios: z.array(z.string()).optional(),
178
- tags: z.array(z.string()).optional(),
179
- }),
180
- handler: async (args, { api, defaultFeatureId }) => {
181
- const featureId = args.featureId ?? defaultFeatureId;
182
- if (!featureId) {
183
- throw new Error('No featureId provided and no defaultFeatureId in .sixseven/config.json. Call sixseven.list_features or sixseven.create_feature first.');
184
- }
185
- const { featureId: _ignore, ...payload } = args;
186
- return api.createTestCase(featureId, payload);
187
- },
188
- },
189
- {
190
- name: 'sixseven.update_testcase',
191
- description: 'Patch an existing testcase — only the fields you pass are touched. Useful in the auto-fix loop after reading evidence from a failed run. A `steps` patch accepts the same shapes as sixseven.create_testcase (flow array, or YAML/JSON string with tasks[]).',
192
- inputSchema: {
193
- type: 'object',
194
- properties: {
195
- id: { type: 'string' },
196
- patch: { type: 'object' },
197
- },
198
- required: ['id', 'patch'],
199
- },
200
- zod: z.object({ id: z.string().min(1), patch: z.record(z.any()) }),
201
- handler: async ({ id, patch }, { api }) => api.updateTestCase(id, patch),
202
- },
203
- // ---------- SixSeven: runs ----------
204
- {
205
- name: 'sixseven.list_runs',
206
- description: 'List recent runs for the bound SixSeven project, optionally filtered by platform.',
207
- inputSchema: {
208
- type: 'object',
209
- properties: {
210
- platform: { type: 'string', enum: ['web', 'android', 'ios'] },
211
- },
212
- },
213
- zod: z.object({ platform: z.enum(['web', 'android', 'ios']).optional() }),
214
- handler: async (args, { api, projectId }) => api.listRuns(projectId, args.platform),
215
- },
216
- {
217
- name: 'sixseven.get_run',
218
- description: 'Fetch a single run by id including current status, started/completed timestamps, and reportUrl when available.',
219
- inputSchema: {
220
- type: 'object',
221
- properties: { runId: { type: 'string' } },
222
- required: ['runId'],
223
- },
224
- zod: z.object({ runId: z.string().min(1) }),
225
- handler: async ({ runId }, { api }) => api.getRun(runId),
226
- },
227
- {
228
- name: 'sixseven.get_run_report',
229
- description: 'Results of a run as the Run Report groups them: case counts (passed/failed/skipped/pending) plus buckets — potential bugs (with bug report, severity), script issues, blocked cases and passed cases. Read-only.',
230
- inputSchema: {
231
- type: 'object',
232
- properties: { runId: { type: 'string' } },
233
- required: ['runId'],
234
- },
235
- zod: z.object({ runId: z.string().min(1) }),
236
- handler: async ({ runId }, { api }) => {
237
- const [run, counts, buckets] = await Promise.all([
238
- api.getRun(runId),
239
- api.getRunCaseStatusCounts(runId),
240
- api.getRunReportBuckets(runId),
241
- ]);
242
- return {
243
- run: {
244
- id: run.id,
245
- name: run.name,
246
- status: run.status,
247
- reportUrl: run.reportUrl ?? null,
248
- },
249
- counts,
250
- ...buckets,
251
- };
252
- },
253
- },
254
- {
255
- name: 'sixseven.create_run',
256
- description: 'Create a new run for one or more testcases. Defaults: caseSelectionMode="select", platform from .sixseven/config.json. Returns the created run object including its id.',
257
- inputSchema: {
258
- type: 'object',
259
- properties: {
260
- name: { type: 'string' },
261
- testCaseIds: { type: 'array', items: { type: 'string' } },
262
- featureIds: { type: 'array', items: { type: 'string' } },
263
- platform: { type: 'string', enum: ['web', 'android', 'ios'] },
264
- caseSelectionMode: { type: 'string', enum: ['all', 'select'] },
265
- configurationId: { type: 'string' },
266
- milestoneId: { type: 'string' },
267
- tags: { type: 'array', items: { type: 'string' } },
268
- notes: { type: 'string' },
269
- browserEngine: {
270
- type: 'string',
271
- enum: ['chrome', 'edge'],
272
- description: 'Leave unset: the cloud runner ships its own Chromium; chrome/edge only work on runners that have that browser installed.',
273
- },
274
- },
275
- required: ['name'],
276
- },
277
- zod: z.object({
278
- name: z.string().min(1),
279
- testCaseIds: z.array(z.string()).optional(),
280
- featureIds: z.array(z.string()).optional(),
281
- platform: z.enum(['web', 'android', 'ios']).optional(),
282
- caseSelectionMode: z.enum(['all', 'select']).optional(),
283
- configurationId: z.string().optional(),
284
- milestoneId: z.string().optional(),
285
- tags: z.array(z.string()).optional(),
286
- notes: z.string().optional(),
287
- browserEngine: z.enum(['chrome', 'edge']).optional(),
288
- }),
289
- handler: async (args, { api, projectId, defaultPlatform }) => {
290
- const body = {
291
- ...args,
292
- platform: args.platform ?? defaultPlatform,
293
- caseSelectionMode: args.caseSelectionMode ??
294
- (args.testCaseIds?.length ? 'select' : 'all'),
295
- };
296
- return api.createRun(projectId, body);
297
- },
298
- },
299
- {
300
- name: 'sixseven.execute_run',
301
- description: 'Trigger execution of an existing run. Fire-and-forget (202): the runner state lives in SixSeven. Use sixseven.wait_for_run to await terminal status.',
302
- inputSchema: {
303
- type: 'object',
304
- properties: {
305
- runId: { type: 'string' },
306
- },
307
- required: ['runId'],
308
- },
309
- zod: z.object({
310
- runId: z.string().min(1),
311
- }),
312
- handler: async ({ runId }, { api }) => api.executeRun(runId),
313
- },
314
- {
315
- name: 'sixseven.cancel_run',
316
- description: 'Cancel an in-flight run. Idempotent for queued runs; for inline runs the cancel may take effect at the next case boundary.',
317
- inputSchema: {
318
- type: 'object',
319
- properties: { runId: { type: 'string' } },
320
- required: ['runId'],
321
- },
322
- zod: z.object({ runId: z.string().min(1) }),
323
- handler: async ({ runId }, { api }) => api.cancelRun(runId),
324
- },
325
- {
326
- name: 'sixseven.wait_for_run',
327
- description: 'Poll a run until it reaches a terminal status (passed/failed/cancelled/error) or the timeout elapses. Returns the final run object plus a summary of per-case statuses. Default timeout 300 s, poll interval 3 s.',
328
- inputSchema: {
329
- type: 'object',
330
- properties: {
331
- runId: { type: 'string' },
332
- timeoutSec: { type: 'number', default: 300 },
333
- pollMs: { type: 'number', default: 3000 },
334
- },
335
- required: ['runId'],
336
- },
337
- zod: z.object({
338
- runId: z.string().min(1),
339
- timeoutSec: z.number().int().positive().max(3600).optional(),
340
- pollMs: z.number().int().positive().max(30_000).optional(),
341
- }),
342
- handler: async (args, { api, baseUrl }) => {
343
- const timeoutMs = (args.timeoutSec ?? 300) * 1000;
344
- const pollMs = args.pollMs ?? 3000;
345
- const start = Date.now();
346
- let last = await api.getRun(args.runId);
347
- while (!TERMINAL_RUN_STATUSES.has(last.status) &&
348
- Date.now() - start < timeoutMs) {
349
- await sleep(pollMs);
350
- last = await api.getRun(args.runId);
351
- }
352
- const terminal = TERMINAL_RUN_STATUSES.has(last.status);
353
- const attempts = await api
354
- .listRunCaseAttempts(args.runId)
355
- .catch(() => ({ attempts: [] }));
356
- const summary = attempts.attempts.reduce((acc, a) => {
357
- acc[a.status] = (acc[a.status] ?? 0) + 1;
358
- return acc;
359
- }, {});
360
- return {
361
- terminal,
362
- elapsedMs: Date.now() - start,
363
- runId: args.runId,
364
- status: last.status,
365
- reportUrl: last.reportUrl ?? null,
366
- viewUrl: `${baseUrl}/runs/${args.runId}`,
367
- completedAt: last.completedAt ?? null,
368
- caseStatusSummary: summary,
369
- run: last,
370
- };
371
- },
372
- },
373
- {
374
- name: 'sixseven.list_run_testcases',
375
- description: 'List the testcases attached to a specific run.',
376
- inputSchema: {
377
- type: 'object',
378
- properties: { runId: { type: 'string' } },
379
- required: ['runId'],
380
- },
381
- zod: z.object({ runId: z.string().min(1) }),
382
- handler: async ({ runId }, { api }) => api.listRunTestCases(runId),
383
- },
384
- {
385
- name: 'sixseven.get_evidence',
386
- description: 'Aggregate evidence for a finished (or in-progress) run: per-case attempts, latest step events, failed-step screenshots and error messages, and the SixSeven report URL. A failed step that hung (tripped the per-step watchdog) also carries stallDiagnostics — a captured process tree, host memory pressure, CDP probe results, and in-flight requests — so a renderer stall can be diagnosed here instead of by shelling into production. Filter by caseId to narrow scope. Use after sixseven.wait_for_run to diagnose failures.',
387
- inputSchema: {
388
- type: 'object',
389
- properties: {
390
- runId: { type: 'string' },
391
- caseId: { type: 'string' },
392
- maxEventsPerCase: { type: 'number', default: 20 },
393
- },
394
- required: ['runId'],
395
- },
396
- zod: z.object({
397
- runId: z.string().min(1),
398
- caseId: z.string().optional(),
399
- maxEventsPerCase: z.number().int().positive().max(200).optional(),
400
- }),
401
- handler: async (args, { api, baseUrl }) => {
402
- const max = args.maxEventsPerCase ?? 20;
403
- const [run, attemptsResp, eventsResp, runCases] = await Promise.all([
404
- api.getRun(args.runId),
405
- api.listRunCaseAttempts(args.runId),
406
- api.listRunStepEvents(args.runId, args.caseId),
407
- api.listRunTestCases(args.runId).catch(() => []),
408
- ]);
409
- const caseNameById = new Map(runCases.map((c) => [c.id, c.name]));
410
- const allEvents = eventsResp.events ?? [];
411
- const eventsByCase = new Map();
412
- for (const e of allEvents) {
413
- const key = e.testCaseId ?? '__unbound__';
414
- if (args.caseId && key !== args.caseId)
415
- continue;
416
- const arr = eventsByCase.get(key) ?? [];
417
- arr.push(e);
418
- eventsByCase.set(key, arr);
419
- }
420
- const attempts = (attemptsResp.attempts ?? []).filter((a) => !args.caseId || a.testCaseId === args.caseId);
421
- const cases = attempts.map((attempt) => {
422
- const events = (eventsByCase.get(attempt.testCaseId) ?? [])
423
- .slice()
424
- .sort((a, b) => (a.stepIndex ?? 0) - (b.stepIndex ?? 0))
425
- .slice(0, max);
426
- const failedSteps = events.filter((e) => e.status === 'failed' || e.error);
427
- return {
428
- testCaseId: attempt.testCaseId,
429
- testCaseName: caseNameById.get(attempt.testCaseId) ?? null,
430
- attemptId: attempt.id,
431
- attemptStatus: attempt.status,
432
- attemptReportUrl: attempt.reportUrl ?? null,
433
- startedAt: attempt.startedAt,
434
- completedAt: attempt.completedAt,
435
- stepEvents: events.map((e) => ({
436
- stepIndex: e.stepIndex,
437
- stepType: e.stepType,
438
- stepPrompt: e.stepPrompt,
439
- status: e.status,
440
- durationMs: e.durationMs,
441
- error: e.error,
442
- screenshotUrl: e.screenshotUrl,
443
- notes: e.notes,
444
- })),
445
- failedSteps: failedSteps.map((e) => ({
446
- stepIndex: e.stepIndex,
447
- stepType: e.stepType,
448
- error: e.error,
449
- screenshotUrl: e.screenshotUrl,
450
- // Present only for a step that tripped the per-step watchdog —
451
- // process tree / host pressure / CDP probes captured right
452
- // before teardown. Lets a stall be diagnosed here instead of by
453
- // SSH-ing into prod to grep an already-rotated container log.
454
- stallDiagnostics: e.stallDiagnostics ?? null,
455
- })),
456
- };
457
- });
458
- return {
459
- runId: args.runId,
460
- status: run.status,
461
- platform: run.platform,
462
- reportUrl: run.reportUrl ?? null,
463
- viewUrl: `${baseUrl}/runs/${args.runId}`,
464
- cases,
465
- totals: {
466
- caseCount: cases.length,
467
- failedCaseCount: cases.filter((c) => c.attemptStatus === 'failed')
468
- .length,
469
- failedStepCount: cases.reduce((n, c) => n + c.failedSteps.length, 0),
470
- },
471
- };
472
- },
473
- },
474
- {
475
- name: 'sixseven.get_screenshot',
476
- description: "Download a run screenshot (or any authenticated blob) to a local file and return its path, so it can then be opened and looked at. Pass a `screenshotUrl` straight from sixseven.get_evidence — those are bare paths that cannot be fetched without the bound base URL and CI token, so this is the only way to actually SEE a step's screenshot. Reach for it whenever a failure's cause is visual: 'the page froze' is often disproved by two consecutive screenshots being identical, or by the page rendering fine with a control merely disabled.",
477
- inputSchema: {
478
- type: 'object',
479
- properties: {
480
- url: {
481
- type: 'string',
482
- description: "screenshotUrl from get_evidence, e.g. '/api/blob/screenshots/<runId>/<caseId>-step14.png'. An absolute URL is accepted only on the bound host.",
483
- },
484
- outPath: {
485
- type: 'string',
486
- description: 'Where to write it. Defaults to a temp file named after the blob.',
487
- },
488
- },
489
- required: ['url'],
490
- },
491
- zod: z.object({
492
- url: z.string().min(1),
493
- outPath: z.string().optional(),
494
- }),
495
- handler: async (args, { api }) => {
496
- const { tmpdir } = await import('node:os');
497
- const path = await import('node:path');
498
- // Name the temp file after the blob so several screenshots from one
499
- // investigation stay tellable apart on disk.
500
- const base = path.basename(args.url.split('?')[0] || '').replace(/[^\w.-]/g, '_') ||
501
- 'screenshot.png';
502
- const dest = args.outPath ?? path.join(tmpdir(), `sixseven-${Date.now()}-${base}`);
503
- const res = await api.downloadBlob(args.url, dest);
504
- return {
505
- ...res,
506
- hint: 'Open this path with your file-reading tool to view the image.',
507
- };
508
- },
509
- },
510
- // ---------- SixSeven: schedules (recurring runs) ----------
511
- {
512
- name: 'sixseven.list_schedules',
513
- description: 'List the recurring run schedules of the bound SixSeven project. Each schedule carries its cron expressions, IANA timezone, computed nextFireAt (UTC), platform, case filter and notify recipients.',
514
- inputSchema: { type: 'object', properties: {} },
515
- zod: z.object({}).passthrough(),
516
- handler: async (_args, { api, projectId }) => api.listSchedules(projectId),
517
- },
518
- {
519
- name: 'sixseven.get_schedule',
520
- description: 'Fetch a single schedule by id. Note lastFiredAt reflects CLOCK-driven fires only — sixseven.run_schedule_now deliberately leaves it untouched, so read sixseven.list_schedule_fires for the full history.',
521
- inputSchema: {
522
- type: 'object',
523
- properties: { scheduleId: { type: 'string' } },
524
- required: ['scheduleId'],
525
- },
526
- zod: z.object({ scheduleId: z.string().min(1) }),
527
- handler: async ({ scheduleId }, { api }) => api.getSchedule(scheduleId),
528
- },
529
- {
530
- name: 'sixseven.create_schedule',
531
- description: "Create a recurring run schedule. cronExpressions is 5-field cron evaluated in `timezone` (IANA, e.g. 'Asia/Jakarta'); several expressions are allowed and the earliest upcoming occurrence wins. caseFilter picks what runs: { mode: 'all' } for every case on the platform, or { mode: 'feature', featureIds: [...] } to narrow (get ids from sixseven.list_features). notifyUserIds must come from sixseven.list_schedule_recipients. Cron and timezone are validated server-side — an invalid cadence is rejected, never silently accepted. Prefer enabled:false while testing, then enable once the cadence reads right.",
532
- inputSchema: {
533
- type: 'object',
534
- properties: {
535
- name: { type: 'string' },
536
- cronExpressions: {
537
- type: 'array',
538
- items: { type: 'string' },
539
- minItems: 1,
540
- description: "5-field cron, e.g. ['0 9 * * 1-5'] for weekdays 09:00.",
541
- },
542
- timezone: {
543
- type: 'string',
544
- description: "IANA timezone the cron is evaluated in, e.g. 'Asia/Jakarta'.",
545
- },
546
- platform: { type: 'string', enum: ['web', 'android', 'ios'] },
547
- enabled: { type: 'boolean', default: true },
548
- configurationId: {
549
- type: 'string',
550
- description: 'Environment the runs execute against. Omit ONLY when the project has a default configuration — without either, every run this schedule creates starts with no base URL and fails at the first navigation.',
551
- },
552
- caseFilter: {
553
- type: 'object',
554
- properties: {
555
- mode: { type: 'string', enum: ['all', 'feature'] },
556
- featureIds: { type: 'array', items: { type: 'string' } },
557
- },
558
- required: ['mode'],
559
- },
560
- notifyUserIds: { type: 'array', items: { type: 'string' } },
561
- misfireGraceMinutes: {
562
- type: 'number',
563
- description: 'How late a clock-driven occurrence may still fire before it is skipped as a misfire.',
564
- },
565
- },
566
- required: ['name', 'cronExpressions', 'timezone'],
567
- },
568
- zod: z.object({
569
- name: z.string().min(1),
570
- cronExpressions: z.array(z.string().min(1)).min(1),
571
- timezone: z.string().min(1),
572
- platform: z.enum(['web', 'android', 'ios']).optional(),
573
- enabled: z.boolean().optional(),
574
- configurationId: z.string().optional(),
575
- caseFilter: z
576
- .object({
577
- mode: z.enum(['all', 'feature']),
578
- featureIds: z.array(z.string()).default([]),
579
- })
580
- .optional(),
581
- notifyUserIds: z.array(z.string().uuid()).optional(),
582
- misfireGraceMinutes: z.number().int().positive().optional(),
583
- }),
584
- handler: async (args, { api, projectId, defaultPlatform }) => {
585
- // Caught here rather than server-side: the API accepts feature mode with
586
- // an empty id list, and the schedule then fires forever into 'no_cases'.
587
- if (args.caseFilter?.mode === 'feature' &&
588
- !args.caseFilter.featureIds.length) {
589
- throw new Error("caseFilter.mode 'feature' needs at least one featureId — otherwise every fire resolves to zero cases. Call sixseven.list_features, or use { mode: 'all' }.");
590
- }
591
- const schedule = await api.createSchedule(projectId, {
592
- ...args,
593
- platform: args.platform ?? defaultPlatform,
594
- });
595
- // A schedule with no configuration — its own or the project's default —
596
- // is accepted by the API and then produces runs that cannot navigate
597
- // anywhere. Say so at creation instead of at the first 3 a.m. failure.
598
- let warning = null;
599
- if (!schedule.configurationId) {
600
- const project = await api.getProject(projectId).catch(() => null);
601
- if (project && !project.defaultConfigurationId) {
602
- warning =
603
- 'This schedule has no configurationId and the project has no default configuration, so its runs will start without a base URL and fail at the first navigation. Set configurationId via sixseven.update_schedule.';
604
- }
605
- }
606
- return { ...schedule, warning };
607
- },
608
- },
609
- {
610
- name: 'sixseven.update_schedule',
611
- description: 'Patch an existing schedule — pause it (enabled:false), change cadence, retarget its configuration, or edit notify recipients. Only the fields you pass are touched; changing cronExpressions or timezone recomputes nextFireAt.',
612
- inputSchema: {
613
- type: 'object',
614
- properties: {
615
- scheduleId: { type: 'string' },
616
- patch: {
617
- type: 'object',
618
- description: 'Any subset of: name, cronExpressions, timezone, platform, enabled, configurationId (null clears), caseFilter, notifyUserIds, misfireGraceMinutes.',
619
- },
620
- },
621
- required: ['scheduleId', 'patch'],
622
- },
623
- zod: z.object({
624
- scheduleId: z.string().min(1),
625
- patch: z.record(z.any()),
626
- }),
627
- handler: async ({ scheduleId, patch }, { api }) => api.updateSchedule(scheduleId, patch),
628
- },
629
- {
630
- name: 'sixseven.delete_schedule',
631
- description: 'Delete a schedule permanently. Runs it already created are kept; only the cadence goes away. Prefer sixseven.update_schedule with enabled:false when you just want to pause it.',
632
- inputSchema: {
633
- type: 'object',
634
- properties: { scheduleId: { type: 'string' } },
635
- required: ['scheduleId'],
636
- },
637
- zod: z.object({ scheduleId: z.string().min(1) }),
638
- handler: async ({ scheduleId }, { api }) => {
639
- await api.deleteSchedule(scheduleId);
640
- return { ok: true, deletedScheduleId: scheduleId };
641
- },
642
- },
643
- {
644
- name: 'sixseven.run_schedule_now',
645
- description: "Fire a schedule immediately on the identical code path the clock uses — the real end-to-end test of a cadence, and it works on a paused (enabled:false) schedule too. Returns { outcome, runId }: 'run_created' means a run was started (feed runId to sixseven.wait_for_run), while 'skipped_overlap' means a previous run of this schedule is still live and 'no_cases' means the case filter matched nothing. Skips are reported, not thrown.",
646
- inputSchema: {
647
- type: 'object',
648
- properties: { scheduleId: { type: 'string' } },
649
- required: ['scheduleId'],
650
- },
651
- zod: z.object({ scheduleId: z.string().min(1) }),
652
- handler: async ({ scheduleId }, { api, baseUrl }) => {
653
- const { outcome, skipped } = await api.runScheduleNow(scheduleId);
654
- // The route answers with the outcome alone, so the runId — the one thing
655
- // a caller needs next — is read back from the fire it just recorded.
656
- let runId = null;
657
- if (outcome === 'run_created') {
658
- const fires = await api
659
- .listScheduleFires(scheduleId)
660
- .catch(() => ({ items: [], hasMore: false }));
661
- runId = fires.items[0]?.runId ?? null;
662
- }
663
- return {
664
- scheduleId,
665
- outcome,
666
- skipped,
667
- runId,
668
- viewUrl: runId ? `${baseUrl}/runs/${runId}` : null,
669
- };
670
- },
671
- },
672
- {
673
- name: 'sixseven.list_schedule_fires',
674
- description: "History of a schedule's occurrences, newest first: when it fired, the outcome, and the run it created (if any). This is the place to find out why a schedule appeared to do nothing — skipped_overlap, skipped_misfire, skipped_capacity, and no_cases all show up here.",
675
- inputSchema: {
676
- type: 'object',
677
- properties: {
678
- scheduleId: { type: 'string' },
679
- page: { type: 'number', default: 1 },
680
- },
681
- required: ['scheduleId'],
682
- },
683
- zod: z.object({
684
- scheduleId: z.string().min(1),
685
- page: z.number().int().positive().optional(),
686
- }),
687
- handler: async ({ scheduleId, page }, { api }) => api.listScheduleFires(scheduleId, page),
688
- },
689
- {
690
- name: 'sixseven.list_schedule_recipients',
691
- description: "The users that may be put in a schedule's notifyUserIds. Resolved exactly the way the server resolves recipients at send time, so a user missing from this list would silently receive nothing if added anyway — including, possibly, your own account.",
692
- inputSchema: { type: 'object', properties: {} },
693
- zod: z.object({}).passthrough(),
694
- handler: async (_args, { api, projectId }) => api.listScheduleRecipients(projectId),
695
- },
696
- // ---------- SixSeven: auto-explore ----------
697
- {
698
- name: 'sixseven.start_exploration',
699
- description: "Trigger SixSeven's BFS crawler (Puppeteer-based, runs server-side) on a set of seed URLs for the bound project. Login via EXPLORER_USERNAME/PASSWORD is automatic when configured. Returns a snapshot immediately (job runs in background); poll with sixseven.get_exploration. One job per project at a time — calling this while a job is already running returns the live snapshot.",
700
- inputSchema: {
701
- type: 'object',
702
- properties: {
703
- seedUrls: { type: 'array', items: { type: 'string' }, minItems: 1 },
704
- configurationId: { type: 'string' },
705
- maxDepth: { type: 'number' },
706
- maxPages: { type: 'number' },
707
- },
708
- required: ['seedUrls'],
709
- },
710
- zod: z.object({
711
- seedUrls: z.array(z.string().url()).min(1),
712
- configurationId: z.string().optional(),
713
- maxDepth: z.number().int().positive().max(20).optional(),
714
- maxPages: z.number().int().positive().max(500).optional(),
715
- }),
716
- handler: async (args, { api, projectId }) => api.startExploration(projectId, args),
717
- },
718
- {
719
- name: 'sixseven.get_exploration',
720
- description: 'Return the latest exploration snapshot for the bound project (or null if none has ever run). Shape: { jobId, status, visited, anchorsUpserted, loggedIn, errors[] }. Use to await completion before generating testcases that depend on discovered routes/anchors.',
721
- inputSchema: { type: 'object', properties: {} },
722
- zod: z.object({}).passthrough(),
723
- handler: async (_args, { api, projectId }) => api.getExploration(projectId),
724
- },
725
- // ---------- SixSeven: bug filing ----------
726
- {
727
- name: 'sixseven.file_bug',
728
- description: "Open an issue report (bug) against the bound SixSeven project. Use this only after the auto-fix loop has identified a real application defect (not a flaky testcase). Severity must be 'critical', 'high', 'medium', or 'low'. Pass evidence URLs (screenshotUrl from sixseven.get_evidence) in evidences[].",
729
- inputSchema: {
730
- type: 'object',
731
- properties: {
732
- title: { type: 'string' },
733
- severity: {
734
- type: 'string',
735
- enum: ['critical', 'high', 'medium', 'low'],
736
- },
737
- description: { type: 'string' },
738
- pageUrl: { type: 'string' },
739
- evidences: { type: 'array', items: { type: 'string' } },
740
- },
741
- required: ['title', 'severity'],
742
- },
743
- zod: z.object({
744
- title: z.string().min(1).max(200),
745
- severity: z.enum(['critical', 'high', 'medium', 'low']),
746
- description: z.string().optional(),
747
- pageUrl: z.string().optional(),
748
- evidences: z.array(z.string()).optional(),
749
- }),
750
- handler: async (args, { api, projectId }) => api.createIssueReport({ ...args, projectId }),
751
- },
752
- {
753
- name: 'sixseven.list_bugs',
754
- description: 'List issue reports (bugs) for the bound SixSeven project. Use to check whether a defect has already been reported before filing a new one.',
755
- inputSchema: { type: 'object', properties: {} },
756
- zod: z.object({}).passthrough(),
757
- handler: async (_args, { api, projectId }) => api.listIssueReports(projectId),
758
- },
759
- {
760
- name: 'sixseven.get_bug',
761
- description: 'Fetch a single issue report by id.',
762
- inputSchema: {
763
- type: 'object',
764
- properties: { id: { type: 'string' } },
765
- required: ['id'],
766
- },
767
- zod: z.object({ id: z.string().min(1) }),
768
- handler: async ({ id }, { api }) => api.getIssueReport(id),
769
- },
770
- // ---------- SixSeven: project context ----------
771
- {
772
- name: 'sixseven.whoami',
773
- description: 'Return the signed-in AuraCheck user, the base URL, how the token was supplied, and the project this MCP session is bound to (null = pass projectId to project tools; see sixseven.list_projects).',
774
- inputSchema: { type: 'object', properties: {} },
775
- zod: z.object({}).passthrough(),
776
- handler: async (_args, { api, boundProjectId, baseUrl, tokenSource }) => {
777
- const [user, project] = await Promise.all([
778
- api.me(),
779
- boundProjectId
780
- ? api.getProject(boundProjectId).catch(() => null)
781
- : Promise.resolve(null),
782
- ]);
783
- return {
784
- user,
785
- baseUrl,
786
- tokenSource,
787
- cliVersion: CLI_VERSION,
788
- projectId: boundProjectId,
789
- project,
790
- };
1
+ // src/mcp/server.ts
2
+ import { hostname } from "os";
3
+
4
+ // ../mcp-core/dist/api.js
5
+ var ApiError = class extends Error {
6
+ status;
7
+ bodyText;
8
+ constructor(status, bodyText, message) {
9
+ super(message);
10
+ this.status = status;
11
+ this.bodyText = bodyText;
12
+ this.name = "ApiError";
13
+ }
14
+ };
15
+ var DEFAULT_SIGN_IN_HINT = "Sign in again.";
16
+ function authHint(status, serverError, signInHint = DEFAULT_SIGN_IN_HINT) {
17
+ if (status === 401) {
18
+ return `Your AuraCheck sign-in is missing, expired or revoked. ${signInHint}`;
19
+ }
20
+ if (status === 403 && /limited to another project/i.test(serverError)) {
21
+ return "This token is a project CI token and only reaches its own project. Sign in personally, or pass that projectId.";
22
+ }
23
+ return null;
24
+ }
25
+ function normalizeBaseUrl(u) {
26
+ return u.replace(new RegExp("\\p{Cc}", "gu"), "").trim().replace(/\/+$/, "");
27
+ }
28
+ function normalizeStepsToYaml(steps, caseName = "") {
29
+ if (typeof steps === "string")
30
+ return steps;
31
+ if (Array.isArray(steps)) {
32
+ return JSON.stringify({
33
+ tasks: [{ name: caseName || "Main flow", flow: steps }]
34
+ });
35
+ }
36
+ if (steps && typeof steps === "object") {
37
+ const obj = steps;
38
+ if (Array.isArray(obj.tasks))
39
+ return JSON.stringify(obj);
40
+ if (Array.isArray(obj.flow)) {
41
+ return JSON.stringify({
42
+ tasks: [{ name: caseName || "Main flow", flow: obj.flow }]
43
+ });
44
+ }
45
+ }
46
+ throw new Error('steps must be a YAML string, an array of Midscene flow items (e.g. [{ aiTap: "Sign in" }, { aiInput: "user@example.com", locate: "Email field" }]), or an object with a tasks[] array.');
47
+ }
48
+ var AuraCheckApi = class {
49
+ baseUrl;
50
+ token;
51
+ timeoutMs;
52
+ fetchImpl;
53
+ extraHeaders;
54
+ dispatcher;
55
+ signInHint;
56
+ constructor(opts) {
57
+ this.baseUrl = normalizeBaseUrl(opts.baseUrl);
58
+ this.token = opts.token;
59
+ this.timeoutMs = opts.timeoutMs ?? 3e4;
60
+ this.fetchImpl = opts.fetchImpl ?? fetch;
61
+ this.extraHeaders = opts.extraHeaders ?? {};
62
+ this.dispatcher = opts.dispatcher;
63
+ this.signInHint = opts.signInHint ?? DEFAULT_SIGN_IN_HINT;
64
+ }
65
+ /** Spreads `{ dispatcher }` into a fetch init only when one was given. */
66
+ dispatcherInit() {
67
+ return this.dispatcher ? { dispatcher: this.dispatcher } : {};
68
+ }
69
+ async request(method, path3, body) {
70
+ const url = `${this.baseUrl}${path3}`;
71
+ const headers = {
72
+ Authorization: `Bearer ${this.token}`,
73
+ Accept: "application/json",
74
+ ...this.extraHeaders
75
+ };
76
+ let payload;
77
+ if (body !== void 0) {
78
+ headers["Content-Type"] = "application/json";
79
+ payload = JSON.stringify(body);
80
+ }
81
+ const controller = new AbortController();
82
+ const timer = setTimeout(() => controller.abort(), this.timeoutMs);
83
+ let res;
84
+ try {
85
+ res = await this.fetchImpl(url, {
86
+ method,
87
+ headers,
88
+ body: payload,
89
+ signal: controller.signal,
90
+ ...this.dispatcherInit()
91
+ });
92
+ } catch (err) {
93
+ throw new ApiError(0, "", `Network error calling ${url}: ${err.message}`);
94
+ } finally {
95
+ clearTimeout(timer);
96
+ }
97
+ const text = await res.text();
98
+ if (!res.ok) {
99
+ let msg = `${method} ${path3} -> ${res.status}`;
100
+ let serverError = "";
101
+ try {
102
+ const parsed = JSON.parse(text);
103
+ if (parsed?.error)
104
+ serverError = String(parsed.error);
105
+ } catch {
106
+ serverError = text.slice(0, 200);
107
+ }
108
+ if (serverError)
109
+ msg += `: ${serverError}`;
110
+ const hint = authHint(res.status, serverError, this.signInHint);
111
+ if (hint)
112
+ msg += `. ${hint}`;
113
+ throw new ApiError(res.status, text, msg);
114
+ }
115
+ if (!text)
116
+ return void 0;
117
+ try {
118
+ return JSON.parse(text);
119
+ } catch {
120
+ return text;
121
+ }
122
+ }
123
+ // --- Auth ---
124
+ async me() {
125
+ return this.request("GET", "/api/auth/me");
126
+ }
127
+ // --- MCP context (role/subscription awareness; §3.4) ---
128
+ async mcpContext() {
129
+ return this.request("GET", "/api/mcp/context");
130
+ }
131
+ // --- Projects ---
132
+ async listProjects() {
133
+ return this.request("GET", "/api/projects");
134
+ }
135
+ async getProject(projectId) {
136
+ return this.request("GET", `/api/projects/${projectId}`);
137
+ }
138
+ async createProject(input) {
139
+ return this.request("POST", "/api/projects", input);
140
+ }
141
+ // --- Features ---
142
+ async listFeatures(projectId) {
143
+ return this.request("GET", `/api/projects/${projectId}/features`);
144
+ }
145
+ async createFeature(projectId, input) {
146
+ return this.request("POST", `/api/projects/${projectId}/features`, input);
147
+ }
148
+ /** There is no `GET /api/features/:id`; look it up via the project's list. */
149
+ async getFeature(id, projectId) {
150
+ const all = await this.listFeatures(projectId);
151
+ return all.find((f) => f.id === id) ?? null;
152
+ }
153
+ /**
154
+ * Delete a feature. Not a blanket cascade: its own test cases that are
155
+ * linked to a run are soft-deleted (reparented onto the feature's parent,
156
+ * run history intact) while unlinked ones are hard-deleted; descendant
157
+ * features are removed once their cases are cleared. `cascade` also
158
+ * removes any sub-features (same per-case split applies to their cases).
159
+ */
160
+ async deleteFeature(id, cascade = false) {
161
+ const qs = cascade ? "?cascade=true" : "";
162
+ await this.request("DELETE", `/api/features/${id}${qs}`);
163
+ }
164
+ // --- Test cases ---
165
+ async listTestCasesByProject(projectId, platform) {
166
+ const qs = platform ? `?platform=${encodeURIComponent(platform)}` : "";
167
+ return this.request("GET", `/api/projects/${projectId}/test-cases${qs}`);
168
+ }
169
+ async listTestCasesByFeature(featureId) {
170
+ return this.request("GET", `/api/features/${featureId}/test-cases`);
171
+ }
172
+ async createTestCase(featureId, input) {
173
+ const body = {
174
+ ...input,
175
+ steps: normalizeStepsToYaml(input.steps, input.name),
176
+ executionType: input.executionType ?? "automation"
177
+ };
178
+ return this.request("POST", `/api/features/${featureId}/test-cases`, body);
179
+ }
180
+ /**
181
+ * Fetch one test case. There is no `GET /api/test-cases/:id` on the server
182
+ * — only PUT, DELETE and sub-routes — so this reads via the project list.
183
+ */
184
+ async getTestCase(id, projectId) {
185
+ const all = await this.listTestCasesByProject(projectId);
186
+ const found = all.find((c) => c.id === id);
187
+ if (!found) {
188
+ throw new ApiError(404, "", `Test case ${id} not found in project ${projectId}`);
189
+ }
190
+ return found;
191
+ }
192
+ /**
193
+ * Patch a test case. PUT, not PATCH: the server defines no PATCH handler
194
+ * for this path, while its PUT handler is explicitly partial.
195
+ */
196
+ async updateTestCase(id, patch) {
197
+ const body = patch && typeof patch === "object" && patch.steps !== void 0 ? {
198
+ ...patch,
199
+ steps: normalizeStepsToYaml(patch.steps, typeof patch.name === "string" ? patch.name : "")
200
+ } : patch;
201
+ return this.request("PUT", `/api/test-cases/${id}`, body);
202
+ }
203
+ /**
204
+ * Delete test cases. A single id goes through `DELETE /api/test-cases/:id`;
205
+ * several go through `DELETE /api/test-cases/bulk` (max 500 ids). Either
206
+ * way the server splits per case: one already linked to a run is
207
+ * soft-deleted, an unlinked one is hard-deleted.
208
+ */
209
+ async deleteTestCases(ids) {
210
+ if (ids.length === 1) {
211
+ await this.request("DELETE", `/api/test-cases/${ids[0]}`);
212
+ return { hardDeleted: null, softDeleted: null };
213
+ }
214
+ return this.request("DELETE", "/api/test-cases/bulk", { ids });
215
+ }
216
+ // --- Prompt-to-test (test_my_flow) ---
217
+ async previewPromptTest(projectId, input) {
218
+ return this.request("POST", `/api/projects/${projectId}/prompt-tests/preview`, input);
219
+ }
220
+ async createPromptTestRun(projectId, input) {
221
+ return this.request("POST", `/api/projects/${projectId}/prompt-tests`, {
222
+ url: input.url,
223
+ prompt: input.prompt,
224
+ plan: input.plan
225
+ });
226
+ }
227
+ // --- Runs ---
228
+ async listRuns(projectId, platform) {
229
+ const qs = platform ? `?platform=${encodeURIComponent(platform)}` : "";
230
+ return this.request("GET", `/api/projects/${projectId}/runs${qs}`);
231
+ }
232
+ async createRun(projectId, input) {
233
+ return this.request("POST", `/api/projects/${projectId}/runs`, input);
234
+ }
235
+ async getRun(runId) {
236
+ return this.request("GET", `/api/runs/${runId}`);
237
+ }
238
+ /** Result buckets the Run Report shows (bugs / script issues / blocked / passed). */
239
+ async getRunReportBuckets(runId) {
240
+ return this.request("GET", `/api/runs/${runId}/report-buckets`);
241
+ }
242
+ async getRunCaseStatusCounts(runId) {
243
+ return this.request("GET", `/api/runs/${runId}/case-status-counts`);
244
+ }
245
+ async executeRun(runId) {
246
+ return this.request("POST", `/api/runs/${runId}/execute`, {});
247
+ }
248
+ async cancelRun(runId) {
249
+ return this.request("POST", `/api/runs/${runId}/cancel`, {});
250
+ }
251
+ async listRunTestCases(runId) {
252
+ return this.request("GET", `/api/runs/${runId}/test-cases`);
253
+ }
254
+ async listRunCaseAttempts(runId) {
255
+ return this.request("GET", `/api/runs/${runId}/case-attempts`);
256
+ }
257
+ async listRunStepEvents(runId, testCaseId) {
258
+ const qs = testCaseId ? `?testCaseId=${encodeURIComponent(testCaseId)}` : "";
259
+ return this.request("GET", `/api/runs/${runId}/events${qs}`);
260
+ }
261
+ // --- Schedules (recurring runs) ---
262
+ async listSchedules(projectId) {
263
+ return this.request("GET", `/api/projects/${projectId}/schedules`);
264
+ }
265
+ async createSchedule(projectId, input) {
266
+ return this.request("POST", `/api/projects/${projectId}/schedules`, input);
267
+ }
268
+ async getSchedule(id) {
269
+ return this.request("GET", `/api/schedules/${id}`);
270
+ }
271
+ async updateSchedule(id, patch) {
272
+ return this.request("PATCH", `/api/schedules/${id}`, patch);
273
+ }
274
+ /** Server replies 204 with no body; resolves to void on success. */
275
+ async deleteSchedule(id) {
276
+ await this.request("DELETE", `/api/schedules/${id}`);
277
+ }
278
+ async listScheduleFires(id, page) {
279
+ const qs = page && page > 1 ? `?page=${page}` : "";
280
+ return this.request("GET", `/api/schedules/${id}/fires${qs}`);
281
+ }
282
+ async listScheduleRecipients(projectId) {
283
+ return this.request("GET", `/api/projects/${projectId}/schedules/assignable-users`);
284
+ }
285
+ /**
286
+ * Fire a schedule immediately. The route answers 202 for `run_created` and
287
+ * 409 for every skip (`skipped_overlap` above all). A skip is a real,
288
+ * informative answer, not a transport failure, so it is unwrapped back
289
+ * into a normal result; only a genuine error (404, 500, network) still
290
+ * throws.
291
+ */
292
+ async runScheduleNow(id) {
293
+ try {
294
+ const res = await this.request("POST", `/api/schedules/${id}/run-now`, {});
295
+ return { outcome: res.outcome, skipped: false };
296
+ } catch (err) {
297
+ if (err instanceof ApiError && err.status === 409) {
298
+ try {
299
+ const parsed = JSON.parse(err.bodyText);
300
+ if (parsed?.outcome)
301
+ return { outcome: parsed.outcome, skipped: true };
302
+ } catch {
303
+ }
304
+ }
305
+ throw err;
306
+ }
307
+ }
308
+ // --- Issue reports (bugs) ---
309
+ async createIssueReport(input) {
310
+ return this.request("POST", "/api/issue-reports", input);
311
+ }
312
+ async listIssueReports(projectId) {
313
+ const qs = projectId ? `?projectId=${encodeURIComponent(projectId)}` : "";
314
+ const resp = await this.request("GET", `/api/issue-reports${qs}`);
315
+ if (Array.isArray(resp))
316
+ return resp;
317
+ return resp.reports ?? [];
318
+ }
319
+ async getIssueReport(id) {
320
+ return this.request("GET", `/api/issue-reports/${id}`);
321
+ }
322
+ // --- Exploration ---
323
+ async startExploration(projectId, input) {
324
+ return this.request("POST", `/api/projects/${projectId}/explore`, input);
325
+ }
326
+ async getExploration(projectId) {
327
+ return this.request("GET", `/api/projects/${projectId}/explore`);
328
+ }
329
+ /**
330
+ * Fetch an authenticated blob (screenshot, report) and return its raw
331
+ * bytes. No filesystem here — a Worker has none. Callers that want a file
332
+ * on disk (the local stdio adapter) write the bytes themselves.
333
+ *
334
+ * `urlOrPath` accepts a bare path (as returned by get_evidence) or an
335
+ * absolute URL — but only on the bound host. A URL elsewhere is refused
336
+ * rather than followed, because following it would hand the bearer token
337
+ * to whatever host the caller named.
338
+ */
339
+ async downloadBlob(urlOrPath) {
340
+ let pathPart;
341
+ if (/^https?:\/\//i.test(urlOrPath)) {
342
+ const given = new URL(urlOrPath);
343
+ const bound = new URL(this.baseUrl);
344
+ if (given.host !== bound.host) {
345
+ throw new ApiError(0, "", `Refusing to download from host ${given.host}: only ${bound.host} is bound`);
346
+ }
347
+ pathPart = `${given.pathname}${given.search}`;
348
+ } else {
349
+ pathPart = urlOrPath.startsWith("/") ? urlOrPath : `/${urlOrPath}`;
350
+ }
351
+ const url = `${this.baseUrl}${pathPart}`;
352
+ let res;
353
+ try {
354
+ res = await this.fetchImpl(url, {
355
+ method: "GET",
356
+ headers: {
357
+ Authorization: `Bearer ${this.token}`,
358
+ ...this.extraHeaders
791
359
  },
792
- },
793
- ];
794
- const CODE_TOOLS = new Set([
795
- 'sixseven.read_code',
796
- 'sixseven.list_dir',
797
- 'sixseven.search_code',
798
- ]);
799
- /** Tools whose handler works on a project: they take an optional `projectId`. */
800
- const PROJECT_TOOLS = new Set([
801
- 'sixseven.list_features',
802
- 'sixseven.create_feature',
803
- 'sixseven.list_testcases',
804
- 'sixseven.get_testcase',
805
- 'sixseven.list_runs',
806
- 'sixseven.create_run',
807
- 'sixseven.list_schedules',
808
- 'sixseven.create_schedule',
809
- 'sixseven.list_schedule_recipients',
810
- 'sixseven.start_exploration',
811
- 'sixseven.get_exploration',
812
- 'sixseven.file_bug',
813
- 'sixseven.list_bugs',
360
+ ...this.dispatcherInit()
361
+ });
362
+ } catch (err) {
363
+ throw new ApiError(0, "", `Network error calling ${url}: ${err.message}`);
364
+ }
365
+ if (!res.ok) {
366
+ const text = await res.text().catch(() => "");
367
+ throw new ApiError(res.status, text, `GET ${pathPart} -> ${res.status}${text ? `: ${text.slice(0, 200)}` : ""}`);
368
+ }
369
+ const buf = new Uint8Array(await res.arrayBuffer());
370
+ if (buf.length === 0) {
371
+ throw new ApiError(res.status, "", `GET ${pathPart} returned an empty body`);
372
+ }
373
+ return {
374
+ bytes: buf,
375
+ contentType: res.headers.get("content-type") ?? "application/octet-stream"
376
+ };
377
+ }
378
+ };
379
+ var TERMINAL_RUN_STATUSES = /* @__PURE__ */ new Set([
380
+ "passed",
381
+ "failed",
382
+ "cancelled",
383
+ "error"
814
384
  ]);
815
- const PROJECT_ID_PROPERTY = {
816
- type: 'string',
817
- description: 'AuraCheck project id (see sixseven.list_projects). Defaults to the project bound in .sixseven/config.json.',
385
+
386
+ // ../mcp-core/dist/context.js
387
+ function requireProjectId(ctx, explicit) {
388
+ const id = explicit?.trim() || ctx.projectId;
389
+ if (!id) {
390
+ throw new Error("No AuraCheck project for this call: pass `projectId` (find it with list_projects), or call set_project first.");
391
+ }
392
+ return id;
393
+ }
394
+
395
+ // ../mcp-core/dist/errors.js
396
+ function parseBody(bodyText) {
397
+ try {
398
+ return JSON.parse(bodyText);
399
+ } catch {
400
+ return {};
401
+ }
402
+ }
403
+ function contactName(contact) {
404
+ return contact.name ?? contact.email;
405
+ }
406
+ var CAPABILITY_LABELS = {
407
+ viewProject: "View project",
408
+ viewReports: "View reports",
409
+ manageTestCases: "Manage test cases",
410
+ manageRuns: "Manage runs",
411
+ runTests: "Run tests",
412
+ manageProjectSetup: "Manage project setup",
413
+ manageBugs: "Manage bugs"
818
414
  };
819
- /** The input schema advertised to the client (adds `projectId` where it applies). */
820
- function advertisedSchema(t) {
821
- if (!PROJECT_TOOLS.has(t.name))
822
- return t.inputSchema;
823
- const props = (t.inputSchema.properties ?? {});
415
+ function capabilityLabel(cap) {
416
+ if (!cap)
417
+ return "this action";
418
+ return CAPABILITY_LABELS[cap] ?? cap;
419
+ }
420
+ function mapApiError(err, ctx, requiresCapability) {
421
+ const body = parseBody(err.bodyText);
422
+ const account = ctx.account;
423
+ switch (err.status) {
424
+ case 402: {
425
+ if (body.isCompanyAdmin ?? isCompanyAdminRole(account)) {
426
+ return {
427
+ blocked: true,
428
+ message: `Your AuraCheck plan has ended, so new runs are paused. Your existing runs and reports are still available. Renew here: ${ctx.renewalUrl}`
429
+ };
430
+ }
431
+ const contact = body.adminContact ?? account?.adminContact ?? null;
432
+ return {
433
+ blocked: true,
434
+ message: contact ? `Your company's AuraCheck plan has ended, so new runs are paused. Please ask your admin ${contactName(contact)} (${contact.email}) to renew. Existing results are still available.` : "Your company's AuraCheck plan has ended, so new runs are paused. Please ask your admin to renew. Existing results are still available."
435
+ };
436
+ }
437
+ case 429: {
438
+ const text = body.error ?? "";
439
+ const isConcurrent = /concurrent|already in progress|1 at a time/i.test(text);
440
+ if (isConcurrent) {
441
+ return {
442
+ blocked: true,
443
+ message: "A run is already in progress (trials run 1 at a time). I'll wait for it to finish, then start yours."
444
+ };
445
+ }
446
+ const isAdmin = body.isCompanyAdmin ?? isCompanyAdminRole(account);
447
+ const limit = account?.subscription.runUsage?.dailyLimit;
448
+ const limitClause = limit ? `Your trial allows ${limit} runs per day and today's are used up.` : "Your trial's daily run cap is used up.";
449
+ const contact = body.adminContact ?? account?.adminContact ?? null;
450
+ const actionClause = isAdmin ? `Upgrade to remove the daily cap: ${ctx.renewalUrl}` : contact ? `Ask ${contactName(contact)} to upgrade.` : "Ask your admin to upgrade.";
451
+ return {
452
+ blocked: true,
453
+ message: `${limitClause} It resets at 07:00 WIB. ${actionClause}`
454
+ };
455
+ }
456
+ case 403: {
457
+ if (/project CI token/i.test(body.error ?? "")) {
458
+ return {
459
+ blocked: true,
460
+ message: "This token can only reach its own project. Sign in personally, or pass that projectId."
461
+ };
462
+ }
463
+ const roleLabel = account?.user.roleLabel ?? "your role";
464
+ return {
465
+ blocked: true,
466
+ message: `Your AuraCheck role (${roleLabel}) can't do that. Ask your admin to give you the '${capabilityLabel(requiresCapability)}' permission.`
467
+ };
468
+ }
469
+ case 401: {
470
+ if (ctx.surface === "local")
471
+ return null;
472
+ return {
473
+ blocked: true,
474
+ message: "This AI app was disconnected from AuraCheck. Reconnect it from the app\u2019s connector settings."
475
+ };
476
+ }
477
+ default:
478
+ return null;
479
+ }
480
+ }
481
+ function isCompanyAdminRole(account) {
482
+ const caps = account?.user.capabilities ?? [];
483
+ const label = account?.user.roleLabel?.toLowerCase() ?? "";
484
+ return label.includes("admin") || caps.includes("manageProjectSetup");
485
+ }
486
+ var MOBILE_RUN_NEXT_STEP = 'Ask the person to open this run in the AuraCheck desktop app with the Android device or emulator connected and click "Run on local" (iOS: macOS desktop app, "Run on iOS"). Then call wait_for_run: it waits while the run is pending.';
487
+ function runFromDesktopAnswer(err, runId) {
488
+ if (err.status !== 422)
489
+ return null;
490
+ let body = {};
491
+ try {
492
+ body = JSON.parse(err.bodyText);
493
+ } catch {
494
+ return null;
495
+ }
496
+ if (body.code !== "run_from_desktop")
497
+ return null;
498
+ return {
499
+ started: false,
500
+ status: "run_from_desktop",
501
+ runId,
502
+ platform: body.platform ?? null,
503
+ runUrl: body.runUrl ?? null,
504
+ message: body.error ?? null,
505
+ next: MOBILE_RUN_NEXT_STEP
506
+ };
507
+ }
508
+ function graceNotice(graceEnd, renewalUrl) {
509
+ return `Heads-up: payment is overdue; runs keep working until ${graceEnd ?? "the grace period ends"}. Renew here: ${renewalUrl}`;
510
+ }
511
+
512
+ // ../mcp-core/dist/knowledge.js
513
+ var SERVER_INSTRUCTIONS = `You are connected to AuraCheck, an AI testing service that runs real browser tests on the user's website.
514
+ Start every conversation with account_status. It tells you the user's role, plan, days/runs left and their projects.
515
+ Talk in outcomes, not YAML. Many users are not engineers. Say "I'll check that new users can sign up" \u2014 not
516
+ "I'll create a Midscene flow". After a run, report: what passed, what failed in one sentence each, the likely cause,
517
+ the run link, and a screenshot for the first failure. Only show steps/YAML if the user asks.
518
+ Before writing or running any test: (1) find the project (list_projects; ask if more than one fits);
519
+ (2) PRELATION \u2014 decide whether the test needs a starting state (logged in, a specific page, seeded data). If yes,
520
+ list_testcases and reuse an existing setup case (e.g. "Login") via prelationTestCaseId. Never copy login steps into a
521
+ test. If none exists, ask the user for the test account to use, create the setup case first, then reference it.
522
+ AuraCheck runs the setup case automatically \u2014 never add it to a run yourself. (3) check list_testcases for a duplicate.
523
+ For "test this on my site" requests use test_my_flow; it shows a plan first \u2014 confirm it with the user before running.
524
+ Runs take minutes: start the run, give the link, then call wait_for_run; if it returns pollAgain, tell the user it's
525
+ still running and call it again (or come back later \u2014 they also get an email).
526
+ Never ask for or repeat passwords, PINs or OTP codes in chat. Test accounts and secrets are stored in AuraCheck
527
+ (Project \u2192 Test accounts); tell the user to add them there. Tool results never contain secret values.
528
+ Delete tools are dry-run first: show what will be deleted and get an explicit "yes" before confirm:true.
529
+ If a tool says the plan is read-only or the trial limit is reached, relay its message and next step exactly; don't retry.
530
+ Apps on localhost, an office VPN or an intranet can't be reached by AuraCheck's cloud runner: suggest the AuraCheck
531
+ desktop app or the local MCP (npx @auracheck-ai/mcp). Android/iOS runs only start from the desktop app on the user's device.`;
532
+ var LOCAL_CODE_TOOLS_PARAGRAPH = `This server also runs on your machine, so it additionally offers read_code, list_dir and search_code over the developer's repo (within configured codeRoots) \u2014 use them to understand routes, components, validators and fixtures before generating a testcase. It also offers login, logout and bind_project for local sign-in and project binding; account_status/whoami work here too.`;
533
+ function serverInstructions(surface) {
534
+ return surface === "local" ? `${SERVER_INSTRUCTIONS}
535
+
536
+ ${LOCAL_CODE_TOOLS_PARAGRAPH}` : SERVER_INSTRUCTIONS;
537
+ }
538
+ var WRITE_TESTCASE_PROMPT = [
539
+ "Before calling create_testcase, check:",
540
+ "- Prelation: does this case need a starting state (logged in, specific page, seeded data)? If so, find or create a setup case and set prelationTestCaseId instead of copying its steps in.",
541
+ "- Reuse the setup case; never duplicate a login flow across cases.",
542
+ "- Ask the user for the test account NAME to use, never the password \u2014 passwords live in AuraCheck (Project \u2192 Test accounts).",
543
+ "- Platform: web, android, or ios? Matches the project/feature this case belongs to?",
544
+ "- Steps: a non-empty Midscene flow (array or tasks[] YAML/JSON) \u2014 never an empty flow.",
545
+ '- Expected result: is it stated, so a run that technically "passes" but does the wrong thing still gets caught?',
546
+ "- executionType: automation (runs in CI/scheduled runs) or manual (a human does it, excluded from automation runs)?",
547
+ "- Is there already a similar case (list_testcases) this would duplicate?"
548
+ ].join("\n");
549
+ var RUN_AND_EXPLAIN_PROMPT = "Pick or create the cases \u2192 start_run \u2192 share link \u2192 wait_for_run until terminal \u2192 run_summary \u2192 for each failure get_evidence + one screenshot \u2192 explain in \u22645 bullets: what broke, where, likely bug vs. test issue, suggested fix/next step.";
550
+ var ONBOARDING_PROMPT = "account_status \u2192 if no project: ask for the website URL \u2192 create_project_from_url (or tell non-admins to ask their admin) \u2192 suggest 3 starter flows (sign-up, login, main purchase/contact form) \u2192 test_my_flow for the first one.";
551
+ var PROMPTS = [
552
+ {
553
+ name: "write_testcase",
554
+ description: "Checklist to run through before authoring a new AuraCheck testcase.",
555
+ text: WRITE_TESTCASE_PROMPT
556
+ },
557
+ {
558
+ name: "run_and_explain",
559
+ description: "Run one or more testcases and explain the result in plain language.",
560
+ text: RUN_AND_EXPLAIN_PROMPT
561
+ },
562
+ {
563
+ name: "onboarding",
564
+ description: "First-run flow for a brand-new AuraCheck connection.",
565
+ text: ONBOARDING_PROMPT
566
+ }
567
+ ];
568
+
569
+ // ../mcp-core/dist/register.js
570
+ import { zodToJsonSchema } from "zod-to-json-schema";
571
+
572
+ // ../mcp-core/dist/secrets.js
573
+ var DENY_KEY_PATTERNS = [
574
+ /password/i,
575
+ /pin$/i,
576
+ /^pin/i,
577
+ /otp/i,
578
+ /secret/i,
579
+ /token/i,
580
+ /api[_-]?key/i,
581
+ /authorization/i,
582
+ /cookie/i,
583
+ /credential/i,
584
+ // Config-var payloads the server itself treats as secret.
585
+ /^variables$/i
586
+ ];
587
+ var REDACTED = "[redacted]";
588
+ var MAX_DEPTH = 12;
589
+ function isSecretKey(key) {
590
+ return DENY_KEY_PATTERNS.some((re) => re.test(key));
591
+ }
592
+ function stripSecrets(value, depth = 0) {
593
+ if (depth > MAX_DEPTH || value === null || value === void 0) {
594
+ return value;
595
+ }
596
+ if (Array.isArray(value)) {
597
+ return value.map((v) => stripSecrets(v, depth + 1));
598
+ }
599
+ if (typeof value === "object") {
600
+ const out = {};
601
+ for (const [k, v] of Object.entries(value)) {
602
+ if (isSecretKey(k)) {
603
+ out[k] = REDACTED;
604
+ } else {
605
+ out[k] = stripSecrets(v, depth + 1);
606
+ }
607
+ }
608
+ return out;
609
+ }
610
+ return value;
611
+ }
612
+
613
+ // ../mcp-core/dist/tools/account.js
614
+ import { z } from "zod";
615
+
616
+ // ../mcp-core/dist/types.js
617
+ function defineTool(def) {
618
+ return def;
619
+ }
620
+
621
+ // ../mcp-core/dist/tools/account.js
622
+ var accountStatus = defineTool({
623
+ name: "account_status",
624
+ title: "Account status",
625
+ description: "Who the signed-in user is, their role, their company's plan/trial state, days and runs left, and the projects they can reach. Call this first in every conversation.",
626
+ input: z.object({}),
627
+ requires: null,
628
+ billing: "read",
629
+ surfaces: ["remote", "local"],
630
+ annotations: { readOnlyHint: true },
631
+ handler: async (_args, ctx) => {
632
+ const { account } = ctx;
633
+ const sub = account.subscription;
634
+ const lines = [];
635
+ if (sub.inGrace) {
636
+ lines.push(graceNotice(sub.graceEnd ?? null, ctx.renewalUrl));
637
+ } else if (!sub.readOnly && sub.runUsage) {
638
+ lines.push(`Trial: ${sub.daysLeft ?? "?"} days left, ${Math.max(sub.runUsage.dailyLimit - sub.runUsage.dailyCount, 0)} runs left today (${Math.max(sub.runUsage.monthlyLimit - sub.runUsage.monthlyCount, 0)} this month).`);
639
+ } else if (sub.readOnly) {
640
+ lines.push(account.adminContact ? `Your company's AuraCheck plan has ended, so new runs are paused. Please ask your admin ${account.adminContact.name ?? account.adminContact.email} (${account.adminContact.email}) to renew. Existing results are still available.` : `Your AuraCheck plan has ended, so new runs are paused. Existing results are still available. Renew here: ${ctx.renewalUrl}`);
641
+ }
824
642
  return {
825
- ...t.inputSchema,
826
- properties: { ...props, projectId: PROJECT_ID_PROPERTY },
643
+ user: account.user,
644
+ company: account.company,
645
+ subscription: sub,
646
+ projects: account.projects,
647
+ renewalUrl: ctx.renewalUrl,
648
+ minLocalMcp: account.minLocalMcp,
649
+ note: lines.join(" ") || null
827
650
  };
651
+ }
652
+ });
653
+ var listProjects = defineTool({
654
+ name: "list_projects",
655
+ title: "List projects",
656
+ description: "List the AuraCheck projects this sign-in can reach (id, name, platforms, defaultConfigurationId). Pass a project id as `projectId` to any project tool to work outside the currently set project.",
657
+ input: z.object({}),
658
+ requires: "viewProject",
659
+ billing: "read",
660
+ surfaces: ["remote", "local"],
661
+ annotations: { readOnlyHint: true },
662
+ handler: async (_args, ctx) => {
663
+ const projects = await ctx.api.listProjects();
664
+ return projects.map((p) => ({
665
+ id: p.id,
666
+ name: p.name,
667
+ companyId: p.companyId,
668
+ platforms: p.platforms,
669
+ defaultConfigurationId: p.defaultConfigurationId ?? null
670
+ }));
671
+ }
672
+ });
673
+ var setProject = defineTool({
674
+ name: "set_project",
675
+ title: "Set project",
676
+ description: "Confirm an AuraCheck project id is reachable and set it as the project for this session. Advisory: still pass `projectId` explicitly to tools when working across more than one project in the same conversation.",
677
+ input: z.object({ projectId: z.string().min(1) }),
678
+ requires: "viewProject",
679
+ billing: "read",
680
+ surfaces: ["remote", "local"],
681
+ handler: async ({ projectId }, ctx) => {
682
+ const projects = await ctx.api.listProjects();
683
+ const project = projects.find((p) => p.id === projectId);
684
+ if (!project) {
685
+ throw new Error(`${projectId} is not in the list of projects this sign-in can reach. Call list_projects.`);
686
+ }
687
+ await ctx.onSetProject?.(projectId);
688
+ return {
689
+ ok: true,
690
+ projectId,
691
+ project: { id: project.id, name: project.name }
692
+ };
693
+ }
694
+ });
695
+ var createProjectFromUrl = defineTool({
696
+ name: "create_project_from_url",
697
+ title: "Create project from URL",
698
+ description: '"Start testing my website": create a new AuraCheck project with the given URL as its web environment. Needs the manageProjectSetup permission.',
699
+ input: z.object({
700
+ name: z.string().min(1),
701
+ targetUrl: z.string().url(),
702
+ description: z.string().optional()
703
+ }),
704
+ requires: "manageProjectSetup",
705
+ billing: "write",
706
+ surfaces: ["remote", "local"],
707
+ handler: async (args, ctx) => {
708
+ try {
709
+ const project = await ctx.api.createProject({
710
+ name: args.name,
711
+ targetUrl: args.targetUrl,
712
+ platforms: ["web"],
713
+ description: args.description
714
+ });
715
+ await ctx.onSetProject?.(project.id);
716
+ return {
717
+ ok: true,
718
+ project: { id: project.id, name: project.name },
719
+ nextStep: "Suggest 3 starter flows (sign-up, login, main purchase/contact form), then use test_my_flow for the first one."
720
+ };
721
+ } catch (err) {
722
+ if (err instanceof ApiError && /unreachable|ENOTFOUND|ECONNREFUSED/i.test(err.message)) {
723
+ return {
724
+ blocked: true,
725
+ message: `AuraCheck's cloud can't reach ${args.targetUrl} (private network or localhost). Use the AuraCheck desktop app or the local MCP.`
726
+ };
727
+ }
728
+ throw err;
729
+ }
730
+ }
731
+ });
732
+ var ACCOUNT_TOOLS = [
733
+ accountStatus,
734
+ listProjects,
735
+ setProject,
736
+ createProjectFromUrl
737
+ ];
738
+
739
+ // ../mcp-core/dist/tools/bugs.js
740
+ import { z as z2 } from "zod";
741
+ var PROJECT_ID = z2.string().optional().describe("AuraCheck project id (see list_projects). Defaults to the project set for this session.");
742
+ var fileBug = defineTool({
743
+ name: "file_bug",
744
+ title: "File bug",
745
+ description: "Open an issue report (bug) against a project. Use this only after the auto-fix loop has identified a real application defect (not a flaky testcase). Severity must be 'critical', 'high', 'medium', or 'low'. Pass evidence URLs (screenshotUrl from get_evidence) in evidences[].",
746
+ input: z2.object({
747
+ projectId: PROJECT_ID,
748
+ title: z2.string().min(1).max(200),
749
+ severity: z2.enum(["critical", "high", "medium", "low"]),
750
+ description: z2.string().optional(),
751
+ pageUrl: z2.string().optional(),
752
+ evidences: z2.array(z2.string()).optional()
753
+ }),
754
+ // manageBugs is proposed (§4): the route itself only checks requireAuth
755
+ // today, so this is a client-side-only gate until the server catches up.
756
+ requires: "manageBugs",
757
+ billing: "write",
758
+ surfaces: ["remote", "local"],
759
+ handler: async ({ projectId, ...args }, ctx) => ctx.api.createIssueReport({
760
+ ...args,
761
+ projectId: requireProjectId(ctx, projectId)
762
+ })
763
+ });
764
+ var listBugs = defineTool({
765
+ name: "list_bugs",
766
+ title: "List bugs",
767
+ description: "List issue reports (bugs) for a project. Use to check whether a defect has already been reported before filing a new one.",
768
+ input: z2.object({ projectId: PROJECT_ID }),
769
+ requires: "viewReports",
770
+ billing: "read",
771
+ surfaces: ["remote", "local"],
772
+ annotations: { readOnlyHint: true },
773
+ handler: async ({ projectId }, ctx) => ctx.api.listIssueReports(requireProjectId(ctx, projectId))
774
+ });
775
+ var getBug = defineTool({
776
+ name: "get_bug",
777
+ title: "Get bug",
778
+ description: "Fetch a single issue report by id.",
779
+ input: z2.object({ id: z2.string().min(1) }),
780
+ requires: "viewReports",
781
+ billing: "read",
782
+ surfaces: ["remote", "local"],
783
+ annotations: { readOnlyHint: true },
784
+ handler: async ({ id }, ctx) => ctx.api.getIssueReport(id)
785
+ });
786
+ var BUG_TOOLS = [fileBug, listBugs, getBug];
787
+
788
+ // ../mcp-core/dist/tools/exploration.js
789
+ import { z as z3 } from "zod";
790
+ var PROJECT_ID2 = z3.string().optional().describe("AuraCheck project id (see list_projects). Defaults to the project set for this session.");
791
+ var startExploration = defineTool({
792
+ name: "start_exploration",
793
+ title: "Start exploration",
794
+ description: "Trigger AuraCheck's crawler on a set of seed URLs for a project. Returns a snapshot immediately (job runs in background); poll with get_exploration. One job per project at a time \u2014 calling this while a job is already running returns the live snapshot.",
795
+ input: z3.object({
796
+ projectId: PROJECT_ID2,
797
+ seedUrls: z3.array(z3.string().url()).min(1),
798
+ configurationId: z3.string().optional(),
799
+ maxDepth: z3.number().int().positive().max(20).optional(),
800
+ maxPages: z3.number().int().positive().max(500).optional()
801
+ }),
802
+ requires: "runTests",
803
+ billing: "run",
804
+ surfaces: ["remote", "local"],
805
+ handler: async ({ projectId, ...args }, ctx) => ctx.api.startExploration(requireProjectId(ctx, projectId), args)
806
+ });
807
+ var getExploration = defineTool({
808
+ name: "get_exploration",
809
+ title: "Get exploration",
810
+ description: "Return the latest exploration snapshot for a project (or null if none has ever run). Shape: { jobId, status, visited, anchorsUpserted, loggedIn, errors[] }. Use to await completion before generating testcases that depend on discovered routes/anchors.",
811
+ input: z3.object({ projectId: PROJECT_ID2 }),
812
+ requires: "viewProject",
813
+ billing: "read",
814
+ surfaces: ["remote", "local"],
815
+ annotations: { readOnlyHint: true },
816
+ handler: async ({ projectId }, ctx) => ctx.api.getExploration(requireProjectId(ctx, projectId))
817
+ });
818
+ var EXPLORATION_TOOLS = [startExploration, getExploration];
819
+
820
+ // ../mcp-core/dist/tools/features.js
821
+ import { z as z4 } from "zod";
822
+ var PROJECT_ID3 = z4.string().optional().describe("AuraCheck project id (see list_projects). Defaults to the project set for this session.");
823
+ var listFeatures = defineTool({
824
+ name: "list_features",
825
+ title: "List features",
826
+ description: "List features (groups of testcases) for a project. Each feature has an id and a name. Pick the most relevant feature id before creating a testcase.",
827
+ input: z4.object({ projectId: PROJECT_ID3 }),
828
+ requires: "viewProject",
829
+ billing: "read",
830
+ surfaces: ["remote", "local"],
831
+ annotations: { readOnlyHint: true },
832
+ handler: async (args, ctx) => ctx.api.listFeatures(requireProjectId(ctx, args.projectId))
833
+ });
834
+ var createFeature = defineTool({
835
+ name: "create_feature",
836
+ title: "Create feature",
837
+ description: "Create a new feature in a project. Use when no existing feature fits the testcase you are about to create.",
838
+ input: z4.object({
839
+ projectId: PROJECT_ID3,
840
+ name: z4.string().min(1),
841
+ path: z4.string().optional(),
842
+ description: z4.string().optional(),
843
+ prdContent: z4.string().optional()
844
+ }),
845
+ requires: "manageTestCases",
846
+ billing: "write",
847
+ surfaces: ["remote", "local"],
848
+ handler: async ({ projectId, ...rest }, ctx) => ctx.api.createFeature(requireProjectId(ctx, projectId), rest)
849
+ });
850
+ var deleteFeature = defineTool({
851
+ name: "delete_feature",
852
+ title: "Delete feature",
853
+ description: "Delete a feature. Requires manageTestCases. Without `confirm: true` this is a DRY RUN \u2014 it only shows the feature's name and how many testcases it holds; nothing is deleted on the first call. Testcases linked to a run are soft-deleted (reparented, run history kept); unlinked ones are removed permanently. Pass `cascade: true` to also remove sub-features.",
854
+ input: z4.object({
855
+ projectId: PROJECT_ID3,
856
+ featureId: z4.string().min(1),
857
+ cascade: z4.boolean().optional(),
858
+ confirm: z4.boolean().optional()
859
+ }),
860
+ requires: "manageTestCases",
861
+ billing: "write",
862
+ surfaces: ["remote", "local"],
863
+ annotations: { destructiveHint: true },
864
+ handler: async ({ projectId, featureId, cascade, confirm }, ctx) => {
865
+ const pid = requireProjectId(ctx, projectId);
866
+ try {
867
+ const feature = await ctx.api.getFeature(featureId, pid);
868
+ if (!feature) {
869
+ throw new Error(`Delete failed (404): feature ${featureId} not found.`);
870
+ }
871
+ if (!confirm) {
872
+ const cases = await ctx.api.listTestCasesByFeature(featureId).catch(() => []);
873
+ return {
874
+ dryRun: true,
875
+ feature: { id: feature.id, name: feature.name },
876
+ testCaseCount: cases.length,
877
+ cascade: !!cascade,
878
+ note: "Testcases linked to a run are soft-deleted (run history kept); others are removed permanently. Re-call with confirm:true to actually delete."
879
+ };
880
+ }
881
+ await ctx.api.deleteFeature(featureId, cascade);
882
+ return { dryRun: false, deletedFeatureId: featureId, cascade: !!cascade };
883
+ } catch (err) {
884
+ if (err instanceof ApiError && err.status === 403) {
885
+ throw new Error("Delete failed (403): this sign-in lacks manageTestCases, or this feature belongs to a project it can't reach.");
886
+ }
887
+ if (err instanceof ApiError && err.status === 404) {
888
+ throw new Error(`Delete failed (404): feature ${featureId} not found.`);
889
+ }
890
+ throw err;
891
+ }
892
+ }
893
+ });
894
+ var FEATURE_TOOLS = [listFeatures, createFeature, deleteFeature];
895
+
896
+ // ../mcp-core/dist/tools/runs.js
897
+ import { z as z5 } from "zod";
898
+ var PROJECT_ID4 = z5.string().optional().describe("AuraCheck project id (see list_projects). Defaults to the project set for this session.");
899
+ function runViewUrl(appUrl, runId, projectId) {
900
+ return projectId ? `${appUrl}/projects/${projectId}/runs/${runId}` : `${appUrl}/runs/${runId}`;
828
901
  }
829
- function logErr(msg) {
830
- process.stderr.write(`[sixseven-mcp] ${msg}\n`);
831
- }
832
- class NotSignedInError extends Error {
833
- constructor(baseUrl) {
834
- super(`Not signed in to AuraCheck (${baseUrl}). Run \`auracheck login\` in a terminal — the MCP server picks the new sign-in up on the next call, no restart needed.`);
835
- }
836
- }
837
- /**
838
- * Start the MCP server on stdio. It never exits for a missing project config
839
- * or sign-in: Claude Code would only show "Failed to connect". Instead every
840
- * tool call explains what is missing, and the saved token is re-read per call
841
- * so `auracheck login` takes effect without restarting the server.
842
- */
843
- export async function runMcpServer(overrides = {}) {
844
- const ctx = await resolveContext(process.cwd(), overrides);
845
- const reader = new SourceReader({
846
- repoRoot: ctx.repoRoot,
847
- config: ctx.config ?? {
848
- baseUrl: ctx.baseUrl,
849
- projectId: ctx.projectId ?? '',
850
- defaultFeatureId: null,
851
- codeRoots: ['.'],
852
- exclude: DEFAULT_EXCLUDE,
853
- platform: ctx.platform,
902
+ var listRuns = defineTool({
903
+ name: "list_runs",
904
+ title: "List runs",
905
+ description: "List recent runs for a project, optionally filtered by platform.",
906
+ input: z5.object({
907
+ projectId: PROJECT_ID4,
908
+ platform: z5.enum(["web", "android", "ios"]).optional()
909
+ }),
910
+ requires: "viewProject",
911
+ billing: "read",
912
+ surfaces: ["remote", "local"],
913
+ annotations: { readOnlyHint: true },
914
+ handler: async ({ projectId, platform }, ctx) => ctx.api.listRuns(requireProjectId(ctx, projectId), platform)
915
+ });
916
+ var createRun = defineTool({
917
+ name: "create_run",
918
+ title: "Create run",
919
+ description: 'Create a new run for one or more testcases. Defaults: caseSelectionMode="select". Returns the created run object including its id. An android/ios run is created here as usual, but only a person can start it: in the AuraCheck desktop app on their device.',
920
+ input: z5.object({
921
+ projectId: PROJECT_ID4,
922
+ name: z5.string().min(1),
923
+ testCaseIds: z5.array(z5.string()).optional(),
924
+ featureIds: z5.array(z5.string()).optional(),
925
+ platform: z5.enum(["web", "android", "ios"]).optional(),
926
+ caseSelectionMode: z5.enum(["all", "select"]).optional(),
927
+ configurationId: z5.string().optional(),
928
+ milestoneId: z5.string().optional(),
929
+ tags: z5.array(z5.string()).optional(),
930
+ notes: z5.string().optional(),
931
+ browserEngine: z5.enum(["chrome", "edge"]).optional()
932
+ }),
933
+ requires: "runTests",
934
+ billing: "run",
935
+ surfaces: ["remote", "local"],
936
+ handler: async ({ projectId, ...args }, ctx) => {
937
+ const pid = requireProjectId(ctx, projectId);
938
+ const body = {
939
+ ...args,
940
+ platform: args.platform ?? ctx.defaultPlatform ?? "web",
941
+ caseSelectionMode: args.caseSelectionMode ?? (args.testCaseIds?.length ? "select" : "all")
942
+ };
943
+ try {
944
+ return await ctx.api.createRun(pid, body);
945
+ } catch (err) {
946
+ if (err instanceof ApiError) {
947
+ const mapped = mapApiError(err, ctx, "runTests");
948
+ if (mapped)
949
+ return mapped;
950
+ }
951
+ throw err;
952
+ }
953
+ }
954
+ });
955
+ var startRun = defineTool({
956
+ name: "start_run",
957
+ // Existing local CLI name, kept so `auracheck.execute_run` doesn't break.
958
+ localAlias: "execute_run",
959
+ title: "Start run",
960
+ description: "Trigger execution of an existing WEB run. Fire-and-forget: the runner state lives in AuraCheck. Use wait_for_run to await terminal status. Android/iOS runs never execute on AuraCheck's servers: for those this returns a blocked result telling the person to open the run in the desktop app and click Run on local / Run on iOS.",
961
+ input: z5.object({ runId: z5.string().min(1) }),
962
+ requires: "runTests",
963
+ billing: "run",
964
+ surfaces: ["remote", "local"],
965
+ handler: async ({ runId }, ctx) => {
966
+ try {
967
+ return await ctx.api.executeRun(runId);
968
+ } catch (err) {
969
+ if (err instanceof ApiError) {
970
+ const answer = runFromDesktopAnswer(err, runId) ?? mapApiError(err, ctx, "runTests");
971
+ if (answer)
972
+ return answer;
973
+ }
974
+ throw err;
975
+ }
976
+ }
977
+ });
978
+ var cancelRun = defineTool({
979
+ name: "cancel_run",
980
+ title: "Cancel run",
981
+ description: "Cancel an in-flight run. Idempotent for queued runs; for inline runs the cancel may take effect at the next case boundary.",
982
+ input: z5.object({ runId: z5.string().min(1) }),
983
+ requires: "manageRuns",
984
+ billing: "write",
985
+ surfaces: ["remote", "local"],
986
+ handler: async ({ runId }, ctx) => ctx.api.cancelRun(runId)
987
+ });
988
+ var waitForRun = defineTool({
989
+ name: "wait_for_run",
990
+ title: "Wait for run",
991
+ description: "Poll a run until it reaches a terminal status (passed/failed/cancelled/error) or the timeout elapses. Returns the final run object plus a summary of per-case statuses. Remote caps the wait at 45s and returns `pollAgain:true` if still running \u2014 call it again (the user also gets an email when the run finishes). Local can wait up to 300s. An android/ios run stays pending until a person starts it in the AuraCheck desktop app.",
992
+ input: z5.object({
993
+ runId: z5.string().min(1),
994
+ timeoutSec: z5.number().int().positive().max(3600).optional(),
995
+ pollMs: z5.number().int().positive().max(3e4).optional()
996
+ }),
997
+ requires: "viewProject",
998
+ billing: "read",
999
+ surfaces: ["remote", "local"],
1000
+ annotations: { readOnlyHint: true },
1001
+ handler: async (args, ctx) => {
1002
+ const requested = args.timeoutSec ?? ctx.waitForRunMaxSec;
1003
+ const timeoutMs = Math.min(requested, ctx.waitForRunMaxSec) * 1e3;
1004
+ const pollMs = args.pollMs ?? 3e3;
1005
+ const start = Date.now();
1006
+ let last = await ctx.api.getRun(args.runId);
1007
+ while (!TERMINAL_RUN_STATUSES.has(last.status) && Date.now() - start < timeoutMs) {
1008
+ await new Promise((resolve) => setTimeout(resolve, pollMs));
1009
+ last = await ctx.api.getRun(args.runId);
1010
+ }
1011
+ const terminal = TERMINAL_RUN_STATUSES.has(last.status);
1012
+ const attempts = await ctx.api.listRunCaseAttempts(args.runId).catch(() => ({ attempts: [] }));
1013
+ const summary = attempts.attempts.reduce((acc, a) => {
1014
+ acc[a.status] = (acc[a.status] ?? 0) + 1;
1015
+ return acc;
1016
+ }, {});
1017
+ const pendingMobile = !terminal && last.status === "pending" && (last.platform === "android" || last.platform === "ios");
1018
+ return {
1019
+ terminal,
1020
+ pollAgain: !terminal,
1021
+ elapsedMs: Date.now() - start,
1022
+ runId: args.runId,
1023
+ status: last.status,
1024
+ reportUrl: last.reportUrl ?? null,
1025
+ viewUrl: runViewUrl(ctx.appUrl, args.runId, last.projectId),
1026
+ completedAt: last.completedAt ?? null,
1027
+ caseStatusSummary: summary,
1028
+ ...pendingMobile ? {
1029
+ message: "Not started yet: Android/iOS runs are started by a person in the AuraCheck desktop app on their own device."
1030
+ } : {},
1031
+ run: last
1032
+ };
1033
+ }
1034
+ });
1035
+ var getRun = defineTool({
1036
+ name: "get_run",
1037
+ title: "Get run",
1038
+ description: "Fetch a single run by id including current status, started/completed timestamps, and reportUrl when available.",
1039
+ input: z5.object({ runId: z5.string().min(1) }),
1040
+ requires: "viewProject",
1041
+ billing: "read",
1042
+ surfaces: ["remote", "local"],
1043
+ annotations: { readOnlyHint: true },
1044
+ handler: async ({ runId }, ctx) => ctx.api.getRun(runId)
1045
+ });
1046
+ var runSummary = defineTool({
1047
+ name: "run_summary",
1048
+ // Existing local CLI name, kept so `auracheck.get_run_report` doesn't break.
1049
+ localAlias: "get_run_report",
1050
+ title: "Run summary",
1051
+ description: "Results of a run as the Run Report groups them: case counts (passed/failed/skipped/pending) plus buckets \u2014 potential bugs (with bug report, severity), script issues, blocked cases and passed cases. Read-only.",
1052
+ input: z5.object({ runId: z5.string().min(1) }),
1053
+ requires: "viewReports",
1054
+ billing: "read",
1055
+ surfaces: ["remote", "local"],
1056
+ annotations: { readOnlyHint: true },
1057
+ handler: async ({ runId }, ctx) => {
1058
+ const [run, counts, buckets] = await Promise.all([
1059
+ ctx.api.getRun(runId),
1060
+ ctx.api.getRunCaseStatusCounts(runId),
1061
+ ctx.api.getRunReportBuckets(runId)
1062
+ ]);
1063
+ return {
1064
+ run: {
1065
+ id: run.id,
1066
+ name: run.name,
1067
+ status: run.status,
1068
+ reportUrl: run.reportUrl ?? null
1069
+ },
1070
+ counts,
1071
+ ...buckets
1072
+ };
1073
+ }
1074
+ });
1075
+ var listRunTestcases = defineTool({
1076
+ name: "list_run_testcases",
1077
+ title: "List run testcases",
1078
+ description: "List the testcases attached to a specific run.",
1079
+ input: z5.object({ runId: z5.string().min(1) }),
1080
+ requires: "viewProject",
1081
+ billing: "read",
1082
+ surfaces: ["remote", "local"],
1083
+ annotations: { readOnlyHint: true },
1084
+ handler: async ({ runId }, ctx) => ctx.api.listRunTestCases(runId)
1085
+ });
1086
+ var getEvidence = defineTool({
1087
+ name: "get_evidence",
1088
+ title: "Get evidence",
1089
+ description: "Aggregate evidence for a finished (or in-progress) run: per-case attempts, latest step events, failed-step screenshots and error messages, and the AuraCheck report URL. A failed step that hung also carries stallDiagnostics. Filter by caseId to narrow scope. Use after wait_for_run to diagnose failures.",
1090
+ input: z5.object({
1091
+ runId: z5.string().min(1),
1092
+ caseId: z5.string().optional(),
1093
+ maxEventsPerCase: z5.number().int().positive().max(200).optional()
1094
+ }),
1095
+ requires: "viewReports",
1096
+ billing: "read",
1097
+ surfaces: ["remote", "local"],
1098
+ annotations: { readOnlyHint: true },
1099
+ handler: async (args, ctx) => {
1100
+ const max = args.maxEventsPerCase ?? 20;
1101
+ const [run, attemptsResp, eventsResp, runCases] = await Promise.all([
1102
+ ctx.api.getRun(args.runId),
1103
+ ctx.api.listRunCaseAttempts(args.runId),
1104
+ ctx.api.listRunStepEvents(args.runId, args.caseId),
1105
+ ctx.api.listRunTestCases(args.runId).catch(() => [])
1106
+ ]);
1107
+ const caseNameById = new Map(runCases.map((c) => [c.id, c.name]));
1108
+ const allEvents = eventsResp.events ?? [];
1109
+ const eventsByCase = /* @__PURE__ */ new Map();
1110
+ for (const e of allEvents) {
1111
+ const key = e.testCaseId ?? "__unbound__";
1112
+ if (args.caseId && key !== args.caseId)
1113
+ continue;
1114
+ const arr = eventsByCase.get(key) ?? [];
1115
+ arr.push(e);
1116
+ eventsByCase.set(key, arr);
1117
+ }
1118
+ const attempts = (attemptsResp.attempts ?? []).filter((a) => !args.caseId || a.testCaseId === args.caseId);
1119
+ const cases = attempts.map((attempt) => {
1120
+ const events = (eventsByCase.get(attempt.testCaseId) ?? []).slice().sort((a, b) => (a.stepIndex ?? 0) - (b.stepIndex ?? 0)).slice(0, max);
1121
+ const failedSteps = events.filter((e) => e.status === "failed" || e.error);
1122
+ return {
1123
+ testCaseId: attempt.testCaseId,
1124
+ testCaseName: caseNameById.get(attempt.testCaseId) ?? null,
1125
+ attemptId: attempt.id,
1126
+ attemptStatus: attempt.status,
1127
+ attemptReportUrl: attempt.reportUrl ?? null,
1128
+ startedAt: attempt.startedAt,
1129
+ completedAt: attempt.completedAt,
1130
+ stepEvents: events.map((e) => ({
1131
+ stepIndex: e.stepIndex,
1132
+ stepType: e.stepType,
1133
+ stepPrompt: e.stepPrompt,
1134
+ status: e.status,
1135
+ durationMs: e.durationMs,
1136
+ error: e.error,
1137
+ screenshotUrl: e.screenshotUrl,
1138
+ notes: e.notes
1139
+ })),
1140
+ failedSteps: failedSteps.map((e) => ({
1141
+ stepIndex: e.stepIndex,
1142
+ stepType: e.stepType,
1143
+ error: e.error,
1144
+ screenshotUrl: e.screenshotUrl,
1145
+ stallDiagnostics: e.stallDiagnostics ?? null
1146
+ }))
1147
+ };
1148
+ });
1149
+ return {
1150
+ runId: args.runId,
1151
+ status: run.status,
1152
+ platform: run.platform,
1153
+ reportUrl: run.reportUrl ?? null,
1154
+ viewUrl: runViewUrl(ctx.appUrl, args.runId),
1155
+ cases,
1156
+ totals: {
1157
+ caseCount: cases.length,
1158
+ failedCaseCount: cases.filter((c) => c.attemptStatus === "failed").length,
1159
+ failedStepCount: cases.reduce((n, c) => n + c.failedSteps.length, 0)
1160
+ }
1161
+ };
1162
+ }
1163
+ });
1164
+ var getScreenshot = defineTool({
1165
+ name: "get_screenshot",
1166
+ title: "Get screenshot",
1167
+ description: "Fetch a run screenshot (or any authenticated blob) so it can actually be SEEN. Pass a `screenshotUrl` straight from get_evidence. Remote returns it as inline MCP image content; local writes it to a file and returns the path. Reach for it whenever a failure's cause is visual.",
1168
+ input: z5.object({
1169
+ url: z5.string().min(1).describe("screenshotUrl from get_evidence, e.g. '/api/blob/screenshots/<runId>/<caseId>-step14.png'. An absolute URL is accepted only on the bound host.")
1170
+ }),
1171
+ requires: "viewReports",
1172
+ billing: "read",
1173
+ // Local keeps its pre-existing, richer implementation (optional outPath,
1174
+ // writes the file itself — mcp-core has no fs) in packages/cli directly;
1175
+ // this one only ever runs on the Worker.
1176
+ surfaces: ["remote"],
1177
+ annotations: { readOnlyHint: true },
1178
+ handler: async ({ url }, ctx) => {
1179
+ const { bytes, contentType } = await ctx.api.downloadBlob(url);
1180
+ return { __binary: true, bytes, contentType, sourceUrl: url };
1181
+ }
1182
+ });
1183
+ var RUN_TOOLS = [
1184
+ listRuns,
1185
+ createRun,
1186
+ startRun,
1187
+ cancelRun,
1188
+ waitForRun,
1189
+ getRun,
1190
+ runSummary,
1191
+ listRunTestcases,
1192
+ getEvidence,
1193
+ getScreenshot
1194
+ ];
1195
+
1196
+ // ../mcp-core/dist/tools/schedules.js
1197
+ import { z as z6 } from "zod";
1198
+ var PROJECT_ID5 = z6.string().optional().describe("AuraCheck project id (see list_projects). Defaults to the project set for this session.");
1199
+ var listSchedules = defineTool({
1200
+ name: "list_schedules",
1201
+ title: "List schedules",
1202
+ description: "List the recurring run schedules of a project. Each schedule carries its cron expressions, IANA timezone, computed nextFireAt (UTC), platform, case filter and notify recipients.",
1203
+ input: z6.object({ projectId: PROJECT_ID5 }),
1204
+ requires: "viewProject",
1205
+ billing: "read",
1206
+ surfaces: ["remote", "local"],
1207
+ annotations: { readOnlyHint: true },
1208
+ handler: async ({ projectId }, ctx) => ctx.api.listSchedules(requireProjectId(ctx, projectId))
1209
+ });
1210
+ var getSchedule = defineTool({
1211
+ name: "get_schedule",
1212
+ title: "Get schedule",
1213
+ description: "Fetch a single schedule by id. lastFiredAt reflects CLOCK-driven fires only \u2014 run_schedule_now deliberately leaves it untouched; use list_schedule_fires for the full history.",
1214
+ input: z6.object({ scheduleId: z6.string().min(1) }),
1215
+ requires: "viewProject",
1216
+ billing: "read",
1217
+ surfaces: ["remote", "local"],
1218
+ annotations: { readOnlyHint: true },
1219
+ handler: async ({ scheduleId }, ctx) => ctx.api.getSchedule(scheduleId)
1220
+ });
1221
+ var createSchedule = defineTool({
1222
+ name: "create_schedule",
1223
+ title: "Create schedule",
1224
+ description: "Create a recurring run schedule. cronExpressions is 5-field cron evaluated in `timezone` (IANA, e.g. 'Asia/Jakarta'); several expressions are allowed. caseFilter picks what runs: { mode: 'all' } for every case on the platform, or { mode: 'feature', featureIds } to narrow (get ids from list_features). notifyUserIds must come from list_schedule_recipients. Prefer enabled:false while testing, then enable once the cadence reads right.",
1225
+ input: z6.object({
1226
+ projectId: PROJECT_ID5,
1227
+ name: z6.string().min(1),
1228
+ cronExpressions: z6.array(z6.string().min(1)).min(1),
1229
+ timezone: z6.string().min(1),
1230
+ platform: z6.enum(["web", "android", "ios"]).optional(),
1231
+ enabled: z6.boolean().optional(),
1232
+ configurationId: z6.string().optional(),
1233
+ caseFilter: z6.object({
1234
+ mode: z6.enum(["all", "feature"]),
1235
+ featureIds: z6.array(z6.string()).default([])
1236
+ }).optional(),
1237
+ notifyUserIds: z6.array(z6.string()).optional(),
1238
+ misfireGraceMinutes: z6.number().int().positive().optional()
1239
+ }),
1240
+ requires: "runTests",
1241
+ billing: "write",
1242
+ surfaces: ["remote", "local"],
1243
+ handler: async ({ projectId, ...args }, ctx) => {
1244
+ const pid = requireProjectId(ctx, projectId);
1245
+ if (args.caseFilter?.mode === "feature" && !args.caseFilter.featureIds?.length) {
1246
+ throw new Error("caseFilter.mode 'feature' needs at least one featureId \u2014 otherwise every fire resolves to zero cases. Call list_features, or use { mode: 'all' }.");
1247
+ }
1248
+ const schedule = await ctx.api.createSchedule(pid, {
1249
+ ...args,
1250
+ platform: args.platform ?? ctx.defaultPlatform ?? "web"
1251
+ });
1252
+ let warning = null;
1253
+ if (!schedule.configurationId) {
1254
+ const project = await ctx.api.getProject(pid).catch(() => null);
1255
+ if (project && !project.defaultConfigurationId) {
1256
+ warning = "This schedule has no configurationId and the project has no default configuration, so its runs will start without a base URL and fail at the first navigation. Set configurationId via update_schedule.";
1257
+ }
1258
+ }
1259
+ return { ...schedule, warning };
1260
+ }
1261
+ });
1262
+ var updateSchedule = defineTool({
1263
+ name: "update_schedule",
1264
+ title: "Update schedule",
1265
+ description: "Patch an existing schedule \u2014 pause it (enabled:false), change cadence, retarget its configuration, or edit notify recipients. Only the fields you pass are touched.",
1266
+ input: z6.object({ scheduleId: z6.string().min(1), patch: z6.record(z6.any()) }),
1267
+ requires: "runTests",
1268
+ billing: "write",
1269
+ surfaces: ["remote", "local"],
1270
+ handler: async ({ scheduleId, patch }, ctx) => ctx.api.updateSchedule(scheduleId, patch)
1271
+ });
1272
+ var deleteSchedule = defineTool({
1273
+ name: "delete_schedule",
1274
+ title: "Delete schedule",
1275
+ description: "Delete a schedule permanently. Runs it already created are kept; only the cadence goes away. Prefer update_schedule with enabled:false to pause it instead.",
1276
+ input: z6.object({ scheduleId: z6.string().min(1) }),
1277
+ requires: "runTests",
1278
+ billing: "write",
1279
+ surfaces: ["remote", "local"],
1280
+ annotations: { destructiveHint: true },
1281
+ handler: async ({ scheduleId }, ctx) => {
1282
+ await ctx.api.deleteSchedule(scheduleId);
1283
+ return { ok: true, deletedScheduleId: scheduleId };
1284
+ }
1285
+ });
1286
+ var runScheduleNow = defineTool({
1287
+ name: "run_schedule_now",
1288
+ title: "Run schedule now",
1289
+ description: "Fire a schedule immediately on the identical code path the clock uses \u2014 works on a paused schedule too. Returns { outcome, runId }: 'run_created' means a run was started (feed runId to wait_for_run), while 'skipped_overlap' means a previous run of this schedule is still live and 'no_cases' means the case filter matched nothing. Skips are reported, not thrown.",
1290
+ input: z6.object({ scheduleId: z6.string().min(1) }),
1291
+ requires: "runTests",
1292
+ billing: "run",
1293
+ surfaces: ["remote", "local"],
1294
+ handler: async ({ scheduleId }, ctx) => {
1295
+ const { outcome, skipped } = await ctx.api.runScheduleNow(scheduleId);
1296
+ let runId = null;
1297
+ if (outcome === "run_created") {
1298
+ const fires = await ctx.api.listScheduleFires(scheduleId).catch(() => ({ items: [], hasMore: false }));
1299
+ runId = fires.items[0]?.runId ?? null;
1300
+ }
1301
+ return {
1302
+ scheduleId,
1303
+ outcome,
1304
+ skipped,
1305
+ runId,
1306
+ viewUrl: runId ? `${ctx.appUrl}/runs/${runId}` : null
1307
+ };
1308
+ }
1309
+ });
1310
+ var listScheduleFires = defineTool({
1311
+ name: "list_schedule_fires",
1312
+ title: "List schedule fires",
1313
+ description: "History of a schedule's occurrences, newest first: when it fired, the outcome, and the run it created (if any).",
1314
+ input: z6.object({
1315
+ scheduleId: z6.string().min(1),
1316
+ page: z6.number().int().positive().optional()
1317
+ }),
1318
+ requires: "viewProject",
1319
+ billing: "read",
1320
+ surfaces: ["remote", "local"],
1321
+ annotations: { readOnlyHint: true },
1322
+ handler: async ({ scheduleId, page }, ctx) => ctx.api.listScheduleFires(scheduleId, page)
1323
+ });
1324
+ var listScheduleRecipients = defineTool({
1325
+ name: "list_schedule_recipients",
1326
+ title: "List schedule recipients",
1327
+ description: "The users that may be put in a schedule's notifyUserIds. Resolved exactly the way the server resolves recipients at send time.",
1328
+ input: z6.object({ projectId: PROJECT_ID5 }),
1329
+ requires: "viewProject",
1330
+ billing: "read",
1331
+ surfaces: ["remote", "local"],
1332
+ annotations: { readOnlyHint: true },
1333
+ handler: async ({ projectId }, ctx) => ctx.api.listScheduleRecipients(requireProjectId(ctx, projectId))
1334
+ });
1335
+ var SCHEDULE_TOOLS = [
1336
+ listSchedules,
1337
+ getSchedule,
1338
+ createSchedule,
1339
+ updateSchedule,
1340
+ deleteSchedule,
1341
+ runScheduleNow,
1342
+ listScheduleFires,
1343
+ listScheduleRecipients
1344
+ ];
1345
+
1346
+ // ../mcp-core/dist/tools/test-my-flow.js
1347
+ import { z as z7 } from "zod";
1348
+ var PROJECT_ID6 = z7.string().optional().describe("AuraCheck project id (see list_projects). Defaults to the project set for this session.");
1349
+ var testMyFlow = defineTool({
1350
+ name: "test_my_flow",
1351
+ title: "Test my flow",
1352
+ description: 'One-shot: turn a plain-English request ("check that sign-up works") into a test plan, show it, then run it on confirmation and summarize the result with a link. Call once without `confirm` to see the plan; call again with `confirm:true` once the person agrees to run it.',
1353
+ input: z7.object({
1354
+ projectId: PROJECT_ID6,
1355
+ url: z7.string().url(),
1356
+ prompt: z7.string().min(8).max(4e3),
1357
+ confirm: z7.boolean().optional()
1358
+ }),
1359
+ requires: "manageTestCases",
1360
+ billing: "run",
1361
+ surfaces: ["remote", "local"],
1362
+ handler: async ({ projectId, url, prompt, confirm }, ctx) => {
1363
+ const pid = requireProjectId(ctx, projectId);
1364
+ let plan = null;
1365
+ let promptToTestEnabled = true;
1366
+ try {
1367
+ const preview = await ctx.api.previewPromptTest(pid, { url, prompt });
1368
+ plan = preview.plan;
1369
+ } catch (err) {
1370
+ if (err instanceof ApiError && err.status === 404) {
1371
+ promptToTestEnabled = false;
1372
+ } else if (err instanceof ApiError) {
1373
+ const mapped = mapApiError(err, ctx, "manageTestCases");
1374
+ if (mapped)
1375
+ return mapped;
1376
+ throw err;
1377
+ } else {
1378
+ throw err;
1379
+ }
1380
+ }
1381
+ if (!confirm) {
1382
+ if (plan) {
1383
+ return {
1384
+ dryRun: true,
1385
+ plan,
1386
+ note: "Confirm this plan with the person, then call test_my_flow again with confirm:true to create and run it."
1387
+ };
1388
+ }
1389
+ return {
1390
+ dryRun: true,
1391
+ plan: {
1392
+ title: prompt.slice(0, 120),
1393
+ category: "positive",
1394
+ steps: [{ kind: "action", description: prompt }]
854
1395
  },
1396
+ note: "This company doesn't have AI plan generation enabled for prompt-to-test, so this will run as a single step using your instruction verbatim. Confirm with the person, then call test_my_flow again with confirm:true."
1397
+ };
1398
+ }
1399
+ try {
1400
+ let runId;
1401
+ let viewUrl;
1402
+ if (promptToTestEnabled && plan) {
1403
+ const { run } = await ctx.api.createPromptTestRun(pid, {
1404
+ url,
1405
+ prompt,
1406
+ plan
1407
+ });
1408
+ runId = run.id;
1409
+ viewUrl = `${ctx.appUrl}/projects/${pid}/runs/${runId}`;
1410
+ } else {
1411
+ const features = await ctx.api.listFeatures(pid);
1412
+ let feature = features.find((f) => f.name === "Prompt tests");
1413
+ if (!feature) {
1414
+ feature = await ctx.api.createFeature(pid, {
1415
+ name: "Prompt tests",
1416
+ description: "Cases created by test_my_flow (AI plan generation not enabled for this company)."
1417
+ });
1418
+ }
1419
+ const testCase = await ctx.api.createTestCase(feature.id, {
1420
+ name: prompt.slice(0, 120),
1421
+ steps: [{ aiAction: prompt }],
1422
+ executionType: "automation",
1423
+ category: "positive",
1424
+ description: prompt
1425
+ });
1426
+ const run = await ctx.api.createRun(pid, {
1427
+ name: prompt.slice(0, 120),
1428
+ testCaseIds: [testCase.id],
1429
+ platform: "web",
1430
+ caseSelectionMode: "select"
1431
+ });
1432
+ runId = run.id;
1433
+ viewUrl = `${ctx.appUrl}/projects/${pid}/runs/${runId}`;
1434
+ }
1435
+ try {
1436
+ await ctx.api.executeRun(runId);
1437
+ } catch (err) {
1438
+ if (err instanceof ApiError) {
1439
+ const answer = runFromDesktopAnswer(err, runId) ?? mapApiError(err, ctx, "runTests");
1440
+ if (answer)
1441
+ return answer;
1442
+ }
1443
+ throw err;
1444
+ }
1445
+ return {
1446
+ started: true,
1447
+ runId,
1448
+ viewUrl,
1449
+ usedAiPlan: promptToTestEnabled,
1450
+ nextStep: "Call wait_for_run with this runId, then run_summary."
1451
+ };
1452
+ } catch (err) {
1453
+ if (err instanceof ApiError) {
1454
+ const mapped = mapApiError(err, ctx, "runTests");
1455
+ if (mapped)
1456
+ return mapped;
1457
+ }
1458
+ throw err;
1459
+ }
1460
+ }
1461
+ });
1462
+ var TEST_MY_FLOW_TOOLS = [testMyFlow];
1463
+
1464
+ // ../mcp-core/dist/tools/testcases.js
1465
+ import { z as z8 } from "zod";
1466
+ var PROJECT_ID7 = z8.string().optional().describe("AuraCheck project id (see list_projects). Defaults to the project set for this session.");
1467
+ var STEPS_SCHEMA = z8.union([
1468
+ z8.array(z8.record(z8.any())).min(1),
1469
+ z8.string().min(1),
1470
+ z8.record(z8.any())
1471
+ ]);
1472
+ var STEPS_DESCRIPTION = "Array of Midscene flow items (auto-wrapped into tasks[]), or a YAML/JSON string shaped as `tasks: [{ name, flow }]`. Recognized action keys: aiTap, aiInput, aiAssert, aiQuery, aiHover, aiWaitFor, aiKeyboardPress, aiScroll, aiAction, sleep, javascript, aiUploadFile, aiHumanInput, aiExpectDownload, mailTmInbox, mailTmWaitOtp, mailTmWaitLink, otpInbox, otpWaitOtp.";
1473
+ var listTestcases = defineTool({
1474
+ name: "list_testcases",
1475
+ title: "List testcases",
1476
+ description: "List testcases for a project, optionally filtered by platform (web/android/ios). Each case carries `prelationTestCaseId` and, when set, a joined `prelationTestCase` \u2014 the setup case AuraCheck runs automatically right before it. Use this to find an existing login/setup case before creating a new one.",
1477
+ input: z8.object({
1478
+ projectId: PROJECT_ID7,
1479
+ platform: z8.enum(["web", "android", "ios"]).optional()
1480
+ }),
1481
+ requires: "viewProject",
1482
+ billing: "read",
1483
+ surfaces: ["remote", "local"],
1484
+ annotations: { readOnlyHint: true },
1485
+ handler: async ({ projectId, platform }, ctx) => ctx.api.listTestCasesByProject(requireProjectId(ctx, projectId), platform)
1486
+ });
1487
+ var getTestcase = defineTool({
1488
+ name: "get_testcase",
1489
+ title: "Get testcase",
1490
+ description: "Fetch a single testcase by id. `steps` comes back as the Midscene YAML/JSON string the server stores, not an array \u2014 parse it before editing, and pass it back through update_testcase in either form. Also carries `prelationTestCaseId` and, when set, a joined `prelationTestCase`.",
1491
+ input: z8.object({ projectId: PROJECT_ID7, id: z8.string().min(1) }),
1492
+ requires: "viewProject",
1493
+ billing: "read",
1494
+ surfaces: ["remote", "local"],
1495
+ annotations: { readOnlyHint: true },
1496
+ handler: async ({ projectId, id }, ctx) => ctx.api.getTestCase(id, requireProjectId(ctx, projectId))
1497
+ });
1498
+ var createTestcase = defineTool({
1499
+ name: "create_testcase",
1500
+ title: "Create testcase",
1501
+ description: `Create a new testcase under an AuraCheck feature. \`steps\` is the Midscene flow: pass EITHER an array of flow items (each item one action, e.g. { aiTap: "Sign in" }, { aiInput: "user@example.com", locate: "Email field" }, { aiAssert: "Dashboard is visible" }) OR a YAML/JSON string shaped as tasks[]. ${STEPS_DESCRIPTION} A bare array is auto-wrapped. Android/iOS cases are authored here exactly like web ones; they are RUN by a person in the AuraCheck desktop app on their own device (see start_run).
1502
+
1503
+ PRELATION \u2014 before writing \`steps\`, decide whether this case needs a starting state (logged in, on a specific page, seeded data). If it does, set \`prelationTestCaseId\` to an existing setup case (find one with list_testcases) instead of copying its steps into every case; create the setup case first if none exists. AuraCheck runs the prelation case automatically immediately before this one every time it runs \u2014 never add the prelation case to a run yourself. A prelation must be in the same project and never points at itself or forms a cycle.`,
1504
+ input: z8.object({
1505
+ projectId: PROJECT_ID7,
1506
+ featureId: z8.string().optional(),
1507
+ name: z8.string().min(1),
1508
+ steps: STEPS_SCHEMA,
1509
+ executionType: z8.enum(["automation", "manual"]).default("automation"),
1510
+ priority: z8.enum(["low", "medium", "high", "critical"]).optional(),
1511
+ category: z8.string().optional(),
1512
+ reason: z8.string().optional(),
1513
+ description: z8.string().optional(),
1514
+ expectedResult: z8.string().optional(),
1515
+ platforms: z8.array(z8.string()).optional(),
1516
+ coveredScenarios: z8.array(z8.string()).optional(),
1517
+ tags: z8.array(z8.string()).optional(),
1518
+ prelationTestCaseId: z8.string().optional()
1519
+ }),
1520
+ requires: "manageTestCases",
1521
+ billing: "write",
1522
+ surfaces: ["remote", "local"],
1523
+ handler: async (args, ctx) => {
1524
+ requireProjectId(ctx, args.projectId);
1525
+ const { projectId: _ignore, featureId, ...rest } = args;
1526
+ if (!featureId) {
1527
+ throw new Error("No featureId provided. Call list_features or create_feature first.");
1528
+ }
1529
+ return ctx.api.createTestCase(featureId, rest);
1530
+ }
1531
+ });
1532
+ var updateTestcase = defineTool({
1533
+ name: "update_testcase",
1534
+ title: "Update testcase",
1535
+ description: "Patch an existing testcase \u2014 only the fields you pass are touched. Useful in the auto-fix loop after reading evidence from a failed run. A `steps` patch accepts the same shapes as create_testcase. `patch.prelationTestCaseId` sets/replaces the setup case AuraCheck runs automatically before this one; pass `null` to clear it. It cannot be set to the case's own id, a case from another project, or create a cycle \u2014 the server rejects those.",
1536
+ input: z8.object({ id: z8.string().min(1), patch: z8.record(z8.any()) }),
1537
+ requires: "manageTestCases",
1538
+ billing: "write",
1539
+ surfaces: ["remote", "local"],
1540
+ handler: async ({ id, patch }, ctx) => ctx.api.updateTestCase(id, patch)
1541
+ });
1542
+ var deleteTestcase = defineTool({
1543
+ name: "delete_testcase",
1544
+ title: "Delete testcase",
1545
+ description: "Delete 1\u2013500 testcases. Requires manageTestCases. Without `confirm: true` this is a DRY RUN \u2014 it only lists what would be deleted and asks you to re-call with confirm:true; nothing is deleted on the first call. A case already linked to a run is soft-deleted (run history kept); a case never attached to a run is removed permanently.",
1546
+ input: z8.object({
1547
+ projectId: PROJECT_ID7,
1548
+ testCaseIds: z8.array(z8.string().min(1)).min(1).max(500),
1549
+ confirm: z8.boolean().optional()
1550
+ }),
1551
+ requires: "manageTestCases",
1552
+ billing: "write",
1553
+ surfaces: ["remote", "local"],
1554
+ annotations: { destructiveHint: true },
1555
+ handler: async ({ projectId, testCaseIds, confirm }, ctx) => {
1556
+ const pid = requireProjectId(ctx, projectId);
1557
+ try {
1558
+ if (!confirm) {
1559
+ const all = await ctx.api.listTestCasesByProject(pid);
1560
+ const byId = new Map(all.map((c) => [c.id, c]));
1561
+ const found = testCaseIds.map((id) => {
1562
+ const c = byId.get(id);
1563
+ return c ? { id, name: c.name, featureId: c.featureId } : { id, name: null, featureId: null, notFound: true };
1564
+ });
1565
+ return {
1566
+ dryRun: true,
1567
+ wouldDelete: found,
1568
+ note: "Cases linked to a run are soft-deleted (run history kept); others are removed permanently. Re-call with confirm:true to actually delete."
1569
+ };
1570
+ }
1571
+ const result = await ctx.api.deleteTestCases(testCaseIds);
1572
+ return { dryRun: false, deletedIds: testCaseIds, ...result };
1573
+ } catch (err) {
1574
+ if (err instanceof ApiError && err.status === 403) {
1575
+ throw new Error("Delete failed (403): this sign-in lacks manageTestCases, or one of these cases belongs to a project it can't reach.");
1576
+ }
1577
+ if (err instanceof ApiError && err.status === 404) {
1578
+ throw new Error("Delete failed (404): one of these test case ids does not exist.");
1579
+ }
1580
+ throw err;
1581
+ }
1582
+ }
1583
+ });
1584
+ var TESTCASE_TOOLS = [
1585
+ listTestcases,
1586
+ getTestcase,
1587
+ createTestcase,
1588
+ updateTestcase,
1589
+ deleteTestcase
1590
+ ];
1591
+
1592
+ // ../mcp-core/dist/register.js
1593
+ var ALL_TOOLS = [
1594
+ ...ACCOUNT_TOOLS,
1595
+ ...FEATURE_TOOLS,
1596
+ ...TESTCASE_TOOLS,
1597
+ ...RUN_TOOLS,
1598
+ ...SCHEDULE_TOOLS,
1599
+ ...EXPLORATION_TOOLS,
1600
+ ...BUG_TOOLS,
1601
+ ...TEST_MY_FLOW_TOOLS
1602
+ ];
1603
+ var TOOLS_BY_NAME = new Map(ALL_TOOLS.map((t) => [t.name, t]));
1604
+ function getTool(name) {
1605
+ return TOOLS_BY_NAME.get(name);
1606
+ }
1607
+ function localName(t) {
1608
+ return t.localAlias ?? t.name;
1609
+ }
1610
+ var TOOLS_BY_LOCAL_NAME = new Map(ALL_TOOLS.map((t) => [localName(t), t]));
1611
+ async function callTool(name, rawArgs, ctx) {
1612
+ const tool = getTool(name);
1613
+ if (!tool) {
1614
+ return { ok: false, error: `Unknown tool: ${name}` };
1615
+ }
1616
+ if (!tool.surfaces.includes(ctx.surface)) {
1617
+ return {
1618
+ ok: false,
1619
+ error: `Tool ${name} is not available on this surface.`
1620
+ };
1621
+ }
1622
+ if (tool.requires && !ctx.account.user.capabilities.includes(tool.requires)) {
1623
+ const roleLabel = ctx.account.user.roleLabel;
1624
+ return {
1625
+ ok: false,
1626
+ error: `Your AuraCheck role (${roleLabel}) can't use ${name}. Ask your admin for the '${tool.requires}' permission.`
1627
+ };
1628
+ }
1629
+ let args;
1630
+ try {
1631
+ args = tool.input.parse(rawArgs ?? {});
1632
+ } catch (err) {
1633
+ return {
1634
+ ok: false,
1635
+ error: `Invalid arguments for ${name}: ${err?.message ?? String(err)}`
1636
+ };
1637
+ }
1638
+ try {
1639
+ const result = await tool.handler(args, ctx);
1640
+ return { ok: true, result: stripSecrets(result) };
1641
+ } catch (err) {
1642
+ if (err instanceof ApiError) {
1643
+ const mapped = mapApiError(err, ctx, tool.requires);
1644
+ if (mapped)
1645
+ return { ok: true, result: mapped };
1646
+ }
1647
+ return {
1648
+ ok: false,
1649
+ error: err instanceof Error ? err.message : String(err)
1650
+ };
1651
+ }
1652
+ }
1653
+
1654
+ // ../mcp-core/dist/standard-schema.js
1655
+ import { zodToJsonSchema as zodToJsonSchema2 } from "zod-to-json-schema";
1656
+ function toStandardSchemaWithJSON(schema) {
1657
+ const jsonSchema = zodToJsonSchema2(schema, {
1658
+ target: "jsonSchema7"
1659
+ });
1660
+ return {
1661
+ "~standard": {
1662
+ version: 1,
1663
+ vendor: "auracheck-mcp-core",
1664
+ validate(value) {
1665
+ const result = schema.safeParse(value);
1666
+ if (result.success)
1667
+ return { value: result.data };
1668
+ return {
1669
+ issues: result.error.issues.map((issue) => ({
1670
+ message: issue.message,
1671
+ path: issue.path
1672
+ }))
1673
+ };
1674
+ },
1675
+ jsonSchema: {
1676
+ input: () => jsonSchema,
1677
+ output: () => jsonSchema
1678
+ }
1679
+ }
1680
+ };
1681
+ }
1682
+
1683
+ // src/mcp/server.ts
1684
+ import { McpServer } from "@modelcontextprotocol/server";
1685
+ import { serveStdio } from "@modelcontextprotocol/server/stdio";
1686
+ import { z as z10 } from "zod";
1687
+
1688
+ // src/browser-login.ts
1689
+ import { spawn } from "child_process";
1690
+ import { createHash, randomBytes } from "crypto";
1691
+ import http from "http";
1692
+
1693
+ // src/api.ts
1694
+ async function exchangeCliCode(baseUrl, input) {
1695
+ const url = `${normalizeBaseUrl(baseUrl)}/api/auth/cli/exchange`;
1696
+ let res;
1697
+ try {
1698
+ res = await fetch(url, {
1699
+ method: "POST",
1700
+ headers: {
1701
+ "Content-Type": "application/json",
1702
+ Accept: "application/json"
1703
+ },
1704
+ body: JSON.stringify(input)
1705
+ });
1706
+ } catch (err) {
1707
+ throw new ApiError(0, "", `Network error calling ${url}: ${err.message}`);
1708
+ }
1709
+ const text = await res.text();
1710
+ let parsed = null;
1711
+ try {
1712
+ parsed = JSON.parse(text);
1713
+ } catch {
1714
+ }
1715
+ if (res.status === 404 || res.ok && !parsed?.token) {
1716
+ throw new ApiError(
1717
+ res.status,
1718
+ text,
1719
+ `${normalizeBaseUrl(baseUrl)} does not support browser sign-in for the CLI yet. Use \`auracheck login --token <67ci_\u2026>\` with a CI token from the project's Integrations page.`
1720
+ );
1721
+ }
1722
+ if (!res.ok) {
1723
+ throw new ApiError(
1724
+ res.status,
1725
+ text,
1726
+ `Sign-in failed (${res.status}): ${parsed?.error ?? text.slice(0, 200)}`
1727
+ );
1728
+ }
1729
+ return parsed;
1730
+ }
1731
+
1732
+ // src/config.ts
1733
+ import { promises as fs } from "fs";
1734
+ import { homedir } from "os";
1735
+ import path from "path";
1736
+ import { z as z9 } from "zod";
1737
+ var DEFAULT_EXCLUDE = [
1738
+ "node_modules",
1739
+ "dist",
1740
+ "build",
1741
+ ".git",
1742
+ ".next",
1743
+ ".turbo",
1744
+ "coverage",
1745
+ ".cache"
1746
+ ];
1747
+ var PROJECT_CONFIG_FILENAME = ".sixseven/config.json";
1748
+ var DEFAULT_BASE_URL = "https://space.auracheck.ai.id";
1749
+ var LEGACY_BASE_URLS = [
1750
+ "https://sixseven-space.sprout.co.id",
1751
+ "https://sixseven.sprout.co.id",
1752
+ "https://sixseven-api.sprout.co.id"
1753
+ ];
1754
+ function migrateLegacyBaseUrl(url) {
1755
+ const normalized = normalizeBaseUrl2(url);
1756
+ return LEGACY_BASE_URLS.includes(normalized) ? DEFAULT_BASE_URL : normalized;
1757
+ }
1758
+ function credentialsDir() {
1759
+ return process.env.AURACHECK_HOME ?? process.env.SIXSEVEN_HOME ?? path.join(homedir(), ".auracheck");
1760
+ }
1761
+ function credentialsFile() {
1762
+ return path.join(credentialsDir(), "credentials");
1763
+ }
1764
+ function legacyCredentialsDir() {
1765
+ if (process.env.AURACHECK_HOME || process.env.SIXSEVEN_HOME) return null;
1766
+ return path.join(homedir(), ".sixseven");
1767
+ }
1768
+ function legacyCredentialsFile() {
1769
+ const dir = legacyCredentialsDir();
1770
+ return dir ? path.join(dir, "credentials") : null;
1771
+ }
1772
+ var projectConfigSchema = z9.object({
1773
+ baseUrl: z9.string().url(),
1774
+ projectId: z9.string().min(1),
1775
+ defaultFeatureId: z9.string().nullish(),
1776
+ codeRoots: z9.array(z9.string().min(1)).default(["."]),
1777
+ exclude: z9.array(z9.string()).default(DEFAULT_EXCLUDE),
1778
+ platform: z9.enum(["web", "android", "ios"]).default("web")
1779
+ });
1780
+ var credentialsSchema = z9.object({
1781
+ tokens: z9.record(z9.string()).default({}),
1782
+ /** Base URL of the last `auracheck login`; used when no project config names one. */
1783
+ defaultBaseUrl: z9.string().optional(),
1784
+ /** Base URLs whose saved token was pasted with `--token` (not created by this sign-in). */
1785
+ pasted: z9.array(z9.string()).optional(),
1786
+ /**
1787
+ * Machine-wide default project, set by `auracheck.bind_project` (MCP) when
1788
+ * run outside a bound repo — i.e. there's no `.sixseven/config.json` to
1789
+ * write a per-repo binding into. A per-repo binding always wins over this.
1790
+ */
1791
+ defaultProjectId: z9.string().optional()
1792
+ });
1793
+ async function fileExists(p) {
1794
+ try {
1795
+ await fs.stat(p);
1796
+ return true;
1797
+ } catch {
1798
+ return false;
1799
+ }
1800
+ }
1801
+ async function findRepoRoot(start) {
1802
+ let cur = path.resolve(start);
1803
+ while (true) {
1804
+ if (await fileExists(path.join(cur, PROJECT_CONFIG_FILENAME))) {
1805
+ return cur;
1806
+ }
1807
+ const parent = path.dirname(cur);
1808
+ if (parent === cur) return null;
1809
+ cur = parent;
1810
+ }
1811
+ }
1812
+ async function readProjectConfig(repoRoot) {
1813
+ const p = path.join(repoRoot, PROJECT_CONFIG_FILENAME);
1814
+ const raw = await fs.readFile(p, "utf8");
1815
+ const parsed = JSON.parse(raw);
1816
+ const config = projectConfigSchema.parse(parsed);
1817
+ const baseUrl = migrateLegacyBaseUrl(config.baseUrl);
1818
+ if (baseUrl !== normalizeBaseUrl2(config.baseUrl)) {
1819
+ process.stderr.write(
1820
+ `AuraCheck CLI: ${PROJECT_CONFIG_FILENAME} points at a retired host; using ${baseUrl} for this run. Update "baseUrl" in that file to stop seeing this.
1821
+ `
1822
+ );
1823
+ return { ...config, baseUrl };
1824
+ }
1825
+ return config;
1826
+ }
1827
+ async function writeProjectConfig(repoRoot, cfg) {
1828
+ const dir = path.join(repoRoot, ".sixseven");
1829
+ await fs.mkdir(dir, { recursive: true });
1830
+ const p = path.join(dir, "config.json");
1831
+ await fs.writeFile(p, `${JSON.stringify(cfg, null, 2)}
1832
+ `, "utf8");
1833
+ return p;
1834
+ }
1835
+ function migrateLegacyCredentials(creds) {
1836
+ const tokens = {};
1837
+ for (const [key, token] of Object.entries(creds.tokens)) {
1838
+ const normalized = normalizeBaseUrl2(key);
1839
+ if (migrateLegacyBaseUrl(key) === normalized) tokens[normalized] = token;
1840
+ }
1841
+ const migratedFrom = /* @__PURE__ */ new Set();
1842
+ for (const [key, token] of Object.entries(creds.tokens)) {
1843
+ const normalized = normalizeBaseUrl2(key);
1844
+ const mapped = migrateLegacyBaseUrl(key);
1845
+ if (mapped === normalized) continue;
1846
+ migratedFrom.add(normalized);
1847
+ if (!(mapped in tokens)) tokens[mapped] = token;
1848
+ }
1849
+ const defaultBaseUrl = creds.defaultBaseUrl ? migrateLegacyBaseUrl(creds.defaultBaseUrl) : creds.defaultBaseUrl;
1850
+ const changed = migratedFrom.size > 0 || defaultBaseUrl !== creds.defaultBaseUrl;
1851
+ if (!changed) return { creds, changed: false, migratedFrom: [] };
1852
+ return {
1853
+ creds: { tokens, defaultBaseUrl, defaultProjectId: creds.defaultProjectId },
1854
+ changed: true,
1855
+ migratedFrom: [...migratedFrom]
1856
+ };
1857
+ }
1858
+ async function removeLegacyCredentials(legacyFile) {
1859
+ await fs.unlink(legacyFile).catch(() => {
1860
+ });
1861
+ const dir = path.dirname(legacyFile);
1862
+ const entries = await fs.readdir(dir).catch(() => null);
1863
+ if (entries && entries.length === 0) {
1864
+ await fs.rmdir(dir).catch(() => {
855
1865
  });
856
- const defaultFeatureId = ctx.config?.defaultFeatureId ?? null;
857
- let cached = null;
858
- async function currentApi() {
859
- const token = ctx.tokenSource === 'env' ? ctx.token : await getToken(ctx.baseUrl);
860
- if (!token)
861
- throw new NotSignedInError(ctx.baseUrl);
862
- if (cached?.token !== token) {
863
- cached = { token, api: new SixSevenApi({ baseUrl: ctx.baseUrl, token }) };
1866
+ }
1867
+ }
1868
+ async function migrateCredentialsDirOnce() {
1869
+ const legacyFile = legacyCredentialsFile();
1870
+ if (!legacyFile || !await fileExists(legacyFile)) return;
1871
+ let legacyCreds;
1872
+ try {
1873
+ legacyCreds = credentialsSchema.parse(
1874
+ JSON.parse(await fs.readFile(legacyFile, "utf8"))
1875
+ );
1876
+ } catch {
1877
+ await removeLegacyCredentials(legacyFile);
1878
+ return;
1879
+ }
1880
+ const file = credentialsFile();
1881
+ if (!await fileExists(file)) {
1882
+ await fs.mkdir(credentialsDir(), { recursive: true, mode: 448 });
1883
+ await fs.writeFile(file, `${JSON.stringify(legacyCreds, null, 2)}
1884
+ `, {
1885
+ mode: 384
1886
+ });
1887
+ const verified = await fs.readFile(file, "utf8").then((raw) => credentialsSchema.parse(JSON.parse(raw))).catch(() => null);
1888
+ if (!verified || JSON.stringify(verified.tokens) !== JSON.stringify(legacyCreds.tokens)) {
1889
+ return;
1890
+ }
1891
+ } else {
1892
+ const existing = await fs.readFile(file, "utf8").then((raw) => credentialsSchema.parse(JSON.parse(raw))).catch(() => null);
1893
+ if (!existing) return;
1894
+ const mergedTokens = { ...legacyCreds.tokens, ...existing.tokens };
1895
+ if (Object.keys(mergedTokens).length !== Object.keys(existing.tokens).length) {
1896
+ await writeCredentials({ ...existing, tokens: mergedTokens });
1897
+ }
1898
+ }
1899
+ await removeLegacyCredentials(legacyFile);
1900
+ process.stderr.write(
1901
+ "AuraCheck CLI: moved your sign-in from ~/.sixseven to ~/.auracheck.\n"
1902
+ );
1903
+ }
1904
+ async function readCredentials() {
1905
+ await migrateCredentialsDirOnce();
1906
+ const file = credentialsFile();
1907
+ if (!await fileExists(file)) {
1908
+ return { tokens: {} };
1909
+ }
1910
+ const raw = await fs.readFile(file, "utf8");
1911
+ let creds;
1912
+ try {
1913
+ creds = credentialsSchema.parse(JSON.parse(raw));
1914
+ } catch {
1915
+ return { tokens: {} };
1916
+ }
1917
+ const migration = migrateLegacyCredentials(creds);
1918
+ if (migration.changed) {
1919
+ await writeCredentials(migration.creds);
1920
+ process.stderr.write(
1921
+ `AuraCheck CLI: your sign-in was saved for ${migration.migratedFrom.join(", ")}, which AuraCheck has moved off of. Switched it to ${DEFAULT_BASE_URL} \u2014 same account, nothing to redo.
1922
+ `
1923
+ );
1924
+ }
1925
+ return migration.creds;
1926
+ }
1927
+ async function writeCredentials(creds) {
1928
+ await fs.mkdir(credentialsDir(), { recursive: true, mode: 448 });
1929
+ await fs.writeFile(credentialsFile(), `${JSON.stringify(creds, null, 2)}
1930
+ `, {
1931
+ mode: 384
1932
+ });
1933
+ }
1934
+ async function saveToken(baseUrl, token, opts = {}) {
1935
+ const creds = await readCredentials();
1936
+ const key = normalizeBaseUrl2(baseUrl);
1937
+ for (const k of Object.keys(creds.tokens)) {
1938
+ if (k !== key && normalizeBaseUrl2(k) === key) delete creds.tokens[k];
1939
+ }
1940
+ creds.tokens[key] = token;
1941
+ creds.pasted = (creds.pasted ?? []).filter(
1942
+ (k) => normalizeBaseUrl2(k) !== key
1943
+ );
1944
+ if (opts.pasted) creds.pasted.push(key);
1945
+ if (opts.makeDefault) creds.defaultBaseUrl = key;
1946
+ await writeCredentials(creds);
1947
+ }
1948
+ async function removeToken(baseUrl) {
1949
+ const creds = await readCredentials();
1950
+ const key = normalizeBaseUrl2(baseUrl);
1951
+ creds.pasted = (creds.pasted ?? []).filter(
1952
+ (k) => normalizeBaseUrl2(k) !== key
1953
+ );
1954
+ let removed = false;
1955
+ for (const k of Object.keys(creds.tokens)) {
1956
+ if (normalizeBaseUrl2(k) === key) {
1957
+ delete creds.tokens[k];
1958
+ removed = true;
1959
+ }
1960
+ }
1961
+ if (creds.defaultBaseUrl && normalizeBaseUrl2(creds.defaultBaseUrl) === key) {
1962
+ creds.defaultBaseUrl = void 0;
1963
+ }
1964
+ if (removed) await writeCredentials(creds);
1965
+ return removed;
1966
+ }
1967
+ async function setDefaultProjectId(projectId) {
1968
+ const creds = await readCredentials();
1969
+ creds.defaultProjectId = projectId;
1970
+ await writeCredentials(creds);
1971
+ }
1972
+ async function getToken(baseUrl) {
1973
+ const creds = await readCredentials();
1974
+ const key = normalizeBaseUrl2(baseUrl);
1975
+ const exact = creds.tokens[key];
1976
+ if (exact) return exact;
1977
+ for (const [k, v] of Object.entries(creds.tokens)) {
1978
+ if (normalizeBaseUrl2(k) === key) return v;
1979
+ }
1980
+ return null;
1981
+ }
1982
+ function normalizeBaseUrl2(u) {
1983
+ return u.replace(new RegExp("\\p{Cc}", "gu"), "").trim().replace(/\/+$/, "");
1984
+ }
1985
+ async function resolveContext(cwd, overrides = {}) {
1986
+ const root = await findRepoRoot(cwd);
1987
+ const config = root ? await readProjectConfig(root) : null;
1988
+ const creds = await readCredentials();
1989
+ const rawBaseUrl = normalizeBaseUrl2(
1990
+ overrides.baseUrl || process.env.AURACHECK_BASE_URL || process.env.SIXSEVEN_BASE_URL || config?.baseUrl || creds.defaultBaseUrl || DEFAULT_BASE_URL
1991
+ );
1992
+ const baseUrl = migrateLegacyBaseUrl(rawBaseUrl);
1993
+ if (baseUrl !== rawBaseUrl) {
1994
+ process.stderr.write(
1995
+ `AuraCheck CLI: ${rawBaseUrl} is retired; using ${baseUrl} instead.
1996
+ `
1997
+ );
1998
+ }
1999
+ const projectId = overrides.projectId || process.env.AURACHECK_PROJECT_ID || process.env.SIXSEVEN_PROJECT_ID || config?.projectId || creds.defaultProjectId || null;
2000
+ const envToken = process.env.AURACHECK_TOKEN?.trim() || process.env.SIXSEVEN_TOKEN?.trim() || null;
2001
+ const savedToken = envToken ? null : await getToken(baseUrl);
2002
+ return {
2003
+ config,
2004
+ configPath: root ? path.join(root, PROJECT_CONFIG_FILENAME) : null,
2005
+ repoRoot: root ?? path.resolve(cwd),
2006
+ baseUrl,
2007
+ projectId,
2008
+ platform: config?.platform ?? "web",
2009
+ token: envToken ?? savedToken,
2010
+ tokenSource: envToken ? "env" : savedToken ? "credentials" : null
2011
+ };
2012
+ }
2013
+
2014
+ // src/browser-login.ts
2015
+ var LOGIN_TIMEOUT_MS = 5 * 60 * 1e3;
2016
+ function makePkce() {
2017
+ const verifier = randomBytes(48).toString("base64url");
2018
+ return {
2019
+ state: randomBytes(24).toString("base64url"),
2020
+ verifier,
2021
+ challenge: createHash("sha256").update(verifier).digest("base64url")
2022
+ };
2023
+ }
2024
+ function buildLoginUrl(baseUrl, p) {
2025
+ const url = new URL("/desktop-login", `${normalizeBaseUrl2(baseUrl)}/`);
2026
+ url.searchParams.set("state", p.state);
2027
+ url.searchParams.set("code_challenge", p.challenge);
2028
+ url.searchParams.set("code_challenge_method", "S256");
2029
+ url.searchParams.set("redirect_uri", p.redirectUri);
2030
+ url.searchParams.set("client", "cli");
2031
+ return url.toString();
2032
+ }
2033
+ function openInBrowser(url) {
2034
+ const [cmd, args] = process.platform === "darwin" ? ["open", [url]] : process.platform === "win32" ? ["cmd", ["/c", "start", '""', url]] : ["xdg-open", [url]];
2035
+ try {
2036
+ const child = spawn(cmd, args, {
2037
+ stdio: "ignore",
2038
+ detached: true
2039
+ });
2040
+ child.on("error", () => void 0);
2041
+ child.unref();
2042
+ } catch {
2043
+ }
2044
+ }
2045
+ var PAGE_STYLE = "font-family:system-ui,sans-serif;max-width:32rem;margin:15vh auto;padding:0 16px;line-height:1.5";
2046
+ var PAGE = (title, body) => `<!doctype html><meta charset="utf-8"><title>${title}</title><body style="${PAGE_STYLE}"><h2>${title}</h2><p>${body}</p></body>`;
2047
+ async function browserLogin(opts) {
2048
+ const pkce = makePkce();
2049
+ const exchange = opts.exchange ?? exchangeCliCode;
2050
+ const server = http.createServer();
2051
+ await new Promise((resolve, reject) => {
2052
+ server.once("error", reject);
2053
+ server.listen(0, "127.0.0.1", () => resolve());
2054
+ });
2055
+ const { port } = server.address();
2056
+ const redirectUri = `http://127.0.0.1:${port}/callback`;
2057
+ try {
2058
+ return await new Promise((resolve, reject) => {
2059
+ let settled = false;
2060
+ const timer = setTimeout(() => {
2061
+ settled = true;
2062
+ reject(
2063
+ new Error(
2064
+ "Timed out waiting for the browser sign-in. Run `auracheck login` again."
2065
+ )
2066
+ );
2067
+ }, opts.timeoutMs ?? LOGIN_TIMEOUT_MS);
2068
+ server.on("request", (req, res) => {
2069
+ const url = new URL(req.url ?? "/", redirectUri);
2070
+ if (url.pathname !== "/callback") {
2071
+ res.writeHead(404).end();
2072
+ return;
864
2073
  }
865
- return cached.api;
866
- }
867
- const server = new Server({ name: 'sixseven', version: CLI_VERSION }, { capabilities: { tools: {} } });
868
- server.setRequestHandler(ListToolsRequestSchema, async () => ({
869
- tools: tools.map((t) => ({
870
- name: t.name,
871
- description: t.description,
872
- inputSchema: advertisedSchema(t),
873
- })),
874
- }));
875
- server.setRequestHandler(CallToolRequestSchema, async (req) => {
876
- const tool = tools.find((t) => t.name === req.params.name);
877
- if (!tool) {
878
- return {
879
- isError: true,
880
- content: [{ type: 'text', text: `Unknown tool: ${req.params.name}` }],
881
- };
2074
+ const send = (status, title, body) => {
2075
+ res.writeHead(status, {
2076
+ "Content-Type": "text/html; charset=utf-8",
2077
+ "Cache-Control": "no-store"
2078
+ });
2079
+ res.end(PAGE(title, body));
2080
+ };
2081
+ if (settled) {
2082
+ send(410, "Sign-in already finished", "You can close this tab.");
2083
+ return;
2084
+ }
2085
+ const code = url.searchParams.get("code");
2086
+ if (url.searchParams.get("state") !== pkce.state || !code) {
2087
+ send(
2088
+ 400,
2089
+ "This sign-in link is not for this terminal",
2090
+ "Go back to the terminal and run <code>auracheck login</code> again."
2091
+ );
2092
+ return;
882
2093
  }
2094
+ settled = true;
2095
+ clearTimeout(timer);
2096
+ exchange(opts.baseUrl, {
2097
+ code,
2098
+ codeVerifier: pkce.verifier,
2099
+ redirectUri,
2100
+ label: opts.label
2101
+ }).then(
2102
+ (result) => {
2103
+ send(
2104
+ 200,
2105
+ "Signed in to the AuraCheck CLI",
2106
+ "You can close this tab and go back to your terminal."
2107
+ );
2108
+ resolve(result);
2109
+ },
2110
+ (err) => {
2111
+ send(
2112
+ 400,
2113
+ "Sign-in failed",
2114
+ "Go back to the terminal for details, then run <code>auracheck login</code> again."
2115
+ );
2116
+ reject(err);
2117
+ }
2118
+ );
2119
+ });
2120
+ const loginUrl = buildLoginUrl(opts.baseUrl, {
2121
+ state: pkce.state,
2122
+ challenge: pkce.challenge,
2123
+ redirectUri
2124
+ });
2125
+ opts.onUrl(loginUrl);
2126
+ if (opts.openBrowser !== false) openInBrowser(loginUrl);
2127
+ });
2128
+ } finally {
2129
+ server.close();
2130
+ server.closeAllConnections?.();
2131
+ }
2132
+ }
2133
+
2134
+ // src/source-reader.ts
2135
+ import { promises as fs2 } from "fs";
2136
+ import path2 from "path";
2137
+ var DEFAULT_MAX_FILE_BYTES = 2e5;
2138
+ var DEFAULT_MAX_SEARCH_RESULTS = 200;
2139
+ var TEXT_EXT = /* @__PURE__ */ new Set([
2140
+ ".ts",
2141
+ ".tsx",
2142
+ ".js",
2143
+ ".jsx",
2144
+ ".mjs",
2145
+ ".cjs",
2146
+ ".json",
2147
+ ".yml",
2148
+ ".yaml",
2149
+ ".md",
2150
+ ".html",
2151
+ ".css",
2152
+ ".scss",
2153
+ ".less",
2154
+ ".toml",
2155
+ ".env",
2156
+ ".txt",
2157
+ ".py",
2158
+ ".go",
2159
+ ".rb",
2160
+ ".java",
2161
+ ".kt",
2162
+ ".swift",
2163
+ ".rs",
2164
+ ".php",
2165
+ ".cs",
2166
+ ".vue",
2167
+ ".svelte",
2168
+ ".sql",
2169
+ ".graphql",
2170
+ ".prisma"
2171
+ ]);
2172
+ var SourceReader = class {
2173
+ repoRoot;
2174
+ roots;
2175
+ excludeNames;
2176
+ excludeGlobs;
2177
+ maxFileBytes;
2178
+ constructor(opts) {
2179
+ this.repoRoot = path2.resolve(opts.repoRoot);
2180
+ this.roots = (opts.config.codeRoots.length ? opts.config.codeRoots : ["."]).map((r) => path2.resolve(this.repoRoot, r));
2181
+ const excludeNames = /* @__PURE__ */ new Set();
2182
+ const excludeGlobs = [];
2183
+ for (const e of opts.config.exclude) {
2184
+ if (e.includes("/") || e.includes("*")) excludeGlobs.push(e);
2185
+ else excludeNames.add(e);
2186
+ }
2187
+ this.excludeNames = excludeNames;
2188
+ this.excludeGlobs = excludeGlobs;
2189
+ this.maxFileBytes = opts.maxFileBytes ?? DEFAULT_MAX_FILE_BYTES;
2190
+ }
2191
+ /**
2192
+ * Resolve a user-supplied relative path. Rejects paths outside the repo root
2193
+ * and outside any configured codeRoot.
2194
+ */
2195
+ resolveSafe(relPath) {
2196
+ const cleaned = relPath.replace(/^[./\\]+/, "").replace(/\\/g, "/");
2197
+ const abs = path2.resolve(this.repoRoot, cleaned);
2198
+ const repoRel = path2.relative(this.repoRoot, abs);
2199
+ if (repoRel.startsWith("..") || path2.isAbsolute(repoRel)) {
2200
+ throw new Error(`Path escapes repo root: ${relPath}`);
2201
+ }
2202
+ if (!this.roots.some(
2203
+ (root) => abs === root || abs.startsWith(root + path2.sep)
2204
+ )) {
2205
+ throw new Error(
2206
+ `Path is outside configured codeRoots (${this.roots.map((r) => path2.relative(this.repoRoot, r)).join(", ")}): ${relPath}`
2207
+ );
2208
+ }
2209
+ if (this.isExcluded(abs)) {
2210
+ throw new Error(`Path matches exclude pattern: ${relPath}`);
2211
+ }
2212
+ return abs;
2213
+ }
2214
+ isExcluded(absPath) {
2215
+ const rel = path2.relative(this.repoRoot, absPath);
2216
+ const parts = rel.split(path2.sep);
2217
+ if (parts.some((p) => this.excludeNames.has(p))) return true;
2218
+ for (const g of this.excludeGlobs) {
2219
+ if (rel.includes(g.replace(/\*/g, ""))) return true;
2220
+ }
2221
+ return false;
2222
+ }
2223
+ async readFile(relPath) {
2224
+ const abs = this.resolveSafe(relPath);
2225
+ const stat = await fs2.stat(abs);
2226
+ if (!stat.isFile()) throw new Error(`Not a file: ${relPath}`);
2227
+ const ext = path2.extname(abs).toLowerCase();
2228
+ if (ext && !TEXT_EXT.has(ext)) {
2229
+ throw new Error(
2230
+ `Refusing to read non-text file: ${relPath} (extension ${ext})`
2231
+ );
2232
+ }
2233
+ const buf = await fs2.readFile(abs);
2234
+ const truncated = buf.byteLength > this.maxFileBytes;
2235
+ const sliced = truncated ? buf.subarray(0, this.maxFileBytes) : buf;
2236
+ return {
2237
+ path: path2.relative(this.repoRoot, abs),
2238
+ bytes: stat.size,
2239
+ content: sliced.toString("utf8"),
2240
+ truncated
2241
+ };
2242
+ }
2243
+ async listDir(relPath) {
2244
+ const abs = this.resolveSafe(relPath || ".");
2245
+ const stat = await fs2.stat(abs);
2246
+ if (!stat.isDirectory()) throw new Error(`Not a directory: ${relPath}`);
2247
+ const dirents = await fs2.readdir(abs, { withFileTypes: true });
2248
+ const entries = dirents.filter((d) => !this.isExcluded(path2.join(abs, d.name))).map((d) => ({
2249
+ name: d.name,
2250
+ type: d.isDirectory() ? "dir" : "file"
2251
+ })).sort(
2252
+ (a, b) => a.type === b.type ? a.name.localeCompare(b.name) : a.type === "dir" ? -1 : 1
2253
+ );
2254
+ return { path: path2.relative(this.repoRoot, abs), entries };
2255
+ }
2256
+ /**
2257
+ * Substring/regex search across configured codeRoots. Returns up to
2258
+ * maxResults matches (default 200). Walks the tree itself — no shell.
2259
+ */
2260
+ async search(query, opts = {}) {
2261
+ if (!query) return [];
2262
+ const maxResults = opts.maxResults ?? DEFAULT_MAX_SEARCH_RESULTS;
2263
+ const flags = opts.caseSensitive ? "g" : "gi";
2264
+ const re = opts.regex ? new RegExp(query, flags) : new RegExp(query.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), flags);
2265
+ const results = [];
2266
+ const walk = async (dir) => {
2267
+ if (results.length >= maxResults) return;
2268
+ let dirents;
2269
+ try {
2270
+ dirents = await fs2.readdir(dir, { withFileTypes: true });
2271
+ } catch {
2272
+ return;
2273
+ }
2274
+ for (const d of dirents) {
2275
+ if (results.length >= maxResults) return;
2276
+ const abs = path2.join(dir, d.name);
2277
+ if (this.isExcluded(abs)) continue;
2278
+ if (d.isDirectory()) {
2279
+ await walk(abs);
2280
+ } else if (d.isFile()) {
2281
+ const ext = path2.extname(d.name).toLowerCase();
2282
+ if (ext && !TEXT_EXT.has(ext)) continue;
2283
+ let content;
2284
+ try {
2285
+ const buf = await fs2.readFile(abs);
2286
+ if (buf.byteLength > this.maxFileBytes) continue;
2287
+ content = buf.toString("utf8");
2288
+ } catch {
2289
+ continue;
2290
+ }
2291
+ const lines = content.split(/\r?\n/);
2292
+ for (let i = 0; i < lines.length; i++) {
2293
+ const line = lines[i];
2294
+ if (re.test(line)) {
2295
+ results.push({
2296
+ file: path2.relative(this.repoRoot, abs),
2297
+ line: i + 1,
2298
+ preview: line.length > 240 ? `${line.slice(0, 240)}\u2026` : line
2299
+ });
2300
+ if (results.length >= maxResults) return;
2301
+ }
2302
+ re.lastIndex = 0;
2303
+ }
2304
+ }
2305
+ }
2306
+ };
2307
+ for (const root of this.roots) {
2308
+ await walk(root);
2309
+ if (results.length >= maxResults) break;
2310
+ }
2311
+ return results;
2312
+ }
2313
+ };
2314
+
2315
+ // src/mcp/server.ts
2316
+ var CLI_VERSION = "0.2.5";
2317
+ var LOCAL_ALL_CAPABILITIES = [
2318
+ "viewProject",
2319
+ "viewReports",
2320
+ "manageTestCases",
2321
+ "manageRuns",
2322
+ "runTests",
2323
+ "manageProjectSetup",
2324
+ "manageBugs"
2325
+ ];
2326
+ function fallbackAccountContext(user, baseUrl) {
2327
+ return {
2328
+ user: {
2329
+ id: user?.id ?? "unknown",
2330
+ name: user?.name ?? null,
2331
+ email: user?.email ?? "",
2332
+ roleLabel: user?.role ?? "unknown",
2333
+ capabilities: LOCAL_ALL_CAPABILITIES
2334
+ },
2335
+ company: { id: user?.companyId ?? "", name: "" },
2336
+ projects: [],
2337
+ subscription: {
2338
+ status: "unknown",
2339
+ planName: "",
2340
+ daysLeft: null,
2341
+ readOnly: false,
2342
+ inGrace: false,
2343
+ billingEnabled: false,
2344
+ runUsage: null
2345
+ },
2346
+ adminContact: null,
2347
+ renewalUrl: `${baseUrl}/admin/billing`,
2348
+ minLocalMcp: CLI_VERSION
2349
+ };
2350
+ }
2351
+ async function resolveLocalAccount(api, baseUrl) {
2352
+ try {
2353
+ const account = await api.mcpContext();
2354
+ return {
2355
+ ...account,
2356
+ user: { ...account.user, capabilities: LOCAL_ALL_CAPABILITIES }
2357
+ };
2358
+ } catch {
2359
+ const user = await api.me().catch(() => null);
2360
+ return fallbackAccountContext(user, baseUrl);
2361
+ }
2362
+ }
2363
+ var MOBILE_RUN_NEXT_STEP2 = 'Ask the person to open this run in the AuraCheck desktop app with the Android device or emulator connected and click "Run on local" (iOS: macOS desktop app, "Run on iOS"). Then call auracheck.wait_for_run: it waits while the run is pending.';
2364
+ var LOCAL_TOOLS = [
2365
+ // ---------- Whitebox: source code ----------
2366
+ {
2367
+ name: "auracheck.read_code",
2368
+ description: "Read a text file from the developer repo. Path is relative to repo root and must fall within configured codeRoots. Use to understand routes, components, validators, and fixtures before generating a testcase.",
2369
+ zod: z10.object({ path: z10.string().min(1) }),
2370
+ handler: async ({ path: path3 }, { reader }) => reader.readFile(path3)
2371
+ },
2372
+ {
2373
+ name: "auracheck.list_dir",
2374
+ description: "List entries of a directory inside the developer repo. Path is relative to repo root.",
2375
+ zod: z10.object({ path: z10.string().default(".") }),
2376
+ handler: async ({ path: path3 }, { reader }) => reader.listDir(path3)
2377
+ },
2378
+ {
2379
+ name: "auracheck.search_code",
2380
+ description: "Search developer repo (within codeRoots) for a substring or regex. Returns up to 200 matches with file + line + preview. Use to locate routes, handlers, components by name.",
2381
+ zod: z10.object({
2382
+ query: z10.string().min(1),
2383
+ regex: z10.boolean().optional(),
2384
+ caseSensitive: z10.boolean().optional(),
2385
+ maxResults: z10.number().int().positive().max(1e3).optional()
2386
+ }),
2387
+ handler: async (args, { reader }) => reader.search(args.query, args)
2388
+ },
2389
+ // ---------- AuraCheck: project context & onboarding ----------
2390
+ {
2391
+ name: "auracheck.whoami",
2392
+ description: "Report sign-in status, the base URL, and the project this MCP session is bound to, plus a nextStep hint for what to do next (sign in, bind a project, or nothing \u2014 already set up). Safe to call first, before signing in.",
2393
+ zod: z10.object({}).passthrough(),
2394
+ handler: async (_args, { api, signedIn, baseUrl, tokenSource }) => {
2395
+ const boundProjectId = await currentDefaultProjectId();
2396
+ if (!signedIn) {
2397
+ return {
2398
+ signedIn: false,
2399
+ baseUrl,
2400
+ cliVersion: CLI_VERSION,
2401
+ projectId: boundProjectId,
2402
+ nextStep: "Not signed in \u2014 call auracheck.login."
2403
+ };
2404
+ }
2405
+ const [user, project] = await Promise.all([
2406
+ api.me(),
2407
+ boundProjectId ? api.getProject(boundProjectId).catch(() => null) : Promise.resolve(null)
2408
+ ]);
2409
+ return {
2410
+ signedIn: true,
2411
+ user,
2412
+ baseUrl,
2413
+ tokenSource,
2414
+ cliVersion: CLI_VERSION,
2415
+ projectId: boundProjectId,
2416
+ project,
2417
+ nextStep: boundProjectId ? null : "No project bound \u2014 call auracheck.list_projects, ask the person which one, then auracheck.bind_project({ projectId })."
2418
+ };
2419
+ }
2420
+ },
2421
+ {
2422
+ name: "auracheck.login",
2423
+ description: "Sign in to AuraCheck through the browser (same OAuth/PKCE flow as `auracheck login` in a terminal) \u2014 no terminal needed. Opens the system browser and waits up to ~90s for the person to click Allow. If it times out before that, it returns the sign-in url and 'Not finished \u2014 call auracheck.login again to resume.'; calling it again starts a fresh attempt (no duplicate tokens are saved \u2014 a new sign-in simply replaces the old one for this baseUrl). On success the token is saved exactly like the CLI command, and tool calls that needed auracheck.login now work.",
2424
+ zod: z10.object({
2425
+ baseUrl: z10.string().url().optional(),
2426
+ timeoutSec: z10.number().int().positive().max(600).optional()
2427
+ }),
2428
+ handler: async (args, { baseUrl: ctxBaseUrl }) => {
2429
+ const baseUrl = normalizeBaseUrl2(args.baseUrl ?? ctxBaseUrl);
2430
+ let signInUrl = "";
2431
+ try {
2432
+ const result = await browserLogin({
2433
+ baseUrl,
2434
+ label: `AuraCheck MCP \xB7 ${hostname() || "unknown host"}`,
2435
+ timeoutMs: (args.timeoutSec ?? 90) * 1e3,
2436
+ openBrowser: process.env.AURACHECK_NO_BROWSER !== "1",
2437
+ onUrl: (url) => {
2438
+ signInUrl = url;
2439
+ }
2440
+ });
2441
+ await saveToken(baseUrl, result.token, { makeDefault: true });
2442
+ return {
2443
+ ok: true,
2444
+ baseUrl,
2445
+ user: result.user,
2446
+ message: `Signed in as ${result.user.email}.`
2447
+ };
2448
+ } catch (err) {
2449
+ if (signInUrl) {
2450
+ return {
2451
+ ok: false,
2452
+ baseUrl,
2453
+ url: signInUrl,
2454
+ message: "Not finished \u2014 the browser sign-in was not completed in time. Call auracheck.login again to resume (open the url yourself if the browser did not open)."
2455
+ };
2456
+ }
2457
+ throw err;
2458
+ }
2459
+ }
2460
+ },
2461
+ {
2462
+ name: "auracheck.logout",
2463
+ description: "Forget the locally saved sign-in for this baseUrl. Local only \u2014 does not revoke the token on the server (do that from Profile \u2192 Active devices if needed).",
2464
+ zod: z10.object({ baseUrl: z10.string().url().optional() }),
2465
+ handler: async (args, { baseUrl: ctxBaseUrl }) => {
2466
+ const baseUrl = normalizeBaseUrl2(args.baseUrl ?? ctxBaseUrl);
2467
+ const removed = await removeToken(baseUrl);
2468
+ return { ok: true, baseUrl, removed };
2469
+ }
2470
+ },
2471
+ {
2472
+ name: "auracheck.bind_project",
2473
+ description: "Set the default AuraCheck project for this repo (if a .sixseven/config.json binding exists or can be created in the current working directory) or, otherwise, as this machine-wide default \u2014 the same fallback project tools use when no projectId is passed. Verifies the id against auracheck.list_projects when signed in. Onboarding order: auracheck.login \u2192 auracheck.list_projects \u2192 ask the person which one \u2192 auracheck.bind_project.",
2474
+ zod: z10.object({ projectId: z10.string().min(1) }),
2475
+ handler: async ({ projectId }, { api, signedIn, repoRoot, config }) => {
2476
+ if (signedIn) {
2477
+ const projects = await api.listProjects().catch(() => null);
2478
+ if (projects && !projects.some((p) => p.id === projectId)) {
2479
+ throw new Error(
2480
+ `${projectId} is not in the list of projects this sign-in can reach. Call auracheck.list_projects.`
2481
+ );
2482
+ }
2483
+ }
2484
+ if (config) {
2485
+ const path3 = await writeProjectConfig(repoRoot, {
2486
+ ...config,
2487
+ projectId
2488
+ });
2489
+ return { ok: true, scope: "repo", projectId, configPath: path3 };
2490
+ }
2491
+ await setDefaultProjectId(projectId);
2492
+ return { ok: true, scope: "global", projectId };
2493
+ }
2494
+ },
2495
+ // ---------- AuraCheck: get_screenshot (local keeps its own outPath arg) ----------
2496
+ {
2497
+ name: "auracheck.get_screenshot",
2498
+ description: "Download a run screenshot (or any authenticated blob) to a local file and return its path, so it can then be opened and looked at. Pass a `screenshotUrl` straight from auracheck.get_evidence \u2014 those are bare paths that cannot be fetched without the bound base URL and CI token, so this is the only way to actually SEE a step's screenshot. Reach for it whenever a failure's cause is visual: 'the page froze' is often disproved by two consecutive screenshots being identical, or by the page rendering fine with a control merely disabled.",
2499
+ zod: z10.object({
2500
+ url: z10.string().min(1).describe(
2501
+ "screenshotUrl from get_evidence, e.g. '/api/blob/screenshots/<runId>/<caseId>-step14.png'. An absolute URL is accepted only on the bound host."
2502
+ ),
2503
+ outPath: z10.string().optional().describe(
2504
+ "Where to write it. Defaults to a temp file named after the blob."
2505
+ )
2506
+ }),
2507
+ handler: async (args, { api }) => {
2508
+ const { tmpdir } = await import("os");
2509
+ const path3 = await import("path");
2510
+ const { mkdir, writeFile } = await import("fs/promises");
2511
+ const { bytes, contentType } = await api.downloadBlob(args.url);
2512
+ const base = path3.basename(args.url.split("?")[0] || "").replace(/[^\w.-]/g, "_") || "screenshot.png";
2513
+ const dest = args.outPath ?? path3.join(tmpdir(), `auracheck-${Date.now()}-${base}`);
2514
+ await mkdir(path3.dirname(dest), { recursive: true });
2515
+ await writeFile(dest, bytes);
2516
+ return {
2517
+ path: dest,
2518
+ bytes: bytes.length,
2519
+ contentType,
2520
+ hint: "Open this path with your file-reading tool to view the image."
2521
+ };
2522
+ }
2523
+ }
2524
+ ];
2525
+ var NO_AUTH_TOOLS = /* @__PURE__ */ new Set([
2526
+ "auracheck.login",
2527
+ "auracheck.logout",
2528
+ "auracheck.whoami",
2529
+ "auracheck.bind_project"
2530
+ ]);
2531
+ var CODE_TOOLS = /* @__PURE__ */ new Set([
2532
+ "auracheck.read_code",
2533
+ "auracheck.list_dir",
2534
+ "auracheck.search_code"
2535
+ ]);
2536
+ function logErr(msg) {
2537
+ process.stderr.write(`[auracheck-mcp] ${msg}
2538
+ `);
2539
+ }
2540
+ var NotSignedInError = class extends Error {
2541
+ constructor(baseUrl) {
2542
+ super(
2543
+ `Not signed in to AuraCheck (${baseUrl}). Call auracheck.login (or run \`auracheck login\` in a terminal) \u2014 the MCP server picks up the new sign-in on the next call, no restart needed.`
2544
+ );
2545
+ }
2546
+ };
2547
+ var ONBOARDING_INSTRUCTIONS = `This server works before sign-in: auracheck.whoami, auracheck.login, auracheck.logout, auracheck.bind_project, and tools/list all work with no credentials. Every other tool needs a sign-in and a bound project.
2548
+
2549
+ First-run order for a new user: 1) auracheck.whoami to check status. 2) If not signed in, auracheck.login \u2014 it opens the person's browser and waits up to ~90s for them to click Allow; if it times out, call it again. 3) auracheck.list_projects, ask the person which project, then auracheck.bind_project({ projectId }). 4) Proceed with the project tools (they fall back to the bound project when projectId is omitted).
2550
+
2551
+ ${serverInstructions("local")}`;
2552
+ function toolResultContent(result) {
2553
+ return {
2554
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
2555
+ };
2556
+ }
2557
+ function errorResultContent(err) {
2558
+ return {
2559
+ isError: true,
2560
+ content: [
2561
+ {
2562
+ type: "text",
2563
+ text: err instanceof Error ? err.message : String(err)
2564
+ }
2565
+ ]
2566
+ };
2567
+ }
2568
+ var overridesRef = {};
2569
+ var runtimeCtx;
2570
+ async function currentDefaultProjectId() {
2571
+ if (overridesRef.projectId) return overridesRef.projectId;
2572
+ const envProjectId = process.env.AURACHECK_PROJECT_ID || process.env.SIXSEVEN_PROJECT_ID;
2573
+ if (envProjectId) return envProjectId;
2574
+ if (runtimeCtx.configPath) {
2575
+ const fresh = await readProjectConfig(runtimeCtx.repoRoot).catch(
2576
+ () => null
2577
+ );
2578
+ if (fresh?.projectId) return fresh.projectId;
2579
+ }
2580
+ const creds = await readCredentials();
2581
+ return creds.defaultProjectId ?? null;
2582
+ }
2583
+ async function runMcpServer(overrides = {}) {
2584
+ overridesRef = overrides;
2585
+ const ctx = await resolveContext(process.cwd(), overrides);
2586
+ runtimeCtx = ctx;
2587
+ const reader = new SourceReader({
2588
+ repoRoot: ctx.repoRoot,
2589
+ config: ctx.config ?? {
2590
+ baseUrl: ctx.baseUrl,
2591
+ projectId: ctx.projectId ?? "",
2592
+ defaultFeatureId: null,
2593
+ codeRoots: ["."],
2594
+ exclude: DEFAULT_EXCLUDE,
2595
+ platform: ctx.platform
2596
+ }
2597
+ });
2598
+ let cached = null;
2599
+ async function currentApi() {
2600
+ const token = ctx.tokenSource === "env" ? ctx.token : await getToken(ctx.baseUrl);
2601
+ if (!token) throw new NotSignedInError(ctx.baseUrl);
2602
+ if (cached?.token !== token) {
2603
+ cached = {
2604
+ token,
2605
+ api: new AuraCheckApi({
2606
+ baseUrl: ctx.baseUrl,
2607
+ token,
2608
+ signInHint: "Run `auracheck login` in a terminal to sign in again."
2609
+ })
2610
+ };
2611
+ }
2612
+ return cached.api;
2613
+ }
2614
+ const server = new McpServer(
2615
+ { name: "auracheck", version: CLI_VERSION },
2616
+ { instructions: ONBOARDING_INSTRUCTIONS }
2617
+ );
2618
+ for (const tool of LOCAL_TOOLS) {
2619
+ server.registerTool(
2620
+ tool.name,
2621
+ {
2622
+ description: tool.description,
2623
+ inputSchema: toStandardSchemaWithJSON(tool.zod)
2624
+ },
2625
+ async (rawArgs) => {
883
2626
  try {
884
- let args = (req.params.arguments ?? {});
885
- let callProjectId = ctx.projectId;
886
- if (PROJECT_TOOLS.has(tool.name)) {
887
- // `projectId` is ours, not part of the tool's own schema.
888
- const { projectId: argProjectId, ...rest } = args;
889
- if (typeof argProjectId === 'string' && argProjectId.trim()) {
890
- callProjectId = argProjectId.trim();
891
- }
892
- args = rest;
2627
+ const parsed = tool.zod.parse(rawArgs ?? {});
2628
+ let api;
2629
+ let signedIn;
2630
+ if (CODE_TOOLS.has(tool.name)) {
2631
+ api = null;
2632
+ signedIn = false;
2633
+ } else if (NO_AUTH_TOOLS.has(tool.name)) {
2634
+ try {
2635
+ api = await currentApi();
2636
+ signedIn = true;
2637
+ } catch {
2638
+ api = null;
2639
+ signedIn = false;
893
2640
  }
894
- const parsed = tool.zod.parse(args);
895
- // The code tools read the local repo only; they need no sign-in.
896
- const api = CODE_TOOLS.has(tool.name)
897
- ? null
898
- : await currentApi();
899
- const toolCtx = {
900
- api,
901
- reader,
902
- get projectId() {
903
- if (!callProjectId) {
904
- throw new Error('No AuraCheck project for this call: pass `projectId` (find it with sixseven.list_projects), or bind this repo with `auracheck init`.');
905
- }
906
- return callProjectId;
907
- },
908
- boundProjectId: ctx.projectId,
909
- defaultFeatureId,
910
- defaultPlatform: ctx.platform,
911
- baseUrl: ctx.baseUrl,
912
- // Re-read per call: a login after start comes from the credentials file.
913
- tokenSource: ctx.tokenSource === 'env' ? 'env' : 'credentials',
914
- };
915
- const result = await tool.handler(parsed, toolCtx);
916
- return {
917
- content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
918
- };
2641
+ } else {
2642
+ api = await currentApi();
2643
+ signedIn = true;
2644
+ }
2645
+ const localCtx = {
2646
+ api,
2647
+ signedIn,
2648
+ reader,
2649
+ baseUrl: ctx.baseUrl,
2650
+ tokenSource: ctx.tokenSource === "env" ? "env" : "credentials",
2651
+ config: ctx.config,
2652
+ repoRoot: ctx.repoRoot
2653
+ };
2654
+ const result = await tool.handler(parsed, localCtx);
2655
+ return toolResultContent(result);
2656
+ } catch (err) {
2657
+ return errorResultContent(err);
919
2658
  }
920
- catch (err) {
921
- return {
922
- isError: true,
923
- content: [
924
- {
925
- type: 'text',
926
- text: err?.message ?? String(err),
927
- },
928
- ],
929
- };
2659
+ }
2660
+ );
2661
+ }
2662
+ for (const tool of ALL_TOOLS.filter((t) => t.surfaces.includes("local"))) {
2663
+ server.registerTool(
2664
+ `auracheck.${localName(tool)}`,
2665
+ {
2666
+ title: tool.title,
2667
+ description: tool.description,
2668
+ inputSchema: toStandardSchemaWithJSON(tool.input),
2669
+ annotations: tool.annotations
2670
+ },
2671
+ async (rawArgs) => {
2672
+ try {
2673
+ const api = await currentApi();
2674
+ const account = await resolveLocalAccount(api, ctx.baseUrl);
2675
+ const defaultProjectId = await currentDefaultProjectId();
2676
+ const toolCtx = {
2677
+ api,
2678
+ surface: "local",
2679
+ appUrl: ctx.baseUrl,
2680
+ renewalUrl: account.renewalUrl,
2681
+ account,
2682
+ projectId: defaultProjectId,
2683
+ defaultPlatform: ctx.platform,
2684
+ onSetProject: async (projectId) => {
2685
+ if (ctx.config) {
2686
+ await writeProjectConfig(ctx.repoRoot, {
2687
+ ...ctx.config,
2688
+ projectId
2689
+ });
2690
+ } else {
2691
+ await setDefaultProjectId(projectId);
2692
+ }
2693
+ },
2694
+ waitForRunMaxSec: 300
2695
+ };
2696
+ const result = await callTool(tool.name, rawArgs, toolCtx);
2697
+ if (result.ok) return toolResultContent(result.result);
2698
+ return errorResultContent(new Error(result.error));
2699
+ } catch (err) {
2700
+ return errorResultContent(err);
930
2701
  }
931
- });
932
- const transport = new StdioServerTransport();
933
- await server.connect(transport);
934
- logErr(`ready v${CLI_VERSION}. baseUrl=${ctx.baseUrl} project=${ctx.projectId ?? '(none bound)'} repo=${ctx.repoRoot}`);
935
- // Diagnose the sign-in once, to stderr only (Claude Code's MCP log). Never
936
- // fatal: tool calls carry the same explanation.
937
- currentApi()
938
- .then((api) => api.me())
939
- .then((u) => logErr(`signed in as ${u.email} (${u.role})`))
940
- .catch((err) => logErr(`sign-in check failed: ${err instanceof ApiError || err instanceof NotSignedInError ? err.message : String(err)}`));
2702
+ }
2703
+ );
2704
+ }
2705
+ for (const prompt of PROMPTS) {
2706
+ server.registerPrompt(
2707
+ prompt.name,
2708
+ { title: prompt.name, description: prompt.description },
2709
+ () => ({
2710
+ messages: [
2711
+ {
2712
+ role: "user",
2713
+ content: { type: "text", text: prompt.text }
2714
+ }
2715
+ ]
2716
+ })
2717
+ );
2718
+ }
2719
+ serveStdio(() => server, {
2720
+ // 2025-era clients (Claude Code's current MCP client, as of this
2721
+ // writing) open with the legacy `initialize` handshake; pin them to a
2722
+ // 2025-era instance from this same factory rather than rejecting them.
2723
+ legacy: "serve"
2724
+ });
2725
+ logErr(
2726
+ `ready v${CLI_VERSION}. baseUrl=${ctx.baseUrl} project=${ctx.projectId ?? "(none bound)"} repo=${ctx.repoRoot}`
2727
+ );
2728
+ currentApi().then((api) => api.me()).then((u) => logErr(`signed in as ${u.email} (${u.role})`)).catch(
2729
+ (err) => logErr(
2730
+ `sign-in check failed: ${err instanceof ApiError || err instanceof NotSignedInError ? err.message : String(err)}`
2731
+ )
2732
+ );
941
2733
  }
2734
+ export {
2735
+ MOBILE_RUN_NEXT_STEP2 as MOBILE_RUN_NEXT_STEP,
2736
+ runMcpServer
2737
+ };
942
2738
  //# sourceMappingURL=server.js.map