|
| 1 | +/** |
| 2 | + * The Model Context Protocol stdio server loop behind `mfn mcp`: one JSON-RPC |
| 3 | + * 2.0 message per line on stdin/stdout. Hand-rolled on node built-ins — no SDK |
| 4 | + * dependency. Tool definitions and execution live in mcp-tools.ts. |
| 5 | + */ |
| 6 | +import { createInterface } from 'node:readline'; |
| 7 | +import { COMMANDS } from '../catalog'; |
| 8 | +import pkg from '../../package.json'; |
| 9 | +import { TOOLS, callTool } from './mcp-tools'; |
| 10 | + |
| 11 | +export const PROTOCOL_VERSION = '2025-06-18'; |
| 12 | + |
| 13 | +/** One line of JSON-RPC on stdout — the MCP stdio framing. */ |
| 14 | +const send = (msg: Record<string, unknown>): void => { |
| 15 | + process.stdout.write(JSON.stringify(msg) + '\n'); |
| 16 | +}; |
| 17 | + |
| 18 | +const reply = (id: unknown, result: Record<string, unknown>): void => |
| 19 | + send({ jsonrpc: '2.0', id, result }); |
| 20 | + |
| 21 | +const replyError = (id: unknown, code: number, message: string): void => |
| 22 | + send({ jsonrpc: '2.0', id, error: { code, message } }); |
| 23 | + |
| 24 | +async function handleMessage(msg: any): Promise<void> { |
| 25 | + const { id, method, params } = msg ?? {}; |
| 26 | + const isRequest = id !== undefined && id !== null; |
| 27 | + |
| 28 | + if (typeof method !== 'string') { |
| 29 | + if (isRequest) replyError(id, -32600, 'Invalid request: no method'); |
| 30 | + return; |
| 31 | + } |
| 32 | + if (method.startsWith('notifications/')) return; // initialized, cancelled, … |
| 33 | + |
| 34 | + switch (method) { |
| 35 | + case 'initialize': { |
| 36 | + const requested = params?.protocolVersion; |
| 37 | + reply(id, { |
| 38 | + protocolVersion: typeof requested === 'string' ? requested : PROTOCOL_VERSION, |
| 39 | + capabilities: { tools: {} }, |
| 40 | + serverInfo: { name: pkg.name, version: pkg.version }, |
| 41 | + instructions: |
| 42 | + `Wraps the mfn CLI (${COMMANDS.length} headless commands). Call mfn_capabilities ` + |
| 43 | + 'first to discover commands, then mfn_run {command, args} to execute one — every ' + |
| 44 | + 'result is a single JSON object ({ok:true,...} or {ok:false,error,message}). ' + |
| 45 | + 'mfn_help returns per-command flags. Security guardrails (sensitive-path refusal, ' + |
| 46 | + 'secret redaction, reversible deletes) are always on; `update` is not exposed.', |
| 47 | + }); |
| 48 | + return; |
| 49 | + } |
| 50 | + case 'ping': |
| 51 | + reply(id, {}); |
| 52 | + return; |
| 53 | + case 'tools/list': |
| 54 | + reply(id, { tools: TOOLS }); |
| 55 | + return; |
| 56 | + case 'tools/call': { |
| 57 | + const name = String(params?.name ?? ''); |
| 58 | + if (!TOOLS.some((t) => t.name === name)) { |
| 59 | + replyError(id, -32602, `Unknown tool "${name}"`); |
| 60 | + return; |
| 61 | + } |
| 62 | + reply(id, await callTool(name, params?.arguments ?? {})); |
| 63 | + return; |
| 64 | + } |
| 65 | + default: |
| 66 | + if (isRequest) replyError(id, -32601, `Method not found: ${method}`); |
| 67 | + } |
| 68 | +} |
| 69 | + |
| 70 | +/** Serve until stdin closes (client disconnect). Never returns. */ |
| 71 | +export async function serveMcp(): Promise<never> { |
| 72 | + process.stderr.write(`${pkg.name} v${pkg.version} — MCP server ready (stdio)\n`); |
| 73 | + const rl = createInterface({ input: process.stdin, crlfDelay: Infinity }); |
| 74 | + for await (const line of rl) { |
| 75 | + const trimmed = line.trim(); |
| 76 | + if (!trimmed) continue; |
| 77 | + let msg: any; |
| 78 | + try { |
| 79 | + msg = JSON.parse(trimmed); |
| 80 | + } catch { |
| 81 | + replyError(null, -32700, 'Parse error: messages must be one JSON object per line'); |
| 82 | + continue; |
| 83 | + } |
| 84 | + try { |
| 85 | + await handleMessage(msg); |
| 86 | + } catch (error) { |
| 87 | + const message = error instanceof Error ? error.message : String(error); |
| 88 | + replyError(msg?.id ?? null, -32603, `Internal error: ${message}`); |
| 89 | + } |
| 90 | + } |
| 91 | + process.exit(0); // stdin closed — client disconnected |
| 92 | +} |
0 commit comments