diff --git a/.changeset/30889-os-mcp-connect.md b/.changeset/30889-os-mcp-connect.md new file mode 100644 index 00000000000..16063b49982 --- /dev/null +++ b/.changeset/30889-os-mcp-connect.md @@ -0,0 +1,14 @@ +--- +'@objectstack/cli': patch +--- + +feat(cli): `os mcp connect` registers your environment's MCP server with Claude Code in one command + +Clause-②: no +Metadata-protocol: none + +`os mcp connect` finds the environment `os deploy` deploys to (`--env`, then the active environment for this control plane, then your organization's only one; several with no `--env` is refused, as deploy refuses) and runs `claude mcp add --transport http NAME https://ENV-HOST/api/v1/mcp`. The server is named after the environment (its slug, else its display name, else its id), so several environments can be registered side by side; `--name` overrides it. + +- `--print` prints the endpoint and the `claude mcp add` line and runs nothing. For any other MCP client, add that endpoint as a remote HTTP MCP server in the client's own settings. +- `--url http://localhost:3000` connects a self-hosted or local server instead, named `objectstack` like the `os dev` banner's Connect row. The banner now prints its line through the same builder, so the two stay one spelling. +- No token is stored or handed to the client. Claude Code runs the environment's own OAuth: run `/mcp` in Claude Code and the browser shows the environment's sign-in and consent. The command prints where to revoke that grant (Account → Connect an AI Assistant in the environment's console). diff --git a/packages/cli/src/commands/dev-mcp-connect-hint-origin.test.ts b/packages/cli/src/commands/dev-mcp-connect-hint-origin.test.ts index 737bec548ca..c998425eacc 100644 --- a/packages/cli/src/commands/dev-mcp-connect-hint-origin.test.ts +++ b/packages/cli/src/commands/dev-mcp-connect-hint-origin.test.ts @@ -38,6 +38,21 @@ import { OBJECTSTACK_MCP_SERVER_NAME, renderSkillMarkdown } from '@objectstack/m import { printMcpConnectHint } from './dev.js'; import { AUTH_BASE_URL_ENV_NAMES, resolveAuthBaseUrl } from './serve.js'; import { printServerReady, type ServerReadyOptions } from '../utils/format.js'; +import McpConnect from './mcp/connect.js'; + +// Pay the first load of what `serve.ts` reaches through dynamic `import()`s at +// MODULE LOAD, outside any clocked case (`pnpm check:test-source-alias`). +import '@objectstack/metadata-protocol'; +import '@objectstack/metadata'; +import '@objectstack/objectql'; +import '@objectstack/plugin-hono-server'; +import '@objectstack/rest'; +import '@objectstack/service-settings'; +import '@objectstack/service-datasource'; +import '@objectstack/driver-turso'; +import '@objectstack/driver-sql'; +import '@objectstack/platform-objects/plugin'; +import '@objectstack/plugin-security'; const HERE = dirname(fileURLToPath(import.meta.url)); const DEV_SOURCE = readFileSync(resolve(HERE, 'dev.ts'), 'utf8'); @@ -371,11 +386,23 @@ describe('os dev MCP connect hint — origin (#16734)', () => { expect(skill).toEqual([OBJECTSTACK_MCP_SERVER_NAME]); }); + it('`os mcp connect --url` for the same origin prints the very line the banner prints', async () => { + const banner = boot(3000).split('\n').find((l) => l.includes('Connect claude mcp add')); + expect(banner).toBeDefined(); + + lines = []; + await McpConnect.run(['--url', 'http://localhost:3000', '--print']); + const connect = lines.find((l) => l.includes('Connect claude mcp add')); + + expect(connect?.trim()).toBe(banner!.trim()); + }); + it('dev reads that constant and derives no name of its own', () => { // The name used to be the folder `os dev` ran in, so a `hotcrm/` checkout // registered the server as `hotcrm` while the skill said `objectstack`. expect(DEV_SOURCE).toContain("import { OBJECTSTACK_MCP_SERVER_NAME } from '@objectstack/mcp';"); - expect(DEV_SOURCE).toContain('claude mcp add --transport http ${OBJECTSTACK_MCP_SERVER_NAME} '); + // The line is `os mcp connect`'s builder, fed that constant: one spelling for both commands. + expect(DEV_SOURCE).toContain('claudeMcpAddLine(OBJECTSTACK_MCP_SERVER_NAME, '); expect(DEV_SOURCE).not.toMatch(/basename\(process\.cwd\(\)\)/); }); }); diff --git a/packages/cli/src/commands/dev.ts b/packages/cli/src/commands/dev.ts index b6d6fc84c9c..bb00f93aa8e 100644 --- a/packages/cli/src/commands/dev.ts +++ b/packages/cli/src/commands/dev.ts @@ -35,6 +35,7 @@ import { import { artifactObjectNames } from '../utils/stack-collections.js'; import { readEnvWithDeprecation, isMcpServerEnabled } from '@objectstack/types'; import { OBJECTSTACK_MCP_SERVER_NAME } from '@objectstack/mcp'; +import { claudeMcpAddLine, MCP_ENDPOINT_PATH } from './mcp/connect.js'; // The ONE port contract, shared with `start` and with the `serve` child this // command spawns (#12673). ⛔ Nothing about ports is declared in this file — // no range, no reader, no wording; a second copy of the bound is exactly what @@ -194,6 +195,9 @@ export function prepareDevDatabaseDirectory( * used to be the current folder's basename, so one endpoint was registered as * the folder's name from the banner and as `objectstack` from the skill and * the console: two entries for one server in the agent's config. + * + * The line itself is `os mcp connect`'s ({@link claudeMcpAddLine}), so + * `os mcp connect --url ` prints and runs exactly this row. */ export function printMcpConnectHint( opts: { boundPort: number | string; boundProtocol?: ListenerProtocol }, @@ -202,9 +206,9 @@ export function printMcpConnectHint( if (baseOrigin === null) return; console.log(); console.log(chalk.cyan(' 🤖 MCP server — connect a coding agent:')); - console.log(` Endpoint ${baseOrigin}/api/v1/mcp`); - console.log(` Skill ${baseOrigin}/api/v1/mcp/skill`); - console.log(chalk.dim(` Connect claude mcp add --transport http ${OBJECTSTACK_MCP_SERVER_NAME} ${baseOrigin}/api/v1/mcp`)); + console.log(` Endpoint ${baseOrigin}${MCP_ENDPOINT_PATH}`); + console.log(` Skill ${baseOrigin}${MCP_ENDPOINT_PATH}/skill`); + console.log(chalk.dim(` Connect ${claudeMcpAddLine(OBJECTSTACK_MCP_SERVER_NAME, `${baseOrigin}${MCP_ENDPOINT_PATH}`)}`)); console.log(chalk.dim(' Disable OS_MCP_SERVER_ENABLED=false')); } diff --git a/packages/cli/src/commands/mcp/connect.ts b/packages/cli/src/commands/mcp/connect.ts new file mode 100644 index 00000000000..115c956e8d4 --- /dev/null +++ b/packages/cli/src/commands/mcp/connect.ts @@ -0,0 +1,292 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * `os mcp connect` — register your environment's MCP server with your MCP + * client in one command. The client then runs the environment's own OAuth. + * + * ## Which server + * + * The environment `os deploy` deploys to, resolved by the same function + * (`resolveInstallTarget`): `--env`, then the active environment recorded for + * this control plane, then your organization's only environment. None or + * several is a refusal naming `--env`, exactly as deploy refuses. Its URL is + * the control plane's environment read (`readCloudEnvironment`, the read + * deploy's wait uses for the environment's origin) plus {@link MCP_ENDPOINT_PATH}. + * `--url` skips the control plane: a self-hosted server or a local `os dev`. + * + * ## Which name + * + * The environment's own (its slug, else its display name, else its id), made + * safe for a client's server name, so several environments can be registered + * side by side. A `--url` server is named {@link OBJECTSTACK_MCP_SERVER_NAME}, + * the name `os dev`'s banner and the served `SKILL.md` give it, so a local + * server is never registered twice under two names. `--name` overrides both. + * + * ## No token, anywhere + * + * ⛔ The command stores no MCP token and writes none into a client config. + * It hands the client the URL alone; on first use the client follows the + * environment's OAuth discovery, registers itself, and the browser shows the + * environment's sign-in and consent. A token copied into a config file would + * expire within the hour, skip the client's refresh, and outlive a revoked + * grant. Reusing the CLI's ObjectOS Cloud login for that consent is out of + * scope: it waits on the decision whether the control plane becomes the one + * authorization server for the CLI and MCP. + * + * ## Which client + * + * Claude Code, by running `claude mcp add --transport http NAME URL` + * ({@link claudeMcpAddArgs}, the one spelling `os dev`'s banner prints too). + * `--print` prints that line and the endpoint and runs nothing, which is also + * how to connect any other client: add the endpoint as a remote HTTP MCP server + * in its own settings. + */ + +import { spawnSync, type SpawnSyncReturns } from 'node:child_process'; +import { Command, Flags } from '@oclif/core'; +import { OBJECTSTACK_MCP_SERVER_NAME } from '@objectstack/mcp'; +import { printError, printHeader, printStep, printSuccess, isExitSignal } from '../../utils/format.js'; +import { DEFAULT_CLOUD_URL, resolveCloudCredential } from '../../utils/cloud-config.js'; +import { describeEnvironment, resolveInstallTarget } from '../../utils/install-target.js'; +import { readCloudEnvironment } from '../../utils/served-version.js'; + +/** Where every ObjectStack server mounts its MCP endpoint. */ +export const MCP_ENDPOINT_PATH = '/api/v1/mcp'; + +/** The clients this command can register with. */ +export const MCP_CLIENTS = ['claude-code'] as const; + +/** A server name every client accepts: letters, digits, `-` and `_`. */ +const SERVER_NAME = /^[A-Za-z0-9_-]+$/; + +/** `claude`'s arguments that register `url` as the remote HTTP MCP server `name`. */ +export function claudeMcpAddArgs(name: string, url: string): string[] { + return ['mcp', 'add', '--transport', 'http', name, url]; +} + +/** The `claude mcp add` line, as `os dev`'s banner and this command print it. */ +export function claudeMcpAddLine(name: string, url: string): string { + return ['claude', ...claudeMcpAddArgs(name, url)].join(' '); +} + +/** + * The environment's name as a client's server name: its slug, else its + * display name, else its id, lower-cased with every run of other characters + * turned into one `-`. A value with nothing left (a display name in another + * script) falls through to the next. + */ +export function environmentServerName(env: { id: string; slug?: string; displayName?: string }): string { + for (const candidate of [env.slug, env.displayName, env.id]) { + const safe = (candidate ?? '').toLowerCase().replace(/[^a-z0-9_-]+/g, '-').replace(/^-+|-+$/g, ''); + if (safe) return safe; + } + return OBJECTSTACK_MCP_SERVER_NAME; +} + +/** + * `--url` as a server base URL: `http(s)://host[:port][/prefix]`, with no + * query and no fragment. The MCP path is added here, so a URL that already + * ends in it is refused rather than doubled. + */ +export function mcpUrlFromBase(raw: string): { ok: true; mcpUrl: string } | { ok: false; reason: string } { + let parsed: URL; + try { + parsed = new URL(raw.trim()); + } catch { + return { ok: false, reason: `\`--url ${raw}\` is not a URL. Pass the server's base URL, such as http://localhost:3000.` }; + } + if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') { + return { ok: false, reason: `\`--url\` must be an http or https URL, not ${parsed.protocol}` }; + } + if (parsed.search || parsed.hash) { + return { ok: false, reason: '`--url` takes the server\'s base URL, with no query or fragment.' }; + } + const path = parsed.pathname.replace(/\/+$/, ''); + if (path === MCP_ENDPOINT_PATH || path.endsWith(MCP_ENDPOINT_PATH)) { + return { + ok: false, + reason: `\`--url\` takes the server's base URL; this command adds ${MCP_ENDPOINT_PATH} itself. Pass ${parsed.origin}${path.slice(0, -MCP_ENDPOINT_PATH.length)}.`, + }; + } + return { ok: true, mcpUrl: `${parsed.origin}${path}${MCP_ENDPOINT_PATH}` }; +} + +/** Runs a client's own CLI. A seam, so a test can stand in for `claude`. */ +export const mcpClientRunner = { + run(command: string, args: string[]): SpawnSyncReturns { + // `claude` is a `.cmd` shim on Windows, which only a shell resolves. + return spawnSync(command, args, { stdio: 'inherit', shell: process.platform === 'win32' }); + }, +}; + +export default class McpConnect extends Command { + static override description = + "Register your environment's MCP server with your MCP client (Claude Code); the client then runs the environment's own sign-in and consent"; + + static override examples = [ + '$ os mcp connect', + '$ os mcp connect --print # print the endpoint and the `claude mcp add` line, run nothing', + '$ os mcp connect --env env_abc123 # your account reaches several environments', + '$ os mcp connect --url http://localhost:3000 # a self-hosted or local server', + ]; + + static override flags = { + env: Flags.string({ + description: + 'Environment id to connect to. Defaults to the environment `os environments switch` recorded ' + + "for this control plane, then to your organization's only environment", + env: 'OS_ENVIRONMENT_ID', + }), + url: Flags.string({ + description: 'Base URL of a self-hosted or local server (e.g. http://localhost:3000); skips ObjectOS Cloud', + }), + name: Flags.string({ + description: "Server name in the client (default: the environment's name; `objectstack` with --url)", + }), + client: Flags.string({ + description: 'MCP client to register with. For any other client, use --print and add the endpoint in its settings', + options: [...MCP_CLIENTS], + default: 'claude-code', + }), + print: Flags.boolean({ + description: 'Print the endpoint and the command that registers it; run nothing', + default: false, + }), + server: Flags.string({ + char: 's', + description: 'ObjectOS Cloud control-plane URL (override for self-hosted control planes)', + env: 'OS_CLOUD_URL', + default: DEFAULT_CLOUD_URL, + }), + token: Flags.string({ + char: 't', + description: 'API key for ObjectOS Cloud (bearer token; defaults to OS_CLOUD_API_KEY / OS_TOKEN, then `os cloud login`). Used only to find the environment; never handed to the MCP client', + env: 'OS_CLOUD_API_KEY', + }), + }; + + async run(): Promise { + const { flags } = await this.parse(McpConnect); + printHeader('MCP connect'); + + try { + if (flags.name !== undefined && !SERVER_NAME.test(flags.name)) { + printError(`\`--name ${flags.name}\` is not a server name: use letters, digits, \`-\` and \`_\` only.`); + this.exit(1); + return; + } + + let mcpUrl: string; + let name: string; + let where: string; + if (flags.url !== undefined) { + const local = mcpUrlFromBase(flags.url); + if (!local.ok) { + printError(local.reason); + this.exit(1); + return; + } + mcpUrl = local.mcpUrl; + name = flags.name ?? OBJECTSTACK_MCP_SERVER_NAME; + where = new URL(mcpUrl).origin; + } else { + const { token, baseUrl } = await resolveCloudCredential({ token: flags.token, server: flags.server }); + if (!token) { + printError( + 'Not logged in to ObjectOS Cloud. Run `os cloud login` first, then `os mcp connect` again ' + + '(or pass `--url` for a self-hosted or local server).', + ); + this.exit(1); + return; + } + const target = await resolveInstallTarget({ + subject: '`os mcp connect`', + purpose: 'to connect to', + explicit: flags.env, + baseUrl, + token, + timeoutMs: 30_000, + }); + if (target.kind === 'refused') { + printError(target.message); + this.exit(1); + return; + } + const env = await readCloudEnvironment({ baseUrl, token, environmentId: target.environmentId }); + const displayName = target.displayName ?? (env.ok ? env.displayName : undefined); + where = describeEnvironment({ id: target.environmentId, displayName }); + if (!env.ok) { + printError( + `${where}'s address could not be read from ${baseUrl}` + + `${env.status ? ` (${env.status})` : ''}: ${env.error}. Nothing was registered.`, + ); + this.exit(1); + return; + } + if (!env.origin) { + printError( + `${baseUrl} reports no hostname for ${where}, so it has no MCP URL to register. ` + + 'Open the environment in the ObjectOS Cloud console to check it is provisioned. Nothing was registered.', + ); + this.exit(1); + return; + } + mcpUrl = `${env.origin}${MCP_ENDPOINT_PATH}`; + name = flags.name ?? environmentServerName({ id: target.environmentId, slug: env.slug, displayName }); + printStep( + target.source === 'only' + ? `Connecting to ${where}, your organization's only environment` + : `Connecting to ${where}`, + ); + } + + const line = claudeMcpAddLine(name, mcpUrl); + console.log(` Endpoint ${mcpUrl}`); + console.log(` Name ${name}`); + console.log(` Connect ${line}`); + + if (!flags.print) { + console.log(''); + printStep(`Registering ${name} with Claude Code...`); + const ran = mcpClientRunner.run('claude', claudeMcpAddArgs(name, mcpUrl)); + if (ran.error) { + const missing = (ran.error as NodeJS.ErrnoException).code === 'ENOENT'; + printError( + missing + ? 'Claude Code\'s `claude` command was not found on your PATH. Install Claude Code, then run the Connect line above ' + + '(or `os mcp connect` again). For another client, add the Endpoint above as a remote HTTP MCP server in its settings.' + : `\`claude\` could not be started: ${ran.error.message}. Run the Connect line above yourself.`, + ); + this.exit(1); + return; + } + if (ran.status !== 0) { + printError( + `\`claude mcp add\` exited ${ran.status ?? `on ${ran.signal}`}; its reason is above. ` + + `If ${name} is already registered, remove it with \`claude mcp remove ${name}\` or pick another --name.`, + ); + this.exit(ran.status || 1); + return; + } + printSuccess(`Registered ${name} with Claude Code.`); + } + + console.log(''); + console.log( + ` Sign-in In Claude Code, run /mcp and authenticate ${name}: your browser shows ${where}'s sign-in and consent. ` + + 'This command stored no token.', + ); + console.log( + ` Revoke In ${where}'s console: Account → Connect an AI Assistant → your authorized assistants → Revoke.`, + ); + console.log( + ' Model MCP reads the environment for context. A managed package\'s content changes through its source ' + + 'and `os deploy`, not through MCP.', + ); + } catch (error) { + if (isExitSignal(error)) throw error; + printError((error as Error).message); + this.exit(1); + } + } +} diff --git a/packages/cli/src/utils/install-target.ts b/packages/cli/src/utils/install-target.ts index 0605353dcc9..204d141755c 100644 --- a/packages/cli/src/utils/install-target.ts +++ b/packages/cli/src/utils/install-target.ts @@ -121,9 +121,12 @@ export function describeEnvironment(env: { id: string; displayName?: string }): /** * Resolve the install target. `subject` names what needs it, for the refusal's * first words — `--install` on `os package publish`, `os deploy` on deploy. + * `purpose` finishes "needs an environment …" for a caller that does not + * install (`os mcp connect` connects to it); the resolution is the same one. */ export async function resolveInstallTarget(args: { subject: string; + purpose?: string; explicit: string | undefined; baseUrl: string; token: string; @@ -136,6 +139,7 @@ export async function resolveInstallTarget(args: { const active = await resolveCloudActiveEnvironmentId(args.baseUrl); if (active) return { kind: 'resolved', environmentId: active, source: 'active' }; + const needs = `${args.subject} needs an environment ${args.purpose ?? 'to install into'}`; const remedy = 'Pass `--env ` (or set $OS_ENVIRONMENT_ID), or record one with `os environments switch `.'; const listed = await (args.list ?? listCloudEnvironments)({ baseUrl: args.baseUrl, @@ -146,7 +150,7 @@ export async function resolveInstallTarget(args: { return { kind: 'refused', message: - `${args.subject} needs an environment to install into. None was given, and the list of your ` + `${needs}. None was given, and the list of your ` + `organization's environments on ${args.baseUrl} could not be read` + `${listed.status ? ` (${listed.status})` : ''}: ${listed.error}. ${remedy}`, }; @@ -161,14 +165,14 @@ export async function resolveInstallTarget(args: { return { kind: 'refused', message: - `${args.subject} needs an environment to install into, and your account has none on ${args.baseUrl}. ` + `${needs}, and your account has none on ${args.baseUrl}. ` + `Create one in the ObjectOS Cloud console, then run this again. ${remedy}`, }; } return { kind: 'refused', message: - `${args.subject} needs an environment to install into, and your account can reach ` + `${needs}, and your account can reach ` + `${candidates.length} on ${args.baseUrl}, so none was picked:\n` + candidates.map((env) => ` • ${describeEnvironment(env)}`).join('\n') + `\n ${remedy}`, diff --git a/packages/cli/src/utils/served-version.ts b/packages/cli/src/utils/served-version.ts index 6db96548c7c..f12517219bc 100644 --- a/packages/cli/src/utils/served-version.ts +++ b/packages/cli/src/utils/served-version.ts @@ -144,28 +144,57 @@ export function interpretServedReport( return { kind: 'pending', observed }; } +/** One environment as its detail read answers it, reduced to what the CLI addresses it by. */ +export interface CloudEnvironmentAddress { + /** `https://` + `data.environment.hostname`; `undefined` when the row carries none. */ + origin: string | undefined; + /** `data.environment.slug`, when the row carries one. */ + slug: string | undefined; + /** `data.environment.display_name`, when the row carries one. */ + displayName: string | undefined; +} + /** - * The environment's own origin, from the control plane's environment read - * (`data.environment.hostname`). `undefined` when it has none or the read - * fails — the wait then cannot wake the build, and the caller says so. + * The control plane's environment read (`GET /api/v1/cloud/environments/{id}`), + * reduced to {@link CloudEnvironmentAddress}. Never throws: a network failure + * and a non-2xx are an `ok: false` naming the status, so a caller that cannot + * go on without the answer (`os mcp connect`) says why, and one that can + * ({@link fetchEnvironmentOrigin}) reads it as "no origin". */ -export async function fetchEnvironmentOrigin(target: Pick): Promise { +export async function readCloudEnvironment( + target: Pick, +): Promise<({ ok: true } & CloudEnvironmentAddress) | { ok: false; status: number; error: string }> { try { const response = await fetch( `${target.baseUrl}/api/v1/cloud/environments/${encodeURIComponent(target.environmentId)}`, { headers: { Authorization: `Bearer ${target.token}` } }, ); - if (!response.ok) return undefined; const parsed: any = await response.json().catch(() => null); - const hostname = (parsed?.data ?? parsed)?.environment?.hostname; - if (typeof hostname !== 'string' || !hostname.trim()) return undefined; - const trimmed = hostname.trim().replace(/\/+$/, ''); - return /^https?:\/\//i.test(trimmed) ? trimmed : `https://${trimmed}`; - } catch { - return undefined; + if (!response.ok) return { ok: false, status: response.status, error: readErrorMessage(parsed, response) }; + const row = (parsed?.data ?? parsed)?.environment; + const text = (value: unknown) => (typeof value === 'string' && value.trim() ? value.trim() : undefined); + const hostname = text(row?.hostname)?.replace(/\/+$/, ''); + return { + ok: true, + origin: hostname ? (/^https?:\/\//i.test(hostname) ? hostname : `https://${hostname}`) : undefined, + slug: text(row?.slug), + displayName: text(row?.display_name), + }; + } catch (err: any) { + return { ok: false, status: 0, error: err?.message ?? String(err) }; } } +/** + * The environment's own origin, from the control plane's environment read + * (`data.environment.hostname`). `undefined` when it has none or the read + * fails — the wait then cannot wake the build, and the caller says so. + */ +export async function fetchEnvironmentOrigin(target: Pick): Promise { + const read = await readCloudEnvironment(target); + return read.ok ? read.origin : undefined; +} + /** * One request to the environment itself, so a request-driven rebuild starts * (or a failed one retries). Best-effort by design: the answer while it builds diff --git a/packages/cli/test/mcp-connect.test.ts b/packages/cli/test/mcp-connect.test.ts new file mode 100644 index 00000000000..2811ef78630 --- /dev/null +++ b/packages/cli/test/mcp-connect.test.ts @@ -0,0 +1,298 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * `os mcp connect` against a stubbed control plane (#30889). + * + * The command runs for real: its credential and environment resolution (the + * one `os deploy` uses), the real `cloud.json` under a redirected `$HOME`. + * Two seams are replaced: `fetch` is the control plane, and the client runner + * stands in for Claude Code's `claude`. + */ + +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; +import { mkdtemp, mkdir, readdir, readFile, rm, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import type { SpawnSyncReturns } from 'node:child_process'; +import { OBJECTSTACK_MCP_SERVER_NAME } from '@objectstack/mcp'; + +const { + default: McpConnect, + mcpClientRunner, + environmentServerName, + mcpUrlFromBase, + claudeMcpAddLine, +} = await import('../src/commands/mcp/connect.js'); + +const CLOUD_PLANE = 'http://cloud.test'; +const CLOUD_TOKEN = 'cloud_tok_30889'; +const MANAGED_ENV = ['OS_CLOUD_URL', 'OS_CLOUD_API_KEY', 'OS_TOKEN', 'OS_ENVIRONMENT_ID'] as const; + +type Call = { url: string; method: string; auth: string | undefined }; + +interface PlaneOptions { + environments?: Array>; + /** The detail read's row, by environment id (default: hostname `.example.test`, no slug). */ + detail?: (id: string) => Record | null; +} + +/** The control plane: the environment list and one environment's detail read. */ +function stubPlane(options: PlaneOptions = {}): Call[] { + const calls: Call[] = []; + vi.stubGlobal('fetch', vi.fn(async (input: string, init: any = {}) => { + const url = String(input); + const method = init?.method ?? 'GET'; + calls.push({ url, method, auth: init?.headers?.Authorization }); + const answer = (data: unknown) => ({ ok: true, status: 200, statusText: 'OK', json: async () => ({ success: true, data }) }) as any; + if (method === 'GET' && url === `${CLOUD_PLANE}/api/v1/cloud/environments`) { + const environments = options.environments ?? [{ id: 'env_acme', display_name: 'Acme', status: 'active' }]; + return answer({ environments, total: environments.length }); + } + const detail = url.match(/\/api\/v1\/cloud\/environments\/([^/]+)$/); + if (method === 'GET' && detail) { + const id = decodeURIComponent(detail[1]); + const row = options.detail ? options.detail(id) : { id, hostname: `${id.replace(/_/g, '-')}.example.test` }; + if (row === null) { + return { ok: false, status: 404, statusText: 'Not Found', json: async () => ({ success: false, error: { message: 'Environment not found' } }) } as any; + } + return answer({ environment: row }); + } + return { ok: false, status: 404, statusText: 'Not Found', json: async () => ({ success: false, error: { message: `unexpected ${method} ${url}` } }) } as any; + })); + return calls; +} + +/** Every file under a directory, with its content. */ +async function snapshot(dir: string): Promise> { + const out: Record = {}; + for (const entry of await readdir(dir, { recursive: true, withFileTypes: true })) { + if (!entry.isFile()) continue; + const path = join(entry.parentPath, entry.name); + out[path] = await readFile(path, 'utf8'); + } + return out; +} + +describe('os mcp connect', () => { + let home = ''; + let work = ''; + const previous: Record = {}; + const prevCwd = process.cwd(); + let output: string[] = []; + let runner: ReturnType SpawnSyncReturns>>; + + beforeEach(async () => { + home = await mkdtemp(join(tmpdir(), 'os-30889-mcp-home-')); + work = await mkdtemp(join(tmpdir(), 'os-30889-mcp-work-')); + await mkdir(join(home, '.objectstack'), { recursive: true }); + for (const key of ['HOME', 'USERPROFILE', ...MANAGED_ENV]) previous[key] = process.env[key]; + process.env.HOME = home; + process.env.USERPROFILE = home; + for (const key of MANAGED_ENV) delete process.env[key]; + await writeFile(join(home, '.objectstack', 'cloud.json'), JSON.stringify({ url: CLOUD_PLANE, token: CLOUD_TOKEN, createdAt: 'now' })); + process.chdir(work); + + runner = vi.fn(() => ({ status: 0, signal: null, pid: 1, output: [], stdout: Buffer.from(''), stderr: Buffer.from('') })); + vi.spyOn(mcpClientRunner, 'run').mockImplementation(runner); + + output = []; + const record = (...args: unknown[]) => { output.push(args.map(String).join(' ').replace(/\u001b\[[0-9;]*m/g, '')); }; + vi.spyOn(console, 'log').mockImplementation(record); + vi.spyOn(console, 'error').mockImplementation(record); + }); + + afterEach(async () => { + process.chdir(prevCwd); + vi.unstubAllGlobals(); + vi.restoreAllMocks(); + for (const [key, value] of Object.entries(previous)) { + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + } + await rm(home, { recursive: true, force: true }); + await rm(work, { recursive: true, force: true }); + }); + + async function connect(argv: string[] = []): Promise { + try { + await McpConnect.run(argv); + return undefined; + } catch (err: any) { + const exit = err?.oclif?.exit ?? err?.exitCode; + if (exit === undefined) throw err; + return exit; + } + } + + const text = () => output.join('\n'); + + it('--print: prints the only environment\'s MCP URL and its `claude mcp add` line, named for the environment, and runs nothing', async () => { + const calls = stubPlane({ + detail: (id) => ({ id, slug: 'acme-prod', display_name: 'Acme', hostname: 'acme.example.test' }), + }); + + const exit = await connect(['--print']); + + expect(exit, text()).toBeUndefined(); + expect(text()).toContain("Connecting to Acme (env_acme), your organization's only environment"); + expect(text()).toContain('Endpoint https://acme.example.test/api/v1/mcp'); + expect(text()).toContain('Connect claude mcp add --transport http acme-prod https://acme.example.test/api/v1/mcp'); + expect(runner).not.toHaveBeenCalled(); + // The environment was read from the control plane the CLI is logged in to, with that login. + expect(calls.map((c) => c.url)).toEqual([ + `${CLOUD_PLANE}/api/v1/cloud/environments`, + `${CLOUD_PLANE}/api/v1/cloud/environments/env_acme`, + ]); + }); + + it('--url http://localhost:3000: prints the local server under the name `os dev`\'s banner gives it, with no control plane', async () => { + // That the banner's Connect row is this same line is pinned beside the banner's other + // pins, in `src/commands/dev-mcp-connect-hint-origin.test.ts`. + const calls = stubPlane(); + + const exit = await connect(['--url', 'http://localhost:3000', '--print']); + + expect(exit, text()).toBeUndefined(); + expect(text()).toContain(`Connect claude mcp add --transport http ${OBJECTSTACK_MCP_SERVER_NAME} http://localhost:3000/api/v1/mcp`); + expect(calls).toEqual([]); + }); + + it('several environments and no --env: refuses non-zero, as `os deploy` does, and registers nothing', async () => { + const calls = stubPlane({ + environments: [ + { id: 'env_a', display_name: 'Alpha', status: 'active' }, + { id: 'env_b', display_name: 'Beta', status: 'active' }, + ], + }); + + const exit = await connect(); + + expect(exit).toBe(1); + expect(text()).toContain('`os mcp connect` needs an environment to connect to, and your account can reach 2'); + expect(text()).toContain('Alpha (env_a)'); + expect(text()).toContain('Pass `--env `'); + expect(runner).not.toHaveBeenCalled(); + expect(calls.some((c) => /environments\/env_/.test(c.url))).toBe(false); + }); + + it('runs `claude mcp add` with the URL alone: no token reaches the client, and the command writes no file', async () => { + stubPlane({ detail: (id) => ({ id, slug: 'acme', hostname: 'acme.example.test' }) }); + const homeBefore = await snapshot(home); + const workBefore = await snapshot(work); + + const exit = await connect(); + + expect(exit, text()).toBeUndefined(); + expect(runner).toHaveBeenCalledTimes(1); + const [command, args] = runner.mock.calls[0]; + expect(command).toBe('claude'); + expect(args).toEqual(['mcp', 'add', '--transport', 'http', 'acme', 'https://acme.example.test/api/v1/mcp']); + expect(args.join(' ')).not.toContain(CLOUD_TOKEN); + expect(args.some((a) => /header|bearer|authorization|token/i.test(a))).toBe(false); + expect(text()).not.toContain(CLOUD_TOKEN); + expect(await snapshot(home)).toEqual(homeBefore); + expect(await snapshot(work)).toEqual(workBefore); + expect(text()).toContain('Registered acme with Claude Code.'); + expect(text()).toContain('Account → Connect an AI Assistant'); + expect(text()).toContain('not through MCP'); + }); + + it('--env picks the environment, and the detail read names it', async () => { + const calls = stubPlane({ + environments: [ + { id: 'env_a', display_name: 'Alpha', status: 'active' }, + { id: 'env_b', display_name: 'Beta', status: 'active' }, + ], + detail: (id) => ({ id, display_name: 'Beta Staging', hostname: 'beta.example.test' }), + }); + + const exit = await connect(['--env', 'env_b', '--print']); + + expect(exit, text()).toBeUndefined(); + expect(text()).toContain('Connecting to Beta Staging (env_b)'); + expect(text()).toContain('claude mcp add --transport http beta-staging https://beta.example.test/api/v1/mcp'); + expect(calls.map((c) => c.url)).toEqual([`${CLOUD_PLANE}/api/v1/cloud/environments/env_b`]); + }); + + it('an environment with no hostname, or an unreadable one, is refused with nothing registered', async () => { + stubPlane({ detail: (id) => ({ id, slug: 'acme' }) }); + expect(await connect()).toBe(1); + expect(text()).toContain('reports no hostname for Acme (env_acme)'); + expect(runner).not.toHaveBeenCalled(); + + vi.unstubAllGlobals(); + output = []; + stubPlane({ detail: () => null }); + expect(await connect()).toBe(1); + expect(text()).toContain("Acme (env_acme)'s address could not be read from http://cloud.test (404): Environment not found"); + expect(runner).not.toHaveBeenCalled(); + }); + + it('not logged in: refuses, naming `os cloud login` and `--url`', async () => { + await rm(join(home, '.objectstack', 'cloud.json')); + const calls = stubPlane(); + + expect(await connect()).toBe(1); + expect(text()).toContain('Run `os cloud login` first'); + expect(calls).toEqual([]); + }); + + it('Claude Code not installed: exits non-zero and leaves the line to paste', async () => { + stubPlane({ detail: (id) => ({ id, slug: 'acme', hostname: 'acme.example.test' }) }); + runner.mockImplementation(() => ({ error: Object.assign(new Error('spawn claude ENOENT'), { code: 'ENOENT' }) }) as any); + + expect(await connect()).toBe(1); + expect(text()).toContain('Connect claude mcp add --transport http acme https://acme.example.test/api/v1/mcp'); + expect(text()).toContain('`claude` command was not found on your PATH'); + }); + + it('`claude mcp add` failing passes its exit code through', async () => { + stubPlane({ detail: (id) => ({ id, slug: 'acme', hostname: 'acme.example.test' }) }); + runner.mockImplementation(() => ({ status: 3, signal: null }) as any); + + expect(await connect()).toBe(3); + expect(text()).toContain('claude mcp remove acme'); + }); + + it('--name overrides the name, and a name a client would refuse is refused first', async () => { + stubPlane(); + expect(await connect(['--url', 'https://os.example.test', '--name', 'crm_local', '--print'])).toBeUndefined(); + expect(text()).toContain('claude mcp add --transport http crm_local https://os.example.test/api/v1/mcp'); + + output = []; + expect(await connect(['--url', 'https://os.example.test', '--name', 'my server'])).toBe(1); + expect(text()).toContain('is not a server name'); + expect(runner).not.toHaveBeenCalled(); + }); +}); + +describe('environmentServerName', () => { + it('takes the slug, then the display name, then the id, made safe for a server name', () => { + expect(environmentServerName({ id: 'env_1', slug: 'acme-prod', displayName: 'Acme' })).toBe('acme-prod'); + expect(environmentServerName({ id: 'env_1', displayName: 'Acme Production (EU)' })).toBe('acme-production-eu'); + // A display name with no Latin letters leaves nothing, so the id names it. + expect(environmentServerName({ id: 'env_1', displayName: '生产环境' })).toBe('env_1'); + }); +}); + +describe('mcpUrlFromBase', () => { + it('adds the MCP path to a base URL, keeping a path prefix', () => { + expect(mcpUrlFromBase('http://localhost:3000/')).toEqual({ ok: true, mcpUrl: 'http://localhost:3000/api/v1/mcp' }); + expect(mcpUrlFromBase('https://example.test/os')).toEqual({ ok: true, mcpUrl: 'https://example.test/os/api/v1/mcp' }); + }); + + it('refuses the MCP URL itself, a non-http URL, and a query, rather than guessing', () => { + const doubled = mcpUrlFromBase('http://localhost:3000/api/v1/mcp'); + expect(doubled.ok).toBe(false); + expect(!doubled.ok && doubled.reason).toContain('Pass http://localhost:3000.'); + expect(mcpUrlFromBase('ftp://example.test').ok).toBe(false); + expect(mcpUrlFromBase('http://example.test/?a=1').ok).toBe(false); + expect(mcpUrlFromBase('not a url').ok).toBe(false); + }); + + it('the line builder is the one `os dev` prints', () => { + expect(claudeMcpAddLine('objectstack', 'http://localhost:3000/api/v1/mcp')).toBe( + 'claude mcp add --transport http objectstack http://localhost:3000/api/v1/mcp', + ); + }); +});