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
4 changes: 2 additions & 2 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ The package ships a **second bin, `dcd-mcp`** (`bin.dcd-mcp` → `dist/mcp/index

## Architecture

Top-level `defineCommand` in `src/index.ts` wires thirteen subcommands (`cloud`, `upload`, `list`, `status`, `artifacts`, `device`, `mcp`, `live`, `upgrade`, plus the auth-related `login`, `logout`, `whoami`, `switch-org`). `live` is hidden and deprecated: it still works for old scripts, and prints a deprecation line on stderr pointing at `device`. `cloud` is the primary command and replicates `maestro cloud`; `upgrade` self-updates the standalone bun binary (no-op for npm installs, which it redirects to `npm install -g`). Note `src/index.ts` deliberately **reimplements** citty's `runMain` rather than calling it — see the Telemetry section for why.
Top-level `defineCommand` in `src/index.ts` wires fourteen subcommands (`cloud`, `upload`, `list`, `status`, `settings`, `artifacts`, `device`, `mcp`, `live`, `upgrade`, plus the auth-related `login`, `logout`, `whoami`, `switch-org`). `live` is hidden and deprecated: it still works for old scripts, and prints a deprecation line on stderr pointing at `device`. `cloud` is the primary command and replicates `maestro cloud`; `upgrade` self-updates the standalone bun binary (no-op for npm installs, which it redirects to `npm install -g`). Note `src/index.ts` deliberately **reimplements** citty's `runMain` rather than calling it — see the Telemetry section for why.

**Flag composition.** Flag definitions are split by domain in `src/config/flags/*.flags.ts` (api, binary, device, environment, execution, github, output) and re-exported as a single `flags` object from `src/constants.ts`. Commands that need the full cloud surface spread `...flags` into their citty `args`; subset commands import individual flag groups.

Expand All @@ -51,7 +51,7 @@ Top-level `defineCommand` in `src/index.ts` wires thirteen subcommands (`cloud`,

**Telemetry.** `src/services/telemetry.service.ts` ships lifecycle (`command started` / `command completed` / `command failed`) and error events to the dcd API's `/cli/logs` proxy → Axiom `cli-dev` / `cli-prod`. Wired in at three points: `src/index.ts` replicates citty's `runMain` (which would otherwise swallow errors and exit 1) to record start/success/failure and honor `CliError.exitCode`; `src/utils/auth.ts` calls `telemetry.configure({ auth })` from `resolveAuth` so the token never has to be re-derived; `src/utils/cli.ts` `logger.error` calls `telemetry.flushSync()` (which shells out to `curl` because `process.exit` bypasses `beforeExit`) before exiting. Unauthenticated invocations (`--help`, `--version`, `dcd login` pre-success) buffer in memory and drop on exit — by design, since there's no identity to attach. Opt out per-invocation with `DCD_TELEMETRY_DISABLED=1`.

**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.
**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: `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`. 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.

Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,7 @@ It signs in the same way as the CLI: with your `dcd login` session, which it ren
| `dcd_list_runs` | List recent test runs (filter by name/date, paginated) |
| `dcd_get_status` | Get the status + per-test results of a run |
| `dcd_download_artifacts` | Download a run's artifacts/report to disk |
| `dcd_get_team_settings` | Read your team's settings: concurrency, test runtime, integrations and more |
| `dcd_run_cloud_test` | Submit a flow to run on the cloud (**billable**) |

By default `dcd_run_cloud_test` is async: it returns an `uploadId` immediately, which you poll with `dcd_get_status`. Pass `wait: true` (bounded by `waitTimeoutSeconds`) to block until completion, or `dryRun: true` to preview the flows without submitting.
Expand Down
171 changes: 171 additions & 0 deletions src/commands/settings.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
/**
* `dcd settings` — prints the active team's settings: concurrency, test
* runtime, sign-in requirement, retry escalation, overage limit and which
* integrations are connected. Read-only; change settings in the console.
*
* Owner/admin settings come back null for a standard member (the API sets
* `restricted`), and are shown as such rather than as "off".
*/
import { defineCommand } from 'citty';

import { apiFlags } from '../config/flags/api.flags.js';
import { jsonFlag } from '../config/flags/output.flags.js';
import { ApiGateway } from '../gateways/api-gateway.js';
import type {
Platform,
SignInRequirement,
TeamSettings,
} from '../types/domain/team-settings.types.js';
import { resolveAuth } from '../utils/auth.js';
import { logger } from '../utils/cli.js';
import { resolveApiUrl } from '../utils/config-store.js';
import { colors, formatId } from '../utils/styling.js';
import { type Field, ui } from '../utils/ui.js';

const OWNER_OR_ADMIN = colors.dim('owner or admin only');

const PLATFORM_LABELS: Record<Platform, string> = { android: 'Android', ios: 'iOS' };

// The console's wording for each level.
const SIGN_IN_LABELS: Record<SignInRequirement, string> = {
off: 'off',
passkey: 'a passkey',
passkey_and_code: 'a passkey and a code',
two_factor: 'two-factor',
};

const ESCALATION_TARGET_LABELS: Record<string, string> = { gpu1: 'GPU', m1: 'M1' };

function limit(min: number, max: number): string {
return max <= 0 ? colors.dim('not enabled') : `min ${min} · max ${max}`;
}

function connected(value: boolean): string {
return value ? 'connected' : colors.dim('not connected');
}

function signInRequirement(settings: TeamSettings): string {
if (settings.signInRequirement === null) return OWNER_OR_ADMIN;
return SIGN_IN_LABELS[settings.signInRequirement] ?? settings.signInRequirement;
}

function retryEscalation(settings: TeamSettings): string {
const escalation = settings.retryEscalation;
if (escalation === null) return OWNER_OR_ADMIN;
if (!escalation.available || !escalation.target) return colors.dim('not available');
const target = ESCALATION_TARGET_LABELS[escalation.target] ?? escalation.target;
return `${escalation.enabled ? 'on' : 'off'} · Android retries move to ${target} runners`;
}

function overage(settings: TeamSettings): string {
const value = settings.overage;
if (value === null) return OWNER_OR_ADMIN;
if (!value.hasSubscription) return colors.dim('no active subscription');
if (value.limitUsd === null) return 'uncapped';
return `$${value.limitUsd} per billing period, on top of included credits`;
}

function concurrencyRows(settings: TeamSettings): string[] {
const { pools, runners } = settings.concurrency;
const fields: Field[] = [
...runners.map(({ max, min, platform, runnerType }): Field => [
`${PLATFORM_LABELS[platform] ?? platform} ${runnerType}`,
limit(min, max),
]),
...pools.map(({ max, min, name }): Field => [`${name} pool`, limit(min, max)]),
];
if (fields.length === 0) return [colors.dim('none')];

const shared = pools.map(
({ members, name }) =>
`${name} pool is shared by ${members
.map((m) => `${PLATFORM_LABELS[m.platform] ?? m.platform} ${m.runnerType}`)
.join(' and ')}`,
);
return [
...ui.fields(fields),
...shared.map((line) => ui.note(line)),
ui.note('min: always available · max: when capacity allows'),
];
}

/** Human-readable output; one section per area, as in the console. */
export function renderTeamSettings(settings: TeamSettings): string[] {
const { extendedMinutes, defaultMinutes } = settings.testRuntime;
const lines = [
ui.section('Team'),
ui.branch(
ui.fields([
['name', settings.name ?? colors.dim('(unnamed)')],
['org id', formatId(String(settings.orgId))],
['sign-in requirement', signInRequirement(settings)],
]),
),
ui.section('Concurrency'),
ui.branch(concurrencyRows(settings)),
ui.section('Test Runtime'),
ui.branch(
ui.fields([
['default', `${defaultMinutes} min per flow`],
[
'extended',
extendedMinutes === null
? colors.dim('off')
: `${extendedMinutes} min per flow with EXTENDED_RUNTIME, charged at twice the rate`,
],
]),
),
ui.section('Retries & Billing'),
ui.branch(
ui.fields([
['retry escalation', retryEscalation(settings)],
['overage limit', overage(settings)],
]),
),
ui.section('Integrations'),
ui.branch(
ui.fields([
['webhook', connected(settings.integrations.webhook)],
['slack', connected(settings.integrations.slack)],
['github', connected(settings.integrations.github)],
]),
),
];
if (settings.restricted) {
lines.push('', ui.note('Some settings are shown to team owners and admins only.'));
}

return lines;
}

export const settingsCommand = defineCommand({
meta: {
name: 'settings',
description: "Show your team's settings (read-only)",
},
args: {
...apiFlags,
json: jsonFlag,
},
async run({ args }) {
const apiKeyFlag = args['api-key'] as string | undefined;
const apiUrl = resolveApiUrl(args['api-url'] as string | undefined);
const json = Boolean(args.json);

try {
const auth = await resolveAuth({ apiKeyFlag });
const settings = await ApiGateway.getTeamSettings(apiUrl, auth);

if (json) {
logger.json(settings);
return;
}

for (const line of renderTeamSettings(settings)) logger.log(line);
} catch (error) {
logger.error(error as Error, { exit: 1, json });
}
},
});

export default settingsCommand;
31 changes: 31 additions & 0 deletions src/gateways/api-gateway.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import type {
LiveSession,
LiveSessionSummary,
} from '../types/domain/live.types.js';
import type { TeamSettings } from '../types/domain/team-settings.types.js';
import { components, paths } from '../types/generated/schema.types.js';

/**
Expand Down Expand Up @@ -616,6 +617,36 @@ export const ApiGateway = {
}
},

/**
* The team's settings (`GET /org/settings`). A 404 means the API predates
* the endpoint, so it gets a message that says so rather than "not found".
*/
async getTeamSettings(baseUrl: string, auth: AuthContext): Promise<TeamSettings> {
const url = `${baseUrl}/org/settings`;
try {
const response = await fetch(url, { headers: { ...auth.headers } });

if (response.status === 404) {
throw new ApiError(
"This DeviceCloud API doesn't support reading team settings yet.",
404,
);
}

if (!response.ok) {
await this.handleApiError(response, 'Failed to get team settings');
}

return await parseJsonResponse<TeamSettings>(response, 'Failed to get team settings');
} catch (error) {
if (error instanceof TypeError && error.message === 'fetch failed') {
throw this.enhanceFetchError(error, url);
}

throw error;
}
},

async listUploads(
baseUrl: string,
auth: AuthContext,
Expand Down
2 changes: 2 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ 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 { settingsCommand } from './commands/settings.js';
import { statusCommand } from './commands/status.js';
import { switchOrgCommand } from './commands/switch-org.js';
import { upgradeCommand } from './commands/upgrade.js';
Expand All @@ -36,6 +37,7 @@ const main = defineCommand({
upload: uploadCommand,
list: listCommand,
status: statusCommand,
settings: settingsCommand,
artifacts: artifactsCommand,
device: deviceCommand,
live: liveCommand,
Expand Down
4 changes: 2 additions & 2 deletions src/mcp/bridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ import { createServer } from './server.js';
* themselves in their own descriptions.
*/
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. 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.';
'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.';

/**
* How long one forwarded call may take. Longer than dcd_run_cloud_test's
Expand All @@ -57,7 +57,7 @@ const INSTRUCTIONS =
export const CALL_TIMEOUT_MS = 2 * 60 * 60 * 1000;

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. Any other tools describe their own use.';
'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.';

/** The inputs this bridge adds to hosted tools, and what they say. */
const LOCAL_INPUTS: Record<string, { description: string; properties: Record<string, object> }> = {
Expand Down
2 changes: 2 additions & 0 deletions src/mcp/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { getCliVersion } from '../utils/cli.js';
import { isReadOnly } from './context.js';
import { registerDownloadArtifacts } from './tools/download-artifacts.js';
import { registerGetStatus } from './tools/get-status.js';
import { registerGetTeamSettings } from './tools/get-team-settings.js';
import { registerListDevices } from './tools/list-devices.js';
import { registerListRuns } from './tools/list-runs.js';
import { registerRunCloudTest } from './tools/run-cloud-test.js';
Expand All @@ -24,6 +25,7 @@ export function createServer(): McpServer {
registerListRuns(server);
registerGetStatus(server);
registerDownloadArtifacts(server);
registerGetTeamSettings(server);

if (!isReadOnly()) {
registerRunCloudTest(server);
Expand Down
33 changes: 33 additions & 0 deletions src/mcp/tools/get-team-settings.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';

import { ApiGateway } from '../../gateways/api-gateway.js';
import { getContext } from '../context.js';
import { jsonResult, runTool } from '../helpers.js';

/**
* Read-only: the team's settings, the same object `dcd settings --json`
* prints. Lets an agent check limits (concurrency, test runtime) before it
* plans a run, and see how the team is set up without the console.
*/
export function registerGetTeamSettings(server: McpServer): void {
server.registerTool(
'dcd_get_team_settings',
{
title: 'Get team settings',
description:
"Read the devicecloud.dev team's settings. Changes nothing. " +
'Returns: { orgId, name, restricted, concurrency: { runners, pools }, testRuntime: { defaultMinutes, extendedMinutes }, ' +
'integrations: { webhook, slack, github }, signInRequirement, retryEscalation, overage }. ' +
'concurrency gives each runner type\'s min/max tests at once; a pooled runner type is listed under its pool. ' +
'extendedMinutes is null when extended runtime is off. ' +
'When restricted is true (a standard team member), signInRequirement, retryEscalation and overage are null; owners, admins and API keys see them.',
inputSchema: {},
annotations: { readOnlyHint: true, openWorldHint: true },
},
async () =>
runTool('dcd_get_team_settings', async () => {
const { apiUrl, auth } = await getContext();
return jsonResult(await ApiGateway.getTeamSettings(apiUrl, auth));
}),
);
}
Loading
Loading