diff --git a/README.md b/README.md index 336219a..e21515d 100644 --- a/README.md +++ b/README.md @@ -52,6 +52,49 @@ The bridge accepts newline-delimited JSON-RPC on stdin and writes only protocol 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 30 seconds. 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. A transport failure exits 1. Clean input EOF exits 0. +## Tracing + +The bridge can record how an agent uses the server: which tools it calls, how long each call waits, and how each one ends. Tracing is off unless `PROOFLINE_MCP_TRACE` names a file. Set it beside the token, to an absolute path: + +```json +"env": { + "PROOFLINE_TOKEN": "YOUR_PROOFLINE_TOKEN", + "PROOFLINE_MCP_TRACE": "/path/to/proofline-trace.jsonl" +} +``` + +The bridge then appends one JSON line for each message, once it has answered the message: + +```json +{"time":"2026-11-15T09:20:45.970Z","method":"tools/call","tool":"request_reverification","outcome":"tool_error","duration_ms":185,"request_bytes":236,"response_bytes":245} +``` + +`time` is when the message was answered. `outcome` is `ok`, `tool_error` (a result with `isError: true`), `rpc_error` (a JSON-RPC error from the server, with its `rpc_code`), `refused` (a message the bridge did not forward, such as a probe before the handshake), or the category of a bridge failure: `http` (with `http_status`), `transport`, `response`, `lifecycle`, `jsonrpc`, or `input`. `duration_ms` is the time spent waiting on the server, and 0 when nothing was forwarded. `request_bytes` and `response_bytes` are the sizes of the JSON-RPC lines the agent sent and received. + +A line never holds the token, request parameters or tool arguments, results, error messages or bodies from the server, or request ids. A method or tool name longer than 128 characters is left out. The trace must be a regular file. The bridge creates it with mode `0600` and does not start if it cannot open it. Sessions can share a file, because each line is one append. If a write fails, tracing stops with one line on stderr and the session continues. The bridge writes nothing about the trace to stdout. + +Summarize a trace with `--trace-summary`: + +```sh +npx -y @proofline/mcp --trace-summary /path/to/proofline-trace.jsonl +``` + +```text +message calls failures median ms max ms +tools/call get_review_status 3 0 98 246 +tools/call get_fix_context 2 0 133 141 +tools/call get_review_state 1 1 27 27 +tools/call list_open_findings 1 0 154 154 +tools/call request_reverification 1 1 185 185 +initialize 1 0 66 66 +notifications/initialized 1 0 22 22 +server/discover 1 1 0 0 +tools/list 1 0 63 63 +total 12 3 87 246 +``` + +Each tool has a row, and so has each method that is not a tool call. A failure is any outcome other than `ok`. In this example, from a test server, the agent probed before the handshake (`server/discover`) and once asked for `get_review_status` under a wrong name (`get_review_state`). Lines that are not trace entries are skipped and counted. + ## Development and releases The hosted endpoint's Official MCP Registry entry is maintained in `server.json`. diff --git a/package.json b/package.json index dd62275..ec2d65d 100644 --- a/package.json +++ b/package.json @@ -12,7 +12,7 @@ "files": ["src"], "scripts": { "test": "node --test tests/*.test.js", - "check": "node --check src/cli.js && node --check src/bridge.js", + "check": "node --check src/cli.js && node --check src/bridge.js && node --check src/trace.js", "test:package": "node scripts/packed-smoke.js" }, "publishConfig": { "access": "public" } diff --git a/src/bridge.js b/src/bridge.js index a351220..2ae8f02 100644 --- a/src/bridge.js +++ b/src/bridge.js @@ -51,7 +51,9 @@ async function* frames(input) { } async function send(output, message) { - if (!output.write(`${JSON.stringify(message)}\n`)) await once(output, "drain"); + const line = `${JSON.stringify(message)}\n`; + if (!output.write(line)) await once(output, "drain"); + return Buffer.byteLength(line) - 1; } async function post(frame, config, protocol, notification) { @@ -106,13 +108,27 @@ function failure(error, id) { } /** Serial, bounded bridge for Proofline's stateless JSON MCP endpoint. Never retries. */ -export async function bridge(input, output, diagnostic, config) { +export async function bridge(input, output, diagnostic, config, trace) { let protocol; let ready = false; let id = null; let notification = false; + let entry = {}; + // Traces the message in hand once it is answered: what was asked and how it + // ended, never parameters, results, ids or upstream text. A trace that fails + // stops, and the session goes on. + const record = (outcome, detail) => { + try { + trace?.({ ...entry, outcome, ...detail }); + } catch { + trace = undefined; + diagnostic.write("Proofline MCP trace failure. Tracing stopped.\n"); + } + entry = {}; + }; try { for await (const frame of frames(input)) { + entry.request_bytes = frame.length; let request; try { request = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(frame)); @@ -125,6 +141,8 @@ export async function bridge(input, output, diagnostic, config) { } notification = !("id" in request); id = notification ? null : request.id; + entry.method = request.method; + if (request.method === "tools/call") entry.tool = request.params?.name; const initializing = request.method === "initialize"; const initialized = request.method === "notifications/initialized"; if (initializing ? protocol || notification : @@ -134,15 +152,19 @@ export async function bridge(input, output, diagnostic, config) { // `server/discover`. Refuse that message and keep the session. MCP // allows `ping` at any time, but the server refuses requests without // a negotiated version, so an early ping is answered here. + const pong = !notification && !protocol && request.method === "ping"; if (!notification) { - await send(output, !protocol && request.method === "ping" ? + entry.response_bytes = await send(output, pong ? { jsonrpc: "2.0", id, result: {} } : failure(new BridgeError("lifecycle"), id)); } + record(pong ? "ok" : "refused"); id = null; notification = false; continue; } - const response = await post(frame, config, protocol, notification); + const started = performance.now(); + const response = await post(frame, config, protocol, notification) + .finally(() => { entry.duration_ms = Math.round(performance.now() - started); }); if (!notification) { if (!object(response) || response.jsonrpc !== "2.0" || response.id !== id || ("result" in response) === ("error" in response) || @@ -155,9 +177,11 @@ export async function bridge(input, output, diagnostic, config) { if (response.result.protocolVersion !== PROTOCOL) throw new BridgeError("lifecycle"); protocol = PROTOCOL; } - await send(output, response); + entry.response_bytes = await send(output, response); } if (initialized) ready = true; + record(response?.error ? "rpc_error" : response?.result.isError === true ? "tool_error" : "ok", + { rpc_code: response?.error?.code }); id = null; notification = false; } @@ -166,9 +190,10 @@ export async function bridge(input, output, diagnostic, config) { const safe = error instanceof BridgeError ? error : new BridgeError("transport"); if (!notification) { try { - await send(output, failure(safe, id)); + entry.response_bytes = await send(output, failure(safe, id)); } catch { /* A closed output cannot receive the failure. */ } } + record(safe.category, { http_status: safe.status }); diagnostic.write(`${safe.message}\n`); return 1; } diff --git a/src/cli.js b/src/cli.js index 0a895d8..9bb6e58 100755 --- a/src/cli.js +++ b/src/cli.js @@ -1,22 +1,27 @@ #!/usr/bin/env node import { readFileSync } from "node:fs"; import { bridge, configuration } from "./bridge.js"; +import { summary, tracer } from "./trace.js"; const args = process.argv.slice(2); if (args.length === 1 && args[0] === "--help") { - console.log("Usage: proofline-mcp\n\nSet PROOFLINE_TOKEN to a scoped Proofline token.\nOptional: PROOFLINE_BASE_URL (default https://proofline.sh).\nReads MCP JSON-RPC from stdin and writes responses to stdout.\nRequires Node.js 22 or later."); + console.log("Usage: proofline-mcp\n proofline-mcp --trace-summary \n\nSet PROOFLINE_TOKEN to a scoped Proofline token.\nOptional: PROOFLINE_BASE_URL (default https://proofline.sh).\nOptional: PROOFLINE_MCP_TRACE, a file that gets one JSON line for each message:\nits method, tool name, outcome, duration and sizes, never its content.\nReads MCP JSON-RPC from stdin and writes responses to stdout.\nWith --trace-summary , prints calls, failures and durations for each tool instead.\nRequires Node.js 22 or later."); } else if (args.length === 1 && args[0] === "--version") { console.log(JSON.parse(readFileSync(new URL("../package.json", import.meta.url))).version); +} else if (args.length === 2 && args[0] === "--trace-summary") { + process.exitCode = await summary(args[1], process.stdout, process.stderr); } else if (args.length) { console.error("Unknown arguments. Run proofline-mcp --help."); process.exitCode = 1; } else { try { const config = configuration(process.env); - process.exitCode = await bridge(process.stdin, process.stdout, process.stderr, config); + const trace = tracer(process.env.PROOFLINE_MCP_TRACE); + process.exitCode = await bridge(process.stdin, process.stdout, process.stderr, config, trace); process.stdin.destroy(); } catch { - console.error("Proofline MCP configuration invalid. Set PROOFLINE_TOKEN and use an HTTPS origin for PROOFLINE_BASE_URL."); + console.error("Proofline MCP configuration invalid. Set PROOFLINE_TOKEN and use an HTTPS origin for PROOFLINE_BASE_URL." + + (process.env.PROOFLINE_MCP_TRACE ? " PROOFLINE_MCP_TRACE must name a regular file that can be appended to." : "")); process.exitCode = 1; } } diff --git a/src/trace.js b/src/trace.js new file mode 100644 index 0000000..61e27c0 --- /dev/null +++ b/src/trace.js @@ -0,0 +1,93 @@ +import { appendFileSync, createReadStream, openSync, statSync } from "node:fs"; + +const NAME_LIMIT = 128; +const LINE_LIMIT = 4096; +const named = (value) => + typeof value === "string" && value.length > 0 && value.length <= NAME_LIMIT ? value : undefined; +const printable = (text) => + text.replace(/[^\x20-\x7e]/gu, (character) => `\\u{${character.codePointAt(0).toString(16)}}`); + +/** + * Returns the writer of a trace file, or nothing without a path. A line holds + * the fields named here and no others. + */ +export function tracer(path) { + if (!path) return; + // A terminal or a pipe may be the protocol stream, and either can block the bridge. + if (statSync(path, { throwIfNoEntry: false })?.isFile() === false) { + throw new Error("The trace is not a regular file."); + } + const file = openSync(path, "a", 0o600); + return (entry) => appendFileSync(file, `${JSON.stringify({ + time: new Date().toISOString(), method: named(entry.method), tool: named(entry.tool), + outcome: entry.outcome, duration_ms: entry.duration_ms ?? 0, request_bytes: entry.request_bytes, + response_bytes: entry.response_bytes ?? 0, http_status: entry.http_status, rpc_code: entry.rpc_code, + })}\n`); +} + +/** Returns the entry a line holds, or nothing when the line is not one. */ +function parse(line) { + if (line.length > LINE_LIMIT) return; + try { + const entry = JSON.parse(line); + const names = [entry?.method, entry?.tool].every((name) => name === undefined || named(name)); + const duration = Number.isFinite(entry?.duration_ms) && entry.duration_ms >= 0; + if (names && duration && typeof entry.outcome === "string") return entry; + } catch { /* Counted with the other malformed lines. */ } +} + +/** Prints calls, failures and durations for each tool, and for each method that is not a tool call. */ +export async function summary(path, output, diagnostic) { + const rows = new Map(); + let malformed = 0; + const read = (line) => { + if (!line.trim()) return; + const entry = parse(line); + if (!entry) { malformed++; return; } + const tool = entry.method === "tools/call" && entry.tool !== undefined; + const key = tool ? `tools/call ${entry.tool}` : entry.method ?? "(no method)"; + if (!rows.has(key)) rows.set(key, { tool, failures: 0, durations: [] }); + if (entry.outcome !== "ok") rows.get(key).failures++; + rows.get(key).durations.push(entry.duration_ms); + }; + try { + let rest = ""; + for await (const chunk of createReadStream(path, { encoding: "utf8" })) { + const lines = (rest + chunk).split("\n"); + rest = lines.pop().slice(0, LINE_LIMIT + 1); // An overlong line stays overlong, and bounded. + lines.forEach(read); + } + read(rest); + } catch (error) { + const code = /^E\w+$/.test(error?.code) ? ` (${error.code})` : ""; + diagnostic.write(`Proofline MCP trace summary failed: cannot read the file${code}.\n`); + return 1; + } + const skipped = malformed ? `${malformed} malformed line${malformed === 1 ? "" : "s"} skipped.` : ""; + if (!rows.size) { + diagnostic.write( + `Proofline MCP trace summary failed: no valid line in the file.${skipped && ` ${skipped}`}\n`); + return 1; + } + // Tools first, then the other methods; within each, the most called first. + const sorted = [...rows].sort(([a, one], [b, other]) => + other.tool - one.tool || other.durations.length - one.durations.length || (a < b ? -1 : 1)); + const total = { + failures: sorted.reduce((sum, [, row]) => sum + row.failures, 0), + durations: sorted.flatMap(([, row]) => row.durations), + }; + const table = [...sorted, ["total", total]].map(([key, { failures, durations }]) => { + durations.sort((a, b) => a - b); + const middle = durations.length >> 1; + const median = durations.length % 2 ? durations[middle] : (durations[middle - 1] + durations[middle]) / 2; + return [printable(key), durations.length, failures, Math.round(median), Math.round(durations.at(-1))]; + }); + const cells = [["message", "calls", "failures", "median ms", "max ms"], ...table] + .map((row) => row.map(String)); + const widths = cells[0].map((_, column) => + cells.reduce((width, row) => Math.max(width, row[column].length), 0)); + const lines = cells.map((row) => row.map((cell, column) => + column ? cell.padStart(widths[column]) : cell.padEnd(widths[column])).join(" ")); + output.write(`${lines.concat(skipped || []).join("\n")}\n`); + return 0; +} diff --git a/tests/bridge.test.js b/tests/bridge.test.js index ec6a9ad..3280b2d 100644 --- a/tests/bridge.test.js +++ b/tests/bridge.test.js @@ -1,7 +1,10 @@ import assert from "node:assert/strict"; -import { spawn } from "node:child_process"; +import { spawn, spawnSync } from "node:child_process"; import { once } from "node:events"; +import { mkdtempSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs"; import { createServer } from "node:http"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; import test from "node:test"; import { fileURLToPath } from "node:url"; @@ -42,10 +45,11 @@ async function server(t, responder) { return { origin, requests }; } -async function run(origin, messages, env = {}) { - const child = spawn(process.execPath, [binary], { - env: { ...process.env, PROOFLINE_TOKEN: token, PROOFLINE_BASE_URL: origin, ...env }, - stdio: ["pipe", "pipe", "pipe"], +async function run(origin, messages, env = {}, cwd, wrapper = []) { + const [command, ...args] = [...wrapper, process.execPath, binary]; + const child = spawn(command, args, { + env: { ...process.env, PROOFLINE_TOKEN: token, PROOFLINE_BASE_URL: origin, PROOFLINE_MCP_TRACE: undefined, ...env }, + cwd, stdio: ["pipe", "pipe", "pipe"], }); let stdout = "", stderr = ""; child.stdout.on("data", (chunk) => { stdout += chunk; }); @@ -57,6 +61,20 @@ async function run(origin, messages, env = {}) { return { code, stderr, responses: stdout.trim() ? stdout.trim().split("\n").map(JSON.parse) : [] }; } +function cli(...args) { + const { status, stdout, stderr } = spawnSync(process.execPath, [binary, ...args], { encoding: "utf8" }); + return { status, stdout, stderr }; +} + +function temporary(t) { + const directory = mkdtempSync(join(tmpdir(), "proofline-mcp-trace-")); + t.after(() => rmSync(directory, { recursive: true, force: true })); + return directory; +} + +const entries = (file) => readFileSync(file, "utf8").trimEnd().split("\n").map(JSON.parse); +const size = (message) => message ? Buffer.byteLength(JSON.stringify(message)) : 0; + test("packed stdio bridge preserves tools, untrusted results, incomplete status and tool refusals", async (t) => { const result = { content: [{ type: "text", text: '{"untrusted_text":"literal\\ntext"}' }], structuredContent: { status: "UNAVAILABLE", items: null, reason: "INCOMPLETE" }, isError: true }; @@ -135,3 +153,174 @@ test("pre-initialize probes are answered without ending the session", async (t) assert.deepEqual(outcome.responses[3], { jsonrpc: "2.0", id: 3, result: tools }); assert.deepEqual(fixture.requests.map((request) => request.method), ["initialize", "notifications/initialized", "tools/list"]); }); + +test("an opt-in trace records the method, tool, outcome, wait and sizes of every message", async (t) => { + const trace = join(temporary(t), "trace.jsonl"); + const tools = { tools: [{ name: "request_reverification", inputSchema: { type: "object" } }] }; + const fixture = await server(t, (body, response) => { + if (body.id === 10) { response.writeHead(503); return response.end("private-upstream-canary"); } + const answer = () => json(response, { jsonrpc: "2.0", id: body.id, ...(body.id === 9 ? + { error: { code: -32602, message: "private-upstream-canary" } } : + { result: body.method === "tools/list" ? tools : { content: [], isError: body.id === 8 } }) }); + if (body.id === 7) setTimeout(answer, 60); else answer(); + }); + const messages = [ + { jsonrpc: "2.0", id: "probe", method: "server/discover" }, + { jsonrpc: "2.0", method: "notifications/cancelled", params: { requestId: "probe" } }, + { jsonrpc: "2.0", id: "early-ping", method: "ping" }, + initialize, notification, { jsonrpc: "2.0", id: 3, method: "tools/list" }, + call, { ...call, id: 8 }, { ...call, id: 9, params: { name: "n".repeat(128) } }, { ...call, id: 10 }, + ]; + const started = Date.now(); + const outcome = await run(fixture.origin, messages, { PROOFLINE_MCP_TRACE: trace }); + assert.equal(outcome.code, 1, "the HTTP refusal ends the session, as it does without a trace"); + const lines = entries(trace); + assert.deepEqual(lines.map(({ time, duration_ms, ...rest }) => rest), [ + { method: "server/discover", outcome: "refused" }, + { method: "notifications/cancelled", outcome: "refused" }, + { method: "ping", outcome: "ok" }, + { method: "initialize", outcome: "ok" }, + { method: "notifications/initialized", outcome: "ok" }, + { method: "tools/list", outcome: "ok" }, + { method: "tools/call", tool: "request_reverification", outcome: "ok" }, + { method: "tools/call", tool: "request_reverification", outcome: "tool_error" }, + { method: "tools/call", tool: "n".repeat(128), outcome: "rpc_error", rpc_code: -32602 }, + { method: "tools/call", tool: "request_reverification", outcome: "http", http_status: 503 }, + ].map((expected, index) => ({ ...expected, request_bytes: size(messages[index]), + response_bytes: size(outcome.responses.find((response) => response.id === messages[index].id)) }))); + assert.match(readFileSync(trace, "utf8"), /^\{"time":"\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z","method":"server\/discover","outcome":"refused","duration_ms":0,"request_bytes":\d+,"response_bytes":\d+\}\n/); + assert.ok(lines.every((line) => Date.parse(line.time) >= started && Date.parse(line.time) <= Date.now())); + assert.ok(lines.every((line) => Number.isSafeInteger(line.duration_ms) && line.duration_ms >= 0)); + assert.deepEqual(lines.slice(0, 3).map((line) => line.duration_ms), [0, 0, 0], "nothing was forwarded"); + assert.ok(lines[6].duration_ms >= 50, "the wait on the server is measured"); + if (process.platform !== "win32") assert.equal(statSync(trace).mode & 0o777, 0o600); + assert.deepEqual(await run(fixture.origin, messages), outcome, "the trace changes nothing the agent sees"); + assert.equal(entries(trace).length, 10); + await run(fixture.origin, messages, { PROOFLINE_MCP_TRACE: trace }); + assert.equal(entries(trace).length, 20, "a later session appends to the same file"); +}); + +test("the trace names the failure category of input that is not a request", async (t) => { + const trace = join(temporary(t), "trace.jsonl"); + const fixture = await server(t, () => assert.fail("unexpected request")); + for (const input of ["{\n", "[]\n", " ".repeat(8193) + "\n"]) await run(fixture.origin, input, { PROOFLINE_MCP_TRACE: trace }); + assert.deepEqual(entries(trace).map(({ time, response_bytes, ...rest }) => rest), [ + { outcome: "jsonrpc", duration_ms: 0, request_bytes: 1 }, + { outcome: "jsonrpc", duration_ms: 0, request_bytes: 2 }, + { outcome: "input", duration_ms: 0 }, + ]); + assert.equal(fixture.requests.length, 0); +}); + +test("sessions that share a trace file append whole lines", async (t) => { + const trace = join(temporary(t), "trace.jsonl"); + const fixture = await server(t, () => assert.fail("unexpected request")); + const probes = Array.from({ length: 100 }, (_, id) => ({ jsonrpc: "2.0", id, method: "server/discover" })); + await Promise.all(Array.from({ length: 4 }, () => run(fixture.origin, probes, { PROOFLINE_MCP_TRACE: trace }))); + assert.equal(entries(trace).filter((line) => line.outcome === "refused").length, 400); +}); + +test("the trace never holds the token, parameters, results, ids or upstream text", async (t) => { + const trace = join(temporary(t), "trace.jsonl"); + const secrets = { review_id: "canary-argument", commit_sha: "c".repeat(40), finding_ids: ["canary-finding"] }; + const fixture = await server(t, (body, response) => { + if (body.id === "canary-id-4") { response.writeHead(403, { "X-Canary": "canary-header" }); return response.end("canary-body"); } + json(response, { jsonrpc: "2.0", id: body.id, ...(body.id === "canary-id-2" ? + { error: { code: -32602, message: "canary-error", data: { detail: "canary-data" } } } : + { result: { content: [{ type: "text", text: "canary-result" }], structuredContent: { status: "canary-status" } } }) }); + }); + const outcome = await run(fixture.origin, [initialize, notification, + { jsonrpc: "2.0", id: "canary-id-1", method: "tools/call", params: { name: "request_reverification", arguments: secrets, _meta: { progressToken: "canary-meta" } } }, + { jsonrpc: "2.0", id: "canary-id-2", method: "tools/call", params: { name: "canary-name-" + "x".repeat(117), arguments: secrets } }, + { jsonrpc: "2.0", id: "canary-id-3", method: "canary-method/" + "x".repeat(115), params: { name: "canary-not-a-tool" } }, + { jsonrpc: "2.0", id: "canary-id-4", method: "tools/call", params: { name: { text: "canary-object" }, arguments: secrets } }, + ], { PROOFLINE_MCP_TRACE: trace }); + assert.equal(outcome.code, 1); + assert.equal(outcome.responses.length, 5, "the agent still receives every answer"); + const text = readFileSync(trace, "utf8"); + for (const secret of [token, "canary", secrets.commit_sha, "test-agent"]) assert.ok(!text.includes(secret), secret); + assert.deepEqual(entries(trace).map((line) => [line.method, line.tool, line.outcome]), [ + ["initialize", undefined, "ok"], ["notifications/initialized", undefined, "ok"], + ["tools/call", "request_reverification", "ok"], ["tools/call", undefined, "rpc_error"], + [undefined, undefined, "ok"], ["tools/call", undefined, "http"], + ]); +}); + +test("without PROOFLINE_MCP_TRACE no file is touched and no message changes", async (t) => { + const directory = temporary(t); + const fixture = await server(t, (body, response) => json(response, { jsonrpc: "2.0", id: body.id, result: {} })); + for (const env of [{}, { PROOFLINE_MCP_TRACE: "" }]) { + const outcome = await run(fixture.origin, [initialize, notification, call], env, directory); + assert.deepEqual([outcome.code, outcome.stderr, outcome.responses.length], [0, "", 2]); + const invalid = await run(fixture.origin, "", { ...env, PROOFLINE_TOKEN: "" }, directory); + assert.equal(invalid.stderr, "Proofline MCP configuration invalid. Set PROOFLINE_TOKEN and use an HTTPS origin for PROOFLINE_BASE_URL.\n"); + } + assert.deepEqual(readdirSync(directory), []); +}); + +test("a trace path that cannot be opened is a configuration failure before any request", async (t) => { + const directory = temporary(t); + const fixture = await server(t, () => assert.fail("unexpected request")); + const paths = [join(directory, "missing", "trace.jsonl"), directory, ...(process.platform === "win32" ? [] : ["/dev/null", "/dev/stdout"])]; + for (const path of paths) { + const outcome = await run(fixture.origin, [initialize, notification, call], { PROOFLINE_MCP_TRACE: path }); + assert.equal(outcome.code, 1); + assert.equal(outcome.responses.length, 0, "nothing reaches stdout, the trace least of all"); + assert.equal(outcome.stderr, "Proofline MCP configuration invalid. Set PROOFLINE_TOKEN and use an HTTPS origin for PROOFLINE_BASE_URL. PROOFLINE_MCP_TRACE must name a regular file that can be appended to.\n"); + } + assert.equal(fixture.requests.length, 0); + assert.deepEqual(readdirSync(directory), []); +}); + +// A file size limit of zero lets the bridge open the trace and refuses every write to it. +const limit = ["sh", "-c", 'ulimit -f 0 && exec "$@"', "sh"]; +const limited = process.platform !== "win32" && spawnSync(limit[0], [...limit.slice(1), "true"]).status === 0; + +test("a trace write that fails stops the trace and nothing else", { skip: !limited }, async (t) => { + const trace = join(temporary(t), "trace.jsonl"); + const tools = { tools: [] }; + const fixture = await server(t, (body, response) => json(response, { jsonrpc: "2.0", id: body.id, result: tools })); + const outcome = await run(fixture.origin, [initialize, notification, { jsonrpc: "2.0", id: 3, method: "tools/list" }], + { PROOFLINE_MCP_TRACE: trace }, undefined, limit); + assert.equal(outcome.code, 0); + assert.equal(outcome.stderr, "Proofline MCP trace failure. Tracing stopped.\n"); + assert.deepEqual(outcome.responses[1], { jsonrpc: "2.0", id: 3, result: tools }); + assert.equal(readFileSync(trace, "utf8"), ""); +}); + +test("--trace-summary prints calls, failures and durations for each tool and method", (t) => { + const directory = temporary(t); + const file = join(directory, "trace.jsonl"); + const line = (method, tool, outcome, duration_ms) => JSON.stringify({ + time: "2026-01-01T00:00:00.000Z", method, tool, outcome, duration_ms, request_bytes: 1, response_bytes: 1 }); + writeFileSync(file, [ + line("initialize", undefined, "ok", 30), + line("tools/call", "get_review_status", "ok", 40), + "{not json", + line("tools/call", "get_review_status", "http", 300), + line("tools/call", "get_review_status", "ok", 80), + "", + line("tools/call", "request_reverification", "tool_error", 120), + line("tools/call", "request_reverification", "ok", undefined), + line("ping", undefined, "ok", 1) + " ".repeat(4096), + line("tools/call", "bell\u0007", "ok", 5), + line("server/discover", undefined, "refused", 0), + ].join("\n")); + assert.deepEqual(cli("--trace-summary", file), { status: 0, stderr: "", stdout: [ + "message calls failures median ms max ms", + "tools/call get_review_status 3 1 80 300", + "tools/call bell\\u{7} 1 0 5 5", + "tools/call request_reverification 1 1 120 120", + "initialize 1 0 30 30", + "server/discover 1 1 0 0", + "total 7 3 40 300", + "3 malformed lines skipped.", + "", + ].join("\n") }); + assert.deepEqual(cli("--trace-summary", join(directory, "missing.jsonl")), { + status: 1, stdout: "", stderr: "Proofline MCP trace summary failed: cannot read the file (ENOENT).\n" }); + writeFileSync(file, "{not json\n\n"); + assert.deepEqual(cli("--trace-summary", file), { + status: 1, stdout: "", stderr: "Proofline MCP trace summary failed: no valid line in the file. 1 malformed line skipped.\n" }); + assert.match(cli("--help").stdout, /PROOFLINE_MCP_TRACE[^]*--trace-summary /); +});