digital-ai-testing-mcp 2.1.1 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/README.md +18 -13
  2. package/dist/api/webdriver.d.ts +61 -3
  3. package/dist/api/webdriver.d.ts.map +1 -1
  4. package/dist/api/webdriver.js +659 -33
  5. package/dist/api/webdriver.js.map +1 -1
  6. package/dist/index.js +1 -0
  7. package/dist/index.js.map +1 -1
  8. package/dist/tools/boilerplate-tools.d.ts +1 -1
  9. package/dist/tools/boilerplate-tools.d.ts.map +1 -1
  10. package/dist/tools/boilerplate-tools.js +155 -52
  11. package/dist/tools/boilerplate-tools.js.map +1 -1
  12. package/dist/tools/inspection-tools.d.ts.map +1 -1
  13. package/dist/tools/inspection-tools.js +217 -23
  14. package/dist/tools/inspection-tools.js.map +1 -1
  15. package/dist/tools/meta-tools.d.ts +1 -1
  16. package/dist/tools/meta-tools.d.ts.map +1 -1
  17. package/dist/tools/meta-tools.js +2 -1
  18. package/dist/tools/meta-tools.js.map +1 -1
  19. package/dist/tools/performance-tools.d.ts.map +1 -1
  20. package/dist/tools/performance-tools.js +6 -1
  21. package/dist/tools/performance-tools.js.map +1 -1
  22. package/dist/types/digital-ai.d.ts +8 -0
  23. package/dist/types/digital-ai.d.ts.map +1 -1
  24. package/dist/utils/test-orchestrator.d.ts +2 -0
  25. package/dist/utils/test-orchestrator.d.ts.map +1 -1
  26. package/dist/utils/test-orchestrator.js +2 -0
  27. package/dist/utils/test-orchestrator.js.map +1 -1
  28. package/package.json +3 -1
  29. package/resources/boilerplate/Android-Native/Java JUnit5/AndroidNative-oss-po.java +48 -0
  30. package/resources/boilerplate/Android-Native/Java JUnit5/AndroidNative-oss.java +23 -13
  31. package/resources/boilerplate/Android-Native/Java JUnit5/AndroidNative.java +19 -10
  32. package/resources/boilerplate/Android-Native/Java JUnit5/gradle-oss +4 -1
  33. package/resources/boilerplate/Android-Native/Java JUnit5/maven-oss +7 -1
  34. package/resources/boilerplate/Android-Native/NodeJS (WebDriver)/AndroidNative-po.js +13 -0
  35. package/resources/boilerplate/Android-Native/NodeJS (WebDriver)/AndroidNative.js +17 -11
  36. package/resources/boilerplate/Android-Native/NodeJS (WebDriver)/wdio-oss.conf.js +7 -2
  37. package/resources/boilerplate/Android-Native/NodeJS (WebDriver)/wdio.conf.js +10 -4
  38. package/resources/boilerplate/Android-Native/Python/AndroidNative-oss.py +30 -14
  39. package/resources/boilerplate/Android-Native/Python/AndroidNative.py +21 -5
  40. package/resources/boilerplate/Android-Native/Robot Framework/AndroidNative-oss.robot +28 -11
  41. package/resources/boilerplate/Android-Native/java TestNG/AndroidNative-oss-po.java +48 -0
  42. package/resources/boilerplate/Android-Native/java TestNG/AndroidNative-oss.java +23 -13
  43. package/resources/boilerplate/Android-Native/java TestNG/AndroidNative.java +19 -10
  44. package/resources/boilerplate/Android-Native/java TestNG/gradle-oss +4 -1
  45. package/resources/boilerplate/Android-Native/java TestNG/maven-oss +7 -1
  46. package/resources/boilerplate/iOS-Native/NodeJS (WebDriver)/iOSNative-po.js +13 -0
  47. package/resources/boilerplate/iOS-Native/NodeJS (WebDriver)/iOSNative.js +17 -11
  48. package/resources/boilerplate/iOS-Native/NodeJS (WebDriver)/wdio-oss.conf.js +4 -1
  49. package/resources/boilerplate/iOS-Native/NodeJS (WebDriver)/wdio.conf.js +2 -0
  50. package/resources/boilerplate/iOS-Native/Python/iOSNative-oss.py +31 -14
  51. package/resources/boilerplate/iOS-Native/Python/iOSNative.py +36 -15
  52. package/resources/boilerplate/iOS-Native/Robot Framework/iOSNative-oss.robot +28 -11
  53. package/resources/boilerplate/iOS-Native/java-JUnit5/gradle-oss +4 -1
  54. package/resources/boilerplate/iOS-Native/java-JUnit5/iOSNative-oss-po.java +45 -0
  55. package/resources/boilerplate/iOS-Native/java-JUnit5/iOSNative-oss.java +24 -13
  56. package/resources/boilerplate/iOS-Native/java-JUnit5/iOSNative.java +21 -11
  57. package/resources/boilerplate/iOS-Native/java-JUnit5/maven-oss +7 -1
  58. package/resources/boilerplate/iOS-Native/java-TestNG/gradle-oss +4 -1
  59. package/resources/boilerplate/iOS-Native/java-TestNG/iOSNative-oss-po.java +45 -0
  60. package/resources/boilerplate/iOS-Native/java-TestNG/iOSNative-oss.java +24 -13
  61. package/resources/boilerplate/iOS-Native/java-TestNG/iOSNative.java +21 -11
  62. package/resources/boilerplate/iOS-Native/java-TestNG/maven-oss +7 -1
  63. package/resources/boilerplate/shared/java-screens/AppScreen.java +27 -0
  64. package/resources/boilerplate/shared/java-screens/BaseScreen.java +40 -0
  65. package/resources/boilerplate/shared/java-screens/DashboardScreen.java +16 -0
  66. package/resources/boilerplate/shared/java-screens/LoginScreen.java +21 -0
  67. package/resources/boilerplate/shared/java-screens/PaymentScreen.java +32 -0
  68. package/resources/boilerplate/shared/node-screens/AppScreen.js +27 -0
  69. package/resources/boilerplate/shared/node-screens/DashboardScreen.js +13 -0
  70. package/resources/boilerplate/shared/node-screens/LoginScreen.js +18 -0
  71. package/resources/boilerplate/shared/node-screens/PaymentScreen.js +28 -0
  72. package/resources/boilerplate/shared/node-screens/PlaceholderScreen.js +21 -0
@@ -1,6 +1,6 @@
1
1
  import { z } from 'zod';
2
2
  import { caseInsensitiveEnum } from '../utils/schema.js';
3
- import { createInspectionSession, quitInspectionSession, captureScreenshot, getPageSource, findElements, tapElement, typeIntoElement, clearElement, swipeScreen, getWindowSize, launchApp, pressBack, longPress, doubleTap, dragAndDrop, pinchZoom, scrollToElement, pressKey, isKeyboardShown, hideKeyboard, appControl, getOrientation, setOrientation, getClipboard, setClipboard, setGeolocation, resetGeolocation, handleAlert, pushFileToDevice, pullFileFromDevice, mockAuthentication, requireSession, findFirstElementId, listActiveSessions, getPendingReportIds, sweepTimedOutStarts, deleteAllTrackedReports, automotiveControl, audioControl, AUTOMOTIVE_RESOLUTIONS, INSTRUMENT_CLUSTER_CONTENT, getForegroundActivity, isSameActivity, } from '../api/webdriver.js';
3
+ import { createInspectionSession, quitInspectionSession, captureScreenshot, getPageSource, findElements, tapElement, typeIntoElement, clearElement, swipeScreen, getWindowSize, launchApp, pressBack, longPress, doubleTap, dragAndDrop, pinchZoom, scrollToElement, pressKey, isKeyboardShown, hideKeyboard, appControl, getOrientation, setOrientation, getClipboard, setClipboard, setGeolocation, resetGeolocation, handleAlert, pushFileToDevice, pullFileFromDevice, mockAuthentication, requireSession, findFirstElementId, listActiveSessions, getPendingReportIds, sweepTimedOutStarts, deleteAllTrackedReports, automotiveControl, audioControl, AUTOMOTIVE_RESOLUTIONS, INSTRUMENT_CLUSTER_CONTENT, getForegroundActivity, isSameActivity, listContexts, switchContext, getDeviceLog, getAlertInfo, isWebviewContext, sessionCapture, networkConnection, setNetworkConditions, injectCameraImage, clearWebCache, deviceDiagnostics, setAppearance, accessibilityAudit } from '../api/webdriver.js';
4
4
  import { checkDestructiveGuard } from '../utils/destructive-guard.js';
5
5
  import { getActiveUrl } from '../api/client.js';
6
6
  import { checkDeleteAllowed } from '../api/access-level.js';
@@ -14,7 +14,7 @@ import { getDeploymentMode } from '../utils/deployment-mode.js';
14
14
  // — faster and less brittle than xpath on iOS, and the form the Mobile Studio iOS Test Recorder emits. iOS on Appium
15
15
  // Server only: the Appium Grid rejects it ("Locator Strategy '-ios predicate string' is not supported for this
16
16
  // session", verified live 2026-10-09 on an iPhone 13 Pro Max) — use xpath or accessibility id there.
17
- const LOCATOR_STRATEGIES = ['xpath', 'id', 'accessibility id', 'class name', '-ios predicate string'];
17
+ const LOCATOR_STRATEGIES = ['xpath', 'id', 'accessibility id', 'class name', '-ios predicate string', 'css selector'];
18
18
  // ─── Helpers ─────────────────────────────────────────────────────────────────
19
19
  // Returns an error result if the session is a browser (web) session — used to
20
20
  // guard mobile-only tools so they produce a clear message instead of a protocol error.
@@ -408,7 +408,7 @@ export function registerInspectionTools(server) {
408
408
  .describe('Preserve the session report (and its platform-recorded video) instead of deleting it. Default false.'),
409
409
  }, async (args) => {
410
410
  try {
411
- const { reportDeleted, reportKept, canDeleteReport, reportTestId, reportUrl } = await quitInspectionSession(args.handle, args.keepReport ?? false);
411
+ const { reportDeleted, reportKept, canDeleteReport, reportTestId, reportUrl, reportDeleteError } = await quitInspectionSession(args.handle, args.keepReport ?? false);
412
412
  let text;
413
413
  if (reportKept) {
414
414
  text =
@@ -420,6 +420,13 @@ export function registerInspectionTools(server) {
420
420
  else if (reportDeleted) {
421
421
  text = `✅ Session ${args.handle} stopped. Device released. Probe report deleted.`;
422
422
  }
423
+ else if (reportDeleteError && reportTestId > 0) {
424
+ text =
425
+ `✅ Session ${args.handle} stopped. Device released.
426
+
427
+ ` +
428
+ `⚠️ Report NOT deleted (test_id=${reportTestId}): ${reportDeleteError}. Report: ${reportUrl}`;
429
+ }
423
430
  else if (!canDeleteReport && reportTestId > 0) {
424
431
  text =
425
432
  `✅ Session ${args.handle} stopped. Device released.\n\n` +
@@ -569,8 +576,13 @@ export function registerInspectionTools(server) {
569
576
  if (mobileErr)
570
577
  return { ...mobileErr, content: [{ type: 'text', text: `"get_element_tree" is for mobile sessions only. For browser sessions use get_page_dom to inspect the rendered DOM.` }] };
571
578
  try {
572
- const platform = requireSession(args.handle).platform;
579
+ const sess = requireSession(args.handle);
580
+ const platform = sess.platform;
573
581
  const xml = await getPageSource(args.handle);
582
+ if (isWebviewContext(sess)) {
583
+ const html = xml.length > 12000 ? xml.slice(0, 12000) + '\n... (truncated)' : xml;
584
+ return { content: [{ type: 'text', text: `Session is in web context ${sess.currentContext} — the page source is HTML (${xml.length} chars), not a native tree. Locate with find_elements(strategy: "css selector") or xpath; switch back with webview_context(action: "native").\n\n${html}` }] };
585
+ }
574
586
  const { elements, totalNodes } = parseElementTree(xml, platform);
575
587
  const table = formatElementTable(elements, totalNodes, platform);
576
588
  let text = table;
@@ -590,10 +602,13 @@ export function registerInspectionTools(server) {
590
602
  // ── find_elements ─────────────────────────────────────────────────────────
591
603
  server.tool('find_elements', 'Find elements on the current screen using a locator strategy and return their IDs and attributes. ' +
592
604
  'The returned elementId values are used with tap_element, type_into_element, and clear_element. ' +
593
- 'Strategies: "xpath" (most flexible), "id" (resource-id, fastest), "accessibility id" (content-desc), ' +
594
- '"class name" (by widget type, often returns many), "-ios predicate string" (iOS on Appium Server projects only — ' +
595
- 'NSPredicate such as "type == \'XCUIElementTypeButton\' AND label == \'Login\'"; faster and steadier than xpath; ' +
596
- 'the Appium Grid rejects it, so use xpath or accessibility id there). Attributes are fetched for the first ' +
605
+ 'Strategies: "id" (Android resource-id, fastest), "accessibility id" (Android content-desc; on iOS it IS the name ' +
606
+ 'attribute — identifier, else label — so it matches exactly what //*[@name=\'x\'] matches, without walking the tree; ' +
607
+ 'works on the Grid too), "-ios predicate string" (iOS on Appium Server projects only — NSPredicate such as ' +
608
+ '"type == \'XCUIElementTypeButton\' AND label == \'Login\'"; the Appium Grid rejects it), "class name" (by widget ' +
609
+ 'type, often returns many), "xpath" (most flexible, slowest — attribute matches only, never positional [1]/[2]), ' +
610
+ '"css selector" (ONLY inside a WEBVIEW context — see webview_context). ' +
611
+ 'Prefer them in that order and copy the strategy you used into the generated test. Attributes are fetched for the first ' +
597
612
  'maxResults matches (default 20); the rest are listed by elementId — narrow the selector rather than raising it.', {
598
613
  handle: z
599
614
  .string()
@@ -653,6 +668,8 @@ export function registerInspectionTools(server) {
653
668
  if (e.bounds)
654
669
  lines.push(` bounds: ${e.bounds}`);
655
670
  lines.push(` clickable: ${e.clickable ?? 'unknown'}`);
671
+ if (e.hittable != null)
672
+ lines.push(` hittable: ${e.hittable}${e.hittable ? '' : ' (visible but not on the hit-test path — a tap may land on what covers it)'}`);
656
673
  lines.push(` enabled: ${e.enabled ?? 'unknown'}`);
657
674
  lines.push('');
658
675
  }
@@ -1056,7 +1073,8 @@ export function registerInspectionTools(server) {
1056
1073
  });
1057
1074
  // ── press_key ─────────────────────────────────────────────────────────────
1058
1075
  server.tool('press_key', 'Press a device key. Android: ENTER to submit forms/search, HOME, APP_SWITCH, volume, or any raw keycode. ' +
1059
- 'iOS: HOME, VOLUME_UP, VOLUME_DOWN, POWER (physical buttons only — for ENTER type "\\n" via type_into_element). ' +
1076
+ 'iOS: HOME, VOLUME_UP, VOLUME_DOWN, POWER (physical buttons only — for ENTER type "\\n" via type_into_element; ' +
1077
+ 'POWER toggles the lock: it locks an unlocked device and unlocks a locked one). ' +
1060
1078
  'Complements press_back (which has its own tool).', {
1061
1079
  handle: z.string().describe('Session handle from start_inspection_session.'),
1062
1080
  key: z
@@ -1104,24 +1122,35 @@ export function registerInspectionTools(server) {
1104
1122
  // ── app_control ───────────────────────────────────────────────────────────
1105
1123
  server.tool('app_control', 'Control app lifecycle in an inspection session: terminate (force-stop), clear_data (reset to first-launch state — Android only; ' +
1106
1124
  'iOS requires uninstall/reinstall), query_state (installed/background/foreground), ' +
1107
- 'deep_link (open a URL/URI directly — skip navigation to the screen under test). ' +
1108
- 'NOTE on Grid sessions: query_state reports only the foreground activity (Android) or is unavailable (iOS); deep_link is best-effort. ' +
1109
- 'To relaunch after terminate, use launch_app.', {
1125
+ 'deep_link (open a URL/URI directly — skip navigation to the screen under test), ' +
1126
+ 'background (send the app to the background for `seconds` and bring it back — lifecycle/resume testing), ' +
1127
+ 'is_installed (true/false for packageName), current (what is in the foreground: Android package + activity, iOS bundle id), ' +
1128
+ 'install (install a repository build mid-session from appRef "cloud:<package or bundle>" / "cloud:uniqueName=<name>" — Appium Server only; ' +
1129
+ 'this lifts the "install before the session" rule for Appium Server projects), ' +
1130
+ 'clear_web_cache (seetest:client.hybridClearCache — drops the cache of the app\'s webviews; both modes). ' +
1131
+ 'NOTE on Grid sessions: query_state/current report only the foreground activity (Android) or are unavailable (iOS); deep_link is best-effort; ' +
1132
+ 'background, is_installed and install are Appium Server only. To relaunch after terminate, use launch_app.', {
1110
1133
  handle: z.string().describe('Session handle from start_inspection_session.'),
1111
1134
  action: z
1112
- .enum(['terminate', 'clear_data', 'query_state', 'deep_link'])
1135
+ .enum(['terminate', 'clear_data', 'query_state', 'deep_link', 'background', 'is_installed', 'current', 'install', 'clear_web_cache'])
1113
1136
  .describe('Lifecycle action to perform.'),
1114
1137
  packageName: z
1115
1138
  .string()
1116
1139
  .optional()
1117
- .describe('Android package name or iOS bundle identifier. Required for terminate, clear_data, query_state; optional Android handler hint for deep_link.'),
1140
+ .describe('Android package name or iOS bundle identifier. Required for terminate, clear_data, query_state, is_installed; optional Android handler hint for deep_link.'),
1118
1141
  url: z.string().optional().describe('URL or URI scheme for deep_link, e.g. "myapp://orders/42" or "https://...".'),
1142
+ seconds: z.number().int().min(1).max(300).optional().describe('For background: how long to keep the app in the background. Default 3.'),
1143
+ appRef: z.string().optional().describe('For install: repository reference — "cloud:com.example.app" (Android may add "/.MainActivity"), "cloud:uniqueName=<name>", or "cloud:<package>:releaseVersion=<v>:buildVersion=<b>".'),
1119
1144
  }, async (args) => {
1120
1145
  const mobileErr = requireMobileSession(args.handle, 'app_control');
1121
1146
  if (mobileErr)
1122
1147
  return mobileErr;
1123
1148
  try {
1124
- const result = await appControl(args.handle, args.action, args.packageName, args.url);
1149
+ if (args.action === 'clear_web_cache') {
1150
+ await clearWebCache(args.handle);
1151
+ return { content: [{ type: 'text', text: '✅ Webview cache cleared (hybridClearCache).' }] };
1152
+ }
1153
+ const result = await appControl(args.handle, args.action, args.packageName, args.url, { seconds: args.seconds, appRef: args.appRef });
1125
1154
  return { content: [{ type: 'text', text: `✅ ${result}` }] };
1126
1155
  }
1127
1156
  catch (e) {
@@ -1130,16 +1159,23 @@ export function registerInspectionTools(server) {
1130
1159
  });
1131
1160
  // ── device_control ────────────────────────────────────────────────────────
1132
1161
  server.tool('device_control', 'Device-level controls for an inspection session: orientation (get/set — rotation testing), clipboard (get/set — paste flows), ' +
1133
- 'geolocation (set/reset — location-based features), alerts (accept/dismiss — system dialogs, Appium Server only), ' +
1134
- 'and file transfer (push_file/pull_file — test fixtures like images for upload flows). ' +
1162
+ 'geolocation (set/reset — location-based features), alerts (get_alert reads the text and, on iOS, the button labels; ' +
1163
+ 'accept/dismiss — system dialogs, Appium Server only; iOS accept/dismiss take buttonLabel to press a specific button), ' +
1164
+ 'file transfer (push_file/pull_file — test fixtures like images for upload flows), ' +
1165
+ 'device_info (one call: model, OS/API level, locale, time zone, battery, screen size/scale, system bars, lock state, ' +
1166
+ 'light/dark appearance — Appium Server), set_appearance (style dark|light: iOS appearance / Android night mode — ' +
1167
+ 'dark-mode screenshot checks), accessibility_audit (iOS: XCTest\'s built-in audit of the current screen, no extra ' +
1168
+ 'dependency; Android: use includeAxeScan in get_test_boilerplate). ' +
1135
1169
  'Grid session limits: alerts and reset_geolocation are not supported, and iOS Grid devices reject clipboard ops ' +
1136
1170
  '(clear errors explain alternatives). iOS file paths may require the @bundleId:container syntax.', {
1137
1171
  handle: z.string().describe('Session handle from start_inspection_session.'),
1138
1172
  action: z
1139
- .enum(['get_orientation', 'set_orientation', 'get_clipboard', 'set_clipboard', 'set_geolocation', 'reset_geolocation', 'accept_alert', 'dismiss_alert', 'push_file', 'pull_file'])
1173
+ .enum(['get_orientation', 'set_orientation', 'get_clipboard', 'set_clipboard', 'set_geolocation', 'reset_geolocation', 'get_alert', 'accept_alert', 'dismiss_alert', 'push_file', 'pull_file', 'device_info', 'set_appearance', 'accessibility_audit'])
1140
1174
  .describe('Device action to perform.'),
1141
1175
  orientation: z.enum(['PORTRAIT', 'LANDSCAPE']).optional().describe('For set_orientation.'),
1176
+ style: z.enum(['dark', 'light']).optional().describe('For set_appearance.'),
1142
1177
  text: z.string().optional().describe('For set_clipboard: the text to place on the clipboard.'),
1178
+ buttonLabel: z.string().optional().describe('For accept_alert / dismiss_alert on iOS: the exact button label to press (from get_alert), e.g. "Allow Once".'),
1143
1179
  latitude: z.number().optional().describe('For set_geolocation.'),
1144
1180
  longitude: z.number().optional().describe('For set_geolocation.'),
1145
1181
  remotePath: z.string().optional().describe('For push_file/pull_file: absolute device path, e.g. "/sdcard/Download/fixture.png".'),
@@ -1183,10 +1219,32 @@ export function registerInspectionTools(server) {
1183
1219
  await resetGeolocation(args.handle);
1184
1220
  return { content: [{ type: 'text', text: '✅ Simulated location cleared — device uses its real location again.' }] };
1185
1221
  }
1222
+ case 'device_info': {
1223
+ const d = await deviceDiagnostics(args.handle);
1224
+ return { content: [{ type: 'text', text: Object.entries(d).filter(([, v]) => v !== undefined).map(([k, v]) => ` ${k}: ${typeof v === 'object' ? JSON.stringify(v) : String(v)}`).join('\n') }] };
1225
+ }
1226
+ case 'set_appearance': {
1227
+ if (!args.style)
1228
+ return { content: [{ type: 'text', text: 'Error: set_appearance requires style (dark|light).' }], isError: true };
1229
+ const now = await setAppearance(args.handle, args.style);
1230
+ if (now !== args.style) {
1231
+ return { content: [{ type: 'text', text: `⚠️ Requested ${args.style} but the device reports ${now} afterwards — this device/OS build does not honour the ${requireSession(args.handle).platform === 'ios' ? 'appearance' : 'night-mode (cmd uimode)'} switch (seen on one Android phone live). Toggle dark mode in the device Settings app instead.` }], isError: true };
1232
+ }
1233
+ return { content: [{ type: 'text', text: `✅ Appearance is now ${now}. Take a screenshot to check the themed screen; set it back before stopping the session.` }] };
1234
+ }
1235
+ case 'accessibility_audit': {
1236
+ const findings = await accessibilityAudit(args.handle);
1237
+ const lines = findings.slice(0, 30).map((f, i) => `${i + 1}. ${String(f.type ?? f.auditType ?? 'issue')}: ${String(f.detailedDescription ?? f.compactDescription ?? f.elementDescription ?? '').split('\n')[0].slice(0, 200)}`);
1238
+ return { content: [{ type: 'text', text: findings.length ? `${findings.length} accessibility finding(s) on this screen:\n${lines.join('\n')}${findings.length > 30 ? `\n… ${findings.length - 30} more` : ''}` : 'No accessibility findings on this screen.' }] };
1239
+ }
1240
+ case 'get_alert': {
1241
+ const a = await getAlertInfo(args.handle);
1242
+ return { content: [{ type: 'text', text: `Alert text: ${JSON.stringify(a.text)}${a.buttons ? `\nButtons: ${a.buttons.map((b) => `"${b}"`).join(', ')} — press one with accept_alert + buttonLabel` : ''}` }] };
1243
+ }
1186
1244
  case 'accept_alert':
1187
1245
  case 'dismiss_alert': {
1188
- await handleAlert(args.handle, args.action === 'accept_alert' ? 'accept' : 'dismiss');
1189
- return { content: [{ type: 'text', text: `✅ Alert ${args.action === 'accept_alert' ? 'accepted' : 'dismissed'}.` }] };
1246
+ await handleAlert(args.handle, args.action === 'accept_alert' ? 'accept' : 'dismiss', args.buttonLabel);
1247
+ return { content: [{ type: 'text', text: `✅ Alert ${args.buttonLabel ? `button "${args.buttonLabel}" pressed` : args.action === 'accept_alert' ? 'accepted' : 'dismissed'}.` }] };
1190
1248
  }
1191
1249
  case 'push_file': {
1192
1250
  if (!args.remotePath || !args.localPath) {
@@ -1296,6 +1354,142 @@ export function registerInspectionTools(server) {
1296
1354
  };
1297
1355
  }
1298
1356
  });
1357
+ // ── webview_context ────────────────────────────────────────────────────────
1358
+ server.tool('webview_context', 'Hybrid apps: list the WebDriver contexts of an inspection session and switch between the native layer and a ' +
1359
+ 'WEBVIEW_… context. In a webview, find_elements takes "css selector" (and xpath over the HTML), get_element_tree ' +
1360
+ 'returns the HTML, tap/type work on the web elements. action "list" shows what is available (waits up to waitMs ' +
1361
+ 'for a webview to be registered — one appears only while a screen with debuggable web content is in front); ' +
1362
+ '"switch" enters the first WEBVIEW (or the one given in name); "native" returns to NATIVE_APP — ALWAYS switch back ' +
1363
+ 'before native taps, and before stop_inspection_session. Appium Server projects; the Appium Grid lists NATIVE_APP only. ' +
1364
+ 'No webview listed? The app must allow web inspection (Android: WebView.setWebContentsDebuggingEnabled(true) in the ' +
1365
+ 'build under test; iOS: web inspector enabled for the app) — a release build usually does not.', {
1366
+ handle: z.string().describe('Session handle from start_inspection_session.'),
1367
+ action: z.enum(['list', 'switch', 'native']).describe('list, switch (to name or the first WEBVIEW), or native.'),
1368
+ name: z.string().optional().describe('For switch: a context id from list, e.g. "WEBVIEW_chrome" or "WEBVIEW_12345.1". Default: the first WEBVIEW.'),
1369
+ waitMs: z.number().int().min(0).max(30000).optional().describe('How long list/switch wait for a webview to appear. Default 3000.'),
1370
+ }, async (args) => {
1371
+ const mobileErr = requireMobileSession(args.handle, 'webview_context');
1372
+ if (mobileErr)
1373
+ return mobileErr;
1374
+ try {
1375
+ if (args.action === 'list') {
1376
+ const ctx = await listContexts(args.handle, args.waitMs ?? 3000);
1377
+ const current = requireSession(args.handle).currentContext ?? 'NATIVE_APP';
1378
+ const lines = ctx.map((c) => ` ${c.id === current ? '▶' : ' '} ${c.id}${c.title ? ` — "${c.title}"` : ''}${c.url ? ` ${c.url}` : ''}${c.package ? ` (${c.package})` : ''}${c.bundleId ? ` (${c.bundleId})` : ''}`);
1379
+ const hasWeb = ctx.some((c) => /^WEBVIEW/i.test(c.id));
1380
+ return { content: [{ type: 'text', text: `Contexts (current: ${current}):\n${lines.join('\n')}${hasWeb ? '\n\nwebview_context(action: "switch") enters the first WEBVIEW.' : '\n\nNo WEBVIEW is registered on this screen.'}` }] };
1381
+ }
1382
+ const r = await switchContext(args.handle, args.action === 'native' ? 'native' : (args.name ?? 'auto'), args.waitMs ?? 3000);
1383
+ return { content: [{ type: 'text', text: r.context === 'NATIVE_APP'
1384
+ ? `✅ Back in NATIVE_APP (contexts: ${r.available.join(', ')}).`
1385
+ : `✅ Switched to ${r.context}${r.title ? ` — "${r.title}"` : ''}${r.url ? ` ${r.url}` : ''}.\nUse find_elements(strategy: "css selector", selector: "input[name=…]") / get_element_tree (HTML); call webview_context(action: "native") when done.` }] };
1386
+ }
1387
+ catch (e) {
1388
+ return { content: [{ type: 'text', text: `Error (webview_context ${args.action}): ${e.message}` }], isError: true };
1389
+ }
1390
+ });
1391
+ // ── get_device_log ─────────────────────────────────────────────────────────
1392
+ server.tool('get_device_log', 'Read the device log of a LIVE inspection session (Android logcat; iOS syslog — also crashlog, and on Appium Server ' +
1393
+ 'performance/safariConsole/safariNetwork) to diagnose a crash, ANR or permission denial while the session is still ' +
1394
+ 'open — no report download needed (get_test_log is the after-the-fact equivalent). Returns the last `tail` lines; ' +
1395
+ 'pass `contains` (e.g. the package name, "FATAL", "Exception", "denied") to filter first — logs run to thousands of lines.', {
1396
+ handle: z.string().describe('Session handle from start_inspection_session.'),
1397
+ logType: z.string().optional().describe('Log type. Default: logcat (Android) / syslog (iOS). The error lists what the session offers.'),
1398
+ contains: z.string().optional().describe('Case-insensitive substring filter applied before the tail.'),
1399
+ tail: z.number().int().min(1).max(2000).optional().describe('Lines to return from the end (after filtering). Default 200.'),
1400
+ }, async (args) => {
1401
+ const mobileErr = requireMobileSession(args.handle, 'get_device_log');
1402
+ if (mobileErr)
1403
+ return mobileErr;
1404
+ try {
1405
+ const r = await getDeviceLog(args.handle, args.logType, { tail: args.tail, contains: args.contains });
1406
+ const head = `${r.type}: ${r.totalLines} line(s) captured${args.contains ? `, ${r.lines.length} shown matching "${args.contains}"` : `, last ${r.lines.length} shown`}${r.types.length ? ` (types: ${r.types.join(', ')})` : ''}`;
1407
+ return { content: [{ type: 'text', text: `${head}\n\n${r.lines.join('\n') || '(no matching lines)'}` }] };
1408
+ }
1409
+ catch (e) {
1410
+ return { content: [{ type: 'text', text: `Error (get_device_log): ${e.message}` }], isError: true };
1411
+ }
1412
+ });
1413
+ // ── session_capture ────────────────────────────────────────────────────────
1414
+ server.tool('session_capture', 'Record part of a live inspection session into the file repository: kind "har" captures the device\'s HTTP traffic ' +
1415
+ '(startHarRecording → stopHarRecording) and kind "device_log" captures logcat/syslog for exactly the window between ' +
1416
+ 'start and stop (startLoggingDevice → stopLoggingDevice). stop returns the repository file (id, size) to fetch with ' +
1417
+ 'download_repository_file / get_repository_file_download_command. The HAR is a ZIP containing har.json. CAVEAT: with ' +
1418
+ 'NV tunneling on for the device (every device on this tenant) the platform records NO HAR entries — the file comes ' +
1419
+ 'back ~290 bytes and the response says so; use a performance transaction for network byte counts. Works on Appium ' +
1420
+ 'Server and Appium Grid sessions (both verified live). For an unbounded in-session read without a file, use get_device_log.', {
1421
+ handle: z.string().describe('Session handle from start_inspection_session.'),
1422
+ kind: z.enum(['har', 'device_log']).describe('What to capture.'),
1423
+ action: z.enum(['start', 'stop']).describe('start or stop (one capture of each kind at a time).'),
1424
+ name: z.string().optional().describe('For start: repository file name (uniqueName; ".har"/".log" is added). Default: mcp-<kind>-<timestamp>.'),
1425
+ }, async (args) => {
1426
+ const mobileErr = requireMobileSession(args.handle, 'session_capture');
1427
+ if (mobileErr)
1428
+ return mobileErr;
1429
+ try {
1430
+ const r = await sessionCapture(args.handle, args.kind, args.action, args.name);
1431
+ if (args.action === 'start')
1432
+ return { content: [{ type: 'text', text: `✅ ${args.kind} capture started → repository file "${r.file}". Run the steps to capture, then session_capture(action: "stop").` }] };
1433
+ const where = r.repositoryFile ? `repository file "${r.file}" (id ${r.repositoryFile.id}, ${r.repositoryFile.size} bytes) — download_repository_file(fileId: ${r.repositoryFile.id})` : `repository file "${r.file}" (not listed yet — list_repository_files(uniqueName: "${r.file}") in a few seconds)`;
1434
+ return { content: [{ type: 'text', text: `✅ ${args.kind} capture stopped → ${where}.${r.note ? `\n⚠️ ${r.note}` : ''}` }] };
1435
+ }
1436
+ catch (e) {
1437
+ return { content: [{ type: 'text', text: `Error (session_capture ${args.kind} ${args.action}): ${e.message}` }], isError: true };
1438
+ }
1439
+ });
1440
+ // ── network_control ────────────────────────────────────────────────────────
1441
+ server.tool('network_control', 'Network state of the device in a live inspection session. action "get" reads whether wifi / mobile_data / ' +
1442
+ 'airplane_mode / bluetooth is on; "set" switches one on or off (Android only — offline-mode and reconnect flows; ' +
1443
+ 'turn it back on before stopping); "set_conditions" applies an NV network profile ("3G-average", "Monitor" = none…) ' +
1444
+ 'to the device\'s traffic WITHOUT recording a transaction — for exploring an app under a slow network; durationMs 0 ' +
1445
+ 'keeps it until changed; needs an ONLINE, tunneled NV server in the device\'s region (list_nv_servers) and a Project Admin ' +
1446
+ 'or Cloud Admin key. Appium Server and Appium Grid sessions (seetest:client commands run on both).', {
1447
+ handle: z.string().describe('Session handle from start_inspection_session.'),
1448
+ action: z.enum(['get', 'set', 'set_conditions']).describe('get / set a connection, or set_conditions (NV profile).'),
1449
+ kind: z.enum(['wifi', 'mobile_data', 'airplane_mode', 'bluetooth']).optional().describe('For get/set: which connection.'),
1450
+ enabled: z.boolean().optional().describe('For set: true = on, false = off.'),
1451
+ profile: z.string().optional().describe('For set_conditions: NV profile name, e.g. "3G-average"; "Monitor" lifts shaping.'),
1452
+ durationMs: z.number().int().min(0).max(3_600_000).optional().describe('For set_conditions: how long to keep the profile; 0 (default) = until changed.'),
1453
+ }, async (args) => {
1454
+ const mobileErr = requireMobileSession(args.handle, 'network_control');
1455
+ if (mobileErr)
1456
+ return mobileErr;
1457
+ try {
1458
+ if (args.action === 'set_conditions') {
1459
+ if (!args.profile)
1460
+ return { content: [{ type: 'text', text: 'Error: set_conditions requires profile.' }], isError: true };
1461
+ return { content: [{ type: 'text', text: `✅ ${await setNetworkConditions(args.handle, args.profile, args.durationMs ?? 0)}` }] };
1462
+ }
1463
+ if (!args.kind)
1464
+ return { content: [{ type: 'text', text: 'Error: get/set require kind.' }], isError: true };
1465
+ if (args.action === 'set' && args.enabled == null)
1466
+ return { content: [{ type: 'text', text: 'Error: set requires enabled.' }], isError: true };
1467
+ const r = await networkConnection(args.handle, args.kind, args.action === 'set' ? args.enabled : undefined);
1468
+ return { content: [{ type: 'text', text: `${args.action === 'set' ? '✅ ' : ''}${r.kind}: ${r.enabled ? 'ON' : 'OFF'}` }] };
1469
+ }
1470
+ catch (e) {
1471
+ return { content: [{ type: 'text', text: `Error (network_control ${args.action}): ${e.message}` }], isError: true };
1472
+ }
1473
+ });
1474
+ // ── inject_camera_image ────────────────────────────────────────────────────
1475
+ server.tool('inject_camera_image', 'Camera image injection: the next camera capture in the app under test returns the given image instead of the sensor ' +
1476
+ 'frame — for check deposit, document/QR scan and profile-photo flows on a real device. source is "cloud:<repository ' +
1477
+ 'uniqueName>" (upload the .jpg/.png with upload_repository_file first) or an http(s) URL ending in .jpg/.jpeg/.png. ' +
1478
+ 'REQUIRES an instrumented build (uploaded with instrument=true, or the session started with digitalai:instrumentApp=true) — ' +
1479
+ 'otherwise the platform answers "application is not instrumented". Call it BEFORE tapping the capture button.', {
1480
+ handle: z.string().describe('Session handle from start_inspection_session.'),
1481
+ source: z.string().describe('"cloud:<uniqueName>.png" or an http(s) URL to a .jpg/.jpeg/.png.'),
1482
+ }, async (args) => {
1483
+ const mobileErr = requireMobileSession(args.handle, 'inject_camera_image');
1484
+ if (mobileErr)
1485
+ return mobileErr;
1486
+ try {
1487
+ return { content: [{ type: 'text', text: `✅ ${await injectCameraImage(args.handle, args.source)}` }] };
1488
+ }
1489
+ catch (e) {
1490
+ return { content: [{ type: 'text', text: `Error (inject_camera_image): ${e.message}` }], isError: true };
1491
+ }
1492
+ });
1299
1493
  // ── mock_authentication ────────────────────────────────────────────────────
1300
1494
  server.tool('mock_authentication', 'Pre-stage a mock biometric authentication response (Touch ID, Face ID, or fingerprint) ' +
1301
1495
  'for the next auth dialog in an instrumented app. ' +
@@ -1314,15 +1508,15 @@ export function registerInspectionTools(server) {
1314
1508
  delay: z
1315
1509
  .number()
1316
1510
  .int()
1317
- .min(0)
1511
+ .min(1)
1318
1512
  .optional()
1319
- .describe('Milliseconds to wait after the auth dialog appears before responding. Default 0.'),
1513
+ .describe('Milliseconds to wait after the auth dialog appears before responding. Default 1 (the platform rejects 0).'),
1320
1514
  }, async (args) => {
1321
1515
  const mobileErr = requireMobileSession(args.handle, 'mock_authentication');
1322
1516
  if (mobileErr)
1323
1517
  return mobileErr;
1324
1518
  try {
1325
- const result = await mockAuthentication(args.handle, args.reply, args.delay ?? 0);
1519
+ const result = await mockAuthentication(args.handle, args.reply, args.delay ?? 1);
1326
1520
  return { content: [{ type: 'text', text: `✅ ${result}` }] };
1327
1521
  }
1328
1522
  catch (e) {