diff --git a/README.md b/README.md index b7d11dc..a75b084 100644 --- a/README.md +++ b/README.md @@ -139,6 +139,15 @@ const page = await client.knowledge.getWikiPage({ Selection applies only to that call, including concurrent calls on one client. A single-organization credential can omit it. An ambiguous omission retains the server's `ORGANIZATION_REQUIRED` tool refusal; a foreign or revoked target retains `NOT_AUTHORIZED` and `isError`. The SDK chooses no default and never retries a tool call. Discovery and targeting use MCP only; an MCP OAuth credential cannot call the REST API. Each organization's scopes and repository restrictions still apply. +To target one organization throughout, pass `organizationId` when you create the client. Every `knowledge` and `fixes` call that has no `organization_id` of its own then sends it, and a call's own `organization_id` still wins. `client.mcp.listOrganizations()` stays untargeted, and REST methods keep `org_id` in their path, so the option affects MCP tool calls only. The value must be a UUID and is sent in lowercase; anything else throws a `TypeError` before any request. The client never reads it from the environment, so pass it explicitly: + +```typescript +const client = new ProoflineClient({ + organizationId: process.env.PROOFLINE_ORGANIZATION_ID || undefined, +}); +const context = await client.fixes.getFixContext(findingId); +``` + ## Knowledge and plans `client.knowledge` provides typed MCP methods: `listWikiPages`, `getWikiPage`, `askCodebase`, `getArchitectureDocument`, `getPlan`, `startPlanImplementation`, and `getPlanImplementation`. diff --git a/src/index.ts b/src/index.ts index 0374a0e..06fb7dd 100644 --- a/src/index.ts +++ b/src/index.ts @@ -28,7 +28,12 @@ import { type UploadCoverageReportsParameters, } from "./operations.js"; import type { components } from "./schema.js"; -import { type ClientOptions, sleep, Transport } from "./transport.js"; +import { + type ClientOptions, + configuredOrganization, + sleep, + Transport, +} from "./transport.js"; export type * from "./operations.js"; export type { components, operations, paths } from "./schema.js"; @@ -85,13 +90,15 @@ export class ProoflineClient extends Operations { constructor(options: ClientOptions = {}) { const transport = new Transport(options); + const organizationId = configuredOrganization(options.organizationId); super((method, path, parameters, body) => transport.request(method, path, parameters, undefined, body), ); this.#transport = transport; + // Discovery stays untargeted so it works before a target is known. this.mcp = new McpClient(transport); - this.knowledge = new KnowledgeClient(transport); - this.fixes = new FixesClient(transport); + this.knowledge = new KnowledgeClient(transport, organizationId); + this.fixes = new FixesClient(transport, organizationId); } async exportReviews(parameters: ExportParameters): Promise { diff --git a/src/mcp.ts b/src/mcp.ts index 5fb7812..6570c2c 100644 --- a/src/mcp.ts +++ b/src/mcp.ts @@ -39,11 +39,20 @@ function envelope(value: unknown, id: number): Record { /** Typed knowledge operations over Proofline's stateless MCP endpoint. Calls never retry. */ export class McpTools { - constructor(private readonly transport: Transport) {} + constructor( + private readonly transport: Transport, + private readonly organizationId?: string, + ) {} protected async call(name: string, args: object): Promise { // Bind the per-call target before protocol negotiation yields to the caller. - const callArguments = { ...args }; + const callArguments: Record = { ...args }; + // A call's own target wins; the helpers pass an absent one as undefined. + if ( + this.organizationId !== undefined && + callArguments.organization_id === undefined + ) + callArguments.organization_id = this.organizationId; const invoke = ( body: object, phase: "initialize" | "notification" | "call", diff --git a/src/transport.ts b/src/transport.ts index 4de2f40..9606be2 100644 --- a/src/transport.ts +++ b/src/transport.ts @@ -108,6 +108,12 @@ export interface ClientOptions { baseUrl?: string; token?: string | SecretToken; requestTimeoutMs?: number; + /** + * The organization UUID that `knowledge` and `fixes` MCP tool calls target when a + * call passes no `organization_id` of its own. A call's own target always wins. + * Discovery and REST paths never use it. No environment variable sets it. + */ + organizationId?: string | undefined; } export interface Parameters { @@ -170,6 +176,18 @@ function configuredOrigin(baseUrl: string | undefined): URL { : origin(fromEnvironment, "PROOFLINE_BASE_URL"); } +const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; + +/** The client's default MCP target, validated before any request and sent lowercase. */ +export function configuredOrganization( + organizationId: string | undefined, +): string | undefined { + if (organizationId === undefined) return undefined; + if (typeof organizationId !== "string" || !UUID.test(organizationId)) + throw new TypeError("organizationId must be a UUID string"); + return organizationId.toLowerCase(); +} + function positive(value: number, name: string): number { if (!Number.isFinite(value) || value <= 0) { throw new TypeError(`${name} must be a finite positive number`); diff --git a/tests/http.test.mjs b/tests/http.test.mjs index 0a189be..4b42874 100644 --- a/tests/http.test.mjs +++ b/tests/http.test.mjs @@ -2518,6 +2518,287 @@ test("MCP helpers isolate per-call organizations and preserve refusals", async ( assert.equal(calls.length, observed.length * 3); }); +async function mcpFixture(t, admitted) { + const observed = []; + const hold = { count: 0, pending: [] }; + const fixture = await server(t, (request, response, seen) => { + assert.equal(request.url, "/mcp"); + 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" }, + }); + if (body.method === "notifications/initialized") { + response.writeHead(202); + return response.end(); + } + const { name, arguments: args } = body.params; + observed.push(body.params); + const code = + name === "list_organizations" + ? undefined + : args.organization_id === undefined + ? "ORGANIZATION_REQUIRED" + : !admitted.has(args.organization_id) + ? "NOT_AUTHORIZED" + : undefined; + const payload = code + ? { ok: false, error: { code, message: "Target refused" } } + : { ok: true, data: { organization_id: args.organization_id ?? null } }; + const reply = () => + json(response, 200, { + jsonrpc: "2.0", + id: 2, + result: { + isError: code !== undefined, + content: [{ type: "text", text: JSON.stringify(payload) }], + structuredContent: payload, + }, + }); + if (hold.count > 0) { + // Hold responses until every concurrent tool call has arrived. + hold.pending.push(reply); + if (hold.pending.length === hold.count) + for (const send of hold.pending.splice(0)) send(); + } else reply(); + }); + return { ...fixture, observed, hold }; +} + +// Every targeted MCP helper, as [tool, invoke(client, target), arguments]. +const targetedHelpers = [ + [ + "list_wiki_pages", + (client, target) => + client.knowledge.listWikiPages({ repository: "owner/name", ...target }), + { repository: "owner/name" }, + ], + [ + "get_wiki_page", + (client, target) => + client.knowledge.getWikiPage({ + repository: "owner/name", + page_key: "index", + ...target, + }), + { repository: "owner/name", page_key: "index" }, + ], + [ + "ask_codebase", + (client, target) => + client.knowledge.askCodebase({ + repository: "owner/name", + question: "How?", + ...target, + }), + { repository: "owner/name", question: "How?" }, + ], + [ + "get_architecture_document", + (client, target) => + client.knowledge.getArchitectureDocument(reviewId, target), + { environment_id: reviewId }, + ], + [ + "get_plan", + (client, target) => client.knowledge.getPlan(reviewId, target), + { plan_id: reviewId }, + ], + [ + "start_plan_implementation", + (client, target) => + client.knowledge.startPlanImplementation(reviewId, target), + { plan_id: reviewId }, + ], + [ + "get_plan_implementation", + (client, target) => + client.knowledge.getPlanImplementation(reviewId, target), + { implementation_id: reviewId }, + ], + [ + "list_open_findings", + (client, target) => client.fixes.listOpenFindings("owner/name", 7, target), + { repository: "owner/name", pull_request_number: 7 }, + ], + [ + "get_fix_context", + (client, target) => client.fixes.getFixContext(findingId, target), + { finding_id: findingId }, + ], + [ + "request_reverification", + (client, target) => + client.fixes.requestReverification({ + review_id: reviewId, + finding_ids: [findingId], + commit_sha: "a".repeat(40), + ...target, + }), + { + review_id: reviewId, + finding_ids: [findingId], + commit_sha: "a".repeat(40), + }, + ], + [ + "get_reverification", + (client, target) => client.fixes.getReverification(reviewId, target), + { request_id: reviewId }, + ], +]; + +test("a client organizationId targets MCP calls that name no organization", async (t) => { + const chosen = orgId; + const other = "00000000-0000-7000-8000-000000000006"; + const { baseUrl, calls, observed, hold } = await mcpFixture( + t, + new Set([chosen, other]), + ); + const client = new ProoflineClient({ + baseUrl, + token, + requestTimeoutMs: 5_000, + organizationId: chosen, + }); + for (const [name, invoke, args] of targetedHelpers) { + // No target, and an own-key undefined target, both use the client's. + for (const target of [undefined, { organization_id: undefined }]) { + const answer = await invoke(client, target); + assert.equal(answer.isError, false); + assert.deepEqual(observed.at(-1), { + name, + arguments: { ...args, organization_id: chosen }, + }); + } + // A call's own target wins over the client's. + const answer = await invoke(client, { organization_id: other }); + assert.equal(answer.structuredContent.data.organization_id, other); + assert.deepEqual(observed.at(-1), { + name, + arguments: { ...args, organization_id: other }, + }); + } + // Discovery stays untargeted. + await client.mcp.listOrganizations(); + assert.deepEqual(observed.at(-1), { + name: "list_organizations", + arguments: {}, + }); + // Concurrent calls keep their own targets on one configured client. + hold.count = 3; + const answers = await Promise.all([ + client.knowledge.getPlan(reviewId), + client.fixes.getFixContext(findingId, { organization_id: other }), + client.fixes.getReverification(reviewId), + ]); + hold.count = 0; + assert.deepEqual( + answers.map((answer) => answer.structuredContent.data.organization_id), + [chosen, other, chosen], + ); + // Each tool call is one initialize, notification and call, never retried. + assert.equal(calls.length, observed.length * 3); +}); + +test("a client organizationId leaves REST paths alone", async (t) => { + const pathOrg = "00000000-0000-7000-8000-000000000006"; + const { baseUrl, calls } = await server(t, (_, response) => + json(response, 200, { id: reviewId }), + ); + const client = new ProoflineClient({ baseUrl, token, organizationId: orgId }); + await client.getReview({ path: { org_id: pathOrg, review_id: reviewId } }); + assert.deepEqual( + calls.map((call) => call.url), + [`/api/v1/organizations/${pathOrg}/reviews/${reviewId}`], + ); +}); + +test("without organizationId MCP calls still send no organization", async (t) => { + const { baseUrl, observed } = await mcpFixture(t, new Set([orgId])); + for (const options of [{}, { organizationId: undefined }]) { + const client = new ProoflineClient({ baseUrl, token, ...options }); + const answer = await client.fixes.getFixContext(findingId); + assert.equal(answer.isError, true); + assert.equal(answer.structuredContent.error.code, "ORGANIZATION_REQUIRED"); + assert.equal( + Object.hasOwn(observed.at(-1).arguments, "organization_id"), + false, + ); + } +}); + +test("organizationId is never read from the environment", async (t) => { + withEnvironment(t, "PROOFLINE_ORGANIZATION_ID", orgId); + const { baseUrl, observed } = await mcpFixture(t, new Set([orgId])); + const client = new ProoflineClient({ baseUrl, token }); + const answer = await client.fixes.getFixContext(findingId); + assert.equal(answer.structuredContent.error.code, "ORGANIZATION_REQUIRED"); + assert.equal( + Object.hasOwn(observed.at(-1).arguments, "organization_id"), + false, + ); +}); + +test("a per-call null or empty organization_id is forwarded unchanged", async (t) => { + const { baseUrl, observed } = await mcpFixture(t, new Set([orgId])); + const client = new ProoflineClient({ baseUrl, token, organizationId: orgId }); + for (const organization_id of [null, ""]) { + await client.fixes.getFixContext(findingId, { organization_id }); + assert.equal(observed.at(-1).arguments.organization_id, organization_id); + } +}); + +test("a refused client organization keeps the tool refusal without retry", async (t) => { + const revoked = "00000000-0000-7000-8000-000000000007"; + const { baseUrl, calls, observed } = await mcpFixture(t, new Set([orgId])); + const client = new ProoflineClient({ + baseUrl, + token, + organizationId: revoked, + }); + const answer = await client.fixes.requestReverification({ + review_id: reviewId, + finding_ids: [findingId], + commit_sha: "a".repeat(40), + }); + assert.equal(answer.isError, true); + assert.equal(answer.structuredContent.error.code, "NOT_AUTHORIZED"); + assert.equal(observed.length, 1); + assert.equal(observed[0].arguments.organization_id, revoked); + assert.equal(calls.length, 3); +}); + +test("organizationId must be a UUID and is sent in lowercase", async (t) => { + const { baseUrl, calls, observed } = await mcpFixture(t, new Set([orgId])); + for (const organizationId of [ + "", + "not-a-uuid", + `${orgId} `, + orgId.replaceAll("-", ""), + `{${orgId}}`, + 1, + null, + ]) + assert.throws( + () => new ProoflineClient({ baseUrl, token, organizationId }), + (error) => + error instanceof TypeError && + error.message === "organizationId must be a UUID string", + ); + assert.equal(calls.length, 0); + const upper = "ABCDEF00-0000-7000-8000-00000000000A"; + const client = new ProoflineClient({ + baseUrl, + token, + organizationId: upper, + }); + await client.knowledge.getPlan(reviewId); + assert.equal(observed.at(-1).arguments.organization_id, upper.toLowerCase()); +}); + 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. @@ -2529,6 +2810,8 @@ test("public MCP types accept existing and targeted calls", async (t) => { fixture, ` import type { ProoflineClient, KnowledgeResult, McpTarget, RepositoryKnowledge, ReverificationRequest } from ${JSON.stringify(entry)}; +export const configured: ConstructorParameters[0] = { organizationId: "00000000-0000-7000-8000-000000000001" }; +export const fromEnvironment: ConstructorParameters[0] = { organizationId: process.env.PROOFLINE_ORGANIZATION_ID || undefined }; export async function use(client: ProoflineClient): Promise { const target: McpTarget = { organization_id: "00000000-0000-7000-8000-000000000001" }; const repository: RepositoryKnowledge = { repository: "owner/name", commit: "a".repeat(40), ...target };