Skip to content
Merged
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
14 changes: 13 additions & 1 deletion src/tools/capability-registry/index-loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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?
*
Expand All @@ -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);
}

Expand Down
41 changes: 28 additions & 13 deletions src/tools/capability-registry/register.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import { Credentials, Transport, fetchTransport } from "./egress.js";
import {
CapabilityRegistry,
InvocationError,
isReadOnly,
ResponseSelection,
resolveResponses,
} from "./index-loader.js";
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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<CallToolResult> => {
Expand Down
8 changes: 6 additions & 2 deletions src/tools/capability-registry/shared-registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -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 {
Expand Down
41 changes: 30 additions & 11 deletions src/tools/testmanagement-utils/list-testcases.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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-<number>)."),
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."),
});

Expand All @@ -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);
Comment thread
SavioBS629 marked this conversation as resolved.
Resolved
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);
Expand Down
2 changes: 1 addition & 1 deletion src/tools/testmanagement.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
{
Expand Down
164 changes: 164 additions & 0 deletions tests/tools/capabilityRegistryReadOnly.test.ts
Original file line number Diff line number Diff line change
@@ -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<string, any> = {};
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"]);
});
});
});
15 changes: 15 additions & 0 deletions tests/tools/capabilitySharedRegistry.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
Loading
Loading