diff --git a/README.md b/README.md index 2d4e510..883fd08 100644 --- a/README.md +++ b/README.md @@ -50,7 +50,7 @@ The server keeps model and repository text wrapped as `untrusted_text`. Treat it The bridge accepts newline-delimited JSON-RPC on stdin and writes only protocol responses to stdout. Diagnostics go to stderr. The bridge forwards one request at a time and never retries. A failed mutation may have committed; inspect its state before making another request. -The bridge supports Proofline's stateless JSON transport with protocol `2025-11-25`. Initialize, then send `notifications/initialized` before calling tools. The bridge limits input frames to 8 KiB, responses to 8 MiB, and requests to 35 seconds. A timed-out request returns a correlated JSON-RPC `-32000` error (`data.category: "timeout"`) without ending the bridge, so no restart is needed; because the call may still have run on the server, read state before repeating a write. It refuses redirects, SSE, and `MCP-Session-Id`. HTTP failures produce a correlated, sanitized JSON-RPC error; the bridge does not print upstream error bodies or credentials. HTTP refusals, timed-out notifications, and other transport failures exit 1. Clean input EOF exits 0. +The bridge supports Proofline's stateless JSON transport with protocol `2025-11-25`. Initialize, then send `notifications/initialized` before calling tools. The bridge limits each input line to 1 MiB of raw bytes, whatever the call contains, responses to 8 MiB, and requests to 35 seconds. A timed-out request returns a correlated JSON-RPC `-32000` error (`data.category: "timeout"`) without ending the bridge, so no restart is needed; because the call may still have run on the server, read state before repeating a write. It refuses redirects, SSE, and `MCP-Session-Id`. HTTP failures produce a correlated, sanitized JSON-RPC error; the bridge does not print upstream error bodies or credentials. HTTP refusals, timed-out notifications, and other transport failures exit 1. Clean input EOF exits 0. ## Development and releases diff --git a/src/bridge.js b/src/bridge.js index 577b6c4..241cc89 100644 --- a/src/bridge.js +++ b/src/bridge.js @@ -1,7 +1,12 @@ import { once } from "node:events"; export const PROTOCOL = "2025-11-25"; -const REQUEST_LIMIT = 8192; +// 1 MiB of raw bytes per input line, the limit proposed for the CLI's bridge +// (prooflinedev/cli#144). It fits the longest bounded string in the server's +// tool schemas (65,536 characters, at most 768 KiB escaped) with room for the +// envelope. A call with several large fields, or an unbounded one, can still +// exceed it. +const REQUEST_LIMIT = 1024 * 1024; const RESPONSE_LIMIT = 8 * 1024 * 1024; const REQUEST_TIMEOUT = 35_000; const TRANSPORT_TIMEOUTS = new Set(["UND_ERR_CONNECT_TIMEOUT", "UND_ERR_HEADERS_TIMEOUT", "UND_ERR_BODY_TIMEOUT", "ETIMEDOUT"]); @@ -35,21 +40,34 @@ export function configuration(env) { } async function* frames(input) { - let pending = Buffer.alloc(0); + // Copy each piece into a buffer the bridge owns, so no view of an input chunk + // is kept however finely a line is split. Doubling the buffer keeps the total + // copying linear. The line is detached before it is yielded, so nothing else + // stays alive while its request is in flight. + let line = Buffer.alloc(0); + let size = 0; for await (const chunk of input) { let bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk); while (bytes.length) { const newline = bytes.indexOf(10); const end = newline === -1 ? bytes.length : newline; - if (pending.length + end > REQUEST_LIMIT) throw new BridgeError("input", -32600); - pending = Buffer.concat([pending, bytes.subarray(0, end)]); + if (size + end > REQUEST_LIMIT) throw new BridgeError("input", -32600); + if (size + end > line.length) { + const grown = Buffer.allocUnsafe(Math.min(REQUEST_LIMIT, Math.max(size + end, line.length * 2))); + line.copy(grown, 0, 0, size); + line = grown; + } + bytes.copy(line, size, 0, end); + size += end; if (newline === -1) break; - yield pending; - pending = Buffer.alloc(0); + const frame = Buffer.from(line.subarray(0, size)); + line = Buffer.alloc(0); + size = 0; + yield frame; bytes = bytes.subarray(newline + 1); } } - if (pending.length) throw new BridgeError("input", -32600); + if (size) throw new BridgeError("input", -32600); } async function send(output, message) { diff --git a/tests/bridge.test.js b/tests/bridge.test.js index 5abf266..a884e82 100644 --- a/tests/bridge.test.js +++ b/tests/bridge.test.js @@ -1,11 +1,16 @@ import assert from "node:assert/strict"; import { spawn } from "node:child_process"; import { once } from "node:events"; +import { realpathSync } from "node:fs"; import { createServer } from "node:http"; +import { Readable, Writable } from "node:stream"; import test from "node:test"; -import { fileURLToPath } from "node:url"; +import { fileURLToPath, pathToFileURL } from "node:url"; const binary = process.env.PROOFLINE_MCP_TEST_BIN ?? fileURLToPath(new URL("../src/cli.js", import.meta.url)); +// The bridge module next to the binary under test, so packed runs test the packed copy. +// Resolve a symlinked binary (such as node_modules/.bin/proofline-mcp) to its target first. +const { bridge } = await import(new URL("bridge.js", pathToFileURL(realpathSync(binary))).href); const token = "test-token-never-print"; const protocol = "2025-11-25"; const initialize = { jsonrpc: "2.0", id: "init", method: "initialize", params: { @@ -15,14 +20,22 @@ const notification = { jsonrpc: "2.0", method: "notifications/initialized" }; const call = { jsonrpc: "2.0", id: 7, method: "tools/call", params: { name: "request_reverification", arguments: { review_id: "review", commit_sha: "a".repeat(40), finding_ids: ["finding"] }, } }; +const inputLimit = 1024 * 1024; +const ping = (id) => ({ jsonrpc: "2.0", id, method: "ping" }); +const frame = (message) => JSON.stringify(message) + "\n"; +// A tools/call whose JSON line is exactly `bytes` long (newline excluded). +const callOfLength = (bytes) => { + const shaped = (padding) => ({ ...call, params: { ...call.params, arguments: { ...call.params.arguments, padding } } }); + return shaped("a".repeat(bytes - Buffer.byteLength(JSON.stringify(shaped(""))))); +}; const json = (response, value) => { response.writeHead(200, { "content-type": "application/json" }); response.end(JSON.stringify(value)); }; async function server(t, responder) { const requests = []; const http = createServer(async (request, response) => { - let raw = ""; - for await (const chunk of request) raw += chunk; - const body = JSON.parse(raw); + const chunks = []; + for await (const chunk of request) chunks.push(chunk); + const body = JSON.parse(Buffer.concat(chunks).toString("utf8")); requests.push(body); assert.equal(request.url, "/mcp"); assert.equal(request.headers.authorization, `Bearer ${token}`); @@ -98,7 +111,7 @@ test("HTTP refusals, redirects and malformed responses fail once without leaking test("invalid frames and lifecycle never reach the server", async (t) => { const fixture = await server(t, () => assert.fail("unexpected request")); - for (const input of ["{\n", " ".repeat(8193) + "\n", JSON.stringify(initialize), "[]\n"]) { + for (const input of ["{\n", " ".repeat(inputLimit + 1) + "\n", JSON.stringify(initialize), "[]\n"]) { const outcome = await run(fixture.origin, input); assert.equal(outcome.code, 1); assert.equal(outcome.responses.length, 1); @@ -115,6 +128,69 @@ test("invalid frames and lifecycle never reach the server", async (t) => { } }); +test("a full-length question in a CJK script is relayed and the session continues", async (t) => { + const fixture = await server(t, (body, response) => json(response, { jsonrpc: "2.0", id: body.id, result: {} })); + // ask_codebase allows 4,000 characters; in a CJK script that is 12,000 bytes. + const ask = { jsonrpc: "2.0", id: 7, method: "tools/call", params: { + name: "ask_codebase", arguments: { question: "代".repeat(4000) } } }; + const outcome = await run(fixture.origin, [initialize, notification, ask, ping(8)]); + assert.equal(outcome.code, 0); + assert.equal(outcome.stderr, ""); + assert.deepEqual(outcome.responses.map((response) => response.id), ["init", 7, 8]); + assert.deepEqual(fixture.requests.at(-2), ask); +}); + +test("an input line is bounded at 1 MiB", async (t) => { + const fixture = await server(t, (body, response) => json(response, { jsonrpc: "2.0", id: body.id, result: {} })); + const atLimit = callOfLength(inputLimit); + const accepted = await run(fixture.origin, [initialize, notification, atLimit, ping(8)]); + assert.equal(accepted.code, 0); + assert.deepEqual(accepted.responses.map((response) => response.id), ["init", 7, 8]); + assert.deepEqual(fixture.requests.at(-2), atLimit); + + const sent = fixture.requests.length; + const refused = await run(fixture.origin, + frame(initialize) + frame(notification) + frame(callOfLength(inputLimit + 1)) + frame(ping(8))); + assert.equal(refused.code, 1); + assert.deepEqual(refused.responses.map((response) => response.id), ["init", null]); + assert.equal(refused.responses[1].error.data.category, "input"); + assert.deepEqual(fixture.requests.slice(sent).map((request) => request.method), + ["initialize", "notifications/initialized"], "the oversized call never reaches the server"); +}); + +// Runs the bridge in-process on input delivered in pieces of exactly `size` bytes, +// so the test, not the operating system's pipe, decides where lines are split. +async function relayInPieces(origin, input, size) { + const bytes = Buffer.from(input); + const pieces = []; + for (let offset = 0; offset < bytes.length; offset += size) pieces.push(bytes.subarray(offset, offset + size)); + let stdout = ""; + const output = new Writable({ write(chunk, _encoding, done) { stdout += chunk; done(); } }); + const diagnostic = new Writable({ write(_chunk, _encoding, done) { done(); } }); + const code = await bridge(Readable.from(pieces), output, diagnostic, { token, origin }); + return { code, responses: stdout.trim() ? stdout.trim().split("\n").map(JSON.parse) : [] }; +} + +test("a line split into small pieces is relayed whole, and the limit counts the whole line", async (t) => { + const fixture = await server(t, (body, response) => json(response, { jsonrpc: "2.0", id: body.id, result: {} })); + const ask = { jsonrpc: "2.0", id: 7, method: "tools/call", params: { + name: "ask_codebase", arguments: { question: "代".repeat(4000) } } }; + // 7-byte pieces split the 3-byte characters, and every line spans many pieces. + const relayed = await relayInPieces(fixture.origin, [initialize, notification, ask, ping(8)].map(frame).join(""), 7); + assert.equal(relayed.code, 0); + assert.deepEqual(relayed.responses.map((response) => response.id), ["init", 7, 8]); + assert.deepEqual(fixture.requests.at(-2), ask, "the line is reassembled byte for byte"); + + const sent = fixture.requests.length; + const refused = await relayInPieces(fixture.origin, + frame(initialize) + frame(notification) + frame(callOfLength(inputLimit + 1)) + frame(ping(8)), 8192); + assert.equal(refused.code, 1); + assert.deepEqual(refused.responses.map((response) => response.id), ["init", null]); + assert.equal(refused.responses[1].error.data.category, "input"); + assert.deepEqual(fixture.requests.slice(sent).map((request) => request.method), + ["initialize", "notifications/initialized"], "no piece of the oversized line reaches the server"); +}); + test("pre-initialize probes are answered without ending the session", async (t) => { const tools = { tools: [] }; const fixture = await server(t, (body, response) => json(response, { jsonrpc: "2.0", id: body.id, result: tools }));