@tarve/mcp 0.0.0-stage → 0.11.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.
- package/README.md +44 -3
- package/dist/cli.js +913 -0
- package/dist/index.js +914 -0
- package/package.json +55 -4
- package/src/cli-args.ts +137 -0
- package/src/cli.ts +9 -0
- package/src/index.ts +4 -0
- package/src/server.ts +156 -0
- package/src/session.ts +295 -0
- package/src/tools.ts +406 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,914 @@
|
|
|
1
|
+
// src/session.ts
|
|
2
|
+
import { spawn, spawnSync } from "node:child_process";
|
|
3
|
+
import { randomBytes } from "node:crypto";
|
|
4
|
+
import { mkdtempSync, rmSync } from "node:fs";
|
|
5
|
+
import { createServer } from "node:net";
|
|
6
|
+
import { tmpdir } from "node:os";
|
|
7
|
+
import { join } from "node:path";
|
|
8
|
+
var Ring = class {
|
|
9
|
+
items = [];
|
|
10
|
+
next = 1;
|
|
11
|
+
limit;
|
|
12
|
+
constructor(limit) {
|
|
13
|
+
this.limit = limit;
|
|
14
|
+
}
|
|
15
|
+
push(item) {
|
|
16
|
+
this.items.push({ ...item, seq: this.next++ });
|
|
17
|
+
if (this.items.length > this.limit) this.items.splice(0, this.items.length - this.limit);
|
|
18
|
+
}
|
|
19
|
+
since(seq = 0, limit = 100) {
|
|
20
|
+
const newer = this.items.filter((item) => item.seq > seq);
|
|
21
|
+
return newer.slice(Math.max(0, newer.length - limit));
|
|
22
|
+
}
|
|
23
|
+
get last() {
|
|
24
|
+
return this.next - 1;
|
|
25
|
+
}
|
|
26
|
+
};
|
|
27
|
+
function controlAddress() {
|
|
28
|
+
const key = randomBytes(16).toString("hex");
|
|
29
|
+
if (process.platform === "win32") return { address: `\\\\.\\pipe\\tarve-mcp-${key}`, cleanup() {
|
|
30
|
+
} };
|
|
31
|
+
const directory = mkdtempSync(join(tmpdir(), "tarve-mcp-"));
|
|
32
|
+
return { address: join(directory, "control.sock"), cleanup() {
|
|
33
|
+
rmSync(directory, { recursive: true, force: true });
|
|
34
|
+
} };
|
|
35
|
+
}
|
|
36
|
+
var AppSession = class {
|
|
37
|
+
launch;
|
|
38
|
+
directory;
|
|
39
|
+
options;
|
|
40
|
+
token = randomBytes(24).toString("hex");
|
|
41
|
+
addr;
|
|
42
|
+
server;
|
|
43
|
+
listening;
|
|
44
|
+
child;
|
|
45
|
+
socket;
|
|
46
|
+
runtime;
|
|
47
|
+
exitCode;
|
|
48
|
+
starts = 0;
|
|
49
|
+
nextId = 1;
|
|
50
|
+
pending = /* @__PURE__ */ new Map();
|
|
51
|
+
connected;
|
|
52
|
+
connectWaiter;
|
|
53
|
+
eventLog;
|
|
54
|
+
logLog;
|
|
55
|
+
constructor(launch, options = {}) {
|
|
56
|
+
this.launch = launch;
|
|
57
|
+
this.options = { connectTimeoutMs: options.connectTimeoutMs ?? 6e4, eventLimit: options.eventLimit ?? 500, logLimit: options.logLimit ?? 1e3 };
|
|
58
|
+
this.eventLog = new Ring(this.options.eventLimit);
|
|
59
|
+
this.logLog = new Ring(this.options.logLimit);
|
|
60
|
+
this.addr = controlAddress();
|
|
61
|
+
this.directory = mkdtempSync(join(tmpdir(), "tarve-mcp-shots-"));
|
|
62
|
+
}
|
|
63
|
+
status() {
|
|
64
|
+
return {
|
|
65
|
+
running: !!this.child && this.child.exitCode === null && this.child.signalCode === null,
|
|
66
|
+
connected: !!this.socket && !this.socket.destroyed,
|
|
67
|
+
...this.child?.pid ? { pid: this.child.pid } : {},
|
|
68
|
+
...this.runtime ? { runtime: this.runtime } : {},
|
|
69
|
+
...this.exitCode !== void 0 ? { exitCode: this.exitCode } : {},
|
|
70
|
+
starts: this.starts,
|
|
71
|
+
command: [this.launch.command, ...this.launch.args]
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
events(since, limit) {
|
|
75
|
+
return { events: this.eventLog.since(since, limit), last: this.eventLog.last };
|
|
76
|
+
}
|
|
77
|
+
logs(since, limit) {
|
|
78
|
+
return { lines: this.logLog.since(since, limit), last: this.logLog.last };
|
|
79
|
+
}
|
|
80
|
+
listen() {
|
|
81
|
+
return this.listening ??= new Promise((resolve2, reject) => {
|
|
82
|
+
const server = createServer((socket) => this.accept(socket));
|
|
83
|
+
server.on("error", reject);
|
|
84
|
+
server.listen(this.addr.address, () => {
|
|
85
|
+
this.server = server;
|
|
86
|
+
resolve2();
|
|
87
|
+
});
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
accept(socket) {
|
|
91
|
+
socket.setEncoding("utf8");
|
|
92
|
+
socket.on("error", () => {
|
|
93
|
+
});
|
|
94
|
+
let buffer = "";
|
|
95
|
+
let introduced = false;
|
|
96
|
+
socket.on("data", (chunk) => {
|
|
97
|
+
buffer += chunk;
|
|
98
|
+
let end;
|
|
99
|
+
while ((end = buffer.indexOf("\n")) >= 0) {
|
|
100
|
+
const line = buffer.slice(0, end);
|
|
101
|
+
buffer = buffer.slice(end + 1);
|
|
102
|
+
let message;
|
|
103
|
+
try {
|
|
104
|
+
message = JSON.parse(line);
|
|
105
|
+
} catch {
|
|
106
|
+
continue;
|
|
107
|
+
}
|
|
108
|
+
if (!introduced) {
|
|
109
|
+
if (message.type !== "hello" || message.token !== this.token) {
|
|
110
|
+
socket.destroy();
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
introduced = true;
|
|
114
|
+
this.socket?.destroy();
|
|
115
|
+
this.socket = socket;
|
|
116
|
+
this.runtime = typeof message.runtime === "string" ? message.runtime : void 0;
|
|
117
|
+
this.connectWaiter?.resolve();
|
|
118
|
+
continue;
|
|
119
|
+
}
|
|
120
|
+
this.receive(message);
|
|
121
|
+
}
|
|
122
|
+
if (buffer.length > 1 << 26) socket.destroy();
|
|
123
|
+
});
|
|
124
|
+
socket.on("close", () => {
|
|
125
|
+
if (this.socket !== socket) return;
|
|
126
|
+
this.socket = void 0;
|
|
127
|
+
this.rejectPending(new Error("The app disconnected"));
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
receive(message) {
|
|
131
|
+
if (message.type === "event" && message.event && typeof message.event === "object") {
|
|
132
|
+
this.eventLog.push({ time: Date.now(), event: message.event });
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
if (message.type === "closed") {
|
|
136
|
+
this.eventLog.push({ time: Date.now(), event: { type: "closed" } });
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
const pending = typeof message.id === "number" ? this.pending.get(message.id) : void 0;
|
|
140
|
+
if (!pending) return;
|
|
141
|
+
this.pending.delete(message.id);
|
|
142
|
+
clearTimeout(pending.timer);
|
|
143
|
+
if (typeof message.error === "string") pending.reject(new Error(message.error));
|
|
144
|
+
else pending.resolve(message.result);
|
|
145
|
+
}
|
|
146
|
+
rejectPending(error) {
|
|
147
|
+
for (const [id, pending] of this.pending) {
|
|
148
|
+
clearTimeout(pending.timer);
|
|
149
|
+
pending.reject(error);
|
|
150
|
+
this.pending.delete(id);
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
recentErrors() {
|
|
154
|
+
const lines = this.logLog.since(0, 15).map((line) => line.text);
|
|
155
|
+
return lines.length ? `
|
|
156
|
+
${lines.join("\n")}` : "";
|
|
157
|
+
}
|
|
158
|
+
/** Starts the app (when it is not running) and resolves once it has connected. */
|
|
159
|
+
async start() {
|
|
160
|
+
if (this.connected && this.status().running) return this.connected;
|
|
161
|
+
await this.listen();
|
|
162
|
+
this.starts++;
|
|
163
|
+
this.exitCode = void 0;
|
|
164
|
+
const { command, args, cwd, env } = this.launch;
|
|
165
|
+
const child = spawn(command, args, {
|
|
166
|
+
cwd,
|
|
167
|
+
env: { ...process.env, ...env, TARVE_CONTROL: this.addr.address, TARVE_CONTROL_TOKEN: this.token, TARVE_DEV: process.env.TARVE_DEV ?? "1" },
|
|
168
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
169
|
+
// Its own process group on Unix, so a stop reaches the runtime a CLI forwards to.
|
|
170
|
+
detached: process.platform !== "win32",
|
|
171
|
+
windowsHide: true,
|
|
172
|
+
// Windows runs `.cmd` shims (npx, bunx) through the shell only.
|
|
173
|
+
shell: process.platform === "win32" && /\.(cmd|bat)$/i.test(command)
|
|
174
|
+
});
|
|
175
|
+
this.child = child;
|
|
176
|
+
for (const stream of ["stdout", "stderr"]) {
|
|
177
|
+
let rest = "";
|
|
178
|
+
child[stream]?.setEncoding("utf8");
|
|
179
|
+
child[stream]?.on("data", (chunk) => {
|
|
180
|
+
const parts = (rest + chunk).split(/\r?\n/);
|
|
181
|
+
rest = parts.pop() ?? "";
|
|
182
|
+
for (const text of parts) this.logLog.push({ time: Date.now(), stream, text });
|
|
183
|
+
});
|
|
184
|
+
child[stream]?.on("end", () => {
|
|
185
|
+
if (rest) this.logLog.push({ time: Date.now(), stream, text: rest });
|
|
186
|
+
rest = "";
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
const connected = new Promise((resolve2, reject) => {
|
|
190
|
+
const timer = setTimeout(() => fail(new Error(`The app did not connect within ${this.options.connectTimeoutMs} ms${this.recentErrors()}`)), this.options.connectTimeoutMs);
|
|
191
|
+
const fail = (error) => {
|
|
192
|
+
clearTimeout(timer);
|
|
193
|
+
this.connectWaiter = void 0;
|
|
194
|
+
reject(error);
|
|
195
|
+
};
|
|
196
|
+
this.connectWaiter = { resolve: () => {
|
|
197
|
+
clearTimeout(timer);
|
|
198
|
+
this.connectWaiter = void 0;
|
|
199
|
+
resolve2();
|
|
200
|
+
}, reject: fail };
|
|
201
|
+
child.once("error", (error) => fail(new Error(`Could not start ${command}: ${error.message}`)));
|
|
202
|
+
child.once("exit", (code) => {
|
|
203
|
+
this.exitCode = code;
|
|
204
|
+
if (this.child === child) this.rejectPending(new Error(`The app exited (code ${code})`));
|
|
205
|
+
if (this.connectWaiter) fail(new Error(`The app exited (code ${code}) before it connected${this.recentErrors()}`));
|
|
206
|
+
});
|
|
207
|
+
});
|
|
208
|
+
this.connected = connected;
|
|
209
|
+
connected.catch(() => {
|
|
210
|
+
});
|
|
211
|
+
return connected;
|
|
212
|
+
}
|
|
213
|
+
/** Sends a control request to the connected app. */
|
|
214
|
+
async request(method, params = {}, timeoutMs = 15e3) {
|
|
215
|
+
if (!this.socket && this.connectWaiter && this.connected) await this.connected;
|
|
216
|
+
const socket = this.socket;
|
|
217
|
+
if (!socket || socket.destroyed) {
|
|
218
|
+
const exited = this.exitCode !== void 0 ? ` (it exited with code ${this.exitCode})` : "";
|
|
219
|
+
return Promise.reject(new Error(`The app is not connected${exited}: call reload to start it again`));
|
|
220
|
+
}
|
|
221
|
+
const id = this.nextId++;
|
|
222
|
+
return new Promise((resolve2, reject) => {
|
|
223
|
+
const timer = setTimeout(() => {
|
|
224
|
+
this.pending.delete(id);
|
|
225
|
+
reject(new Error(`${method} timed out after ${timeoutMs} ms`));
|
|
226
|
+
}, timeoutMs);
|
|
227
|
+
this.pending.set(id, { resolve: resolve2, reject, timer });
|
|
228
|
+
socket.write(JSON.stringify({ id, method, params }) + "\n");
|
|
229
|
+
});
|
|
230
|
+
}
|
|
231
|
+
/** Stops the app: asks it to close, then ends its process tree. */
|
|
232
|
+
async stop() {
|
|
233
|
+
const child = this.child;
|
|
234
|
+
if (!child || child.exitCode !== null || child.signalCode !== null) return;
|
|
235
|
+
const exited = new Promise((resolve2) => child.once("exit", () => resolve2()));
|
|
236
|
+
await this.request("close", {}, 1500).catch(() => {
|
|
237
|
+
});
|
|
238
|
+
const closed = await Promise.race([exited.then(() => true), new Promise((resolve2) => setTimeout(() => resolve2(false), 3e3))]);
|
|
239
|
+
if (!closed) {
|
|
240
|
+
this.kill(child);
|
|
241
|
+
await Promise.race([exited, new Promise((resolve2) => setTimeout(resolve2, 3e3))]);
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
kill(child) {
|
|
245
|
+
if (!child.pid) return;
|
|
246
|
+
try {
|
|
247
|
+
if (process.platform === "win32") spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore", windowsHide: true });
|
|
248
|
+
else process.kill(-child.pid, "SIGKILL");
|
|
249
|
+
} catch {
|
|
250
|
+
child.kill("SIGKILL");
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
async restart() {
|
|
254
|
+
await this.stop();
|
|
255
|
+
this.connected = void 0;
|
|
256
|
+
return this.start();
|
|
257
|
+
}
|
|
258
|
+
/** Stops the app and removes the socket and screenshots. */
|
|
259
|
+
async dispose() {
|
|
260
|
+
await this.stop();
|
|
261
|
+
this.socket?.destroy();
|
|
262
|
+
await new Promise((resolve2) => this.server ? this.server.close(() => resolve2()) : resolve2());
|
|
263
|
+
this.addr.cleanup();
|
|
264
|
+
rmSync(this.directory, { recursive: true, force: true });
|
|
265
|
+
}
|
|
266
|
+
/** Synchronous last resort when the server process exits. */
|
|
267
|
+
killNow() {
|
|
268
|
+
if (this.child && this.child.exitCode === null && this.child.signalCode === null) this.kill(this.child);
|
|
269
|
+
}
|
|
270
|
+
};
|
|
271
|
+
|
|
272
|
+
// src/server.ts
|
|
273
|
+
var PROTOCOL_VERSIONS = ["2025-06-18", "2025-03-26", "2024-11-05"];
|
|
274
|
+
var ErrorCode = { parse: -32700, invalidRequest: -32600, methodNotFound: -32601, invalidParams: -32602, internal: -32603 };
|
|
275
|
+
var RpcError = class extends Error {
|
|
276
|
+
code;
|
|
277
|
+
constructor(code, message) {
|
|
278
|
+
super(message);
|
|
279
|
+
this.code = code;
|
|
280
|
+
}
|
|
281
|
+
};
|
|
282
|
+
var textResult = (text, isError = false) => ({ content: [{ type: "text", text }], ...isError ? { isError } : {} });
|
|
283
|
+
function createHandler(tools, info) {
|
|
284
|
+
const byName = new Map(tools.map((tool) => [tool.name, tool]));
|
|
285
|
+
async function dispatch(method, params) {
|
|
286
|
+
switch (method) {
|
|
287
|
+
case "initialize": {
|
|
288
|
+
const asked = typeof params.protocolVersion === "string" ? params.protocolVersion : "";
|
|
289
|
+
return {
|
|
290
|
+
protocolVersion: PROTOCOL_VERSIONS.includes(asked) ? asked : PROTOCOL_VERSIONS[0],
|
|
291
|
+
capabilities: { tools: { listChanged: false } },
|
|
292
|
+
serverInfo: { name: info.name, version: info.version },
|
|
293
|
+
...info.instructions ? { instructions: info.instructions } : {}
|
|
294
|
+
};
|
|
295
|
+
}
|
|
296
|
+
case "ping":
|
|
297
|
+
return {};
|
|
298
|
+
case "tools/list":
|
|
299
|
+
return { tools: tools.map(({ name, description, inputSchema, annotations }) => ({ name, description, inputSchema, ...annotations ? { annotations } : {} })) };
|
|
300
|
+
case "tools/call": {
|
|
301
|
+
const tool = typeof params.name === "string" ? byName.get(params.name) : void 0;
|
|
302
|
+
if (!tool) throw new RpcError(ErrorCode.invalidParams, `Unknown tool: ${String(params.name)}`);
|
|
303
|
+
const args = params.arguments && typeof params.arguments === "object" && !Array.isArray(params.arguments) ? params.arguments : {};
|
|
304
|
+
try {
|
|
305
|
+
return await tool.run(args);
|
|
306
|
+
} catch (error) {
|
|
307
|
+
return textResult(error instanceof Error ? error.message : String(error), true);
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
default:
|
|
311
|
+
throw new RpcError(ErrorCode.methodNotFound, `Method not found: ${method}`);
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
return async (message) => {
|
|
315
|
+
if (!message || typeof message !== "object" || Array.isArray(message)) {
|
|
316
|
+
return { jsonrpc: "2.0", id: null, error: { code: ErrorCode.invalidRequest, message: "Invalid request" } };
|
|
317
|
+
}
|
|
318
|
+
const { id, method, params } = message;
|
|
319
|
+
if (typeof method !== "string") return void 0;
|
|
320
|
+
if (id === void 0) return void 0;
|
|
321
|
+
try {
|
|
322
|
+
const result = await dispatch(method, params && typeof params === "object" ? params : {});
|
|
323
|
+
return { jsonrpc: "2.0", id, result };
|
|
324
|
+
} catch (error) {
|
|
325
|
+
const code = error instanceof RpcError ? error.code : ErrorCode.internal;
|
|
326
|
+
return { jsonrpc: "2.0", id, error: { code, message: error instanceof Error ? error.message : String(error) } };
|
|
327
|
+
}
|
|
328
|
+
};
|
|
329
|
+
}
|
|
330
|
+
function serveStdio(tools, info, streams = { input: process.stdin, output: process.stdout }) {
|
|
331
|
+
const handle = createHandler(tools, info);
|
|
332
|
+
const send = (response) => {
|
|
333
|
+
streams.output.write(JSON.stringify(response) + "\n");
|
|
334
|
+
};
|
|
335
|
+
const decoder = new TextDecoder();
|
|
336
|
+
let buffer = "";
|
|
337
|
+
const pending = /* @__PURE__ */ new Set();
|
|
338
|
+
const receive = (line) => {
|
|
339
|
+
let message;
|
|
340
|
+
try {
|
|
341
|
+
message = JSON.parse(line);
|
|
342
|
+
} catch {
|
|
343
|
+
send({ jsonrpc: "2.0", id: null, error: { code: ErrorCode.parse, message: "Parse error" } });
|
|
344
|
+
return;
|
|
345
|
+
}
|
|
346
|
+
const task = (async () => {
|
|
347
|
+
if (Array.isArray(message)) {
|
|
348
|
+
const responses = (await Promise.all(message.map(handle))).filter(Boolean);
|
|
349
|
+
if (responses.length) send(responses);
|
|
350
|
+
} else {
|
|
351
|
+
const response = await handle(message);
|
|
352
|
+
if (response) send(response);
|
|
353
|
+
}
|
|
354
|
+
})();
|
|
355
|
+
pending.add(task);
|
|
356
|
+
void task.finally(() => pending.delete(task));
|
|
357
|
+
};
|
|
358
|
+
streams.input.setEncoding?.("utf8");
|
|
359
|
+
return new Promise((resolve2) => {
|
|
360
|
+
let done = false;
|
|
361
|
+
const finish = () => {
|
|
362
|
+
if (done) return;
|
|
363
|
+
done = true;
|
|
364
|
+
if (buffer.trim()) receive(buffer);
|
|
365
|
+
void Promise.allSettled([...pending]).then(() => resolve2());
|
|
366
|
+
};
|
|
367
|
+
streams.input.on("data", (chunk) => {
|
|
368
|
+
buffer += typeof chunk === "string" ? chunk : decoder.decode(chunk, { stream: true });
|
|
369
|
+
let end;
|
|
370
|
+
while ((end = buffer.indexOf("\n")) >= 0) {
|
|
371
|
+
const line = buffer.slice(0, end).replace(/\r$/, "");
|
|
372
|
+
buffer = buffer.slice(end + 1);
|
|
373
|
+
if (line.trim()) receive(line);
|
|
374
|
+
}
|
|
375
|
+
});
|
|
376
|
+
streams.input.on("end", finish);
|
|
377
|
+
streams.input.on("close", finish);
|
|
378
|
+
});
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
// src/tools.ts
|
|
382
|
+
import { readFileSync, rmSync as rmSync2 } from "node:fs";
|
|
383
|
+
import { join as join2 } from "node:path";
|
|
384
|
+
var KEYS = {
|
|
385
|
+
enter: "Enter",
|
|
386
|
+
return: "Enter",
|
|
387
|
+
tab: "Tab",
|
|
388
|
+
esc: "Escape",
|
|
389
|
+
escape: "Escape",
|
|
390
|
+
space: "Space",
|
|
391
|
+
backspace: "Backspace",
|
|
392
|
+
delete: "Delete",
|
|
393
|
+
del: "Delete",
|
|
394
|
+
home: "Home",
|
|
395
|
+
end: "End",
|
|
396
|
+
pageup: "PageUp",
|
|
397
|
+
pagedown: "PageDown",
|
|
398
|
+
up: "ArrowUp",
|
|
399
|
+
down: "ArrowDown",
|
|
400
|
+
left: "ArrowLeft",
|
|
401
|
+
right: "ArrowRight",
|
|
402
|
+
arrowup: "ArrowUp",
|
|
403
|
+
arrowdown: "ArrowDown",
|
|
404
|
+
arrowleft: "ArrowLeft",
|
|
405
|
+
arrowright: "ArrowRight",
|
|
406
|
+
selectall: "SelectAll"
|
|
407
|
+
};
|
|
408
|
+
var keyName = (key) => KEYS[key.trim().toLowerCase()] ?? key.trim();
|
|
409
|
+
var label = (node) => node.control?.label ?? node.text ?? "";
|
|
410
|
+
var visible = (node) => node.width > 0 && node.height > 0;
|
|
411
|
+
var round = (value) => Math.round(value * 10) / 10;
|
|
412
|
+
var box = (node) => `${round(node.x)},${round(node.y)} ${round(node.width)}x${round(node.height)}`;
|
|
413
|
+
var quote = (text, max = 80) => JSON.stringify(text.length > max ? `${text.slice(0, max - 1)}\u2026` : text);
|
|
414
|
+
var json = (value) => textResult(JSON.stringify(value, null, 2));
|
|
415
|
+
function findByText(snapshot, text, exact = false) {
|
|
416
|
+
const shown = snapshot.nodes.filter(visible);
|
|
417
|
+
const same = shown.filter((node) => label(node) === text);
|
|
418
|
+
const matches = same.length || exact ? same : shown.filter((node) => label(node).includes(text));
|
|
419
|
+
return matches.sort((a, b) => a.width * a.height - b.width * b.height)[0];
|
|
420
|
+
}
|
|
421
|
+
function outline(root, snapshot, options = {}) {
|
|
422
|
+
const maxDepth = options.maxDepth ?? 12, maxNodes = options.maxNodes ?? 400;
|
|
423
|
+
const boxes = new Map(snapshot?.nodes.map((node) => [node.id, node]) ?? []);
|
|
424
|
+
const lines = [];
|
|
425
|
+
let omitted = 0;
|
|
426
|
+
const walk = (node, depth) => {
|
|
427
|
+
const shot = boxes.get(node.id);
|
|
428
|
+
if (options.visibleOnly && shot && !visible(shot)) return;
|
|
429
|
+
if (lines.length >= maxNodes) {
|
|
430
|
+
omitted++;
|
|
431
|
+
return;
|
|
432
|
+
}
|
|
433
|
+
const parts = [`${node.kind}#${node.id}`];
|
|
434
|
+
const content = shot?.text || node.text;
|
|
435
|
+
if (content) parts.push(quote(content));
|
|
436
|
+
if (node.value !== void 0) parts.push(`value=${quote(String(node.value))}`);
|
|
437
|
+
if (node.placeholder) parts.push(`placeholder=${quote(node.placeholder)}`);
|
|
438
|
+
if (shot?.control?.label && shot.control.label !== content) parts.push(`label=${quote(shot.control.label)}`);
|
|
439
|
+
if (node.disabled) parts.push("disabled");
|
|
440
|
+
if (node.src) parts.push(`src=${quote(node.src, 60)}`);
|
|
441
|
+
if (shot) parts.push(`[${box(shot)}]`);
|
|
442
|
+
if (shot && shot.scrollMax > 0) parts.push(`scroll=${round(shot.scroll)}/${round(shot.scrollMax)}`);
|
|
443
|
+
if (snapshot?.focused === node.id) parts.push("(focused)");
|
|
444
|
+
if (snapshot?.hovered === node.id) parts.push("(hovered)");
|
|
445
|
+
if (options.styles && node.style) parts.push(`style=${JSON.stringify(node.style)}`);
|
|
446
|
+
lines.push(`${" ".repeat(depth)}${parts.join(" ")}`);
|
|
447
|
+
if (depth + 1 > maxDepth) {
|
|
448
|
+
if (node.children.length) lines.push(`${" ".repeat(depth + 1)}\u2026 ${node.children.length} children (raise maxDepth)`);
|
|
449
|
+
return;
|
|
450
|
+
}
|
|
451
|
+
for (const child of node.children) walk(child, depth + 1);
|
|
452
|
+
};
|
|
453
|
+
walk(root, 0);
|
|
454
|
+
if (omitted) lines.push(`\u2026 ${omitted} more nodes (raise maxNodes or pass root)`);
|
|
455
|
+
return lines.join("\n");
|
|
456
|
+
}
|
|
457
|
+
function findNode(node, id) {
|
|
458
|
+
if (node.id === id) return node;
|
|
459
|
+
for (const child of node.children) {
|
|
460
|
+
const found = findNode(child, id);
|
|
461
|
+
if (found) return found;
|
|
462
|
+
}
|
|
463
|
+
return void 0;
|
|
464
|
+
}
|
|
465
|
+
var str = (value) => typeof value === "string" && value !== "" ? value : void 0;
|
|
466
|
+
var num = (value) => typeof value === "number" && Number.isFinite(value) ? value : void 0;
|
|
467
|
+
var int = (value, fallback, max) => Math.max(1, Math.min(max, Math.floor(num(value) ?? fallback)));
|
|
468
|
+
var TARGET = {
|
|
469
|
+
text: { type: "string", description: "Visible text or control label of the node (exact match first, then substring; the smallest node wins)" },
|
|
470
|
+
id: { type: "string", description: "Node id (from inspect_tree or query_nodes)" },
|
|
471
|
+
x: { type: "number", description: "Window x in logical px (with y, instead of text/id)" },
|
|
472
|
+
y: { type: "number", description: "Window y in logical px" }
|
|
473
|
+
};
|
|
474
|
+
async function resolvePoint(session, args, prefix = "") {
|
|
475
|
+
const x = num(args[`${prefix}x`]), y = num(args[`${prefix}y`]);
|
|
476
|
+
if (x !== void 0 && y !== void 0) return { point: { x, y } };
|
|
477
|
+
const id = str(args[`${prefix}id`]), text = str(args[`${prefix}text`]);
|
|
478
|
+
if (!id && !text) throw new Error(`Give ${prefix}text, ${prefix}id or ${prefix}x and ${prefix}y`);
|
|
479
|
+
const snapshot = await session.request("inspect");
|
|
480
|
+
const node = id ? snapshot.nodes.find((candidate) => candidate.id === id) : findByText(snapshot, text);
|
|
481
|
+
if (!node) throw new Error(id ? `No node has id ${JSON.stringify(id)}` : `No visible node shows ${JSON.stringify(text)}`);
|
|
482
|
+
if (!visible(node)) throw new Error(`Node ${node.id} is not laid out (zero size)`);
|
|
483
|
+
return { point: { x: node.x + node.width / 2, y: node.y + node.height / 2 }, node };
|
|
484
|
+
}
|
|
485
|
+
async function settled(session, done) {
|
|
486
|
+
const snapshot = await session.request("settle", {}, 1e4);
|
|
487
|
+
return json({ ...done, focused: snapshot.focused, hovered: snapshot.hovered });
|
|
488
|
+
}
|
|
489
|
+
var input = (session, params) => session.request("input", params);
|
|
490
|
+
var describe = (node) => node ? { id: node.id, kind: node.kind, text: label(node) } : void 0;
|
|
491
|
+
function createTools(session) {
|
|
492
|
+
let shots = 0;
|
|
493
|
+
const readOnly = { readOnlyHint: true, openWorldHint: false };
|
|
494
|
+
const acts = { readOnlyHint: false, destructiveHint: false, openWorldHint: false };
|
|
495
|
+
return [
|
|
496
|
+
// Reading the app.
|
|
497
|
+
{
|
|
498
|
+
name: "app_status",
|
|
499
|
+
description: "Whether the app is running and connected, its pid and runtime, window size and scale, fps, and the focused and hovered nodes.",
|
|
500
|
+
inputSchema: { type: "object", properties: {}, additionalProperties: false },
|
|
501
|
+
annotations: { title: "App status", ...readOnly },
|
|
502
|
+
async run() {
|
|
503
|
+
const status = session.status();
|
|
504
|
+
if (!status.connected) return json(status);
|
|
505
|
+
const snapshot = await session.request("inspect");
|
|
506
|
+
return json({ ...status, window: { width: snapshot.width, height: snapshot.height, scale: snapshot.scale }, fps: snapshot.fps, focused: snapshot.focused, hovered: snapshot.hovered, nodes: snapshot.nodes.length });
|
|
507
|
+
}
|
|
508
|
+
},
|
|
509
|
+
{
|
|
510
|
+
name: "inspect_tree",
|
|
511
|
+
description: 'The app\'s node tree as an indented outline: `kind#id "text" [x,y wxh]` per node (window coordinates, logical px), with values, labels, scroll, focus and hover. Use the ids with the other tools.',
|
|
512
|
+
inputSchema: {
|
|
513
|
+
type: "object",
|
|
514
|
+
properties: {
|
|
515
|
+
root: { type: "string", description: "Only the subtree of this node id" },
|
|
516
|
+
maxDepth: { type: "number", description: "Default 12" },
|
|
517
|
+
maxNodes: { type: "number", description: "Default 400" },
|
|
518
|
+
styles: { type: "boolean", description: "Include each node's style (verbose)" },
|
|
519
|
+
visibleOnly: { type: "boolean", description: "Skip nodes with no size" }
|
|
520
|
+
},
|
|
521
|
+
additionalProperties: false
|
|
522
|
+
},
|
|
523
|
+
annotations: { title: "Inspect node tree", ...readOnly },
|
|
524
|
+
async run(args) {
|
|
525
|
+
const styles = args.styles === true;
|
|
526
|
+
const [tree, snapshot] = await Promise.all([session.request("tree", { styles }), session.request("inspect")]);
|
|
527
|
+
if (!tree) return textResult("The app has not rendered a tree yet.", true);
|
|
528
|
+
const rootId = str(args.root);
|
|
529
|
+
const root = rootId ? findNode(tree, rootId) : tree;
|
|
530
|
+
if (!root) return textResult(`No node has id ${JSON.stringify(rootId)}`, true);
|
|
531
|
+
const header = `window ${snapshot.width}x${snapshot.height} @${snapshot.scale}x, focused=${snapshot.focused ?? "none"}, hovered=${snapshot.hovered ?? "none"}`;
|
|
532
|
+
return textResult(`${header}
|
|
533
|
+
${outline(root, snapshot, { maxDepth: int(args.maxDepth, 12, 200), maxNodes: int(args.maxNodes, 400, 5e3), styles, visibleOnly: args.visibleOnly === true })}`);
|
|
534
|
+
}
|
|
535
|
+
},
|
|
536
|
+
{
|
|
537
|
+
name: "query_nodes",
|
|
538
|
+
description: "Finds laid-out nodes by text/label (substring unless exact), id or kind, with their boxes, scroll and control state.",
|
|
539
|
+
inputSchema: {
|
|
540
|
+
type: "object",
|
|
541
|
+
properties: {
|
|
542
|
+
text: { type: "string" },
|
|
543
|
+
exact: { type: "boolean", description: "Text must match the whole label" },
|
|
544
|
+
id: { type: "string" },
|
|
545
|
+
kind: { type: "string", description: "Node kind: view, text, pressable, input, textarea, scroll, image\u2026" },
|
|
546
|
+
includeHidden: { type: "boolean", description: "Also nodes with no size" },
|
|
547
|
+
limit: { type: "number", description: "Default 20" }
|
|
548
|
+
},
|
|
549
|
+
additionalProperties: false
|
|
550
|
+
},
|
|
551
|
+
annotations: { title: "Query nodes", ...readOnly },
|
|
552
|
+
async run(args) {
|
|
553
|
+
const snapshot = await session.request("inspect");
|
|
554
|
+
const text = str(args.text), id = str(args.id), kind = str(args.kind);
|
|
555
|
+
const matches = snapshot.nodes.filter((node) => (args.includeHidden === true || visible(node)) && (!id || node.id === id) && (!kind || node.kind === kind) && (!text || (args.exact === true ? label(node) === text : label(node).includes(text))));
|
|
556
|
+
const limit = int(args.limit, 20, 500);
|
|
557
|
+
return json({ total: matches.length, nodes: matches.slice(0, limit) });
|
|
558
|
+
}
|
|
559
|
+
},
|
|
560
|
+
{
|
|
561
|
+
name: "screenshot",
|
|
562
|
+
description: "A PNG of the app window as it is drawn now.",
|
|
563
|
+
inputSchema: { type: "object", properties: {}, additionalProperties: false },
|
|
564
|
+
annotations: { title: "Screenshot", ...readOnly },
|
|
565
|
+
async run() {
|
|
566
|
+
const path = join2(session.directory, `shot-${++shots}.png`);
|
|
567
|
+
await session.request("capture", { path }, 2e4);
|
|
568
|
+
try {
|
|
569
|
+
const data = readFileSync(path).toString("base64");
|
|
570
|
+
const snapshot = await session.request("inspect");
|
|
571
|
+
return { content: [{ type: "image", data, mimeType: "image/png" }, { type: "text", text: `${snapshot.width}x${snapshot.height} logical px @${snapshot.scale}x` }] };
|
|
572
|
+
} finally {
|
|
573
|
+
rmSync2(path, { force: true });
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
},
|
|
577
|
+
// Driving it.
|
|
578
|
+
{
|
|
579
|
+
name: "click",
|
|
580
|
+
description: "Moves the pointer to a node (by text or id) or a window point and clicks there, through native hit testing like a user. Waits for the next frame.",
|
|
581
|
+
inputSchema: { type: "object", properties: { ...TARGET, double: { type: "boolean", description: "Double click" } }, additionalProperties: false },
|
|
582
|
+
annotations: { title: "Click", ...acts },
|
|
583
|
+
async run(args) {
|
|
584
|
+
const { point, node } = await resolvePoint(session, args);
|
|
585
|
+
await input(session, { action: "move", ...point });
|
|
586
|
+
for (let count = args.double === true ? 2 : 1; count > 0; count--) {
|
|
587
|
+
await input(session, { action: "down" });
|
|
588
|
+
await input(session, { action: "up" });
|
|
589
|
+
}
|
|
590
|
+
return settled(session, { clicked: describe(node), at: point });
|
|
591
|
+
}
|
|
592
|
+
},
|
|
593
|
+
{
|
|
594
|
+
name: "hover",
|
|
595
|
+
description: "Moves the pointer over a node (by text or id) or to a window point.",
|
|
596
|
+
inputSchema: { type: "object", properties: TARGET, additionalProperties: false },
|
|
597
|
+
annotations: { title: "Hover", ...acts },
|
|
598
|
+
async run(args) {
|
|
599
|
+
const { point, node } = await resolvePoint(session, args);
|
|
600
|
+
await input(session, { action: "move", ...point });
|
|
601
|
+
return settled(session, { hovering: describe(node), at: point });
|
|
602
|
+
}
|
|
603
|
+
},
|
|
604
|
+
{
|
|
605
|
+
name: "type_text",
|
|
606
|
+
description: "Types text into the focused field, or first focuses the node given by id (or clicks the node given by text).",
|
|
607
|
+
inputSchema: {
|
|
608
|
+
type: "object",
|
|
609
|
+
properties: { text: { type: "string", description: "What to type" }, id: TARGET.id, target: { type: "string", description: "Text or label of the field to click first" }, clear: { type: "boolean", description: "Select all and delete first" } },
|
|
610
|
+
required: ["text"],
|
|
611
|
+
additionalProperties: false
|
|
612
|
+
},
|
|
613
|
+
annotations: { title: "Type text", ...acts },
|
|
614
|
+
async run(args) {
|
|
615
|
+
if (typeof args.text !== "string") throw new Error("text must be a string");
|
|
616
|
+
const id = str(args.id), target = str(args.target);
|
|
617
|
+
if (id) await session.request("focus", { id });
|
|
618
|
+
else if (target) {
|
|
619
|
+
const { point } = await resolvePoint(session, { text: target });
|
|
620
|
+
await input(session, { action: "move", ...point });
|
|
621
|
+
await input(session, { action: "down" });
|
|
622
|
+
await input(session, { action: "up" });
|
|
623
|
+
await session.request("settle");
|
|
624
|
+
}
|
|
625
|
+
if (args.clear === true) {
|
|
626
|
+
await input(session, { action: "key", text: "SelectAll" });
|
|
627
|
+
await input(session, { action: "key", text: "Backspace" });
|
|
628
|
+
}
|
|
629
|
+
if (args.text) await input(session, { action: "text", text: args.text });
|
|
630
|
+
return settled(session, { typed: args.text });
|
|
631
|
+
}
|
|
632
|
+
},
|
|
633
|
+
{
|
|
634
|
+
name: "press_key",
|
|
635
|
+
description: "Presses a key (Enter, Tab, Escape, Space, Backspace, Delete, Home, End, PageUp, PageDown, ArrowUp/Down/Left/Right, SelectAll or a character), optionally focusing a node id first.",
|
|
636
|
+
inputSchema: { type: "object", properties: { key: { type: "string" }, id: TARGET.id, repeat: { type: "number", description: "Times to press it. Default 1" } }, required: ["key"], additionalProperties: false },
|
|
637
|
+
annotations: { title: "Press key", ...acts },
|
|
638
|
+
async run(args) {
|
|
639
|
+
const key = str(args.key);
|
|
640
|
+
if (!key) throw new Error("key must be a non-empty string");
|
|
641
|
+
const id = str(args.id);
|
|
642
|
+
if (id) await session.request("focus", { id });
|
|
643
|
+
const name = keyName(key);
|
|
644
|
+
for (let count = int(args.repeat, 1, 100); count > 0; count--) await input(session, { action: "key", text: name });
|
|
645
|
+
return settled(session, { pressed: name });
|
|
646
|
+
}
|
|
647
|
+
},
|
|
648
|
+
{
|
|
649
|
+
name: "scroll",
|
|
650
|
+
description: "Scrolls with the wheel over a node (by text or id) or a window point; positive deltaY scrolls down. With `to` and an id, jumps a scroll container to start or end instead.",
|
|
651
|
+
inputSchema: {
|
|
652
|
+
type: "object",
|
|
653
|
+
properties: { ...TARGET, deltaY: { type: "number", description: "Pixels, positive is down" }, deltaX: { type: "number", description: "Pixels, positive is right" }, to: { type: "string", enum: ["start", "end"], description: "With id: scroll that container to its start or end" } },
|
|
654
|
+
additionalProperties: false
|
|
655
|
+
},
|
|
656
|
+
annotations: { title: "Scroll", ...acts },
|
|
657
|
+
async run(args) {
|
|
658
|
+
const id = str(args.id);
|
|
659
|
+
if (args.to === "start" || args.to === "end") {
|
|
660
|
+
if (!id) throw new Error("to needs the id of a scroll container");
|
|
661
|
+
await session.request("scrollTo", { id, y: args.to });
|
|
662
|
+
return settled(session, { scrolled: id, to: args.to });
|
|
663
|
+
}
|
|
664
|
+
const deltaY = num(args.deltaY) ?? 0, deltaX = num(args.deltaX) ?? 0;
|
|
665
|
+
if (!deltaY && !deltaX) throw new Error("Give deltaY or deltaX (or to)");
|
|
666
|
+
const { point, node } = await resolvePoint(session, args);
|
|
667
|
+
await input(session, { action: "move", ...point });
|
|
668
|
+
await input(session, { action: "wheel", ...deltaY ? { deltaY } : {}, ...deltaX ? { deltaX } : {} });
|
|
669
|
+
return settled(session, { scrolled: describe(node), at: point, deltaX, deltaY });
|
|
670
|
+
}
|
|
671
|
+
},
|
|
672
|
+
{
|
|
673
|
+
name: "drag",
|
|
674
|
+
description: "Presses on one node or point, moves to another and releases (sliders, splitters, drag and drop). Targets: fromText/fromId/fromX+fromY and toText/toId/toX+toY.",
|
|
675
|
+
inputSchema: {
|
|
676
|
+
type: "object",
|
|
677
|
+
properties: {
|
|
678
|
+
fromText: { type: "string" },
|
|
679
|
+
fromId: { type: "string" },
|
|
680
|
+
fromX: { type: "number" },
|
|
681
|
+
fromY: { type: "number" },
|
|
682
|
+
toText: { type: "string" },
|
|
683
|
+
toId: { type: "string" },
|
|
684
|
+
toX: { type: "number" },
|
|
685
|
+
toY: { type: "number" },
|
|
686
|
+
steps: { type: "number", description: "Intermediate moves. Default 8" }
|
|
687
|
+
},
|
|
688
|
+
additionalProperties: false
|
|
689
|
+
},
|
|
690
|
+
annotations: { title: "Drag", ...acts },
|
|
691
|
+
async run(args) {
|
|
692
|
+
const from = (await resolvePoint(session, args, "from")).point;
|
|
693
|
+
const to = (await resolvePoint(session, args, "to")).point;
|
|
694
|
+
const steps = int(args.steps, 8, 100);
|
|
695
|
+
await input(session, { action: "move", ...from });
|
|
696
|
+
await input(session, { action: "down" });
|
|
697
|
+
for (let step = 1; step <= steps; step++) {
|
|
698
|
+
await input(session, { action: "move", x: from.x + (to.x - from.x) * step / steps, y: from.y + (to.y - from.y) * step / steps });
|
|
699
|
+
}
|
|
700
|
+
await input(session, { action: "up" });
|
|
701
|
+
return settled(session, { from, to });
|
|
702
|
+
}
|
|
703
|
+
},
|
|
704
|
+
{
|
|
705
|
+
name: "focus",
|
|
706
|
+
description: "Gives keyboard focus to a node by id.",
|
|
707
|
+
inputSchema: { type: "object", properties: { id: TARGET.id }, required: ["id"], additionalProperties: false },
|
|
708
|
+
annotations: { title: "Focus", ...acts },
|
|
709
|
+
async run(args) {
|
|
710
|
+
const id = str(args.id);
|
|
711
|
+
if (!id) throw new Error("id must be a non-empty string");
|
|
712
|
+
await session.request("focus", { id });
|
|
713
|
+
return settled(session, { focusing: id });
|
|
714
|
+
}
|
|
715
|
+
},
|
|
716
|
+
{
|
|
717
|
+
name: "wait_for",
|
|
718
|
+
description: "Waits until a node showing the text appears (or, with gone, disappears).",
|
|
719
|
+
inputSchema: { type: "object", properties: { text: { type: "string" }, gone: { type: "boolean" }, exact: { type: "boolean" }, timeoutMs: { type: "number", description: "Default 5000, at most 60000" } }, required: ["text"], additionalProperties: false },
|
|
720
|
+
annotations: { title: "Wait for text", ...readOnly },
|
|
721
|
+
async run(args) {
|
|
722
|
+
const text = str(args.text);
|
|
723
|
+
if (!text) throw new Error("text must be a non-empty string");
|
|
724
|
+
const deadline = Date.now() + Math.min(num(args.timeoutMs) ?? 5e3, 6e4);
|
|
725
|
+
for (; ; ) {
|
|
726
|
+
const node = findByText(await session.request("inspect"), text, args.exact === true);
|
|
727
|
+
if (args.gone === true ? !node : node) return json(args.gone === true ? { gone: text } : { found: describe(node), box: node && box(node) });
|
|
728
|
+
if (Date.now() >= deadline) return textResult(`Timed out: ${JSON.stringify(text)} ${args.gone === true ? "is still shown" : "never appeared"}`, true);
|
|
729
|
+
await new Promise((resolve2) => setTimeout(resolve2, 100));
|
|
730
|
+
}
|
|
731
|
+
}
|
|
732
|
+
},
|
|
733
|
+
// Development loop.
|
|
734
|
+
{
|
|
735
|
+
name: "reload",
|
|
736
|
+
description: "Restarts the app process (a clean start: state is lost). Edits already hot-reload in dev mode; use this after a crash, a closed window or changes hot reload cannot apply.",
|
|
737
|
+
inputSchema: { type: "object", properties: {}, additionalProperties: false },
|
|
738
|
+
annotations: { title: "Reload app", readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false },
|
|
739
|
+
async run() {
|
|
740
|
+
await session.restart();
|
|
741
|
+
await session.request("settle", {}, 15e3).catch(() => {
|
|
742
|
+
});
|
|
743
|
+
return json(session.status());
|
|
744
|
+
}
|
|
745
|
+
},
|
|
746
|
+
{
|
|
747
|
+
name: "get_metrics",
|
|
748
|
+
description: "Performance: percentiles (ms) of the JS update phases (render, diff, shadow, send, update) and native frame phases (apply, layout, paint, present, frame, gpu), memory, fps and frame/layout/paint counters.",
|
|
749
|
+
inputSchema: { type: "object", properties: { reset: { type: "boolean", description: "Clear the samples after reading them" } }, additionalProperties: false },
|
|
750
|
+
annotations: { title: "Metrics", ...readOnly },
|
|
751
|
+
async run(args) {
|
|
752
|
+
const [stats, snapshot] = await Promise.all([session.request("stats", { reset: args.reset === true }), session.request("inspect")]);
|
|
753
|
+
const { nodes: _nodes, ...counters } = snapshot;
|
|
754
|
+
return json({ counters, ...stats });
|
|
755
|
+
}
|
|
756
|
+
},
|
|
757
|
+
{
|
|
758
|
+
name: "get_events",
|
|
759
|
+
description: "Recent native events of the app (clicks, keys, focus, size, window\u2026), oldest first. Pass `since` (the `last` of a previous call) for only new ones.",
|
|
760
|
+
inputSchema: { type: "object", properties: { since: { type: "number" }, limit: { type: "number", description: "Default 50" } }, additionalProperties: false },
|
|
761
|
+
annotations: { title: "Events", ...readOnly },
|
|
762
|
+
async run(args) {
|
|
763
|
+
return json(session.events(num(args.since), int(args.limit, 50, 500)));
|
|
764
|
+
}
|
|
765
|
+
},
|
|
766
|
+
{
|
|
767
|
+
name: "get_logs",
|
|
768
|
+
description: "The app's stdout and stderr (console output, errors, stack traces), oldest first. Pass `since` (the `last` of a previous call) for only new lines.",
|
|
769
|
+
inputSchema: { type: "object", properties: { since: { type: "number" }, limit: { type: "number", description: "Default 100" }, stream: { type: "string", enum: ["stdout", "stderr"] } }, additionalProperties: false },
|
|
770
|
+
annotations: { title: "Logs", ...readOnly },
|
|
771
|
+
async run(args) {
|
|
772
|
+
const { lines, last } = session.logs(num(args.since), int(args.limit, 100, 1e3));
|
|
773
|
+
const stream = args.stream === "stdout" || args.stream === "stderr" ? args.stream : void 0;
|
|
774
|
+
const shown = stream ? lines.filter((line) => line.stream === stream) : lines;
|
|
775
|
+
return textResult(`${shown.map((line) => `${line.seq} ${line.stream === "stderr" ? "!" : " "} ${line.text}`).join("\n") || "(no output)"}
|
|
776
|
+
last=${last}`);
|
|
777
|
+
}
|
|
778
|
+
}
|
|
779
|
+
];
|
|
780
|
+
}
|
|
781
|
+
|
|
782
|
+
// src/cli-args.ts
|
|
783
|
+
import { existsSync, readFileSync as readFileSync2 } from "node:fs";
|
|
784
|
+
import { dirname, join as join3, resolve } from "node:path";
|
|
785
|
+
var VERSION = "0.10.0";
|
|
786
|
+
var USAGE = `tarve-mcp: a Model Context Protocol server (stdio) that runs a Tarve app and lets an agent inspect, screenshot, drive and reload it.
|
|
787
|
+
|
|
788
|
+
Usage:
|
|
789
|
+
tarve-mcp [options] <app.tsx> start the app with \`tarve dev\` (hot reload)
|
|
790
|
+
tarve-mcp [options] <dist/App.exe> start a built app (\`tarve build\`, any runtime) as it is
|
|
791
|
+
tarve-mcp [options] --exec <command...> start the app with your own command (it must use @tarve/core)
|
|
792
|
+
(\`-- <command...>\` too, where the runtime keeps \`--\`: Bun drops it)
|
|
793
|
+
|
|
794
|
+
Options:
|
|
795
|
+
--run \`tarve run\` instead of \`tarve dev\` (no hot reload)
|
|
796
|
+
--runtime <name> bun or node, passed to the tarve CLI
|
|
797
|
+
--inspect also open the visual inspector window
|
|
798
|
+
--cwd <dir> working directory of the app (default: the current one)
|
|
799
|
+
--connect-timeout <ms> how long the app may take to connect (default 60000)
|
|
800
|
+
|
|
801
|
+
MCP client config (Claude Desktop, Cursor, VS Code\u2026):
|
|
802
|
+
{ "command": "bunx", "args": ["tarve-mcp", "src/app.tsx"] }`;
|
|
803
|
+
function parseArgs(argv, cwd = process.cwd()) {
|
|
804
|
+
const args = { mode: "dev", inspect: false, cwd, help: false };
|
|
805
|
+
for (let index = 0; index < argv.length; index++) {
|
|
806
|
+
const arg = argv[index];
|
|
807
|
+
const value = () => {
|
|
808
|
+
const next = argv[++index];
|
|
809
|
+
if (next === void 0) throw new Error(`${arg} needs a value`);
|
|
810
|
+
return next;
|
|
811
|
+
};
|
|
812
|
+
if (arg === "--" || arg === "--exec") {
|
|
813
|
+
args.command = argv.slice(index + 1);
|
|
814
|
+
break;
|
|
815
|
+
}
|
|
816
|
+
if (arg === "--help" || arg === "-h") args.help = true;
|
|
817
|
+
else if (arg === "--run") args.mode = "run";
|
|
818
|
+
else if (arg === "--dev") args.mode = "dev";
|
|
819
|
+
else if (arg === "--inspect") args.inspect = true;
|
|
820
|
+
else if (arg === "--runtime") args.runtime = value();
|
|
821
|
+
else if (arg === "--cwd") args.cwd = resolve(cwd, value());
|
|
822
|
+
else if (arg === "--connect-timeout") {
|
|
823
|
+
const ms = Number(value());
|
|
824
|
+
if (!Number.isFinite(ms) || ms <= 0) throw new Error("--connect-timeout needs a positive number of milliseconds");
|
|
825
|
+
args.connectTimeoutMs = ms;
|
|
826
|
+
} else if (arg.startsWith("-")) throw new Error(`Unknown option ${arg}`);
|
|
827
|
+
else if (args.entry) throw new Error(`Unexpected argument ${arg}: give one app entry, or a command after --`);
|
|
828
|
+
else args.entry = arg;
|
|
829
|
+
}
|
|
830
|
+
if (args.command && !args.command.length) throw new Error("Give the command after --exec");
|
|
831
|
+
if (args.command && args.entry) throw new Error("Give an app entry or a command after --exec, not both");
|
|
832
|
+
return args;
|
|
833
|
+
}
|
|
834
|
+
var readJson = (path) => {
|
|
835
|
+
try {
|
|
836
|
+
return JSON.parse(readFileSync2(path, "utf8"));
|
|
837
|
+
} catch {
|
|
838
|
+
return void 0;
|
|
839
|
+
}
|
|
840
|
+
};
|
|
841
|
+
function findTarveCli(cwd) {
|
|
842
|
+
const binOf = (root, manifest) => {
|
|
843
|
+
const bin = manifest.bin;
|
|
844
|
+
const path = typeof bin === "string" ? bin : bin && typeof bin === "object" ? bin.tarve : void 0;
|
|
845
|
+
return typeof path === "string" && existsSync(join3(root, path)) ? join3(root, path) : void 0;
|
|
846
|
+
};
|
|
847
|
+
for (let directory = resolve(cwd); ; directory = dirname(directory)) {
|
|
848
|
+
const own = readJson(join3(directory, "package.json"));
|
|
849
|
+
if (own?.name === "@tarve/core") {
|
|
850
|
+
const source = join3(directory, "packages", "core", "cli.ts");
|
|
851
|
+
if (existsSync(source)) return [process.versions.bun ? process.execPath : "bun", source];
|
|
852
|
+
const built = binOf(directory, own);
|
|
853
|
+
if (built) return [process.execPath, built];
|
|
854
|
+
}
|
|
855
|
+
const installed = join3(directory, "node_modules", "@tarve", "core");
|
|
856
|
+
const manifest = readJson(join3(installed, "package.json"));
|
|
857
|
+
const bin = manifest && binOf(installed, manifest);
|
|
858
|
+
if (bin) return [process.execPath, bin];
|
|
859
|
+
if (dirname(directory) === directory) return void 0;
|
|
860
|
+
}
|
|
861
|
+
}
|
|
862
|
+
var SOURCE = /\.(?:[cm]?[jt]sx?|svelte)$/i;
|
|
863
|
+
function resolveLaunch(args) {
|
|
864
|
+
const env = args.inspect ? { TARVE_INSPECTOR: "1" } : {};
|
|
865
|
+
if (args.command) return { command: args.command[0], args: args.command.slice(1), cwd: args.cwd, env };
|
|
866
|
+
if (!args.entry) throw new Error(`Give the app entry (tarve-mcp app.tsx) or a command after --exec
|
|
867
|
+
|
|
868
|
+
${USAGE}`);
|
|
869
|
+
const entry = resolve(args.cwd, args.entry);
|
|
870
|
+
if (!existsSync(entry)) throw new Error(`${entry} does not exist`);
|
|
871
|
+
if (!SOURCE.test(entry)) return { command: entry, args: [], cwd: args.cwd, env };
|
|
872
|
+
const cli = findTarveCli(args.cwd);
|
|
873
|
+
if (!cli) throw new Error(`@tarve/core is not installed in ${args.cwd} or above: install it, or give the command after --exec`);
|
|
874
|
+
return { command: cli[0], args: [...cli.slice(1), args.mode, entry, ...args.runtime ? ["--runtime", args.runtime] : []], cwd: args.cwd, env };
|
|
875
|
+
}
|
|
876
|
+
var INSTRUCTIONS = `Drives a running Tarve desktop app (native window, not a browser).
|
|
877
|
+
Start with inspect_tree (or screenshot) to see the UI; target nodes by visible text or by the ids it shows.
|
|
878
|
+
click, hover, type_text, press_key, scroll and drag go through native hit testing and wait for the next frame.
|
|
879
|
+
Coordinates are window logical px. get_logs shows console output and errors; get_events the app's native events; get_metrics performance.
|
|
880
|
+
Source edits hot-reload in dev mode; call reload after a crash or a closed window.`;
|
|
881
|
+
async function startServer(argv) {
|
|
882
|
+
const args = parseArgs(argv);
|
|
883
|
+
if (args.help) {
|
|
884
|
+
process.stderr.write(`${USAGE}
|
|
885
|
+
`);
|
|
886
|
+
return 0;
|
|
887
|
+
}
|
|
888
|
+
const session = new AppSession(resolveLaunch(args), { ...args.connectTimeoutMs ? { connectTimeoutMs: args.connectTimeoutMs } : {} });
|
|
889
|
+
process.once("exit", () => session.killNow());
|
|
890
|
+
const shutdown = () => {
|
|
891
|
+
void session.dispose().finally(() => process.exit(0));
|
|
892
|
+
};
|
|
893
|
+
process.once("SIGINT", shutdown);
|
|
894
|
+
process.once("SIGTERM", shutdown);
|
|
895
|
+
session.start().catch((error) => process.stderr.write(`[tarve-mcp] ${error instanceof Error ? error.message : String(error)}
|
|
896
|
+
`));
|
|
897
|
+
await serveStdio(createTools(session), { name: "tarve", version: VERSION, instructions: INSTRUCTIONS });
|
|
898
|
+
await session.dispose();
|
|
899
|
+
return 0;
|
|
900
|
+
}
|
|
901
|
+
export {
|
|
902
|
+
AppSession,
|
|
903
|
+
PROTOCOL_VERSIONS,
|
|
904
|
+
createHandler,
|
|
905
|
+
createTools,
|
|
906
|
+
findByText,
|
|
907
|
+
keyName,
|
|
908
|
+
outline,
|
|
909
|
+
parseArgs,
|
|
910
|
+
resolveLaunch,
|
|
911
|
+
serveStdio,
|
|
912
|
+
startServer,
|
|
913
|
+
textResult
|
|
914
|
+
};
|