Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
81009e4
feat(device): add dcd device start, list, status, stop, install, laun…
riglar Oct 19, 2026
c259c51
feat(device): add dcd device inspect, screenshot, run, logs and open
riglar Oct 19, 2026
f7d6f6f
feat(device): add dcd device artifacts
riglar Oct 19, 2026
820da4c
fix(device): renew a dcd login token while polling
riglar Oct 19, 2026
1a86590
Merge branch 'feat/device-inspect-run' into feat/device-artifacts
riglar Oct 19, 2026
7d7ed0c
feat(device): run a directory of flows as a bundle
riglar Oct 19, 2026
96ac72f
feat(mcp): add dcd mcp, one stdio server for cloud tests and cloud de…
riglar Oct 19, 2026
7a2a432
fix(mcp): refuse state-changing device tools in read-only mode
riglar Oct 19, 2026
f8ae6cf
Merge remote-tracking branch 'origin/feature/agent-devices' into feat…
riglar Oct 19, 2026
d81d778
Merge branch 'feat/device-inspect-run' into feat/device-artifacts
riglar Oct 19, 2026
a57f176
Merge branch 'feat/device-artifacts' into feat/device-run-bundles
riglar Oct 19, 2026
d1f229a
Merge branch 'feat/device-run-bundles' into feat/device-mcp-bridge
riglar Oct 19, 2026
7966e9c
Merge remote-tracking branch 'origin/feature/agent-devices' into feat…
riglar Oct 19, 2026
aa769d3
Merge branch 'feat/device-artifacts' into feat/device-run-bundles
riglar Oct 19, 2026
d74f257
Merge branch 'feat/device-run-bundles' into feat/device-mcp-bridge
riglar Oct 19, 2026
9958924
fix(mcp): don't cut forwarded calls off at the SDK's 60s default
riglar Oct 19, 2026
b31701b
Merge remote-tracking branch 'origin/feature/agent-devices' into feat…
riglar Oct 19, 2026
81d1300
Merge branch 'feat/device-run-bundles' into feat/device-mcp-bridge
riglar Oct 19, 2026
e677477
test(mcp): check the bridge's call timeout is the one applied
riglar Oct 19, 2026
e2addaa
Merge remote-tracking branch 'origin/feature/agent-devices' into feat…
riglar Oct 19, 2026
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: 2 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,8 @@ Top-level `defineCommand` in `src/index.ts` wires eleven 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` (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 hidden `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: `install_app` takes `app_path` (uploaded with `uploadLocalApp`) and `run` takes `path` (a file is sent as `yaml`, a directory is uploaded as a flow bundle). Credentials are the CLI's (`getContext`): the hosted `/mcp` accepts an API key or a `dcd login` session with `x-dcd-org`, and the remote connection is remade when a session is renewed. 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.

## Contributing

Full guide in `CONTRIBUTING.md`; the operationally important parts (the ones that gate a merge or affect a release):
Expand Down
34 changes: 34 additions & 0 deletions src/commands/mcp.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { defineCommand } from 'citty';

import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';

import { createBridgeServer } from '../mcp/bridge.js';
import { isReadOnly, logStderr } from '../mcp/context.js';
import { telemetry } from '../services/telemetry.service.js';

/**
* `dcd mcp`: the MCP server over stdio, for MCP clients to launch. It serves
* the dcd_* cloud-test tools and the device tools (see src/mcp/bridge.ts).
* Nothing but JSON-RPC may reach stdout.
*/
export const mcpCommand = defineCommand({
meta: {
name: 'mcp',
description: 'Run the DeviceCloud MCP server on stdio (cloud tests and cloud devices)',
// Listed in `dcd --help` with `dcd device`, once the device API is live.
hidden: true,
},
args: {
'read-only': {
type: 'boolean',
default: false,
description: 'Serve only tools that change nothing (also DCD_MCP_READONLY=1)',
},
},
async run() {
telemetry.setCommand('mcp');
const server = await createBridgeServer();
await server.connect(new StdioServerTransport());
logStderr(`DeviceCloud MCP server running on stdio${isReadOnly() ? ' (read-only)' : ''}`);
},
});
2 changes: 2 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { listCommand } from './commands/list.js';
import { liveCommand } from './commands/live.js';
import { loginCommand } from './commands/login.js';
import { logoutCommand } from './commands/logout.js';
import { mcpCommand } from './commands/mcp.js';
import { statusCommand } from './commands/status.js';
import { switchOrgCommand } from './commands/switch-org.js';
import { upgradeCommand } from './commands/upgrade.js';
Expand Down Expand Up @@ -39,6 +40,7 @@ const main = defineCommand({
artifacts: artifactsCommand,
device: deviceCommand,
live: liveCommand,
mcp: mcpCommand,
login: loginCommand,
logout: logoutCommand,
whoami: whoamiCommand,
Expand Down
234 changes: 234 additions & 0 deletions src/mcp/bridge.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,234 @@
/**
* `dcd mcp`: one stdio MCP server with two sets of tools (dcd plan 4.4).
*
* - The `dcd_*` cloud-test tools, from the same in-process server `dcd-mcp`
* runs (createServer), reached over an in-memory transport.
* - The device tools, proxied from the hosted endpoint at `<api>/mcp`, so
* they are defined (and contract-tested) once, in the API. The bridge adds
* what a remote server can't do: `install_app` takes a local `app_path`,
* and `run` takes a local `path` (a flow file, or a directory uploaded as
* a bundle).
*
* Auth is the CLI's: an API key or a `dcd login` session (getContext). The
* hosted endpoint accepts both. A session is renewed before it expires, and
* the remote connection is remade with it.
*
* stdout is the JSON-RPC channel: everything else goes to stderr.
*/
import { readFile, stat } from 'node:fs/promises';

import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import {
CallToolRequestSchema,
type CallToolResult,
ListToolsRequestSchema,
type Tool,
} from '@modelcontextprotocol/sdk/types.js';

import type { AuthContext } from '../types/domain/auth.types.js';
import { uploadLocalApp } from '../utils/app-upload.js';
import { getCliVersion } from '../utils/cli.js';
import { uploadFlowBundle } from '../utils/device-bundle.js';
import { getContext, isReadOnly, logStderr } from './context.js';
import { errorResult, runTool } from './helpers.js';
import { createServer } from './server.js';

const INSTRUCTIONS =
'DeviceCloud tools. dcd_* tools run Maestro test suites in the cloud. The device tools lease a cloud iOS or Android device for you to drive: start_device, then inspect_screen / take_screenshot, launch_app, run, and stop_device when done. Call cheat_sheet first for Maestro syntax. Local files: install_app takes app_path and run takes path (a flow file or a directory), which this server uploads for you.';

/**
* How long one forwarded call may take. Longer than dcd_run_cloud_test's
* longest wait (3600s) plus an upload. The MCP client calling this server
* still applies its own timeout, and its cancel is passed through.
*/
export const CALL_TIMEOUT_MS = 2 * 60 * 60 * 1000;

const READ_ONLY_INSTRUCTIONS =
'DeviceCloud tools, read-only: nothing here starts a device, runs a test or changes anything. dcd_* tools read cloud test runs and their results. The device tools read open device sessions: list_devices, get_device_status, inspect_screen, take_screenshot, get_logs.';

/** The inputs this bridge adds to hosted tools, and what they say. */
const LOCAL_INPUTS: Record<string, { description: string; properties: Record<string, object> }> = {
install_app: {
description:
' Or pass app_path, a build on this machine (.apk, or a simulator .app / .zip / Expo .tar.gz), which is uploaded first.',
properties: {
app_path: {
type: 'string',
description: 'A build on this machine to upload and install. Pass this, app_binary_id or app_url.',
},
},
},
run: {
description:
' Or pass path: a flow file on this machine (sent as yaml), or a directory of flows (uploaded as a bundle; flow picks the entry file inside it).',
properties: {
path: {
type: 'string',
description: 'A local flow file, or a directory of flows. Pass this, yaml or flow_upload_id.',
},
},
},
};

/** A hosted tool with this bridge's local inputs added. */
export function withLocalInputs(tool: Tool): Tool {
const extra = LOCAL_INPUTS[tool.name];
if (!extra) return tool;
return {
...tool,
description: `${tool.description ?? ''}${extra.description}`,
inputSchema: {
...tool.inputSchema,
properties: { ...tool.inputSchema.properties, ...extra.properties },
},
};
}

/**
* Do the local part of a call (uploads, reading a file) and return the
* arguments the hosted tool takes.
*/
export async function resolveLocalInputs(
name: string,
args: Record<string, unknown>,
ctx: { apiUrl: string; auth: AuthContext },
): Promise<Record<string, unknown>> {
if (name === 'install_app' && typeof args.app_path === 'string') {
const { app_path: filePath, ...rest } = args;
logStderr(`Uploading ${filePath}…`);
const binaryId = await uploadLocalApp({
...ctx,
filePath: filePath as string,
log: logStderr,
showProgress: false,
});
return { ...rest, app_binary_id: binaryId };
}

if (name === 'run' && typeof args.path === 'string') {
const { path: flowPath, ...rest } = args;
const info = await stat(flowPath as string).catch(() => null);
if (!info) throw new Error(`No such file or directory: ${flowPath}`);
if (info.isDirectory()) {
logStderr(`Uploading the flows in ${flowPath}…`);
const bundle = await uploadFlowBundle({ ...ctx, dir: flowPath as string, log: logStderr });
return { ...rest, flow_upload_id: bundle.id };
}

return { ...rest, yaml: await readFile(flowPath as string, 'utf8') };
}

return args;
}

/** The hosted device tools, connected lazily and remade when auth changes. */
class RemoteDevices {
private client: Client | null = null;
private auth: AuthContext | null = null;
private tools: Tool[] | null = null;

async connect(): Promise<{ client: Client; ctx: { apiUrl: string; auth: AuthContext } }> {
const ctx = await getContext();
if (this.client && this.auth === ctx.auth) return { client: this.client, ctx };

await this.client?.close().catch(() => {});
const client = new Client({ name: 'dcd-mcp-bridge', version: getCliVersion() });
await client.connect(
new StreamableHTTPClientTransport(new URL(`${ctx.apiUrl}/mcp`), {
requestInit: { headers: { ...ctx.auth.headers } },
}),
);
this.client = client;
this.auth = ctx.auth;
return { client, ctx };
}

async list(): Promise<Tool[]> {
if (this.tools) return this.tools;
const { client } = await this.connect();
const { tools } = await client.listTools();
this.tools = tools;
return tools;
}

has(name: string): boolean {
return this.tools?.some((t) => t.name === name) ?? false;
}

/** Annotated read-only by the hosted server: changes nothing, costs nothing. */
isReadOnly(name: string): boolean {
return this.tools?.find((t) => t.name === name)?.annotations?.readOnlyHint === true;
}
}

/**
* Build the `dcd mcp` server. Without a reachable hosted endpoint (no
* credentials yet, or an API without it), it still serves the dcd_* tools
* and says why on stderr.
*/
export async function createBridgeServer(
opts: { callTimeoutMs?: number } = {},
): Promise<Server> {
const callTimeoutMs = opts.callTimeoutMs ?? CALL_TIMEOUT_MS;
const [localClientSide, localServerSide] = InMemoryTransport.createLinkedPair();
await createServer().connect(localServerSide);
const local = new Client({ name: 'dcd-mcp-bridge', version: getCliVersion() });
await local.connect(localClientSide);
const localNames = new Set((await local.listTools()).tools.map((t) => t.name));

const remote = new RemoteDevices();
const readOnly = isReadOnly();

const server = new Server(
{ name: 'devicecloud', version: getCliVersion() },
{
capabilities: { tools: {} },
instructions: readOnly ? READ_ONLY_INSTRUCTIONS : INSTRUCTIONS,
},
);

server.setRequestHandler(ListToolsRequestSchema, async () => {
const { tools: localTools } = await local.listTools();
let deviceTools: Tool[] = [];
try {
deviceTools = (await remote.list())
// Read-only mode keeps only the tools that change nothing.
.filter((t) => !readOnly || t.annotations?.readOnlyHint === true)
.map((t) => withLocalInputs(t));
} catch (error) {
logStderr(
`Device tools unavailable: ${error instanceof Error ? error.message : String(error)}. Serving the dcd_* tools only.`,
);
}

return { tools: [...localTools, ...deviceTools] };
});

server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
// The client's own timeout and cancel apply, not the SDK's 60s default:
// dcd_run_cloud_test can wait an hour, and a device run or upload is long.
const options = { signal: extra.signal, timeout: callTimeoutMs, resetTimeoutOnProgress: true };
const { name } = request.params;
const args = (request.params.arguments ?? {}) as Record<string, unknown>;
if (localNames.has(name)) {
return (await local.callTool({ name, arguments: args }, undefined, options)) as CallToolResult;
}

return runTool(`device ${name}`, async () => {
await remote.list();
if (!remote.has(name)) return errorResult(`Unknown tool: ${name}`);
Comment thread
riglar marked this conversation as resolved.
// The list hides these in read-only mode; refuse them if called anyway.
if (readOnly && !remote.isReadOnly(name)) {
return errorResult(`${name} is not available in read-only mode.`);
}
const { client, ctx } = await remote.connect();
const remoteArgs = await resolveLocalInputs(name, args, ctx);
return (await client.callTool({ name, arguments: remoteArgs }, undefined, options)) as CallToolResult;
});
});

return server;
}
Loading
Loading