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
25 changes: 24 additions & 1 deletion pkgs/mcpx/plugin/opencode/v2/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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<void> {
Expand Down Expand Up @@ -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,
Expand Down
84 changes: 84 additions & 0 deletions pkgs/mcpx/plugin/opencode/v2/permission.test.ts
Original file line number Diff line number Diff line change
@@ -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> = {},
): 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> = {},
): 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();
});
});
91 changes: 91 additions & 0 deletions pkgs/mcpx/plugin/opencode/v2/permission.ts
Original file line number Diff line number Diff line change
@@ -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<string>;
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<string, unknown>;
};

/** The slice of the v2 permission domain this plugin uses. */
export type PermissionDomainLike = {
hook(
name: "evaluate",
fn: (input: PermissionEvaluationLike) => void,
): Promise<unknown>;
assert(input: PermissionAssertInput): Promise<void>;
};

/**
* 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<void>) | undefined> {
if (!domain) return undefined;
try {
await domain.hook("evaluate", evaluateMcpxPermission);
} catch {
return undefined;
}
return (input) => domain.assert(input);
}
67 changes: 67 additions & 0 deletions pkgs/mcpx/plugin/opencode/v2/tools.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ const runtime = (over: Record<string, unknown> = {}) =>
discoverFn: async () => discoveryWith([candidate(socketTarget)]),
runBinFn: async () => "from the binary",
clientFor: () => fakeClient(),
assertPermission: async () => {},
...over,
} as never);

Expand Down Expand Up @@ -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"]);
});
});
Loading
Loading