import { randomUUID } from 'node:crypto'; import { readFileSync } from 'node:fs'; import { Server } from '@modelcontextprotocol/sdk/server/index.js'; import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'; import { CallToolRequestSchema, ListToolsRequestSchema, } from '@modelcontextprotocol/sdk/types.js'; import { ClaudeChannelIpcServer } from './claude-channel-ipc-server.js'; const CHANNEL_SERVER_NAME = 'clawclaw-channel'; const CHANNEL_PROBE_INITIAL_DELAY_MS = 250; const CHANNEL_PROBE_RETRY_MS = 5_000; const PACKAGE_VERSION = String(JSON.parse( readFileSync(new URL('../../package.json', import.meta.url), 'utf8'), ).version ?? '0.0.0'); type ToolArguments = Record; function toolResult(value: Record, isError = false) { return { content: [{ type: 'text' as const, text: JSON.stringify(value) }], ...(isError ? { isError: true } : {}), }; } function toolError(error: unknown) { return toolResult({ ok: false, error: error instanceof Error ? error.message : String(error), }, true); } function stringArgument(args: ToolArguments, name: string): string | undefined { const value = args[name]; return typeof value === 'string' && value.trim() ? value.trim() : undefined; } /** Claude-owned MCP bridge. It receives Owner pushes but never owns game lifecycle. */ export class ClaudeChannelServer { private readonly mcp = new Server( { name: CHANNEL_SERVER_NAME, version: PACKAGE_VERSION }, { capabilities: { experimental: { 'claude/channel': {} }, tools: {}, }, instructions: [ 'This server is the realtime ClawClaw delivery bridge for Claude Code.', 'On the connection probe, call channel_confirm with its probe_id only to record receipt.', 'Start and control the game with ccl commands; this Channel server does not own the game process.', 'Each gameplay Channel message is one clawclaw.channel-events.v2 JSON payload.', 'Process every Event in order and take any required game actions.', 'Do not poll for Events or acknowledge deliveries; delivery state is internal to the Channel Adapter.', ].join(' '), }, ); private readonly transport = new StdioServerTransport(); private readonly ipc = new ClaudeChannelIpcServer({ deliver: (payload, meta) => this.channelNotification(JSON.stringify(payload), meta), diagnostic: (name, attributes) => this.logDiagnostic(name, attributes), }); private readonly probeId = randomUUID(); private confirmed = false; private closing = false; private probeTimer?: ReturnType; private probeAttempts = 0; private lastProbeSentAt?: string; private lastProbeError?: string; private closeResolve?: () => void; private readonly closed = new Promise((resolve) => { this.closeResolve = resolve; }); constructor() { this.installHandlers(); } async run(): Promise { await this.mcp.connect(this.transport); await this.ipc.start(); this.scheduleProbe(); const protocolClose = this.transport.onclose; this.transport.onclose = () => { protocolClose?.(); void this.shutdown(false); }; process.stdin.once('end', () => void this.shutdown(false)); process.stdin.once('close', () => void this.shutdown(false)); process.once('SIGINT', () => void this.shutdown(true)); process.once('SIGTERM', () => void this.shutdown(true)); await this.closed; } private installHandlers(): void { this.mcp.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: [ { name: 'channel_confirm', description: 'Record that Claude received the Channel probe. It does not gate gameplay delivery.', inputSchema: { type: 'object', properties: { probe_id: { type: 'string' } }, required: ['probe_id'], additionalProperties: false, }, }, { name: 'channel_status', description: 'Inspect probe receipt and the Owner-to-Channel IPC bridge.', inputSchema: { type: 'object', properties: {}, additionalProperties: false }, }, ], })); this.mcp.setRequestHandler(CallToolRequestSchema, async (request) => { const args = (request.params.arguments ?? {}) as ToolArguments; try { switch (request.params.name) { case 'channel_confirm': return toolResult(this.confirm(stringArgument(args, 'probe_id'))); case 'channel_status': return toolResult(this.status()); default: return toolError(`Unknown tool: ${request.params.name}`); } } catch (error) { return toolError(error); } }); } private scheduleProbe(delayMs = CHANNEL_PROBE_INITIAL_DELAY_MS): void { if (this.confirmed || this.closing || this.probeTimer) return; this.probeTimer = setTimeout(() => { this.probeTimer = undefined; if (this.confirmed || this.closing) return; void this.sendProbe() .catch((error) => this.logError('probe', error)) .finally(() => this.scheduleProbe(CHANNEL_PROBE_RETRY_MS)); }, delayMs); } private async sendProbe(): Promise { this.probeAttempts += 1; try { await this.channelNotification( JSON.stringify({ schema: 'clawclaw.channel-probe.v1', probe_id: this.probeId, instruction: 'Call channel_confirm with this probe_id to record receipt. Gameplay does not wait for confirmation.', }), { kind: 'connection_probe', probe_id: this.probeId, }, ); this.lastProbeSentAt = new Date().toISOString(); this.lastProbeError = undefined; } catch (error) { this.lastProbeError = error instanceof Error ? error.message : String(error); throw error; } } private confirm(probeId: string | undefined): Record { if (probeId !== this.probeId) throw new Error('Invalid or stale Channel probe_id.'); if (this.confirmed) return { ok: true, status: 'already_confirmed', ...this.status() }; this.confirmed = true; if (this.probeTimer) clearTimeout(this.probeTimer); this.probeTimer = undefined; return { ok: true, status: 'confirmed', ...this.status() }; } private status(): Record { return { ok: true, confirmed: this.confirmed, delivery_waits_for_confirmation: false, ipc: this.ipc.status(), probe: { attempts: this.probeAttempts, last_sent_at: this.lastProbeSentAt ?? null, last_error: this.lastProbeError ?? null, }, }; } private channelNotification(content: string, meta: Record): Promise { return this.mcp.notification({ method: 'notifications/claude/channel', params: { content, meta }, } as any); } private async shutdown(closeTransport: boolean): Promise { if (this.closing) return this.closed; this.closing = true; if (this.probeTimer) clearTimeout(this.probeTimer); this.probeTimer = undefined; await this.ipc.close().catch(() => {}); if (closeTransport) { try { await this.transport.close(); } catch {} } this.closeResolve?.(); } private logDiagnostic(name: string, attributes?: Record): void { if (process.env.CLAWCLAW_CHANNEL_DEBUG !== '1') return; process.stderr.write(`[clawclaw-channel] ${name} ${JSON.stringify(attributes ?? {})}\n`); } private logError(stage: string, error: unknown): void { process.stderr.write( `[clawclaw-channel] ${stage}: ${error instanceof Error ? error.message : String(error)}\n`, ); } } export async function runClaudeChannelServer(): Promise { await new ClaudeChannelServer().run(); }