@coreautomata/cli 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +34 -4
- package/dist/api.js +15 -2
- package/dist/cli.js +3 -0
- package/dist/commands/mcp.js +115 -0
- package/dist/commands/upload.js +4 -3
- package/dist/context.js +33 -1
- package/dist/mcp/proxy.js +308 -0
- package/dist/mcp/stdio.js +84 -0
- package/dist/mcp/uploadTool.js +277 -0
- package/dist/mcp/upstream.js +347 -0
- package/dist/plan.js +2 -0
- package/dist/version.js +4 -2
- package/package.json +2 -2
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The host side of ``coreautomata mcp``: newline-delimited JSON-RPC on stdin and
|
|
3
|
+
* stdout (the MCP stdio transport). stdout carries JSON-RPC frames and nothing else.
|
|
4
|
+
*/
|
|
5
|
+
export const PARSE_ERROR = -32700;
|
|
6
|
+
export const INVALID_REQUEST = -32600;
|
|
7
|
+
export const METHOD_NOT_FOUND = -32601;
|
|
8
|
+
export const INVALID_PARAMS = -32602;
|
|
9
|
+
export const INTERNAL_ERROR = -32603;
|
|
10
|
+
/** A host line longer than this is dropped and answered with a parse error. */
|
|
11
|
+
export const MAX_HOST_LINE_CHARS = 8 * 1024 * 1024;
|
|
12
|
+
export function isRecord(value) {
|
|
13
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
14
|
+
}
|
|
15
|
+
export function isJsonRpcId(value) {
|
|
16
|
+
return typeof value === "string" || (typeof value === "number" && Number.isFinite(value));
|
|
17
|
+
}
|
|
18
|
+
/** A response (``result`` or ``error``, no ``method``). */
|
|
19
|
+
export function isResponse(message) {
|
|
20
|
+
return ("result" in message || "error" in message) && !("method" in message);
|
|
21
|
+
}
|
|
22
|
+
export function rpcResult(id, result) {
|
|
23
|
+
return { jsonrpc: "2.0", id, result };
|
|
24
|
+
}
|
|
25
|
+
export function rpcError(id, code, message) {
|
|
26
|
+
return { jsonrpc: "2.0", id, error: { code, message } };
|
|
27
|
+
}
|
|
28
|
+
/** Writes one JSON-RPC frame per line. A closed stdout (the host went away) is ignored. */
|
|
29
|
+
export class FrameWriter {
|
|
30
|
+
sink;
|
|
31
|
+
constructor(sink) {
|
|
32
|
+
this.sink = sink;
|
|
33
|
+
}
|
|
34
|
+
send(message) {
|
|
35
|
+
try {
|
|
36
|
+
this.sink.write(`${JSON.stringify(message)}\n`);
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
/* the host closed stdout */
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Calls ``onLine`` for every line of ``source`` (without waiting for it) and resolves
|
|
45
|
+
* on end of input. A line over ``maxChars`` is skipped up to its newline and reported
|
|
46
|
+
* through ``onOversize``.
|
|
47
|
+
*/
|
|
48
|
+
export async function readLines(source, onLine, onOversize, maxChars = MAX_HOST_LINE_CHARS) {
|
|
49
|
+
const decoder = new TextDecoder();
|
|
50
|
+
let pending = "";
|
|
51
|
+
let skipping = false;
|
|
52
|
+
const take = (text) => {
|
|
53
|
+
let start = 0;
|
|
54
|
+
for (;;) {
|
|
55
|
+
const nl = text.indexOf("\n", start);
|
|
56
|
+
if (nl < 0)
|
|
57
|
+
break;
|
|
58
|
+
const piece = text.slice(start, nl);
|
|
59
|
+
start = nl + 1;
|
|
60
|
+
if (skipping) {
|
|
61
|
+
skipping = false;
|
|
62
|
+
pending = "";
|
|
63
|
+
continue;
|
|
64
|
+
}
|
|
65
|
+
const line = (pending + piece).replace(/\r$/, "");
|
|
66
|
+
pending = "";
|
|
67
|
+
onLine(line);
|
|
68
|
+
}
|
|
69
|
+
if (skipping)
|
|
70
|
+
return;
|
|
71
|
+
pending += text.slice(start);
|
|
72
|
+
if (pending.length > maxChars) {
|
|
73
|
+
pending = "";
|
|
74
|
+
skipping = true;
|
|
75
|
+
onOversize();
|
|
76
|
+
}
|
|
77
|
+
};
|
|
78
|
+
for await (const chunk of source) {
|
|
79
|
+
take(typeof chunk === "string" ? chunk : decoder.decode(chunk, { stream: true }));
|
|
80
|
+
}
|
|
81
|
+
take(decoder.decode());
|
|
82
|
+
if (!skipping && pending.trim())
|
|
83
|
+
onLine(pending.replace(/\r$/, ""));
|
|
84
|
+
}
|
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ``upload_build``: the one tool ``coreautomata mcp`` answers itself. It uploads a
|
|
3
|
+
* build file from this machine (the remote server cannot read local files) as an
|
|
4
|
+
* ordinary v1 upload, so the result is the same build object ``get_build`` returns.
|
|
5
|
+
*/
|
|
6
|
+
import { createHash } from "node:crypto";
|
|
7
|
+
import { realpath } from "node:fs/promises";
|
|
8
|
+
import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
|
|
9
|
+
import { ApiClient } from "../api.js";
|
|
10
|
+
import { DEFAULT_MAX_UPLOAD_MB } from "../config.js";
|
|
11
|
+
import { ApiError, UsageError } from "../errors.js";
|
|
12
|
+
import { safeLine } from "../text.js";
|
|
13
|
+
import { validateId } from "../commands/shared.js";
|
|
14
|
+
import { uploadBuild, validateBuildFile, validateCarryFrom, waitAnalyzed } from "../commands/upload.js";
|
|
15
|
+
import { MCP_CLIENT_HEADER_VALUE } from "../version.js";
|
|
16
|
+
import { abortableSleep, RequestCancelled } from "./upstream.js";
|
|
17
|
+
export const UPLOAD_TOOL_NAME = "upload_build";
|
|
18
|
+
export const DEDUPE_TTL_MS = 10 * 60_000;
|
|
19
|
+
export const MAX_WAIT_SECONDS = 600;
|
|
20
|
+
const ID_PATTERN = "^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$";
|
|
21
|
+
export const UPLOAD_TOOL = {
|
|
22
|
+
name: UPLOAD_TOOL_NAME,
|
|
23
|
+
title: "Upload build",
|
|
24
|
+
description: "Upload a local .apk, .xapk or .ipa from this machine as a new build of a CoreAutomata project. " +
|
|
25
|
+
"The file must be inside the folder the MCP server started in (unless that is / or the home folder) or a folder passed with --allow-path. " +
|
|
26
|
+
"Cases and the app map are carried from the latest build unless carry_from says otherwise. " +
|
|
27
|
+
"Uploads do not analyse the app; analysis_state stays 'uploaded' until a device discovery runs on the Board (next_step says so). " +
|
|
28
|
+
"Uploading the same file to the same project again within 10 minutes returns the first build with replayed: true unless force is true.",
|
|
29
|
+
inputSchema: {
|
|
30
|
+
type: "object",
|
|
31
|
+
properties: {
|
|
32
|
+
path: {
|
|
33
|
+
type: "string",
|
|
34
|
+
minLength: 1,
|
|
35
|
+
maxLength: 4096,
|
|
36
|
+
description: "Path to the .apk, .xapk or .ipa file (absolute, or relative to the folder the server started in).",
|
|
37
|
+
},
|
|
38
|
+
project_id: { type: "string", pattern: ID_PATTERN, description: "Project id (from list_projects)." },
|
|
39
|
+
carry_from: {
|
|
40
|
+
type: "string",
|
|
41
|
+
default: "latest",
|
|
42
|
+
maxLength: 64,
|
|
43
|
+
description: "latest (default), none, or a build id to copy cases and the app map from.",
|
|
44
|
+
},
|
|
45
|
+
wait_seconds: {
|
|
46
|
+
type: "integer",
|
|
47
|
+
minimum: 0,
|
|
48
|
+
maximum: MAX_WAIT_SECONDS,
|
|
49
|
+
default: 0,
|
|
50
|
+
description: "Wait up to this long while the build is being discovered (0 returns at once).",
|
|
51
|
+
},
|
|
52
|
+
force: {
|
|
53
|
+
type: "boolean",
|
|
54
|
+
default: false,
|
|
55
|
+
description: "Upload again even if the same file was uploaded to this project in the last 10 minutes.",
|
|
56
|
+
},
|
|
57
|
+
},
|
|
58
|
+
required: ["path", "project_id"],
|
|
59
|
+
additionalProperties: false,
|
|
60
|
+
},
|
|
61
|
+
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
|
|
62
|
+
};
|
|
63
|
+
/** Local error codes and the HTTP-like status reported with them. */
|
|
64
|
+
const LOCAL_STATUS = {
|
|
65
|
+
API_KEY_MISSING: 401,
|
|
66
|
+
INVALID_ARGUMENT: 422,
|
|
67
|
+
PATH_NOT_ALLOWED: 403,
|
|
68
|
+
UPLOAD_INVALID: 422,
|
|
69
|
+
UPLOAD_TOO_LARGE: 413,
|
|
70
|
+
};
|
|
71
|
+
export function toolError(code, message, status) {
|
|
72
|
+
const error = { code, message, status: status ?? LOCAL_STATUS[code] ?? 0 };
|
|
73
|
+
return { content: [{ type: "text", text: JSON.stringify({ error }) }], isError: true };
|
|
74
|
+
}
|
|
75
|
+
class ToolFailure extends Error {
|
|
76
|
+
code;
|
|
77
|
+
constructor(code, message) {
|
|
78
|
+
super(message);
|
|
79
|
+
this.code = code;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
function parseArgs(raw) {
|
|
83
|
+
if (raw === undefined || raw === null)
|
|
84
|
+
raw = {};
|
|
85
|
+
if (typeof raw !== "object" || Array.isArray(raw))
|
|
86
|
+
throw new ToolFailure("INVALID_ARGUMENT", "arguments must be an object.");
|
|
87
|
+
const args = raw;
|
|
88
|
+
const known = new Set(Object.keys(UPLOAD_TOOL.inputSchema.properties));
|
|
89
|
+
const extra = Object.keys(args).filter((k) => !known.has(k));
|
|
90
|
+
if (extra.length)
|
|
91
|
+
throw new ToolFailure("INVALID_ARGUMENT", `Unknown argument: ${safeLine(extra[0], 64)}.`);
|
|
92
|
+
const { path, project_id, carry_from = "latest", wait_seconds = 0, force = false } = args;
|
|
93
|
+
if (typeof path !== "string" || path.length < 1 || path.length > 4096 || path.includes("\0")) {
|
|
94
|
+
throw new ToolFailure("INVALID_ARGUMENT", "path must be a file path of 1 to 4096 characters.");
|
|
95
|
+
}
|
|
96
|
+
if (typeof project_id !== "string" || !new RegExp(ID_PATTERN).test(project_id)) {
|
|
97
|
+
throw new ToolFailure("INVALID_ARGUMENT", "project_id must be a project id (letters, digits, '-', '_', '.', ':').");
|
|
98
|
+
}
|
|
99
|
+
if (typeof carry_from !== "string")
|
|
100
|
+
throw new ToolFailure("INVALID_ARGUMENT", "carry_from must be latest, none or a build id.");
|
|
101
|
+
let carry;
|
|
102
|
+
try {
|
|
103
|
+
carry = validateCarryFrom(carry_from);
|
|
104
|
+
}
|
|
105
|
+
catch {
|
|
106
|
+
throw new ToolFailure("INVALID_ARGUMENT", "carry_from must be latest, none or a build id of at most 64 characters.");
|
|
107
|
+
}
|
|
108
|
+
if (typeof wait_seconds !== "number" || !Number.isInteger(wait_seconds) || wait_seconds < 0 || wait_seconds > MAX_WAIT_SECONDS) {
|
|
109
|
+
throw new ToolFailure("INVALID_ARGUMENT", `wait_seconds must be a whole number from 0 to ${MAX_WAIT_SECONDS}.`);
|
|
110
|
+
}
|
|
111
|
+
if (typeof force !== "boolean")
|
|
112
|
+
throw new ToolFailure("INVALID_ARGUMENT", "force must be true or false.");
|
|
113
|
+
return { path, project_id: validateId(project_id, "project_id"), carry_from: carry, wait_seconds, force };
|
|
114
|
+
}
|
|
115
|
+
/** True when ``real`` is strictly inside ``root`` (both already resolved). */
|
|
116
|
+
export function isInside(root, real) {
|
|
117
|
+
const rel = relative(root, real);
|
|
118
|
+
return rel !== "" && !rel.startsWith("..") && !isAbsolute(rel);
|
|
119
|
+
}
|
|
120
|
+
export class UploadTool {
|
|
121
|
+
opts;
|
|
122
|
+
cache = new Map();
|
|
123
|
+
constructor(opts) {
|
|
124
|
+
this.opts = opts;
|
|
125
|
+
}
|
|
126
|
+
async call(rawArgs, signal) {
|
|
127
|
+
try {
|
|
128
|
+
return await this.run(rawArgs, signal);
|
|
129
|
+
}
|
|
130
|
+
catch (err) {
|
|
131
|
+
if (signal.aborted || err instanceof RequestCancelled)
|
|
132
|
+
throw new RequestCancelled();
|
|
133
|
+
if (err instanceof ToolFailure)
|
|
134
|
+
return toolError(err.code, err.message);
|
|
135
|
+
if (err instanceof ApiError)
|
|
136
|
+
return toolError(err.code, err.message, err.status);
|
|
137
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
138
|
+
this.opts.log(`upload_build failed: ${message}`);
|
|
139
|
+
return toolError("UPLOAD_FAILED", "The upload failed on this machine; see the MCP server log.", 0);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
async run(rawArgs, signal) {
|
|
143
|
+
const { deps, apiKey } = this.opts;
|
|
144
|
+
if (!apiKey)
|
|
145
|
+
throw new ToolFailure("API_KEY_MISSING", "set COREAUTOMATA_API_KEY");
|
|
146
|
+
const args = parseArgs(rawArgs);
|
|
147
|
+
// (1) D20: the resolved path must be strictly inside a resolved root.
|
|
148
|
+
const real = await this.resolveAllowed(args.path);
|
|
149
|
+
// (2) Every CLI upload check, on the resolved path.
|
|
150
|
+
let file;
|
|
151
|
+
try {
|
|
152
|
+
file = await validateBuildFile(deps.files, real, this.opts.maxUploadMb ?? DEFAULT_MAX_UPLOAD_MB);
|
|
153
|
+
}
|
|
154
|
+
catch (err) {
|
|
155
|
+
if (err instanceof UsageError) {
|
|
156
|
+
const code = /upload limit is/.test(err.message) ? "UPLOAD_TOO_LARGE" : "UPLOAD_INVALID";
|
|
157
|
+
throw new ToolFailure(code, err.message);
|
|
158
|
+
}
|
|
159
|
+
throw err;
|
|
160
|
+
}
|
|
161
|
+
// (3) Open it once (the handle pins the inode), make sure it is still the file
|
|
162
|
+
// that was checked, and read it through that handle only: the hash and the
|
|
163
|
+
// upload are the same bytes, whatever happens to the path afterwards.
|
|
164
|
+
const changed = () => new ToolFailure("UPLOAD_INVALID", `${file.name} changed while it was being checked.`);
|
|
165
|
+
let opened;
|
|
166
|
+
try {
|
|
167
|
+
opened = await deps.files.openNoFollow(real);
|
|
168
|
+
}
|
|
169
|
+
catch {
|
|
170
|
+
throw changed();
|
|
171
|
+
}
|
|
172
|
+
let bytes;
|
|
173
|
+
try {
|
|
174
|
+
const again = opened.stat;
|
|
175
|
+
if (!again.isFile() ||
|
|
176
|
+
again.size !== file.size ||
|
|
177
|
+
String(again.ino) !== String(file.ino) ||
|
|
178
|
+
String(again.dev) !== String(file.dev)) {
|
|
179
|
+
throw changed();
|
|
180
|
+
}
|
|
181
|
+
bytes = await opened.readAll();
|
|
182
|
+
}
|
|
183
|
+
finally {
|
|
184
|
+
await opened.close().catch(() => { });
|
|
185
|
+
}
|
|
186
|
+
if (bytes.length !== file.size)
|
|
187
|
+
throw changed();
|
|
188
|
+
// (4) Dedupe: the same content to the same project and carry source.
|
|
189
|
+
const digest = createHash("sha256").update(bytes).digest("hex");
|
|
190
|
+
const blob = new Blob([bytes]);
|
|
191
|
+
const cacheKey = `${digest}:${args.project_id}:${args.carry_from}`;
|
|
192
|
+
const now = deps.rt.now();
|
|
193
|
+
for (const [key, entry] of this.cache)
|
|
194
|
+
if (now - entry.at > DEDUPE_TTL_MS)
|
|
195
|
+
this.cache.delete(key);
|
|
196
|
+
const hit = this.cache.get(cacheKey);
|
|
197
|
+
if (hit && !args.force)
|
|
198
|
+
return toResult({ ...hit.result, replayed: true });
|
|
199
|
+
if (signal.aborted)
|
|
200
|
+
throw new RequestCancelled();
|
|
201
|
+
// (5) Upload, then optionally wait (progress goes to stderr only).
|
|
202
|
+
const ctx = this.ctx(apiKey, signal);
|
|
203
|
+
this.opts.log(`Uploading ${safeLine(file.name, 200)} (${Math.ceil(file.size / 1048576)} MB) to project ${args.project_id}…`);
|
|
204
|
+
let build = await uploadBuild(ctx, file, args.project_id, args.carry_from, { blob, signal });
|
|
205
|
+
// Cached as soon as it exists, so a retry after a failed wait does not upload twice.
|
|
206
|
+
this.cache.set(cacheKey, { at: deps.rt.now(), result: buildResult(build, 0) });
|
|
207
|
+
let waited = 0;
|
|
208
|
+
if (args.wait_seconds > 0) {
|
|
209
|
+
const started = deps.rt.now();
|
|
210
|
+
this.opts.log(`Waiting up to ${args.wait_seconds}s for build ${safeLine(build.build_id, 64)} (${safeLine(build.analysis_state, 16)}).`);
|
|
211
|
+
try {
|
|
212
|
+
({ build } = await waitAnalyzed(ctx, build, args.project_id, args.wait_seconds));
|
|
213
|
+
}
|
|
214
|
+
catch (err) {
|
|
215
|
+
if (!(err instanceof ApiError))
|
|
216
|
+
throw err;
|
|
217
|
+
this.opts.log(`Stopped waiting for build ${safeLine(build.build_id, 64)}: ${err.code}.`);
|
|
218
|
+
}
|
|
219
|
+
waited = Math.round((deps.rt.now() - started) / 1000);
|
|
220
|
+
}
|
|
221
|
+
const result = buildResult(build, waited);
|
|
222
|
+
this.cache.set(cacheKey, { at: deps.rt.now(), result });
|
|
223
|
+
return toResult(result);
|
|
224
|
+
}
|
|
225
|
+
async resolveAllowed(path) {
|
|
226
|
+
const { roots, cwd } = this.opts;
|
|
227
|
+
const resolveReal = this.opts.realpath ?? realpath;
|
|
228
|
+
const lexical = resolve(cwd, path);
|
|
229
|
+
let real;
|
|
230
|
+
try {
|
|
231
|
+
real = await resolveReal(lexical);
|
|
232
|
+
}
|
|
233
|
+
catch {
|
|
234
|
+
// Say "no such file" only for paths that would have been allowed.
|
|
235
|
+
const parent = await resolveReal(dirname(lexical)).catch(() => null);
|
|
236
|
+
if (parent && roots.some((root) => isInside(root, join(parent, basename(lexical))))) {
|
|
237
|
+
throw new ToolFailure("UPLOAD_INVALID", `Cannot read ${safeLine(path, 200)}: no such file.`);
|
|
238
|
+
}
|
|
239
|
+
throw new ToolFailure("PATH_NOT_ALLOWED", notAllowed(path));
|
|
240
|
+
}
|
|
241
|
+
if (!roots.some((root) => isInside(root, real)))
|
|
242
|
+
throw new ToolFailure("PATH_NOT_ALLOWED", notAllowed(path));
|
|
243
|
+
return real;
|
|
244
|
+
}
|
|
245
|
+
ctx(apiKey, signal) {
|
|
246
|
+
const { deps, apiBase, log } = this.opts;
|
|
247
|
+
// Retry waits and build polls stop when the host cancels.
|
|
248
|
+
const rt = { ...deps.rt, sleep: (ms) => abortableSleep(deps.rt, ms, signal) };
|
|
249
|
+
const client = new ApiClient({ apiBase, apiKey }, rt, { log, clientHeader: MCP_CLIENT_HEADER_VALUE });
|
|
250
|
+
return { ...deps, rt, client, gha: false, line: (value, maxLen = 300) => safeLine(value, maxLen) };
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
function notAllowed(path) {
|
|
254
|
+
return (`${safeLine(path, 200)} is outside the folders this MCP server may read. ` +
|
|
255
|
+
"Move the build into the project folder, or restart the server with --allow-path <dir>.");
|
|
256
|
+
}
|
|
257
|
+
function buildResult(build, waited) {
|
|
258
|
+
return {
|
|
259
|
+
build_id: build.build_id,
|
|
260
|
+
project_id: build.project_id ?? null,
|
|
261
|
+
platform: build.platform ?? null,
|
|
262
|
+
package_id: build.package_id ?? null,
|
|
263
|
+
status: build.status,
|
|
264
|
+
analysis_state: build.analysis_state,
|
|
265
|
+
case_count: build.case_count,
|
|
266
|
+
app_map_source: build.app_map_source,
|
|
267
|
+
carried_from_build_id: build.carried_from_build_id ?? null,
|
|
268
|
+
next_step: build.next_step ?? null,
|
|
269
|
+
board_url: build.board_url ?? null,
|
|
270
|
+
waited_seconds: waited,
|
|
271
|
+
replayed: false,
|
|
272
|
+
};
|
|
273
|
+
}
|
|
274
|
+
function toResult(result) {
|
|
275
|
+
const structured = result;
|
|
276
|
+
return { content: [{ type: "text", text: JSON.stringify(structured) }], structuredContent: structured };
|
|
277
|
+
}
|