offscreen-android 0.0.0-stage → 0.1.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.
@@ -0,0 +1,410 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * mcp-server.mjs — 把后台屏的 11 个工具暴露成 MCP server,让别的 agent 宿主能调。
4
+ *
5
+ * 为什么手写而不用 SDK:宿主里只装了 `@modelcontextprotocol/client` 和 `core`,
6
+ * **没有 server 端包**。而 MCP 的 stdio 传输本质上就是「stdin/stdout 上跑换行分隔的
7
+ * JSON-RPC 2.0」,一个 initialize + 一个 tools/list + 一个 tools/call 就够用了。
8
+ * 零依赖意味着不用改 package.json、不用担心 Node 版本、坏了自己能读。
9
+ *
10
+ * ## 用法(Claude Desktop / Cursor 等)
11
+ *
12
+ * ```json
13
+ * {
14
+ * "mcpServers": {
15
+ * "background-screen": {
16
+ * "command": "node",
17
+ * "args": ["/root/workspace/offscreen-android/screen/bin/mcp-server.mjs"]
18
+ * }
19
+ * }
20
+ * }
21
+ * ```
22
+ *
23
+ * ## 前置条件
24
+ *
25
+ * - adb 已连上(默认 127.0.0.1:5555,可用 ADB_TARGET 覆盖)
26
+ * - OCR 要 `pip install rapidocr-onnxruntime`,没装的话 vdisplay_text 会返回明确错误
27
+ *
28
+ * ## 和 DSH 插件的关系
29
+ *
30
+ * 这层不重复实现任何逻辑,只做协议转换:把 MCP 的 tools/call 转成对 tools.js
31
+ * 里同名函数的调用。所以工具行为和 DSH 里完全一致,不存在两套实现漂移。
32
+ */
33
+
34
+ import { createInterface } from 'node:readline';
35
+
36
+ // tools.js 里的执行体。注意:这些函数返回 `{ text }`,要转成 MCP 的 content 数组。
37
+ let T = null;
38
+ let SPECS = null;
39
+
40
+ async function loadTools() {
41
+ if (T) return;
42
+ T = await import('../src/tools.js');
43
+ SPECS = await import('../src/tool-spec.js');
44
+ }
45
+
46
+ /** tool-spec 里的 spec 函数名 → 执行体名 */
47
+ const EXEC_MAP = {
48
+ vdisplay_start: 'start',
49
+ vdisplay_stop: 'stop',
50
+ vdisplay_status: 'status',
51
+ vdisplay_launch: 'launch',
52
+ vdisplay_shot: 'shot',
53
+ vdisplay_text: 'text',
54
+ vdisplay_input: 'input',
55
+ vdisplay_stream: 'streamStart',
56
+ vdisplay_stream_stop: 'streamStop',
57
+ screen_shot_main: 'mainShot',
58
+ vdisplay_apps: 'apps',
59
+ screen_modes: 'modes',
60
+ };
61
+
62
+ /**
63
+ * 把 tool-spec.js 的 parameters 转成 MCP 的 inputSchema。
64
+ *
65
+ * 两者格式接近但不完全一样:
66
+ * tool-spec:{ type: 'integer', description: '...' }
67
+ * MCP: { type: 'integer', description: '...' } —— 一样
68
+ * 差异在于 required 字段:tool-spec 用 `required: true` 写在字段里,MCP 要顶层数组。
69
+ */
70
+ function toInputSchema(params) {
71
+ const properties = {};
72
+ const required = [];
73
+ for (const [k, v] of Object.entries(params || {})) {
74
+ const { required: req, ...rest } = v;
75
+ properties[k] = rest;
76
+ if (req) required.push(k);
77
+ }
78
+ const schema = { type: 'object', properties };
79
+ if (required.length) schema.required = required;
80
+ return schema;
81
+ }
82
+
83
+ /**
84
+ * MCP 下**不该暴露**的工具。
85
+ *
86
+ * vdisplay_stream / vdisplay_stream_stop:它们的消费者是 DSH Go 的「AI 画面」胶囊
87
+ * (原生插件去回环端口拉 MJPEG),别的宿主没有这个组件,暴露了只会让模型白调一次。
88
+ */
89
+ const HIDDEN = new Set(['vdisplay_stream', 'vdisplay_stream_stop']);
90
+
91
+ /** 收集所有工具定义 */
92
+ function listTools() {
93
+ const out = [];
94
+ for (const key of Object.keys(SPECS)) {
95
+ if (!key.endsWith('Spec') || typeof SPECS[key] !== 'function') continue;
96
+ let spec;
97
+ try { spec = SPECS[key](); } catch { continue; }
98
+ if (!spec?.name) continue;
99
+ if (HIDDEN.has(spec.name)) continue;
100
+ out.push({
101
+ name: spec.name,
102
+ description: String(spec.description || '').slice(0, 4000),
103
+ inputSchema: toInputSchema(spec.parameters),
104
+ });
105
+ }
106
+ return out;
107
+ }
108
+
109
+ /** 执行一个工具,返回 MCP 的 content 数组 */
110
+ /*
111
+ * **所有调用都走 daemon,不直接调 tools.js。**
112
+ *
113
+ * 为什么:tools.js 的每个函数都依赖 vd.js 里的模块级 state(displayId、sfId、
114
+ * scrcpy 的 socket)。这个进程是新起的,state 是空的 —— 直接调 tools.text()
115
+ * 只会得到「虚拟屏没在运行」,即使另一处已经起好了屏。实测第一次接 MCP 就是这么翻车的。
116
+ *
117
+ * daemon 才是持有状态的地方(dashboard bin/vdisplayd.mjs),它已经覆盖了
118
+ * start/stop/status/launch/shot/text/input/mainShot。MCP 只做协议转换。
119
+ */
120
+
121
+ /** 读 daemon 的端口(它会写一个 json 文件) */
122
+ async function daemonPort() {
123
+ const { readFile } = await import('node:fs/promises');
124
+ const { homedir } = await import('node:os');
125
+ const { join } = await import('node:path');
126
+ const home = process.env.DSH_HOME || join(homedir(), '.dsh');
127
+ const explicit = process.env.VD_DAEMON_FILE; // 允许显式指定,方便在 PC 上跑
128
+ if (explicit) { try { const j = JSON.parse(await readFile(explicit, 'utf8')); if (Number(j?.port) > 0) return j.port; } catch { /* 继续试默认路径 */ } }
129
+ // 实际路径是 <DSH_HOME>/plugin-screen/cli-daemon.json(实测),
130
+ // 之前写成了 dsh-go/vdisplay/ —— 找不到端口,MCP 就静默返回空。
131
+ const cands = [
132
+ join(home, 'plugin-screen', 'cli-daemon.json'),
133
+ join(home, 'dsh-go', 'vdisplay', 'cli-daemon.json'),
134
+ '/tmp/dsh-vd-daemon.json',
135
+ ];
136
+ for (const f of cands) {
137
+ try {
138
+ const j = JSON.parse(await readFile(f, 'utf8'));
139
+ if (Number(j?.port) > 0) return j.port;
140
+ } catch { /* 试下一个 */ }
141
+ }
142
+ return null;
143
+ }
144
+
145
+ /** 调 daemon 的 /cmd */
146
+ async function callDaemon(action, args) {
147
+ const port = await daemonPort();
148
+ if (!port) return { ok: false, hint: 'daemon 没在跑。先在设备上执行一次 `vdisplay start` 或 `vdisplay status` 把它拉起来。' };
149
+ try {
150
+ const fetch = globalThis.fetch;
151
+ const r = await fetch(`http://127.0.0.1:${port}/cmd`, {
152
+ method: 'POST',
153
+ headers: { 'content-type': 'application/json' },
154
+ body: JSON.stringify({ action, args: args || {} }),
155
+ signal: AbortSignal.timeout(120000),
156
+ });
157
+ const j = await r.json();
158
+ if (!j.ok) return { ok: false, hint: j.error || 'daemon 返回失败' };
159
+ return { ok: true, result: j.result };
160
+ } catch (e) {
161
+ return { ok: false, hint: `连 daemon 失败:${String(e?.message || e).slice(0, 200)}` };
162
+ }
163
+ }
164
+
165
+ /** MCP 工具名 → daemon action */
166
+ const ACTION_MAP = {
167
+ vdisplay_start: 'start',
168
+ vdisplay_stop: 'stop',
169
+ vdisplay_status: 'status',
170
+ vdisplay_launch: 'launch',
171
+ vdisplay_shot: 'shot',
172
+ vdisplay_text: 'text',
173
+ vdisplay_input: 'input',
174
+ screen_shot_main: 'mainShot',
175
+ vdisplay_apps: 'apps',
176
+ // 多屏池
177
+ screen_pool: 'poolInfo',
178
+ screen_new: 'poolCreate',
179
+ screen_use: 'poolUse',
180
+ screen_close: 'poolDestroy',
181
+ screen_check_app: 'checkApp',
182
+ // 租约
183
+ screen_claim_app: 'claimApp',
184
+ screen_release_app: 'releaseApp',
185
+ screen_leases: 'leasesList',
186
+ };
187
+
188
+ /**
189
+ * 把截图变成 MCP 的 image content。
190
+ *
191
+ * **这是 MCP 和 DSH 插件最大的区别**:DSH 那边工具返回的是本地路径,模型自己
192
+ * read_image 打开;但 MCP 客户端可能跑在另一台电脑上,手机 /tmp 下的路径对它
193
+ * 毫无意义。所以必须把字节读出来、base64 塞进 content。
194
+ *
195
+ * 两个坑:
196
+ * ① mime 要按 magic bytes 判,不能信路径后缀 —— vd.shot 可能返回 .png 而实际是 jpeg。
197
+ * ② 图上限制:超过 1.5MB 直接拒绝并建议改 width/region,别让一个巨型 base64
198
+ * 撑爆 JSON-RPC 帧(客户端多半会截断或崩)。
199
+ */
200
+ async function imageContent(path) {
201
+ if (!path) return null;
202
+ const { readFile, stat } = await import('node:fs/promises');
203
+ try {
204
+ const st = await stat(path);
205
+ if (st.size > 1.5 * 1024 * 1024) {
206
+ return {
207
+ type: 'text',
208
+ text: `图太大(${Math.round(st.size / 1024)}KB),MCP 传输会撑爆。请把 width 调小,或用 region 只截一块。路径:${path}`,
209
+ };
210
+ }
211
+ const b = await readFile(path);
212
+ // magic bytes 判 mime
213
+ let mime = 'image/jpeg';
214
+ if (b.length > 8 && b[0] === 0x89 && b[1] === 0x50 && b[2] === 0x4e && b[3] === 0x47) mime = 'image/png';
215
+ else if (b.length > 3 && b[0] === 0xff && b[1] === 0xd8) mime = 'image/jpeg';
216
+ else if (b.length > 12 && b.toString('ascii', 0, 4) === 'RIFF' && b.toString('ascii', 8, 12) === 'WEBP') mime = 'image/webp';
217
+ return { type: 'image', data: b.toString('base64'), mimeType: mime };
218
+ } catch {
219
+ return null;
220
+ }
221
+ }
222
+
223
+ async function callTool(name, args) {
224
+ // modes 是纯静态说明,不依赖状态
225
+ if (name === 'screen_modes') {
226
+ await loadTools();
227
+ const r = await T.modes();
228
+ return { content: [{ type: 'text', text: String(r?.text ?? r).slice(0, 20000) }] };
229
+ }
230
+
231
+ const action = ACTION_MAP[name];
232
+ if (!action) {
233
+ return {
234
+ content: [{ type: 'text', text: `这个 MCP server 没暴露「${name}」。推流(vdisplay_stream)依赖 DSH 插件进程内的状态,MCP 下不可用。` }],
235
+ isError: true,
236
+ };
237
+ }
238
+
239
+ const r = await callDaemon(action, args);
240
+ if (!r.ok) {
241
+ return { content: [{ type: 'text', text: r.hint }], isError: true };
242
+ }
243
+ // daemon 返回的是结构化对象;转成可读文本
244
+ const res = r.result;
245
+ let text;
246
+ if (res && typeof res === 'object') {
247
+ if (Array.isArray(res.packages)) {
248
+ // apps 的返回:{ok, count, packages[]}
249
+ text = `第三方 App 共 ${res.count} 个(用包名调 vdisplay_launch):\n`
250
+ + res.packages.map((p) => ` ${p}`).join('\n');
251
+ } else if (res.text) text = res.text;
252
+ else if (typeof res.ok === 'boolean' && res.ok === false) text = `失败:${res.hint || '未知原因'}`;
253
+ else if (Array.isArray(res.lines)) {
254
+ const W = res.imageWidth || 720; const H = res.imageHeight || 1600;
255
+ const pl = [`识别到 ${res.count} 行(${res.cached ? '缓存命中' : (res.elapsedMs + 'ms')})`];
256
+ for (const ln of res.lines) {
257
+ const nx = ((ln.x + ln.w / 2) / W).toFixed(3);
258
+ const ny = ((ln.y + ln.h / 2) / H).toFixed(3);
259
+ pl.push(` [${ln.conf}] ${ln.text} nx=${nx} ny=${ny}`);
260
+ }
261
+ text = pl.join('\n');
262
+ } else if (res.path) {
263
+ // **截图要真的把图给出去**,光给路径对远端客户端没用。
264
+ const img = await imageContent(res.path);
265
+ if (img && img.type === 'image') {
266
+ const note = res.unchanged
267
+ ? '(这张和上次画面完全一样 —— MCP 这边仍然重发,因为客户端可能没有上一张)'
268
+ : '';
269
+ return {
270
+ content: [
271
+ img,
272
+ { type: 'text', text: `图 ${res.imageWidth || '?'}px,屏 ${res.width}x${res.height}${note}` },
273
+ ],
274
+ };
275
+ }
276
+ text = (img && img.text) || (`图片路径:${res.path}`);
277
+ } else {
278
+ text = JSON.stringify(res, null, 2).slice(0, 20000);
279
+ }
280
+ } else {
281
+ text = String(res);
282
+ }
283
+ return { content: [{ type: 'text', text: String(text).slice(0, 100000) }] };
284
+ }
285
+
286
+ /* ---------------- JSON-RPC over stdio ---------------- */
287
+
288
+ function send(obj) {
289
+ process.stdout.write(`${JSON.stringify(obj)}\n`);
290
+ }
291
+
292
+ function sendError(id, code, message) {
293
+ send({ jsonrpc: '2.0', id, error: { code, message } });
294
+ }
295
+
296
+ const PROTOCOL_VERSION = '2024-11-05';
297
+
298
+ async function handle(msg) {
299
+ const { id, method, params } = msg;
300
+
301
+ // 通知(没有 id)不需要回复
302
+ const isNotification = id === undefined || id === null;
303
+
304
+ switch (method) {
305
+ case 'initialize':
306
+ await loadTools();
307
+ send({
308
+ jsonrpc: '2.0', id,
309
+ result: {
310
+ protocolVersion: PROTOCOL_VERSION,
311
+ capabilities: { tools: { listChanged: false } },
312
+ serverInfo: { name: 'background-screen', version: '0.1.0' },
313
+ instructions: [
314
+ '这是一台 Android 手机的「后台屏」:一块用户看不见的虚拟屏,AI 可以在上面跑任意 App。',
315
+ '',
316
+ '典型顺序:vdisplay_start → vdisplay_launch → vdisplay_text(读屏)→ vdisplay_input(点按)。',
317
+ '',
318
+ '省 token 的要点:',
319
+ ' · 读文字数字用 vdisplay_text —— 0 图片 token,带 nx/ny 坐标可直接点。',
320
+ ' · 看整体布局用 vdisplay_shot(width=420 约 230 token)。',
321
+ ' · 看不清某块用 region 只截那一块,比调大 width 更清晰也更便宜。',
322
+ ' · 看「在不在动、往哪动」用 frames=9,单帧结构上做不到。',
323
+ '',
324
+ '注意:九格拼图里的小字读不出来(26px 缩到 5px),不要把数值希望放在那上面。',
325
+ ].join('\n'),
326
+ },
327
+ });
328
+ return;
329
+
330
+ case 'notifications/initialized':
331
+ case 'notifications/cancelled':
332
+ return; // 通知,不回复
333
+
334
+ case 'ping':
335
+ send({ jsonrpc: '2.0', id, result: {} });
336
+ return;
337
+
338
+ case 'tools/list':
339
+ await loadTools();
340
+ send({ jsonrpc: '2.0', id, result: { tools: listTools() } });
341
+ return;
342
+
343
+ case 'tools/call': {
344
+ const name = params?.name;
345
+ const args = params?.arguments || {};
346
+ // 支持取消:MCP 允许客户端发 notifications/cancelled,这里最简实现是执行完再判
347
+ const result = await callTool(name, args);
348
+ send({ jsonrpc: '2.0', id, result });
349
+ return;
350
+ }
351
+
352
+ case 'resources/list':
353
+ send({ jsonrpc: '2.0', id, result: { resources: [] } });
354
+ return;
355
+
356
+ case 'prompts/list':
357
+ send({ jsonrpc: '2.0', id, result: { prompts: [] } });
358
+ return;
359
+
360
+ default:
361
+ if (!isNotification) sendError(id, -32601, `不支持的方法:${method}`);
362
+ }
363
+ }
364
+
365
+ async function main() {
366
+ const rl = createInterface({ input: process.stdin, crlfDelay: Infinity });
367
+
368
+ // **stdin 关了不能立刻 exit。**
369
+ // 实测踩过:用 printf 管道喂两条消息,第一条 initialize 同步返回了,
370
+ // 第二条 tools/call 要等 OCR 1.4 秒 —— 但管道一结束 stdin 就 EOF,
371
+ // 原来的 process.exit(0) 直接把还没跑完的请求杀掉了,客户端只看到一条回复。
372
+ // 现在记录在途请求数,全部跑完才退出。
373
+ let inflight = 0;
374
+ let stdinClosed = false;
375
+
376
+ const maybeExit = () => {
377
+ if (stdinClosed && inflight === 0) process.exit(0);
378
+ };
379
+
380
+ for await (const line of rl) {
381
+ const s = line.trim();
382
+ if (!s) continue;
383
+ let msg;
384
+ try {
385
+ msg = JSON.parse(s);
386
+ } catch {
387
+ sendError(null, -32700, 'JSON 解析失败');
388
+ continue;
389
+ }
390
+ inflight += 1;
391
+ handle(msg)
392
+ .catch((e) => {
393
+ if (msg?.id !== undefined && msg?.id !== null) {
394
+ sendError(msg.id, -32603, `内部错误:${String(e?.message || e).slice(0, 300)}`);
395
+ }
396
+ })
397
+ .finally(() => {
398
+ inflight -= 1;
399
+ maybeExit();
400
+ });
401
+ }
402
+
403
+ stdinClosed = true;
404
+ maybeExit();
405
+ }
406
+
407
+ main().catch((e) => {
408
+ process.stderr.write(`mcp-server 启动失败: ${e?.message || e}\n`);
409
+ process.exit(1);
410
+ });