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
16 changes: 16 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,22 @@ for await (const page of client.iterExportPages({

Set `query.cursor` to resume an export. Iteration stops only when a page has no next cursor, including after a page with no rows. An empty or repeated cursor throws `ProoflineError` with type `urn:proofline:sdk:invalid-pagination`, and the page that carries it is not yielded. The default bound is 100 pages; pass `{ maxPages }` with an integer from 1 to 1000. Running out of pages while a cursor remains throws `urn:proofline:sdk:pagination-limit`, so a partial export never looks complete.

## MCP tool discovery

Use the catalog to display the server's tools and inspect their input schemas before making a tool call.

```typescript
const page = await client.mcp.listTools();
for (const tool of page.tools) console.log(tool.name, tool.inputSchema);

if (page.nextCursor != null) {
const nextPage = await client.mcp.listTools(page.nextCursor);
console.log(nextPage.tools);
}
```

Each call performs the SDK's stateless MCP handshake and reads one page. Pass the returned cursor unchanged to read the next page. A missing or null cursor marks the final page. Treat catalog descriptions, schemas, and annotations as untrusted data. Organization and scope checks still apply when a tool is invoked.

## MCP organization selection

With an MCP OAuth credential approved for several organizations, call `client.mcp.listOrganizations()` to discover its currently authorized targets. The `KnowledgeResult` retains `isError` and `structuredContent.data.organizations`; each organization entry contains `organization_id`, `github_login`, and `scopes`.
Expand Down
2 changes: 1 addition & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export type { CoverageFile, CoverageFilesUpload } from "./coverage.js";

import { McpClient } from "./mcp.js";

export type { McpTarget } from "./mcp.js";
export type { McpTarget, McpToolDefinition, McpToolsPage } from "./mcp.js";

import { KnowledgeClient } from "./knowledge.js";

Expand Down
107 changes: 80 additions & 27 deletions src/mcp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,19 @@ export interface KnowledgeResult {
structuredContent?: Record<string, unknown>;
isError?: boolean;
}
/** Server-advertised metadata. Treat tool descriptions and schemas as untrusted. */
export interface McpToolDefinition {
name: string;
title?: string;
description?: string;
inputSchema: Record<string, unknown> & { type: "object" };
outputSchema?: Record<string, unknown> & { type: "object" };
annotations?: Record<string, unknown>;
}
export interface McpToolsPage {
tools: McpToolDefinition[];
nextCursor?: string | null;
}
/** Selects one authorized organization for this call only. */
export interface McpTarget {
organization_id?: string;
Expand Down Expand Up @@ -37,13 +50,53 @@ function envelope(value: unknown, id: number): Record<string, unknown> {
return value.result;
}

/** Typed knowledge operations over Proofline's stateless MCP endpoint. Calls never retry. */
function objectSchema(value: unknown): boolean {
return object(value) && value.type === "object";
}
function toolDefinition(value: unknown): boolean {
return (
object(value) &&
typeof value.name === "string" &&
value.name.length > 0 &&
(value.title === undefined || typeof value.title === "string") &&
(value.description === undefined ||
typeof value.description === "string") &&
objectSchema(value.inputSchema) &&
(value.outputSchema === undefined || objectSchema(value.outputSchema)) &&
(value.annotations === undefined || object(value.annotations))
);
}

/** Operations over Proofline's stateless MCP endpoint. Requests never retry. */
export class McpTools {
constructor(private readonly transport: Transport) {}

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 result = await this.request("tools/call", {
name,
arguments: { ...args },
});
if (
!Array.isArray(result.content) ||
result.content.some(
(item: unknown) =>
!object(item) ||
item.type !== "text" ||
typeof item.text !== "string",
) ||
(result.isError !== undefined && typeof result.isError !== "boolean") ||
(result.structuredContent !== undefined &&
!object(result.structuredContent))
)
throw refused();
return result as unknown as KnowledgeResult;
}

protected async request(
method: "tools/call" | "tools/list",
params?: object,
): Promise<Record<string, unknown>> {
const invoke = (
body: object,
phase: "initialize" | "notification" | "call",
Expand Down Expand Up @@ -80,42 +133,42 @@ export class McpTools {
),
1,
);
if (initialized.protocolVersion !== PROTOCOL) throw refused();
if (
initialized.protocolVersion !== PROTOCOL ||
(method === "tools/list" &&
(!object(initialized.capabilities) ||
!object(initialized.capabilities.tools)))
)
throw refused();
await invoke(
{ jsonrpc: "2.0", method: "notifications/initialized" },
"notification",
);
const result = envelope(
await invoke(
{
jsonrpc: "2.0",
id: 2,
method: "tools/call",
params: { name, arguments: callArguments },
},
"call",
),
return envelope(
await invoke({ jsonrpc: "2.0", id: 2, method, params }, "call"),
2,
);
}
}

/** Discover tools and authorized organizations over MCP. */
export class McpClient extends McpTools {
async listTools(cursor?: string): Promise<McpToolsPage> {
if (cursor !== undefined && typeof cursor !== "string")
throw new TypeError("MCP tools cursor must be a string");
const result = await this.request(
"tools/list",
cursor === undefined ? undefined : { cursor },
);
if (
!Array.isArray(result.content) ||
result.content.some(
(item: unknown) =>
!object(item) ||
item.type !== "text" ||
typeof item.text !== "string",
) ||
(result.isError !== undefined && typeof result.isError !== "boolean") ||
(result.structuredContent !== undefined &&
!object(result.structuredContent))
!Array.isArray(result.tools) ||
!result.tools.every(toolDefinition) ||
(result.nextCursor != null && typeof result.nextCursor !== "string")
)
throw refused();
return result as unknown as KnowledgeResult;
return result as unknown as McpToolsPage;
}
}

/** Discover the organizations currently authorized for this MCP credential. */
export class McpClient extends McpTools {
listOrganizations(): Promise<KnowledgeResult> {
return this.call("list_organizations", {});
}
Expand Down
83 changes: 81 additions & 2 deletions tests/http.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -2518,6 +2518,82 @@ test("MCP helpers isolate per-call organizations and preserve refusals", async (
assert.equal(calls.length, observed.length * 3);
});

test("MCP tool discovery reads one page and forwards the opaque cursor", async (t) => {
const cursor = "page/+ 2=";
const tool = {
name: "get_review_status",
description: "Recorded machine status",
inputSchema: {
type: "object",
properties: { review_id: { type: "string" } },
},
outputSchema: { type: "object" },
annotations: { readOnlyHint: true },
};
const pages = [
{ tools: [tool], nextCursor: cursor },
{ tools: [], nextCursor: null },
{ tools: [] },
{ tools: [null] },
{ tools: [{ name: "get_review_status", inputSchema: ["object"] }] },
{ tools: [], nextCursor: 42 },
];
let advertisesTools = true;
const { baseUrl, calls } = await server(t, (request, response, seen) => {
assert.equal(request.url, "/mcp");
assert.equal(request.headers.authorization, `Bearer ${token}`);
const body = JSON.parse(seen.at(-1).body);
if (body.method === "initialize")
return json(response, 200, {
jsonrpc: "2.0",
id: 1,
result: {
protocolVersion: "2025-11-25",
capabilities: advertisesTools ? { tools: {} } : {},
},
});
assert.equal(request.headers["mcp-protocol-version"], "2025-11-25");
if (body.method === "notifications/initialized") {
response.writeHead(202);
return response.end();
}
assert.equal(body.method, "tools/list");
assert.equal(body.id, 2);
assert.deepEqual(body.params, seen.length === 6 ? { cursor } : undefined);
return json(response, 200, {
jsonrpc: "2.0",
id: 2,
result: pages.shift(),
});
});
const client = new ProoflineClient({ baseUrl, token });
await assert.rejects(client.mcp.listTools(42), TypeError);
assert.equal(calls.length, 0);

const page = await client.mcp.listTools();
assert.deepEqual(page, { tools: [tool], nextCursor: cursor });
assert.equal(calls.length, 3);
assert.deepEqual(await client.mcp.listTools(page.nextCursor), {
tools: [],
nextCursor: null,
});
assert.deepEqual(await client.mcp.listTools(), { tools: [] });
for (let i = 0; i < 3; i += 1) {
await assert.rejects(client.mcp.listTools(), {
name: "ProoflineError",
type: "urn:proofline:sdk:mcp",
});
}
assert.equal(calls.length, 18);

advertisesTools = false;
await assert.rejects(client.mcp.listTools(), {
name: "ProoflineError",
type: "urn:proofline:sdk:mcp",
});
assert.equal(calls.length, 19);
});

test("public MCP types accept existing and targeted calls", async (t) => {
// Check consumer code against the built public declarations, including
// object literals whose extra properties JavaScript HTTP tests cannot check.
Expand All @@ -2528,7 +2604,7 @@ test("public MCP types accept existing and targeted calls", async (t) => {
await writeFile(
fixture,
`
import type { ProoflineClient, KnowledgeResult, McpTarget, RepositoryKnowledge, ReverificationRequest } from ${JSON.stringify(entry)};
import type { ProoflineClient, KnowledgeResult, McpTarget, McpToolDefinition, McpToolsPage, RepositoryKnowledge, ReverificationRequest } from ${JSON.stringify(entry)};
export async function use(client: ProoflineClient): Promise<void> {
const target: McpTarget = { organization_id: "00000000-0000-7000-8000-000000000001" };
const repository: RepositoryKnowledge = { repository: "owner/name", commit: "a".repeat(40), ...target };
Expand Down Expand Up @@ -2558,7 +2634,10 @@ export async function use(client: ProoflineClient): Promise<void> {
client.fixes.getReverification("request-id"),
client.fixes.getReverification("request-id", target),
]);
console.log(results);
const page: McpToolsPage = await client.mcp.listTools();
const tools: McpToolDefinition[] = page.tools;
if (page.nextCursor != null) await client.mcp.listTools(page.nextCursor);
console.log(results, tools);
}
`,
);
Expand Down