Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ Top-level `defineCommand` in `src/index.ts` wires fourteen subcommands (`cloud`,

**MCP server.** `src/mcp/` is a third front-end onto the same service layer (a sibling to `src/commands/`), shipped as the `dcd-mcp` bin over stdio transport (`@modelcontextprotocol/sdk`, `zod` schemas). `index.ts` boots the server; `server.ts` registers tools; `context.ts` resolves auth + API URL **lazily**, and again when a `dcd login` session nears expiry (so `tools/list` works unauthenticated, auth errors surface as tool errors rather than a boot crash, and a long-lived server outlasts the one-hour access token) via the same `resolveAuth`/`resolveApiUrl` as the CLI — `DEVICE_CLOUD_API_KEY` env or stored `dcd login` session, with `DCD_API_URL` to override. **Critical invariant: stdout is the JSON-RPC channel** — tools must never call the `src/commands/*` layer or `utils/cli` `logger` (both write to stdout / can `process.exit`); they call services/gateways directly with `logStderr` and return data via `helpers.ts` `jsonResult`/`errorResult`. The `runTool` wrapper records `mcp tool …` telemetry and converts thrown errors to `isError` results. Tools: `dcd_list_devices`, `dcd_list_runs`, `dcd_get_status`, `dcd_download_artifacts`, `dcd_get_team_settings` (read-only), and `dcd_run_cloud_test` (billable — gated out by `--read-only` / `DCD_MCP_READONLY=1`, annotated destructive, async-by-default). `dcd_run_cloud_test` reuses `computeCommonRoot`/`buildTestMetadataMap` from `src/services/flow-paths.ts` (extracted from `cloud.ts` so both build identical server-side paths). Registry manifest: `server.json` at repo root.

**`dcd mcp` (the bridge).** A second stdio entry point, `src/mcp/bridge.ts`, run by the `dcd mcp` command. It is a low-level `Server` that routes between two MCP clients: the `dcd_*` tools from the same in-process `createServer()` (over an in-memory transport), and the device tools proxied from the hosted `<api>/mcp`, so those are defined and contract-tested once, in the dcd API. It adds the inputs only a local process can serve: `start_device` and `install_app` take `app_path` (uploaded with `uploadLocalApp`, before the session starts for `start_device`) and `run` takes `path` (a file that uses no other files is sent as `yaml`; one that does, or a directory, is uploaded as a flow bundle of only what the entry reaches). `path`, `app_path`, and what `dcd_download_artifacts` writes, must be inside the working directory, and a write never replaces a file the server did not write (`src/mcp/local-files.ts`). When the device tools can't be listed it lists `load_device_tools` instead, whose description says why, and sends `tools/list_changed` once they load. Credentials are the CLI's (`getContext`): the hosted `/mcp` accepts an API key or a `dcd login` session with `x-dcd-org`. One connection is shared, and its `fetch` re-reads the auth headers from `getContext()` on every request, so a renewed session is picked up without remaking the connection (which would close it under a `run` still going). If the hosted endpoint can't be reached, it serves the `dcd_*` tools only and says why on stderr. Read-only mode keeps only device tools annotated `readOnlyHint`. `dcd-mcp` itself is unchanged.
**`dcd mcp` (the bridge).** A second stdio entry point, `src/mcp/bridge.ts`, run by the `dcd mcp` command. It is a low-level `Server` that routes between two MCP clients: the `dcd_*` tools from the same in-process `createServer()` (over an in-memory transport), and the device tools proxied from the hosted `<api>/mcp`, so those are defined and contract-tested once, in the dcd API. It adds the inputs only a local process can serve: `start_device` and `install_app` take `app_path` (uploaded with `uploadLocalApp`, before the session starts for `start_device`) and `run` takes `path` (a file that uses no other files is sent as `yaml`; one that does, or a directory, is uploaded as a flow bundle of only what the entry reaches). `take_screenshot` with `full_size: true` takes `path` too: the hosted tool answers with a link to the PNG, which the bridge downloads there (`saveFullScreenshot`). Those paths, `app_path`, and what `dcd_download_artifacts` writes, must be inside the working directory, and a write never replaces a file the server did not write (`src/mcp/local-files.ts`). When the device tools can't be listed it lists `load_device_tools` instead, whose description says why, and sends `tools/list_changed` once they load. Credentials are the CLI's (`getContext`): the hosted `/mcp` accepts an API key or a `dcd login` session with `x-dcd-org`. One connection is shared, and its `fetch` re-reads the auth headers from `getContext()` on every request, so a renewed session is picked up without remaking the connection (which would close it under a `run` still going). If the hosted endpoint can't be reached, it serves the `dcd_*` tools only and says why on stderr. Read-only mode keeps only device tools annotated `readOnlyHint`. `dcd-mcp` itself is unchanged.

**`dcd mcp install [client]`** (`src/utils/mcp-install.ts`) adds the server to Claude Code (`claude mcp add --scope user`), VS Code (`code --add-mcp`), or Claude Desktop / Cursor (merges an entry into their JSON config, and refuses a file that isn't plain JSON rather than rewrite it). Entries always start dcd by **full path**, since desktop apps opened from the Dock don't read the shell rc that puts `~/.dcd/bin` on PATH: the standalone binary is `process.execPath`; an npm install is node (`stableNodePath`, the PATH entry rather than Homebrew's versioned Cellar path) plus `argv[1]` as started, not resolved. It refuses to run from source or from the npx cache. Note citty runs a parent's `run` **after** its subcommand, so `mcpCommand.run` returns early when a positional is present — without that, `dcd mcp install` would go on to start a server.

Expand Down
44 changes: 42 additions & 2 deletions src/commands/device.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ import { bundlePath, flowFileBundle, uploadFlowBundle } from '../utils/device-bu
import {
type DeviceArtifactFile,
downloadArtifactFiles,
downloadFile,
fetchAllArtifacts,
pendingArtifacts,
pendingArtifactsWarning,
Expand Down Expand Up @@ -1310,6 +1311,16 @@ export function decodeDataUrl(dataUrl: string): { bytes: Buffer; ext: string } {
return { bytes: Buffer.from(match[2], 'base64'), ext: match[1] === 'jpeg' ? 'jpg' : match[1] };
}

/** What `dcd device screenshot` reports: a JPEG frame, or with --full a PNG. */
type ScreenshotData = {
bytes?: null | number;
captured_at: null | string;
fresh?: boolean;
height?: null | number;
path: string;
width?: null | number;
};

const screenshotSub = defineCommand({
meta: { name: 'screenshot', description: 'Save a screenshot of the device' },
args: {
Expand All @@ -1318,14 +1329,43 @@ const screenshotSub = defineCommand({
output: {
type: 'string',
alias: ['o'],
description: 'Where to save it (default: ./<session>-<time>.jpg)',
description: 'Where to save it (default: ./<session>-<time>.jpg, or .png with --full)',
},
full: {
type: 'boolean',
description:
"A PNG at the device's own resolution, instead of the smaller JPEG frame (for baseline images). Takes a few seconds. A device busy running a flow can't take it: after 30 seconds the request fails, so take it once the flow has finished",
},
},
async run({ args }) {
const json = Boolean(args.json);
await runDeviceCommand(json, async () => {
await runDeviceCommand<ScreenshotData>(json, async () => {
const ctx = await context(args);
const id = await resolveSessionId(ctx.apiUrl, ctx.auth, args.id as string | undefined);
if (args.full) {
const { screenshot, session } = await DeviceGateway.fullScreenshot(ctx.apiUrl, ctx.auth, id);
const file =
(args.output as string | undefined) ||
`${session.id}-${new Date().toISOString().replaceAll(/[:.]/g, '-')}.png`;
await downloadFile(screenshot.url, file);
const filePath = resolvePath(file);
const size = screenshot.width && screenshot.height ? `${screenshot.width}x${screenshot.height}` : null;
return {
session,
data: {
path: filePath,
captured_at: screenshot.captured_at,
width: screenshot.width,
height: screenshot.height,
bytes: screenshot.bytes,
},
print() {
logger.log(ui.success(`Saved ${filePath}${size ? ` (${size})` : ''}`));
printWarnings(session);
},
};
}

const { screenshot, session } = await DeviceGateway.screenshot(ctx.apiUrl, ctx.auth, id);
const { bytes, ext } = decodeDataUrl(screenshot.data_url);
const file =
Expand Down
13 changes: 13 additions & 0 deletions src/gateways/device-gateway.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import type {
DeviceCatalogue,
DeviceCommandResult,
DeviceFlowBundle,
DeviceFullScreenshot,
DeviceHumanStatus,
DeviceInstalledApp,
DeviceLogLevel,
Expand Down Expand Up @@ -373,6 +374,18 @@ export const DeviceGateway = {
return request(baseUrl, auth, 'GET', `${sessionPath(id)}/screenshot`);
},

/**
* A PNG at the device's own resolution, as a link. A device whose runner
* is too old for it answers LIVE_NOT_SUPPORTED.
*/
fullScreenshot(
baseUrl: string,
auth: AuthContext,
id: string,
): Promise<{ screenshot: DeviceFullScreenshot; session: DeviceSession }> {
return request(baseUrl, auth, 'GET', `${sessionPath(id)}/screenshot?full=true`);
},

start(
baseUrl: string,
auth: AuthContext,
Expand Down
81 changes: 79 additions & 2 deletions src/mcp/bridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,11 @@ import { DeviceGateway, START_RECOVERY_WINDOW_MS } from '../gateways/device-gate
import type { AuthContext } from '../types/domain/auth.types.js';
import { uploadLocalApp } from '../utils/app-upload.js';
import { getCliVersion } from '../utils/cli.js';
import { downloadFile } from '../utils/device-artifacts.js';
import { bundlePath, flowFileBundle, uploadFlowBundle } from '../utils/device-bundle.js';
import { getContext, isReadOnly, logStderr } from './context.js';
import { errorResult, runTool } from './helpers.js';
import { isInside, localInput, workingDirectory } from './local-files.js';
import { isInside, localInput, localOutput, markWritten, workingDirectory } from './local-files.js';
import { createServer } from './server.js';

// Moved to utils/device-bundle.ts, where `dcd device run` uses it too.
Expand Down Expand Up @@ -97,6 +98,17 @@ const LOCAL_INPUTS: Record<string, { description: string; properties: Record<str
},
},
},
take_screenshot: {
description:
' With full_size, also pass path to save the PNG on this machine, inside the working directory this server runs in.',
properties: {
path: {
type: 'string',
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.',
},
},
},
run: {
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.',
Expand Down Expand Up @@ -157,6 +169,13 @@ export async function resolveLocalInputs(
return { ...rest, app_binary_id: binaryId };
}

if (name === 'take_screenshot' && args.path !== undefined) {
// The hosted tool takes no path: the bridge saves the file
// (saveFullScreenshot) once the link comes back.
const { path: _saveTo, ...rest } = args;
return rest;
}

if (name === 'run' && typeof args.path === 'string') {
const { path: given, ...rest } = args;
// Only inside the working directory: an agent's call is not the user
Expand Down Expand Up @@ -195,6 +214,61 @@ export async function resolveLocalInputs(
return args;
}

/**
* Where a take_screenshot call asks for the full-size PNG to be saved, checked
* before the call is made: inside the working directory, not over a file this
* server did not write. Null when it asks for no file.
*/
export function screenshotTarget(args: Record<string, unknown>, root: string = workingDirectory()): null | string {
if (args.path === undefined) return null;
if (typeof args.path !== 'string' || args.path.trim() === '') {
throw new Error('path is where to save the full-size PNG, a file name inside the working directory.');
}

if (args.full_size !== true) {
throw new Error('path saves a full-size screenshot: pass full_size: true with it.');
}

return localOutput(args.path, root);
}

/**
* Save the full-size PNG a take_screenshot call linked to, and say so in its
* result. The link stays in the result whatever happens here: a download
* that fails says why, and the agent can still use the link.
*/
export async function saveFullScreenshot(
result: CallToolResult,
target: string,
download: (url: string, file: string) => Promise<void> = downloadFile,
): Promise<CallToolResult> {
if (result.isError) return result;
const note = (text: string): CallToolResult => ({ ...result, content: [...result.content, { type: 'text', text }] });
const first = result.content.find((c) => c.type === 'text');
let url: unknown;
try {
url = (JSON.parse(first && first.type === 'text' ? first.text : '{}') as { full_size?: { url?: unknown } })
.full_size?.url;
} catch {
url = undefined;
}

if (typeof url !== 'string' || !/^https?:\/\//.test(url)) {
return note('Not saved: the answer had no link to a full-size screenshot.');
}

try {
await download(url, target);
} catch (error) {
return note(
`Not saved to ${target}: ${error instanceof Error ? error.message : String(error)}. The link above still works for an hour.`,
);
}

markWritten(target);
return note(`Saved to ${target}.`);
}

/**
* What to tell the agent when a start_device call failed without an answer
* (the connection dropped, or the server never replied). The request may
Expand Down Expand Up @@ -426,9 +500,12 @@ export async function createBridgeServer(
}
const client = await remote.connect();
const ctx = await getContext();
// Checked before the device is asked: a bad path is refused at once.
const saveTo = name === 'take_screenshot' ? screenshotTarget(args) : null;
const remoteArgs = await resolveLocalInputs(name, args, ctx);
try {
return (await client.callTool({ name, arguments: remoteArgs }, undefined, options)) as CallToolResult;
const result = (await client.callTool({ name, arguments: remoteArgs }, undefined, options)) as CallToolResult;
return saveTo ? await saveFullScreenshot(result, saveTo) : result;
} catch (error) {
// A tool's own refusal comes back as a result. A throw means no answer
// arrived, so for a start the session's fate is unknown.
Expand Down
14 changes: 14 additions & 0 deletions src/types/domain/device-session.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -268,6 +268,20 @@ export interface DeviceScreenshot {
fresh: boolean;
}

/** GET .../screenshot?full=true: a PNG at the device's own resolution, as a link. */
export interface DeviceFullScreenshot {
bytes: null | number;
captured_at: string;
content_type: string;
/** How long `url` works, in seconds. */
expires_in_s: number;
full: true;
/** In the device's own pixels; null when the device could not say. */
height: null | number;
url: string;
width: null | number;
}

/** POST .../run and GET .../commands/:id. */
export interface DeviceRunResponse {
command_id: string;
Expand Down
23 changes: 23 additions & 0 deletions src/utils/device-artifacts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,29 @@ async function downloadOnce(url: string, target: string, idleMs: number, totalMs
}
}

/**
* Download one link to `target`, tried twice, making its folder. A failed
* download leaves no partial file behind.
*/
export async function downloadFile(url: string, target: string, options: DownloadArtifactOptions = {}): Promise<void> {
const idleMs = options.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS;
const totalMs = options.totalTimeoutMs ?? DEFAULT_TOTAL_TIMEOUT_MS;
const attempts = Math.max(1, options.attempts ?? DEFAULT_ATTEMPTS);
await mkdir(path.dirname(target), { recursive: true });
let lastError: unknown;
for (let attempt = 1; attempt <= attempts; attempt++) {
try {
await downloadOnce(url, target, idleMs, totalMs);
return;
} catch (error) {
lastError = error;
}
}

await rm(target, { force: true }).catch(() => {});
throw lastError instanceof Error ? lastError : new Error(String(lastError));
}

/**
* Download every file with a link into `dir`, four at a time. Each file is
* tried twice (a stalled CDN response usually succeeds on a second
Expand Down
11 changes: 9 additions & 2 deletions src/utils/device-output.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,20 @@ export const DEVICE_EXIT = {
usage: 1,
/** It ran and failed: a flow or action failed, or the API could not do it. */
failed: 2,
/** A limit: concurrency, spend cap or rate limit. */
/** A limit: concurrency, a spend cap or usage limit, or a rate limit. */
limit: 3,
/** The session has ended, or there is no such session. */
gone: 4,
} as const;

const LIMIT_CODES = new Set(['LIVE_CONCURRENCY_LIMIT', 'LIVE_RATE_LIMITED', 'LIVE_SPEND_CAP']);
// USAGE_LIMIT_EXCEEDED: the team's overage cap or a usage alert's hard stop
// refused a session start, as it refuses a test run.
const LIMIT_CODES = new Set([
'LIVE_CONCURRENCY_LIMIT',
'LIVE_RATE_LIMITED',
'LIVE_SPEND_CAP',
'USAGE_LIMIT_EXCEEDED',
]);
const GONE_CODES = new Set(['LIVE_NOT_FOUND', 'LIVE_SESSION_ENDED']);
const USAGE_CODES = new Set([
'LIVE_INVALID_ACTION',
Expand Down
Loading
Loading