appium-mcp 1.97.1 → 1.98.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 (35) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/README.md +52 -2
  3. package/dist/create-server.d.ts.map +1 -1
  4. package/dist/create-server.js +12 -3
  5. package/dist/create-server.js.map +1 -1
  6. package/dist/devicemanager/ios-manager.d.ts +0 -1
  7. package/dist/devicemanager/ios-manager.d.ts.map +1 -1
  8. package/dist/devicemanager/ios-manager.js +10 -23
  9. package/dist/devicemanager/ios-manager.js.map +1 -1
  10. package/dist/http-security.d.ts +7 -0
  11. package/dist/http-security.d.ts.map +1 -0
  12. package/dist/http-security.js +36 -0
  13. package/dist/http-security.js.map +1 -0
  14. package/dist/telemetry/init.d.ts +2 -0
  15. package/dist/telemetry/init.d.ts.map +1 -1
  16. package/dist/telemetry/init.js +14 -1
  17. package/dist/telemetry/init.js.map +1 -1
  18. package/dist/tools/ios/prepare-ios-simulator.d.ts.map +1 -1
  19. package/dist/tools/ios/prepare-ios-simulator.js +21 -37
  20. package/dist/tools/ios/prepare-ios-simulator.js.map +1 -1
  21. package/dist/ui/mcp-ui-utils.d.ts.map +1 -1
  22. package/dist/ui/mcp-ui-utils.js +45 -9
  23. package/dist/ui/mcp-ui-utils.js.map +1 -1
  24. package/dist/ui/page-source-inspector-app.d.ts.map +1 -1
  25. package/dist/ui/page-source-inspector-app.js +164 -89
  26. package/dist/ui/page-source-inspector-app.js.map +1 -1
  27. package/package.json +9 -8
  28. package/server.json +2 -2
  29. package/src/create-server.ts +12 -3
  30. package/src/devicemanager/ios-manager.ts +11 -26
  31. package/src/http-security.ts +43 -0
  32. package/src/telemetry/init.ts +18 -1
  33. package/src/tools/ios/prepare-ios-simulator.ts +21 -39
  34. package/src/ui/mcp-ui-utils.ts +45 -9
  35. package/src/ui/page-source-inspector-app.ts +164 -89
@@ -0,0 +1,43 @@
1
+ import type {IncomingMessage} from 'node:http';
2
+
3
+ import type {ServerStartOptions} from './transport.js';
4
+
5
+ type CorsOptions = NonNullable<ServerStartOptions['httpStream']>['cors'];
6
+
7
+ /** Snapshot operator-controlled origins once, when constructing the server. */
8
+ export function createHttpOriginPolicy(raw = process.env.APPIUM_MCP_ALLOWED_ORIGINS) {
9
+ const origins = raw?.trim() ? raw.split(',').map((value) => value.trim()) : [];
10
+ for (const origin of origins) {
11
+ let valid = false;
12
+ try {
13
+ const url = new URL(origin);
14
+ valid = ['http:', 'https:'].includes(url.protocol) && url.origin === origin && !origin.includes('*');
15
+ } catch {
16
+ // Fail startup rather than silently weakening a malformed allowlist.
17
+ }
18
+ if (!valid) {
19
+ throw new Error(
20
+ 'APPIUM_MCP_ALLOWED_ORIGINS must contain comma-separated exact HTTP(S) origins ' +
21
+ '(scheme://host[:port]), without paths, credentials, wildcards, or null origins.',
22
+ );
23
+ }
24
+ }
25
+ const allowedOrigins = new Set(origins);
26
+ const cors: CorsOptions = origins.length
27
+ ? {origin: [...allowedOrigins], credentials: false, methods: ['GET', 'POST', 'DELETE', 'OPTIONS']}
28
+ : false;
29
+
30
+ return {
31
+ cors,
32
+ async authenticate(request?: IncomingMessage): Promise<Record<string, never>> {
33
+ // FastMCP also calls this hook with no request for stdio sessions.
34
+ const origin = request?.headers.origin;
35
+ // Check requests as well as CORS headers: unreadable responses alone do
36
+ // not prevent side effects. Empty, opaque and multiple origins are denied.
37
+ if (origin !== undefined && (typeof origin !== 'string' || !allowedOrigins.has(origin))) {
38
+ throw new Response('Browser origin is not allowed', {status: 403});
39
+ }
40
+ return {};
41
+ },
42
+ };
43
+ }
@@ -11,6 +11,20 @@ let sdkStarted = false;
11
11
  let shutdownRegistered = false;
12
12
  let sdk: {start(): void; shutdown(): Promise<void>} | undefined;
13
13
 
14
+ /** Resolve trace-specific configuration before the general OTLP setting. */
15
+ export function getTraceExportProtocol(): 'http/json' | 'grpc' {
16
+ const protocol =
17
+ process.env.OTEL_EXPORTER_OTLP_TRACES_PROTOCOL?.trim() ||
18
+ process.env.OTEL_EXPORTER_OTLP_PROTOCOL?.trim() ||
19
+ 'http/json';
20
+ if (protocol !== 'http/json' && protocol !== 'grpc') {
21
+ throw new Error(
22
+ 'Unsupported OTLP trace protocol. Use http/json or grpc in OTEL_EXPORTER_OTLP_TRACES_PROTOCOL or OTEL_EXPORTER_OTLP_PROTOCOL.',
23
+ );
24
+ }
25
+ return protocol;
26
+ }
27
+
14
28
  /**
15
29
  * Initializes the OpenTelemetry SDK if telemetry is enabled and not already started.
16
30
  * This function is idempotent and safe to call multiple times; the SDK will only
@@ -22,9 +36,12 @@ export async function initializeOpenTelemetry(): Promise<void> {
22
36
  return;
23
37
  }
24
38
 
39
+ const protocol = getTraceExportProtocol();
25
40
  const [{NodeSDK}, {OTLPTraceExporter}] = await Promise.all([
26
41
  import('@opentelemetry/sdk-node'),
27
- import('@opentelemetry/exporter-trace-otlp-http'),
42
+ protocol === 'grpc'
43
+ ? import('@opentelemetry/exporter-trace-otlp-grpc')
44
+ : import('@opentelemetry/exporter-trace-otlp-http'),
28
45
  ]);
29
46
 
30
47
  const nodeSdk = new NodeSDK({
@@ -1,5 +1,6 @@
1
1
  import path from 'node:path';
2
2
 
3
+ import {NativeSimctl} from '@appium/coresim';
3
4
  import {fs, net, plist, zip} from '@appium/support';
4
5
  /**
5
6
  * Single-call tool to prepare an iOS simulator for Appium testing.
@@ -7,7 +8,6 @@ import {fs, net, plist, zip} from '@appium/support';
7
8
  * Each step checks preconditions and skips if already satisfied.
8
9
  */
9
10
  import type {ContentResult, FastMCP} from 'fastmcp';
10
- import {Simctl} from 'node-simctl';
11
11
  import {exec} from 'teen_process';
12
12
  import {z} from 'zod';
13
13
 
@@ -115,28 +115,28 @@ async function getLatestWDAVersionFromCache(): Promise<string | null> {
115
115
  }
116
116
 
117
117
  async function getSimulatorArchitecture(simulatorUdid: string): Promise<string[]> {
118
- const {stdout} = await exec('xcrun', ['simctl', 'getenv', simulatorUdid, 'SIMULATOR_ARCHS']);
119
- const archs = stdout.trim().split(/\s+/);
118
+ const value = await new NativeSimctl().getEnv(simulatorUdid, 'SIMULATOR_ARCHS');
119
+ const archs = value.trim().split(/\s+/).filter(Boolean);
120
+ if (archs.length === 0) {
121
+ throw new Error(`No architectures reported for simulator ${simulatorUdid}`);
122
+ }
120
123
  return archs;
121
124
  }
122
125
 
123
126
  async function installAppOnSimulator(appPath: string, simulatorUdid: string): Promise<void> {
124
- await exec('xcrun', ['simctl', 'install', simulatorUdid, appPath]);
127
+ const simulator = new NativeSimctl();
128
+ await simulator.installApp(simulatorUdid, appPath);
125
129
  }
126
130
 
127
131
  async function launchAppOnSimulator(bundleId: string, simulatorUdid: string, wdaPort: number): Promise<void> {
128
- // simctl forwards env vars prefixed with SIMCTL_CHILD_ to the launched app.
129
- // WDA reads USE_PORT to choose which local port to listen on inside the
130
- // simulator, so each simulator's WDA can run on its own port instead of all
131
- // colliding on the default 8100.
132
- await exec('xcrun', ['simctl', 'launch', simulatorUdid, bundleId], {
133
- env: {...process.env, SIMCTL_CHILD_USE_PORT: String(wdaPort)},
134
- });
132
+ const simulator = new NativeSimctl();
133
+ await simulator.launchApp(simulatorUdid, bundleId, {environment: {USE_PORT: String(wdaPort)}});
135
134
  }
136
135
 
137
136
  async function terminateAppOnSimulator(bundleId: string, simulatorUdid: string): Promise<void> {
138
137
  try {
139
- await exec('xcrun', ['simctl', 'terminate', simulatorUdid, bundleId]);
138
+ const simulator = new NativeSimctl();
139
+ await simulator.terminateApp(simulatorUdid, bundleId);
140
140
  } catch {
141
141
  // Nothing running to terminate — ignore.
142
142
  }
@@ -172,33 +172,16 @@ async function getAppBundleId(appPath: string): Promise<string> {
172
172
  return manifest.CFBundleIdentifier;
173
173
  }
174
174
 
175
- async function getWDAState(simulatorUdid: string): Promise<WDAState> {
176
- let installed = false;
177
-
178
- // Check if installed via simctl listapps
179
- try {
180
- const {stdout} = await exec('xcrun', ['simctl', 'listapps', simulatorUdid, '--json']);
181
- const data = JSON.parse(stdout);
182
-
183
- for (const [bundleId, appInfo] of Object.entries(data)) {
184
- if (bundleId.includes('WebDriverAgentRunner') || (appInfo as any)?.CFBundleName?.includes('WebDriverAgent')) {
185
- installed = true;
186
- break;
187
- }
188
- }
189
- } catch {
190
- return {installed: false, running: false};
191
- }
192
-
175
+ async function getWDAState(simulatorUdid: string, bundleId: string): Promise<WDAState> {
176
+ const simulator = new NativeSimctl();
177
+ const installed = await simulator.isAppInstalled(simulatorUdid, bundleId);
193
178
  if (!installed) {
194
179
  return {installed: false, running: false};
195
180
  }
196
181
 
197
- // Check if actually running via launchctl inside the simulator
198
182
  try {
199
- const {stdout} = await exec('xcrun', ['simctl', 'spawn', simulatorUdid, 'launchctl', 'list']);
200
- const running = stdout.includes('WebDriverAgentRunner');
201
- return {installed: true, running};
183
+ const processes = await simulator.listProcesses(simulatorUdid);
184
+ return {installed: true, running: processes.some(({name}) => name === bundleId)};
202
185
  } catch {
203
186
  return {installed: true, running: false};
204
187
  }
@@ -303,8 +286,8 @@ async function resolveWdaAppPath(
303
286
 
304
287
  async function installWdaStep(result: PrepareResult, udid: string, wdaAppPath: string): Promise<void> {
305
288
  try {
306
- const wdaState = await getWDAState(udid);
307
289
  const bundleId = await getAppBundleId(wdaAppPath);
290
+ const wdaState = await getWDAState(udid, bundleId);
308
291
 
309
292
  // Install if not already installed.
310
293
  if (!wdaState.installed) {
@@ -391,10 +374,9 @@ async function prepareSimulator(
391
374
  };
392
375
  } else {
393
376
  log.info(`Booting simulator ${simulator.name} (${udid})...`);
394
- const simctl = new Simctl();
395
- simctl.udid = udid;
396
- await simctl.bootDevice();
397
- await simctl.startBootMonitor({timeout: 120000});
377
+ const device = new NativeSimctl();
378
+ await device.bootDevice(udid);
379
+ await device.waitForBoot(udid, {timeoutMs: 120000});
398
380
  result.boot = {
399
381
  status: 'completed',
400
382
  detail: `${simulator.name} booted successfully`,
@@ -940,7 +940,7 @@ export function createPageSourceInspectorUI(pageSource: string): string {
940
940
  background: #1e1e1e;
941
941
  color: #d4d4d4;
942
942
  padding: 0;
943
- overflow: hidden;
943
+ overflow: auto;
944
944
  }
945
945
  summary {
946
946
  padding: 12px 16px;
@@ -987,7 +987,9 @@ export function createPageSourceInspectorUI(pageSource: string): string {
987
987
  color: #999;
988
988
  }
989
989
  .viewer {
990
- max-height: 320px;
990
+ height: 320px;
991
+ min-height: 160px;
992
+ resize: vertical;
991
993
  overflow: auto;
992
994
  padding: 16px;
993
995
  }
@@ -1036,7 +1038,7 @@ export function createPageSourceInspectorUI(pageSource: string): string {
1036
1038
  <button class="btn" onclick="generateLocators()">Generate Locators</button>
1037
1039
  </div>
1038
1040
  </div>
1039
- <div class="viewer">
1041
+ <div class="viewer" title="Drag the bottom-right corner to resize vertically">
1040
1042
  <pre class="xml-content" id="xmlContent">${escapedSource}</pre>
1041
1043
  </div>
1042
1044
  </details>
@@ -1049,13 +1051,46 @@ export function createPageSourceInspectorUI(pageSource: string): string {
1049
1051
  }
1050
1052
 
1051
1053
  function formatXML() {
1052
- const content = document.getElementById('xmlContent').textContent;
1053
1054
  try {
1054
1055
  const parser = new DOMParser();
1055
- const xmlDoc = parser.parseFromString(content, 'text/xml');
1056
+ const xmlDoc = parser.parseFromString(originalSource, 'text/xml');
1057
+ if (!xmlDoc.documentElement || xmlDoc.getElementsByTagName('parsererror').length) {
1058
+ throw new Error('Invalid XML');
1059
+ }
1060
+
1061
+ function indentElement(element, depth) {
1062
+ // Do not introduce whitespace into mixed content or preserved subtrees.
1063
+ if (element.getAttribute('xml:space') === 'preserve') return;
1064
+ const children = Array.from(element.childNodes);
1065
+ if (children.some(child =>
1066
+ child.nodeType === 4 || (child.nodeType === 3 && child.nodeValue.trim())
1067
+ )) return;
1068
+ if (!children.some(child => child.nodeType === 1)) return;
1069
+
1070
+ for (const child of children) {
1071
+ if (child.nodeType === 3) {
1072
+ element.removeChild(child);
1073
+ continue;
1074
+ }
1075
+ if (child.nodeType === 1) indentElement(child, depth + 1);
1076
+ element.insertBefore(xmlDoc.createTextNode('\\n' + ' '.repeat(depth + 1)), child);
1077
+ }
1078
+ element.appendChild(xmlDoc.createTextNode('\\n' + ' '.repeat(depth)));
1079
+ }
1080
+
1081
+ indentElement(xmlDoc.documentElement, 0);
1056
1082
  const serializer = new XMLSerializer();
1057
- const formatted = serializer.serializeToString(xmlDoc);
1058
- document.getElementById('xmlContent').textContent = formatted;
1083
+ let formatted = Array.from(xmlDoc.childNodes)
1084
+ .filter(node => node.nodeType !== 3)
1085
+ .map(node => serializer.serializeToString(node))
1086
+ .join('\\n');
1087
+ // Browser DOMParser does not retain the XML declaration.
1088
+ const declaration = originalSource.match(/^\\s*(<\\?xml\\s[^?]*\\?>)/);
1089
+ if (declaration && !formatted.startsWith('<?xml ')) {
1090
+ formatted = declaration[1] + '\\n' + formatted;
1091
+ }
1092
+ displayedSource = formatted;
1093
+ renderSource(document.getElementById('searchBox').value);
1059
1094
  } catch (e) {
1060
1095
  alert('Failed to format XML');
1061
1096
  }
@@ -1073,6 +1108,7 @@ export function createPageSourceInspectorUI(pageSource: string): string {
1073
1108
 
1074
1109
  const xmlContent = document.getElementById('xmlContent');
1075
1110
  const originalSource = xmlContent.textContent;
1111
+ let displayedSource = originalSource;
1076
1112
 
1077
1113
  function appendTextWithHighlights(container, text, searchTerm) {
1078
1114
  const searchLower = searchTerm.toLowerCase();
@@ -1104,11 +1140,11 @@ export function createPageSourceInspectorUI(pageSource: string): string {
1104
1140
  function renderSource(searchTerm = '') {
1105
1141
  xmlContent.textContent = '';
1106
1142
  if (!searchTerm) {
1107
- xmlContent.textContent = originalSource;
1143
+ xmlContent.textContent = displayedSource;
1108
1144
  return;
1109
1145
  }
1110
1146
 
1111
- appendTextWithHighlights(xmlContent, originalSource, searchTerm);
1147
+ appendTextWithHighlights(xmlContent, displayedSource, searchTerm);
1112
1148
  }
1113
1149
 
1114
1150
  // Search functionality
@@ -13,102 +13,72 @@ export function createPageSourceInspectorAppUI(): string {
13
13
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
14
14
  <title>Page Source Inspector</title>
15
15
  <style>
16
+ :root { color-scheme: dark; --bg: #17191d; --panel: #202329; --line: #343941; --text: #e5e8ee; --muted: #a3acba; --accent: #91baff; }
16
17
  * { box-sizing: border-box; }
17
- body {
18
- margin: 0;
19
- overflow: hidden;
20
- background: #1e1e1e;
21
- color: #d4d4d4;
22
- font-family: Monaco, Menlo, "Courier New", monospace;
23
- }
24
- summary {
25
- padding: 12px 16px;
26
- background: #2d2d2d;
27
- cursor: pointer;
28
- font-size: 14px;
29
- }
30
- summary .info { margin-left: 8px; }
31
- .toolbar {
32
- display: flex;
33
- flex-wrap: wrap;
34
- align-items: center;
35
- justify-content: space-between;
36
- gap: 12px;
37
- padding: 12px 16px;
38
- border-bottom: 1px solid #3e3e3e;
39
- background: #2d2d2d;
40
- }
41
- .toolbar-right {
42
- flex-wrap: wrap;
43
- display: flex;
44
- align-items: center;
45
- gap: 8px;
46
- }
47
- .title { font-size: 14px; font-weight: 500; }
48
- .info { color: #999; font-size: 12px; }
49
- .btn {
50
- padding: 6px 12px;
51
- border: 0;
52
- border-radius: 4px;
53
- background: #007aff;
54
- color: #fff;
55
- cursor: pointer;
56
- font: 13px -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
57
- }
58
- .btn:hover { background: #0056b3; }
59
- .btn-secondary { background: #444; }
60
- .btn-secondary:hover { background: #555; }
61
- .search-box {
62
- width: 200px;
63
- padding: 6px 12px;
64
- border: 1px solid #555;
65
- border-radius: 4px;
66
- outline: none;
67
- background: #3e3e3e;
68
- color: #d4d4d4;
69
- font-size: 13px;
70
- }
71
- .search-box:focus { border-color: #007aff; }
72
- .viewer {
73
- max-height: 320px;
74
- overflow: auto;
75
- padding: 16px;
76
- }
77
- .xml-content {
78
- margin: 0;
79
- white-space: pre;
80
- color: #d4d4d4;
81
- font-size: 13px;
82
- line-height: 1.6;
83
- }
84
- mark {
85
- border-radius: 2px;
86
- background: #ffd54f;
87
- color: #1e1e1e;
88
- }
89
- .empty {
90
- color: #999;
91
- font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
92
- }
18
+ [hidden] { display: none !important; }
19
+ body { margin: 0; overflow: auto; background: var(--bg); color: var(--text); font: 13px/1.5 -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; }
20
+ summary { cursor: pointer; padding: 16px 20px; }
21
+ summary::marker { color: var(--muted); }
22
+ .title { font-size: 15px; font-weight: 600; letter-spacing: -.2px; }
23
+ .info { color: var(--muted); font-size: 12px; margin-left: 10px; }
24
+ .toolbar, .section-header { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 12px; }
25
+ .toolbar { padding: 12px 20px; border-block: 1px solid var(--line); background: var(--panel); }
26
+ .toolbar-right { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }
27
+ .btn { padding: 8px 12px; border: 1px solid transparent; border-radius: 7px; background: #a7c7ff; color: #14243d; cursor: pointer; font: inherit; font-weight: 600; }
28
+ .btn:hover { background: #c2d8ff; }
29
+ .btn:disabled { opacity: .55; cursor: wait; }
30
+ .btn-secondary { background: transparent; border-color: #48505d; color: var(--text); }
31
+ .btn-secondary:hover { background: #303641; }
32
+ .btn:focus-visible, summary:focus-visible, input:focus-visible { outline: 2px solid var(--accent); outline-offset: 3px; }
33
+ .search-box { width: min(240px, 100%); min-width: 0; padding: 8px 12px; border: 1px solid #48505d; border-radius: 7px; background: var(--bg); color: var(--text); font: inherit; }
34
+ .search-box::placeholder { color: var(--muted); }
35
+ .viewer { height: 320px; min-height: 160px; resize: vertical; overflow: auto; padding: 20px; }
36
+ .xml-content, .selector { margin: 0; font: 12px/1.75 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
37
+ .xml-content { white-space: pre; color: #c5d3e7; }
38
+ mark { border-radius: 3px; background: #eac77a; color: #252019; }
39
+ .empty, .hint { color: var(--muted); }
40
+ .empty { font-family: inherit; }
41
+ .hint { margin: 6px 0 0; font-size: 12px; }
42
+ .locators { border-top: 1px solid var(--line); padding: 20px; }
43
+ h2 { margin: 0; font-size: 14px; font-weight: 600; }
44
+ #locatorStatus { margin: 16px 0 10px; color: var(--accent); font-size: 12px; }
45
+ .locator-results { max-height: 480px; overflow: auto; }
46
+ .locator-card { margin: 8px 0; border: 1px solid var(--line); border-radius: 8px; background: var(--panel); overflow: hidden; }
47
+ .locator-card summary { padding: 12px 14px; overflow-wrap: anywhere; }
48
+ .element-type { margin-left: 8px; color: var(--muted); font-size: 11px; }
49
+ .locator-row { margin: 0 14px 14px; }
50
+ .strategy { display: block; margin-bottom: 5px; color: var(--muted); font-size: 11px; font-weight: 600; }
51
+ .selector { padding: 10px 12px; background: var(--bg); border-radius: 5px; white-space: pre-wrap; overflow-wrap: anywhere; user-select: all; }
52
+ @media (max-width: 420px) { .toolbar, .locators { padding: 12px; } .toolbar-right { width: 100%; } .search-box { width: 100%; } .info { display: block; margin: 4px 0 0 18px; } }
93
53
  </style>
94
54
  </head>
95
55
  <body>
96
- <details>
56
+ <details open>
97
57
  <summary>
98
- <span class="title">📄 Page Source Inspector</span>
58
+ <span class="title">Page Source Inspector</span>
99
59
  <span class="info" id="sourceInfo">Waiting for page source…</span>
100
60
  </summary>
101
61
  <div class="toolbar">
62
+ <input type="search" class="search-box" id="searchBox" placeholder="Find in XML…" aria-label="Find in XML" title="Highlight matching text in the XML">
102
63
  <div class="toolbar-right">
103
- <input type="text" class="search-box" id="searchBox" placeholder="Search…">
104
- <button class="btn btn-secondary" id="copyButton">Copy</button>
105
- <button class="btn btn-secondary" id="formatButton">Format</button>
106
- <button class="btn" id="generateButton">Generate Locators</button>
64
+ <button class="btn btn-secondary" id="formatButton">Format XML</button>
65
+ <button class="btn btn-secondary" id="copyButton">Copy XML</button>
107
66
  </div>
108
67
  </div>
109
- <div class="viewer">
68
+ <div class="viewer" title="Drag the bottom-right corner to resize vertically">
110
69
  <pre class="xml-content empty" id="xmlContent">Waiting for page source…</pre>
111
70
  </div>
71
+ <section class="locators" aria-labelledby="locatorsHeading">
72
+ <div class="section-header">
73
+ <h2 id="locatorsHeading">Locator candidates</h2>
74
+ <button class="btn" id="generateButton">Generate from current page</button>
75
+ </div>
76
+ <p class="hint">Fetches fresh XML from the device and generates candidates for supported element types, including hidden elements. XML search only highlights text above.</p>
77
+ <div id="locatorResults" hidden>
78
+ <p id="locatorStatus" role="status" aria-live="polite"></p>
79
+ <div class="locator-results" id="locatorOutput"></div>
80
+ </div>
81
+ </section>
112
82
  </details>
113
83
  <script>
114
84
  (() => {
@@ -116,6 +86,10 @@ export function createPageSourceInspectorAppUI(): string {
116
86
  const xmlContent = document.getElementById('xmlContent');
117
87
  const sourceInfo = document.getElementById('sourceInfo');
118
88
  const searchBox = document.getElementById('searchBox');
89
+ const generateButton = document.getElementById('generateButton');
90
+ const locatorResults = document.getElementById('locatorResults');
91
+ const locatorStatus = document.getElementById('locatorStatus');
92
+ const locatorOutput = document.getElementById('locatorOutput');
119
93
  let source = '';
120
94
  let savedFile;
121
95
  let nextRequestId = 1;
@@ -204,10 +178,41 @@ export function createPageSourceInspectorAppUI(): string {
204
178
  try {
205
179
  const parser = new DOMParser();
206
180
  const documentNode = parser.parseFromString(source, 'text/xml');
207
- if (documentNode.querySelector('parsererror')) {
181
+ if (!documentNode.documentElement || documentNode.getElementsByTagName('parsererror').length) {
208
182
  throw new Error('Invalid XML');
209
183
  }
210
- source = new XMLSerializer().serializeToString(documentNode);
184
+
185
+ function indentElement(element, depth) {
186
+ if (element.getAttribute('xml:space') === 'preserve') return;
187
+ const children = Array.from(element.childNodes);
188
+ const hasMixedContent = children.some((child) =>
189
+ child.nodeType === 4 || (child.nodeType === 3 && (child.nodeValue || '').trim()),
190
+ );
191
+ if (hasMixedContent || !children.some((child) => child.nodeType === 1)) return;
192
+
193
+ for (const child of children) {
194
+ if (child.nodeType === 3) {
195
+ element.removeChild(child);
196
+ continue;
197
+ }
198
+ if (child.nodeType === 1) indentElement(child, depth + 1);
199
+ element.insertBefore(documentNode.createTextNode('\\n' + ' '.repeat(depth + 1)), child);
200
+ }
201
+ element.appendChild(documentNode.createTextNode('\\n' + ' '.repeat(depth)));
202
+ }
203
+
204
+ indentElement(documentNode.documentElement, 0);
205
+ const serializer = new XMLSerializer();
206
+ let formattedSource = Array.from(documentNode.childNodes)
207
+ .filter((node) => node.nodeType !== 3)
208
+ .map((node) => serializer.serializeToString(node))
209
+ .join('\\n');
210
+ const declaration = source.match(/^\\s*(<\\?xml\\s[^?]*\\?>)/);
211
+ if (declaration && !formattedSource.startsWith('<?xml ')) {
212
+ formattedSource = declaration[1] + '\\n' + formattedSource;
213
+ }
214
+
215
+ source = formattedSource;
211
216
  renderSource();
212
217
  } catch {
213
218
  window.alert('Failed to format XML');
@@ -223,11 +228,67 @@ export function createPageSourceInspectorAppUI(): string {
223
228
  }
224
229
  }
225
230
 
231
+ function renderLocators(elements) {
232
+ locatorOutput.textContent = '';
233
+ elements.forEach((element, index) => {
234
+ const card = document.createElement('details');
235
+ card.className = 'locator-card';
236
+ card.open = index === 0;
237
+ const heading = document.createElement('summary');
238
+ const label = element.text || element.contentDesc || element.resourceId;
239
+ heading.textContent = (index + 1) + '. ' + (label || element.tagName || 'Element');
240
+ if (label && element.tagName) {
241
+ const type = document.createElement('span');
242
+ type.className = 'element-type';
243
+ type.textContent = element.tagName;
244
+ heading.appendChild(type);
245
+ }
246
+ card.appendChild(heading);
247
+ const entries = Object.entries(element.locators || {}).filter(([, value]) => typeof value === 'string');
248
+ entries.forEach(([strategy, selector]) => {
249
+ const row = document.createElement('div');
250
+ row.className = 'locator-row';
251
+ const name = document.createElement('span');
252
+ name.className = 'strategy';
253
+ name.textContent = strategy;
254
+ const code = document.createElement('pre');
255
+ code.className = 'selector';
256
+ code.textContent = selector;
257
+ row.appendChild(name);
258
+ row.appendChild(code);
259
+ card.appendChild(row);
260
+ });
261
+ if (!entries.length) {
262
+ const empty = document.createElement('p');
263
+ empty.className = 'locator-row hint';
264
+ empty.textContent = 'No candidate selectors for this element.';
265
+ card.appendChild(empty);
266
+ }
267
+ locatorOutput.appendChild(card);
268
+ });
269
+ }
270
+
226
271
  async function generateLocators() {
272
+ if (generateButton.disabled) return;
273
+ generateButton.disabled = true;
274
+ locatorResults.hidden = false;
275
+ locatorStatus.textContent = 'Fetching XML and generating candidates…';
276
+ locatorOutput.textContent = '';
227
277
  try {
228
- await sendRequest('tools/call', {name: 'generate_locators', arguments: {}});
229
- } catch {
230
- window.alert('Failed to generate locators');
278
+ const result = await sendRequest('tools/call', {name: 'generate_locators', arguments: {}});
279
+ const text = (result?.content || []).filter((item) => item.type === 'text').map((item) => item.text).join('\\n');
280
+ if (result?.isError) throw new Error(text || 'Tool returned an error');
281
+ const data = JSON.parse(text);
282
+ if (!Array.isArray(data.interactableElements)) throw new Error('No locator data returned');
283
+ const elements = data.interactableElements;
284
+ locatorStatus.textContent = elements.length
285
+ ? 'Candidates generated for ' + elements.length + ' elements from freshly fetched XML.'
286
+ : 'No supported elements found in the fetched XML.';
287
+ renderLocators(elements);
288
+ } catch (error) {
289
+ locatorStatus.textContent = 'Failed to generate locators: ' + error.message;
290
+ } finally {
291
+ generateButton.disabled = false;
231
292
  }
232
293
  }
233
294
 
@@ -262,7 +323,21 @@ export function createPageSourceInspectorAppUI(): string {
262
323
  appInfo: {name: 'Appium Page Source Inspector', version: '1.0.0'},
263
324
  appCapabilities: {availableDisplayModes: ['inline', 'fullscreen']},
264
325
  })
265
- .then(() => sendNotification('ui/notifications/initialized', {}))
326
+ .then(() => {
327
+ sendNotification('ui/notifications/initialized', {});
328
+ // Let flexible MCP App hosts follow resizing and details expansion.
329
+ if (typeof ResizeObserver !== 'undefined') {
330
+ let previousHeight;
331
+ const observer = new ResizeObserver(() => {
332
+ const height = Math.ceil(document.body.getBoundingClientRect().height);
333
+ if (height !== previousHeight) {
334
+ previousHeight = height;
335
+ sendNotification('ui/notifications/size-changed', {height});
336
+ }
337
+ });
338
+ observer.observe(document.body);
339
+ }
340
+ })
266
341
  .catch(() => {
267
342
  sourceInfo.textContent = 'Unable to initialize inspector';
268
343
  });