|
| 1 | +// `insta mcp install` — write the insta-cloud remote MCP server into each coding agent's own |
| 2 | +// config format. Claude Code is NOT handled here — it has a real registry CLI (`claude mcp add`, |
| 3 | +// see setup.ts registerMcp); these are the config-file agents. All entries are OAuth (no |
| 4 | +// credential written): each client discovers the platform AS via RFC 9728 and runs the browser |
| 5 | +// flow on first use. |
| 6 | +import { promises as fs } from 'node:fs' |
| 7 | +import { existsSync } from 'node:fs' |
| 8 | +import os from 'node:os' |
| 9 | +import path from 'node:path' |
| 10 | +import { info } from '../util.js' |
| 11 | +import { DEFAULT_MCP_URL, MCP_SERVER_NAME, registerMcp } from './setup.js' |
| 12 | + |
| 13 | +export const MCP_AGENT_TARGETS = ['cursor', 'codex', 'opencode', 'copilot', 'factory-droid'] as const |
| 14 | +export type McpAgent = (typeof MCP_AGENT_TARGETS)[number] |
| 15 | + |
| 16 | +export function configPath(slug: McpAgent, home: string): string { |
| 17 | + switch (slug) { |
| 18 | + case 'cursor': return path.join(home, '.cursor', 'mcp.json') |
| 19 | + case 'codex': return path.join(home, '.codex', 'config.toml') |
| 20 | + case 'opencode': return path.join(home, '.config', 'opencode', 'opencode.json') |
| 21 | + case 'copilot': return path.join(home, '.copilot', 'mcp-config.json') |
| 22 | + case 'factory-droid': return path.join(home, '.factory', 'mcp.json') |
| 23 | + } |
| 24 | +} |
| 25 | + |
| 26 | +// An agent counts as "on this machine" when its config dir already exists — we configure what's |
| 27 | +// installed, never scaffold a tool the user doesn't have. |
| 28 | +export function detectAgents(home: string): McpAgent[] { |
| 29 | + return MCP_AGENT_TARGETS.filter((slug) => existsSync(path.dirname(configPath(slug, home)))) |
| 30 | +} |
| 31 | + |
| 32 | +// Merge our entry into existing JSON config. Returns null (skip, leave file alone) when the |
| 33 | +// existing content isn't valid JSON — never clobber a config we can't parse. |
| 34 | +export function renderJsonConfig(slug: McpAgent, existing: string | null, url: string): string | null { |
| 35 | + let root: any = {} |
| 36 | + if (existing && existing.trim()) { |
| 37 | + try { root = JSON.parse(existing) } catch { return null } |
| 38 | + if (typeof root !== 'object' || root === null || Array.isArray(root)) return null |
| 39 | + } |
| 40 | + if (slug === 'opencode') { |
| 41 | + // OpenCode: `mcp` key, `type: "remote"` schema (docs.opencode.ai). |
| 42 | + root.mcp = { ...(root.mcp ?? {}), [MCP_SERVER_NAME]: { type: 'remote', url, enabled: true } } |
| 43 | + root.$schema ??= 'https://opencode.ai/config.json' |
| 44 | + } else { |
| 45 | + const entry = |
| 46 | + slug === 'cursor' ? { url } // Cursor auto-detects HTTP from `url` |
| 47 | + : slug === 'copilot' ? { type: 'http', url, tools: ['*'] } |
| 48 | + : { type: 'http', url, disabled: false } // factory-droid |
| 49 | + root.mcpServers = { ...(root.mcpServers ?? {}), [MCP_SERVER_NAME]: entry } |
| 50 | + } |
| 51 | + return JSON.stringify(root, null, 2) + '\n' |
| 52 | +} |
| 53 | + |
| 54 | +// Codex config is TOML. Appending a complete `[mcp_servers.<name>]` table is always valid at |
| 55 | +// EOF, so we avoid a TOML parser: string-detect for idempotency, append for install. |
| 56 | +export function renderCodexConfig(existing: string | null, url: string): string | null { |
| 57 | + const base = existing ?? '' |
| 58 | + if (base.includes(`[mcp_servers.${MCP_SERVER_NAME}]`)) return null // already configured |
| 59 | + const sep = base.length && !base.endsWith('\n') ? '\n' : '' |
| 60 | + return `${base}${sep}\n[mcp_servers.${MCP_SERVER_NAME}]\nurl = "${url}"\n` |
| 61 | +} |
| 62 | + |
| 63 | +// Install for one agent. Returns 'installed' | 'already' | 'skipped' (unparseable config). |
| 64 | +export async function installFor(slug: McpAgent, home: string, url: string): Promise<'installed' | 'already' | 'skipped'> { |
| 65 | + const file = configPath(slug, home) |
| 66 | + let existing: string | null = null |
| 67 | + try { existing = await fs.readFile(file, 'utf8') } catch { existing = null } |
| 68 | + if (slug === 'codex') { |
| 69 | + const next = renderCodexConfig(existing, url) |
| 70 | + if (next === null) return 'already' |
| 71 | + await fs.mkdir(path.dirname(file), { recursive: true }) |
| 72 | + await fs.writeFile(file, next) |
| 73 | + return 'installed' |
| 74 | + } |
| 75 | + if (existing) { |
| 76 | + try { |
| 77 | + const root = JSON.parse(existing) |
| 78 | + const entry = slug === 'opencode' ? root?.mcp?.[MCP_SERVER_NAME] : root?.mcpServers?.[MCP_SERVER_NAME] |
| 79 | + if (entry) return 'already' |
| 80 | + } catch { /* fall through to renderJsonConfig, which refuses to clobber */ } |
| 81 | + } |
| 82 | + const next = renderJsonConfig(slug, existing, url) |
| 83 | + if (next === null) return 'skipped' |
| 84 | + await fs.mkdir(path.dirname(file), { recursive: true }) |
| 85 | + await fs.writeFile(file, next) |
| 86 | + return 'installed' |
| 87 | +} |
| 88 | + |
| 89 | +const AGENT_LABELS: Record<McpAgent, string> = { |
| 90 | + cursor: 'Cursor', codex: 'OpenAI Codex', opencode: 'OpenCode', copilot: 'GitHub Copilot', 'factory-droid': 'Factory Droid', |
| 91 | +} |
| 92 | + |
| 93 | +// Configure every detected config-file agent (or one forced via `agent`). Returns the labels of |
| 94 | +// agents now configured (installed or already present) for the caller's summary line. |
| 95 | +export async function installAgentConfigs(agent?: string, home: string = os.homedir()): Promise<string[]> { |
| 96 | + const url = process.env.INSTA_MCP_URL || DEFAULT_MCP_URL |
| 97 | + const targets = agent |
| 98 | + ? (MCP_AGENT_TARGETS as readonly string[]).includes(agent) ? [agent as McpAgent] : [] |
| 99 | + : detectAgents(home) |
| 100 | + if (agent && targets.length === 0) { |
| 101 | + info(`unknown --agent "${agent}" — supported: claude-code, ${MCP_AGENT_TARGETS.join(', ')}`) |
| 102 | + return [] |
| 103 | + } |
| 104 | + const done: string[] = [] |
| 105 | + for (const slug of targets) { |
| 106 | + const result = await installFor(slug, home, url) |
| 107 | + if (result === 'skipped') info(` ${AGENT_LABELS[slug]}: existing config at ${configPath(slug, home)} isn't valid JSON — add ${MCP_SERVER_NAME} manually`) |
| 108 | + else done.push(AGENT_LABELS[slug]) |
| 109 | + } |
| 110 | + return done |
| 111 | +} |
| 112 | + |
| 113 | +// `insta mcp install [--agent <slug>] [--mcp-token]` — claude-code goes through its registry CLI |
| 114 | +// (registerMcp); everything else is a config-file write. No --agent = claude-code + all detected. |
| 115 | +export async function mcpInstall(opts: { agent?: string; mcpToken?: boolean }): Promise<void> { |
| 116 | + if (!opts.agent || opts.agent === 'claude-code') { |
| 117 | + await registerMcp(undefined, undefined, !!opts.mcpToken) |
| 118 | + if (opts.agent) return |
| 119 | + } |
| 120 | + const done = await installAgentConfigs(opts.agent) |
| 121 | + if (done.length) info(`✓ MCP — configured for ${done.join(', ')} (restart those tools to pick it up)`) |
| 122 | + else if (opts.agent) { /* messages already printed */ } |
| 123 | + else info(' no other MCP-capable agents detected (supported: cursor, codex, opencode, copilot, factory-droid)') |
| 124 | +} |
0 commit comments