/** * opencode-config-sync.js — BADA의 MCP 프로필 상태를 opencode 설정에 미러링 * * 배경: BADA의 에이전트 프로필별 MCP 온/오프(syncAgentMcpServers)는 지금까지 * ~/.claude/settings.json 의 mcpServers 만 갱신했다. opencode는 자체 설정 * (~/.config/opencode/opencode.json)의 `mcp` 키를 읽으므로, 활성 CLI가 opencode일 때 * bada MCP 서버(에이전트↔BADA 연동 백본)가 에이전트에 노출되지 않는 락인이 있었다. * 이 모듈이 Claude 형식 → opencode 형식 변환·미러링을 담당한다. * * 형식 대응 (opencode config 스키마, 2026-07 기준): * - stdio: { command, args, env } → { type:'local', command:[command,...args], environment: env, enabled } * - 원격: { type:'sse'|'http', url } → { type:'remote', url, enabled } * * 안전 원칙: * 1) 사용자가 opencode.json에 직접 정의한(우리 관리 대상이 아닌) mcp 항목은 절대 건드리지 않는다. * 2) 이미 존재하는 동명 항목은 통째로 교체하지 않고 `enabled` 플래그만 토글한다. * 3) 서버를 끌 때 삭제하지 않고 enabled:false 로 둔다 (opencode가 공식 지원하는 방식). * 4) 최초 수정 전 1회 원본 백업(opencode.json.bada-backup)을 남긴다. */ const fs = require('fs'); const path = require('path'); const cliPaths = require('./cli-paths'); const jsonc = require('jsonc-parser'); /** Claude(settings.json) 형식의 MCP 항목 하나를 opencode 형식으로 변환한다. */ function convertMcpEntry(claudeEntry, enabled) { if (!claudeEntry || typeof claudeEntry !== 'object' || Array.isArray(claudeEntry)) return null; const stringMap = value => value && typeof value === 'object' && !Array.isArray(value) && Object.values(value).every(item => typeof item === 'string'); // 원격 서버 (sse/http/url 지정형) if (claudeEntry.url) { try { if (typeof claudeEntry.url !== 'string' || !['http:', 'https:'].includes(new URL(claudeEntry.url).protocol)) return null; } catch { return null; } if (claudeEntry.headers !== undefined && !stringMap(claudeEntry.headers)) return null; const converted = { type: 'remote', url: claudeEntry.url, enabled: !!enabled }; if (claudeEntry.headers && typeof claudeEntry.headers === 'object') converted.headers = { ...claudeEntry.headers }; return converted; } // 로컬(stdio) 서버 if (claudeEntry.command) { if (typeof claudeEntry.command !== 'string' || !claudeEntry.command.trim()) return null; if (claudeEntry.args !== undefined && (!Array.isArray(claudeEntry.args) || !claudeEntry.args.every(arg => typeof arg === 'string'))) return null; if (claudeEntry.env !== undefined && !stringMap(claudeEntry.env)) return null; const cmdArr = [claudeEntry.command, ...(Array.isArray(claudeEntry.args) ? claudeEntry.args : [])]; const converted = { type: 'local', command: cmdArr, enabled: !!enabled }; if (claudeEntry.env && typeof claudeEntry.env === 'object' && Object.keys(claudeEntry.env).length > 0) { converted.environment = claudeEntry.env; } return converted; } return null; // 알 수 없는 형식 — 미러링 생략 } /** * BADA가 관리하는 MCP 서버 목록(claude 형식)을 opencode.json 의 `mcp` 키에 반영한다. * * @param {Object} masterMcp 전체 마스터 MCP 정의 (이름 → claude 형식 항목) * @param {Set|string[]} enabledNames 이번 프로필에서 켜야 할 서버 이름들 * @returns {{ synced: boolean, reason?: string }} */ function prepareMcpToOpencode(masterMcp, enabledNames, targetCli = 'opencode') { const application = require('./profile-application'); const candidates = cliPaths.getCliPaths(targetCli).settingsFiles; const configPath = candidates.find(file => path.basename(file) === targetCli + '.jsonc' && fs.existsSync(file)) || candidates.find(file => path.basename(file) === targetCli + '.json' && fs.existsSync(file)) || candidates.find(file => path.basename(file) === targetCli + '.json'); if (!configPath) throw new Error('OpenCode configuration path is unavailable'); const original = application.read(configPath); const raw = original?.toString('utf8').replace(/^\uFEFF/, '') || '{}'; const errors = [], config = jsonc.parse(raw, errors, { allowTrailingComma: true }); if (errors.length || !config || typeof config !== 'object' || Array.isArray(config)) throw new Error('Invalid OpenCode configuration'); if (config.mcp !== undefined && (!config.mcp || typeof config.mcp !== 'object' || Array.isArray(config.mcp))) throw new Error('Invalid OpenCode MCP configuration'); const mcp = Object.assign(Object.create(null), config.mcp), enabled = new Set(enabledNames); for (const [name, entry] of Object.entries(masterMcp)) { if (mcp[name] && typeof mcp[name] === 'object') mcp[name] = { ...mcp[name], enabled: enabled.has(name) }; else if (enabled.has(name)) { const converted = convertMcpEntry(entry, true); if (!converted) throw new Error('Unsupported MCP server: ' + name); mcp[name] = converted; } } const output = jsonc.applyEdits(raw, jsonc.modify(raw, ['mcp'], mcp, { formattingOptions: { insertSpaces: true, tabSize: 2 } })); const plans = []; if (original !== null && !fs.existsSync(configPath + '.bada-backup') && output !== raw) plans.push(application.plan(configPath + '.bada-backup', original)); plans.push(application.plan(configPath, output, original)); return plans; } function syncMcpToOpencode(masterMcp, enabledNames, targetCli = null) { try { const current = targetCli || require('../context').getActiveCli(); const cli = ['opencode', 'codeagent'].includes(current) ? current : 'opencode'; require('./profile-application').commit(prepareMcpToOpencode(masterMcp, enabledNames, cli)); return { synced: true }; } catch (error) { return { synced: false, reason: error.message }; } } module.exports = { syncMcpToOpencode, prepareMcpToOpencode, convertMcpEntry };