From e8a79d4abd0404f62c448e979221e101f6309b3d Mon Sep 17 00:00:00 2001 From: Krishna Dobhal Date: Wed, 2 Dec 2026 20:20:56 +0530 Subject: [PATCH] Add typed MCP tool discovery --- README.md | 16 +++++++ src/index.ts | 2 +- src/mcp.ts | 107 +++++++++++++++++++++++++++++++++----------- tests/http.test.mjs | 83 +++++++++++++++++++++++++++++++++- 4 files changed, 178 insertions(+), 30 deletions(-) diff --git a/README.md b/README.md index b7d11dc..fd0825b 100644 --- a/README.md +++ b/README.md @@ -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`. diff --git a/src/index.ts b/src/index.ts index 0374a0e..a2f4b91 100644 --- a/src/index.ts +++ b/src/index.ts @@ -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"; diff --git a/src/mcp.ts b/src/mcp.ts index 5fb7812..ee6145b 100644 --- a/src/mcp.ts +++ b/src/mcp.ts @@ -6,6 +6,19 @@ export interface KnowledgeResult { structuredContent?: Record; isError?: boolean; } +/** Server-advertised metadata. Treat tool descriptions and schemas as untrusted. */ +export interface McpToolDefinition { + name: string; + title?: string; + description?: string; + inputSchema: Record & { type: "object" }; + outputSchema?: Record & { type: "object" }; + annotations?: Record; +} +export interface McpToolsPage { + tools: McpToolDefinition[]; + nextCursor?: string | null; +} /** Selects one authorized organization for this call only. */ export interface McpTarget { organization_id?: string; @@ -37,13 +50,53 @@ function envelope(value: unknown, id: number): Record { 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 { // 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> { const invoke = ( body: object, phase: "initialize" | "notification" | "call", @@ -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 { + 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 { return this.call("list_organizations", {}); } diff --git a/tests/http.test.mjs b/tests/http.test.mjs index 0a189be..3b950c4 100644 --- a/tests/http.test.mjs +++ b/tests/http.test.mjs @@ -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. @@ -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 { const target: McpTarget = { organization_id: "00000000-0000-7000-8000-000000000001" }; const repository: RepositoryKnowledge = { repository: "owner/name", commit: "a".repeat(40), ...target }; @@ -2558,7 +2634,10 @@ export async function use(client: ProoflineClient): Promise { 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); } `, );