From 26e9327cc56db648f69b7a3153455d8308c1b98a Mon Sep 17 00:00:00 2001 From: finalerock44 Date: Mon, 16 Nov 2026 18:21:41 +0000 Subject: [PATCH] feat: dcd settings command and dcd_get_team_settings MCP tool Teams could see most of their settings only in the console. `dcd settings` prints them, and `dcd_get_team_settings` gives an agent the same object: - team name, org id and sign-in requirement - concurrency: each runner type's min/max, and shared pools with their members - test runtime: the default and the EXTENDED_RUNTIME cap, or off - retry escalation and the overage limit - whether a webhook, Slack and GitHub are connected Both read GET /org/settings with the usual auth: --api-key, DEVICE_CLOUD_API_KEY, or the `dcd login` session and its org. `--json` prints the API response as-is. For a standard team member the API withholds the sign-in requirement, retry escalation and overage limit, and the command shows them as "owner or admin only" rather than as off. An API without the endpoint answers 404, which becomes "This DeviceCloud API doesn't support reading team settings yet" rather than "Resource not found". The response type is hand-defined in src/types/domain/team-settings.types.ts, as the device-session types are, rather than regenerating schema.types.ts. The MCP tool is read-only, so it is also served in --read-only mode. --- CLAUDE.md | 4 +- README.md | 1 + src/commands/settings.ts | 171 ++++++++++++++++ src/gateways/api-gateway.ts | 31 +++ src/index.ts | 2 + src/mcp/bridge.ts | 4 +- src/mcp/server.ts | 2 + src/mcp/tools/get-team-settings.ts | 33 +++ src/types/domain/team-settings.types.ts | 47 +++++ test/integration/mcp.integration.test.ts | 3 +- test/unit/get-team-settings-tool.test.ts | 92 +++++++++ test/unit/settings-command.test.ts | 245 +++++++++++++++++++++++ 12 files changed, 630 insertions(+), 5 deletions(-) create mode 100644 src/commands/settings.ts create mode 100644 src/mcp/tools/get-team-settings.ts create mode 100644 src/types/domain/team-settings.types.ts create mode 100644 test/unit/get-team-settings-tool.test.ts create mode 100644 test/unit/settings-command.test.ts diff --git a/CLAUDE.md b/CLAUDE.md index c73acc9..b821a9f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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. @@ -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 `/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. diff --git a/README.md b/README.md index 646a023..b465c52 100644 --- a/README.md +++ b/README.md @@ -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. diff --git a/src/commands/settings.ts b/src/commands/settings.ts new file mode 100644 index 0000000..c805860 --- /dev/null +++ b/src/commands/settings.ts @@ -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 = { android: 'Android', ios: 'iOS' }; + +// The console's wording for each level. +const SIGN_IN_LABELS: Record = { + off: 'off', + passkey: 'a passkey', + passkey_and_code: 'a passkey and a code', + two_factor: 'two-factor', +}; + +const ESCALATION_TARGET_LABELS: Record = { 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; diff --git a/src/gateways/api-gateway.ts b/src/gateways/api-gateway.ts index d08eb1d..d61f6bb 100644 --- a/src/gateways/api-gateway.ts +++ b/src/gateways/api-gateway.ts @@ -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'; /** @@ -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 { + 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(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, diff --git a/src/index.ts b/src/index.ts index d6a0b79..90f8499 100644 --- a/src/index.ts +++ b/src/index.ts @@ -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'; @@ -36,6 +37,7 @@ const main = defineCommand({ upload: uploadCommand, list: listCommand, status: statusCommand, + settings: settingsCommand, artifacts: artifactsCommand, device: deviceCommand, live: liveCommand, diff --git a/src/mcp/bridge.ts b/src/mcp/bridge.ts index 5614c77..421f388 100644 --- a/src/mcp/bridge.ts +++ b/src/mcp/bridge.ts @@ -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 @@ -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 }> = { diff --git a/src/mcp/server.ts b/src/mcp/server.ts index 662bac7..e87cba4 100644 --- a/src/mcp/server.ts +++ b/src/mcp/server.ts @@ -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'; @@ -24,6 +25,7 @@ export function createServer(): McpServer { registerListRuns(server); registerGetStatus(server); registerDownloadArtifacts(server); + registerGetTeamSettings(server); if (!isReadOnly()) { registerRunCloudTest(server); diff --git a/src/mcp/tools/get-team-settings.ts b/src/mcp/tools/get-team-settings.ts new file mode 100644 index 0000000..7c540f9 --- /dev/null +++ b/src/mcp/tools/get-team-settings.ts @@ -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)); + }), + ); +} diff --git a/src/types/domain/team-settings.types.ts b/src/types/domain/team-settings.types.ts new file mode 100644 index 0000000..63addbd --- /dev/null +++ b/src/types/domain/team-settings.types.ts @@ -0,0 +1,47 @@ +// Hand-defined: GET /org/settings is newer than the swagger spec the CLI +// generates schema.types.ts from. It mirrors OrgSettingsResponseDto in the +// API (dcd/api/src/apps/org-settings/dto/org-settings.dto.ts). + +export type Platform = 'android' | 'ios'; + +export type SignInRequirement = 'off' | 'passkey' | 'passkey_and_code' | 'two_factor'; + +export interface TeamSettings { + orgId: number; + name: null | string; + /** + * True when the caller is a standard member: `signInRequirement`, + * `retryEscalation` and `overage` are then null. Owners, admins and org API + * keys see them. + */ + restricted: boolean; + concurrency: { + /** Runner types with their own limit. A pooled runner type is listed under its pool. */ + runners: Array<{ max: number; min: number; platform: Platform; runnerType: string }>; + /** Limits shared by several runner types. */ + pools: Array<{ + max: number; + members: Array<{ platform: Platform; runnerType: string }>; + min: number; + name: string; + }>; + }; + testRuntime: { + defaultMinutes: number; + /** With the EXTENDED_RUNTIME override; null when extended runtime is off. */ + extendedMinutes: null | number; + }; + integrations: { github: boolean; slack: boolean; webhook: boolean }; + signInRequirement: null | SignInRequirement; + retryEscalation: { + available: boolean; + enabled: boolean; + /** Runner type an Android test is retried on after an infrastructure failure. */ + target: 'gpu1' | 'm1' | null; + } | null; + overage: { + hasSubscription: boolean; + /** US dollars per billing period on top of included credits; null when uncapped. */ + limitUsd: null | number; + } | null; +} diff --git a/test/integration/mcp.integration.test.ts b/test/integration/mcp.integration.test.ts index 5553cda..862cca5 100644 --- a/test/integration/mcp.integration.test.ts +++ b/test/integration/mcp.integration.test.ts @@ -41,7 +41,7 @@ function parseResult(result: { content: Array<{ type: string; text?: string }>; describe('MCP Server Integration Tests', () => { describe('tool discovery', () => { - it('lists all five tools by default', async () => { + it('lists all six tools by default', async () => { const { client, ready } = connect(); await ready; try { @@ -50,6 +50,7 @@ describe('MCP Server Integration Tests', () => { expect(names).to.deep.equal([ 'dcd_download_artifacts', 'dcd_get_status', + 'dcd_get_team_settings', 'dcd_list_devices', 'dcd_list_runs', 'dcd_run_cloud_test', diff --git a/test/unit/get-team-settings-tool.test.ts b/test/unit/get-team-settings-tool.test.ts new file mode 100644 index 0000000..d834e82 --- /dev/null +++ b/test/unit/get-team-settings-tool.test.ts @@ -0,0 +1,92 @@ +import { Client } from '@modelcontextprotocol/sdk/client/index.js'; +import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js'; +import { expect } from 'chai'; +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; + +import { clearContextCache } from '../../src/mcp/context.js'; +import { createServer } from '../../src/mcp/server.js'; +import { OWNER_SETTINGS } from './settings-command.test.js'; + +const API = 'https://api.example.test'; + +describe('dcd_get_team_settings', () => { + const realFetch = globalThis.fetch; + const ORIGINAL_ENV = { ...process.env }; + let tempDir: string; + let client: Client; + let calls: Array<{ headers: Record; url: string }>; + + const stubFetch = (status: number, body: unknown) => { + globalThis.fetch = (async (input: unknown, init?: RequestInit) => { + calls.push({ url: String(input), headers: (init?.headers ?? {}) as Record }); + return new Response(JSON.stringify(body), { status }); + }) as typeof fetch; + }; + + const connect = async () => { + const server = createServer(); + const [a, b] = InMemoryTransport.createLinkedPair(); + await server.connect(b); + client = new Client({ name: 'agent', version: '1' }); + await client.connect(a); + }; + + const text = (result: Awaited>) => + (result.content as { text: string }[])[0].text; + + beforeEach(async () => { + tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'dcd-team-settings-tool-')); + process.env.DCD_CONFIG_DIR = tempDir; + process.env.DCD_TELEMETRY_DISABLED = '1'; + process.env.DEVICE_CLOUD_API_KEY = 'k'; + process.env.DCD_API_URL = API; + clearContextCache(); + calls = []; + }); + + afterEach(async () => { + await client?.close(); + globalThis.fetch = realFetch; + process.env = { ...ORIGINAL_ENV }; + clearContextCache(); + fs.rmSync(tempDir, { force: true, recursive: true }); + }); + + it('is a read-only tool with no inputs, present in read-only mode too', async () => { + process.env.DCD_MCP_READONLY = '1'; + await connect(); + + const { tools } = await client.listTools(); + const tool = tools.find((t) => t.name === 'dcd_get_team_settings'); + + expect(tool, 'dcd_get_team_settings is registered').to.exist; + expect(tool!.annotations?.readOnlyHint).to.equal(true); + expect(tool!.inputSchema.properties ?? {}).to.deep.equal({}); + }); + + it('returns the API response as JSON', async () => { + stubFetch(200, OWNER_SETTINGS); + await connect(); + + const result = await client.callTool({ name: 'dcd_get_team_settings', arguments: {} }); + + expect(result.isError).to.not.equal(true); + expect(JSON.parse(text(result))).to.deep.equal(OWNER_SETTINGS); + // runTool also flushes telemetry through fetch; only the settings call matters here. + const settingsCalls = calls.filter((c) => c.url === `${API}/org/settings`); + expect(settingsCalls).to.have.length(1); + expect(settingsCalls[0].headers['x-app-api-key']).to.equal('k'); + }); + + it('returns an error result the agent can read when the API predates the endpoint', async () => { + stubFetch(404, { message: 'Cannot GET /org/settings' }); + await connect(); + + const result = await client.callTool({ name: 'dcd_get_team_settings', arguments: {} }); + + expect(result.isError).to.equal(true); + expect(text(result)).to.include("doesn't support reading team settings yet"); + }); +}); diff --git a/test/unit/settings-command.test.ts b/test/unit/settings-command.test.ts new file mode 100644 index 0000000..c21c500 --- /dev/null +++ b/test/unit/settings-command.test.ts @@ -0,0 +1,245 @@ +import { expect } from 'chai'; +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import { stripVTControlCharacters } from 'node:util'; + +import { settingsCommand } from '../../src/commands/settings.js'; +import type { TeamSettings } from '../../src/types/domain/team-settings.types.js'; +import { writeConfig } from '../../src/utils/config-store.js'; + +const API = 'https://api.devicecloud.dev'; + +/** What the API returns to an owner, an admin or an org API key. */ +export const OWNER_SETTINGS: TeamSettings = { + orgId: 7, + name: 'Acme', + restricted: false, + concurrency: { + runners: [ + { platform: 'ios', runnerType: 'm4', min: 0, max: 2 }, + { platform: 'android', runnerType: 'gpu1', min: 0, max: 0 }, + ], + pools: [ + { + name: 'standard', + min: 2, + max: 12, + members: [ + { platform: 'ios', runnerType: 'default' }, + { platform: 'android', runnerType: 'cpu1' }, + ], + }, + ], + }, + testRuntime: { defaultMinutes: 10, extendedMinutes: 20 }, + integrations: { webhook: true, slack: false, github: true }, + signInRequirement: 'passkey', + retryEscalation: { available: true, target: 'm1', enabled: true }, + overage: { hasSubscription: true, limitUsd: 200 }, +}; + +/** What a standard member gets. */ +const STANDARD_SETTINGS: TeamSettings = { + ...OWNER_SETTINGS, + restricted: true, + signInRequirement: null, + retryEscalation: null, + overage: null, +}; + +interface Call { + headers: Record; + method: string; + url: string; +} + +function stubFetch(status: number, body: unknown): Call[] { + const calls: Call[] = []; + globalThis.fetch = (async (input: unknown, init?: RequestInit) => { + calls.push({ + url: String(input), + method: init?.method ?? 'GET', + headers: (init?.headers ?? {}) as Record, + }); + return new Response(JSON.stringify(body), { status }); + }) as typeof fetch; + return calls; +} + +class ExitError extends Error { + constructor(public code: number) { + super(`exit ${code}`); + } +} + +/** Run `dcd settings`, capturing stdout and the exit code. */ +async function run(args: Record): Promise<{ exit: number; out: string }> { + let out = ''; + const write = process.stdout.write.bind(process.stdout); + const log = console.log; + const exit = process.exit; + process.stdout.write = ((chunk: string) => { + out += chunk; + return true; + }) as typeof process.stdout.write; + console.log = (...parts: unknown[]) => { + out += parts.join(' ') + '\n'; + }; + process.exit = ((code?: number) => { + throw new ExitError(code ?? 0); + }) as typeof process.exit; + let code = 0; + try { + await (settingsCommand.run as (c: unknown) => Promise)({ + args: { 'api-url': API, ...args }, + rawArgs: [], + }); + } catch (error) { + if (!(error instanceof ExitError)) throw error; + code = error.code; + } finally { + process.stdout.write = write; + console.log = log; + process.exit = exit; + } + + return { exit: code, out: stripVTControlCharacters(out) }; +} + +describe('dcd settings', () => { + const realFetch = globalThis.fetch; + const ORIGINAL_ENV = { ...process.env }; + let tempDir: string; + + beforeEach(() => { + tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'dcd-settings-test-')); + process.env.DCD_CONFIG_DIR = tempDir; + process.env.DCD_TELEMETRY_DISABLED = '1'; + delete process.env.DEVICE_CLOUD_API_KEY; + }); + + afterEach(() => { + globalThis.fetch = realFetch; + process.env = { ...ORIGINAL_ENV }; + fs.rmSync(tempDir, { force: true, recursive: true }); + }); + + it('reads GET /org/settings with the API key and prints it as-is with --json', async () => { + const calls = stubFetch(200, OWNER_SETTINGS); + + const { exit, out } = await run({ 'api-key': 'k', json: true }); + + expect(exit).to.equal(0); + expect(JSON.parse(out)).to.deep.equal(OWNER_SETTINGS); + expect(calls).to.have.length(1); + expect(calls[0].url).to.equal(`${API}/org/settings`); + expect(calls[0].method).to.equal('GET'); + expect(calls[0].headers['x-app-api-key']).to.equal('k'); + }); + + it('uses the dcd login session and its org when there is no API key', async () => { + writeConfig({ + version: 1, + env: 'prod', + api_url: API, + supabase_url: 'https://cloud.devicecloud.dev', + session: { + access_token: 'access', + refresh_token: 'refresh', + expires_at: Math.floor(Date.now() / 1000) + 3600, + user_email: 'u@example.com', + user_id: 'u1', + }, + current_org_id: '7', + current_org_name: 'Acme', + }); + const calls = stubFetch(200, OWNER_SETTINGS); + + const { exit } = await run({ json: true }); + + expect(exit).to.equal(0); + expect(calls[0].headers.authorization).to.equal('Bearer access'); + expect(calls[0].headers['x-dcd-org']).to.equal('7'); + expect(calls[0].headers).not.to.have.property('x-app-api-key'); + }); + + it('prints every section for an owner', async () => { + stubFetch(200, OWNER_SETTINGS); + + const { exit, out } = await run({ 'api-key': 'k' }); + + expect(exit).to.equal(0); + for (const expected of [ + 'Team', + 'Acme', + 'sign-in requirement a passkey', + 'iOS m4', + 'min 0 · max 2', + 'Android gpu1', + 'not enabled', + 'standard pool', + 'min 2 · max 12', + 'standard pool is shared by iOS default and Android cpu1', + '10 min per flow', + '20 min per flow with EXTENDED_RUNTIME', + 'on · Android retries move to M1 runners', + '$200 per billing period, on top of included credits', + 'webhook connected', + 'slack not connected', + 'github connected', + ]) { + expect(out).to.include(expected); + } + expect(out).not.to.include('owner or admin only'); + }); + + it('marks the owner/admin settings for a standard member instead of showing them as off', async () => { + stubFetch(200, STANDARD_SETTINGS); + + const { exit, out } = await run({ 'api-key': 'k' }); + + expect(exit).to.equal(0); + expect(out.match(/owner or admin only/g)).to.have.length(3); + expect(out).to.include('Some settings are shown to team owners and admins only.'); + }); + + it('describes the empty states', async () => { + stubFetch(200, { + ...OWNER_SETTINGS, + name: null, + testRuntime: { defaultMinutes: 10, extendedMinutes: null }, + retryEscalation: { available: false, target: null, enabled: false }, + overage: { hasSubscription: true, limitUsd: null }, + concurrency: { runners: [], pools: [] }, + }); + + const { out } = await run({ 'api-key': 'k' }); + + expect(out).to.include('(unnamed)'); + expect(out).to.match(/extended\s+off/); + expect(out).to.include('retry escalation not available'); + expect(out).to.include('overage limit uncapped'); + expect(out).to.match(/Concurrency\n\s+⎿ none/); + }); + + it('says so when the API predates the endpoint', async () => { + stubFetch(404, { message: 'Cannot GET /org/settings' }); + + const { exit, out } = await run({ 'api-key': 'k', json: true }); + + expect(exit).to.equal(1); + const body = JSON.parse(out); + expect(body.status).to.equal('FAILED'); + expect(body.error).to.include("doesn't support reading team settings yet"); + }); + + it('passes a 403 through, e.g. for a key scoped to device sessions', async () => { + stubFetch(403, { message: 'This API key is limited to device sessions', error: 'API_KEY_SCOPE' }); + + const { exit, out } = await run({ 'api-key': 'k', json: true }); + + expect(exit).to.equal(1); + expect(JSON.parse(out).error).to.include('This API key is limited to device sessions'); + }); +});