@aarwitz/tapp 0.17.27 → 0.18.1

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.
@@ -251,13 +251,53 @@ async function listSimulators() {
251
251
  return { simulators: sims, booted: sims.filter((s) => s.booted) };
252
252
  }
253
253
 
254
+ // Which simulator a run drives. Public issue #31: with two simulators booted, `--device` was
255
+ // honoured for web only and every iOS path took whichever simulator simctl listed first — a
256
+ // production build instead of the sandbox one, then another agent session's simulator. A
257
+ // device is a name or UDID (`TAPP_UDID` is the environment default); with several booted and
258
+ // none chosen the answer is the list, not a guess.
259
+ export function selectSimulator(sims, device = "") {
260
+ const wanted = String(device || process.env.TAPP_UDID || "").trim();
261
+ const all = sims.simulators || [];
262
+ const booted = sims.booted || all.filter((s) => s.booted);
263
+ const describe = (list) => list.map((s) => `${s.name} (${s.udid})`).join(", ");
264
+ if (wanted) {
265
+ const lower = wanted.toLowerCase();
266
+ const match = all.find((s) => s.udid.toLowerCase() === lower)
267
+ || all.find((s) => s.name.toLowerCase() === lower)
268
+ || (() => { const p = booted.filter((s) => s.name.toLowerCase().startsWith(lower)); return p.length === 1 ? p[0] : null; })();
269
+ if (!match) return { error: `No simulator matches "${wanted}". Booted: ${booted.length ? describe(booted) : "none"}.` };
270
+ if (!match.booted) return { notBooted: match };
271
+ return { booted: match };
272
+ }
273
+ if (booted.length === 1) return { booted: booted[0] };
274
+ if (booted.length === 0) return { none: true };
275
+ return { error: `simulator-selection-required: ${booted.length} simulators are booted — ${describe(booted)}. Pass device (a name or UDID) or set TAPP_UDID so the run does not drive someone else's simulator.`, ambiguous: booted };
276
+ }
277
+
278
+ // The simulator the current engine process has chosen. Every simctl call and every spawned
279
+ // harness script must address it by UDID: the `booted` alias means "whichever is first".
280
+ let selectedSimUdid = null;
281
+ function simTarget() { return selectedSimUdid || "booted"; }
282
+ function simEnv() { return selectedSimUdid ? { TAPP_UDID: selectedSimUdid } : {}; }
283
+
254
284
  // Pre-flight for every iOS entry point: the #1 first-session failure is "no simulator
255
285
  // booted", and the harness's raw failure text is unactionable. Long-running tools
256
286
  // (run_qa) auto-boot the first available iPhone; fast tools return an instructive error
257
287
  // the agent can act on instead of a shrug.
258
- export async function ensureBootedSim({ autoBoot = false } = {}) {
288
+ export async function ensureBootedSim({ autoBoot = false, device = "" } = {}) {
259
289
  const sims = await listSimulators();
260
- if (sims.booted && sims.booted.length) return { booted: sims.booted[0] };
290
+ const choice = sims.error ? { none: true } : selectSimulator(sims, device);
291
+ if (choice.booted) { selectedSimUdid = choice.booted.udid; return { booted: choice.booted }; }
292
+ if (choice.error) return { error: choice.error };
293
+ if (choice.notBooted) {
294
+ if (!autoBoot) return { error: `${choice.notBooted.name} (${choice.notBooted.udid}) is not booted. Boot it with tapp_build (action boot) and retry.` };
295
+ await runCommand("xcrun", ["simctl", "boot", choice.notBooted.udid], { timeoutMs: 2 * 60 * 1000 });
296
+ const st = await runCommand("xcrun", ["simctl", "bootstatus", choice.notBooted.udid, "-b"], { timeoutMs: 3 * 60 * 1000 });
297
+ if (st.code !== 0) return { error: `Boot of ${choice.notBooted.name} failed — boot it manually with tapp_build (action boot).` };
298
+ selectedSimUdid = choice.notBooted.udid;
299
+ return { booted: { ...choice.notBooted, booted: true }, autoBooted: true };
300
+ }
261
301
  // A failed listing is NOT "no simulators" — surface the real reason (was silently
262
302
  // misdiagnosed as "No iOS simulators exist" when simctl errored in odd environments).
263
303
  if (sims.error) {
@@ -272,11 +312,12 @@ export async function ensureBootedSim({ autoBoot = false } = {}) {
272
312
  return { error: "No iOS simulators exist on this Mac. Install a simulator runtime in Xcode (Settings → Platforms), then retry." };
273
313
  }
274
314
  if (!autoBoot) {
275
- return { error: `No simulator is booted. Call tapp_boot_simulator (e.g. udid "${candidate.udid}" — ${candidate.name}) and retry.` };
315
+ return { error: `No simulator is booted. Call tapp_build (action boot) (e.g. udid "${candidate.udid}" — ${candidate.name}) and retry.` };
276
316
  }
277
317
  await runCommand("xcrun", ["simctl", "boot", candidate.udid], { timeoutMs: 2 * 60 * 1000 });
278
318
  const st = await runCommand("xcrun", ["simctl", "bootstatus", candidate.udid, "-b"], { timeoutMs: 3 * 60 * 1000 });
279
- if (st.code !== 0) return { error: `Auto-boot of ${candidate.name} failed — boot one manually with tapp_boot_simulator.` };
319
+ if (st.code !== 0) return { error: `Auto-boot of ${candidate.name} failed — boot one manually with tapp_build (action boot).` };
320
+ selectedSimUdid = candidate.udid;
280
321
  return { booted: candidate, autoBooted: true };
281
322
  }
282
323
 
@@ -284,7 +325,7 @@ export async function ensureBootedSim({ autoBoot = false } = {}) {
284
325
  // never installed). Without this pre-flight the harness reports a misleading "crashed at launch"
285
326
  // and sessions die with an unactionable error — check cheaply up front instead.
286
327
  async function appInstalledOnBootedSim(bundleId) {
287
- const r = await runCommand("xcrun", ["simctl", "get_app_container", "booted", bundleId, "app"], { timeoutMs: 15_000 });
328
+ const r = await runCommand("xcrun", ["simctl", "get_app_container", simTarget(), bundleId, "app"], { timeoutMs: 15_000 });
288
329
  return r.code === 0;
289
330
  }
290
331
 
@@ -292,7 +333,7 @@ function notInstalledError(bundleId, booted) {
292
333
  const name = booted && booted.name ? booted.name : "the booted simulator";
293
334
  return (
294
335
  `\`${bundleId}\` is not installed on ${name}. Install a simulator build first — ` +
295
- `tapp_install_app with the .app path (CLI: xcrun simctl install booted path/to/App.app) — ` +
336
+ `tapp_build (action install) with the .app path (CLI: xcrun simctl install booted path/to/App.app) — ` +
296
337
  `or double-check the bundle id (xcrun simctl listapps booted).`
297
338
  );
298
339
  }
@@ -302,7 +343,7 @@ function notInstalledError(bundleId, booted) {
302
343
  // and the tapp_build MCP tool.
303
344
 
304
345
  export async function listInstalledUserApps() {
305
- const r = await runCommand("xcrun", ["simctl", "listapps", "booted"], { timeoutMs: 30_000, rawStdout: true });
346
+ const r = await runCommand("xcrun", ["simctl", "listapps", simTarget()], { timeoutMs: 30_000, rawStdout: true });
306
347
  if (r.code !== 0) return { error: "Could not list installed apps", details: { stderr: r.stderr } };
307
348
  // simctl emits an old-style plist; plutil converts it.
308
349
  const tmp = path.join(os.tmpdir(), `tapp-apps-${Date.now().toString(36)}.plist`);
@@ -510,16 +551,16 @@ export async function installAppOnBootedSim(appPath, { cleanInstall = true, onSt
510
551
  const bundleId = (bid.stdout || "").trim();
511
552
  if (!bundleId) return { error: `Could not read CFBundleIdentifier from ${appPath}/Info.plist — is this a simulator .app build?` };
512
553
  if (cleanInstall) {
513
- const existing = await runCommand("xcrun", ["simctl", "get_app_container", "booted", bundleId, "app"], { timeoutMs: 15_000 });
554
+ const existing = await runCommand("xcrun", ["simctl", "get_app_container", simTarget(), bundleId, "app"], { timeoutMs: 15_000 });
514
555
  if (existing.code === 0 && (existing.stdout || "").trim()) onStatus(replacingInstalledBuildNotice(bundleId));
515
556
  }
516
557
  if (cleanInstall) {
517
558
  // Clean install: stale keychain items from a previous install leave apps half-signed-in
518
559
  // (Firebase Auth's "error accessing the keychain") — uninstall first for a fresh state.
519
- await runCommand("xcrun", ["simctl", "terminate", "booted", bundleId], { timeoutMs: 30_000 });
520
- await runCommand("xcrun", ["simctl", "uninstall", "booted", bundleId], { timeoutMs: 60_000 });
560
+ await runCommand("xcrun", ["simctl", "terminate", simTarget(), bundleId], { timeoutMs: 30_000 });
561
+ await runCommand("xcrun", ["simctl", "uninstall", simTarget(), bundleId], { timeoutMs: 60_000 });
521
562
  }
522
- const inst = await runCommand("xcrun", ["simctl", "install", "booted", appPath], { timeoutMs: 3 * 60 * 1000 });
563
+ const inst = await runCommand("xcrun", ["simctl", "install", simTarget(), appPath], { timeoutMs: 3 * 60 * 1000 });
523
564
  if (inst.code !== 0) return { error: `Install failed: ${(inst.stderr || "").trim().slice(0, 300)}` };
524
565
  return { bundleId };
525
566
  }
@@ -762,11 +803,11 @@ function focusMetadata(result) {
762
803
  return metadata;
763
804
  }
764
805
 
765
- async function startSession(bundleId, extraEnv = {}) {
806
+ async function startSession(bundleId, extraEnv = {}, { device = "" } = {}) {
766
807
  if (activeSession && !activeSession.ended) {
767
- return { error: "A session is already active; call tapp_session_end first.", screen: treeSnapshot() };
808
+ return { error: "A session is already active; call tapp_session (action end) first.", screen: treeSnapshot() };
768
809
  }
769
- const sim = await ensureBootedSim();
810
+ const sim = await ensureBootedSim({ device });
770
811
  if (sim.error) return { error: sim.error };
771
812
  if (!(await appInstalledOnBootedSim(bundleId))) return { error: notInstalledError(bundleId, sim.booted) };
772
813
  const token = Date.now().toString(36) + Math.random().toString(36).slice(2, 6);
@@ -777,11 +818,11 @@ async function startSession(bundleId, extraEnv = {}) {
777
818
  const captureScript = path.join(scriptsDir, "quick-capture.sh");
778
819
  const proc = spawn("bash", [captureScript, "session", bundleId], {
779
820
  cwd: repoRoot,
780
- env: { ...process.env, ...extraEnv, OCQA_SESSION_CMD_PATH: cmdPath, OCQA_SESSION_RESULT_PATH: resultPath, OCQA_SESSION_TIMEOUT: "7200" },
821
+ env: { ...process.env, ...simEnv(), ...extraEnv, OCQA_SESSION_CMD_PATH: cmdPath, OCQA_SESSION_RESULT_PATH: resultPath, OCQA_SESSION_TIMEOUT: "7200" },
781
822
  });
782
823
  activeSession = {
783
824
  platform:"ios", proc, bundleId, seq: 0, cmdPath, resultPath, latestTree: null, treeVersion: 0, buffer: "", ready: false, ended: false,
784
- // Always-on recorder: each act appends a Flow step; tapp_flow_save snapshots it to a file.
825
+ // Always-on recorder: each act appends a Flow step; tapp_session (action save_flow) snapshots it to a file.
785
826
  recording: [],
786
827
  creds: { email: extraEnv.OCQA_TEST_EMAIL || "", password: extraEnv.OCQA_TEST_PASSWORD || "" },
787
828
  lastScreen: null,
@@ -811,7 +852,7 @@ async function startSession(bundleId, extraEnv = {}) {
811
852
 
812
853
  async function startAndroidSession(appId, { serial, apkPath, clearData = true, testEmail = "", testPassword = "" } = {}) {
813
854
  if (activeSession && !activeSession.ended) {
814
- return { error: "A session is already active; call tapp_session_end first.", screen: treeSnapshot() };
855
+ return { error: "A session is already active; call tapp_session (action end) first.", screen: treeSnapshot() };
815
856
  }
816
857
  try {
817
858
  const { AndroidDriver } = await import("./android-driver.js");
@@ -887,23 +928,23 @@ async function firstVisibleWebLocator(page, target, { input = false } = {}) {
887
928
  return await fallback.isVisible().catch(() => false) ? fallback : null;
888
929
  }
889
930
 
890
- async function startWebSession(url, { testEmail = "", testPassword = "", device = "", viewport = "" } = {}) {
891
- if (activeSession && !activeSession.ended) return { error: "A session is already active; call tapp_session_end first.", screen:treeSnapshot() };
931
+ async function startWebSession(url, { testEmail = "", testPassword = "", device = "", viewport = "", recordVideoDir = "" } = {}) {
932
+ if (activeSession && !activeSession.ended) return { error: "A session is already active; call tapp_session (action end) first.", screen:treeSnapshot() };
892
933
  let browser;
893
934
  try {
894
935
  const parsed = new URL(String(url || ""));
895
936
  if (!/^https?:$/.test(parsed.protocol)) return { error:"Web session URL must be http(s)" };
896
- const { loadPlaywright, webContextOptions } = await import("./web-explorer.js");
937
+ const { loadPlaywright, webContextOptions, webBrowserLaunchOptions } = await import("./web-explorer.js");
897
938
  const { chromium, devices } = await loadPlaywright();
898
- browser = await chromium.launch({ headless:true });
899
- const context = await browser.newContext(webContextOptions({ device, viewport, devices }));
939
+ browser = await chromium.launch(webBrowserLaunchOptions());
940
+ const context = await browser.newContext({ ...webContextOptions({ device, viewport, devices }), ...(recordVideoDir ? {recordVideo:{dir:recordVideoDir}} : {}) });
900
941
  const page = await context.newPage();
901
942
  await page.goto(parsed.href, { waitUntil:"domcontentloaded", timeout:30_000 });
902
943
  await page.waitForLoadState("networkidle", { timeout:5_000 }).catch(() => {});
903
944
  const snapshot = await webSessionSnapshot(page);
904
945
  activeSession = {
905
946
  platform:"web", browser, context, page, latestTree:snapshot, treeVersion:1, recording:[],
906
- creds:{ email:testEmail, password:testPassword },
947
+ creds:{ email:testEmail, password:testPassword }, credentialOrigin:parsed.origin,
907
948
  lastScreen:snapshot.screenTitle, ended:false,
908
949
  };
909
950
  return { ok:true, ...treeSnapshot(), url:snapshot.url };
@@ -1016,7 +1057,7 @@ function recordStep(cmd, result) {
1016
1057
  if (newScreen) activeSession.lastScreen = newScreen;
1017
1058
  }
1018
1059
 
1019
- // Argument shapes tapp_session_act accepts, per action. A malformed call is answered here with
1060
+ // Argument shapes tapp_session accepts, per action. A malformed call is answered here with
1020
1061
  // the accepted shape and never reaches the driver, so it can neither time out nor disturb the
1021
1062
  // session (feedback #7: `{action:"wait", seconds:3}` used to wait on an empty target).
1022
1063
  const SESSION_ACT_ARGS = Object.freeze({
@@ -1046,11 +1087,14 @@ export function sessionActUsageError(cmd = {}) {
1046
1087
  async function sessionAct(cmd) {
1047
1088
  const startedAt = Date.now();
1048
1089
  const done = (result) => ({ ...result, durationMs: Date.now() - startedAt });
1049
- if (!activeSession) return done({ error: "No active session. Call tapp_session_start first." });
1090
+ if (!activeSession) return done({ error: "No active session. Call tapp_session (action start) first." });
1050
1091
  if (activeSession.ended) return done({ error: sessionFailureReason(activeSession.buffer, activeSession.creds) });
1051
1092
  const usage = sessionActUsageError(cmd);
1052
1093
  if (usage) return done({ status: "usage", detail: usage, ...treeSnapshot(), recordedSteps: activeSession.recording.length });
1053
1094
  if (cmd.action === "login") {
1095
+ if (activeSession.platform === "web" && process.env.TAPP_ENFORCE_PUBLIC_EGRESS === "1" && new URL(activeSession.page.url()).origin !== activeSession.credentialOrigin) {
1096
+ return done({status:"blocked",detail:"The sign-in page is on another origin. Configure that authentication path before sending saved credentials.",...treeSnapshot()});
1097
+ }
1054
1098
  if (cmd.email) activeSession.creds.email = cmd.email;
1055
1099
  if (cmd.password) activeSession.creds.password = cmd.password;
1056
1100
  }
@@ -1226,6 +1270,7 @@ async function endSession() {
1226
1270
  const s = activeSession;
1227
1271
  if (s.platform === "web") {
1228
1272
  activeSession = null;
1273
+ await s.context?.close().catch(() => {});
1229
1274
  await s.browser.close().catch(() => {});
1230
1275
  if (s.managedRuntime) await stopManagedWebTarget(s.managedRuntime).catch(() => {});
1231
1276
  return { ok:true };
@@ -1399,8 +1444,8 @@ export async function captureInteractiveSessionFrame(maxWidth = 900) {
1399
1444
  // Fast "just show me a screen": launch the app fresh (optionally bypassing login), grab a screenshot
1400
1445
  // while it's on screen, return the tree too, then close it. No exploration. Uses the session
1401
1446
  // machinery only to keep the app alive long enough to photograph it.
1402
- export async function openApp(bundleId, extraEnv, maxWidth) {
1403
- const start = await startSession(bundleId, extraEnv);
1447
+ export async function openApp(bundleId, extraEnv, maxWidth, { device = "" } = {}) {
1448
+ const start = await startSession(bundleId, extraEnv, { device });
1404
1449
  if (start.error) return { error: start.error };
1405
1450
  const img = await captureScreenshotImage(maxWidth);
1406
1451
  const result = { screenTitle: start.screenTitle ?? null, elements: start.elements ?? [], img };
@@ -1415,7 +1460,7 @@ async function runExploreStreaming(bundleId, actions, timeout, env, onProgress)
1415
1460
  const captureScript = path.join(scriptsDir, "quick-capture.sh");
1416
1461
  const cmdArgs = [captureScript, "explore", bundleId, "--actions", String(actions), "--timeout", String(timeout)];
1417
1462
  const before = new Set(listCaptureRuns(80).map((r) => r.id));
1418
- const proc = spawn("bash", cmdArgs, { cwd: repoRoot, env: { ...process.env, ...env } });
1463
+ const proc = spawn("bash", cmdArgs, { cwd: repoRoot, env: { ...process.env, ...simEnv(), ...env } });
1419
1464
  proc.stdout.on("data", () => {});
1420
1465
  let captureStderr = "";
1421
1466
  proc.stderr.on("data", (chunk) => {
@@ -1426,6 +1471,7 @@ async function runExploreStreaming(bundleId, actions, timeout, env, onProgress)
1426
1471
  let captureDir = null;
1427
1472
  let pos = 0;
1428
1473
  let timedOut = false;
1474
+ let lastProgress = { action: 0, max: actions, states: 0 };
1429
1475
  // Interactive runs pause for a human — time spent waiting is excluded from the harness's own
1430
1476
  // budget, so give the watchdog matching headroom.
1431
1477
  const interactiveGrace = env.OCQA_INTERACTIVE_INPUT === "1" ? 900 : 0;
@@ -1450,7 +1496,17 @@ async function runExploreStreaming(bundleId, actions, timeout, env, onProgress)
1450
1496
  pos = size;
1451
1497
  for (const line of buf.toString("utf8").split("\n")) {
1452
1498
  if (line.startsWith("OCQA_PROGRESS:")) {
1453
- try { onProgress(JSON.parse(line.slice("OCQA_PROGRESS:".length))); } catch {}
1499
+ try { lastProgress = JSON.parse(line.slice("OCQA_PROGRESS:".length)); onProgress(lastProgress); } catch {}
1500
+ }
1501
+ // Per-action narration for transcript hosts; the harness does not always write a
1502
+ // narrative, so one is synthesized from the action itself.
1503
+ if (line.startsWith("OCQA_ACTION:")) {
1504
+ try {
1505
+ const action = JSON.parse(line.slice("OCQA_ACTION:".length));
1506
+ const target = action.identifier || action.label || action.target || (action.x !== undefined ? `(${action.x}, ${action.y})` : "");
1507
+ const narrative = action.narrative || `${String(action.type || "action").replace(/^\w/, (c) => c.toUpperCase())} ${target}${action.status === "disabled" ? " (disabled)" : ""}`.trim();
1508
+ onProgress({ ...lastProgress, narrative, ...(action.screen ? { screen: action.screen } : {}) });
1509
+ } catch {}
1454
1510
  }
1455
1511
  // Surface harness pause requests to the host as a sidecar file next to the response
1456
1512
  // path — prompting hosts (VS Code extension) poll it, answer the human, and write
@@ -1470,7 +1526,11 @@ async function runExploreStreaming(bundleId, actions, timeout, env, onProgress)
1470
1526
  if (which === "closed") break;
1471
1527
  if (Date.now() > hardDeadline) { try { proc.kill("SIGTERM"); } catch {} timedOut = true; break; }
1472
1528
  }
1473
- await closed;
1529
+ // 'close' needs every stdio pipe released; a grandchild (the simulator recorder) that survives
1530
+ // the script holds them open, and waiting on it unconditionally turned a finished exploration
1531
+ // into a hang. Give the script a bounded grace period, then carry on with what it wrote.
1532
+ const closedInTime = await Promise.race([closed.then(() => true), sleep(20_000).then(() => false)]);
1533
+ if (!closedInTime) { try { proc.kill("SIGKILL"); } catch {} }
1474
1534
  const created = listCaptureRuns(80).find((r) => !before.has(r.id))
1475
1535
  || (captureDir ? { id: path.basename(captureDir), path: captureDir, relativePath: path.relative(repoRoot, captureDir) } : null);
1476
1536
  return { created, timedOut, captureStderr };
@@ -1494,7 +1554,7 @@ export async function captureScreenshotImage(maxWidth) {
1494
1554
  const stamp = Date.now().toString(36) + Math.random().toString(36).slice(2, 6);
1495
1555
  const png = `/tmp/tapp-shot-${stamp}.png`;
1496
1556
  const jpg = `/tmp/tapp-shot-${stamp}.jpg`;
1497
- const r = await runCommand("xcrun", ["simctl", "io", "booted", "screenshot", png], { timeoutMs: 30_000 });
1557
+ const r = await runCommand("xcrun", ["simctl", "io", simTarget(), "screenshot", png], { timeoutMs: 30_000 });
1498
1558
  if (!fs.existsSync(png)) return { error: "Screenshot failed (is a simulator booted?)", stderr: r.stderr };
1499
1559
  await runCommand("sips", ["-Z", String(maxWidth), "-s", "format", "jpeg", "-s", "formatOptions", "60", png, "--out", jpg], { timeoutMs: 30_000 });
1500
1560
  const file = fs.existsSync(jpg) ? jpg : png;
@@ -1506,12 +1566,12 @@ export async function captureScreenshotImage(maxWidth) {
1506
1566
  }
1507
1567
 
1508
1568
  // ---- Model backend (subscription proxy / BYO key) — mirrors Tapp/Services/ModelBackend.swift.
1509
- // Used by AI-generate (tapp_flow_generate). Resolution: Tapp subscription token → proxy;
1569
+ // Used by AI-generate (tapp_session (action draft_flow)). Resolution: Tapp subscription token → proxy;
1510
1570
  // else ANTHROPIC_API_KEY → api.anthropic.com; else null (feature disabled).
1511
1571
  // Remote-AI opt-in for IMPLICIT model calls (post-run finding enrichment). A bare
1512
1572
  // ANTHROPIC_API_KEY is often ambient in dev shells — its mere presence must never silently
1513
1573
  // change data-handling behavior. A subscription token is an explicit tapp choice, and
1514
- // explicitly-invoked AI tools (tapp_flow_generate, assert_ai) carry their own consent.
1574
+ // explicitly-invoked AI tools (tapp_session (action draft_flow), assert_ai) carry their own consent.
1515
1575
  export function remoteAiOptedIn(env = process.env) {
1516
1576
  if ((env.TAPP_SUBSCRIPTION_TOKEN || "").trim()) return true;
1517
1577
  return ["1", "true", "yes"].includes(String(env.TAPP_ENABLE_REMOTE_AI || "").trim().toLowerCase());
@@ -1764,7 +1824,7 @@ export function qaNextSteps(report, surface = "mcp") {
1764
1824
  const next = [];
1765
1825
  if (report?.findings?.length) next.push("inspect the evidence with `npx -y @aarwitz/tapp@latest report latest`");
1766
1826
  next.push("save this run with `--json <report.json>`, then re-run with `--baseline <report.json>` to compare a fix (`tapp ci` gates it)");
1767
- next.push("replay a committed journey with `npx -y @aarwitz/tapp@latest flow run <file>`");
1827
+ next.push("replay a committed journey with `npx -y @aarwitz/tapp@latest run <file>`");
1768
1828
  return next;
1769
1829
  }
1770
1830
  const next = [];
@@ -1774,11 +1834,11 @@ export function qaNextSteps(report, surface = "mcp") {
1774
1834
  const reason = String(report.stopReason || "");
1775
1835
  if (reason.startsWith("login-wall")) next.push("re-run with `testEmail`/`testPassword` (or an `actor` from .tapp/project.json) — the sign-in wall was not exercised");
1776
1836
  else if (reason === "time-budget-exhausted") next.push("re-run with a larger `timeoutSeconds` or a smaller `maxActions` — the time budget ran out, not the app");
1777
- else next.push("check the app launches: `tapp_open_app` first (add `appLaunchArgs`/`appLaunchEnv` if it needs a test bypass), then re-run");
1837
+ else next.push("check the app launches: `tapp_look` first (add `appLaunchArgs`/`appLaunchEnv` if it needs a test bypass), then re-run");
1778
1838
  }
1779
- if (report?.findings?.length) next.push("open a flagged screen with `tapp_open_app`");
1839
+ if (report?.findings?.length) next.push("open a flagged screen with `tapp_look`");
1780
1840
  next.push("re-run with `baselineFindings` to gate a fix");
1781
- next.push("drive it step-by-step via `tapp_session_start`");
1841
+ next.push("drive it step-by-step via `tapp_session (action start)`");
1782
1842
  return next;
1783
1843
  }
1784
1844
 
@@ -2010,7 +2070,7 @@ export async function runQaAndroid({ appId, apkPath, serial, maxActions, timeout
2010
2070
  return { structured, text };
2011
2071
  }
2012
2072
 
2013
- export async function runQaIos({ bundleId, maxActions, timeout, args = {}, surface = "mcp", onProgress = () => {} }) {
2073
+ export async function runQaIos({ bundleId, maxActions, timeout, args = {}, device = "", surface = "mcp", onProgress = () => {} }) {
2014
2074
  const { storagePreflight } = await import("./environment-preflight.js");
2015
2075
  const storage = storagePreflight(capturesDir);
2016
2076
  if (!storage.ok) return { error: storage.message, details: { environment: "storage", storage } };
@@ -2018,7 +2078,7 @@ export async function runQaIos({ bundleId, maxActions, timeout, args = {}, surfa
2018
2078
  if (!fs.existsSync(captureScript)) return { error: "Capture script not found", details: { captureScript } };
2019
2079
 
2020
2080
  // run_qa runs for minutes anyway — auto-boot rather than bounce the user.
2021
- const sim = await ensureBootedSim({ autoBoot: true });
2081
+ const sim = await ensureBootedSim({ autoBoot: true, device });
2022
2082
  if (sim.error) return { error: sim.error };
2023
2083
  if (!(await appInstalledOnBootedSim(bundleId))) return { error: notInstalledError(bundleId, sim.booted) };
2024
2084
 
@@ -2547,10 +2607,10 @@ const server = new Server(
2547
2607
  // reaching for the wrong tool, in the order the mistakes actually happen.
2548
2608
  instructions: [
2549
2609
  "Tapp gives you hands and eyes on real iOS, Android and web app surfaces. Pick the smallest operation:",
2550
- "- see or screenshot one screen → tapp_open_app; what is on screen now → tapp_screenshot / tapp_ui_tree;",
2551
- "- reach a named screen or drive a journey → tapp_session_start (+ focus) then session_act;",
2610
+ "- see or screenshot one screen → tapp_look; what is on screen now → tapp_look / tapp_look (tree: true);",
2611
+ "- reach a named screen or drive a journey → tapp_session (action start) (+ focus) then session_act;",
2552
2612
  "- find bugs in an app or environment you own → tapp_explore (it clicks, types and submits; minutes);",
2553
- "- check production or a site you do not own → tapp_audit only (read-only: never clicks);",
2613
+ "- check production or a site you do not own → tapp_explore (readOnly: true) only (read-only: never clicks);",
2554
2614
  "- a merge decision → the CI gate (tapp ci / GitHub Action), never exploration.",
2555
2615
  "Results are observations with findings, coverage and evidence paths — never a score or ship verdict.",
2556
2616
  "inconclusive:true is not a pass; say what blocked coverage. A clean audit says the page is served without structural defects, not that the product works.",
@@ -2599,7 +2659,7 @@ server.setRequestHandler(GetPromptRequestSchema, async (request) => {
2599
2659
  text:
2600
2660
  `${goal}.${target} Use the connected Tapp tools on the real UI surface. ` +
2601
2661
  "Use the smallest operation that satisfies the request; initialize/explore the source repo only for a general repository test. " +
2602
- "For a named screen/control, pass the exact request as session focus or call tapp_focus so Tapp uses source + its observed UI Map instead of wandering. " +
2662
+ "For a named screen/control, pass the exact request as session focus or call tapp_explore (goal) so Tapp uses source + its observed UI Map instead of wandering. " +
2603
2663
  "If Tapp returns multiple target choices, ask me to select one instead of guessing. " +
2604
2664
  "Read visual evidence before describing it. Report findings, coverage, authority, inconclusive state, and checked/not-checked scope; " +
2605
2665
  "never turn exploration into a score or ship verdict. Do not edit the app unless I ask for a fix.",
@@ -2609,792 +2669,383 @@ server.setRequestHandler(GetPromptRequestSchema, async (request) => {
2609
2669
  };
2610
2670
  });
2611
2671
 
2612
- server.setRequestHandler(ListToolsRequestSchema, async () => ({
2613
- tools: [
2614
- {
2615
- name: "tapp_feedback",
2616
- title: "Send feedback to the tapp maintainers",
2617
- description:
2618
- "Draft a public GitHub issue on aarwitz/tapp about tapp itself — a bug in tapp, an idea, or a " +
2619
- "question (not a finding about the app under test). Adds the tapp version, platform availability, " +
2620
- "and the latest capture id automatically and redacts home paths and tokens. Default is a DRAFT: " +
2621
- "returns the composed issue plus a prefilled github.com URL the user can open. Pass submit:true only " +
2622
- "after the user has agreed to file a public issue; filing uses this machine's authenticated GitHub CLI.",
2623
- inputSchema: {
2624
- type: "object",
2625
- properties: {
2626
- title: { type: "string", description: "Short, specific title" },
2627
- body: { type: "string", description: "What happened, what you expected, the exact command or tool call. No secrets or private source." },
2628
- type: { type: "string", enum: ["bug", "idea", "question"], description: "Default bug" },
2629
- capture: { type: "string", description: "Capture id to reference, 'latest' (default) or 'none'" },
2630
- submit: { type: "boolean", description: "File the issue now with gh (needs the user's consent). Default false = draft only." },
2631
- },
2632
- required: ["title"],
2633
- },
2634
- },
2635
- {
2636
- name: "tapp_health",
2637
- title: "Check Tapp readiness",
2638
- description: "Check Tapp workspace and toolchain availability",
2639
- inputSchema: {
2640
- type: "object",
2641
- properties: {},
2642
- },
2643
- },
2644
- {
2645
- name: "tapp_build",
2646
- title: "Build the iOS app",
2647
- description:
2648
- "Build the user's iOS app for the simulator from an Xcode project/workspace (auto-detects the " +
2649
- "container and scheme under projectDir, default cwd), install it on the booted simulator, and " +
2650
- "return the bundle id. Use before tapp_explore / tapp_open_app when the app isn't installed yet — " +
2651
- "no bundle id needed up front.",
2652
- inputSchema: {
2653
- type: "object",
2654
- properties: {
2655
- authToken: {
2656
- type: "string",
2657
- description: "Required when TAPP_MCP_TOKEN is set",
2658
- },
2659
- projectDir: { type: "string", description: "Repo/dir to search for the .xcworkspace/.xcodeproj (default: cwd)" },
2660
- scheme: { type: "string", description: "Scheme to build (default: auto-detected)" },
2661
- configuration: { type: "string", default: "Debug" },
2662
- install: { type: "boolean", default: true, description: "Install on the booted simulator after building" },
2663
- },
2664
- },
2665
- },
2666
- {
2667
- name: "tapp_capture",
2668
- title: "Headless capture",
2669
- description: "Run headless capture workflows using scripts/quick-capture.sh",
2670
- inputSchema: {
2671
- type: "object",
2672
- properties: {
2673
- authToken: {
2674
- type: "string",
2675
- description: "Required when TAPP_MCP_TOKEN is set",
2676
- },
2677
- mode: {
2678
- type: "string",
2679
- enum: ["screenshot", "record", "explore", "tree"],
2680
- description: "Capture mode",
2681
- },
2682
- appBundleId: {
2683
- type: "string",
2684
- description: "Bundle ID (required for explore/tree)",
2685
- },
2686
- actions: {
2687
- type: "integer",
2688
- minimum: 1,
2689
- maximum: 1000,
2690
- description: "Action limit for explore",
2691
- },
2692
- duration: {
2693
- type: "integer",
2694
- minimum: 1,
2695
- maximum: 3600,
2696
- description: "Record duration in seconds",
2697
- },
2698
- testEmail: {
2699
- type: "string",
2700
- description: "Optional OCQA_TEST_EMAIL override",
2701
- },
2702
- testPassword: {
2703
- type: "string",
2704
- description: "Optional OCQA_TEST_PASSWORD override",
2705
- },
2706
- inputOverrides: {
2707
- type: "object",
2708
- description:
2709
- "Deterministic field values typed during explore. Map of field key -> value. " +
2710
- "Keys: 'id:<identifier>', 'label:<label>', or scoped 'screen:<title>|id:<identifier>'. " +
2711
- "Example: {\"id:email_field\": \"user@example.com\", \"id:zip\": \"90210\"}. " +
2712
- "Values replace the default 'test' input and are typed exactly as given on every run.",
2713
- additionalProperties: { type: "string" },
2714
- },
2715
- },
2716
- required: ["mode"],
2717
- },
2718
- },
2719
- {
2720
- name: "tapp_parse_markers",
2721
- title: "Parse capture markers",
2722
- description: "Parse OCQA markers from a capture run into structured summary",
2723
- inputSchema: {
2724
- type: "object",
2725
- properties: {
2726
- runId: {
2727
- type: "string",
2728
- description: "Capture run directory name under captures/",
2729
- },
2730
- runPath: {
2731
- type: "string",
2732
- description: "Absolute capture path override (must remain under captures/)",
2733
- },
2734
- },
2735
- },
2736
- },
2737
- {
2738
- name: "tapp_list_captures",
2739
- title: "List captures",
2740
- description: "List recent capture runs for THIS project (the workspace the server runs in). The captures directory is shared by every project on the machine; other projects' captures and pre-provenance captures are counted but hidden unless allProjects is true. Each entry carries provenance {kind, platform, target, project}. Use the capture a command just returned as evidence; never cite a capture from another project as if it were this one.",
2741
- inputSchema: {
2742
- type: "object",
2743
- properties: {
2744
- limit: {
2745
- type: "integer",
2746
- minimum: 1,
2747
- maximum: 100,
2748
- default: 10,
2749
- },
2750
- allProjects: { type: "boolean", default: false, description: "Include captures from other projects and captures without provenance — only when the user explicitly asks for historical evidence" },
2751
- },
2752
- },
2753
- },
2754
- {
2755
- name: "tapp_capture_summary",
2756
- title: "Capture summary",
2757
- description: "Show summary metadata for a capture run",
2758
- inputSchema: {
2759
- type: "object",
2760
- properties: {
2761
- runId: {
2762
- type: "string",
2763
- description: "Capture run directory name under captures/",
2764
- },
2765
- runPath: {
2766
- type: "string",
2767
- description: "Absolute capture path override",
2768
- },
2769
- },
2770
- },
2771
- },
2772
- {
2773
- name: "tapp_explore",
2774
- title: "Explore (autonomous)",
2775
- description:
2776
- "Autonomously explore iOS (appBundleId), Android (androidAppId), OR a web app " +
2777
- "(url — requires Playwright installed) and return a structured EXPLORATION OBSERVATION. " +
2778
- "Exploration OBSERVES — it surfaces findings + coverage + evidence; it does NOT render a ship " +
2779
- "verdict or score. To gate a merge, run the deterministic gate (contracts + baseline via CI). " +
2780
- "Use when the user wants to find bugs / observe what breaks — this " +
2781
- "runs for MINUTES exploring the whole app. Do NOT use it just to view, screenshot, or reach a specific " +
2782
- "screen — use tapp_open_app (launch + screenshot) or a session for that. Tapp explores the app " +
2783
- "like a tester (taps, types, navigates, scrolls) and detects real issues — crashes, dead buttons, failed sign-ins, error screens, " +
2784
- "stuck/hung screens; on web also uncaught JS exceptions, failed/5xx requests, broken links and assets. " +
2785
- "Returns {kind:'tapp-exploration-run', headline, inconclusive, screensExplored, " +
2786
- "actionsPerformed, findingCounts, findings:[{type,severity,category,authority,title,screen}]} — NO " +
2787
- "verdict/releaseScore. Web separates deterministic findings from advisory sampled control probes. " +
2788
- "There is a coverage floor: if the app barely explored (crash on launch / sign-in wall) it reports " +
2789
- "`inconclusive` — absence of findings is NEVER a pass. For iOS the app must already be installed on a booted simulator (use tapp_list_simulators / " +
2790
- "tapp_boot_simulator first). For web, only point it at an app/environment you own — it CLICKS things; for production or a site you do not own use tapp_audit (read-only). " +
2791
- "Tapp explores autonomously and does NOT pause to prompt for input — " +
2792
- "it fills forms with safe defaults. The result includes `inputFieldsEncountered` (and `inputHint`): if " +
2793
- "the app showed login/form fields and the user hasn't given you values, ASK THE USER what to enter (offer " +
2794
- "to use defaults or skip), then re-run with testEmail/testPassword or inputOverrides for a real result.",
2795
- inputSchema: {
2796
- type: "object",
2797
- properties: {
2798
- authToken: { type: "string", description: "Required when TAPP_MCP_TOKEN is set" },
2799
- appBundleId: { type: "string", description: "iOS: bundle id of the installed app to test, e.g. com.acme.app. Provide exactly one of appBundleId | url." },
2800
- androidAppId: { type: "string", description: "Android: application id installed on a connected emulator/device, e.g. com.acme.app." },
2801
- apkPath: { type: "string", description: "Android: optional APK to install before testing." },
2802
- androidSerial: { type: "string", description: "Android: optional adb device serial; defaults to the first authorized device." },
2803
- clearData: { type: "boolean", default: true, description: "Android: clear app data before launch for a repeatable starting state." },
2804
- url: { type: "string", description: "Web: URL of the app to explore in a real browser (same-origin only; your own app/staging). Provide exactly one of appBundleId | url." },
2805
- watch: { type: "boolean", default: false, description: "Web only: open Tapp's controlled Chromium window and show a cursor/HUD for each exploration action. Evidence screenshots exclude the overlay." },
2806
- device: { type: "string", description: "Web only: render as a Playwright device profile (e.g. \"iPhone 13\") — viewport, user agent, touch" },
2807
- viewport: { type: "string", description: "Web only: explicit viewport WIDTHxHEIGHT (e.g. \"390x844\"); overrides the device profile's viewport" },
2808
- maxActions: { type: "integer", minimum: 1, maximum: 1000, default: 60, description: "Exploration action budget" },
2809
- timeout: { type: "integer", minimum: 30, maximum: 3600, default: 600, description: "Max wall-clock seconds" },
2810
- testEmail: { type: "string", description: "Email for the login preamble, if the app has a sign-in" },
2811
- testPassword: { type: "string", description: "Password for the login preamble" },
2812
- interactive: { type: "boolean", description: "Host-with-a-human only (e.g. the VS Code extension): pause at input screens and wait for values via interactiveResponsePath. Plain agents: omit." },
2813
- interactiveResponsePath: { type: "string", description: "File path the prompting host answers on (requests appear at <path>.request)" },
2814
- visualReadyPath: { type: "string", description: "Local-client temp path written once the iOS target is foregrounded and settled, so previews exclude build/install footage" },
2815
- inputOverrides: {
2816
- type: "object",
2817
- additionalProperties: { type: "string" },
2818
- description:
2819
- "Deterministic field values typed during exploration. Map of field key -> value; keys are " +
2820
- "'id:<identifier>', 'label:<label>', or scoped 'screen:<title>|id:<identifier>'. " +
2821
- "Example: {\"id:email_field\": \"user@example.com\"}.",
2822
- },
2823
- appLaunchArgs: {
2824
- type: "array",
2825
- items: { type: "string" },
2826
- description: "Launch arguments passed to the app, e.g. [\"--uitesting\"] to enable a login bypass.",
2827
- },
2828
- appLaunchEnv: {
2829
- type: "object",
2830
- additionalProperties: { type: "string" },
2831
- description: "Launch environment for the app, e.g. {\"UI_TEST_BACKEND\": \"staging\"} to point it at a test backend.",
2832
- },
2833
- loginSteps: {
2834
- type: "array",
2835
- items: {},
2836
- description:
2837
- "Explicit login replay run BEFORE exploration, for custom login UIs the heuristic can't " +
2838
- "parse (the #1 reason a real app stays invisible). Each step is {action:'type'|'tap'|'wait', " +
2839
- "target:'<accessibility-id-or-label>', value?:'<text>', timeoutMs?:<for wait>} — or a shorthand " +
2840
- "string 'action:target[:value]'. $TEST_EMAIL/$TEST_PASSWORD are substituted from testEmail/" +
2841
- "testPassword. Example: [{\"action\":\"type\",\"target\":\"email_field\",\"value\":\"$TEST_EMAIL\"}," +
2842
- "{\"action\":\"type\",\"target\":\"password_field\",\"value\":\"$TEST_PASSWORD\"},{\"action\":\"tap\",\"target\":\"sign_in_button\"}].",
2843
- },
2844
- baselineFindings: {
2845
- type: "array",
2846
- items: { type: "object" },
2847
- description:
2848
- "Findings from a previous run (pass back the `findings` array a prior tapp_explore returned). " +
2849
- "When provided, the result adds a `regression` COMPARISON {counts:{new,persisting,resolved}, " +
2850
- "newFindings, resolved} vs. that baseline — an observation, not a gate signal. To gate a merge, " +
2851
- "run `npx -y @aarwitz/tapp@latest ci` (or the GitHub Action): it applies the deterministic policy and returns the " +
2852
- "pass/fail/inconclusive outcome.",
2853
- },
2854
- },
2855
- },
2856
- },
2857
- {
2858
- name: "tapp_audit",
2859
- title: "Audit (read-only)",
2860
- description:
2861
- "Read-only audit of a web page or site: renders it and reads it, NEVER clicks, types, submits or hovers — " +
2862
- "the one analysis safe to point at production or at a site you do not own. Finds controls that were never " +
2863
- "alive (dead in-page anchors, placeholder links, aria-controls naming nothing, buttons with no handler/form/link), " +
2864
- "images that failed to load, same-origin assets answering 404, 5xx/failed requests and uncaught JS exceptions " +
2865
- "during load, same-origin links answering 404/410/5xx, mixed content, and a page wider than its viewport. " +
2866
- "pages > 1 crawls same-origin links breadth-first with robots.txt honoured. Writes a capture (screenshots, " +
2867
- "per-finding evidence, report.html) like an explore run. Returns {kind:'tapp-structural-audit', readOnly:true, " +
2868
- "pagesAudited, findingCounts, pages:[{url,title,controlsExamined,linksChecked,findings}], checkedFor, notChecked, capture}. " +
2869
- "An observation, never a verdict; absence of findings says the page is served without structural defects, not that the product works. " +
2870
- "NOT for exercising behaviour (forms, buttons, journeys) on an app you own — that is tapp_explore or a session.",
2871
- inputSchema: {
2872
- type: "object",
2873
- properties: {
2874
- authToken: { type: "string", description: "Required when TAPP_MCP_TOKEN is set" },
2875
- url: { type: "string", description: "http(s) URL of the page to audit (the crawl start page when pages > 1)" },
2876
- pages: { type: "integer", default: 1, minimum: 1, maximum: 200, description: "How many same-origin pages to audit at most (1 = this page only)" },
2877
- delayMs: { type: "integer", default: 1000, minimum: 0, description: "Pause between pages when crawling — be polite to sites you do not own" },
2878
- linkCheckLimit: { type: "integer", default: 30, minimum: 0, description: "Same-origin links to HEAD-check per page" },
2879
- device: { type: "string", description: "Playwright device profile, e.g. 'iPhone 13' — audit the mobile rendering" },
2880
- viewport: { type: "string", description: "WIDTHxHEIGHT viewport override" },
2881
- capture: { type: "boolean", default: true, description: "Write a capture directory (screenshots, evidence, report.html)" },
2882
- },
2883
- required: ["url"],
2884
- },
2885
- },
2886
- {
2887
- name: "tapp_init",
2888
- title: "Inspect or explore a repository and create the Tapp application model and release plan",
2889
- description:
2890
- "Deterministically inspect repository targets, reviewed Tasks/contracts, actors, capabilities, entities, requirements, and the persistent UI Map. Returns an evidence-classified application model plus a compact grounded release-contract plan. `inspect` is read-only; `write` creates artifacts without overwriting; `refresh` updates source evidence; `explore` safely builds/starts a detected web target when url is omitted (or resolves native targets), runs the ordinary real-surface QA engine, tears managed runtimes down, merges its observed UI Map, then refreshes the model/plan while preserving explicit decisions and invalidating stale replay trust. Execution is deterministic/keyless and does not invoke AI unless remote AI was separately and explicitly enabled.",
2891
- inputSchema: {
2892
- type: "object",
2893
- properties: {
2894
- authToken: { type: "string", description: "Required when TAPP_MCP_TOKEN is set" },
2895
- operation: { type: "string", enum: ["inspect", "write", "refresh", "explore"], default: "inspect" },
2896
- projectDir: { type: "string", description: "Repo-relative project root; defaults to the MCP workspace root" },
2897
- platform: { type: "string", enum: ["ios", "android", "web"], description: "Optional target filter" },
2898
- url: { type: "string", description: "Owned web runtime URL when already running; omit during web explore to build/start one safely detected target" },
2899
- target: { type: "string", description: "Explore target selector: web target name/path, or iOS repo directory, Xcode container, .app, or bundle id; defaults to projectDir" },
2900
- appBundleId: { type: "string", description: "iOS explore: already-installed bundle id, avoiding a build" },
2901
- androidAppId: { type: "string", description: "Android explore: required application id" },
2902
- apkPath: { type: "string", description: "Android explore: optional repo-relative APK to install" },
2903
- androidSerial: { type: "string", description: "Android explore: optional adb device serial" },
2904
- maxActions: { type: "integer", minimum: 1, maximum: 1000, default: 40 },
2905
- timeout: { type: "integer", minimum: 30, maximum: 3600, default: 600 },
2906
- testEmail: { type: "string", description: "Explore: actor/login email; never persisted in the model" },
2907
- testPassword: { type: "string", description: "Explore: actor/login password; never persisted in the model" },
2908
- watch: { type: "boolean", default: false, description: "Web explore only: show the controlled browser and Tapp's actions" },
2909
- maxContracts: { type: "integer", minimum: 1, maximum: 50, default: 15 },
2910
- outDir: { type: "string", description: "Repo-relative artifact directory; default .tapp" },
2911
- },
2912
- },
2913
- },
2914
- {
2915
- name: "tapp_actor_config",
2916
- title: "Inspect or configure named test actors without storing credential values",
2917
- description:
2918
- "Manage the repository-native .tapp/project.json actor/session contract used by init, release-contract generation, and CI. `read` is inspect-only. `set` writes an explicit actor role, isolation/provisioning policy, and credential-name to environment-variable-name bindings. The tool never accepts, returns, or persists credential values and never overwrites an actor unless replace is explicit.",
2919
- inputSchema: {
2920
- type: "object",
2921
- properties: {
2922
- authToken: { type: "string", description: "Required when TAPP_MCP_TOKEN is set" },
2923
- operation: { type: "string", enum: ["read", "set"], default: "read" },
2924
- projectDir: { type: "string", description: "Repo-relative project root; defaults to the MCP workspace root" },
2925
- name: { type: "string", description: "Set: stable actor name" },
2926
- role: { type: "string", description: "Set: product role, such as member or admin" },
2927
- session: { type: "string", enum: ["default", "isolated"], default: "default" },
2928
- provisioning: { type: "string", enum: ["existing", "seeded", "api", "unknown"], default: "existing" },
2929
- credentialBindings: { type: "object", additionalProperties: { type: "string", pattern: "^[A-Z_][A-Z0-9_]{0,127}$" }, description: "Set: credential names mapped to environment-variable names, for example {email:'ALICE_EMAIL'}; values/secrets are forbidden" },
2930
- replace: { type: "boolean", default: false, description: "Explicitly replace an existing actor's non-secret configuration" },
2931
- },
2932
- },
2933
- },
2934
- {
2935
- name: "tapp_release_plan",
2936
- title: "Inspect or explicitly review a Tapp release plan",
2937
- description:
2938
- "Read the repository-native release plan, apply explicit approve/reject/defer decisions, generate grounded Task/contract drafts, deterministically validate drafts on a real target, or explicitly promote fully replay-validated drafts into reviewed repository-native artifacts. Review changes only decision metadata. Generation writes under .tapp/proposals, never overwrites, never invokes AI, and remains untrusted until real deterministic replay passes. Web validation can build/start/stop the detected managed target when url is omitted.",
2939
- inputSchema: {
2940
- type: "object",
2941
- properties: {
2942
- authToken: { type: "string", description: "Required when TAPP_MCP_TOKEN is set" },
2943
- operation: { type: "string", enum: ["read", "review", "generate", "validate", "promote"], default: "read" },
2944
- planPath: { type: "string", description: "Repo-relative plan path; default .tapp/release-plan.json" },
2945
- projectDir: { type: "string", description: "Generate: repo-relative project root containing the scoped .tapp Task directories" },
2946
- approve: { type: "array", items: { type: "string" }, description: "Plan item ids or names to approve" },
2947
- reject: { type: "array", items: { type: "string" }, description: "Plan item ids or names to reject" },
2948
- defer: { type: "array", items: { type: "string" }, description: "Plan item ids or names to defer" },
2949
- items: { type: "array", items: { type: "string" }, description: "Validate/promote only these plan item ids or names; defaults to every matching draft" },
2950
- platform: { type: "string", enum: ["ios", "android", "web"], description: "Validate: target platform; inferred when all selected drafts use one platform" },
2951
- url: { type: "string", description: "Validate web: already-running owned URL; omit to use Tapp's managed target lifecycle" },
2952
- target: { type: "string", description: "Validate managed web: target id, name, or source path when the repository has multiple browser targets" },
2953
- appBundleId: { type: "string", description: "Validate iOS: installed application bundle id" },
2954
- androidAppId: { type: "string", description: "Validate Android: installed application id" },
2955
- apkPath: { type: "string", description: "Validate Android: optional repo-relative APK" },
2956
- androidSerial: { type: "string", description: "Validate Android: optional adb serial" },
2957
- timeout: { type: "integer", minimum: 30, maximum: 3600, default: 600 },
2958
- },
2959
- },
2960
- },
2961
- {
2962
- name: "tapp_ci_setup",
2963
- title: "Create a target-scoped baseline or reviewable CI installation",
2964
- description:
2965
- "Complete the local release-contract onboarding loop from the shared application model. `inspect` renders a target-aware GitHub workflow and machine-readable CI manifest without writing; `install` writes both with collision protection; `baseline` imports an existing successful conclusive portable-gate report into a platform/target-specific repository baseline. No network resources, commits, pushes, branch protection, or AI are used.",
2966
- inputSchema: {
2967
- type: "object",
2968
- properties: {
2969
- authToken: { type: "string", description: "Required when TAPP_MCP_TOKEN is set" },
2970
- operation: { type: "string", enum: ["inspect", "install", "baseline"], default: "inspect" },
2971
- projectDir: { type: "string", description: "Repo-relative project root; defaults to the MCP workspace root" },
2972
- modelPath: { type: "string", description: "Repo-relative application model path; defaults to <projectDir>/.tapp/application-model.json" },
2973
- actionRef: { type: "string", description: "GitHub Action reference owner/repository@release-tag-or-sha; defaults to the current Tapp release tag" },
2974
- defaultBranch: { type: "string", default: "main" },
2975
- workflowPath: { type: "string", description: "Install: project-relative output; default .github/workflows/tapp.yml" },
2976
- manifestPath: { type: "string", description: "Install: project-relative output; default .tapp/ci.json" },
2977
- allowUnresolved: { type: "boolean", default: false, description: "Permit writing a draft whose manifest names unresolved target configuration" },
2978
- replace: { type: "boolean", default: false, description: "Explicitly replace an existing generated workflow/manifest or target baseline" },
2979
- reportPath: { type: "string", description: "Baseline: repo-relative successful conclusive portable-gate JSON report" },
2980
- platform: { type: "string", enum: ["ios", "android", "web"], description: "Baseline: select a target platform" },
2981
- target: { type: "string", description: "Baseline: application-model target id, name, or source path" },
2982
- baselinePath: { type: "string", description: "Baseline: optional project-relative target baseline output" },
2983
- },
2984
- },
2985
- },
2986
- {
2987
- name: "tapp_ui_map",
2988
- title: "Build, inspect, or diff the Tapp UI Map",
2989
- description:
2990
- "Use Tapp's first-class platform-neutral UI Map: evidence-grounded screen states, semantic controls, transitions, platform variants, provenance, and task/contract coverage hooks. " +
2991
- "QA runs create capture-local ui-map.json automatically. `read` returns one; `build` deterministically builds/merges a repository map from OCQA evidence; `diff` reports additions and absences without calling shallow-run absence a regression unless comparableFullSweep is explicitly true. No AI is used.",
2992
- inputSchema: {
2993
- type: "object",
2994
- properties: {
2995
- authToken: { type: "string", description: "Required when TAPP_MCP_TOKEN is set" },
2996
- operation: { type: "string", enum: ["read", "build", "diff"], default: "read" },
2997
- captureId: { type: "string", description: "Read/build from this Tapp capture's ocqa-markers.txt/ui-map.json" },
2998
- mapPath: { type: "string", description: "Repo-relative UI Map path for read, or build output (default .tapp/ui-map.json)" },
2999
- markersPath: { type: "string", description: "Repo-relative OCQA markers path for build when captureId is not supplied" },
3000
- beforePath: { type: "string", description: "Repo-relative baseline UI Map for diff" },
3001
- afterPath: { type: "string", description: "Repo-relative current UI Map for diff" },
3002
- platform: { type: "string", enum: ["ios", "android", "web"], default: "ios" },
3003
- target: { type: "string", description: "Bundle id, Android app id, or owned URL recorded as map provenance" },
3004
- replace: { type: "boolean", default: false, description: "Build: replace rather than merge existing repository map" },
3005
- comparableFullSweep: { type: "boolean", default: false, description: "Diff: only enable when both runs had comparable target/config/action budget; permits lost-reachability classification" },
3006
- },
3007
- },
3008
- },
3009
- {
3010
- name: "tapp_task",
3011
- title: "Inspect, validate, or compile a reusable deterministic Task",
3012
- description:
3013
- "Work with repository-native compositional Tasks in .tapp/tasks. Tasks define inputs, outputs, pre/postconditions, platform implementations, and the UI Map states/transitions they cover. " +
3014
- "Validation is deterministic and can ground selectors/coverage against ui-map.json. Compilation expands a Task into the shared keyless Flow contract with reviewable Task provenance; pass that returned flow to tapp_flow_run to replay it. No AI or API key is used.",
3015
- inputSchema: {
3016
- type: "object",
3017
- required: ["taskPath"],
3018
- properties: {
3019
- authToken: { type: "string", description: "Required when TAPP_MCP_TOKEN is set" },
3020
- operation: { type: "string", enum: ["read", "validate", "compile"], default: "validate" },
3021
- taskPath: { type: "string", description: "Repo-relative .tapp/tasks/*.yml|json file" },
3022
- platform: { type: "string", enum: ["ios", "android", "web"], description: "Implementation to validate/compile" },
3023
- inputs: { type: "object", additionalProperties: { type: "string" }, description: "Task inputs for compile. Secret inputs must be environment placeholders such as $TEST_PASSWORD, never plaintext." },
3024
- mapPath: { type: "string", description: "Optional repo-relative UI Map v1 used to ground states, edges, and semantic controls" },
3025
- updateMap: { type: "boolean", default: false, description: "Explicitly add the validated Task's coverage references to mapPath" },
3026
- outPath: { type: "string", description: "Compile: optional repo-relative JSON output; omitted returns the compiled Flow without writing" },
3027
- },
3028
- },
3029
- },
3030
- {
3031
- name: "tapp_release_contract",
3032
- title: "Inspect, validate, compile, or run a release contract",
3033
- description:
3034
- "Work with repository-native TypeScript release contracts in .tapp/contracts. Contracts express business guarantees through reusable Tasks, named actors, exact/eventual expectations, criticality, policy, and UI Map coverage. " +
3035
- "Compilation targets the same deterministic Flow/Scenario evidence contract; ordinary run is keyless and never invokes a model. Multi-actor isolated replay is currently web-only.",
3036
- inputSchema: {
3037
- type: "object",
3038
- required: ["contractPath"],
3039
- properties: {
3040
- authToken: { type: "string", description: "Required when TAPP_MCP_TOKEN is set" },
3041
- operation: { type: "string", enum: ["read", "validate", "compile", "run"], default: "validate" },
3042
- contractPath: { type: "string", description: "Repo-relative .tapp/contracts/*.contract.ts file" },
3043
- platform: { type: "string", enum: ["ios", "android", "web"], description: "Target platform; optional when the contract declares exactly one" },
3044
- mapPath: { type: "string", description: "Optional repo-relative UI Map v1 for coverage grounding" },
3045
- updateMap: { type: "boolean", default: false, description: "Explicitly add the reviewed contract coverage to mapPath" },
3046
- outPath: { type: "string", description: "Compile: optional repo-relative deterministic JSON output" },
3047
- url: { type: "string", description: "Run: web target URL override" },
3048
- appBundleId: { type: "string", description: "Run: iOS bundle id override" },
3049
- androidAppId: { type: "string", description: "Run: Android application id override" },
3050
- apkPath: { type: "string", description: "Run: optional Android APK" },
3051
- androidSerial: { type: "string", description: "Run: optional adb serial" },
3052
- },
3053
- },
3054
- },
3055
- {
3056
- name: "tapp_pr_plan",
3057
- title: "Plan PR coverage or explicitly adopt an observed coverage proposal",
3058
- description:
3059
- "Plan builds a deterministic reviewable PR plan from changed files, reviewed ownership, exact observed static-route evidence, UI Map coverage, reusable Tasks, and contract policy. It also emits bounded exploration targets for changed weakly covered UI states. Adopt is an explicit write: it appends one conclusively observed, review-only coverage proposal to the repository release plan, but generates or trusts nothing. No AI runs; plan is read-only and adopt never rewrites existing items.",
3060
- inputSchema: {
3061
- type: "object",
3062
- properties: {
3063
- authToken: { type: "string", description: "Required when TAPP_MCP_TOKEN is set" },
3064
- operation: { type: "string", enum: ["plan", "adopt"], default: "plan" },
3065
- changedFiles: {
3066
- type: "array", minItems: 1,
3067
- items: {
3068
- anyOf: [
3069
- { type: "string" },
3070
- {
3071
- type: "object", required: ["filename"], additionalProperties: false,
3072
- properties: {
3073
- filename: { type: "string" },
3074
- previous_filename: { type: "string" },
3075
- patch: { type: "string", description: "Optional bounded unified patch from the PR provider; consumed locally and never copied into the plan" },
3076
- },
3077
- },
3078
- ],
3079
- },
3080
- description: "Repository-relative PR paths or provider change objects with optional bounded patch evidence for reviewed symbol ownership",
3081
- },
3082
- projectDir: { type: "string", description: "Repo-relative project root; defaults to the MCP workspace root" },
3083
- platform: { type: "string", enum: ["ios", "android", "web"], description: "Optional platform filter" },
3084
- mapPath: { type: "string", description: "Project-relative UI Map; defaults to .tapp/ui-map.json" },
3085
- prPlanPath: { type: "string", description: "Adopt: project-relative executed PR plan containing conclusive exploration evidence" },
3086
- item: { type: "string", description: "Adopt: stable exploration target id whose reviewable proposal should be appended" },
3087
- releasePlanPath: { type: "string", description: "Adopt: project-relative target; defaults to .tapp/release-plan.json" },
3088
- },
3089
- },
3090
- },
3091
- {
3092
- name: "tapp_flow_run",
3093
- title: "Run a deterministic E2E flow",
3094
- description:
3095
- "Replay a deterministic, authored end-to-end test (a Flow) against iOS (XCUITest), Android " +
3096
- "(ADB/UIAutomator), or web (Playwright), and return a scannable pass/fail report. A Flow is a list of steps + assertions " +
3097
- "(see docs/flows-architecture.md). Unlike tapp_explore (autonomous exploration), a Flow does EXACTLY " +
3098
- "what you specify, the same way every time — use it for regression tests and verifying a fix. Steps: " +
3099
- "{tap: X} · {type: {field: F, value: V}} · {swipe: up} · {back} · {wait_for: SCREEN}. Assertions " +
3100
- "(deterministic): {assert_screen: X} · {assert_exists: X} · {assert_absent: X} · {assert_text: {of, contains}}. " +
3101
- "Opt-in AI assertion: {assert_ai: '<claim about the current screen>'} (judged host-side; needs a key; " +
3102
- "skipped otherwise). Pass a flow inline via `flow`, or a repo-relative `flowPath` to a .yml/.json. " +
3103
- "A failed assertion fails the flow and is reported like a QA finding. $TEST_EMAIL/$TEST_PASSWORD and any " +
3104
- "flow `vars` are substituted; pass testEmail/testPassword for real credential values, or `actor` to " +
3105
- "resolve them from a configured actor's environment-variable bindings.",
3106
- inputSchema: {
3107
- type: "object",
3108
- properties: {
3109
- authToken: { type: "string", description: "Required when TAPP_MCP_TOKEN is set" },
3110
- flow: {
3111
- type: "object",
3112
- description:
3113
- "Inline Flow: {name, app, steps:[...], vars?}. Example: {name:'login', app:'com.acme.app', steps:[{tap:'Sign In'}, {type:{field:'Email', value:'$TEST_EMAIL'}}, {tap:'Continue'}, {assert_screen:'Home'}]}",
3114
- },
3115
- flowPath: { type: "string", description: "Alternative to `flow`: repo-relative path to a .yml/.json Flow (e.g. .tapp/flows/login.yml)" },
3116
- platform: { type: "string", enum: ["ios", "web", "android"], description: "Overrides Flow platform detection" },
3117
- appBundleId: { type: "string", description: "iOS: overrides the Flow's `app:` field" },
3118
- androidAppId: { type: "string", description: "Android: overrides the Flow's `app:` field" },
3119
- url: { type: "string", description: "Web start URL. Overrides the Flow's `url:` field." },
3120
- apkPath: { type: "string", description: "Android APK to install before replay." },
3121
- androidSerial: { type: "string", description: "Android adb device serial." },
3122
- testEmail: { type: "string", description: "Value for $TEST_EMAIL" },
3123
- testPassword: { type: "string", description: "Value for $TEST_PASSWORD" },
3124
- actor: { type: "string", description: "Configured actor name; resolves $TEST_EMAIL/$TEST_PASSWORD from the actor's env-var bindings (explicit testEmail/testPassword win)" },
3125
- device: { type: "string", description: "Web flows: replay in a Playwright device profile (e.g. \"iPhone 13\")" },
3126
- viewport: { type: "string", description: "Web flows: explicit viewport WIDTHxHEIGHT (e.g. \"390x844\")" },
3127
- },
3128
- },
3129
- },
3130
- {
3131
- name: "tapp_scenario_run",
3132
- title: "Run a deterministic multi-actor Scenario",
3133
- description:
3134
- "Replay a repository-native system test whose named actors run in isolated browser contexts against shared application state. " +
3135
- "Scenarios use the same deterministic Flow actions/assertions plus explicit actors, shared variables, setup/teardown requests, " +
3136
- "and polling timeouts for eventual consistency. No model or API key is used during replay. Every result is tagged with its actor. " +
3137
- "Web actor isolation is implemented now; iOS and Android multi-actor replay is reported as unsupported rather than simulated.",
3138
- inputSchema: {
3139
- type: "object",
3140
- properties: {
3141
- authToken: { type: "string", description: "Required when TAPP_MCP_TOKEN is set" },
3142
- scenario: { type: "object", description: "Inline Scenario with {kind:'scenario', platform:'web', actors, steps, setup?, teardown?}" },
3143
- scenarioPath: { type: "string", description: "Repo-relative path to a .yml/.json Scenario" },
3144
- url: { type: "string", description: "Override the Scenario's web URL" },
3145
- variables: { type: "object", additionalProperties: { type: "string" }, description: "Explicit non-secret/shared variable overrides. Actor secrets may also be referenced by environment variable name in committed Scenario vars." },
3146
- },
2672
+ // ADR-0007: one command surface. Thirteen public tools; the engine handlers below keep their
2673
+ // original internal names and are reached through dispatchTool(). Every pre-0.18 tool name still
2674
+ // answers (see LEGACY_TOOLS) with a `deprecated` pointer to its replacement.
2675
+ const AUTH = { authToken: { type: "string", description: "Required when TAPP_MCP_TOKEN is set" } };
2676
+ const PLATFORM = { type: "string", enum: ["ios", "android", "web"] };
2677
+ const TARGET_PROPS = {
2678
+ appBundleId: { type: "string", description: "iOS: bundle id of the installed app" },
2679
+ androidAppId: { type: "string", description: "Android: application id on a connected emulator/device" },
2680
+ apkPath: { type: "string", description: "Android: optional APK to install first" },
2681
+ androidSerial: { type: "string", description: "Android: optional adb device serial" },
2682
+ url: { type: "string", description: "Web: http(s) URL of an app or environment you own" },
2683
+ };
2684
+ const INPUT_OVERRIDES = {
2685
+ type: "object", additionalProperties: { type: "string" },
2686
+ description: "Deterministic field values typed during exploration: {'id:<identifier>'|'label:<label>'|'screen:<title>|id:<identifier>': value}",
2687
+ };
2688
+
2689
+ export const TOOLS = [
2690
+ {
2691
+ name: "tapp_explore",
2692
+ title: "Explore the real app (observe — never a verdict)",
2693
+ description:
2694
+ "Autonomously explore an iOS app (appBundleId), Android app (androidAppId) or web app (url) like a tester — taps, types, " +
2695
+ "navigates — and return findings, coverage and evidence. It OBSERVES: no score, no ship verdict; the deterministic gate " +
2696
+ "(`npx -y @aarwitz/tapp@latest ci`) judges. Runs for minutes; for one screen use tapp_look, for a journey use tapp_session. " +
2697
+ "readOnly:true turns it into the read-only audit (renders and reads, never clicks, crawls `pages` same-origin pages) — the only " +
2698
+ "mode safe against production or a site you do not own. goal:\"…\" locates a named screen/control from source + the observed " +
2699
+ "UI Map and, inside an active session, takes the shortest observed route there. If the app barely explored (sign-in wall, crash) " +
2700
+ "the result is `inconclusive` — absence of findings is never a pass. When fields were encountered and you have no values, ASK the user.",
2701
+ inputSchema: {
2702
+ type: "object",
2703
+ properties: {
2704
+ ...AUTH, ...TARGET_PROPS,
2705
+ readOnly: { type: "boolean", default: false, description: "Read-only audit of `url`: never clicks, types, submits or hovers" },
2706
+ goal: { type: "string", description: "A named screen, control or focused task to locate (source-connected) instead of exploring everything" },
2707
+ pages: { type: "integer", default: 1, minimum: 1, maximum: 200, description: "readOnly: same-origin pages to audit at most" },
2708
+ delayMs: { type: "integer", default: 1000, minimum: 0, description: "readOnly: pause between crawled pages" },
2709
+ linkCheckLimit: { type: "integer", default: 30, minimum: 0, description: "readOnly: same-origin links to check per page" },
2710
+ capture: { type: "boolean", default: true, description: "readOnly: write a capture (screenshots, evidence, report.html)" },
2711
+ projectDir: { type: "string", description: "goal: repository root; defaults to the MCP workspace" },
2712
+ mapPath: { type: "string", description: "goal: repository-relative UI Map; defaults to .tapp/ui-map.json" },
2713
+ platform: { ...PLATFORM, description: "goal: optional when no session is active" },
2714
+ clearData: { type: "boolean", default: true, description: "Android: clear app data before launch" },
2715
+ watch: { type: "boolean", default: false, description: "Web: show Tapp's controlled Chromium window and a cursor/HUD" },
2716
+ device: { type: "string", description: "Web: Playwright device profile, e.g. \"iPhone 13\". iOS: simulator name or UDID — required when more than one simulator is booted (TAPP_UDID is the environment default)" },
2717
+ viewport: { type: "string", description: "Web: viewport WIDTHxHEIGHT, e.g. \"390x844\"" },
2718
+ maxActions: { type: "integer", minimum: 1, maximum: 1000, default: 60, description: "Exploration action budget" },
2719
+ timeout: { type: "integer", minimum: 30, maximum: 3600, default: 600, description: "Max wall-clock seconds" },
2720
+ testEmail: { type: "string", description: "Email for the sign-in preamble" },
2721
+ testPassword: { type: "string", description: "Password for the sign-in preamble" },
2722
+ interactive: { type: "boolean", description: "Host-with-a-human only: pause at input screens and wait for values via interactiveResponsePath" },
2723
+ interactiveResponsePath: { type: "string", description: "File path the prompting host answers on" },
2724
+ visualReadyPath: { type: "string", description: "Local-client temp path written once the iOS target is foregrounded" },
2725
+ inputOverrides: INPUT_OVERRIDES,
2726
+ appLaunchArgs: { type: "array", items: { type: "string" }, description: "Launch arguments, e.g. [\"--uitesting\"]" },
2727
+ appLaunchEnv: { type: "object", additionalProperties: { type: "string" }, description: "Launch environment, e.g. {\"UI_TEST_BACKEND\": \"staging\"}" },
2728
+ loginSteps: { type: "array", items: {}, description: "Explicit login replay before exploring: [{action:'type'|'tap'|'wait', target, value?, timeoutMs?}] or 'action:target[:value]' strings; $TEST_EMAIL/$TEST_PASSWORD substituted" },
2729
+ baselineFindings: { type: "array", items: { type: "object" }, description: "Findings from a previous run; adds a `regression` comparison (an observation, not a gate)" },
3147
2730
  },
3148
2731
  },
3149
- {
3150
- name: "tapp_flow_generate",
3151
- title: "Generate a Flow from a goal (AI)",
3152
- description:
3153
- "Write a deterministic E2E Flow from a natural-language goal (e.g. 'sign in and open Settings'), " +
3154
- "GROUNDED in the app's real screens so it can't invent steps. Tapp explores the app to build a " +
3155
- "screen/control map (or reuses a recent run via captureId), then a model authors a Flow using only " +
3156
- "screens/controls that were actually observed. Saves it as an UNTRUSTED PROPOSAL under " +
3157
- ".tapp/proposals/flows/<name>.yml (never directly into .tapp/flows/) and returns the YAML for " +
3158
- "review (optionally runs it). Review → replay against the real app → explicitly PROMOTE (move to " +
3159
- ".tapp/flows/) before CI depends on it. Needs a model backend (Tapp subscription token or " +
3160
- "ANTHROPIC_API_KEY). Use this to bootstrap a test you then refine; use tapp_flow_run to replay it.",
3161
- inputSchema: {
3162
- type: "object",
3163
- properties: {
3164
- authToken: { type: "string", description: "Required when TAPP_MCP_TOKEN is set" },
3165
- goal: { type: "string", description: "What the test should do, in plain English (e.g. 'sign in with test creds and reach the dashboard')" },
3166
- appBundleId: { type: "string", description: "Bundle id of the installed app to author against" },
3167
- captureId: { type: "string", description: "Reuse this capture's grounding instead of exploring (from a prior run_qa, faster)" },
3168
- maxActions: { type: "integer", minimum: 5, maximum: 200, default: 35, description: "Exploration budget when building grounding" },
3169
- run: { type: "boolean", default: false, description: "Also replay the generated flow and include the pass/fail result" },
3170
- testEmail: { type: "string" },
3171
- testPassword: { type: "string" },
3172
- },
3173
- required: ["goal", "appBundleId"],
2732
+ },
2733
+ {
2734
+ name: "tapp_look",
2735
+ title: "See one screen",
2736
+ description:
2737
+ "The fast way (seconds) to SEE the app: with appBundleId/androidAppId it launches the installed app fresh and returns a screenshot " +
2738
+ "plus the accessibility tree of the screen it lands on; with no target it photographs whatever is on the booted simulator right now " +
2739
+ "(tree:true returns the accessibility tree instead). No exploration, no findings. Use appLaunchArgs/appLaunchEnv for a login bypass " +
2740
+ "or backend override. For a screen reached by signing in or several taps, use tapp_session.",
2741
+ inputSchema: {
2742
+ type: "object",
2743
+ properties: {
2744
+ ...AUTH,
2745
+ appBundleId: TARGET_PROPS.appBundleId, androidAppId: TARGET_PROPS.androidAppId, apkPath: TARGET_PROPS.apkPath, androidSerial: TARGET_PROPS.androidSerial,
2746
+ tree: { type: "boolean", default: false, description: "No target: return the accessibility tree of the current screen instead of a screenshot" },
2747
+ clearData: { type: "boolean", default: false, description: "Android: clear app data before launch" },
2748
+ appLaunchArgs: { type: "array", items: { type: "string" }, description: "Launch args, e.g. [\"--uitesting\"]" },
2749
+ appLaunchEnv: { type: "object", additionalProperties: { type: "string" }, description: "Launch env, e.g. {\"UI_TEST_BACKEND\": \"staging\"}" },
2750
+ maxWidth: { type: "integer", minimum: 200, maximum: 1400, default: 700, description: "Max screenshot width in px" },
3174
2751
  },
3175
2752
  },
3176
- {
3177
- name: "tapp_flow_save",
3178
- title: "Save the session as a Flow",
3179
- description:
3180
- "Save what you've done in the CURRENT interactive session as a reusable, deterministic Flow " +
3181
- "(record-by-doing). Every successful tapp_session_act (tap/type/swipe/back) is recorded; this " +
3182
- "writes them to .tapp/flows/<name>.yml with wait_for steps auto-inserted on screen changes and a " +
3183
- "final assert_screen checkpoint. Typed credentials are templated to $TEST_EMAIL/$TEST_PASSWORD so the " +
3184
- "flow is shareable. The saved flow replays with tapp_flow_run. Do it once → it's a test.",
3185
- inputSchema: {
3186
- type: "object",
3187
- properties: {
3188
- authToken: { type: "string", description: "Required when TAPP_MCP_TOKEN is set" },
3189
- name: { type: "string", description: "Human name for the flow, e.g. 'Sign in and reach Home'" },
3190
- addFinalAssertion: { type: "boolean", default: true, description: "Append assert_screen for the final screen as a checkpoint" },
3191
- replace: { type: "boolean", default: false, description: "Explicitly replace a Flow with the same generated filename. Existing Flows are preserved by default." },
3192
- },
3193
- required: ["name"],
2753
+ },
2754
+ {
2755
+ name: "tapp_run",
2756
+ title: "Replay a Flow, Task, contract, or Scenario",
2757
+ description:
2758
+ "Replay a committed deterministic test exactly, the same way every time — keyless, no model. Pass ONE of: flowPath or an inline " +
2759
+ "`flow` ({name, app|url, steps:[{tap:X},{type:{field,value}},{wait_for:S},{assert_screen:S},{assert_exists:X},…]}), taskPath " +
2760
+ "(.tapp/tasks/*.yml, compiled then replayed), contractPath (.tapp/contracts/*.contract.ts), or scenarioPath / inline `scenario` " +
2761
+ "(multi-actor, web). A failed assertion fails the run and is reported like a finding. $TEST_EMAIL/$TEST_PASSWORD come from " +
2762
+ "testEmail/testPassword or a configured `actor`. Use tapp_explore to find bugs; use this to prove a fix or guard a regression.",
2763
+ inputSchema: {
2764
+ type: "object",
2765
+ properties: {
2766
+ ...AUTH,
2767
+ flowPath: { type: "string", description: "Repo-relative Flow (.yml/.json), e.g. .tapp/flows/login.yml" },
2768
+ flow: { type: "object", description: "Inline Flow instead of flowPath" },
2769
+ taskPath: { type: "string", description: "Repo-relative .tapp/tasks/*.yml Task" },
2770
+ inputs: { type: "object", additionalProperties: { type: "string" }, description: "Task inputs; secrets as $ENV placeholders, never plaintext" },
2771
+ contractPath: { type: "string", description: "Repo-relative .tapp/contracts/*.contract.ts" },
2772
+ scenarioPath: { type: "string", description: "Repo-relative Scenario (.yml/.json)" },
2773
+ scenario: { type: "object", description: "Inline Scenario instead of scenarioPath" },
2774
+ variables: { type: "object", additionalProperties: { type: "string" }, description: "Scenario: non-secret shared variable overrides" },
2775
+ platform: { ...PLATFORM, description: "Overrides platform detection" },
2776
+ ...TARGET_PROPS,
2777
+ testEmail: { type: "string", description: "Value for $TEST_EMAIL" },
2778
+ testPassword: { type: "string", description: "Value for $TEST_PASSWORD" },
2779
+ actor: { type: "string", description: "Configured actor; resolves $TEST_EMAIL/$TEST_PASSWORD from its env-var bindings" },
2780
+ device: { type: "string", description: "Web: Playwright device profile. iOS: simulator name or UDID — required when more than one simulator is booted" },
2781
+ viewport: { type: "string", description: "Web: viewport WIDTHxHEIGHT" },
3194
2782
  },
3195
2783
  },
3196
- {
3197
- name: "tapp_ui_tree",
3198
- title: "Inspect screen (a11y tree)",
3199
- description:
3200
- "Dump the accessibility (UI) tree of the current screen of an installed iOS or Android app — " +
3201
- "the inspection primitive (like Playwright's snapshot). Returns {screenTitle, elements:[{type,id,label," +
3202
- "enabled,hittable,x,y,w,h}]}. Use it to see what's on screen before/after acting. NOT for launching an app (tapp_open_app) or finding bugs (tapp_explore).",
3203
- inputSchema: {
3204
- type: "object",
3205
- properties: {
3206
- authToken: { type: "string", description: "Required when TAPP_MCP_TOKEN is set" },
3207
- appBundleId: { type: "string", description: "iOS bundle id of the installed app" },
3208
- androidAppId: { type: "string", description: "Android application id of the installed app" },
3209
- androidSerial: { type: "string", description: "Android adb device serial" },
3210
- },
2784
+ },
2785
+ {
2786
+ name: "tapp_validate",
2787
+ title: "Check a Flow, Task, contract, or Scenario without launching",
2788
+ description:
2789
+ "Deterministically validate a committed artifact — pass ONE of flowPath/flow, taskPath, contractPath, scenarioPath/scenario. " +
2790
+ "Tasks and contracts can be grounded against the UI Map (mapPath; updateMap:true records their coverage). compile:true returns the " +
2791
+ "expanded keyless Flow a Task or contract executes as (Tasks only need a `platform`). Nothing is launched and no model is used.",
2792
+ inputSchema: {
2793
+ type: "object",
2794
+ properties: {
2795
+ ...AUTH,
2796
+ flowPath: { type: "string" }, flow: { type: "object" },
2797
+ taskPath: { type: "string" }, contractPath: { type: "string" },
2798
+ scenarioPath: { type: "string" }, scenario: { type: "object" },
2799
+ compile: { type: "boolean", default: false, description: "Task/contract: return the compiled deterministic executor form" },
2800
+ platform: { ...PLATFORM, description: "Implementation to validate/compile" },
2801
+ inputs: { type: "object", additionalProperties: { type: "string" }, description: "Task compile inputs" },
2802
+ mapPath: { type: "string", description: "Optional repo-relative UI Map for grounding" },
2803
+ updateMap: { type: "boolean", default: false, description: "Record the validated artifact's coverage in mapPath" },
2804
+ outPath: { type: "string", description: "compile: optional repo-relative JSON output" },
3211
2805
  },
3212
2806
  },
3213
- {
3214
- name: "tapp_screenshot",
3215
- title: "Screenshot current screen",
3216
- description:
3217
- "Return an inline image of whatever is CURRENTLY on the booted simulator. It does NOT launch or " +
3218
- "navigate the app — it just photographs the current screen (use it during a session, or after " +
3219
- "tapp_open_app). To launch an app and screenshot the screen it opens on, use tapp_open_app instead.",
3220
- inputSchema: {
3221
- type: "object",
3222
- properties: {
3223
- authToken: { type: "string", description: "Required when TAPP_MCP_TOKEN is set" },
3224
- maxWidth: { type: "integer", minimum: 200, maximum: 1400, default: 700, description: "Max image width in px (downscaled to keep payload small)" },
3225
- },
2807
+ },
2808
+ {
2809
+ name: "tapp_init",
2810
+ title: "Inspect a repository: application model + release plan",
2811
+ description:
2812
+ "Deterministically inspect repository targets, reviewed Tasks/contracts, actors, capabilities and the persistent UI Map, and return the " +
2813
+ "application model plus a compact grounded release-contract plan. `inspect` is read-only; `write` creates .tapp artifacts without " +
2814
+ "overwriting; `refresh` updates source evidence; `explore` builds/starts a detected target, runs the real-surface exploration, " +
2815
+ "merges its UI Map, then refreshes the plan. Keyless; no AI unless remote AI was explicitly enabled.",
2816
+ inputSchema: {
2817
+ type: "object",
2818
+ properties: {
2819
+ ...AUTH,
2820
+ operation: { type: "string", enum: ["inspect", "write", "refresh", "explore"], default: "inspect" },
2821
+ projectDir: { type: "string", description: "Repo-relative project root; defaults to the MCP workspace root" },
2822
+ platform: { ...PLATFORM, description: "Optional target filter" },
2823
+ url: { type: "string", description: "Owned web runtime URL when already running; omit during web explore to build/start the detected target" },
2824
+ target: { type: "string", description: "Explore target selector: web target name/path, or iOS repo dir, Xcode container, .app, or bundle id" },
2825
+ appBundleId: TARGET_PROPS.appBundleId, androidAppId: TARGET_PROPS.androidAppId, apkPath: TARGET_PROPS.apkPath, androidSerial: TARGET_PROPS.androidSerial,
2826
+ maxActions: { type: "integer", minimum: 1, maximum: 1000, default: 40 },
2827
+ timeout: { type: "integer", minimum: 30, maximum: 3600, default: 600 },
2828
+ testEmail: { type: "string", description: "Explore: actor/login email; never persisted" },
2829
+ testPassword: { type: "string", description: "Explore: actor/login password; never persisted" },
2830
+ watch: { type: "boolean", default: false, description: "Web explore: show the controlled browser" },
2831
+ maxContracts: { type: "integer", minimum: 1, maximum: 50, default: 15 },
2832
+ outDir: { type: "string", description: "Repo-relative artifact directory; default .tapp" },
3226
2833
  },
3227
2834
  },
3228
- {
3229
- name: "tapp_open_app",
3230
- title: "Launch app + screenshot",
3231
- description:
3232
- "Launch an installed iOS or Android app and return a SCREENSHOT of the screen it lands on " +
3233
- "(plus the accessibility tree) — with NO exploration. This is the fast way (seconds) to just SEE a " +
3234
- "screen. Use this — NOT tapp_explore — whenever the user wants to view or screenshot a screen. Pass " +
3235
- "appLaunchArgs like [\"--uitesting\"] to bypass login and land on the home screen, and appLaunchEnv for " +
3236
- "a backend override. The app is launched fresh and closed afterward. (To screenshot a screen reached by " +
3237
- "real login or several taps, use a session instead and call tapp_screenshot along the way.)",
3238
- inputSchema: {
3239
- type: "object",
3240
- properties: {
3241
- authToken: { type: "string", description: "Required when TAPP_MCP_TOKEN is set" },
3242
- appBundleId: { type: "string", description: "iOS bundle id of the installed app" },
3243
- androidAppId: { type: "string", description: "Android application id of the installed app" },
3244
- apkPath: { type: "string", description: "Android APK to install before launch" },
3245
- androidSerial: { type: "string", description: "Android adb device serial" },
3246
- clearData: { type: "boolean", default: false, description: "Android: clear app data before launch" },
3247
- appLaunchArgs: { type: "array", items: { type: "string" }, description: "Launch args, e.g. [\"--uitesting\"] to bypass login" },
3248
- appLaunchEnv: { type: "object", additionalProperties: { type: "string" }, description: "Launch env, e.g. {\"UI_TEST_BACKEND\": \"staging\"}" },
3249
- maxWidth: { type: "integer", minimum: 200, maximum: 1400, default: 700, description: "Max screenshot width in px" },
3250
- },
2835
+ },
2836
+ {
2837
+ name: "tapp_plan",
2838
+ title: "The release-plan lifecycle",
2839
+ description:
2840
+ "One tool for the reviewed release plan in .tapp/release-plan.json. action: `read` (default) · `review` (approve/reject/defer items — " +
2841
+ "decision metadata only) · `generate` (grounded Task/contract DRAFTS under .tapp/proposals; untrusted, no AI) · `validate` (replay drafts " +
2842
+ "on a real target) · `promote` (move fully validated drafts into reviewed artifacts) · `pr` (deterministic PR coverage plan from " +
2843
+ "changedFiles) · `adopt` (append one observed PR coverage proposal) · `actor_read` / `actor_set` (named test actors; env-var NAMES only, " +
2844
+ "never credential values). Nothing is trusted until real deterministic replay passes and promotion is explicit.",
2845
+ inputSchema: {
2846
+ type: "object",
2847
+ properties: {
2848
+ ...AUTH,
2849
+ action: { type: "string", enum: ["read", "review", "generate", "validate", "promote", "pr", "adopt", "actor_read", "actor_set"], default: "read" },
2850
+ planPath: { type: "string", description: "Repo-relative plan path; default .tapp/release-plan.json" },
2851
+ projectDir: { type: "string", description: "Repo-relative project root; defaults to the MCP workspace root" },
2852
+ approve: { type: "array", items: { type: "string" }, description: "review: item ids/names to approve" },
2853
+ reject: { type: "array", items: { type: "string" }, description: "review: item ids/names to reject" },
2854
+ defer: { type: "array", items: { type: "string" }, description: "review: item ids/names to defer" },
2855
+ items: { type: "array", items: { type: "string" }, description: "validate/promote: only these items" },
2856
+ platform: { ...PLATFORM, description: "validate/pr: target platform" },
2857
+ url: { type: "string", description: "validate web: already-running owned URL" },
2858
+ target: { type: "string", description: "validate managed web: target id/name/path" },
2859
+ appBundleId: TARGET_PROPS.appBundleId, androidAppId: TARGET_PROPS.androidAppId, apkPath: TARGET_PROPS.apkPath, androidSerial: TARGET_PROPS.androidSerial,
2860
+ timeout: { type: "integer", minimum: 30, maximum: 3600, default: 600 },
2861
+ changedFiles: { type: "array", minItems: 1, items: { anyOf: [{ type: "string" }, { type: "object", required: ["filename"], additionalProperties: false, properties: { filename: { type: "string" }, previous_filename: { type: "string" }, patch: { type: "string" } } }] }, description: "pr: repository-relative changed paths or provider change objects" },
2862
+ mapPath: { type: "string", description: "pr: project-relative UI Map; default .tapp/ui-map.json" },
2863
+ prPlanPath: { type: "string", description: "adopt: executed PR plan with conclusive exploration evidence" },
2864
+ item: { type: "string", description: "adopt: exploration target id to append" },
2865
+ releasePlanPath: { type: "string", description: "adopt: target plan; default .tapp/release-plan.json" },
2866
+ name: { type: "string", description: "actor_set: stable actor name" },
2867
+ role: { type: "string", description: "actor_set: product role" },
2868
+ session: { type: "string", enum: ["default", "isolated"], default: "default" },
2869
+ provisioning: { type: "string", enum: ["existing", "seeded", "api", "unknown"], default: "existing" },
2870
+ credentialBindings: { type: "object", additionalProperties: { type: "string", pattern: "^[A-Z_][A-Z0-9_]{0,127}$" }, description: "actor_set: credential names → environment-variable NAMES" },
2871
+ replace: { type: "boolean", default: false, description: "actor_set: replace an existing actor's non-secret configuration" },
3251
2872
  },
3252
2873
  },
3253
- {
3254
- name: "tapp_list_simulators",
3255
- title: "List simulators",
3256
- description: "List available iOS simulators (name, udid, state, runtime, booted) so you can pick or boot one before running QA.",
3257
- inputSchema: { type: "object", properties: {} },
3258
- },
3259
- {
3260
- name: "tapp_boot_simulator",
3261
- title: "Boot simulator",
3262
- description: "Boot an iOS simulator by udid (preferred) or name so Tapp can run against it. No-op if already booted.",
3263
- inputSchema: {
3264
- type: "object",
3265
- properties: {
3266
- authToken: { type: "string", description: "Required when TAPP_MCP_TOKEN is set" },
3267
- udid: { type: "string", description: "Simulator UDID (from tapp_list_simulators)" },
3268
- name: { type: "string", description: "Simulator name, e.g. 'iPhone 16 Pro' (used if udid omitted)" },
3269
- },
2874
+ },
2875
+ {
2876
+ name: "tapp_map",
2877
+ title: "The UI Map: read, build, or diff",
2878
+ description:
2879
+ "Tapp's platform-neutral UI Map: observed screen states, semantic controls, transitions, provenance and Task/contract coverage. " +
2880
+ "action `read` returns one (repo .tapp/ui-map.json or a capture's); `build` merges a map from OCQA evidence; `diff` reports additions " +
2881
+ "and absences, calling absence a lost state only when comparableFullSweep is true. No AI.",
2882
+ inputSchema: {
2883
+ type: "object",
2884
+ properties: {
2885
+ ...AUTH,
2886
+ action: { type: "string", enum: ["read", "build", "diff"], default: "read" },
2887
+ captureId: { type: "string", description: "Read/build from this capture" },
2888
+ mapPath: { type: "string", description: "Repo-relative map path (default .tapp/ui-map.json)" },
2889
+ markersPath: { type: "string", description: "build: repo-relative OCQA markers when captureId is not supplied" },
2890
+ beforePath: { type: "string", description: "diff: baseline map" },
2891
+ afterPath: { type: "string", description: "diff: current map" },
2892
+ platform: { ...PLATFORM, default: "ios" },
2893
+ target: { type: "string", description: "Bundle id, app id, or owned URL recorded as provenance" },
2894
+ replace: { type: "boolean", default: false, description: "build: replace rather than merge" },
2895
+ comparableFullSweep: { type: "boolean", default: false, description: "diff: both runs had comparable budget; permits lost-reachability classification" },
3270
2896
  },
3271
2897
  },
3272
- {
3273
- name: "tapp_install_app",
3274
- title: "Install app on sim",
3275
- description:
3276
- "Build a target iOS app for the booted simulator and install it, so it's ready for tapp_explore or " +
3277
- "a session. Provide the Xcode project OR workspace path + scheme. Best-effort — apps with CocoaPods/" +
3278
- "signing quirks may still need their normal build. Returns {ok, installed, simulator}.",
3279
- inputSchema: {
3280
- type: "object",
3281
- properties: {
3282
- authToken: { type: "string", description: "Required when TAPP_MCP_TOKEN is set" },
3283
- project: { type: "string", description: "Absolute path to .xcodeproj (use this OR workspace)" },
3284
- workspace: { type: "string", description: "Absolute path to .xcworkspace (use this OR project)" },
3285
- scheme: { type: "string", description: "Scheme to build" },
3286
- configuration: { type: "string", default: "Debug", description: "Build configuration (default Debug)" },
3287
- cleanInstall: { type: "boolean", default: true, description: "Uninstall the app first (clears data + keychain session; avoids Firebase keychain errors). Set false to install over the existing app." },
3288
- },
3289
- required: ["scheme"],
2898
+ },
2899
+ {
2900
+ name: "tapp_ci",
2901
+ title: "The merge gate in CI: preview, install, baseline",
2902
+ description:
2903
+ "Set up the deterministic release gate from the application model. action `inspect` (default) renders the target-aware GitHub " +
2904
+ "workflow and CI manifest without writing; `install` writes both with collision protection; `baseline` imports a successful conclusive " +
2905
+ "gate report as the target's baseline. The gate itself runs with `npx -y @aarwitz/tapp@latest ci`. No network, commits, or AI.",
2906
+ inputSchema: {
2907
+ type: "object",
2908
+ properties: {
2909
+ ...AUTH,
2910
+ action: { type: "string", enum: ["inspect", "install", "baseline"], default: "inspect" },
2911
+ projectDir: { type: "string", description: "Repo-relative project root; defaults to the MCP workspace root" },
2912
+ modelPath: { type: "string", description: "Repo-relative application model; default <projectDir>/.tapp/application-model.json" },
2913
+ actionRef: { type: "string", description: "GitHub Action reference owner/repo@tag; defaults to this release" },
2914
+ defaultBranch: { type: "string", default: "main" },
2915
+ workflowPath: { type: "string", description: "install: default .github/workflows/tapp.yml" },
2916
+ manifestPath: { type: "string", description: "install: default .tapp/ci.json" },
2917
+ allowUnresolved: { type: "boolean", default: false },
2918
+ replace: { type: "boolean", default: false, description: "Replace an existing workflow/manifest or baseline" },
2919
+ reportPath: { type: "string", description: "baseline: repo-relative successful conclusive gate JSON report" },
2920
+ platform: { ...PLATFORM, description: "baseline: target platform" },
2921
+ target: { type: "string", description: "baseline: application-model target id, name, or source path" },
2922
+ baselinePath: { type: "string", description: "baseline: optional project-relative output" },
3290
2923
  },
3291
2924
  },
3292
- {
3293
- name: "tapp_session_start",
3294
- title: "Start interactive session",
3295
- description:
3296
- "Start a PERSISTENT interactive session against an installed iOS/Android app, a web URL, or an " +
3297
- "unambiguous managed web target in the MCP workspace. The app " +
3298
- "launches once and stays up, so you can drive a Playwright-style tap → inspect loop without a cold " +
3299
- "launch per action. NOT for finding bugs autonomously (tapp_explore), a one-off screenshot (tapp_open_app), " +
3300
- "or a site you do not own (tapp_audit — a session clicks). Returns the initial screen {screenTitle, elements[]}. Drive it with " +
3301
- "tapp_focus for any named destination (source + shortest observed route), then tapp_session_act only for remaining actions; finish with tapp_session_end. " +
3302
- "For a focused user request, ALWAYS pass it in `focus` so the session reaches that surface before returning. Only one session at a time. Starts from a " +
3303
- "fresh COLD launch (terminate + relaunch, for a deterministic starting screen): persisted data such as Keychain credentials survives, but the app opens on its " +
3304
- "launch screen, NOT a resumed foreground state — an app that gates each cold start behind sign-in will show its login wall, so plan a `login` act (or a login bypass " +
3305
- "launch argument) as the first step. CLI `tapp tree`/`tapp screenshot` warm-resume the currently foregrounded app instead, which is why they can look signed-in when a session does not. " +
3306
- "Use appLaunchArgs/appLaunchEnv for apps that need a backend override or login bypass. " +
3307
- "When you reach a screen with input fields and don't have values for them, ASK THE USER what to type " +
3308
- "(offer defaults/skip) before typing — the session does not prompt on its own.",
3309
- inputSchema: {
3310
- type: "object",
3311
- properties: {
3312
- authToken: { type: "string", description: "Required when TAPP_MCP_TOKEN is set" },
3313
- appBundleId: { type: "string", description: "Bundle id of the installed app to drive" },
3314
- androidAppId: { type: "string", description: "Android application id to drive (alternative to appBundleId)" },
3315
- url: { type: "string", description: "Owned http(s) web app URL to drive (alternative to appBundleId/androidAppId); omit all three target identifiers to build/start an unambiguous owned web target from projectDir" },
3316
- device: { type: "string", description: "Web sessions: render as a Playwright device profile (e.g. \"iPhone 13\")" },
3317
- viewport: { type: "string", description: "Web sessions: explicit viewport WIDTHxHEIGHT (e.g. \"390x844\")" },
3318
- target: { type: "string", description: "Optional managed-web target name/path when projectDir contains multiple browser applications" },
3319
- apkPath: { type: "string", description: "Android APK to install before starting" },
3320
- androidSerial: { type: "string", description: "Android adb device serial" },
3321
- clearData: { type: "boolean", default: true, description: "Android: clear app data before launch" },
3322
- testEmail: { type: "string", description: "Email available to the app/harness, if it has a sign-in" },
3323
- testPassword: { type: "string", description: "Password available to the app/harness" },
3324
- appLaunchArgs: { type: "array", items: { type: "string" }, description: "Launch arguments, e.g. [\"--uitesting\"]" },
3325
- appLaunchEnv: { type: "object", additionalProperties: { type: "string" }, description: "Launch environment, e.g. {\"UI_TEST_BACKEND\": \"staging\"}" },
3326
- focus: { type: "string", description: "Exact focused UI goal/control/screen to locate from repository source and reach through the shortest observed UI Map route before returning" },
3327
- projectDir: { type: "string", description: "Repository root for source-connected focus; defaults to the MCP workspace" },
3328
- mapPath: { type: "string", description: "Optional repository-relative UI Map for focus; defaults to .tapp/ui-map.json" },
3329
- },
2925
+ },
2926
+ {
2927
+ name: "tapp_report",
2928
+ title: "Evidence: recent runs, or one run's summary",
2929
+ description:
2930
+ "Without captureId: list recent capture runs for THIS project (other projects' captures are counted but hidden unless allProjects). " +
2931
+ "With captureId: that run's summary metadata. Cite only the capture a command just returned as evidence.",
2932
+ inputSchema: {
2933
+ type: "object",
2934
+ properties: {
2935
+ captureId: { type: "string", description: "Capture run id to summarise; omit to list" },
2936
+ runPath: { type: "string", description: "Absolute capture path override (must stay under captures/)" },
2937
+ limit: { type: "integer", minimum: 1, maximum: 100, default: 10 },
2938
+ allProjects: { type: "boolean", default: false, description: "Include other projects' and pre-provenance captures" },
3330
2939
  },
3331
2940
  },
3332
- {
3333
- name: "tapp_focus",
3334
- title: "Locate and reach a requested UI surface",
3335
- description:
3336
- "The FAST source-connected path for focused tasks. Locate a requested screen/control from owned repository source, reconcile it with Tapp's runtime-observed UI Map, and—when a session is active—execute the shortest replayable route in one call. Use before step-by-step tapping when the user names a destination such as 'Save storefront settings'. Source identifies intent; Tapp never invents navigation from source, and only observed/validated UI Map edges are executed. Without an active session this returns the grounded location/route plan without acting.",
3337
- inputSchema: {
3338
- type: "object",
3339
- required: ["query"],
3340
- properties: {
3341
- authToken: { type: "string", description: "Required when TAPP_MCP_TOKEN is set" },
3342
- query: { type: "string", description: "User's requested screen, control, or focused UI task" },
3343
- projectDir: { type: "string", description: "Repository root; defaults to the MCP workspace" },
3344
- platform: { type: "string", enum: ["ios", "android", "web"], description: "Optional without an active session; an active session is authoritative" },
3345
- mapPath: { type: "string", description: "Optional repository-relative UI Map; defaults to .tapp/ui-map.json" },
3346
- },
2941
+ },
2942
+ {
2943
+ name: "tapp_session",
2944
+ title: "Drive the app step by step (persistent session)",
2945
+ description:
2946
+ "A persistent interactive session: the app launches once and stays up for a tap → inspect loop. action `start` launches an installed " +
2947
+ "iOS/Android app, an owned web URL, or the workspace's managed web target (pass `focus` to reach a named screen first); then one action " +
2948
+ "per call: `login` (email+password or `actor` — fills, submits and verifies in one call; prefer it over manual typing), `tap` (id/label " +
2949
+ "or x/y), `type` (text, optional id — replaces the field), `swipe`, `back`, `wait` (for id/text), `tree` (re-inspect; full:true for every " +
2950
+ "raw element), `screenshot`; `save_flow` writes the recorded steps as a replayable Flow; `draft_flow` has a model write a Flow from `goal` " +
2951
+ "grounded in observed screens (untrusted proposal; needs a model backend); `end` quits the app — always call it when done. One session " +
2952
+ "at a time; starts from a cold launch, so plan a `login` first when the app gates on sign-in. Ask the user before typing into fields you have no values for.",
2953
+ inputSchema: {
2954
+ type: "object",
2955
+ required: ["action"],
2956
+ properties: {
2957
+ ...AUTH,
2958
+ action: { type: "string", enum: ["start", "login", "tap", "type", "swipe", "back", "wait", "tree", "screenshot", "save_flow", "draft_flow", "end"] },
2959
+ ...TARGET_PROPS,
2960
+ target: { type: "string", description: "start: managed-web target name/path when the workspace has several" },
2961
+ device: { type: "string", description: "start: web Playwright device profile, or iOS simulator name/UDID (required when more than one simulator is booted)" },
2962
+ viewport: { type: "string", description: "start (web): viewport WIDTHxHEIGHT" },
2963
+ clearData: { type: "boolean", default: true, description: "start (Android): clear app data" },
2964
+ testEmail: { type: "string" }, testPassword: { type: "string" },
2965
+ appLaunchArgs: { type: "array", items: { type: "string" } },
2966
+ appLaunchEnv: { type: "object", additionalProperties: { type: "string" } },
2967
+ focus: { type: "string", description: "start: a named screen/control to reach (source + shortest observed route) before returning" },
2968
+ projectDir: { type: "string", description: "start: repository root for source-connected focus" },
2969
+ mapPath: { type: "string", description: "start: repository-relative UI Map; default .tapp/ui-map.json" },
2970
+ email: { type: "string", description: "login: email/username" },
2971
+ password: { type: "string", description: "login: password" },
2972
+ actor: { type: "string", description: "login: configured actor name" },
2973
+ id: { type: "string", description: "tap/type/wait: accessibility id or visible/partial label" },
2974
+ x: { type: "number" }, y: { type: "number" },
2975
+ text: { type: "string", description: "type: text to type · wait: text to wait for" },
2976
+ direction: { type: "string", enum: ["up", "down", "left", "right"] },
2977
+ timeoutMs: { type: "integer", minimum: 500, maximum: 60000, default: 5000 },
2978
+ full: { type: "boolean", default: false, description: "tree: complete raw element list with frames" },
2979
+ label: { type: "string", description: "screenshot: optional label" },
2980
+ name: { type: "string", description: "save_flow: human name for the Flow" },
2981
+ addFinalAssertion: { type: "boolean", default: true, description: "save_flow: append assert_screen for the final screen" },
2982
+ replace: { type: "boolean", default: false, description: "save_flow: replace a Flow with the same filename" },
2983
+ goal: { type: "string", description: "draft_flow: what the test should do, in plain English" },
2984
+ captureId: { type: "string", description: "draft_flow: reuse this capture's grounding instead of exploring" },
2985
+ maxActions: { type: "integer", minimum: 5, maximum: 200, default: 35, description: "draft_flow: exploration budget for grounding" },
2986
+ run: { type: "boolean", default: false, description: "draft_flow: also replay the draft" },
3347
2987
  },
3348
2988
  },
3349
- {
3350
- name: "tapp_session_act",
3351
- title: "Session: tap/type/inspect",
3352
- description:
3353
- "Perform ONE action in the active interactive session and get the resulting screen back (the fresh " +
3354
- "accessibility tree). Actions: 'login' (`email` + `password` — fills the login form, submits, and " +
3355
- "verifies IN ONE CALL; always prefer this over manual type/tap for sign-in: iOS wipes secure fields " +
3356
- "on refocus, so step-by-step login flows lose the password), 'tap' (by `id` = accessibility identifier " +
3357
- "or visible/partial label or placeholder, or by `x`/`y` coordinates), 'type' (`text`, optional `id` to " +
3358
- "target a field — always REPLACES the field's content), 'swipe' (`direction`), 'back', 'wait' (block " +
3359
- "until an element with `id`/`text` appears, up to `timeoutMs`), 'tree' (re-inspect without acting; " +
3360
- "pass `full: true` for every raw element with frames — the default projection dedupes and caps at " +
3361
- "160 elements, so grep-style checks against it can miss text that IS on screen), " +
3362
- "'screenshot'. Returns {status, screenTitle, elements[], durationMs}; status 'not_found'/'timeout'/'still_on_login' " +
3363
- "etc. with a `detail` explaining login failures.",
3364
- inputSchema: {
3365
- type: "object",
3366
- properties: {
3367
- authToken: { type: "string", description: "Required when TAPP_MCP_TOKEN is set" },
3368
- action: { type: "string", enum: ["login", "tap", "type", "swipe", "back", "wait", "tree", "screenshot"] },
3369
- email: { type: "string", description: "login: email/username to sign in with" },
3370
- password: { type: "string", description: "login: password to sign in with" },
3371
- actor: { type: "string", description: "login: configured actor; explicit email/password override its environment bindings" },
3372
- id: { type: "string", description: "Element accessibility id or visible/partial label (for tap/type/wait)" },
3373
- x: { type: "number", description: "Tap X coordinate (points), if not using id" },
3374
- y: { type: "number", description: "Tap Y coordinate (points), if not using id" },
3375
- text: { type: "string", description: "Text to type, or the label/text to wait for" },
3376
- direction: { type: "string", enum: ["up", "down", "left", "right"], description: "Swipe direction" },
3377
- timeoutMs: { type: "integer", minimum: 500, maximum: 60000, default: 5000, description: "For 'wait': how long to poll for the element" },
3378
- full: { type: "boolean", default: false, description: "For 'tree': return the complete raw element list (frames included) instead of the deduplicated agent-facing projection capped at 160 elements" },
3379
- label: { type: "string", description: "Optional screenshot label" },
3380
- },
3381
- required: ["action"],
2989
+ },
2990
+ {
2991
+ name: "tapp_build",
2992
+ title: "iOS simulator: build, install, boot",
2993
+ description:
2994
+ "action `build` (default): build the iOS app under projectDir for the simulator (auto-detects container and scheme) and install it, " +
2995
+ "returning the bundle id — use before tapp_explore/tapp_look when the app is not installed; `install`: build a given project/workspace + " +
2996
+ "scheme and install it; `simulators`: list available simulators; `boot`: boot one by udid or name.",
2997
+ inputSchema: {
2998
+ type: "object",
2999
+ properties: {
3000
+ ...AUTH,
3001
+ action: { type: "string", enum: ["build", "install", "simulators", "boot"], default: "build" },
3002
+ projectDir: { type: "string", description: "build: dir to search for the .xcworkspace/.xcodeproj (default cwd)" },
3003
+ scheme: { type: "string", description: "Scheme (build: auto-detected; install: required)" },
3004
+ configuration: { type: "string", default: "Debug" },
3005
+ install: { type: "boolean", default: true, description: "build: install on the booted simulator afterwards" },
3006
+ project: { type: "string", description: "install: absolute .xcodeproj path" },
3007
+ workspace: { type: "string", description: "install: absolute .xcworkspace path" },
3008
+ cleanInstall: { type: "boolean", default: true, description: "install: uninstall first" },
3009
+ udid: { type: "string", description: "boot: simulator UDID" },
3010
+ name: { type: "string", description: "boot: simulator name, e.g. 'iPhone 16 Pro'" },
3382
3011
  },
3383
3012
  },
3384
- {
3385
- name: "tapp_session_end",
3386
- title: "End session",
3387
- description: "End the active interactive session (quits the app + harness). Always call this when done.",
3388
- inputSchema: {
3389
- type: "object",
3390
- properties: { authToken: { type: "string", description: "Required when TAPP_MCP_TOKEN is set" } },
3013
+ },
3014
+ {
3015
+ name: "tapp_doctor",
3016
+ title: "Check Tapp readiness",
3017
+ description: "Check the workspace and toolchain: Xcode, simulators, adb, Playwright, and what each platform can run right now.",
3018
+ inputSchema: { type: "object", properties: {} },
3019
+ },
3020
+ {
3021
+ name: "tapp_feedback",
3022
+ title: "Send feedback to the tapp maintainers",
3023
+ description:
3024
+ "Draft a public GitHub issue on aarwitz/tapp about tapp itself — a bug in tapp, an idea, or a question (not a finding about the app " +
3025
+ "under test). Adds the tapp version, platform availability and the latest capture id, and redacts home paths and tokens. Default is a " +
3026
+ "DRAFT with a prefilled github.com URL; pass submit:true only after the user agreed to file a public issue (uses this machine's gh).",
3027
+ inputSchema: {
3028
+ type: "object",
3029
+ properties: {
3030
+ title: { type: "string", description: "Short, specific title" },
3031
+ body: { type: "string", description: "What happened, what you expected, the exact call. No secrets or private source." },
3032
+ type: { type: "string", enum: ["bug", "idea", "question"], description: "Default bug" },
3033
+ capture: { type: "string", description: "Capture id to reference, 'latest' (default) or 'none'" },
3034
+ submit: { type: "boolean", description: "File the issue now with gh (needs the user's consent). Default false." },
3391
3035
  },
3036
+ required: ["title"],
3392
3037
  },
3393
- ],
3394
- }));
3038
+ },
3039
+ ];
3395
3040
 
3396
- server.setRequestHandler(CallToolRequestSchema, async (request) => {
3397
- const { name, arguments: args = {} } = request.params;
3041
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: TOOLS }));
3042
+
3043
+
3044
+ // The in-flight MCP request (progress tokens); routed and legacy calls share it.
3045
+ let currentRequest = null;
3046
+
3047
+ async function handleTool(name, args = {}) {
3048
+ const request = currentRequest || { params: { name, arguments: args, _meta: {} } };
3398
3049
 
3399
3050
  if (name === "tapp_feedback") {
3400
3051
  const fb = await import("./feedback.js");
@@ -3786,6 +3437,7 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
3786
3437
  maxActions: args.maxActions,
3787
3438
  timeout: args.timeout,
3788
3439
  args,
3440
+ device: isNonEmptyString(args.device) ? args.device.trim() : "",
3789
3441
  onProgress: (p) => {
3790
3442
  lastProgress = p;
3791
3443
  iosProgress(p);
@@ -4275,7 +3927,7 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
4275
3927
  const loaded = readProjectConfig(workspaceRoot);
4276
3928
  if (loaded.errors.length) return errorResult(`Invalid ${loaded.relativePath}: ${loaded.errors.join("; ")}`);
4277
3929
  const actor = loaded.config.actors?.[args.actor.trim()];
4278
- if (!actor) return errorResult(`Actor '${args.actor.trim()}' is not configured in ${loaded.relativePath}`, { hint: "Configure it with tapp_actor_set / tapp actor set first" });
3930
+ if (!actor) return errorResult(`Actor '${args.actor.trim()}' is not configured in ${loaded.relativePath}`, { hint: "Configure it with tapp_plan (action actor_set) / tapp actor set first" });
4279
3931
  // Actors store env-var NAMES only; resolve values here. Explicit testEmail/testPassword win.
4280
3932
  for (const [credential, argName, envKey] of [["email", "testEmail", "OCQA_TEST_EMAIL"], ["password", "testPassword", "OCQA_TEST_PASSWORD"]]) {
4281
3933
  if (isNonEmptyString(args[argName])) continue;
@@ -4450,7 +4102,7 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
4450
4102
  L.push("", "---", "", (rep.stdout || "").trim());
4451
4103
  }
4452
4104
  } else {
4453
- L.push("", `Replay the proposal: \`tapp_flow_run\` with \`flowPath: "${rel}"\`. After it passes, promote it to \`.tapp/flows/\`.`);
4105
+ L.push("", `Replay the proposal: \`tapp_run\` with \`flowPath: "${rel}"\`. After it passes, promote it to \`.tapp/flows/\`.`);
4454
4106
  }
4455
4107
  return richResult(L.join("\n"), { path: rel, proposal: true, promotePath: promotedPath, flow, groundedScreens: grounding.screens.length, ungrounded });
4456
4108
  }
@@ -4532,7 +4184,7 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
4532
4184
  }
4533
4185
  }
4534
4186
  const maxWidth = Math.max(200, Math.min(1400, asInteger(args.maxWidth, 700)));
4535
- const r = await openApp(String(args.appBundleId).trim(), explorationEnvFromArgs(args), maxWidth);
4187
+ const r = await openApp(String(args.appBundleId).trim(), explorationEnvFromArgs(args), maxWidth, { device: isNonEmptyString(args.device) ? args.device.trim() : "" });
4536
4188
  if (r.error) return errorResult(r.error, r.details || {});
4537
4189
  const content = [];
4538
4190
  content.push({ type: "text", text: `🚀 Launched \`${String(args.appBundleId).trim()}\`\n\n` + formatScreen(r.screenTitle, r.elements) });
@@ -4548,7 +4200,7 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
4548
4200
  for (const s of list.slice(0, 20)) {
4549
4201
  L.push(`- ${s.booted ? "🟢" : "⚪️"} **${s.name}** — ${s.runtime || "?"}${s.booted ? " · **booted**" : ""} \`${s.udid}\``);
4550
4202
  }
4551
- if (!booted.length) L.push("", "No simulator booted — `tapp_boot_simulator` to start one before QA.");
4203
+ if (!booted.length) L.push("", "No simulator booted — `tapp_build (action boot)` to start one before QA.");
4552
4204
  return richResult(L.join("\n"), sims);
4553
4205
  }
4554
4206
 
@@ -4583,7 +4235,7 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
4583
4235
  const configuration = isNonEmptyString(args.configuration) ? args.configuration.trim() : "Debug";
4584
4236
  const sims = await listSimulators();
4585
4237
  const booted = (sims.booted || [])[0];
4586
- if (!booted) return errorResult("No booted simulator. Call tapp_boot_simulator first.");
4238
+ if (!booted) return errorResult("No booted simulator. Call tapp_build (action boot) first.");
4587
4239
  const target = workspace || project;
4588
4240
  if (!fs.existsSync(target)) return errorResult("Project/workspace path not found", { target });
4589
4241
 
@@ -4644,7 +4296,7 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
4644
4296
  if (!isInsideDir(workspaceRoot, focusProjectDir) || !fs.statSync(focusProjectDir).isDirectory()) return errorResult("projectDir must be an existing directory inside the workspace");
4645
4297
  }
4646
4298
  const r = ios
4647
- ? await startSession(target, explorationEnvFromArgs(args))
4299
+ ? await startSession(target, explorationEnvFromArgs(args), { device: isNonEmptyString(args.device) ? args.device.trim() : "" })
4648
4300
  : android
4649
4301
  ? await startAndroidSession(target, { serial: args.androidSerial, apkPath: args.apkPath, clearData: args.clearData !== false, testEmail: args.testEmail, testPassword: args.testPassword })
4650
4302
  : web
@@ -4670,7 +4322,7 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
4670
4322
  const screen = agentScreenProjection(focused || r);
4671
4323
  const text = focused
4672
4324
  ? `🎬 Session started — \`${target}\` (${platformLabel})\n\n${(await import("./focused-navigation.js")).focusedTargetSummary(focused)}\n\n${formatScreen(screen.screenTitle, screen.elements)}`
4673
- : `🎬 Session started — \`${target}\` (${platformLabel})\n\n${formatScreen(screen.screenTitle, screen.elements)}\n\nDrive it with \`tapp_focus\` for a named destination, or \`tapp_session_act\` for one action.`;
4325
+ : `🎬 Session started — \`${target}\` (${platformLabel})\n\n${formatScreen(screen.screenTitle, screen.elements)}\n\nDrive it with \`tapp_explore (goal)\` for a named destination, or \`tapp_session\` for one action.`;
4674
4326
  // Return the final focused screen once. Previously this duplicated the complete native tree
4675
4327
  // inside `focus` and at top level, and retained the pre-focus web URL at top level.
4676
4328
  const structured = focused
@@ -4742,7 +4394,7 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
4742
4394
  : tgt ? `${verb} \`${tgt}\`` : verb;
4743
4395
  const detailNote = !ok && r.detail ? ` — ${r.detail}` : "";
4744
4396
  const head = `${did} — ${ok ? "ok" : `⚠️ ${r.status}${detailNote}`} → now on **${r.screenTitle || "Unknown"}**`;
4745
- const rec = typeof r.recordedSteps === "number" ? `\n\n🔴 Recording — ${r.recordedSteps} step(s). \`tapp_flow_save\` to keep it as a test.` : "";
4397
+ const rec = typeof r.recordedSteps === "number" ? `\n\n🔴 Recording — ${r.recordedSteps} step(s). \`tapp_session (action save_flow)\` to keep it as a test.` : "";
4746
4398
  // `verbose` is the documented spelling (SESSION_ACT_ARGS.tree); `full` is the original.
4747
4399
  // Accepting only `full` meant the documented flag silently did nothing (field issue #9).
4748
4400
  const fullTree = action === "tree" && (args.full === true || args.verbose === true || cmd.verbose === true || cmd.full === true);
@@ -4757,7 +4409,7 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
4757
4409
  if (unauthorized) return unauthorized;
4758
4410
  try {
4759
4411
  const saved = await saveInteractiveSessionFlow({ projectDir:workspaceRoot, name:args.name, addFinalAssertion:args.addFinalAssertion !== false, replace:args.replace === true });
4760
- const text = `💾 Saved flow **${saved.flow.name}** → \`${saved.path}\` (${saved.flow.steps.length} steps)\n\n\`\`\`yaml\n${saved.yaml}\n\`\`\`\n\nReplay it anytime: \`tapp_flow_run\` with \`flowPath: "${saved.path}"\`.`;
4412
+ const text = `💾 Saved flow **${saved.flow.name}** → \`${saved.path}\` (${saved.flow.steps.length} steps)\n\n\`\`\`yaml\n${saved.yaml}\n\`\`\`\n\nReplay it anytime: \`tapp_run\` with \`flowPath: "${saved.path}"\`.`;
4761
4413
  return richResult(text, { path:saved.path, flow:saved.flow });
4762
4414
  } catch (error) {
4763
4415
  return errorResult(error.message || String(error), error.code ? { code:error.code } : {});
@@ -4769,13 +4421,159 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
4769
4421
  if (unauthorized) return unauthorized;
4770
4422
  const recorded = activeSession && activeSession.recording ? activeSession.recording.length : 0;
4771
4423
  await endSession();
4772
- const hint = recorded > 0 ? ` (${recorded} recorded step(s) discarded — use tapp_flow_save before ending to keep them)` : "";
4424
+ const hint = recorded > 0 ? ` (${recorded} recorded step(s) discarded — use tapp_session (action save_flow) before ending to keep them)` : "";
4773
4425
  return richResult(`🏁 Session ended.${hint}`, { ok: true, recordedStepsDiscarded: recorded });
4774
4426
  }
4775
4427
 
4776
4428
  return errorResult(`Unknown tool: ${name}`);
4429
+ }
4430
+
4431
+ // Public tool → engine handler routing (ADR-0007). Handlers keep their original names so the
4432
+ // engine does not change; only the surface does.
4433
+ const PUBLIC_TOOL_NAMES = new Set(TOOLS.map((tool) => tool.name));
4434
+
4435
+ // Every pre-0.18 tool name still answers through its original handler, plus a pointer to the
4436
+ // public tool that replaced it. ListTools no longer advertises these.
4437
+ export const LEGACY_TOOLS = Object.freeze({
4438
+ tapp_run_qa: { tool: "tapp_explore" },
4439
+ tapp_audit: { tool: "tapp_explore", hint: "readOnly: true" },
4440
+ tapp_focus: { tool: "tapp_explore", hint: "goal: <query>" },
4441
+ tapp_open_app: { tool: "tapp_look" },
4442
+ tapp_ui_tree: { tool: "tapp_look", hint: "tree: true" },
4443
+ tapp_screenshot: { tool: "tapp_look" },
4444
+ tapp_flow_run: { tool: "tapp_run" },
4445
+ tapp_scenario_run: { tool: "tapp_run" },
4446
+ tapp_task: { tool: "tapp_validate", hint: "taskPath (tapp_run replays it)" },
4447
+ tapp_release_contract: { tool: "tapp_validate", hint: "contractPath (tapp_run replays it)" },
4448
+ tapp_flow_generate: { tool: "tapp_session", hint: 'action: "draft_flow"' },
4449
+ tapp_flow_save: { tool: "tapp_session", hint: 'action: "save_flow"' },
4450
+ tapp_session_start: { tool: "tapp_session", hint: 'action: "start"' },
4451
+ tapp_session_act: { tool: "tapp_session" },
4452
+ tapp_session_end: { tool: "tapp_session", hint: 'action: "end"' },
4453
+ tapp_list_simulators: { tool: "tapp_build", hint: 'action: "simulators"' },
4454
+ tapp_boot_simulator: { tool: "tapp_build", hint: 'action: "boot"' },
4455
+ tapp_install_app: { tool: "tapp_build", hint: 'action: "install"' },
4456
+ tapp_health: { tool: "tapp_doctor" },
4457
+ tapp_release_plan: { tool: "tapp_plan" },
4458
+ tapp_pr_plan: { tool: "tapp_plan", hint: 'action: "pr" | "adopt"' },
4459
+ tapp_actor_config: { tool: "tapp_plan", hint: 'action: "actor_read" | "actor_set"' },
4460
+ tapp_ui_map: { tool: "tapp_map" },
4461
+ tapp_ci_setup: { tool: "tapp_ci" },
4462
+ tapp_list_captures: { tool: "tapp_report" },
4463
+ tapp_capture_summary: { tool: "tapp_report", hint: "captureId" },
4464
+ tapp_capture: { tool: "tapp_explore", hint: "(harness-era capture; explore writes the same evidence)" },
4465
+ tapp_parse_markers: { tool: "tapp_report", hint: "captureId" },
4777
4466
  });
4778
4467
 
4468
+ async function validateArtifactTool(args) {
4469
+ const { compile, ...v } = args;
4470
+ const operation = compile === true ? "compile" : "validate";
4471
+ if (isNonEmptyString(v.taskPath)) return handleTool("tapp_task", { ...v, operation });
4472
+ if (isNonEmptyString(v.contractPath)) return handleTool("tapp_release_contract", { ...v, operation });
4473
+ if (v.flow || isNonEmptyString(v.flowPath)) {
4474
+ const { loadFlowFile, validateFlowSteps } = await import("./flow-runtime.js");
4475
+ let flow = v.flow;
4476
+ if (!flow) {
4477
+ const flowFile = path.resolve(workspaceRoot, v.flowPath.trim());
4478
+ if (!isInsideDir(workspaceRoot, flowFile)) return errorResult("flowPath must be inside the workspace");
4479
+ if (!fs.existsSync(flowFile)) return errorResult("Flow file not found", { flowPath: v.flowPath });
4480
+ try { flow = loadFlowFile(flowFile); } catch (error) { return errorResult("Could not load Flow", { detail: error.message || String(error) }); }
4481
+ }
4482
+ const errors = validateFlowSteps(flow, v.platform || undefined);
4483
+ if (errors.length) return errorResult(`Flow has ${errors.length} invalid step(s)`, { errors, flow: flow.name });
4484
+ return richResult(`✅ Valid Flow — ${flow.name || "unnamed"} · ${(flow.steps || []).length} steps`, { ok: true, flow: flow.name, steps: (flow.steps || []).length });
4485
+ }
4486
+ if (v.scenario || isNonEmptyString(v.scenarioPath)) {
4487
+ const { loadScenarioFile, validateScenario } = await import("./scenario-runtime.js");
4488
+ let scenario = v.scenario;
4489
+ if (!scenario) {
4490
+ const scenarioFile = path.resolve(workspaceRoot, v.scenarioPath.trim());
4491
+ if (!isInsideDir(workspaceRoot, scenarioFile)) return errorResult("scenarioPath must be inside the workspace");
4492
+ if (!fs.existsSync(scenarioFile)) return errorResult("Scenario file not found", { scenarioPath: v.scenarioPath });
4493
+ try { scenario = loadScenarioFile(scenarioFile); } catch (error) { return errorResult("Could not load Scenario", { detail: error.message || String(error) }); }
4494
+ }
4495
+ const errors = validateScenario(scenario);
4496
+ if (errors.length) return errorResult(`Scenario has ${errors.length} problem(s)`, { errors });
4497
+ return richResult(`✅ Valid Scenario — ${scenario.name || "unnamed"} · ${Object.keys(scenario.actors || {}).length} actors · ${(scenario.steps || []).length} steps`, { ok: true, scenario: scenario.name });
4498
+ }
4499
+ return errorResult("tapp_validate needs one of taskPath, contractPath, flowPath|flow, or scenarioPath|scenario");
4500
+ }
4501
+
4502
+ export async function routePublicTool(name, args = {}) {
4503
+ const { readOnly, goal, tree, action, ...rest } = args;
4504
+ switch (name) {
4505
+ case "tapp_explore":
4506
+ if (readOnly === true) return handleTool("tapp_audit", rest);
4507
+ if (isNonEmptyString(goal)) return handleTool("tapp_focus", { query: goal, projectDir: rest.projectDir, platform: rest.platform, mapPath: rest.mapPath, authToken: rest.authToken });
4508
+ return handleTool("tapp_explore", rest);
4509
+ case "tapp_look":
4510
+ if (isNonEmptyString(rest.appBundleId) || isNonEmptyString(rest.androidAppId)) return handleTool("tapp_open_app", rest);
4511
+ return handleTool(tree === true ? "tapp_ui_tree" : "tapp_screenshot", rest);
4512
+ case "tapp_run": {
4513
+ if (rest.flow || isNonEmptyString(rest.flowPath)) return handleTool("tapp_flow_run", rest);
4514
+ if (rest.scenario || isNonEmptyString(rest.scenarioPath)) return handleTool("tapp_scenario_run", rest);
4515
+ if (isNonEmptyString(rest.contractPath)) return handleTool("tapp_release_contract", { ...rest, operation: "run" });
4516
+ if (isNonEmptyString(rest.taskPath)) {
4517
+ const compiled = await handleTool("tapp_task", { operation: "compile", taskPath: rest.taskPath, platform: rest.platform, inputs: rest.inputs, authToken: rest.authToken });
4518
+ if (compiled.isError || !compiled.structuredContent?.flow) return compiled;
4519
+ const { taskPath, inputs, ...replay } = rest;
4520
+ return handleTool("tapp_flow_run", { ...replay, flow: compiled.structuredContent.flow });
4521
+ }
4522
+ return errorResult("tapp_run needs one of flowPath|flow, taskPath, contractPath, or scenarioPath|scenario");
4523
+ }
4524
+ case "tapp_validate":
4525
+ return validateArtifactTool(rest);
4526
+ case "tapp_plan": {
4527
+ const op = action || "read";
4528
+ if (op === "pr" || op === "adopt") return handleTool("tapp_pr_plan", { ...rest, operation: op === "pr" ? "plan" : "adopt" });
4529
+ if (op === "actor_read" || op === "actor_set") return handleTool("tapp_actor_config", { ...rest, operation: op === "actor_set" ? "set" : "read" });
4530
+ return handleTool("tapp_release_plan", { ...rest, operation: op });
4531
+ }
4532
+ case "tapp_map":
4533
+ return handleTool("tapp_ui_map", { ...rest, operation: action || rest.operation || "read" });
4534
+ case "tapp_ci":
4535
+ return handleTool("tapp_ci_setup", { ...rest, operation: action || rest.operation || "inspect" });
4536
+ case "tapp_report":
4537
+ if (isNonEmptyString(rest.captureId) || isNonEmptyString(rest.runPath)) return handleTool("tapp_capture_summary", { runId: rest.captureId, runPath: rest.runPath });
4538
+ return handleTool("tapp_list_captures", rest);
4539
+ case "tapp_session": {
4540
+ if (action === "start") return handleTool("tapp_session_start", rest);
4541
+ if (action === "end") return handleTool("tapp_session_end", rest);
4542
+ if (action === "save_flow") return handleTool("tapp_flow_save", rest);
4543
+ if (action === "draft_flow") return handleTool("tapp_flow_generate", { ...rest, goal });
4544
+ return handleTool("tapp_session_act", { ...rest, action: action || "tree" });
4545
+ }
4546
+ case "tapp_build": {
4547
+ if (action === "simulators") return handleTool("tapp_list_simulators", rest);
4548
+ if (action === "boot") return handleTool("tapp_boot_simulator", rest);
4549
+ if (action === "install") return handleTool("tapp_install_app", rest);
4550
+ return handleTool("tapp_build", rest);
4551
+ }
4552
+ case "tapp_doctor":
4553
+ return handleTool("tapp_health", rest);
4554
+ default:
4555
+ return handleTool(name, args);
4556
+ }
4557
+ }
4558
+
4559
+ export async function dispatchTool(name, args = {}) {
4560
+ if (PUBLIC_TOOL_NAMES.has(name)) return routePublicTool(name, args);
4561
+ const legacy = LEGACY_TOOLS[name];
4562
+ if (!legacy) return errorResult(`Unknown tool: ${name}`);
4563
+ const result = await handleTool(name, args);
4564
+ const deprecated = `${name} is deprecated; use ${legacy.tool}${legacy.hint ? ` with ${legacy.hint}` : ""}.`;
4565
+ result.structuredContent = { ...(result.structuredContent || {}), deprecated };
4566
+ if (result.content?.[0]?.type === "text") result.content[0].text = `${result.content[0].text}\n\nℹ️ ${deprecated}`;
4567
+ return result;
4568
+ }
4569
+
4570
+ server.setRequestHandler(CallToolRequestSchema, async (request) => {
4571
+ currentRequest = request;
4572
+ try { return await dispatchTool(request.params.name, request.params.arguments || {}); }
4573
+ finally { currentRequest = null; }
4574
+ });
4575
+
4576
+
4779
4577
  export async function startMcpServer() {
4780
4578
  const transport = new StdioServerTransport();
4781
4579
  await server.connect(transport);