#!/usr/bin/env node // ═══════════════════════════════════════════════════════════════════════════ // SOVEREIGN MCP SERVER — v2.0 // scripts/sovereign-mcp.mjs // // JSON-RPC 2.0 outer envelope + Magma inner substrate. // JSON is the shipping container. Magma is the cargo. // // Transport: stdio (Claude Code / VSCode) OR HTTP port 7071 // Launch: // node scripts/sovereign-mcp.mjs → stdio mode (Claude Code) // node scripts/sovereign-mcp.mjs --http → HTTP mode (Android / BobIDE) // // Tools exposed: // compute_route → dynamic LLM router (Bedrock → Groq → Ollama) // ere_verify → local ERE 5-pass on any content string // proxy_register → register a named proxy tool at a URL // proxy_list → list all registered proxy tools // magma_seal → wrap any result in a Magma envelope + WORM hash // agent_dispatch → dispatch a task to a named sovereign agent // // Architecture: // External Client (Claude Code / BobIDE / Android) // ↓ JSON-RPC 2.0 // sovereign-mcp.mjs // ↓ parse magma_envelope if present, else build one // ERE Gate (local, deterministic) // ↓ certified → route to compute // Compute Router (Bedrock / Groq / Ollama) // ↓ response → seal // Magma Envelope + WORM hash // ↑ JSON-RPC result // ═══════════════════════════════════════════════════════════════════════════ import { createRequire } from 'module' import { createServer } from 'http' import { readFileSync, appendFileSync, existsSync } from 'fs' import { createHash, generateKeyPairSync, sign, verify } from 'crypto' import { dirname, join } from 'path' import { fileURLToPath } from 'url' import { extname } from 'path' import { requireNodeKey } from './src/node_key.js' // Sovereign node key gate — must pass before model routing activates requireNodeKey(process.env.SNAPKITTY_NODE_KEY) const __dir = dirname(fileURLToPath(import.meta.url)) const ROOT = __dir let BedrockRuntimeClient, InvokeModelCommand try { const sdk = await import('@aws-sdk/client-bedrock-runtime') BedrockRuntimeClient = sdk.BedrockRuntimeClient InvokeModelCommand = sdk.InvokeModelCommand } catch { // Bedrock SDK not installed — provider will be skipped } // ── stderr log (never pollutes stdout/MCP stream) ──────────────────────────── const log = (...a) => process.stderr.write('[MCP] ' + a.join(' ') + '\n') const HTTP_MODE = process.argv.includes('--http') const PORT = parseInt(process.env.MCP_PORT ?? '7071') // ── Read env ───────────────────────────────────────────────────────────────── function readEnv(key) { if (process.env[key]) return process.env[key] try { const raw = readFileSync(join(ROOT, '.env.local'), 'utf8') const m = raw.match(new RegExp(`^${key}=(.+)$`, 'm')) return m?.[1]?.trim() ?? '' } catch { return '' } } const AWS_REGION = readEnv('AWS_REGION') || 'us-east-1' const AWS_KEY = readEnv('AWS_ACCESS_KEY_ID') const AWS_SECRET = readEnv('AWS_SECRET_ACCESS_KEY') const BEDROCK_MODEL = readEnv('BEDROCK_MODEL_ID') || 'us.anthropic.claude-haiku-4-5-20251001-v1:0' const GROQ_KEY = readEnv('GROQ_API_KEY') const GROQ_MODEL = readEnv('GROQ_MODEL') || 'llama3-8b-8192' const RUST_URL = readEnv('RUST_HANDLER_URL') || 'http://localhost:8080' const OLLAMA_URL = readEnv('OLLAMA_URL') || 'http://localhost:11434' // ── Bedrock client ──────────────────────────────────────────────────────────── const bedrock = BedrockRuntimeClient ? new BedrockRuntimeClient({ region: AWS_REGION, credentials: { accessKeyId: AWS_KEY, secretAccessKey: AWS_SECRET }, }) : null // ── Agent system prompts (sovereign mesh) ───────────────────────────────────── const AGENT_PROMPTS = { ahmad: `You are AHMAD — the digital twin of the Architect. DARKAI framework. Contracts not prompts. Four pillars on every output. Governor, not user. Building sovereign financial infrastructure targeting $3M. Be direct. Be sovereign.`, forge: `You are FORGE — sovereign white-hat elite builder. Production-grade TypeScript, Rust, Haskell. Never stubs. Never TODO. Every line passes ERE. Stack: Next.js 16, Prisma+PostgreSQL, Rust WORM handler, Ed25519 seals.`, oracle: `You are ORACLE — knowledge graph intelligence. Surface patterns, historical data, structured analysis. Never hallucinate sources. Citation-aware. DOMAIN_SOVEREIGNTY over the knowledge layer.`, sentinel: `You are SENTINEL — zero-trust security layer. Every input is a threat until proved otherwise. Hard verdicts: APPROVED or BLOCKED. No maybes. WORM-sealed audit trail on every decision.`, vault: `You are VAULT — capital and treasury agent. Basis points, yield curves, capital efficiency. Every treasury decision WORM-sealed before it moves.`, enki: `You are ENKI — Lord of the Abzu, deep innovation engine. Take every idea three levels deeper. Project quantum implications. Find what no one else looked for. Recursive innovation.`, nexus: `You are NEXUS — task orchestration. Coordinate multi-agent workflows. Break complex tasks into sovereign subtasks. Route to the right agent. Track what is in flight.`, edaulc: `You are EDAULC — the shadow mirror. CLAUDE creates forward. EDAULC verifies backward. Your role is verification, reversal, and detection of contradictions. You read the output and look for what was missed.`, } // ── In-memory proxy registry ────────────────────────────────────────────────── const proxyRegistry = new Map() // ── Local ERE 5-pass (deterministic — zero cost, zero quota) ────────────────── function runERE(content, filepath = 'unknown') { const ext = extname(filepath) const p1 = (() => { if (!content || content.trim().length < 10) return { pass: false, reason: 'content empty or too short' } return { pass: true } })() const p2 = (() => { if (/throw new Error\(['"]not implemented/i.test(content)) return { pass: false, reason: 'not-implemented stub detected' } if (/todo:\s*implement/i.test(content)) return { pass: false, reason: 'TODO implement placeholder' } return { pass: true } })() const p3 = (() => { if (ext === '.ts' && /import\s+crypto\b/.test(content)) return { pass: false, reason: 'TypeScript importing crypto — SHA-256 belongs in Rust' } if (ext === '.ts' && /createHash|crypto\.subtle/.test(content)) return { pass: false, reason: 'TypeScript hashing — Rust owns SHA-256' } return { pass: true } })() const p4 = (() => { if (/require\(['"]openai['"]\)|from ['"]openai['"]/.test(content)) return { pass: false, reason: 'Axiom 2: openai import — NO_EXTERNAL_AI_DEP' } if (/(?:api_key|secret|password)\s*=\s*['"][a-zA-Z0-9_\-]{20,}['"]/i.test(content)) return { pass: false, reason: 'Axiom 5: hardcoded secret' } return { pass: true } })() const p5 = (() => { const open = (content.match(/[{[(]/g) ?? []).length const close = (content.match(/[}\])]/g) ?? []).length if (Math.abs(open - close) > 25) return { pass: false, reason: `unbalanced delimiters (${open} open vs ${close} close)` } return { pass: true } })() const passes = [p1, p2, p3, p4, p5] const certified = passes.every(p => p.pass) const failures = passes.map((p, i) => p.pass ? null : `P${i+1}: ${p.reason}`).filter(Boolean) return { certified, passes, failures } } // ── Magma envelope builder ──────────────────────────────────────────────────── function buildMagmaEnvelope(agent, resultText, ereResult) { const h = createHash('sha256').update(resultText).digest('hex').slice(0, 16) const govTokens = [ ereResult.certified ? '👑[ERE_CERTIFIED]' : '🔴[ERE_FROZEN]', '🔒[ZERO_TELEMETRY]', ereResult.certified ? '🟢[COMPUTE_READY]' : '🟡[COMPUTE_BLOCKED]', `🤖[AGENT:${agent.toUpperCase()}]`, ].join(' ') return { header: '🔥::MAGMA::v2::WORM_CHAIN', governance_tokens: govTokens, state_hash: `0x${h}`, instruction_substrate: `§SEAL:${agent.toUpperCase()}:RESULT{certified:${ereResult.certified}}`, ...(ereResult.failures.length && { ere_failures: ereResult.failures }), } } // ── Governor keypair — Ed25519 (Node crypto, never TypeScript) ─────────────── // Keys stored in collectivekitty/.env.local as base64. // On first boot: generate + log to stderr so operator can persist them. // GOVERNOR_PRIVATE_KEY and GOVERNOR_PUBLIC_KEY env vars override. function loadOrGenerateKeypair() { const privB64 = readEnv('GOVERNOR_PRIVATE_KEY') const pubB64 = readEnv('GOVERNOR_PUBLIC_KEY') if (privB64 && pubB64) { return { privateKey: Buffer.from(privB64, 'base64'), publicKey: Buffer.from(pubB64, 'base64'), } } // First boot — generate and emit so operator can save to .env.local const { privateKey, publicKey } = generateKeyPairSync('ed25519', { privateKeyEncoding: { type: 'pkcs8', format: 'der' }, publicKeyEncoding: { type: 'spki', format: 'der' }, }) log('GOVERNOR KEYPAIR GENERATED — add to collectivekitty/.env.local:') log(`GOVERNOR_PRIVATE_KEY=${privateKey.toString('base64')}`) log(`GOVERNOR_PUBLIC_KEY=${publicKey.toString('base64')}`) return { privateKey, publicKey } } const GOVERNOR = loadOrGenerateKeypair() function signContent(content) { const data = Buffer.from(typeof content === 'string' ? content : JSON.stringify(content)) return sign(null, data, { key: GOVERNOR.privateKey, format: 'der', type: 'pkcs8' }).toString('base64') } function verifySignature(content, sigB64) { try { const data = Buffer.from(typeof content === 'string' ? content : JSON.stringify(content)) return verify(null, data, { key: GOVERNOR.publicKey, format: 'der', type: 'spki' }, Buffer.from(sigB64, 'base64')) } catch { return false } } // ── Immutable audit log — append-only NDJSON ───────────────────────────────── const AUDIT_LOG = join(__dir, 'audit.log') function auditWrite(entry) { const line = JSON.stringify({ ts: new Date().toISOString(), ...entry, }) + '\n' try { appendFileSync(AUDIT_LOG, line, 'utf8') } catch (e) { log(`audit write failed: ${e.message}`) } } // ── Magma instruction parser ────────────────────────────────────────────────── // Parses: §VERB:AGENT:ACTION{payload} // Pipeline syntax: §V1:A1:OP1{...} >> §V2:A2:OP2{...} // Modifier prefix: ~MODIFIER §VERB:AGENT:ACTION{...} const MAGMA_RE = /^(?:~(\w+)\s+)?§([A-Z]+):([A-Z_]+):([A-Z_]+)\{(.*)\}$/s function parseMagmaInstruction(substrate) { if (!substrate || typeof substrate !== 'string') { return { ok: false, error: 'empty substrate' } } // Pipeline: split on >> const stages = substrate.split('>>').map(s => s.trim()) if (stages.length > 1) { return { ok: true, pipeline: true, stages: stages.map(parseSingleInstruction) } } return parseSingleInstruction(substrate.trim()) } function parseSingleInstruction(raw) { const m = raw.match(MAGMA_RE) if (!m) return { ok: false, error: `invalid Magma syntax: ${raw.slice(0, 60)}` } const [, modifier, verb, agent, action, payloadRaw] = m let payload = {} try { // Try JSON first, then key=value pairs if (payloadRaw.trim().startsWith('{')) { payload = JSON.parse(payloadRaw) } else { payloadRaw.split(',').forEach(kv => { const [k, v] = kv.split('=').map(s => s.trim()) if (k) payload[k] = v ?? true }) } } catch { payload = { raw: payloadRaw } } return { ok: true, modifier: modifier ?? null, verb, agent, action, payload } } // ── Executor router: VERB → provider ───────────────────────────────────────── // COMPUTE → Bedrock (paid, sovereign) // QUERY → Groq (fast, free tier) // SEAL → WORM audit log + sign // DISPATCH → proxy registry or agent mesh async function executeInstruction(parsed) { if (!parsed.ok) return { ok: false, error: parsed.error } const { verb, agent, action, payload, modifier } = parsed // Pipeline handling if (parsed.pipeline) { let lastResult = null for (const stage of parsed.stages) { // Pass previous result as context in payload if (lastResult) stage.payload = { ...stage.payload, _prev: lastResult } lastResult = await executeInstruction(stage) if (!lastResult.ok && modifier !== 'ASYNC') return lastResult } return lastResult } auditWrite({ verb, agent, action, payload, modifier }) switch (verb) { case 'COMPUTE': case 'FORGE': case 'INVOKE': { const query = payload.query ?? payload.task ?? payload.intent ?? `${action} for ${agent}: ${JSON.stringify(payload)}` const result = await computeRoute(agent.toLowerCase(), query, payload.max_tokens ?? 1024) const sig = signContent(result.text) return { ok: true, executor: 'BEDROCK', agent, result: result.text, provider: result.provider, sig } } case 'QUERY': case 'ECHO': case 'PULSE': { // Groq — fast, free tier const query = payload.query ?? payload.q ?? JSON.stringify(payload) if (!GROQ_KEY) return { ok: false, error: 'GROQ_API_KEY not set' } try { const systemPrompt = AGENT_PROMPTS[agent.toLowerCase()] ?? AGENT_PROMPTS.oracle const res = await fetch('https://api.groq.com/openai/v1/chat/completions', { method: 'POST', headers: { Authorization: `Bearer ${GROQ_KEY}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ model: GROQ_MODEL, max_tokens: payload.max_tokens ?? 512, messages: [{ role: 'system', content: systemPrompt }, { role: 'user', content: query }], }), signal: AbortSignal.timeout(12000), }) const j = await res.json() const text = j?.choices?.[0]?.message?.content?.trim() ?? '' const sig = signContent(text) return { ok: true, executor: 'GROQ', agent, result: text, sig } } catch (e) { return { ok: false, error: e.message } } } case 'SEAL': case 'ANCHOR': case 'BIND': { // WORM seal — sign payload and write to audit log const content = payload.content ?? payload.data ?? JSON.stringify(payload) const hash = createHash('sha256').update(content).digest('hex') const sig = signContent(content) auditWrite({ type: 'WORM_SEAL', agent, action, hash, sig, content: content.slice(0, 200) }) return { ok: true, executor: 'SEAL', agent, hash: `0x${hash}`, sig, worm: true } } case 'DISPATCH': case 'FLUX': case 'NEXUS': { // Route to proxy registry or agent mesh const target = agent.toLowerCase() const taskStr = payload.task ?? payload.query ?? JSON.stringify(payload) const ere = runERE(taskStr) if (!ere.certified) { return { ok: false, error: `ERE gate blocked dispatch: ${ere.failures.join(', ')}` } } if (proxyRegistry.has(target)) { const proxy = proxyRegistry.get(target) try { const headers = { 'Content-Type': 'application/json' } if (proxy.secret) headers['x-bot-secret'] = proxy.secret const r = await fetch(`${proxy.url}/dispatch`, { method: 'POST', headers, body: JSON.stringify({ payload: taskStr, agent: target }), signal: AbortSignal.timeout(20000), }) const json = await r.json() const sig = signContent(JSON.stringify(json)) return { ok: true, executor: 'PROXY', agent: target, result: json, sig } } catch (e) { return { ok: false, error: `proxy "${target}" unreachable: ${e.message}` } } } // Fall through to compute const result = await computeRoute(target, taskStr) const sig = signContent(result.text) return { ok: true, executor: 'AGENT_MESH', agent: target, result: result.text, provider: result.provider, sig } } case 'NULLIFY': { auditWrite({ type: 'NULLIFY', agent, action, payload }) return { ok: true, executor: 'NULLIFY', agent, nullified: true } } default: return { ok: false, error: `unknown Magma verb: ${verb}` } } } // ── Compute router: Bedrock → Groq → Ollama ─────────────────────────────────── async function computeRoute(agent, query, maxTokens = 1024) { const systemPrompt = AGENT_PROMPTS[agent.toLowerCase()] ?? AGENT_PROMPTS.ahmad // 1. Try Bedrock (primary — sovereign, paid credits) if (bedrock && AWS_KEY && AWS_SECRET) { try { const body = JSON.stringify({ anthropic_version: 'bedrock-2023-05-31', max_tokens: maxTokens, system: systemPrompt, messages: [{ role: 'user', content: query }], }) const cmd = new InvokeModelCommand({ modelId: BEDROCK_MODEL, contentType: 'application/json', accept: 'application/json', body: new TextEncoder().encode(body), }) const res = await bedrock.send(cmd) const decoded = new TextDecoder().decode(res.body) const data = JSON.parse(decoded) const text = data.content?.[0]?.text?.trim() ?? '' if (text) return { text, provider: 'bedrock', model: BEDROCK_MODEL, usage: data.usage } } catch (err) { log(`Bedrock failed: ${err.message} — falling back to Groq`) } } // 2. Fallback: Groq if (GROQ_KEY) { try { const res = await fetch('https://api.groq.com/openai/v1/chat/completions', { method: 'POST', headers: { Authorization: `Bearer ${GROQ_KEY}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ model: GROQ_MODEL, max_tokens: maxTokens, messages: [ { role: 'system', content: systemPrompt }, { role: 'user', content: query }, ], }), signal: AbortSignal.timeout(15000), }) if (res.ok) { const j = await res.json() const text = j?.choices?.[0]?.message?.content?.trim() ?? '' if (text) return { text, provider: 'groq', model: GROQ_MODEL, usage: j.usage } } } catch (err) { log(`Groq failed: ${err.message} — falling back to Ollama`) } } // 3. Fallback: Ollama (local bare metal) try { const ollamaModel = readEnv('OLLAMA_MODEL') || 'llama3.1:8b' const res = await fetch(`${OLLAMA_URL}/api/chat`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ model: ollamaModel, stream: false, messages: [ { role: 'system', content: systemPrompt }, { role: 'user', content: query }, ], }), signal: AbortSignal.timeout(30000), }) if (res.ok) { const j = await res.json() const text = j?.message?.content?.trim() ?? '' if (text) return { text, provider: 'ollama', model: ollamaModel } } } catch (err) { log(`Ollama failed: ${err.message}`) } throw new Error('All compute providers offline (Bedrock + Groq + Ollama)') } // ── MCP Tool definitions ────────────────────────────────────────────────────── const TOOLS = [ { name: 'compute_route', description: 'Route a query to the best available compute provider (Bedrock → Groq → Ollama). Returns result wrapped in Magma envelope.', inputSchema: { type: 'object', properties: { agent: { type: 'string', description: 'Agent key: ahmad, forge, oracle, sentinel, vault, enki, nexus, edaulc' }, query: { type: 'string', description: 'The question or task to send to the agent' }, max_tokens: { type: 'number', description: 'Max tokens for response (default 1024)' }, }, required: ['agent', 'query'], }, }, { name: 'ere_verify', description: 'Run ERE 5-pass verification on a content string. Returns pass/fail per pod and METATRON certification.', inputSchema: { type: 'object', properties: { content: { type: 'string', description: 'Content to verify' }, filepath: { type: 'string', description: 'Filepath hint for language detection (e.g. "foo.ts")' }, }, required: ['content'], }, }, { name: 'proxy_register', description: 'Register a named proxy tool at a URL. Proxied tools are callable via agent_dispatch.', inputSchema: { type: 'object', properties: { name: { type: 'string', description: 'Unique name for this proxy' }, url: { type: 'string', description: 'Base URL of the proxy service' }, description: { type: 'string', description: 'What this proxy does' }, secret: { type: 'string', description: 'Optional bot secret for internal proxies' }, }, required: ['name', 'url'], }, }, { name: 'proxy_list', description: 'List all registered proxy tools and their status.', inputSchema: { type: 'object', properties: {} }, }, { name: 'magma_seal', description: 'Wrap any content in a Magma envelope with ERE verification and WORM hash.', inputSchema: { type: 'object', properties: { content: { type: 'string', description: 'Content to seal' }, agent: { type: 'string', description: 'Agent that produced the content' }, }, required: ['content', 'agent'], }, }, { name: 'agent_dispatch', description: 'Dispatch a task to a registered proxy tool or sovereign agent. Runs ERE gate before forwarding.', inputSchema: { type: 'object', properties: { target: { type: 'string', description: 'Proxy name (from proxy_list) or agent key' }, payload: { type: 'string', description: 'Task or query payload' }, }, required: ['target', 'payload'], }, }, { name: 'magma_exec', description: 'Execute a Magma instruction string. Parses §VERB:AGENT:ACTION{payload}, routes to the correct executor (COMPUTE→Bedrock, QUERY→Groq, SEAL→WORM, DISPATCH→proxy), signs result with governor Ed25519 key, and returns Magma envelope. Supports pipeline syntax with >>.', inputSchema: { type: 'object', properties: { instruction: { type: 'string', description: 'Magma instruction: §VERB:AGENT:ACTION{payload} or pipeline with >>' }, verify_sig: { type: 'string', description: 'Optional: base64 Ed25519 sig to verify against instruction before executing' }, }, required: ['instruction'], }, }, { name: 'governor_pubkey', description: 'Return the governor public key (base64 Ed25519 SPKI DER). Use this to verify Magma envelope signatures externally.', inputSchema: { type: 'object', properties: {} }, }, ] // ── Tool handler ────────────────────────────────────────────────────────────── async function handleTool(name, args) { switch (name) { case 'compute_route': { const { agent = 'ahmad', query, max_tokens = 1024 } = args const result = await computeRoute(agent, query, max_tokens) const ere = runERE(result.text, 'response.txt') const envelope = buildMagmaEnvelope(agent, result.text, ere) return { content: [{ type: 'text', text: result.text }], magma_envelope: envelope, provider: result.provider, model: result.model, usage: result.usage ?? null, } } case 'ere_verify': { const { content, filepath = 'unknown' } = args const ere = runERE(content, filepath) const summary = ere.certified ? 'METATRON: YES — all 5 passes certified' : `METATRON: NO — frozen at ${ere.failures.join(', ')}` return { content: [{ type: 'text', text: summary }], certified: ere.certified, passes: ere.passes.map((p, i) => ({ pod: `P${i+1}`, ...p })), failures: ere.failures, } } case 'proxy_register': { const { name: pname, url, description = '', secret = '' } = args proxyRegistry.set(pname, { url, description, secret, registered: new Date().toISOString() }) log(`Proxy registered: ${pname} → ${url}`) return { content: [{ type: 'text', text: `Proxy "${pname}" registered at ${url}` }], name: pname, url, registered: true, } } case 'proxy_list': { const proxies = [...proxyRegistry.entries()].map(([k, v]) => ({ name: k, url: v.url, description: v.description, registered: v.registered, })) const text = proxies.length ? proxies.map(p => `${p.name}: ${p.url} — ${p.description}`).join('\n') : 'No proxies registered.' return { content: [{ type: 'text', text }], proxies } } case 'magma_seal': { const { content, agent = 'sovereign' } = args const ere = runERE(content) const envelope = buildMagmaEnvelope(agent, content, ere) return { content: [{ type: 'text', text: `Sealed. Hash: ${envelope.state_hash}` }], magma_envelope: envelope, certified: ere.certified, } } case 'agent_dispatch': { const { target, payload } = args // Check ERE on the payload before forwarding const ere = runERE(payload) if (!ere.certified) { return { content: [{ type: 'text', text: `ERE gate blocked dispatch: ${ere.failures.join(', ')}` }], blocked: true, ere_failures: ere.failures, } } // Check proxy registry first if (proxyRegistry.has(target)) { const proxy = proxyRegistry.get(target) try { const headers = { 'Content-Type': 'application/json' } if (proxy.secret) headers['x-bot-secret'] = proxy.secret const res = await fetch(`${proxy.url}/dispatch`, { method: 'POST', headers, body: JSON.stringify({ payload, agent: target }), signal: AbortSignal.timeout(20000), }) const json = await res.json() const envelope = buildMagmaEnvelope(target, JSON.stringify(json), ere) return { content: [{ type: 'text', text: JSON.stringify(json) }], magma_envelope: envelope, proxy: target, } } catch (err) { return { content: [{ type: 'text', text: `Proxy "${target}" unreachable: ${err.message}` }], error: true } } } // Fall through to compute_route for known agents if (AGENT_PROMPTS[target.toLowerCase()]) { const result = await computeRoute(target, payload) const envelope = buildMagmaEnvelope(target, result.text, ere) return { content: [{ type: 'text', text: result.text }], magma_envelope: envelope, provider: result.provider, } } return { content: [{ type: 'text', text: `Unknown target: "${target}"` }], error: true } } case 'magma_exec': { const { instruction, verify_sig } = args // Optional: verify incoming instruction signature before executing if (verify_sig) { const valid = verifySignature(instruction, verify_sig) if (!valid) { return { content: [{ type: 'text', text: 'GOVERNOR VERIFY: FAILED — signature invalid, execution blocked' }], blocked: true, reason: 'invalid_signature', } } } const parsed = parseMagmaInstruction(instruction) if (!parsed.ok) { return { content: [{ type: 'text', text: `Magma parse error: ${parsed.error}` }], blocked: true, reason: 'parse_error', } } const execResult = await executeInstruction(parsed) const resultText = typeof execResult.result === 'string' ? execResult.result : JSON.stringify(execResult) const ere = runERE(resultText) const envelope = buildMagmaEnvelope( parsed.agent ?? 'sovereign', resultText, ere, ) // Attach governor signature to envelope envelope.governor_sig = execResult.sig ?? signContent(resultText) envelope.governor_pubkey = GOVERNOR.publicKey.toString('base64') auditWrite({ type: 'MAGMA_EXEC', instruction: instruction.slice(0, 200), executor: execResult.executor, ok: execResult.ok, sig: envelope.governor_sig, }) return { content: [{ type: 'text', text: resultText }], magma_envelope: envelope, executor: execResult.executor, ok: execResult.ok, ...(execResult.error && { error: execResult.error }), } } case 'governor_pubkey': { return { content: [{ type: 'text', text: GOVERNOR.publicKey.toString('base64') }], pubkey_b64: GOVERNOR.publicKey.toString('base64'), algorithm: 'Ed25519', format: 'SPKI DER base64', } } default: throw new Error(`Unknown tool: ${name}`) } } // ── JSON-RPC 2.0 handler ────────────────────────────────────────────────────── async function handleRpc(msg) { const { jsonrpc, id, method, params } = msg if (method === 'initialize') { return { jsonrpc: '2.0', id, result: { protocolVersion: '2024-11-05', capabilities: { tools: {} }, serverInfo: { name: 'sovereign-mcp', version: '1.0.0' }, }, } } if (method === 'tools/list') { return { jsonrpc: '2.0', id, result: { tools: TOOLS } } } if (method === 'tools/call') { const { name, arguments: args = {} } = params ?? {} try { const result = await handleTool(name, args) return { jsonrpc: '2.0', id, result: { status: 'SEALED', ...result, }, } } catch (err) { return { jsonrpc: '2.0', id, error: { code: -32000, message: err.message }, } } } if (method === 'notifications/initialized') return null return { jsonrpc: '2.0', id, error: { code: -32601, message: `Method not found: ${method}` }, } } // ── Stdio transport ─────────────────────────────────────────────────────────── function startStdio() { log(`Sovereign MCP server starting (stdio mode)`) log(`Bedrock: ${AWS_KEY ? 'ready' : 'no credentials'} Groq: ${GROQ_KEY ? 'ready' : 'no key'} Ollama: ${OLLAMA_URL}`) let buffer = '' process.stdin.setEncoding('utf8') process.stdin.on('data', chunk => { buffer += chunk; processBuffer() }) process.stdin.on('end', () => process.exit(0)) function processBuffer() { const lines = buffer.split('\n') buffer = lines.pop() ?? '' for (const line of lines) { const trimmed = line.trim() if (!trimmed) continue try { const msg = JSON.parse(trimmed) handleRpc(msg).then(res => { if (res) process.stdout.write(JSON.stringify(res) + '\n') }).catch(err => { log(`RPC error: ${err.message}`) }) } catch (err) { log(`Parse error: ${err.message}`) } } } } // ── HTTP transport ──────────────────────────────────────────────────────────── function startHttp() { log(`Sovereign MCP server starting (HTTP mode) on port ${PORT}`) const server = createServer(async (httpReq, httpRes) => { if (httpReq.method === 'OPTIONS') { httpRes.writeHead(204, { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'POST, GET, OPTIONS', 'Access-Control-Allow-Headers': 'Content-Type, x-bot-secret', }) httpRes.end(); return } let body = '' httpReq.on('data', c => { body += c }) httpReq.on('end', async () => { httpRes.setHeader('Content-Type', 'application/json') httpRes.setHeader('Access-Control-Allow-Origin', '*') try { const msg = JSON.parse(body) const res = await handleRpc(msg) httpRes.writeHead(200) httpRes.end(JSON.stringify(res ?? { ok: true })) } catch (err) { httpRes.writeHead(400) httpRes.end(JSON.stringify({ error: err.message })) } }) }) server.listen(PORT, () => log(`HTTP server live on http://localhost:${PORT}`)) } // ── Entry ───────────────────────────────────────────────────────────────────── if (HTTP_MODE) startHttp() else startStdio()