| 1 | import { McpServer } from '@modelcontextprotocol/server'; |
| 2 | import { StdioServerTransport } from '@modelcontextprotocol/server/stdio'; |
| 3 | import { z } from 'zod'; |
| 4 | import { spawn } from 'node:child_process'; |
| 5 | import { createHash, randomUUID } from 'node:crypto'; |
| 6 | import { appendFileSync, constants, openSync, closeSync, readFileSync, fstatSync, writeFileSync } from 'node:fs'; |
| 7 | import { dirname, join, resolve } from 'node:path'; |
| 8 | import { fileURLToPath } from 'node:url'; |
| 9 | import { createInterface } from 'node:readline'; |
| 10 | |
| 11 | const here = dirname(fileURLToPath(import.meta.url)); |
| 12 | const role = z.enum(['creator', 'consumer']).parse(process.env.WHALENET_ROLE); |
| 13 | const directory = resolve(z.string().min(1).parse(process.env.WHALENET_DIRECTORY)); |
| 14 | const expires = z.coerce.number().int().positive().parse(process.env.WHALENET_EXPIRES_AT); |
| 15 | const expected = role === 'consumer' ? z.string().regex(/^[a-f0-9]{64}$/).parse(process.env.WHALENET_CAPABILITY) : null; |
| 16 | const instance = randomUUID(); |
| 17 | const digest = (data: string | Buffer) => createHash('sha256').update(data).digest('hex'); |
| 18 | const workerDigest = digest(readFileSync(join(here, 'worker.py'))); |
| 19 | const serverDigest = digest(readFileSync(fileURLToPath(import.meta.url))); |
| 20 | const log = (event: Record<string, unknown>) => appendFileSync(join(directory, `${role}.jsonl`), JSON.stringify({at: new Date().toISOString(), role, instance, node_pid: process.pid, ...event}) + '\n', {mode: 0o600}); |
| 21 | |
| 22 | if (process.env.DEEPSEEK_API_KEY) throw new Error('Provider credentials must not enter the MCP process'); |
| 23 | const python = spawn(process.env.WHALENET_PYTHON ?? 'python3', ['-I', '-u', join(here, 'worker.py')], { |
| 24 | cwd: directory, env: {PATH: process.env.PATH ?? '/usr/bin:/bin', PYTHONIOENCODING: 'utf-8'}, stdio: ['pipe', 'pipe', 'pipe'], |
| 25 | }); |
| 26 | type Reply = {id: number; result?: Record<string, unknown>; error?: string; python_pid: number; sequence: number}; |
| 27 | let pending: {id: number; resolve: (value: Reply) => void; reject: (error: Error) => void} | null = null; |
| 28 | let sequence = 0; |
| 29 | let closed = false; |
| 30 | let busy = false; |
| 31 | let calls = 0; |
| 32 | let trainingHash: string | null = null; |
| 33 | function failWorker(message: string) { |
| 34 | closed = true; |
| 35 | pending?.reject(new Error(message)); |
| 36 | python.kill('SIGTERM'); |
| 37 | } |
| 38 | const lines = createInterface({input: python.stdout}); |
| 39 | lines.on('line', line => { |
| 40 | try { |
| 41 | if (line.length > 65536) throw new Error('Python response exceeds limit'); |
| 42 | const response = JSON.parse(line) as Reply; |
| 43 | if (!pending || response.id !== pending.id) throw new Error('Python response sequence mismatch'); |
| 44 | pending.resolve(response); |
| 45 | } catch { |
| 46 | failWorker('Invalid Python response'); |
| 47 | } |
| 48 | }); |
| 49 | python.stderr.on('data', () => log({event: 'python_stderr'})); |
| 50 | python.stdin.on('error', () => failWorker('Python input pipe closed')); |
| 51 | python.on('error', () => failWorker('Python worker failed to start')); |
| 52 | python.on('exit', (code, signal) => { |
| 53 | closed = true; |
| 54 | log({event: 'python_exit', python_pid: python.pid, code, signal}); |
| 55 | pending?.reject(new Error('Python worker exited')); |
| 56 | }); |
| 57 | log({event: 'start', python_pid: python.pid, worker_sha256: workerDigest, server_sha256: serverDigest, expires_at: expires}); |
| 58 | |
| 59 | function checkGrant() { |
| 60 | if (Date.now() >= expires) throw new Error('Capability lease expired'); |
| 61 | if (closed) throw new Error('Python worker is closed'); |
| 62 | if (calls >= 12) throw new Error('This task exhausted its 12-call allowance'); |
| 63 | if (busy) throw new Error('Wait for the current tool call to finish'); |
| 64 | } |
| 65 | |
| 66 | async function pythonCall(operation: string, input: Record<string, unknown>, signal: AbortSignal): Promise<Record<string, unknown>> { |
| 67 | if (signal.aborted) throw new Error('Tool call cancelled'); |
| 68 | const id = ++sequence; |
| 69 | let timer: NodeJS.Timeout; |
| 70 | const abort = () => failWorker('Tool call cancelled'); |
| 71 | const response = await new Promise<Reply>((resolveReply, reject) => { |
| 72 | pending = {id, resolve: resolveReply, reject}; |
| 73 | timer = setTimeout(() => failWorker('Python call exceeded five seconds'), 5000); |
| 74 | signal.addEventListener('abort', abort, {once: true}); |
| 75 | python.stdin.write(JSON.stringify({id, operation, ...input}) + '\n'); |
| 76 | }).finally(() => {clearTimeout(timer!); signal.removeEventListener('abort', abort); pending = null;}); |
| 77 | if (response.error || !response.result) throw new Error(response.error ?? 'Missing Python result'); |
| 78 | log({event: 'python_result', operation, python_pid: response.python_pid, sequence: response.sequence}); |
| 79 | return {...response.result, python_pid: response.python_pid, sequence: response.sequence}; |
| 80 | } |
| 81 | |
| 82 | function readBounded(path: string) { |
| 83 | const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW); |
| 84 | try { |
| 85 | const stat = fstatSync(fd); |
| 86 | if (!stat.isFile() || stat.size > 65536) throw new Error('Expected a regular file smaller than 64 KiB'); |
| 87 | return readFileSync(fd); |
| 88 | } finally { closeSync(fd); } |
| 89 | } |
| 90 | |
| 91 | const capabilitySchema = z.object({ |
| 92 | version: z.literal(1), kind: z.literal('duration_regression'), name: z.string().min(1).max(80), |
| 93 | rationale: z.string().min(1).max(800), owner: z.literal('demo-creator'), |
| 94 | expires_at: z.number().int().positive(), training_sha256: z.string().regex(/^[a-f0-9]{64}$/), |
| 95 | worker_sha256: z.string(), server_sha256: z.string(), |
| 96 | parameters: z.object({mad_multiplier: z.number().min(3).max(8), minimum_regression: z.number().min(0.1).max(0.5)}).strict(), |
| 97 | rules: z.record(z.string().min(1).max(80), z.object({baseline_seconds: z.number().positive().max(86400), threshold_seconds: z.number().positive().max(1000000)}).strict()), |
| 98 | }).strict(); |
| 99 | |
| 100 | function loadCapability() { |
| 101 | if (!expected) throw new Error('This task has no admitted capability hash'); |
| 102 | const raw = readBounded(join(directory, `${expected}.json`)); |
| 103 | if (digest(raw) !== expected) throw new Error('Capability hash mismatch'); |
| 104 | const capability = capabilitySchema.parse(JSON.parse(raw.toString('utf8'))); |
| 105 | if (capability.expires_at <= Date.now()) throw new Error('Saved capability expired'); |
| 106 | if (capability.worker_sha256 !== workerDigest || capability.server_sha256 !== serverDigest) throw new Error('Capability implementation changed; review it again'); |
| 107 | return capability; |
| 108 | } |
| 109 | |
| 110 | const server = new McpServer({name: 'whalenet-reuse-mcp-server', version: '0.1.0'}); |
| 111 | async function execute(name: string, action: () => Promise<Record<string, unknown>>) { |
| 112 | let acquired = false; |
| 113 | try { |
| 114 | checkGrant(); |
| 115 | calls += 1; |
| 116 | busy = true; |
| 117 | acquired = true; |
| 118 | const result = await action(); |
| 119 | if (Date.now() >= expires) throw new Error('Capability lease expired during execution'); |
| 120 | log({event: 'tool_result', tool: name, result}); |
| 121 | return {content: [{type: 'text' as const, text: JSON.stringify(result)}], structuredContent: result}; |
| 122 | } catch (error) { |
| 123 | const message = error instanceof Error ? error.message : 'Tool failed'; |
| 124 | log({event: 'tool_error', tool: name, message}); |
| 125 | return {isError: true, content: [{type: 'text' as const, text: message}]}; |
| 126 | } finally { if (acquired) busy = false; } |
| 127 | } |
| 128 | const annotations = {readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false}; |
| 129 | |
| 130 | if (role === 'creator') { |
| 131 | server.registerTool('profile_training', {description: 'Use the persistent Python worker to summarize fixture build durations by job. Inspect before publishing a reusable detector.', inputSchema: z.object({}).strict(), annotations}, |
| 132 | async (_args, extra) => execute('profile_training', async () => { |
| 133 | const raw = readBounded(join(here, 'training.json')); |
| 134 | trainingHash = digest(raw); |
| 135 | return {...await pythonCall('profile', {rows: JSON.parse(raw.toString('utf8'))}, extra.mcpReq.signal), training_sha256: trainingHash}; |
| 136 | })); |
| 137 | server.registerTool('publish_detector', { |
| 138 | description: 'Create an immutable, leased duration-regression capability for a later task. Python fits per-job thresholds from the previously inspected training state. Choose the rule name, sensitivity, and rationale.', |
| 139 | inputSchema: z.object({name: z.string().min(1).max(80), rationale: z.string().min(1).max(800), mad_multiplier: z.number().min(3).max(8), minimum_regression: z.number().min(0.1).max(0.5)}).strict(), |
| 140 | annotations: {...annotations, readOnlyHint: false, idempotentHint: false}, |
| 141 | }, async (args, extra) => execute('publish_detector', async () => { |
| 142 | if (!trainingHash) throw new Error('Call profile_training first'); |
| 143 | const result = await pythonCall('fit', args, extra.mcpReq.signal); |
| 144 | const capability = capabilitySchema.parse({version: 1, kind: 'duration_regression', name: args.name, rationale: args.rationale, |
| 145 | owner: 'demo-creator', expires_at: expires, training_sha256: trainingHash, worker_sha256: workerDigest, server_sha256: serverDigest, |
| 146 | parameters: {mad_multiplier: args.mad_multiplier, minimum_regression: args.minimum_regression}, rules: result.rules}); |
| 147 | if (extra.mcpReq.signal.aborted || Date.now() >= expires) throw new Error('Publication cancelled or lease expired'); |
| 148 | const raw = JSON.stringify(capability, null, 2) + '\n'; |
| 149 | const hash = digest(raw); |
| 150 | writeFileSync(join(directory, `${hash}.json`), raw, {flag: 'wx', mode: 0o600}); |
| 151 | return {capability_sha256: hash, capability, python_pid: result.python_pid, sequence: result.sequence}; |
| 152 | })); |
| 153 | } else { |
| 154 | server.registerTool('discover_capability', {description: 'Discover the single capability admitted to this later task. Validates its content hash, implementation hashes and expiry.', inputSchema: z.object({}).strict(), annotations}, |
| 155 | async () => execute('discover_capability', async () => ({capability_sha256: expected, capability: loadCapability()}))); |
| 156 | server.registerTool('apply_detector', {description: 'Apply the admitted capability to the held-out later build batch using a fresh Python worker. Returns measured durations, thresholds and regression decisions.', inputSchema: z.object({}).strict(), annotations}, |
| 157 | async (_args, extra) => execute('apply_detector', async () => { |
| 158 | const capability = loadCapability(); |
| 159 | const raw = readBounded(join(here, 'later.json')); |
| 160 | return {...await pythonCall('score', {rules: capability.rules, rows: JSON.parse(raw.toString('utf8'))}, extra.mcpReq.signal), capability_sha256: expected, input_sha256: digest(raw)}; |
| 161 | })); |
| 162 | } |
| 163 | |
| 164 | const shutdown = () => {closed = true; python.stdin.end(); python.kill('SIGTERM'); setTimeout(() => python.kill('SIGKILL'), 1000).unref();}; |
| 165 | process.on('SIGTERM', () => {shutdown(); void server.close();}); |
| 166 | process.on('SIGINT', () => {shutdown(); void server.close();}); |
| 167 | process.stdin.on('end', shutdown); |
| 168 | const leaseTimer = setTimeout(() => {log({event: 'lease_expired'}); shutdown(); void server.close();}, Math.max(0, Math.min(expires - Date.now(), 3600000))); |
| 169 | leaseTimer.unref(); |
| 170 | await server.connect(new StdioServerTransport(process.stdin, process.stdout, {maxBufferSize: 65536})); |
| 171 |