diff --git a/pkgs/mcpx/plugin/opencode/v2/index.ts b/pkgs/mcpx/plugin/opencode/v2/index.ts index 3e10da218e..47aa85de9c 100644 --- a/pkgs/mcpx/plugin/opencode/v2/index.ts +++ b/pkgs/mcpx/plugin/opencode/v2/index.ts @@ -4,13 +4,18 @@ * Setup wires the whole core: the remembered-daemon read (ctx.storage), * the idempotent system-prompt paragraph (session context hook), the * once-per-session full-environment send, execute.after timing records, - * and tool registration (tools.ts: tool.transform under the mcpx + * the permission gate (permission.ts: evaluate hook + daemon_select + * assert), and tool registration (tools.ts: tool.transform under the mcpx * namespace, so the model sees the v1 names — mcpx_exec and friends). * The v1 tree stays beside this one, untouched, until v2 is what runs. */ import { targetKey, type Target } from "../mcpx/daemon.ts"; import { appendContextOnce, type ContextHookInput } from "./context.ts"; import { resolveOptions, type Options } from "./options.ts"; +import { + wirePermissionGate, + type PermissionDomainLike, +} from "./permission.ts"; import { readRememberedDaemon, type StorageLike } from "./remember.ts"; import { createSessionEnv } from "./session-env.ts"; import { @@ -37,6 +42,14 @@ export type McpxV2Context = { tool: ToolDomainLike & { hook(name: "execute.after", fn: (input: ExecuteAfterInput) => void): void; }; + /** + * The v2 permission domain (permission.ts): setup registers the + * evaluate hook and wires assert into daemon_select. Optional in the + * type because stub hosts omit it; a host without it — or whose + * evaluate-hook registration fails — gets a daemon_select that + * refuses to apply unconfirmed choices. + */ + permission?: PermissionDomainLike; }; export async function setupMcpxV2(ctx: McpxV2Context, rawOptions?: Options): Promise { @@ -130,12 +143,22 @@ export async function setupMcpxV2(ctx: McpxV2Context, rawOptions?: Options): Pro // during load loses the session bridge and the environment send too, // which are worth more than the tool surface. Registration does its // own boot discovery for the daemon-tools default (tools.ts). + // The permission gate (#1858 item (2)): the evaluate hook keeps + // mcpx's confirmation action at "ask", and daemon_select asserts + // through the same domain before applying a choice. Registration is + // awaited and fail-closed (wirePermissionGate in permission.ts): + // the assert callback exists only once the hook is registered, so + // a failed registration leaves daemon_select refusing, never + // silently applying. + const assertPermission = await wirePermissionGate(ctx.permission); + runtime = createToolRuntime({ directory, env: process.env, options, storage: ctx.storage, onTarget: noteTarget, + assertPermission, }); await registerTools(ctx.tool, runtime, { toolsEnabled: options.tools ?? false, diff --git a/pkgs/mcpx/plugin/opencode/v2/permission.test.ts b/pkgs/mcpx/plugin/opencode/v2/permission.test.ts new file mode 100644 index 0000000000..397a15733c --- /dev/null +++ b/pkgs/mcpx/plugin/opencode/v2/permission.test.ts @@ -0,0 +1,84 @@ +/** + * The v2 permission gate's evaluate hook (#1858 SET-REMAINDER item (2)). + * + * bun test plugin/opencode/v2/permission.test.ts + */ +import { describe, expect, test } from "bun:test"; +import { + DAEMON_SELECT_ACTION, + evaluateMcpxPermission, + wirePermissionGate, + type PermissionAssertInput, + type PermissionDomainLike, + type PermissionEvaluationLike, +} from "./permission.ts"; + +const event = ( + over: Partial = {}, +): PermissionEvaluationLike => ({ + sessionID: "s1", + action: DAEMON_SELECT_ACTION, + resources: ["unix:///tmp/m.sock"], + effect: "allow", + ...over, +}); + +describe("evaluateMcpxPermission", () => { + test("daemon_select always asks, even under a blanket allow rule", () => { + const ev = event(); + evaluateMcpxPermission(ev); + expect(ev.effect).toBe("ask"); + }); + + test("a computed deny is left alone", () => { + const ev = event({ effect: "deny" }); + evaluateMcpxPermission(ev); + expect(ev.effect).toBe("deny"); + }); + + test("other actions pass through unchanged", () => { + const ev = event({ action: "bash", effect: "allow" }); + evaluateMcpxPermission(ev); + expect(ev.effect).toBe("allow"); + }); +}); + +describe("wirePermissionGate (fail-closed wiring)", () => { + const fakeDomain = ( + over: Partial = {}, + ): PermissionDomainLike & { hooks: string[]; asserted: PermissionAssertInput[] } => { + const hooks: string[] = []; + const asserted: PermissionAssertInput[] = []; + const base: PermissionDomainLike = { + hook: async (name) => void hooks.push(name), + assert: async (input) => void asserted.push(input), + }; + return { ...base, ...over, hooks, asserted }; + }; + + test("successful registration hands out an assert that forwards", async () => { + const d = fakeDomain(); + const assert = await wirePermissionGate(d); + expect(d.hooks).toEqual(["evaluate"]); + expect(assert).toBeDefined(); + await assert!({ + sessionID: "s1", + action: DAEMON_SELECT_ACTION, + resources: ["unix:///tmp/m.sock"], + }); + expect(d.asserted.length).toBe(1); + }); + + test("a rejected registration wires nothing — daemon_select stays refused", async () => { + const d = fakeDomain({ + hook: async () => { + throw new Error("host refused the hook"); + }, + }); + expect(await wirePermissionGate(d)).toBeUndefined(); + }); + + test("no permission domain wires nothing", async () => { + expect(await wirePermissionGate(undefined)).toBeUndefined(); + }); +}); diff --git a/pkgs/mcpx/plugin/opencode/v2/permission.ts b/pkgs/mcpx/plugin/opencode/v2/permission.ts new file mode 100644 index 0000000000..70ff87bfe9 --- /dev/null +++ b/pkgs/mcpx/plugin/opencode/v2/permission.ts @@ -0,0 +1,91 @@ +/** + * The v2 permission gate for mcpx's own actions (#1858 SET-REMAINDER + * item (2), implemented under #2841). + * + * v1's daemon_select confirmed through ctx.ask — the only interactive + * channel a v1 server plugin had. The v2 replacement is the permission + * domain (verified against the pinned source, + * packages/plugin/src/promise/permission.ts): + * + * - `permission.assert(input)` evaluates the session's rules for an + * action and, when approval is required, prompts the user and waits. + * It resolves when allowed; a deny rule or a rejection rejects. + * - `permission.hook("evaluate", fn)` receives every evaluation with + * the rule-computed effect already set, and may override it — the + * host's own config policy plugin uses it exactly this way + * (packages/core/src/config/plugin/policy.ts). + * + * mcpx's policy is narrow: its one user-confirmation action, + * `mcpx_daemon_select`, always evaluates to "ask", so a blanket allow + * rule can never make daemon_select apply a choice silently — the + * failure mode the v2 core shipped with. A deny the host computed is + * left alone (the core short-circuits denies before hooks run, but the + * handler does not rely on that), and every other action is untouched. + * The assertion itself carries `save: [target]` as v1's ask carried + * `always: [target]`, so the host can record the user's answer. + */ + +/** The permission action daemon_select asserts, as v1 named it. */ +export const DAEMON_SELECT_ACTION = "mcpx_daemon_select"; + +/** The slice of the pinned PermissionEvaluation this gate uses. */ +export type PermissionEvaluationLike = { + sessionID: string; + action: string; + resources: ReadonlyArray; + effect: "allow" | "deny" | "ask"; + message?: string; +}; + +/** The assert payload, in the pinned AssertInput shape. */ +export type PermissionAssertInput = { + sessionID: string; + action: string; + resources: string[]; + save?: string[]; + metadata?: Record; +}; + +/** The slice of the v2 permission domain this plugin uses. */ +export type PermissionDomainLike = { + hook( + name: "evaluate", + fn: (input: PermissionEvaluationLike) => void, + ): Promise; + assert(input: PermissionAssertInput): Promise; +}; + +/** + * The evaluate hook: mcpx's own confirmation action always asks. + * Anything else — other actions, a computed deny — passes through + * unchanged. + */ +export function evaluateMcpxPermission(event: PermissionEvaluationLike): void { + if (event.action !== DAEMON_SELECT_ACTION) return; + if (event.effect === "deny") return; + event.effect = "ask"; +} + +/** + * Wire the gate into a host's permission domain, fail-closed. + * + * The assert callback daemon_select confirms through is handed out ONLY + * after the evaluate hook has registered successfully. Registration is + * awaited, never fire-and-forget: if it rejects, the gate is not wired + * (undefined) and daemon_select refuses the choice instead of applying + * it (tools.ts) — a host whose blanket allow rule would otherwise let + * `permission.assert` resolve silently, without the prompt this hook + * exists to force. A host with no permission domain gets the same + * refusal. + */ +export async function wirePermissionGate( + domain: PermissionDomainLike | undefined, +): Promise<((input: PermissionAssertInput) => Promise) | undefined> { + if (!domain) return undefined; + try { + await domain.hook("evaluate", evaluateMcpxPermission); + } catch { + return undefined; + } + return (input) => domain.assert(input); +} diff --git a/pkgs/mcpx/plugin/opencode/v2/tools.test.ts b/pkgs/mcpx/plugin/opencode/v2/tools.test.ts index 5c0957ecbf..4df7288e59 100644 --- a/pkgs/mcpx/plugin/opencode/v2/tools.test.ts +++ b/pkgs/mcpx/plugin/opencode/v2/tools.test.ts @@ -94,6 +94,7 @@ const runtime = (over: Record = {}) => discoverFn: async () => discoveryWith([candidate(socketTarget)]), runBinFn: async () => "from the binary", clientFor: () => fakeClient(), + assertPermission: async () => {}, ...over, } as never); @@ -336,3 +337,69 @@ describe("tool executors", () => { expect(storage.map.get("daemon:/work")).toBeDefined(); }); }); + +describe("daemon_select permission gate (#1858 item (2))", () => { + test("asserts mcpx_daemon_select with the v1 ask payload before applying", async () => { + const asserted: unknown[] = []; + const rt = runtime({ + assertPermission: async (input: never) => void asserted.push(input), + }); + const select = rt.daemonTools().find((t) => t.name === "daemon_select")!; + const out = await select.execute({ candidate: 0 } as never, { sessionID: "s1" }); + expect(out.content).toContain("Now using"); + expect(asserted).toEqual([ + expect.objectContaining({ + sessionID: "s1", + action: "mcpx_daemon_select", + resources: ["unix:///tmp/m.sock"], + save: ["unix:///tmp/m.sock"], + metadata: expect.objectContaining({ + socket: "unix:///tmp/m.sock", + remember: "session", + stopOthers: false, + }), + }), + ]); + }); + + test("a rejected assert applies nothing", async () => { + const targets: Target[] = []; + const rt = runtime({ + onTarget: (t: Target) => void targets.push(t), + assertPermission: async () => { + throw new Error("user rejected"); + }, + }); + const select = rt.daemonTools().find((t) => t.name === "daemon_select")!; + await expect( + select.execute({ candidate: 0 } as never, { sessionID: "s1" }), + ).rejects.toThrow("user rejected"); + expect(targets).toEqual([]); + }); + + test("with no permission gate wired, the choice is refused, not silently applied", async () => { + const rt = runtime({ assertPermission: undefined }); + const select = rt.daemonTools().find((t) => t.name === "daemon_select")!; + const out = await select.execute({ candidate: 0 } as never, { sessionID: "s1" }); + expect(out.content).toContain("no permission prompt"); + expect(out.content).not.toContain("Now using"); + }); +}); + +describe("setup: permission gate registration (#1858 item (2))", () => { + test("setup registers the evaluate hook on the permission domain", async () => { + const hooks: string[] = []; + const ctx: McpxV2Context = { + storage: stubStorage(), + directory: "/work", + session: { hook: () => {} }, + tool: { hook: () => {}, transform: async () => ({}) }, + permission: { + hook: async (name: string) => void hooks.push(name), + assert: async () => {}, + } as never, + }; + await setupMcpxV2(ctx, { tools: false, daemonTools: false }); + expect(hooks).toEqual(["evaluate"]); + }); +}); diff --git a/pkgs/mcpx/plugin/opencode/v2/tools.ts b/pkgs/mcpx/plugin/opencode/v2/tools.ts index 823c64e83a..47a44b2ea4 100644 --- a/pkgs/mcpx/plugin/opencode/v2/tools.ts +++ b/pkgs/mcpx/plugin/opencode/v2/tools.ts @@ -21,11 +21,12 @@ * * What differs from v1, honestly: * - * - No ctx.ask. v1's daemon_select confirmed through the tool context's - * permission prompt; the v2 ToolContext has no ask, and the permission - * domain (permission.hook("evaluate")) is SET-REMAINDER work on #1858, - * not this core. So v2 daemon_select applies the choice it was told to - * apply. Its description no longer claims a confirmation happens. + * - daemon_select confirms through the v2 permission domain + * (permission.ts, #1858 SET-REMAINDER item (2)): the tool asserts + * `mcpx_daemon_select` before applying, the evaluate hook keeps that + * action at "ask", and a rejection applies nothing. With no + * permission domain wired there is no channel to confirm through, + * and the tool says so instead of applying silently. * - No toasts. The v2 server context slice this tree uses has no TUI * channel; ambiguity is surfaced the other v1 way — the annotation line * on tool results — which needs no interface at all. @@ -51,6 +52,10 @@ import { type Target, } from "../mcpx/daemon.ts"; import type { Options } from "./options.ts"; +import { + DAEMON_SELECT_ACTION, + type PermissionAssertInput, +} from "./permission.ts"; import { forgetDaemon, readRememberedDaemon, @@ -119,6 +124,13 @@ export type ToolRuntimeDeps = { * hook for exactly this reason. */ onTarget?: (target: Target) => void; + /** + * The permission gate daemon_select asserts through before applying + * a choice (permission.ts). Wired from ctx.permission.assert in + * index.ts; absent means this host offers no permission domain, and + * daemon_select refuses rather than applying a choice unconfirmed. + */ + assertPermission?: (input: PermissionAssertInput) => Promise; }; export type ToolRuntime = { @@ -367,7 +379,8 @@ export function createToolRuntime(deps: ToolRuntimeDeps): ToolRuntime { name: "daemon_select", description: "Point this session at one of the daemons mcpx_daemon_status listed, by its " + - "index. The tool sets the socket itself — pass the index, never a path.", + "index. The user is asked to confirm, and the tool sets the socket itself — " + + "pass the index, never a path.", input: { type: "object", properties: { @@ -392,7 +405,10 @@ export function createToolRuntime(deps: ToolRuntimeDeps): ToolRuntime { additionalProperties: false, }, options: { namespace: NAMESPACE }, - execute: async (input: { candidate: number; remember?: string; stopOthers?: boolean }) => { + execute: async ( + input: { candidate: number; remember?: string; stopOthers?: boolean }, + context: { sessionID: string }, + ) => { const record = await readRememberedDaemon(deps.storage, deps.directory).catch( () => undefined, ); @@ -411,6 +427,37 @@ export function createToolRuntime(deps: ToolRuntimeDeps): ToolRuntime { const scope = (input.remember ?? options.remember ?? "session") as "session" | "until-gone" | "indefinite" | "permanent"; + // The user confirms, and sees what they are confirming — v1's + // ctx.ask, carried to the v2 permission domain (permission.ts). + // A rejection (or a deny rule) throws out of assert, so nothing + // is applied and the tool call fails with the reason. + if (!deps.assertPermission) { + return result( + "This host offers no permission prompt, so the choice was not applied. " + + "Start the session where mcpx_daemon_select can ask, or set the daemon " + + "endpoint in the mcpx config directly.", + ); + } + await deps.assertPermission({ + sessionID: context.sessionID, + action: DAEMON_SELECT_ACTION, + resources: [targetKey(pick.target)], + save: [targetKey(pick.target)], + metadata: { + daemon: label(pick), + socket: targetKey(pick.target), + config: pick.configPath, + started: pick.startedAt, + version: pick.version, + servers: pick.servers, + sessions: pick.sessions, + remember: scope, + stopOthers: input.stopOthers === true, + others: list + .filter((c) => c !== pick) + .map((c) => targetKey(c.target)), + }, + }); const note = await applyChoice(pick.target, scope); let stopped = ""; if (input.stopOthers) {