-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmcp-server.js
More file actions
402 lines (374 loc) · 12.6 KB
/
mcp-server.js
File metadata and controls
402 lines (374 loc) · 12.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
#!/usr/bin/env node
/**
* mcp-server.js — MCP server for baremobile.
*
* Raw JSON-RPC 2.0 over stdio. No SDK dependency.
* 11 tools: snapshot, tap, type, press, scroll, swipe, long_press, launch, screenshot, back, find_by_text.
*
* Dual-platform: Android (default) and iOS. Each platform gets its own
* lazy-created page. Pass platform: "ios" to target iPhone.
* Action tools return 'ok' — agent calls snapshot explicitly to observe.
*/
import { mkdirSync, writeFileSync, readFileSync } from 'node:fs';
import { join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { checkIosCert } from './src/ios-cert.js';
const __dirname = import.meta.dirname;
const PKG_VERSION = JSON.parse(readFileSync(join(__dirname, 'package.json'), 'utf8')).version;
const MAX_CHARS_DEFAULT = 30000;
const OUTPUT_DIR = join(process.cwd(), '.baremobile');
function saveSnapshot(text) {
mkdirSync(OUTPUT_DIR, { recursive: true });
const ts = new Date().toISOString().replace(/[:.]/g, '-');
const file = join(OUTPUT_DIR, `screen-${ts}.yml`);
writeFileSync(file, text);
return file;
}
let _pages = { android: null, ios: null };
let _iosCertWarning = null;
async function getPage(platform = 'android') {
if (!_pages[platform]) {
if (platform === 'ios') {
_iosCertWarning = checkIosCert();
const mod = await import('./src/ios.js');
_pages[platform] = await mod.connect();
} else {
const mod = await import('./src/index.js');
_pages[platform] = await mod.connect();
}
}
return _pages[platform];
}
const PLATFORM_PROP = {
platform: { type: 'string', enum: ['android', 'ios'], description: 'Target platform (default: android)' },
};
const TOOLS = [
{
name: 'snapshot',
description: 'Get the current screen accessibility snapshot. Returns a YAML-like tree with [ref=N] markers on interactive elements.',
inputSchema: {
type: 'object',
properties: {
maxChars: { type: 'number', description: 'Max chars to return inline. Larger snapshots are saved to .baremobile/ and a file path is returned instead. Default: 30000.' },
...PLATFORM_PROP,
},
},
},
{
name: 'tap',
description: 'Tap an element by its ref from the snapshot. Returns ok — call snapshot to observe.',
inputSchema: {
type: 'object',
properties: {
ref: { type: 'string', description: 'Element ref from snapshot (e.g. "8")' },
...PLATFORM_PROP,
},
required: ['ref'],
},
},
{
name: 'type',
description: 'Type text into an element by its ref. Taps to focus first (skips if already focused). Returns ok — call snapshot to observe.',
inputSchema: {
type: 'object',
properties: {
ref: { type: 'string', description: 'Element ref from snapshot' },
text: { type: 'string', description: 'Text to type' },
clear: { type: 'boolean', description: 'Clear existing content first (default: false)' },
...PLATFORM_PROP,
},
required: ['ref', 'text'],
},
},
{
name: 'press',
description: 'Press a key: home, back, enter, tab, delete, volume_up, volume_down, power, etc. Returns ok.',
inputSchema: {
type: 'object',
properties: {
key: { type: 'string', description: 'Key name (e.g. "home", "back", "enter")' },
...PLATFORM_PROP,
},
required: ['key'],
},
},
{
name: 'scroll',
description: 'Scroll an element or the screen. Direction: up, down, left, right. Returns ok.',
inputSchema: {
type: 'object',
properties: {
ref: { type: 'string', description: 'Element ref to scroll (e.g. "3")' },
direction: { type: 'string', enum: ['up', 'down', 'left', 'right'], description: 'Scroll direction' },
...PLATFORM_PROP,
},
required: ['ref', 'direction'],
},
},
{
name: 'swipe',
description: 'Swipe between two screen coordinates. Returns ok.',
inputSchema: {
type: 'object',
properties: {
x1: { type: 'number', description: 'Start X coordinate' },
y1: { type: 'number', description: 'Start Y coordinate' },
x2: { type: 'number', description: 'End X coordinate' },
y2: { type: 'number', description: 'End Y coordinate' },
duration: { type: 'number', description: 'Swipe duration in ms (default: 300)' },
...PLATFORM_PROP,
},
required: ['x1', 'y1', 'x2', 'y2'],
},
},
{
name: 'long_press',
description: 'Long-press an element by its ref from the snapshot. Returns ok — call snapshot to observe.',
inputSchema: {
type: 'object',
properties: {
ref: { type: 'string', description: 'Element ref from snapshot' },
...PLATFORM_PROP,
},
required: ['ref'],
},
},
{
name: 'launch',
description: 'Launch an app by identifier. Returns ok — call snapshot to observe.',
inputSchema: {
type: 'object',
properties: {
pkg: { type: 'string', description: 'App identifier (e.g. "com.android.settings" or "com.apple.Preferences")' },
...PLATFORM_PROP,
},
required: ['pkg'],
},
},
{
name: 'screenshot',
description: 'Take a screenshot. Returns base64-encoded PNG image.',
inputSchema: {
type: 'object',
properties: { ...PLATFORM_PROP },
},
},
{
name: 'back',
description: 'Navigate back. Returns ok.',
inputSchema: {
type: 'object',
properties: { ...PLATFORM_PROP },
},
},
{
name: 'find_by_text',
description: 'Find an interactive element by text match. Returns the ref number or null if not found. Requires a prior snapshot.',
inputSchema: {
type: 'object',
properties: {
text: { type: 'string', description: 'Text to search for (substring match)' },
...PLATFORM_PROP,
},
required: ['text'],
},
},
];
async function handleToolCall(name, args) {
const platform = args.platform || 'android';
switch (name) {
case 'snapshot': {
const page = await getPage(platform);
let text = await page.snapshot();
// Prepend cert warning on first iOS snapshot
if (platform === 'ios' && _iosCertWarning) {
text = `⚠️ ${_iosCertWarning}\n\n${text}`;
_iosCertWarning = null;
}
const limit = args.maxChars ?? MAX_CHARS_DEFAULT;
if (text.length > limit) {
const file = saveSnapshot(text);
return `Snapshot (${text.length} chars) saved to ${file}`;
}
return text;
}
case 'tap': {
const page = await getPage(platform);
await page.tap(args.ref);
return 'ok';
}
case 'type': {
const page = await getPage(platform);
await page.type(args.ref, args.text, { clear: args.clear });
return 'ok';
}
case 'press': {
const page = await getPage(platform);
await page.press(args.key);
return 'ok';
}
case 'scroll': {
const page = await getPage(platform);
await page.scroll(args.ref, args.direction);
return 'ok';
}
case 'swipe': {
const page = await getPage(platform);
await page.swipe(args.x1, args.y1, args.x2, args.y2, args.duration);
return 'ok';
}
case 'long_press': {
const page = await getPage(platform);
await page.longPress(args.ref);
return 'ok';
}
case 'launch': {
const page = await getPage(platform);
await page.launch(args.pkg);
return 'ok';
}
case 'screenshot': {
const page = await getPage(platform);
const buf = await page.screenshot();
const b64 = buf.toString('base64');
return { _image: b64 };
}
case 'back': {
const page = await getPage(platform);
await page.back();
return 'ok';
}
case 'find_by_text': {
const page = await getPage(platform);
const ref = page.findByText(args.text);
return ref !== null ? String(ref) : 'null';
}
default:
throw new Error(`Unknown tool: ${name}`);
}
}
function jsonrpcResponse(id, result) {
return JSON.stringify({ jsonrpc: '2.0', id, result });
}
function jsonrpcError(id, code, message) {
return JSON.stringify({ jsonrpc: '2.0', id, error: { code, message } });
}
async function handleMessage(msg) {
const { id, method, params } = msg;
if (method === 'initialize') {
return jsonrpcResponse(id, {
protocolVersion: '2024-11-05',
capabilities: { tools: {} },
serverInfo: { name: 'baremobile', version: PKG_VERSION },
});
}
if (method === 'notifications/initialized') {
return null;
}
if (method === 'tools/list') {
return jsonrpcResponse(id, { tools: TOOLS });
}
if (method === 'tools/call') {
const { name, arguments: args } = params;
try {
let result;
try {
result = await handleToolCall(name, args || {});
} catch (err) {
// Auto-reconnect: if WDA/device connection died, clear cache and retry once
const msg = err?.message || '';
const isConnErr = err?.code === 'ECONNREFUSED' || err?.code === 'ECONNRESET'
|| msg.includes('fetch failed') || msg.includes('ECONNREFUSED')
|| msg.includes('ECONNRESET') || msg.includes('UND_ERR');
const platform = (args || {}).platform || 'android';
if (isConnErr && _pages[platform]) {
try { _pages[platform].close(); } catch { /* ignore */ }
_pages[platform] = null;
result = await handleToolCall(name, args || {});
} else {
throw err;
}
}
// Screenshot returns image content type
if (result && result._image) {
return jsonrpcResponse(id, {
content: [{ type: 'image', data: result._image, mimeType: 'image/png' }],
});
}
return jsonrpcResponse(id, {
content: [{ type: 'text', text: typeof result === 'string' ? result : JSON.stringify(result) }],
});
} catch (err) {
const msg = err?.message || '';
const isConnErr = err?.code === 'ECONNREFUSED' || err?.code === 'ECONNRESET'
|| msg.includes('fetch failed') || msg.includes('ECONNREFUSED');
const platform = (args || {}).platform || 'android';
// Tier 2: iOS auto-restart — reconnect failed, try restarting WDA tunnel
if (isConnErr && platform === 'ios') {
try {
const { restartWda } = await import('./src/setup.js');
await restartWda((m) => process.stderr.write(`[baremobile] ${m}\n`));
_pages[platform] = null;
const result = await handleToolCall(name, args || {});
if (result && result._image) {
return jsonrpcResponse(id, {
content: [{ type: 'image', data: result._image, mimeType: 'image/png' }],
});
}
return jsonrpcResponse(id, {
content: [{ type: 'text', text: typeof result === 'string' ? result : JSON.stringify(result) }],
});
} catch (restartErr) {
return jsonrpcResponse(id, {
content: [{ type: 'text', text: `WDA tunnel died and auto-restart failed: ${restartErr.message}. Reconnect USB and run \`npx baremobile setup\`.` }],
isError: true,
});
}
}
const hint = isConnErr
? ' WDA/ADB may be down. Reconnect USB and run `npx baremobile setup`.'
: '';
return jsonrpcResponse(id, {
content: [{ type: 'text', text: `Error: ${msg}${hint}` }],
isError: true,
});
}
}
return jsonrpcError(id, -32601, `Method not found: ${method}`);
}
// --- Stdio transport (only when run directly, not imported) ---
import { realpathSync } from 'node:fs';
const __filename = fileURLToPath(import.meta.url);
const isMain = process.argv[1] && realpathSync(resolve(process.argv[1])) === realpathSync(__filename);
if (isMain) {
let buffer = '';
process.stdin.setEncoding('utf8');
process.stdin.on('data', async (chunk) => {
buffer += chunk;
let newlineIdx;
while ((newlineIdx = buffer.indexOf('\n')) !== -1) {
const line = buffer.slice(0, newlineIdx).trim();
buffer = buffer.slice(newlineIdx + 1);
if (!line) continue;
try {
const msg = JSON.parse(line);
const response = await handleMessage(msg);
if (response) {
process.stdout.write(response + '\n');
}
} catch (err) {
process.stdout.write(jsonrpcError(null, -32700, `Parse error: ${err.message}`) + '\n');
}
}
});
process.on('SIGINT', async () => {
for (const p of Object.values(_pages)) if (p) p.close();
process.exit(0);
});
process.on('SIGTERM', async () => {
for (const p of Object.values(_pages)) if (p) p.close();
process.exit(0);
});
}
// Export for testing
export { TOOLS, handleMessage, handleToolCall };