diff --git a/packages/api/src/index.ts b/packages/api/src/index.ts index bdc5e54a6..c1badaaf1 100644 --- a/packages/api/src/index.ts +++ b/packages/api/src/index.ts @@ -14,3 +14,19 @@ export { appRouter, createCaller, createTRPCContext }; export type { AppRouter, RouterInputs, RouterOutputs }; export { recordMcpActivity } from "./utils/mcp/activity"; export type { RecordMcpActivityInput } from "./utils/mcp/activity"; + +export { buildActionCatalog, getActionCatalog } from "./utils/mcp/catalog"; +export type { ActionCatalog, McpAction } from "./utils/mcp/catalog"; +export { + callAction, + createActionGateway, + describeAction, + searchActions, +} from "./utils/mcp/gateway"; +export type { + ActionGateway, + McpActionDescription, + McpActionSummary, + McpCallOptions, + McpToolCallEvent, +} from "./utils/mcp/gateway"; diff --git a/packages/api/src/tests/mcp/catalog-coverage.test.ts b/packages/api/src/tests/mcp/catalog-coverage.test.ts new file mode 100644 index 000000000..19067a1a0 --- /dev/null +++ b/packages/api/src/tests/mcp/catalog-coverage.test.ts @@ -0,0 +1,110 @@ +import type { AnyProcedure, AnyRouter } from "@trpc/server"; +import { describe, expect, it, vi } from "vitest"; + +import type { ForgeTRPCMeta } from "../../utils/forms/callbacks"; +import { + appRouter, + callAction, + describeAction, + searchActions, +} from "../../index"; +import { buildActionCatalog } from "../../utils/mcp/catalog"; +import { createEmptyPermissionMap } from "../../utils/permissions"; + +const mocks = vi.hoisted(() => ({ + loadPermissions: vi.fn(), + report: vi.fn((input: unknown) => Promise.resolve(input)), +})); +vi.mock("../../utils/permissions-db", () => ({ + loadPermissionsForUser: mocks.loadPermissions, +})); +vi.mock("../../utils/analytics/team-performance-report", () => ({ + getTeamPerformanceReport: mocks.report, + listTeamPerformanceOptions: () => Promise.resolve(["development"]), +})); +vi.mock("@forge/db/client", () => ({ db: {} })); +vi.mock("@forge/utils/stripe", () => ({ stripe: {} })); +vi.mock("../../utils/profile-picture/storage", () => ({ + profilePictureStorageClient: {}, +})); +vi.mock("../../utils/resume/storage", () => ({ resumeStorageClient: {} })); +vi.mock("../../minio/minio-client", () => ({ minioClient: {} })); + +describe("MCP catalog router coverage", () => { + it("exports the app gateway and preserves native Date inputs for real procedures", async () => { + const permissions = createEmptyPermissionMap(); + permissions.READ_CLUB_DATA = true; + mocks.loadPermissions.mockResolvedValue(permissions); + const session = { + session: { + id: "session", + userId: "actor", + token: "fixture", + createdAt: new Date(), + updatedAt: new Date(), + expiresAt: new Date(), + }, + user: { + id: "actor", + name: "Actor", + email: "actor@example.com", + emailVerified: true, + discordUserId: "123", + createdAt: new Date(), + updatedAt: new Date(), + }, + }; + expect( + (await searchActions(session, "")).map((action) => action.path), + ).toContain("analytics.listTeamPerformanceOptions"); + await expect( + describeAction(session, "analytics.getTeamPerformanceReport"), + ).resolves.toMatchObject({ + path: "analytics.getTeamPerformanceReport", + inputSchema: { required: ["teamSlug"] }, + }); + await expect( + callAction(session, "analytics.listTeamPerformanceOptions", undefined), + ).resolves.toEqual(["development"]); + const input = { + teamSlug: "development", + period: { + kind: "custom", + from: new Date("2026-01-01T00:00:00Z"), + to: new Date("2026-01-02T00:00:00Z"), + }, + }; + await expect( + callAction(session, "analytics.getTeamPerformanceReport", input), + ).resolves.toEqual(input); + expect(mocks.report).toHaveBeenCalledExactlyOnceWith(input); + permissions.IS_OFFICER = true; + expect( + (await searchActions(session, " ")).map((action) => action.path).sort(), + ).toEqual([...buildActionCatalog(appRouter).keys()].sort()); + await expect( + callAction(session, "analytics.getTeamPerformanceReport", { + ...input, + period: { ...input.period, from: input.period.from.toISOString() }, + }), + ).rejects.toMatchObject({ code: "BAD_REQUEST" }); + }); + + it("contains every opted-in procedure, with a generated input schema", () => { + const router: AnyRouter = appRouter; + const expected = Object.entries( + router._def.procedures as Record, + ) + .filter( + ([, procedure]) => + (procedure._def.meta as ForgeTRPCMeta | undefined)?.mcp !== undefined, + ) + .map(([path]) => path) + .sort(); + expect(expected.length).toBeGreaterThan(0); + const catalog = buildActionCatalog(appRouter); + expect([...catalog.keys()].sort()).toEqual(expected); + for (const action of catalog.values()) + expect(action.inputSchema).toBeDefined(); + }); +}); diff --git a/packages/api/src/tests/mcp/catalog.test.ts b/packages/api/src/tests/mcp/catalog.test.ts new file mode 100644 index 000000000..255358779 --- /dev/null +++ b/packages/api/src/tests/mcp/catalog.test.ts @@ -0,0 +1,119 @@ +import { describe, expect, it } from "vitest"; +import { z } from "zod"; + +import { createTRPCRouter, permProcedure, publicProcedure } from "../../trpc"; +import { buildActionCatalog, getActionCatalog } from "../../utils/mcp/catalog"; + +const registration = { + access: { mode: "any", permissions: ["READ_CLUB_DATA"] }, + description: "Read a Club report.", +} as const; + +describe("MCP action catalog", () => { + it("memoizes static catalogs per router and describes zero-input actions", () => { + const router = createTRPCRouter({ + read: permProcedure.meta({ mcp: registration }).query(() => "read"), + }); + expect(getActionCatalog(router)).toBe(getActionCatalog(router)); + expect(getActionCatalog(router).get("read")?.inputSchema).toMatchObject({ + type: "object", + properties: {}, + additionalProperties: false, + }); + }); + + it.each([ + { description: " " }, + { access: { mode: "any", permissions: [] } }, + { access: { mode: "unknown", permissions: ["READ_CLUB_DATA"] } }, + { access: { mode: "any", permissions: ["NOT_A_PERMISSION"] } }, + ])("rejects invalid registration %j", (invalid) => { + const read = permProcedure + .meta({ mcp: { ...registration } }) + .query(() => "read"); + Object.assign(read._def, { + meta: { mcp: { ...registration, ...invalid } }, + }); + expect(() => buildActionCatalog(createTRPCRouter({ read }))).toThrow( + "Invalid MCP metadata for read", + ); + }); + + it("rejects subscriptions and validators that cannot produce JSON schemas", () => { + const stream = publicProcedure + .meta({ mcp: registration }) + .subscription(async function* () { + yield await Promise.resolve("event"); + }); + expect(() => buildActionCatalog(createTRPCRouter({ stream }))).toThrow( + "cannot be a subscription", + ); + for (const input of [ + z.bigint(), + z.custom(), + z.map(z.string(), z.string()), + ]) { + const read = permProcedure + .meta({ mcp: registration }) + .input(input) + .query(({ input }) => input); + expect(() => buildActionCatalog(createTRPCRouter({ read }))).toThrow( + "cannot be represented", + ); + } + const read = permProcedure + .meta({ mcp: registration }) + .input((input) => input) + .query(({ input }) => input); + expect(() => buildActionCatalog(createTRPCRouter({ read }))).toThrow( + "must use Zod", + ); + }); + + it("derives transforms from their input and marks native dates for protocol adapters", () => { + const router = createTRPCRouter({ + read: permProcedure + .meta({ mcp: registration }) + .input(z.object({ at: z.date(), count: z.string().transform(Number) })) + .query(({ input }) => input), + }); + expect(buildActionCatalog(router).get("read")?.inputSchema).toMatchObject({ + properties: { + at: { + type: "string", + format: "date-time", + "x-forge-native-type": "Date", + }, + count: { type: "string" }, + }, + }); + }); + + it("collects nested opted-in actions and derives their input schema", () => { + const router = createTRPCRouter({ + reports: createTRPCRouter({ + read: permProcedure + .meta({ mcp: registration }) + .input( + z.object({ slug: z.string().min(1), limit: z.number().default(5) }), + ) + .query(({ input }) => input), + hidden: publicProcedure.query(() => "hidden"), + }), + }); + const catalog = buildActionCatalog(router); + expect([...catalog.keys()]).toEqual(["reports.read"]); + expect(catalog.get("reports.read")).toMatchObject({ + path: "reports.read", + description: "Read a Club report.", + inputSchema: { + type: "object", + properties: { + slug: { type: "string", minLength: 1 }, + limit: { type: "number", default: 5 }, + }, + required: ["slug"], + }, + }); + }); +}); diff --git a/packages/api/src/tests/mcp/gateway.test.ts b/packages/api/src/tests/mcp/gateway.test.ts new file mode 100644 index 000000000..5d6d1038d --- /dev/null +++ b/packages/api/src/tests/mcp/gateway.test.ts @@ -0,0 +1,278 @@ +import { TRPCError } from "@trpc/server"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { z } from "zod"; + +import type { Session } from "@forge/auth/server"; +import type { PERMISSIONS } from "@forge/consts"; + +import { createTRPCRouter, permProcedure, publicProcedure } from "../../trpc"; +import { createActionGateway } from "../../utils/mcp/gateway"; +import { permissionBitstring } from "../support/permissions"; + +const mocks = vi.hoisted(() => ({ + db: { select: vi.fn() }, + rows: [] as { permissions: string }[], + audit: vi.fn(), +})); +vi.mock("@forge/db/client", () => ({ db: mocks.db })); + +const now = new Date("2026-11-13T00:00:00Z"); +const session: Session = { + session: { + id: "session", + userId: "actor", + token: "fixture-token", + expiresAt: now, + createdAt: now, + updatedAt: now, + ipAddress: null, + userAgent: null, + }, + user: { + id: "actor", + name: "Actor", + email: "actor@example.com", + emailVerified: true, + image: null, + createdAt: now, + updatedAt: now, + discordUserId: "123", + }, +}; +const club = { + access: { mode: "any", permissions: ["READ_CLUB_DATA"] }, + description: "Read Club reports.", +} as const; +const router = createTRPCRouter({ + reports: createTRPCRouter({ + club: permProcedure.meta({ mcp: club }).query(() => "club"), + hack: permProcedure + .meta({ + mcp: { + access: { mode: "any", permissions: ["READ_HACK_DATA"] }, + description: "Read hackathon reports.", + }, + }) + .query(() => "hack"), + owned: permProcedure + .meta({ + mcp: { + ...club, + description: "Read one owned resource with Club reports.", + }, + }) + .input(z.object({ ownerId: z.string().min(1) })) + .mutation(({ ctx, input }) => { + if (ctx.session.user.id !== input.ownerId) + throw new TRPCError({ + code: "FORBIDDEN", + message: "Not your resource", + }); + mocks.audit({ actor: ctx.session.user.id, source: ctx.source }); + return input.ownerId; + }), + hidden: publicProcedure.query(() => "hidden"), + }), +}); +const gateway = createActionGateway(router); +function grant(...keys: PERMISSIONS.PermissionKey[]) { + mocks.rows = [{ permissions: permissionBitstring(...keys) }]; +} + +beforeEach(() => { + vi.clearAllMocks(); + grant(); + mocks.db.select.mockImplementation(() => ({ + from: () => ({ + innerJoin: () => ({ where: () => Promise.resolve(mocks.rows) }), + }), + })); +}); + +describe("MCP action gateway", () => { + it("rejects anonymous sessions before reading permissions", async () => { + await expect(gateway.searchActions(null, "")).rejects.toMatchObject({ + code: "UNAUTHORIZED", + }); + await expect( + gateway.describeAction(null, "reports.club"), + ).rejects.toMatchObject({ code: "UNAUTHORIZED" }); + const onToolCall = vi.fn(); + await expect( + gateway.callAction(null, "reports.club", {}, { onToolCall }), + ).rejects.toMatchObject({ code: "UNAUTHORIZED" }); + expect(mocks.db.select).not.toHaveBeenCalled(); + expect(onToolCall).toHaveBeenCalledExactlyOnceWith({ + actorUserId: null, + path: "reports.club", + outcome: "denied", + errorCode: "UNAUTHORIZED", + }); + }); + + it("enforces metadata even if the opted-in procedure is public", async () => { + const resolve = vi.fn(() => "public"); + const alternate = createActionGateway( + createTRPCRouter({ + read: publicProcedure.meta({ mcp: club }).query(resolve), + }), + ); + await expect( + alternate.callAction(session, "read", {}), + ).rejects.toMatchObject({ code: "FORBIDDEN" }); + expect(resolve).not.toHaveBeenCalled(); + }); + + it("preserves procedure errors if the activity hook fails", async () => { + grant("READ_CLUB_DATA"); + const failure = new Error("Activity writer unavailable"); + const onToolCall = vi.fn(() => Promise.reject(failure)); + await expect( + gateway.callAction( + session, + "reports.owned", + { ownerId: "other" }, + { onToolCall }, + ), + ).rejects.toMatchObject({ code: "FORBIDDEN" }); + await expect( + gateway.callAction(session, "reports.club", {}, { onToolCall }), + ).rejects.toBe(failure); + expect(onToolCall).toHaveBeenCalledTimes(2); + }); + + it("reads permission changes on the very next search, describe and call", async () => { + grant("READ_CLUB_DATA"); + await expect(gateway.callAction(session, "reports.club", {})).resolves.toBe( + "club", + ); + grant(); + await expect( + gateway.callAction(session, "reports.club", {}), + ).rejects.toMatchObject({ code: "FORBIDDEN" }); + await expect(gateway.searchActions(session, "")).resolves.toEqual([]); + await expect( + gateway.describeAction(session, "reports.club"), + ).rejects.toMatchObject({ code: "FORBIDDEN" }); + grant("READ_CLUB_DATA"); + await expect(gateway.callAction(session, "reports.club", {})).resolves.toBe( + "club", + ); + }); + + it("reports allowed, denied and failed calls once without inputs or results", async () => { + const onToolCall = vi.fn(); + grant("READ_CLUB_DATA"); + await gateway.callAction( + session, + "reports.owned", + { ownerId: "actor" }, + { onToolCall }, + ); + await expect( + gateway.callAction( + session, + "reports.owned", + { ownerId: "other" }, + { onToolCall }, + ), + ).rejects.toMatchObject({ code: "FORBIDDEN" }); + await expect( + gateway.callAction( + session, + "reports.owned", + { ownerId: "" }, + { onToolCall }, + ), + ).rejects.toMatchObject({ code: "BAD_REQUEST" }); + expect(onToolCall.mock.calls).toEqual([ + [ + { + actorUserId: "actor", + path: "reports.owned", + outcome: "allowed", + errorCode: null, + }, + ], + [ + { + actorUserId: "actor", + path: "reports.owned", + outcome: "denied", + errorCode: "FORBIDDEN", + }, + ], + [ + { + actorUserId: "actor", + path: "reports.owned", + outcome: "failed", + errorCode: "BAD_REQUEST", + }, + ], + ]); + }); + it("runs the real validation, resource check and audit on calls", async () => { + grant("READ_CLUB_DATA"); + await expect( + gateway.callAction(session, "reports.owned", { ownerId: "other" }), + ).rejects.toMatchObject({ + code: "FORBIDDEN", + message: "Not your resource", + }); + await expect( + gateway.callAction(session, "reports.owned", { ownerId: "" }), + ).rejects.toMatchObject({ code: "BAD_REQUEST" }); + expect(mocks.audit).not.toHaveBeenCalled(); + await expect( + gateway.callAction(session, "reports.owned", { + ownerId: session.user.id, + }), + ).resolves.toBe("actor"); + expect(mocks.audit).toHaveBeenCalledExactlyOnceWith({ + actor: "actor", + source: "mcp", + }); + await expect( + gateway.callAction(session, "reports.hidden", {}), + ).rejects.toMatchObject({ code: "NOT_FOUND" }); + }); + it("describes allowed actions and distinguishes forbidden from absent paths", async () => { + grant("READ_CLUB_DATA"); + await expect( + gateway.describeAction(session, "reports.owned"), + ).resolves.toMatchObject({ + path: "reports.owned", + description: "Read one owned resource with Club reports.", + inputSchema: { type: "object", required: ["ownerId"] }, + }); + await expect( + gateway.describeAction(session, "reports.hack"), + ).rejects.toMatchObject({ code: "FORBIDDEN" }); + await expect( + gateway.describeAction(session, "reports.hidden"), + ).rejects.toMatchObject({ code: "NOT_FOUND" }); + await expect( + gateway.describeAction(session, "missing"), + ).rejects.toMatchObject({ code: "NOT_FOUND" }); + }); + it("lists all allowed actions for an empty query and filters and ranks text matches", async () => { + grant("READ_CLUB_DATA"); + expect( + (await gateway.searchActions(session, "")).map((action) => action.path), + ).toEqual(["reports.club", "reports.owned"]); + expect( + (await gateway.searchActions(session, "CLUB")).map( + (action) => action.path, + ), + ).toEqual(["reports.club", "reports.owned"]); + expect( + (await gateway.searchActions(session, "club resource")).map( + (action) => action.path, + ), + ).toEqual(["reports.owned"]); + expect(await gateway.searchActions(session, "hackathon")).toEqual([]); + grant("IS_OFFICER"); + expect(await gateway.searchActions(session, "")).toHaveLength(3); + }); +}); diff --git a/packages/api/src/utils/mcp/catalog.ts b/packages/api/src/utils/mcp/catalog.ts new file mode 100644 index 000000000..c161bc78e --- /dev/null +++ b/packages/api/src/utils/mcp/catalog.ts @@ -0,0 +1,102 @@ +import type { AnyProcedure, AnyRouter } from "@trpc/server"; +import { z } from "zod"; + +import { PERMISSIONS } from "@forge/consts"; + +import type { ForgeTRPCMeta } from "../forms/callbacks"; +import type { McpAccessRule } from "./access"; + +export interface McpAction { + access: McpAccessRule; + description: string; + inputSchema: z.core.JSONSchema.JSONSchema; + path: string; +} + +export type ActionCatalog = ReadonlyMap; + +const registrationSchema = z + .object({ + access: z + .object({ + mode: z.enum(["any", "all"]), + permissions: z + .tuple([z.enum(PERMISSIONS.PERMISSION_KEYS)]) + .rest(z.enum(PERMISSIONS.PERMISSION_KEYS)), + }) + .strict(), + description: z.string().trim().min(1), + }) + .strict(); + +/** Derive action definitions from the same flattened procedure record tRPC calls. */ +export function buildActionCatalog(router: AnyRouter): ActionCatalog { + const catalog = new Map(); + const procedures = router._def.procedures as Record; + for (const [path, procedure] of Object.entries(procedures)) { + const meta = procedure._def.meta as ForgeTRPCMeta | undefined; + if (meta?.mcp === undefined) continue; + const parsed = registrationSchema.safeParse(meta.mcp); + if (!parsed.success) + throw new Error( + `Invalid MCP metadata for ${path}: ${parsed.error.message}`, + ); + if (procedure._def.type === "subscription") + throw new Error(`MCP action ${path} cannot be a subscription.`); + if (catalog.has(path)) throw new Error(`Duplicate MCP action: ${path}`); + const inputs = procedure._def.inputs; + const schemas = inputs.map((input) => { + if (!(input instanceof z.ZodType)) + throw new Error(`MCP action ${path} must use Zod input validators.`); + return z.toJSONSchema(input, { + io: "input", + unrepresentable: "any", + override: ({ zodSchema, jsonSchema }) => { + const type = zodSchema._zod.def.type; + if (type === "date") { + // JSON transports encode Dates as ISO strings. The plain gateway + // preserves native tRPC inputs; #641 must revive these Date fields. + jsonSchema.type = "string"; + jsonSchema.format = "date-time"; + jsonSchema["x-forge-native-type"] = "Date"; + } else if ( + [ + "bigint", + "symbol", + "undefined", + "void", + "nan", + "custom", + "function", + "transform", + "map", + "set", + "literal", + ].includes(type) + ) { + // Retain Zod's fail-closed behavior for every other unsupported + // type (including non-JSON literals), rather than silently using {}. + z.toJSONSchema(zodSchema, { io: "input" }); + } + }, + }); + }); + const inputSchema = + schemas.length > 1 + ? { allOf: schemas } + : (schemas[0] ?? z.toJSONSchema(z.object({}).strict())); + catalog.set(path, { ...parsed.data, path, inputSchema }); + } + return catalog; +} + +const catalogs = new WeakMap(); + +/** Cache only static definitions, never sessions or permissions. */ +export function getActionCatalog(router: AnyRouter): ActionCatalog { + const cached = catalogs.get(router); + if (cached) return cached; + const catalog = buildActionCatalog(router); + catalogs.set(router, catalog); + return catalog; +} diff --git a/packages/api/src/utils/mcp/gateway.ts b/packages/api/src/utils/mcp/gateway.ts new file mode 100644 index 000000000..1a6222eb0 --- /dev/null +++ b/packages/api/src/utils/mcp/gateway.ts @@ -0,0 +1,173 @@ +import type { AnyRouter, TRPC_ERROR_CODE_KEY } from "@trpc/server"; +import { getTRPCErrorFromUnknown, TRPCError } from "@trpc/server"; + +import type { Session } from "@forge/auth/server"; + +import type { McpAction } from "./catalog"; +import { createTRPCContext } from "../../trpc"; +import { loadPermissionsForUser } from "../permissions-db"; +import { assertAccess, evaluateAccess } from "./access"; +import { getActionCatalog } from "./catalog"; + +/** Safe activity-writer seam: never includes input, results, session or tokens. */ +export interface McpToolCallEvent { + actorUserId: string | null; + errorCode: TRPC_ERROR_CODE_KEY | null; + outcome: "allowed" | "denied" | "failed"; + path: string; +} + +export interface McpCallOptions { + onToolCall?: (event: McpToolCallEvent) => void | Promise; +} + +export type McpActionSummary = Pick; +export type McpActionDescription = Pick< + McpAction, + "description" | "inputSchema" | "path" +>; + +export interface ActionGateway { + callAction( + session: Session | null, + path: string, + input: unknown, + options?: McpCallOptions, + ): Promise; + describeAction( + session: Session | null, + path: string, + ): Promise; + searchActions( + session: Session | null, + query: string, + ): Promise; +} + +/** Create a gateway for a normal Forge router; only static metadata is cached. */ +export function createActionGateway(router: AnyRouter): ActionGateway { + const catalog = getActionCatalog(router); + return { + /** Run native tRPC input, including Date values, through the server caller. */ + async callAction( + session: Session | null, + path: string, + input: unknown, + options: McpCallOptions = {}, + ) { + let result: unknown; + let error: TRPCError | undefined; + try { + if (!session?.user) throw new TRPCError({ code: "UNAUTHORIZED" }); + const permissions = await loadPermissionsForUser(session.user.id); + const action = catalog.get(path); + if (!action) throw new TRPCError({ code: "NOT_FOUND" }); + assertAccess(action.access, permissions); + const caller = router.createCaller( + createTRPCContext({ + session, + headers: new Headers({ "x-trpc-source": "mcp" }), + }), + ); + const call = caller[path]; + if (typeof call !== "function") + throw new TRPCError({ code: "NOT_FOUND" }); + result = await call(input); + } catch (cause) { + error = getTRPCErrorFromUnknown(cause); + } + try { + await options.onToolCall?.({ + actorUserId: session?.user.id ?? null, + errorCode: error?.code ?? null, + outcome: !error + ? "allowed" + : ["FORBIDDEN", "UNAUTHORIZED", "NOT_FOUND"].includes(error.code) + ? "denied" + : "failed", + path, + }); + } catch (cause) { + // A writer failure must not replace an existing procedure error. On + // success it propagates; the procedure may already have committed. + if (!error) throw cause; + } + if (error) throw error; + return result; + }, + /** Known but disallowed actions return FORBIDDEN, matching normal tRPC. */ + async describeAction(session: Session | null, path: string) { + if (!session?.user) throw new TRPCError({ code: "UNAUTHORIZED" }); + const permissions = await loadPermissionsForUser(session.user.id); + const action = catalog.get(path); + if (!action) throw new TRPCError({ code: "NOT_FOUND" }); + assertAccess(action.access, permissions); + return { + path: action.path, + description: action.description, + inputSchema: action.inputSchema, + }; + }, + async searchActions(session: Session | null, query: string) { + if (!session?.user) throw new TRPCError({ code: "UNAUTHORIZED" }); + const permissions = await loadPermissionsForUser(session.user.id); + const terms = query.trim().toLowerCase().split(/\s+/).filter(Boolean); + return [...catalog.values()] + .filter((action) => evaluateAccess(action.access, permissions)) + .map((action) => { + const path = action.path.toLowerCase(); + const description = action.description.toLowerCase(); + const matches = terms.map((term) => + path.includes(term) ? 2 : description.includes(term) ? 1 : 0, + ); + return { + action, + matches, + score: matches.reduce((sum, score) => sum + score, 0), + }; + }) + .filter(({ matches }) => matches.every((score) => score > 0)) + .sort( + (a, b) => + b.score - a.score || a.action.path.localeCompare(b.action.path), + ) + .map(({ action }) => ({ + path: action.path, + description: action.description, + })); + }, + }; +} + +let defaultGateway: Promise | undefined; +function getDefaultGateway() { + defaultGateway ??= import("../../root").then(({ appRouter }) => + createActionGateway(appRouter), + ); + return defaultGateway; +} + +/** Empty/whitespace query returns every action the current permissions allow. */ +export async function searchActions( + session: Session | null, + query: string, +): Promise { + return (await getDefaultGateway()).searchActions(session, query); +} + +export async function describeAction( + session: Session | null, + path: string, +): Promise { + return (await getDefaultGateway()).describeAction(session, path); +} + +/** Protocol adapters must supply validated sessions and native tRPC input. */ +export async function callAction( + session: Session | null, + path: string, + input: unknown, + options?: McpCallOptions, +) { + return (await getDefaultGateway()).callAction(session, path, input, options); +}