@devicecloud.dev/dcd 5.14.0 → 5.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +4 -2
  2. package/dist/commands/artifacts.d.ts +13 -0
  3. package/dist/commands/artifacts.js +43 -5
  4. package/dist/commands/cloud.d.ts +1 -1
  5. package/dist/commands/cloud.js +2 -2
  6. package/dist/commands/device.d.ts +39 -0
  7. package/dist/commands/device.js +479 -101
  8. package/dist/commands/live.js +1 -1
  9. package/dist/config/flags/device.flags.d.ts +1 -1
  10. package/dist/config/flags/device.flags.js +1 -1
  11. package/dist/constants.d.ts +1 -1
  12. package/dist/gateways/api-gateway.d.ts +25 -3
  13. package/dist/gateways/api-gateway.js +68 -6
  14. package/dist/gateways/device-gateway.d.ts +34 -10
  15. package/dist/gateways/device-gateway.js +72 -17
  16. package/dist/mcp/bridge.d.ts +30 -16
  17. package/dist/mcp/bridge.js +201 -64
  18. package/dist/mcp/local-files.d.ts +14 -0
  19. package/dist/mcp/local-files.js +75 -0
  20. package/dist/mcp/tools/download-artifacts.d.ts +4 -1
  21. package/dist/mcp/tools/download-artifacts.js +44 -17
  22. package/dist/services/report-download.service.d.ts +32 -0
  23. package/dist/services/report-download.service.js +51 -2
  24. package/dist/services/telemetry.service.d.ts +20 -1
  25. package/dist/services/telemetry.service.js +27 -6
  26. package/dist/types/domain/device-session.types.d.ts +73 -3
  27. package/dist/types/domain/device-session.types.js +2 -0
  28. package/dist/utils/api-url.d.ts +20 -0
  29. package/dist/utils/api-url.js +49 -0
  30. package/dist/utils/app-upload.d.ts +6 -0
  31. package/dist/utils/app-upload.js +19 -0
  32. package/dist/utils/config-store.d.ts +5 -1
  33. package/dist/utils/config-store.js +18 -2
  34. package/dist/utils/device-artifacts.d.ts +5 -0
  35. package/dist/utils/device-artifacts.js +22 -0
  36. package/dist/utils/device-bundle.d.ts +39 -9
  37. package/dist/utils/device-bundle.js +153 -51
  38. package/dist/utils/device-flags.d.ts +17 -0
  39. package/dist/utils/device-flags.js +145 -0
  40. package/dist/utils/device-output.d.ts +53 -7
  41. package/dist/utils/device-output.js +148 -21
  42. package/dist/utils/device-run.d.ts +8 -3
  43. package/dist/utils/device-run.js +85 -8
  44. package/dist/utils/zip-integrity.d.ts +21 -0
  45. package/dist/utils/zip-integrity.js +45 -0
  46. package/package.json +3 -2
@@ -5,9 +5,10 @@
5
5
  * runs (createServer), reached over an in-memory transport.
6
6
  * - The device tools, proxied from the hosted endpoint at `<api>/mcp`, so
7
7
  * they are defined (and contract-tested) once, in the API. The bridge adds
8
- * what a remote server can't do: `install_app` takes a local `app_path`,
9
- * and `run` takes a local `path` (a flow file, or a directory uploaded as
10
- * a bundle).
8
+ * what a remote server can't do: `start_device` and `install_app` take a
9
+ * local `app_path`, and `run` takes a local `path` (a flow file, or a
10
+ * directory uploaded as a bundle), which must be inside the working
11
+ * directory (local-files.ts).
11
12
  *
12
13
  * Auth is the CLI's: an API key or a `dcd login` session (getContext). The
13
14
  * hosted endpoint accepts both. A session is renewed before it expires; the
@@ -15,22 +16,25 @@
15
16
  *
16
17
  * stdout is the JSON-RPC channel: everything else goes to stderr.
17
18
  */
19
+ import { randomBytes } from 'node:crypto';
20
+ import { realpathSync } from 'node:fs';
18
21
  import { readFile, stat } from 'node:fs/promises';
19
- import * as path from 'node:path';
20
22
  import { Client } from '@modelcontextprotocol/sdk/client/index.js';
21
23
  import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
22
24
  import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
23
25
  import { Server } from '@modelcontextprotocol/sdk/server/index.js';
24
26
  import { CallToolRequestSchema, ListToolsRequestSchema, } from '@modelcontextprotocol/sdk/types.js';
25
27
  import { DeviceGateway, START_RECOVERY_WINDOW_MS } from '../gateways/device-gateway.js';
26
- import { processDependencies, readTestYamlFileAsJson } from '../services/execution-plan.utils.js';
27
- import { computeCommonRoot } from '../services/flow-paths.js';
28
28
  import { uploadLocalApp } from '../utils/app-upload.js';
29
29
  import { getCliVersion } from '../utils/cli.js';
30
- import { uploadFlowBundle } from '../utils/device-bundle.js';
30
+ import { downloadFile } from '../utils/device-artifacts.js';
31
+ import { bundlePath, flowFileBundle, uploadFlowBundle } from '../utils/device-bundle.js';
31
32
  import { getContext, isReadOnly, logStderr } from './context.js';
32
33
  import { errorResult, runTool } from './helpers.js';
34
+ import { isInside, localInput, localOutput, markWritten, workingDirectory } from './local-files.js';
33
35
  import { createServer } from './server.js';
36
+ // Moved to utils/device-bundle.ts, where `dcd device run` uses it too.
37
+ export { flowFileBundle } from '../utils/device-bundle.js';
34
38
  /*
35
39
  * Sent at initialize, before this server knows which hosted tools the
36
40
  * account has: the hosted server only serves its tools to organizations that
@@ -38,6 +42,14 @@ import { createServer } from './server.js';
38
42
  * themselves in their own descriptions.
39
43
  */
40
44
  const INSTRUCTIONS = 'DeviceCloud tools. dcd_* tools run Maestro test suites in the cloud: dcd_list_devices shows what you can test on, dcd_run_cloud_test submits flows (billable), and dcd_get_status follows a run. dcd_get_team_settings reads the team settings and limits. Any other tools describe their own use. Where a tool takes a path to a local file (an app build, a flow file or a directory), this server uploads it for you.';
45
+ /** The header the API reads a connection's name from. */
46
+ export const CLIENT_INSTANCE_HEADER = 'x-dcd-client-instance';
47
+ /**
48
+ * This process's name for its connection to the hosted tools, the same for
49
+ * as long as it runs: one `dcd mcp` is one agent's connection, and a
50
+ * reconnect must not make its sessions someone else's.
51
+ */
52
+ export const BRIDGE_INSTANCE = `dcd-mcp-${randomBytes(8).toString('hex')}`;
41
53
  /**
42
54
  * How long one forwarded call may take. Longer than dcd_run_cloud_test's
43
55
  * longest wait (3600s) plus an upload. The MCP client calling this server
@@ -47,25 +59,45 @@ export const CALL_TIMEOUT_MS = 2 * 60 * 60 * 1000;
47
59
  const READ_ONLY_INSTRUCTIONS = 'DeviceCloud tools, read-only: nothing here runs a test or changes anything. dcd_* tools read cloud test runs and their results, and the team settings. Any other tools describe their own use.';
48
60
  /** The inputs this bridge adds to hosted tools, and what they say. */
49
61
  const LOCAL_INPUTS = {
62
+ start_device: {
63
+ description: ' Or pass app_path, a build on this machine (.apk, or a simulator .app / .zip / Expo .tar.gz) inside the working directory this server runs in: it is uploaded before the session starts, so no device time is spent on the upload.',
64
+ properties: {
65
+ app_path: {
66
+ type: 'string',
67
+ description: 'A build on this machine to upload and install when the device is ready, relative to the working directory or inside it. Pass this or app_binary_id.',
68
+ },
69
+ },
70
+ },
50
71
  install_app: {
51
- description: ' Or pass app_path, a build on this machine (.apk, or a simulator .app / .zip / Expo .tar.gz), which is uploaded first.',
72
+ description: ' Or pass app_path, a build on this machine (.apk, or a simulator .app / .zip / Expo .tar.gz) inside the working directory this server runs in, which is uploaded first.',
52
73
  properties: {
53
74
  app_path: {
54
75
  type: 'string',
55
- description: 'A build on this machine to upload and install. Pass this, app_binary_id or app_url.',
76
+ description: 'A build on this machine to upload and install, relative to the working directory or inside it. Pass this, app_binary_id or app_url.',
77
+ },
78
+ },
79
+ },
80
+ take_screenshot: {
81
+ description: ' With full_size, also pass path to save the PNG on this machine, inside the working directory this server runs in.',
82
+ properties: {
83
+ path: {
84
+ type: 'string',
85
+ description: 'Where to save the full-size PNG, relative to the working directory or inside it. Only with full_size: true. Not over a file this server did not write.',
56
86
  },
57
87
  },
58
88
  },
59
89
  run: {
60
- description: ' Or pass path: a flow file on this machine, or a directory of flows (flow picks the entry file inside it). A file that uses other files (runFlow, runScript, addMedia and the like) is uploaded with its folder; one that uses none is sent as yaml. Only the YAML files and the files the flows use (scripts, media) are uploaded, not builds or anything else in the directory.',
90
+ description: ' Or pass path: a flow file (.yaml or .yml) on this machine, or a directory of flows (flow picks the entry file inside it), inside the working directory this server runs in. A file that uses other files (runFlow, runScript, addMedia and the like) is uploaded with them; one that uses none is sent as yaml. Only the flows and the files they use (scripts, media) are uploaded, not builds or anything else in the directory.',
61
91
  properties: {
62
92
  path: {
63
93
  type: 'string',
64
- description: 'A local flow file, or a directory of flows. Pass this, yaml or flow_upload_id.',
94
+ description: 'A flow file or a directory of flows, relative to the working directory or inside it. Pass this, yaml or flow_upload_id.',
65
95
  },
66
96
  },
67
97
  },
68
98
  };
99
+ /** A flow file the device runs. */
100
+ const FLOW_FILE = /\.ya?ml$/i;
69
101
  /** A hosted tool with this bridge's local inputs added. */
70
102
  export function withLocalInputs(tool) {
71
103
  const extra = LOCAL_INPUTS[tool.name];
@@ -80,71 +112,111 @@ export function withLocalInputs(tool) {
80
112
  },
81
113
  };
82
114
  }
83
- /**
84
- * For a single flow file that uses other files (runFlow, runScript, addMedia
85
- * and the like): the folder to upload as a bundle, and the file's path
86
- * inside it. Sent as yaml on its own, the flow would fail on the device with
87
- * an invalid file path, because the files it uses would not be there. Null
88
- * when the flow uses no other files, or can't be read (the device reports
89
- * that itself).
90
- */
91
- export function flowFileBundle(file) {
92
- const absolute = path.resolve(file);
93
- let deps;
94
- try {
95
- const { config, testSteps } = readTestYamlFileAsJson(absolute);
96
- deps = processDependencies({ config, input: absolute, testSteps });
97
- }
98
- catch {
99
- return null;
100
- }
101
- // A missing file goes this way too, so the upload names it.
102
- if (deps.allFiles.length === 0 && deps.allErrors.length === 0)
103
- return null;
104
- const dir = computeCommonRoot([absolute], deps.allFiles) || path.dirname(absolute);
105
- return { dir, entry: path.relative(dir, absolute) };
106
- }
107
115
  /**
108
116
  * Do the local part of a call (uploads, reading a file) and return the
109
117
  * arguments the hosted tool takes.
110
118
  */
111
- export async function resolveLocalInputs(name, args, ctx) {
112
- if (name === 'install_app' && typeof args.app_path === 'string') {
119
+ export async function resolveLocalInputs(name, args, ctx, root = workingDirectory()) {
120
+ if ((name === 'install_app' || name === 'start_device') && typeof args.app_path === 'string') {
113
121
  const { app_path: filePath, ...rest } = args;
114
- logStderr(`Uploading ${filePath}…`);
122
+ if (rest.app_binary_id !== undefined || rest.app_url !== undefined) {
123
+ throw new Error('Pass app_path or app_binary_id (or app_url), not both.');
124
+ }
125
+ // Only inside the working directory, as run's path: an agent's call is
126
+ // not the user typing a path (local-files.ts), and a build from anywhere
127
+ // on disk would be uploaded to the team's storage.
128
+ const appFile = localInput(filePath, root);
129
+ logStderr(`Uploading ${appFile}…`);
115
130
  const binaryId = await uploadLocalApp({
116
131
  ...ctx,
117
- filePath: filePath,
132
+ filePath: appFile,
118
133
  log: logStderr,
119
134
  showProgress: false,
120
135
  });
121
136
  return { ...rest, app_binary_id: binaryId };
122
137
  }
138
+ if (name === 'take_screenshot' && args.path !== undefined) {
139
+ // The hosted tool takes no path: the bridge saves the file
140
+ // (saveFullScreenshot) once the link comes back.
141
+ const { path: _saveTo, ...rest } = args;
142
+ return rest;
143
+ }
123
144
  if (name === 'run' && typeof args.path === 'string') {
124
- const { path: flowPath, ...rest } = args;
125
- const info = await stat(flowPath).catch(() => null);
126
- if (!info)
127
- throw new Error(`No such file or directory: ${flowPath}`);
145
+ const { path: given, ...rest } = args;
146
+ // Only inside the working directory: an agent's call is not the user
147
+ // typing a path (local-files.ts).
148
+ const flowPath = localInput(given, root);
149
+ const info = await stat(flowPath);
150
+ // The API takes forward slashes; a path typed on Windows has backslashes.
151
+ const entry = typeof rest.flow === 'string' ? rest.flow.replaceAll('\\', '/') : undefined;
128
152
  if (info.isDirectory()) {
129
153
  logStderr(`Uploading the flows in ${flowPath}…`);
130
- const bundle = await uploadFlowBundle({
131
- ...ctx,
132
- dir: flowPath,
133
- entry: typeof rest.flow === 'string' ? rest.flow : undefined,
134
- log: logStderr,
135
- });
136
- return { ...rest, flow_upload_id: bundle.id };
154
+ const bundle = await uploadFlowBundle({ ...ctx, confineTo: root, dir: flowPath, entry, log: logStderr });
155
+ return { ...rest, ...(entry !== undefined && { flow: entry }), flow_upload_id: bundle.id };
156
+ }
157
+ if (!FLOW_FILE.test(flowPath)) {
158
+ throw new Error(`${given} is not a flow file: path takes a .yaml or .yml file, or a directory of flows.`);
137
159
  }
138
160
  const bundled = flowFileBundle(flowPath);
139
161
  if (bundled) {
140
- logStderr(`${flowPath} uses other files; uploading it with ${bundled.dir}…`);
141
- const bundle = await uploadFlowBundle({ ...ctx, ...bundled, log: logStderr });
142
- return { ...rest, flow: bundled.entry, flow_upload_id: bundle.id };
162
+ // The files it uses go too, so they must be inside as well.
163
+ if (!isInside(realpathSync(bundled.dir), root)) {
164
+ throw new Error(`${given} uses files outside the working directory (${root}). This server uploads only from there: start it in a folder that holds the flow and every file it uses.`);
165
+ }
166
+ logStderr(`${given} uses other files; uploading it with them, from ${bundled.dir}…`);
167
+ const bundle = await uploadFlowBundle({ ...ctx, ...bundled, confineTo: root, log: logStderr });
168
+ return { ...rest, flow: bundlePath(bundled.entry), flow_upload_id: bundle.id };
143
169
  }
144
170
  return { ...rest, yaml: await readFile(flowPath, 'utf8') };
145
171
  }
146
172
  return args;
147
173
  }
174
+ /**
175
+ * Where a take_screenshot call asks for the full-size PNG to be saved, checked
176
+ * before the call is made: inside the working directory, not over a file this
177
+ * server did not write. Null when it asks for no file.
178
+ */
179
+ export function screenshotTarget(args, root = workingDirectory()) {
180
+ if (args.path === undefined)
181
+ return null;
182
+ if (typeof args.path !== 'string' || args.path.trim() === '') {
183
+ throw new Error('path is where to save the full-size PNG, a file name inside the working directory.');
184
+ }
185
+ if (args.full_size !== true) {
186
+ throw new Error('path saves a full-size screenshot: pass full_size: true with it.');
187
+ }
188
+ return localOutput(args.path, root);
189
+ }
190
+ /**
191
+ * Save the full-size PNG a take_screenshot call linked to, and say so in its
192
+ * result. The link stays in the result whatever happens here: a download
193
+ * that fails says why, and the agent can still use the link.
194
+ */
195
+ export async function saveFullScreenshot(result, target, download = downloadFile) {
196
+ if (result.isError)
197
+ return result;
198
+ const note = (text) => ({ ...result, content: [...result.content, { type: 'text', text }] });
199
+ const first = result.content.find((c) => c.type === 'text');
200
+ let url;
201
+ try {
202
+ url = JSON.parse(first && first.type === 'text' ? first.text : '{}')
203
+ .full_size?.url;
204
+ }
205
+ catch {
206
+ url = undefined;
207
+ }
208
+ if (typeof url !== 'string' || !/^https?:\/\//.test(url)) {
209
+ return note('Not saved: the answer had no link to a full-size screenshot.');
210
+ }
211
+ try {
212
+ await download(url, target);
213
+ }
214
+ catch (error) {
215
+ return note(`Not saved to ${target}: ${error instanceof Error ? error.message : String(error)}. The link above still works for an hour.`);
216
+ }
217
+ markWritten(target);
218
+ return note(`Saved to ${target}.`);
219
+ }
148
220
  /**
149
221
  * What to tell the agent when a start_device call failed without an answer
150
222
  * (the connection dropped, or the server never replied). The request may
@@ -182,6 +254,8 @@ export async function explainFailedStart(message, ctx, now = Date.now()) {
182
254
  class RemoteDevices {
183
255
  connecting = null;
184
256
  tools = null;
257
+ /** Why the last listing gave no device tools, while it did not. */
258
+ unavailable = null;
185
259
  /** Calls that arrive together share one connect. A failed one is retried by the next call. */
186
260
  connect() {
187
261
  this.connecting ??= this.open().catch((error) => {
@@ -203,18 +277,38 @@ class RemoteDevices {
203
277
  const headers = new Headers(init?.headers);
204
278
  for (const [key, value] of Object.entries(auth.headers))
205
279
  headers.set(key, value);
280
+ // This process, by name: the sessions it starts are its own
281
+ // (started_by.this_client), and a call that names no session takes
282
+ // one of them, never a session another process started.
283
+ headers.set(CLIENT_INSTANCE_HEADER, BRIDGE_INSTANCE);
206
284
  return fetch(url, { ...init, headers });
207
285
  },
208
286
  }));
209
287
  return client;
210
288
  }
289
+ /**
290
+ * The hosted device tools. A list that came back empty is not kept, nor is
291
+ * a failure: the next call asks again, so signing in or the organization
292
+ * being enabled later is picked up without a restart.
293
+ */
211
294
  async list() {
212
295
  if (this.tools)
213
296
  return this.tools;
214
- const client = await this.connect();
215
- const { tools } = await client.listTools();
216
- this.tools = tools;
217
- return tools;
297
+ try {
298
+ const client = await this.connect();
299
+ const { tools } = await client.listTools();
300
+ if (tools.length === 0) {
301
+ this.unavailable = NO_DEVICE_TOOLS;
302
+ return tools;
303
+ }
304
+ this.tools = tools;
305
+ this.unavailable = null;
306
+ return tools;
307
+ }
308
+ catch (error) {
309
+ this.unavailable = error instanceof Error ? error.message : String(error);
310
+ throw error;
311
+ }
218
312
  }
219
313
  has(name) {
220
314
  return this.tools?.some((t) => t.name === name) ?? false;
@@ -224,10 +318,25 @@ class RemoteDevices {
224
318
  return this.tools?.find((t) => t.name === name)?.annotations?.readOnlyHint === true;
225
319
  }
226
320
  }
321
+ /** Why an account sees no device tools when the endpoint answered. */
322
+ const NO_DEVICE_TOOLS = 'the hosted server offers no device tools to this account: Agent Devices may not be enabled for your organization';
323
+ /**
324
+ * Listed in place of the device tools while they can't be loaded, so the
325
+ * agent sees why (in its description) and can load them once that is fixed.
326
+ */
327
+ export const LOAD_DEVICE_TOOLS = 'load_device_tools';
328
+ function loadDeviceToolsTool(reason) {
329
+ return {
330
+ name: LOAD_DEVICE_TOOLS,
331
+ description: `The device tools (start_device and the rest, for driving a cloud phone) could not be loaded: ${reason}. Once that is fixed (for example after \`dcd login\`), call this to load them.`,
332
+ inputSchema: { type: 'object', properties: {} },
333
+ annotations: { readOnlyHint: true },
334
+ };
335
+ }
227
336
  /**
228
337
  * Build the `dcd mcp` server. Without a reachable hosted endpoint (no
229
- * credentials yet, or an API without it), it still serves the dcd_* tools
230
- * and says why on stderr.
338
+ * credentials yet, or an API without it), it still serves the dcd_* tools,
339
+ * says why on stderr, and lists load_device_tools, which says why too.
231
340
  */
232
341
  export async function createBridgeServer(opts = {}) {
233
342
  const callTimeoutMs = opts.callTimeoutMs ?? CALL_TIMEOUT_MS;
@@ -239,7 +348,8 @@ export async function createBridgeServer(opts = {}) {
239
348
  const remote = new RemoteDevices();
240
349
  const readOnly = isReadOnly();
241
350
  const server = new Server({ name: 'devicecloud', version: getCliVersion() }, {
242
- capabilities: { tools: {} },
351
+ // listChanged: the device tools can arrive after the first listing.
352
+ capabilities: { tools: { listChanged: true } },
243
353
  instructions: readOnly ? READ_ONLY_INSTRUCTIONS : INSTRUCTIONS,
244
354
  });
245
355
  server.setRequestHandler(ListToolsRequestSchema, async () => {
@@ -251,8 +361,12 @@ export async function createBridgeServer(opts = {}) {
251
361
  .filter((t) => !readOnly || t.annotations?.readOnlyHint === true)
252
362
  .map((t) => withLocalInputs(t));
253
363
  }
254
- catch (error) {
255
- logStderr(`Device tools unavailable: ${error instanceof Error ? error.message : String(error)}. Serving the dcd_* tools only.`);
364
+ catch {
365
+ // remote.unavailable says why.
366
+ }
367
+ if (remote.unavailable) {
368
+ logStderr(`Device tools unavailable: ${remote.unavailable}. Serving the dcd_* tools only.`);
369
+ return { tools: [...localTools, loadDeviceToolsTool(remote.unavailable)] };
256
370
  }
257
371
  return { tools: [...localTools, ...deviceTools] };
258
372
  });
@@ -265,8 +379,28 @@ export async function createBridgeServer(opts = {}) {
265
379
  if (localNames.has(name)) {
266
380
  return (await local.callTool({ name, arguments: args }, undefined, options));
267
381
  }
382
+ if (name === LOAD_DEVICE_TOOLS) {
383
+ return runTool(`device ${name}`, async () => {
384
+ const tools = await remote.list().catch(() => []);
385
+ if (tools.length === 0) {
386
+ return errorResult(`The device tools are still unavailable: ${remote.unavailable ?? 'no answer'}.`);
387
+ }
388
+ await server.sendToolListChanged();
389
+ return {
390
+ content: [
391
+ {
392
+ type: 'text',
393
+ text: `Loaded the device tools: ${tools.map((t) => t.name).join(', ')}. List the tools again to see them.`,
394
+ },
395
+ ],
396
+ };
397
+ });
398
+ }
268
399
  return runTool(`device ${name}`, async () => {
269
- await remote.list();
400
+ await remote.list().catch(() => []);
401
+ if (remote.unavailable) {
402
+ return errorResult(`${name} is not available: the device tools could not be loaded (${remote.unavailable}).`);
403
+ }
270
404
  if (!remote.has(name)) {
271
405
  // In read-only mode the hosted server lists only its read-only tools,
272
406
  // so a device tool that changes something is unknown here as well.
@@ -280,9 +414,12 @@ export async function createBridgeServer(opts = {}) {
280
414
  }
281
415
  const client = await remote.connect();
282
416
  const ctx = await getContext();
417
+ // Checked before the device is asked: a bad path is refused at once.
418
+ const saveTo = name === 'take_screenshot' ? screenshotTarget(args) : null;
283
419
  const remoteArgs = await resolveLocalInputs(name, args, ctx);
284
420
  try {
285
- return (await client.callTool({ name, arguments: remoteArgs }, undefined, options));
421
+ const result = (await client.callTool({ name, arguments: remoteArgs }, undefined, options));
422
+ return saveTo ? await saveFullScreenshot(result, saveTo) : result;
286
423
  }
287
424
  catch (error) {
288
425
  // A tool's own refusal comes back as a result. A throw means no answer
@@ -0,0 +1,14 @@
1
+ /** The working directory, as the file system names it (symbolic links resolved). */
2
+ export declare function workingDirectory(): string;
3
+ /** Whether `child` is `parent` or inside it. Both absolute and resolved. */
4
+ export declare function isInside(child: string, parent: string): boolean;
5
+ /** An existing file or folder the agent named, resolved, inside the working directory. */
6
+ export declare function localInput(given: string, root?: string): string;
7
+ /**
8
+ * Where to write a file the agent asked for, resolved: inside the working
9
+ * directory, and not over a file this server did not write. Folders that do
10
+ * not exist yet are allowed; the writer makes them.
11
+ */
12
+ export declare function localOutput(given: string, root?: string): string;
13
+ /** Record a file this server wrote, so a later call may write it again. */
14
+ export declare function markWritten(file: string): void;
@@ -0,0 +1,75 @@
1
+ /**
2
+ * The local files an MCP tool may read or write for the agent: only inside
3
+ * the working directory the server was started in (the agent's project), and
4
+ * a write never replaces a file this server did not write. An agent's tool
5
+ * call is not the user typing a path: without these limits a tool could
6
+ * send `~/.aws/credentials` as a flow, or write a report over `~/.zshrc`.
7
+ * Symbolic links are followed before the check, so a link can't lead out.
8
+ */
9
+ import { existsSync, lstatSync, realpathSync } from 'node:fs';
10
+ import * as path from 'node:path';
11
+ /** The working directory, as the file system names it (symbolic links resolved). */
12
+ export function workingDirectory() {
13
+ return realpathSync(process.cwd());
14
+ }
15
+ /** Whether `child` is `parent` or inside it. Both absolute and resolved. */
16
+ export function isInside(child, parent) {
17
+ const relative = path.relative(parent, child);
18
+ return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative));
19
+ }
20
+ function outside(given, root) {
21
+ return new Error(`${given} is outside the working directory (${root}). This server reads and writes files only there: start it in the folder that holds them, or copy them in.`);
22
+ }
23
+ /** An existing file or folder the agent named, resolved, inside the working directory. */
24
+ export function localInput(given, root = workingDirectory()) {
25
+ let real;
26
+ try {
27
+ real = realpathSync(path.resolve(root, given));
28
+ }
29
+ catch {
30
+ throw new Error(`No such file or directory: ${given}`);
31
+ }
32
+ if (!isInside(real, root))
33
+ throw outside(given, root);
34
+ return real;
35
+ }
36
+ /** Files this server wrote, which it may write again. */
37
+ const written = new Set();
38
+ /**
39
+ * Where to write a file the agent asked for, resolved: inside the working
40
+ * directory, and not over a file this server did not write. Folders that do
41
+ * not exist yet are allowed; the writer makes them.
42
+ */
43
+ export function localOutput(given, root = workingDirectory()) {
44
+ const absolute = path.resolve(root, given);
45
+ // The deepest folder that exists, resolved; the rest is appended to it.
46
+ let existing = path.dirname(absolute);
47
+ const rest = [path.basename(absolute)];
48
+ while (!existsSync(existing)) {
49
+ rest.unshift(path.basename(existing));
50
+ const parent = path.dirname(existing);
51
+ if (parent === existing)
52
+ break;
53
+ existing = parent;
54
+ }
55
+ const target = path.join(realpathSync(existing), ...rest);
56
+ if (!isInside(target, root) || target === root)
57
+ throw outside(given, root);
58
+ // lstat, not exists: a dangling symbolic link is a file there too.
59
+ let present;
60
+ try {
61
+ lstatSync(target);
62
+ present = true;
63
+ }
64
+ catch {
65
+ present = false;
66
+ }
67
+ if (present && !written.has(target)) {
68
+ throw new Error(`${given} already exists, and this server did not write it. Pass a new path, or remove the file first.`);
69
+ }
70
+ return target;
71
+ }
72
+ /** Record a file this server wrote, so a later call may write it again. */
73
+ export function markWritten(file) {
74
+ written.add(file);
75
+ }
@@ -2,7 +2,10 @@ import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
2
  /**
3
3
  * Download a completed run's artifacts (zip) and/or a formatted report to local
4
4
  * disk. This reads cloud state and writes files locally — it does not change
5
- * anything cloud-side, so it stays available in read-only mode.
5
+ * anything cloud-side, so it stays available in read-only mode. It does write
6
+ * files, so it is not annotated read-only: the files go inside the working
7
+ * directory only, and never over a file this server did not write
8
+ * (local-files.ts).
6
9
  *
7
10
  * The underlying service swallows download failures into `warnLogger` rather
8
11
  * than throwing (a missing-artifacts 404 isn't fatal), so we collect those
@@ -1,12 +1,16 @@
1
- import * as path from 'node:path';
1
+ import { existsSync } from 'node:fs';
2
2
  import { z } from 'zod';
3
3
  import { ReportDownloadService } from '../../services/report-download.service.js';
4
4
  import { getContext, logStderr } from '../context.js';
5
5
  import { jsonResult, runTool } from '../helpers.js';
6
+ import { localOutput, markWritten } from '../local-files.js';
6
7
  /**
7
8
  * Download a completed run's artifacts (zip) and/or a formatted report to local
8
9
  * disk. This reads cloud state and writes files locally — it does not change
9
- * anything cloud-side, so it stays available in read-only mode.
10
+ * anything cloud-side, so it stays available in read-only mode. It does write
11
+ * files, so it is not annotated read-only: the files go inside the working
12
+ * directory only, and never over a file this server did not write
13
+ * (local-files.ts).
10
14
  *
11
15
  * The underlying service swallows download failures into `warnLogger` rather
12
16
  * than throwing (a missing-artifacts 404 isn't fatal), so we collect those
@@ -16,6 +20,7 @@ export function registerDownloadArtifacts(server) {
16
20
  server.registerTool('dcd_download_artifacts', {
17
21
  title: 'Download run artifacts',
18
22
  description: 'Download a completed test run\'s artifacts (videos/logs zip) and/or a formatted report to local disk. ' +
23
+ 'Paths are relative to the working directory this server runs in, and must stay inside it; an existing file this server did not write is never replaced. ' +
19
24
  'Returns the resolved output paths and any warnings (a non-empty warnings array means a download could not be produced, e.g. no results yet).',
20
25
  inputSchema: {
21
26
  uploadId: z.string().describe('UUID of the upload to download artifacts for'),
@@ -26,7 +31,18 @@ export function registerDownloadArtifacts(server) {
26
31
  artifactsPath: z
27
32
  .string()
28
33
  .optional()
29
- .describe('Local path to write the artifacts zip (default ./artifacts.zip)'),
34
+ .describe('Where to write the artifacts zip, inside the working directory (default ./artifacts.zip)'),
35
+ resultId: z
36
+ .number()
37
+ .int()
38
+ .positive()
39
+ .optional()
40
+ .describe("Only this result's artifacts: its flow's attempts on that one device. Leave unset with flow."),
41
+ flow: z
42
+ .string()
43
+ .min(1)
44
+ .optional()
45
+ .describe('Only the artifacts of the flow with this file path or name (e.g. flows/login.yaml or login). A name matching several results (one per device) gives a warning listing their ids; pass one as resultId.'),
30
46
  report: z
31
47
  .enum(['junit', 'allure', 'html'])
32
48
  .optional()
@@ -34,10 +50,14 @@ export function registerDownloadArtifacts(server) {
34
50
  reportPath: z
35
51
  .string()
36
52
  .optional()
37
- .describe('Local path for the report file (default ./report.xml for junit, ./report.html for allure, ./report.zip for html, which is a ZIP of report.html and its assets)'),
53
+ .describe('Where to write the report, inside the working directory (default ./report.xml for junit, ./report.html for allure, ./report.zip for html, which is a ZIP of report.html and its assets)'),
38
54
  },
39
- annotations: { readOnlyHint: true, openWorldHint: true },
55
+ // It writes local files (nothing in the cloud), and never over one it did not write.
56
+ annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: true },
40
57
  }, async (args) => runTool('dcd_download_artifacts', async () => {
58
+ if (args.resultId !== undefined && args.flow !== undefined) {
59
+ throw new Error('Pass resultId or flow, not both');
60
+ }
41
61
  const { apiUrl, auth } = await getContext();
42
62
  const service = new ReportDownloadService();
43
63
  const warnings = [];
@@ -45,26 +65,31 @@ export function registerDownloadArtifacts(server) {
45
65
  warnings.push(m);
46
66
  logStderr(m);
47
67
  };
48
- const artifactsPath = args.artifactsPath ?? './artifacts.zip';
68
+ // Both checked before anything is downloaded.
69
+ const artifactsPath = localOutput(args.artifactsPath ?? './artifacts.zip');
70
+ const defaultReportPath = args.report
71
+ ? { allure: 'report.html', html: 'report.zip', junit: 'report.xml' }[args.report]
72
+ : undefined;
73
+ const reportPath = defaultReportPath ? localOutput(args.reportPath || defaultReportPath) : undefined;
74
+ if (reportPath && reportPath === artifactsPath) {
75
+ throw new Error('artifactsPath and reportPath name the same file. Give them different paths.');
76
+ }
49
77
  await service.downloadArtifacts({
50
78
  apiUrl,
51
79
  auth,
52
80
  uploadId: args.uploadId,
53
81
  downloadType: args.type ?? 'ALL',
54
82
  artifactsPath,
83
+ flow: args.flow,
84
+ resultId: args.resultId,
55
85
  logger: logStderr,
56
86
  warnLogger,
57
87
  });
58
- let reportPath;
59
- if (args.report) {
60
- // The HTML report is a ZIP of report.html plus assets; Allure's is
61
- // a single HTML file.
62
- const defaultReportPath = {
63
- allure: 'report.html',
64
- html: 'report.zip',
65
- junit: 'report.xml',
66
- }[args.report];
67
- reportPath = path.resolve(args.reportPath || defaultReportPath);
88
+ if (existsSync(artifactsPath))
89
+ markWritten(artifactsPath);
90
+ // The HTML report is a ZIP of report.html plus assets; Allure's is a
91
+ // single HTML file.
92
+ if (args.report && reportPath) {
68
93
  await service.downloadReports({
69
94
  apiUrl,
70
95
  auth,
@@ -76,10 +101,12 @@ export function registerDownloadArtifacts(server) {
76
101
  logger: logStderr,
77
102
  warnLogger,
78
103
  });
104
+ if (existsSync(reportPath))
105
+ markWritten(reportPath);
79
106
  }
80
107
  return jsonResult({
81
108
  uploadId: args.uploadId,
82
- artifactsPath: path.resolve(artifactsPath),
109
+ artifactsPath,
83
110
  reportPath,
84
111
  warnings,
85
112
  });