Skip to content
Open
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
175 changes: 168 additions & 7 deletions src/mcp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,34 +6,165 @@ export interface KnowledgeResult {
structuredContent?: Record<string, unknown>;
isError?: boolean;
}

/** Selects one authorized organization for this call only. */
export interface McpTarget {
organization_id?: string;
}

export interface RepositoryKnowledge extends McpTarget {
repository: string;
commit?: string;
}

const PROTOCOL = "2025-11-25";

function object(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === "object" && !Array.isArray(value);
}

function refused(): ProoflineError {
return new ProoflineError(
0,
"urn:proofline:sdk:mcp",
"Invalid or refused MCP response",
);
}

/**
* Creates an incremental SSE decoder for one expected JSON-RPC response.
*
* It processes complete lines as chunks arrive and stops as soon as the
* expected response ID is received. A pending final event is dispatched at EOF.
*/
function sseDecoder(expectedId: number) {
let buffer = "";
let data: string[] = [];
let matched: unknown;

const processLine = (line: string) => {
if (line === "") {
if (data.length > 0) {
const message = data.join("\n");

try {
const value: unknown = JSON.parse(message);

if (
object(value) &&
value.jsonrpc === "2.0" &&
value.id === expectedId
) {
matched = value;
}
} catch {
// Ignore malformed SSE messages and continue looking.
}
}

data = [];
return;
}

// Lines beginning with ":" are SSE comments.
if (line.startsWith(":")) return;

const separator = line.indexOf(":");
const field = separator === -1 ? line : line.slice(0, separator);
let value = separator === -1 ? "" : line.slice(separator + 1);

// SSE removes at most one leading space after the colon.
if (value.startsWith(" ")) {
value = value.slice(1);
}

if (field === "data") {
data.push(value);
}
};

return (
chunk: string,
_headers: Headers,
final: boolean,
): { done: boolean; value?: unknown } => {
if (matched !== undefined) {
return { done: true, value: matched };
}

buffer += chunk;

for (;;) {
const cr = buffer.indexOf("\r");
const lf = buffer.indexOf("\n");

let separator = -1;

if (cr === -1) {
separator = lf;
} else if (lf === -1) {
separator = cr;
} else {
separator = Math.min(cr, lf);
}

if (separator === -1) break;

// Wait for the next chunk if CR may be followed by LF.
if (
buffer[separator] === "\r" &&
separator === buffer.length - 1 &&
!final
) {
break;
}

const line = buffer.slice(0, separator);
const isCrLf =
buffer[separator] === "\r" && buffer[separator + 1] === "\n";

buffer = buffer.slice(separator + (isCrLf ? 2 : 1));

processLine(line);

if (matched !== undefined) {
return { done: true, value: matched };
}
}

// Any remaining unterminated line/event is incomplete.
if (final) {
// EOF terminates a final line even when it has no line ending.
if (buffer.length > 0) {
processLine(buffer);
buffer = "";
}

// The SSE specification dispatches pending data at EOF.
if (data.length > 0) {
processLine("");
}

if (matched !== undefined) {
return { done: true, value: matched };
}
}

return { done: false };
};
}

function envelope(value: unknown, id: number): Record<string, unknown> {
if (
!object(value) ||
value.jsonrpc !== "2.0" ||
value.id !== id ||
"error" in value ||
!object(value.result)
)
) {
throw refused();
}

return value.result;
}

Expand All @@ -44,26 +175,48 @@ export class McpTools {
protected async call(name: string, args: object): Promise<KnowledgeResult> {
// Bind the per-call target before protocol negotiation yields to the caller.
const callArguments = { ...args };

const invoke = (
body: object,
phase: "initialize" | "notification" | "call",
) =>
this.transport.request<unknown>(
) => {
const expectedId = phase === "initialize" ? 1 : 2;

return this.transport.request<unknown>(
"POST",
"/mcp",
{},
undefined,
body,
(text) => {
(text, headers) => {
if (phase === "notification") {
if (text !== "") throw refused();
return undefined;
}
return JSON.parse(text) as unknown;

const contentType = headers
.get("content-type")
?.split(";")[0]
?.trim()
.toLowerCase();

if (contentType === "application/json") {
return JSON.parse(text) as unknown;
}

if (contentType !== "text/event-stream") {
throw refused();
}

// SSE responses are decoded incrementally by the transport.
throw refused();
},
"application/json, text/event-stream",
phase,
phase === "notification" ? undefined : sseDecoder(expectedId),
);
};

const initialized = envelope(
await invoke(
{
Expand All @@ -80,11 +233,16 @@ export class McpTools {
),
1,
);
if (initialized.protocolVersion !== PROTOCOL) throw refused();

if (initialized.protocolVersion !== PROTOCOL) {
throw refused();
}

await invoke(
{ jsonrpc: "2.0", method: "notifications/initialized" },
"notification",
);

const result = envelope(
await invoke(
{
Expand All @@ -97,6 +255,7 @@ export class McpTools {
),
2,
);

if (
!Array.isArray(result.content) ||
result.content.some(
Expand All @@ -108,8 +267,10 @@ export class McpTools {
(result.isError !== undefined && typeof result.isError !== "boolean") ||
(result.structuredContent !== undefined &&
!object(result.structuredContent))
)
) {
throw refused();
}

return result as unknown as KnowledgeResult;
}
}
Expand Down
Loading