Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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" }
Expand Down
37 changes: 31 additions & 6 deletions src/bridge.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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));
Expand All @@ -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 :
Expand All @@ -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) ||
Expand All @@ -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;
}
Expand All @@ -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;
}
Expand Down
11 changes: 8 additions & 3 deletions src/cli.js
Original file line number Diff line number Diff line change
@@ -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 <file>\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 <file>, 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;
}
}
93 changes: 93 additions & 0 deletions src/trace.js
Original file line number Diff line number Diff line change
@@ -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;
}
Loading