storebound/cli/mcp.ts
CRT 117c5a3f79 MCP server and install --agent for any AI coding tool
- storebound mcp: stdio MCP server (spec 2025-11-25, tools only), one tool per command, write tools
  dry_run by default, readOnly/destructive/idempotent/openWorld annotations; submit, release,
  rollout, cancel and delete are not exposed. Own JSON-RPC subset, no SDK, zero runtime deps.
- storebound install --agent claude|codex|cursor|copilot|windsurf|gemini|opencode: copies the skills
  and adds the storebound MCP entry (.mcp.json, .codex/config.toml, .cursor/mcp.json, .vscode/mcp.json,
  Windsurf mcp_config.json, .gemini/settings.json, opencode.json). Idempotent, keeps other entries, --dry.
2026-10-10 13:03:10 +00:00

104 lines
6 KiB
TypeScript

// `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<string, unknown> }
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<Record<string, unknown> | 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<string, unknown>;
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<Id, ReturnType<typeof Bun.spawn>>();
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<void> {
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) } }));
}
}
}