Something went wrong. Try again.
Parametric learning in your code harness.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122// A minimal MCP server (streamable HTTP transport, JSON responses only) that// exposes a machine's tools to a harness that speaks MCP, such as opencode.// Tools run in this process with the run's tool context, exactly as they do// under other harnesses. The server listens on 127.0.0.1 only and requires a// random bearer token, so other local processes cannot call the tools.
import { randomBytes } from "node:crypto";import { createServer, type IncomingMessage, type ServerResponse } from "node:http";import type { AddressInfo } from "node:net";import type { Tool, ToolContext } from "./harness.ts";
export type McpToolServer = { url: string; /** Send as `Authorization: Bearer <token>`. */ token: string; close(): Promise<void>;};
type JsonRpcRequest = { jsonrpc: "2.0"; id?: string | number | null; method: string; params?: any };type JsonRpcResponse = { jsonrpc: "2.0"; id: string | number | null; result?: unknown; error?: { code: number; message: string } };
const PROTOCOL_VERSIONS = ["2025-06-18", "2025-03-26", "2024-11-05"];const MAX_BODY = 4 * 1024 * 1024;
export async function serveToolsOverMcp(tools: Tool[], context: ToolContext): Promise<McpToolServer> { const token = randomBytes(24).toString("hex"); const byName = new Map(tools.map((t) => [t.name, t]));
const handle = async (message: JsonRpcRequest): Promise<JsonRpcResponse | undefined> => { const id = message.id ?? null; const ok = (result: unknown): JsonRpcResponse => ({ jsonrpc: "2.0", id, result }); const fail = (code: number, msg: string): JsonRpcResponse => ({ jsonrpc: "2.0", id, error: { code, message: msg } }); // Notifications get no response. if (message.id === undefined) return undefined;
switch (message.method) { case "initialize": { const requested = message.params?.protocolVersion; return ok({ protocolVersion: PROTOCOL_VERSIONS.includes(requested) ? requested : PROTOCOL_VERSIONS[0], capabilities: { tools: { listChanged: false } }, serverInfo: { name: "machine", version: "0.4.0" }, }); } case "ping": return ok({}); case "tools/list": return ok({ tools: tools.map((t) => ({ name: t.name, description: t.description, inputSchema: t.inputSchema })) }); case "tools/call": { const tool = byName.get(message.params?.name); if (!tool) return fail(-32602, `Unknown tool "${message.params?.name}".`); try { const result = await tool.execute(message.params?.arguments ?? {}, context); return ok({ content: [{ type: "text", text: typeof result === "string" ? result : JSON.stringify(result) }] }); } catch (error) { return ok({ content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }], isError: true }); } } default: return fail(-32601, `Method not found: ${message.method}`); } };
const server = createServer(async (req: IncomingMessage, res: ServerResponse) => { if (req.headers.authorization !== `Bearer ${token}`) return send(res, 401, { error: "unauthorized" }); // JSON responses only: no server-initiated stream, no sessions to delete. if (req.method !== "POST") return send(res, 405, { error: "method not allowed" }); let body: unknown; try { body = JSON.parse(await readBody(req)); } catch { return send(res, 400, { jsonrpc: "2.0", id: null, error: { code: -32700, message: "Parse error" } }); } const batch = Array.isArray(body); const messages = (batch ? body : [body]) as JsonRpcRequest[]; const responses = (await Promise.all(messages.map(handle))).filter((r): r is JsonRpcResponse => r !== undefined); if (responses.length === 0) { res.writeHead(202).end(); return; } send(res, 200, batch ? responses : responses[0]); });
await new Promise<void>((resolve, reject) => { server.once("error", reject); server.listen(0, "127.0.0.1", () => resolve()); }); const { port } = server.address() as AddressInfo;
return { url: `http://127.0.0.1:${port}/mcp`, token, close: () => new Promise((resolve) => { server.closeAllConnections?.(); server.close(() => resolve()); }), };}
function send(res: ServerResponse, status: number, body: unknown) { res.writeHead(status, { "content-type": "application/json" }).end(JSON.stringify(body));}
function readBody(req: IncomingMessage): Promise<string> { return new Promise((resolve, reject) => { let size = 0; const chunks: Buffer[] = []; req.on("data", (chunk: Buffer) => { size += chunk.length; if (size > MAX_BODY) { reject(new Error("body too large")); req.destroy(); return; } chunks.push(chunk); }); req.on("end", () => resolve(Buffer.concat(chunks).toString("utf8"))); req.on("error", reject); });}