diff --git a/cli/index.ts b/cli/index.ts old mode 100644 new mode 100755 index d61ce4fd..4d76b861 --- a/cli/index.ts +++ b/cli/index.ts @@ -10,6 +10,8 @@ type Plain = { run(args: ReturnType): Promise }; /** Commands that work without a storebound.config.ts. */ const PLAIN: Record Promise, string]> = { 'init': [() => import('./init'), 'copy the templates (config, listing, copy, privacy policy) into this project'], + 'install': [() => import('./install'), 'skills + MCP server for --agent claude|codex|cursor|copilot|windsurf|gemini|opencode'], + 'mcp': [async () => ({ run: async () => (await import('./mcp')).serve() }), 'stdio MCP server wrapping these commands (for any MCP-capable AI tool)'], 'privacy-manifest': [() => import('./privacy-manifest'), 'iOS PrivacyInfo.xcprivacy + required-reason API + SDK manifest scan (--ios )'], }; const COMMANDS: Record Promise, string]> = { diff --git a/cli/install.ts b/cli/install.ts new file mode 100644 index 00000000..3dcb50d9 --- /dev/null +++ b/cli/install.ts @@ -0,0 +1,78 @@ +// Put the storebound skills and MCP server into a game project for one or more AI coding tools. +// storebound install --agent claude|codex|cursor|copilot|windsurf|gemini|opencode[,...] [--dir .] [--dry] +// [--no-skills] [--no-mcp] [--command "bunx storebound"] +// Skills are copied to the tool's skills folder (our own skill folders are updated, nothing else is touched). The MCP +// entry "storebound" is added to the tool's config file; every other entry stays as it is. Re-running is safe. +// MCP command: `bunx storebound mcp` when the project has storebound in node_modules, else this toolchain's +// bin/storebound by absolute path (override with --command). +import { cpSync, existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { homedir } from 'node:os'; +import { dirname, join, resolve } from 'node:path'; +import type { Args } from './lib/args'; +import { AGENTS, type AgentId, isAgent, type McpCommand, mergeCodexToml, mergeJsonServer } from './lib/agents'; +import { log, warn } from './lib/log'; + +const TOOLCHAIN = resolve(import.meta.dir, '..'); + +/** Every file of a folder, relative path -> content, for comparing skill folders. */ +function snapshot(dir: string, base = dir, out = new Map()): Map { + if (!existsSync(dir)) return out; + for (const n of readdirSync(dir, { withFileTypes: true })) { + const p = join(dir, n.name); + if (n.isDirectory()) snapshot(p, base, out); else out.set(p.slice(base.length), readFileSync(p, 'utf8')); + } + return out; +} +const same = (a: Map, b: Map) => a.size === b.size && [...a].every(([k, v]) => b.get(k) === v); + +export function mcpCommand(project: string, override?: string): McpCommand { + if (override) { const [command, ...args] = override.split(/\s+/).filter(Boolean); return { command: command!, args: [...args, 'mcp'] }; } + if (existsSync(join(project, 'node_modules', 'storebound', 'package.json'))) return { command: 'bunx', args: ['storebound', 'mcp'] }; + return { command: join(TOOLCHAIN, 'bin', 'storebound'), args: ['mcp'] }; +} + +export async function run(args: Args): Promise { + const agents = args.list('agent'); + if (!agents.length || !agents.every(isAgent)) throw new Error(`usage: install --agent ${Object.keys(AGENTS).join('|')}[,...] [--dir .] [--dry] [--no-skills] [--no-mcp]`); + const project = resolve(args.str('dir', '.')); + const dry = args.has('dry'); + const home = args.get('home') ?? homedir(); + const cmd = mcpCommand(project, args.get('command')); + const skillsSrc = join(TOOLCHAIN, 'skills'); + const skills = readdirSync(skillsSrc).filter(n => existsSync(join(skillsSrc, n, 'SKILL.md'))).sort(); + const say = (m: string) => log('install', dry ? `${m} (dry)` : m); + const doneDirs = new Set(); + + for (const id of agents as AgentId[]) { + const a = AGENTS[id]; + log('install', `${a.label}`); + if (!args.has('no-skills') && !doneDirs.has(a.skillsDir)) { + doneDirs.add(a.skillsDir); + let created = 0, updated = 0, kept = 0; + for (const s of skills) { + const from = join(skillsSrc, s); + const to = join(project, a.skillsDir, s); + const had = existsSync(to); + if (had && same(snapshot(from), snapshot(to))) { kept++; continue; } + if (!dry) { mkdirSync(dirname(to), { recursive: true }); cpSync(from, to, { recursive: true, force: true }); } + if (had) updated++; else created++; + } + say(`skills -> ${a.skillsDir}: ${created} new, ${updated} updated, ${kept} up to date`); + } + if (!args.has('no-mcp')) { + const rel = a.mcpFile({ home, xdg: process.env.XDG_CONFIG_HOME, exists: existsSync }); + const file = rel.startsWith('~/') ? join(home, rel.slice(2)) : rel.startsWith('/') ? rel : join(project, rel); + const cur = existsSync(file) ? readFileSync(file, 'utf8') : null; + try { + const r = a.format === 'codex-toml' ? mergeCodexToml(cur, cmd) : mergeJsonServer(cur, a.format, cmd); + if (!r.changed) log('install', `mcp ${rel}: up to date`); + else { + if (!dry) { mkdirSync(dirname(file), { recursive: true }); writeFileSync(file, r.text); } + say(`mcp ${rel}: storebound -> ${cmd.command} ${cmd.args.join(' ')}`); + } + } catch (e) { warn('install', `mcp ${rel}: ${(e as Error).message}`); } + } + if (a.note) log('install', ` note: ${a.note}`); + } + log('install', 'restart the AI tool so it picks up the skills and the MCP server; credentials stay in env / .storebound/'); +} diff --git a/cli/lib/agents.ts b/cli/lib/agents.ts new file mode 100644 index 00000000..203ae067 --- /dev/null +++ b/cli/lib/agents.ts @@ -0,0 +1,85 @@ +// Where each AI coding tool looks for Agent Skills and MCP servers in a project, and pure merge helpers that add the +// storebound entry without touching anything else in those files. Formats checked against each tool's docs in +// October 2026 (see README "Agent support"). + +export type AgentId = 'claude' | 'codex' | 'cursor' | 'copilot' | 'windsurf' | 'gemini' | 'opencode'; + +export interface McpCommand { command: string; args: string[] } + +export interface AgentTarget { + label: string; + /** Project-relative skills folder (Agent Skills standard: //SKILL.md). */ + skillsDir: string; + /** MCP config file; "~/" = the user's home directory (outside the project). */ + mcpFile: (env: { home: string; xdg?: string; exists: (p: string) => boolean }) => string; + format: 'mcpServers' | 'vscode' | 'codex-toml' | 'opencode'; + note?: string; +} + +export const AGENTS: Record = { + claude: { label: 'Claude Code', skillsDir: '.claude/skills', mcpFile: () => '.mcp.json', format: 'mcpServers', + note: 'or install the plugin: /plugin marketplace add , /plugin install storebound@crtkafa' }, + codex: { label: 'OpenAI Codex', skillsDir: '.agents/skills', mcpFile: () => '.codex/config.toml', format: 'codex-toml', + note: 'Codex reads a project .codex/config.toml only for trusted projects' }, + cursor: { label: 'Cursor', skillsDir: '.agents/skills', mcpFile: () => '.cursor/mcp.json', format: 'mcpServers' }, + copilot: { label: 'VS Code / GitHub Copilot', skillsDir: '.github/skills', mcpFile: () => '.vscode/mcp.json', format: 'vscode' }, + windsurf: { label: 'Windsurf (Devin Desktop)', skillsDir: '.agents/skills', format: 'mcpServers', + mcpFile: e => (e.exists(`${e.home}/.codeium/windsurf/mcp_config.json`) ? '~/.codeium/windsurf/mcp_config.json' : `${e.xdg ? e.xdg : '~/.config'}/devin/mcp_config.json`), + note: 'MCP config is global (in your home directory); older installs keep it in ~/.codeium/windsurf/' }, + gemini: { label: 'Gemini CLI', skillsDir: '.gemini/skills', mcpFile: () => '.gemini/settings.json', format: 'mcpServers', + note: 'or install the extension: gemini extensions install ' }, + opencode: { label: 'OpenCode', skillsDir: '.opencode/skills', mcpFile: () => 'opencode.json', format: 'opencode' }, +}; + +export const isAgent = (s: string): s is AgentId => s in AGENTS; + +export interface MergeResult { text: string; changed: boolean } + +/** JSON config: sets .storebound and leaves every other key alone. Throws on invalid JSON. */ +export function mergeJsonServer(existing: string | null, format: 'mcpServers' | 'vscode' | 'opencode', cmd: McpCommand): MergeResult { + let doc: Record = {}; + if (existing && existing.trim()) { + try { doc = JSON.parse(existing) as Record; } catch (e) { throw new Error(`not valid JSON, left untouched (${(e as Error).message})`); } + if (!doc || typeof doc !== 'object' || Array.isArray(doc)) throw new Error('not a JSON object, left untouched'); + } + const key = format === 'vscode' ? 'servers' : format === 'opencode' ? 'mcp' : 'mcpServers'; + const entry = format === 'vscode' ? { type: 'stdio', command: cmd.command, args: cmd.args } + : format === 'opencode' ? { type: 'local', command: [cmd.command, ...cmd.args], enabled: true } + : { command: cmd.command, args: cmd.args }; + if (format === 'opencode' && !existing?.trim()) doc.$schema = 'https://opencode.ai/config.json'; + const servers = (doc[key] && typeof doc[key] === 'object' ? doc[key] : {}) as Record; + const before = JSON.stringify(servers.storebound ?? null); + servers.storebound = entry; + doc[key] = servers; + const text = JSON.stringify(doc, null, 2) + '\n'; + return { text, changed: before !== JSON.stringify(entry) || !existing }; +} + +const tomlStr = (s: string) => JSON.stringify(s); + +/** Codex config.toml: replaces the [mcp_servers.storebound] table (and its sub-tables) or appends it. */ +export function mergeCodexToml(existing: string | null, cmd: McpCommand): MergeResult { + const block = `[mcp_servers.storebound]\ncommand = ${tomlStr(cmd.command)}\nargs = [${cmd.args.map(tomlStr).join(', ')}]\n`; + const src = existing ?? ''; + const lines = src.split('\n'); + const isOurs = (l: string) => /^\s*\[\s*mcp_servers\.(storebound|"storebound")(\.[^\]]+)?\s*\]\s*$/.test(l); + const isHeader = (l: string) => /^\s*\[/.test(l); + const out: string[] = []; + let skipping = false; + let found = false; + let oldBlock = ''; + for (const l of lines) { + if (isHeader(l)) { + if (isOurs(l)) { skipping = true; if (!found) { found = true; out.push('\u0000'); } oldBlock += l + '\n'; continue; } + skipping = false; + } + if (skipping) { oldBlock += l + '\n'; continue; } + out.push(l); + } + if (found) { + const text = out.join('\n').replace('\u0000', block.trimEnd() + '\n').replace(/\n{3,}/g, '\n\n'); + return { text: text.endsWith('\n') ? text : text + '\n', changed: oldBlock.trim() !== block.trim() }; + } + const base = src.trimEnd(); + return { text: (base ? base + '\n\n' : '') + block, changed: true }; +} diff --git a/cli/mcp-tools.ts b/cli/mcp-tools.ts new file mode 100644 index 00000000..9092530b --- /dev/null +++ b/cli/mcp-tools.ts @@ -0,0 +1,153 @@ +// The tools `storebound mcp` offers, as data. Pure, so tests can check the list and the argv each call builds. +// Rules: one tool per CLI command; every tool that writes anything has `dry_run` defaulting to true; nothing that +// submits for review, releases to the public, resumes / completes a rollout, cancels a submission or deletes is +// exposed. Those stay terminal commands the owner runs (they also ask for confirmation there). + +export interface JsonSchema { type: string; description?: string; enum?: (string | number)[]; default?: unknown; items?: JsonSchema; minimum?: number; maximum?: number; pattern?: string } + +export interface ToolDef { + name: string; + title: string; + description: string; + /** CLI words before the options, e.g. ['play', 'listing']. */ + command: string[]; + /** Writes to a store or to local files. Gets `dry_run` (default true). */ + write: boolean; + /** Replaces existing data (screenshots, a whole form) instead of only adding. */ + destructive?: boolean; + idempotent?: boolean; + /** Talks to a store API or the internet. */ + network: boolean; + props?: Record; + required?: string[]; + /** Input -> extra CLI options (dry_run is handled for every write tool). */ + args?: (i: Record) => string[]; +} + +const only: JsonSchema = { type: 'string', description: 'Comma-separated ids / language codes to limit the run to (optional)' }; +const opt = (flag: string, v: unknown): string[] => (v === undefined || v === null || v === '' ? [] : [`--${flag}`, String(v)]); +const flag = (name: string, v: unknown): string[] => (v === true ? [`--${name}`] : []); + +export const TOOLS: ToolDef[] = [ + { name: 'check', title: 'Offline config check', command: ['check'], write: false, network: false, + description: 'Validate storebound.config.ts, both listing files, screenshot copy, Data safety answers, product texts and referenced files. Offline.' }, + { name: 'check_aso', title: 'Keyword audit', command: ['check'], write: false, network: false, + description: 'Offline ASO audit of the listing files: App Store keyword field rules (100 chars, no spaces, no name/subtitle repeats, >= 90% used) and Play keyword stuffing.', + props: { storefront: { type: 'string', description: 'App Store storefront for the cross-locale hint', default: 'US' } }, + args: i => ['--aso', ...opt('storefront', i.storefront)] }, + { name: 'validate', title: 'Store readiness report', command: ['validate'], write: false, network: true, + description: 'Read-only readiness report for App Store Connect and/or Google Play with ordered blockers (build, encryption, metadata, screenshots, review details, age rating, prices, IAPs, privacy URL, app-ads.txt, tracks, products).', + props: { store: { type: 'string', enum: ['both', 'apple', 'play'], default: 'both' } }, + args: i => (i.store === 'apple' ? ['--apple'] : i.store === 'play' ? ['--play'] : []) }, + { name: 'apple_status', title: 'App Store status', command: ['apple', 'status'], write: false, network: true, + description: 'Read-only App Store Connect overview: versions and their states, recent builds, in-app purchases, review submissions.' }, + { name: 'apple_next_build', title: 'Next iOS build number', command: ['apple', 'next-build'], write: false, network: true, + description: 'Next safe CFBundleVersion: one above every build uploaded for the app.' }, + { name: 'play_status', title: 'Google Play status', command: ['play', 'status'], write: false, network: true, + description: 'Read-only Play overview: tracks and releases (with rollout fraction), listing languages, one-time products.' }, + { name: 'play_next_version_code', title: 'Next Play versionCode', command: ['play', 'next-version-code'], write: false, network: true, + description: 'Next Play versionCode: one above every uploaded bundle and track release.' }, + { name: 'privacy_manifest', title: 'iOS privacy manifest scan', command: ['privacy-manifest'], write: false, network: false, + description: 'Local scan of an iOS project: PrivacyInfo.xcprivacy present, required-reason APIs declared, SDKs without manifests.', + props: { ios: { type: 'string', description: 'Path of the iOS project folder, e.g. ios/App' }, sdk_dirs: { type: 'string', description: 'Extra plugin / SDK folders, comma-separated' } }, + required: ['ios'], args: i => [...opt('ios', i.ios), ...opt('sdk-dirs', i.sdk_dirs)] }, + + { name: 'whats_new', title: 'Draft release notes', command: ['whats-new'], write: true, network: false, idempotent: true, + description: 'Draft player-facing release notes from the git log since a tag; with dry_run false writes the draft into the listing files (local text only, nothing is sent to a store).', + props: { since: { type: 'string', description: 'Git tag or ref (default: latest tag)' }, lang: { type: 'string' }, all_languages: { type: 'boolean', default: false } }, + args: i => [...opt('since', i.since), ...opt('lang', i.lang), ...flag('all', i.all_languages)] }, + { name: 'play_listing', title: 'Push Play listing text', command: ['play', 'listing'], write: true, network: true, idempotent: true, + description: 'Google Play app details + title / short / full description per language from the listing file. Not public until the next review / publish.', + props: { only }, args: i => opt('only', i.only) }, + { name: 'play_images', title: 'Upload Play graphics', command: ['play', 'images'], write: true, destructive: true, network: true, idempotent: true, + description: 'Replace icon, feature graphic and screenshots per Play language from the renders folder. Slow (minutes): prefer the terminal with a log for many languages.', + props: { only }, args: i => opt('only', i.only) }, + { name: 'play_products', title: 'Sync Play one-time products', command: ['play', 'products'], write: true, network: true, idempotent: true, + description: 'Create / update one-time products with regional prices and activate their purchase option.', + props: { only }, args: i => opt('only', i.only) }, + { name: 'play_data_safety', title: 'Push Play Data safety', command: ['play', 'data-safety'], write: true, destructive: true, network: true, idempotent: true, + description: 'Replace the whole Play Data safety form with the answers from the config (CSV import). dry_run prints the CSV.' }, + { name: 'play_release_testing', title: 'Release to a Play testing track', command: ['play', 'release'], write: true, network: true, + description: 'Upload an AAB (or reuse a versionCode) to a TESTING track (internal, alpha, beta) with release notes. Production is not available here.', + props: { aab: { type: 'string', description: 'Path to the .aab' }, version_code: { type: 'integer', minimum: 1 }, + track: { type: 'string', enum: ['internal', 'alpha', 'beta'], default: 'internal' }, status: { type: 'string', enum: ['completed', 'draft'], default: 'completed' } }, + args: i => [...(i.aab ? [String(i.aab)] : []), ...opt('version-code', i.version_code), `--${String(i.track ?? 'internal')}`, String(i.status ?? 'completed')] }, + { name: 'apple_bundle', title: 'Register bundle id', command: ['apple', 'bundle'], write: true, network: true, idempotent: true, + description: 'Register the bundle id if missing and look up the App Store Connect app record.' }, + { name: 'apple_iap', title: 'Sync App Store IAPs', command: ['apple', 'iap'], write: true, network: true, idempotent: true, + description: 'Create missing in-app purchases, localizations, price schedules and availability. Never submits.', + props: { only }, args: i => opt('only', i.only) }, + { name: 'apple_iap_review', title: 'IAP review screenshots', command: ['apple', 'iap-review'], write: true, destructive: true, network: true, idempotent: true, + description: 'Upload (replace when changed) the App Review screenshot of every in-app purchase. Never submits.' }, + { name: 'apple_listing', title: 'Push App Store version + text', command: ['apple', 'listing'], write: true, network: true, idempotent: true, + description: 'Create / update the editable version (manual release), attach a build by explicit number, and push name / subtitle / description / keywords / promo / what\'s new per locale.', + props: { version: { type: 'string', pattern: '^\\d+(\\.\\d+){0,2}$' }, build: { type: 'string', description: 'Exact build number to attach (use the number you just uploaded, never "latest")' }, only }, + required: ['version'], args: i => [...opt('version', i.version), ...opt('build', i.build), ...opt('only', i.only)] }, + { name: 'apple_screenshots', title: 'Upload App Store screenshots', command: ['apple', 'screenshots'], write: true, destructive: true, network: true, idempotent: true, + description: 'Sync 6.9" and 6.5" screenshots per locale (MD5-idempotent; changed sets are replaced). Slow: prefer the terminal with a log.', + props: { only }, args: i => opt('only', i.only) }, + { name: 'apple_appinfo', title: 'App Store app info', command: ['apple', 'appinfo'], write: true, network: true, idempotent: true, + description: 'Categories, age rating declaration, content rights, Free price and availability (when missing).' }, + { name: 'apple_review_details', title: 'App Review information', command: ['apple', 'review-details'], write: true, network: true, idempotent: true, + description: 'App Review contact (from .storebound/credentials.json) and review notes from the config.' }, + { name: 'apple_encryption', title: 'Export compliance answer', command: ['apple', 'encryption'], write: true, network: true, idempotent: true, + description: 'Answer export compliance for builds from apple.usesNonExemptEncryption in the config (never guesses).', + props: { build: { type: 'string', description: 'Build number (default: every build without an answer)' } }, args: i => opt('build', i.build) }, + { name: 'apple_phased_release', title: 'Phased release on / pause', command: ['apple', 'release'], write: true, network: true, idempotent: true, + description: 'Turn on the 7-day phased release for the upcoming version, or pause an active one (pausing is not a rollback). Resume / complete / release are owner-only terminal commands.', + props: { action: { type: 'string', enum: ['on', 'pause'] }, version: { type: 'string' } }, required: ['action'], + args: i => ['--phased', String(i.action), ...opt('version', i.version)] }, + { name: 'icons', title: 'Generate icons', command: ['icons'], write: true, network: false, idempotent: true, + description: 'Write every store / launcher / web icon from the artwork in the config (local files, needs ffmpeg).' }, +]; + +/** CLI flags / commands that must never be reachable through MCP. Tests assert none of the tools can produce them. */ +export const FORBIDDEN_ARGS = ['--yes', '--manual-release', '--cancel-submission', '--production', 'rollout', 'resume', 'complete']; + +export function inputSchema(t: ToolDef): Record { + const props: Record = { ...(t.props ?? {}) }; + if (t.write) props.dry_run = { type: 'boolean', default: true, description: 'Default true: only show what would change. Set false only after the owner agreed.' }; + return { type: 'object', properties: props, ...(t.required?.length ? { required: t.required } : {}), additionalProperties: false }; +} + +export const OUTPUT_SCHEMA = { + type: 'object', + properties: { exitCode: { type: 'integer' }, dryRun: { type: 'boolean' }, command: { type: 'string' }, output: { type: 'string' } }, + required: ['exitCode', 'command', 'output'], +} as const; + +export function listTools(): Record[] { + return TOOLS.map(t => ({ + name: t.name, title: t.title, description: t.description, + inputSchema: inputSchema(t), outputSchema: OUTPUT_SCHEMA, + annotations: { title: t.title, readOnlyHint: !t.write, destructiveHint: t.write ? !!t.destructive : false, idempotentHint: !!t.idempotent || !t.write, openWorldHint: t.network }, + })); +} + +/** Checks an input against the tool schema; returns problems (empty = fine). */ +export function validateInput(t: ToolDef, input: unknown): string[] { + const e: string[] = []; + if (input === undefined || input === null) input = {}; + if (typeof input !== 'object' || Array.isArray(input)) return ['arguments must be an object']; + const s = inputSchema(t) as { properties: Record; required?: string[] }; + const i = input as Record; + for (const r of s.required ?? []) if (i[r] === undefined) e.push(`${r}: required`); + for (const [k, v] of Object.entries(i)) { + const p = s.properties[k]; + if (!p) { e.push(`${k}: unknown argument`); continue; } + const ok = p.type === 'integer' ? Number.isInteger(v) : p.type === 'boolean' ? typeof v === 'boolean' : p.type === 'string' ? typeof v === 'string' : true; + if (!ok) { e.push(`${k}: must be ${p.type}`); continue; } + if (p.enum && !p.enum.includes(v as string)) e.push(`${k}: one of ${p.enum.join(', ')}`); + if (p.pattern && typeof v === 'string' && !new RegExp(p.pattern).test(v)) e.push(`${k}: does not match ${p.pattern}`); + if (p.minimum !== undefined && typeof v === 'number' && v < p.minimum) e.push(`${k}: >= ${p.minimum}`); + if (typeof v === 'string' && /^-/.test(v)) e.push(`${k}: must not start with "-"`); + } + return e; +} + +/** argv after `storebound` for a validated call. Write tools get --dry unless dry_run is explicitly false. */ +export function toArgv(t: ToolDef, input: Record = {}): { argv: string[]; dryRun: boolean } { + const dryRun = t.write ? input.dry_run !== false : false; + const argv = [...t.command, ...(t.args?.(input) ?? []), ...(dryRun ? ['--dry'] : [])]; + return { argv, dryRun }; +} diff --git a/cli/mcp.ts b/cli/mcp.ts new file mode 100644 index 00000000..a5694e73 --- /dev/null +++ b/cli/mcp.ts @@ -0,0 +1,104 @@ +// `storebound mcp`: a stdio MCP server (spec revision 2025-11-25, tools only) that wraps the CLI, so any agent tool +// with MCP support (Claude Code, Codex, Gemini CLI, Cursor, VS Code / Copilot, Windsurf, OpenCode, ...) can call it. +// +// Why no SDK: the server needs initialize, ping, tools/list and tools/call over newline-delimited JSON-RPC. That is +// ~150 lines, and keeps storebound at zero runtime dependencies (the official SDK pulls in zod, express, ...). +// +// Every tool runs the CLI as a child process in the project directory (STOREBOUND_PROJECT or the server's cwd) and +// returns its output. stdout of this process carries protocol messages only; logs go to stderr. +// Tool list and safety rules: mcp-tools.ts (write tools default to dry_run, nothing public or irreversible exposed). +import { join } from 'node:path'; +import pkg from '../package.json' with { type: 'json' }; +import { listTools, TOOLS, toArgv, validateInput } from './mcp-tools'; + +export const PROTOCOL = '2025-11-25'; +export const SUPPORTED = [PROTOCOL, '2025-06-18', '2025-03-26', '2024-11-05']; + +export const INSTRUCTIONS = [ + 'storebound ships mobile games to Google Play and the App Store.', + 'Write tools default to dry_run: show the dry run to the owner and only call again with dry_run false after they agree.', + 'Nothing here submits for review, releases, cancels or deletes: tell the owner which terminal command or console click does that.', + 'Credentials come only from env or .storebound/ in the project; never ask for keys in chat or write them into files.', + 'Run `check` (offline) and `validate` (read-only) before writes. Long uploads (images, screenshots) are better run in a terminal with a log.', +].join(' '); + +type Id = string | number; +interface Msg { jsonrpc: '2.0'; id?: Id; method?: string; params?: Record } + +const MAX_OUTPUT = 60_000; +const CLI = join(import.meta.dir, 'index.ts'); + +/** Handles one message; returns the response object (or null for notifications). Exported for tests. */ +export async function handle(m: Msg, run: (argv: string[], id: Id) => Promise<{ code: number; out: string }> = runCli): Promise | null> { + const ok = (result: unknown) => ({ jsonrpc: '2.0', id: m.id, result }); + const err = (code: number, message: string) => ({ jsonrpc: '2.0', id: m.id ?? null, error: { code, message } }); + if (m.id === undefined) { + if (m.method === 'notifications/cancelled') cancel(m.params?.requestId as Id); + return null; // notifications/initialized and any other notification + } + switch (m.method) { + case 'initialize': { + const asked = String(m.params?.protocolVersion ?? ''); + return ok({ + protocolVersion: SUPPORTED.includes(asked) ? asked : PROTOCOL, + capabilities: { tools: { listChanged: false } }, + serverInfo: { name: 'storebound', title: 'storebound', version: pkg.version, description: pkg.description }, + instructions: INSTRUCTIONS, + }); + } + case 'ping': return ok({}); + case 'tools/list': return ok({ tools: listTools() }); + case 'tools/call': { + const name = String(m.params?.name ?? ''); + const tool = TOOLS.find(t => t.name === name); + if (!tool) return err(-32602, `Unknown tool: ${name}`); + const input = (m.params?.arguments ?? {}) as Record; + const problems = validateInput(tool, input); + if (problems.length) return ok({ content: [{ type: 'text', text: `Invalid arguments: ${problems.join('; ')}` }], isError: true }); + const { argv, dryRun } = toArgv(tool, input); + const r = await run(argv, m.id); + let out = r.out.length > MAX_OUTPUT ? `[... first ${r.out.length - MAX_OUTPUT} characters cut ...]\n` + r.out.slice(-MAX_OUTPUT) : r.out; + if (dryRun) out += '\n\n(dry run: nothing was changed. Ask the owner before calling again with dry_run: false.)'; + const structured = { exitCode: r.code, dryRun, command: `storebound ${argv.join(' ')}`, output: out }; + return ok({ content: [{ type: 'text', text: `$ storebound ${argv.join(' ')}\n${out}\n[exit ${r.code}]` }], structuredContent: structured, isError: r.code !== 0 }); + } + default: return err(-32601, `Method not found: ${m.method}`); + } +} + +const running = new Map>(); +function cancel(id: Id | undefined): void { if (id !== undefined) running.get(id)?.kill(); } + +async function runCli(argv: string[], id: Id): Promise<{ code: number; out: string }> { + const cwd = process.env.STOREBOUND_PROJECT || process.cwd(); + const p = Bun.spawn([process.execPath, CLI, ...argv], { cwd, stdin: 'ignore', stdout: 'pipe', stderr: 'pipe', env: { ...process.env, NO_COLOR: '1' } }); + running.set(id, p); + try { + const [out, errText, code] = await Promise.all([new Response(p.stdout).text(), new Response(p.stderr).text(), p.exited]); + return { code, out: (out + (errText ? `\n${errText}` : '')).trim() }; + } finally { running.delete(id); } +} + +export async function serve(): Promise { + const send = (o: unknown) => process.stdout.write(JSON.stringify(o) + '\n'); + console.error(`[storebound mcp] ${pkg.version} on stdio, project ${process.env.STOREBOUND_PROJECT || process.cwd()}`); + let buf = ''; + const decoder = new TextDecoder(); + const reader = Bun.stdin.stream().getReader(); + for (;;) { + const { value, done } = await reader.read(); + if (done) break; + buf += decoder.decode(value, { stream: true }); + let nl: number; + while ((nl = buf.indexOf('\n')) >= 0) { + const line = buf.slice(0, nl).trim(); + buf = buf.slice(nl + 1); + if (!line) continue; + let msg: Msg; + try { msg = JSON.parse(line) as Msg; } catch { send({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } }); continue; } + if (Array.isArray(msg)) { send({ jsonrpc: '2.0', id: null, error: { code: -32600, message: 'Batches are not supported' } }); continue; } + // Calls run concurrently; each answers when its child process ends. + handle(msg).then(r => { if (r) send(r); }, e => send({ jsonrpc: '2.0', id: msg.id ?? null, error: { code: -32603, message: String((e as Error).message) } })); + } + } +}