diff --git a/src/tools/capability-registry/index-loader.ts b/src/tools/capability-registry/index-loader.ts index afb61ab4..f003f311 100644 --- a/src/tools/capability-registry/index-loader.ts +++ b/src/tools/capability-registry/index-loader.ts @@ -85,9 +85,21 @@ export function endpointKey(method: string, path: string): string { */ export function isDisabled(capability: Capability): boolean { if (capability.disabled) return true; + if (isWriteWithheld(capability)) return true; return Boolean(capability.local_only) && Boolean(appConfig.REMOTE_MCP); } +/** CAPABILITY_REGISTRY_READ_ONLY=true withholds every capability that is not a read. */ +export function isReadOnly(): boolean { + return ( + (process.env.CAPABILITY_REGISTRY_READ_ONLY || "").toLowerCase() === "true" + ); +} + +function isWriteWithheld(capability: Capability): boolean { + return isReadOnly() && capability.mode !== "read"; +} + /** * Is this capability published for reference only on this surface? * @@ -97,7 +109,7 @@ export function isDisabled(capability: Capability): boolean { * question it was asked. */ export function isReferenceOnly(capability: Capability): boolean { - if (capability.disabled) return false; + if (capability.disabled || isWriteWithheld(capability)) return false; return Boolean(capability.local_only) && Boolean(appConfig.REMOTE_MCP); } diff --git a/src/tools/capability-registry/register.ts b/src/tools/capability-registry/register.ts index ad57bd08..a7fdb394 100644 --- a/src/tools/capability-registry/register.ts +++ b/src/tools/capability-registry/register.ts @@ -33,6 +33,7 @@ import { Credentials, Transport, fetchTransport } from "./egress.js"; import { CapabilityRegistry, InvocationError, + isReadOnly, ResponseSelection, resolveResponses, } from "./index-loader.js"; @@ -104,6 +105,11 @@ function announceLoad(registry: CapabilityRegistry): void { // WITHHELD CAPABILITIES ARE LOGGED, because they are otherwise undetectable from // outside: the flag's whole job is to make them invisible, so the count at startup is // the only place an operator can see that the surface is smaller than the artifact. + if (isReadOnly()) { + logger.info( + "capability registry is read-only (CAPABILITY_REGISTRY_READ_ONLY): writes and deletes are withheld", + ); + } const withheld = registry.disabledCounts(); if (Object.keys(withheld).length) { logger.info( @@ -1141,9 +1147,13 @@ export function addCapabilityRegistryTools( }, ); + const readOnly = isReadOnly(); tools.invokeCapability = server.tool( "invokeCapability", - "Run a capability after describeCapability, by `name` (or `method` + `path` if unnamed); args go in path_params / query / body. `select` narrows the response only where the contract carries `narrowable`. If `completed` is false, fetch the next page with the capability's own page parameter, not `offset`. Writes: ask the user first, then resend with user_permission='granted' and a change_summary. Deletes are refused; archive, close and merge are writes.", + "Run a capability after describeCapability, by `name` (or `method` + `path` if unnamed); args go in path_params / query / body. `select` narrows the response only where the contract carries `narrowable`. If `completed` is false, fetch the next page with the capability's own page parameter, not `offset`." + + (readOnly + ? " Read-only: writes and deletes are not available." + : " Writes: ask the user first, then resend with user_permission='granted' and a change_summary. Deletes are refused; archive, close and merge are writes."), { name: z .string() @@ -1178,16 +1188,20 @@ export function addCapabilityRegistryTools( product: productArg() .optional() .describe("Owning product; needed only when names or paths collide."), - user_permission: z - .enum(PERMISSION_VALUES) - .optional() - .describe( - "Set to 'granted' only after the user has confirmed a write.", - ), - change_summary: z - .string() - .optional() - .describe("What will change. Required for writes."), + ...(readOnly + ? {} + : { + user_permission: z + .enum(PERMISSION_VALUES) + .optional() + .describe( + "Set to 'granted' only after the user has confirmed a write.", + ), + change_summary: z + .string() + .optional() + .describe("What will change. Required for writes."), + }), select: z .object({ where: z @@ -1221,9 +1235,10 @@ export function addCapabilityRegistryTools( // destructive endpoints are refused before binding — the refusal is enforced here, // not merely hinted at. Not idempotent: it creates, clones and starts runs. Closed // world: it reaches BrowserStack products the index describes, nothing else. - readOnlyHint: false, + // Under CAPABILITY_REGISTRY_READ_ONLY every write is withheld at load, so it reads only. + readOnlyHint: readOnly, destructiveHint: false, - idempotentHint: false, + idempotentHint: readOnly, openWorldHint: false, }, async (input): Promise => { diff --git a/src/tools/capability-registry/shared-registry.ts b/src/tools/capability-registry/shared-registry.ts index ad213f43..5a1a6b3a 100644 --- a/src/tools/capability-registry/shared-registry.ts +++ b/src/tools/capability-registry/shared-registry.ts @@ -19,7 +19,7 @@ import { statSync } from "node:fs"; import appConfig from "../../config.js"; -import { CapabilityRegistry } from "./index-loader.js"; +import { CapabilityRegistry, isReadOnly } from "./index-loader.js"; let shared: { key: string; registry: CapabilityRegistry } | undefined; @@ -41,7 +41,11 @@ function cacheKey(files: string[]): string { return `${file}:unreadable:${Date.now()}`; } }); - return [`remote=${Boolean(appConfig.REMOTE_MCP)}`, ...parts].join("\n"); + return [ + `remote=${Boolean(appConfig.REMOTE_MCP)}`, + `readonly=${isReadOnly()}`, + ...parts, + ].join("\n"); } function deepFreeze(value: unknown): void { diff --git a/src/tools/testmanagement-utils/list-testcases.ts b/src/tools/testmanagement-utils/list-testcases.ts index e7e4a694..2140efd2 100644 --- a/src/tools/testmanagement-utils/list-testcases.ts +++ b/src/tools/testmanagement-utils/list-testcases.ts @@ -12,26 +12,40 @@ import { markCallerFault } from "../../lib/upstream-status.js"; * Schema for listing test cases with optional filters. */ export const ListTestCasesSchema = z.object({ - project_identifier: z - .string() - .describe( - "Identifier of the project to fetch test cases from. This id starts with a PR- and is followed by a number.", - ), + project_identifier: z.string().describe("Project identifier (PR-)."), folder_id: z .string() .optional() - .describe("Only this folder's cases (ids from listFolders). Omit for all."), + .describe("Only this folder's cases (ids from listFolders)."), + id: z + .string() + .optional() + .describe("Comma-separated test case ids, e.g. TC-12,TC-34."), case_type: z .string() .optional() - .describe( - "Comma-separated list of case types (e.g. functional,regression).", - ), + .describe("Comma-separated case types, e.g. functional,regression."), priority: z .string() .optional() - .describe("Comma-separated list of priorities (e.g. critical,medium,low)."), - + .describe("Comma-separated priorities, e.g. critical,low."), + review_status: z + .array( + z.enum([ + "approved", + "rejected", + "in_review", + "pending", + "changes_requested", + "l1_approved", + ]), + ) + .optional() + .describe("Review statuses."), + custom_fields: z + .record(z.string(), z.string()) + .optional() + .describe('Custom field name to value, e.g. {"Theme": "Checkout"}.'), p: z.number().optional().describe("Page number."), }); @@ -48,8 +62,13 @@ export async function listTestCases( // Build query string const params = new URLSearchParams(); if (args.folder_id) params.append("folder_id", args.folder_id); + if (args.id) params.append("id", args.id); if (args.case_type) params.append("case_type", args.case_type); if (args.priority) params.append("priority", args.priority); + if (args.review_status?.length) + params.append("review_status", args.review_status.join(",")); + for (const [field, value] of Object.entries(args.custom_fields ?? {})) + params.append(`custom_fields[${field}]`, value); if (args.p !== undefined) params.append("p", args.p.toString()); const tmBaseUrl = await getTMBaseURL(config); diff --git a/src/tools/testmanagement.ts b/src/tools/testmanagement.ts index 963ec64d..7c28e027 100644 --- a/src/tools/testmanagement.ts +++ b/src/tools/testmanagement.ts @@ -786,7 +786,7 @@ export default function addTestManagementTools( tools.listTestCases = server.tool( "listTestCases", - "List test cases in a project, optionally one folder (see listFolders). Filters: case_type, priority, paging." + + "List test cases in a project or one folder (see listFolders). Filters: id, case_type, priority, paging." + NEEDS_PROJECT_ID, ListTestCasesSchema.shape, { diff --git a/tests/tools/capabilityRegistryReadOnly.test.ts b/tests/tools/capabilityRegistryReadOnly.test.ts new file mode 100644 index 00000000..f84fefc2 --- /dev/null +++ b/tests/tools/capabilityRegistryReadOnly.test.ts @@ -0,0 +1,164 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { CapabilityRegistry } from "../../src/tools/capability-registry/index-loader.js"; +import { addCapabilityRegistryTools } from "../../src/tools/capability-registry/register.js"; +import { readAnswer } from "../../src/tools/capability-registry/answer.js"; +import { searchCapabilities } from "../../src/tools/capability-registry/search.js"; + +const index = { + schema_version: 1, + build_id: "test", + products: { + p: { + summary: "s", + base_url: "https://p.example", + capabilities: [ + { + name: "get_case", + method: "GET", + path: "/cases/{id}", + mode: "read", + entity: "case", + intent: "Get a test case.", + path_params: [{ name: "id", type: "string", required: true }], + }, + { + name: "create_case", + method: "POST", + path: "/cases/{id}", + mode: "write", + entity: "case", + intent: "Create a test case.", + path_params: [{ name: "id", type: "string", required: true }], + }, + { + name: "delete_case", + method: "DELETE", + path: "/cases/{id}", + mode: "destructive", + entity: "case", + intent: "Delete a test case.", + path_params: [{ name: "id", type: "string", required: true }], + }, + ], + entities: { + case: { + description: "A test case", + capabilities: ["get_case", "create_case", "delete_case"], + }, + }, + }, + }, +}; + +function harness(status: number) { + const sent: string[] = []; + const tools: Record = {}; + const registry = new CapabilityRegistry(index as never); + addCapabilityRegistryTools( + { + tool: (...args: any[]) => { + tools[args[0]] = { + description: args[1], + shape: args[2], + annotations: args[3], + handler: args.find((a) => typeof a === "function"), + }; + return { name: args[0] }; + }, + } as never, + { + registry, + baseUrlFor: async () => "https://p.example", + credentialsFor: () => ({ username: "u", accessKey: "k" }) as never, + transport: async (method: string, url: string) => { + sent.push(`${method} ${url}`); + return { status, body: {} } as never; + }, + } as never, + ); + const invoke = async (name: string) => + readAnswer( + await tools.invokeCapability.handler( + { + name, + product: "p", + path_params: { id: "1" }, + user_permission: "granted", + change_summary: "x", + }, + {}, + ), + ); + return { registry, tools, sent, invoke }; +} + +afterEach(() => { + vi.unstubAllEnvs(); +}); + +describe("CAPABILITY_REGISTRY_READ_ONLY", () => { + it("leaves writes available and the tool writable when unset", async () => { + const { registry, tools, sent, invoke } = harness(200); + + expect(registry.byNameLookup("create_case", "p").capability.mode).toBe( + "write", + ); + expect(tools.invokeCapability.annotations.readOnlyHint).toBe(false); + expect(tools.invokeCapability.shape).toHaveProperty("user_permission"); + + await invoke("create_case"); + expect(sent).toEqual(["POST https://p.example/cases/1"]); + }); + + describe("when true", () => { + it("marks invokeCapability read-only and drops the write fields", () => { + vi.stubEnv("CAPABILITY_REGISTRY_READ_ONLY", "true"); + const { tools } = harness(200); + + expect(tools.invokeCapability.annotations).toMatchObject({ + readOnlyHint: true, + destructiveHint: false, + }); + expect(tools.invokeCapability.shape).not.toHaveProperty( + "user_permission", + ); + expect(tools.invokeCapability.shape).not.toHaveProperty( + "change_summary", + ); + expect(tools.invokeCapability.description).not.toContain( + "user_permission", + ); + }); + + it("hides writes and deletes from search", () => { + vi.stubEnv("CAPABILITY_REGISTRY_READ_ONLY", "true"); + const { registry } = harness(200); + + const { hits } = searchCapabilities(registry.index.products, "*", { + product: "p", + }); + expect(hits.map((h) => h.capability.name)).toEqual(["get_case"]); + expect(registry.index.products.p.entities.case.capabilities).toEqual([ + "get_case", + ]); + }); + + it("refuses to invoke a write without calling the API", async () => { + vi.stubEnv("CAPABILITY_REGISTRY_READ_ONLY", "true"); + const { sent, invoke } = harness(200); + + const answer = await invoke("create_case"); + expect(answer.ok).toBe(false); + expect(sent).toEqual([]); + }); + + it("still runs reads", async () => { + vi.stubEnv("CAPABILITY_REGISTRY_READ_ONLY", "true"); + const { sent, invoke } = harness(200); + + const answer = await invoke("get_case"); + expect(answer.ok).toBe(true); + expect(sent).toEqual(["GET https://p.example/cases/1"]); + }); + }); +}); diff --git a/tests/tools/capabilitySharedRegistry.test.ts b/tests/tools/capabilitySharedRegistry.test.ts index b61d3ad9..f08c61f3 100644 --- a/tests/tools/capabilitySharedRegistry.test.ts +++ b/tests/tools/capabilitySharedRegistry.test.ts @@ -228,6 +228,21 @@ describe("sharedRegistry", () => { ).toBe(false); }); + it("reloads when read-only mode changes", async () => { + writeFileSync(file, index(THING)); + const sharedRegistry = await load(); + const before = sharedRegistry([file]); + + vi.stubEnv("CAPABILITY_REGISTRY_READ_ONLY", "true"); + try { + const after = sharedRegistry([file]); + expect(after.loaded).toBe(true); + expect(after.registry).not.toBe(before.registry); + } finally { + vi.unstubAllEnvs(); + } + }); + it("does not remember a failed load", async () => { writeFileSync(file, "{ not json"); const sharedRegistry = await load(); diff --git a/tests/tools/list-testcases.test.ts b/tests/tools/list-testcases.test.ts index de54f0e7..e3622330 100644 --- a/tests/tools/list-testcases.test.ts +++ b/tests/tools/list-testcases.test.ts @@ -182,3 +182,58 @@ describe("listTestCases — linked issues in summary", () => { expect(inside(json, note)).toBe(true); }); }); + +describe("listTestCases — id filter", () => { + beforeEach(() => { + vi.clearAllMocks(); + (apiClient.get as any).mockResolvedValue({ + data: { success: true, info: { count: 0 }, test_cases: [] }, + }); + }); + + const requestedUrl = () => + new URL((apiClient.get as any).mock.calls[0][0].url); + + it("sends the id filter to the API", async () => { + await listTestCases( + { project_identifier: "PR-1", id: "TC-61870435,TC-2" }, + mockConfig, + ); + + expect(requestedUrl().searchParams.get("id")).toBe("TC-61870435,TC-2"); + }); + + it("omits the filters when not given", async () => { + await listTestCases({ project_identifier: "PR-1" }, mockConfig); + + const params = requestedUrl().searchParams; + expect(params.has("id")).toBe(false); + expect(params.has("review_status")).toBe(false); + expect([...params.keys()]).toEqual([]); + }); + + it("sends review statuses comma-separated", async () => { + await listTestCases( + { project_identifier: "PR-1", review_status: ["approved", "in_review"] }, + mockConfig, + ); + + expect(requestedUrl().searchParams.get("review_status")).toBe( + "approved,in_review", + ); + }); + + it("sends each custom field by name", async () => { + await listTestCases( + { + project_identifier: "PR-1", + custom_fields: { Theme: "Checkout", "Release Train": "R1" }, + }, + mockConfig, + ); + + const params = requestedUrl().searchParams; + expect(params.get("custom_fields[Theme]")).toBe("Checkout"); + expect(params.get("custom_fields[Release Train]")).toBe("R1"); + }); +});