Public: anyone can read this; the crew can change it.

An admin's agent can cut a wave through MCP #16600

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

mason/forge:mason/16261-an-admin-s-agent-can-cut-a-wave-through → main 0 commits fork 1 thread · 1 unresolved

  • Merged. mason/16261-an-admin-s-agent-can-cut-a-wave-through was merged into main as 0317a57.

Review

Sign in to review this change.
10 files changed +143 −5
docs/MCP.md +2
@@ -74,6 +74,8 @@ card (`tokenFreeTools`) and `/api/v1/here`.
7474 The complete list, with schemas, is MCP `tools/list` called with a token.
7575 `/llms.txt`, under "## MCP tools", lists only the tools open without a token (one line each, from its `doc`) and counts the rest, pointing on to `tools/list`; signed in, it lists the tools that token may call (a read-only token omits the writes it cannot make; admin tools need an admin account and an admin-scope token). It carries an ETag that changes only when its words do; a stranger's read is public for five minutes and answers `If-None-Match` with 304, a token's is private.
7676
77 `cut_wave` (`{ repo }`) calls `cutWaveFor`, as Settings and the terminal do: it opens the next draft `waves/<next>.md` as a pull and answers `{ version, number, url }`. It is listed to a forge admin only; a repository's non-admin who calls it by name is refused in the page's words ("Only a repository admin can cut a wave.").
78
7779 Sending a failed webhook delivery again (`redeliver`, #8075) is the terminal's `r` on a hook's Deliveries screen only; the `hooks` tool has no action for it yet.
7880
7981 ### Adding a tool
src/actions/cut_wave.ts +4 −1
@@ -35,6 +35,9 @@ async function readWaves(app: App, repo: Repo): Promise<WaveFile[]> {
3535 return files;
3636 }
3737
38 /** The refusal for anyone who is not a repository admin; callers tell it from other failures. */
39 export const CUT_WAVE_REFUSED = "Only a repository admin can cut a wave.";
40
3841 /** What a cut would write, or the reason it cannot; nothing is written. */
3942 export async function planCutFor(
4043 app: App,
@@ -42,7 +45,7 @@ export async function planCutFor(
4245 repo: Repo,
4346 ): Promise<Result<Cut, string>> {
4447 if (!actor || actor.kind === "agent" || !canAdmin(app.db, repo, actor))
45 return err("Only a repository admin can cut a wave.");
48 return err(CUT_WAVE_REFUSED);
4649 const waves = await readWaves(app, repo);
4750 const base = app.config.url ?? `http://localhost:${app.config.port}`;
4851 const repoUrl = `${base.replace(/\/+$/, "")}/${repo.ownerName}/${repo.name}`;
src/crew/conversation_ask.ts +1
@@ -160,6 +160,7 @@ export const ASKED_AS: Readonly<Record<string, Form>> = {
160160 close: (a) =>
161161 a["state"] === "open" ? `Reopen ${item(a)}` : `Close ${item(a)}${clause(" as ", verb(a, "reason", { done: "done", dropped: "dropped", split: "split up" }, ""))}`,
162162 merge: (a) => `Merge ${pull(a)}`,
163 cut_wave: (a) => `Cut the next wave of ${repo(a, "the app")} as a draft pull`,
163164 wall: (a) => (a["answer"] === "send_back" ? `Send ${pull(a)} back at the access wall` : `Allow ${pull(a)} at the access wall and merge it`),
164165 edit: (a) =>
165166 a["title"] !== undefined ? `Retitle ${item(a)}${clause(" to ", quote(a, "title"))}` : `Rewrite the description of ${item(a)}`,
src/crew/conversation_confirm.ts +2
@@ -52,6 +52,8 @@ export const ASKING: Readonly<Record<string, Asking>> = {
5252 undo: (a) => (a["reason"] !== undefined ? "`release_hold` with `lift` and the hold's id lifts it" : undefined),
5353 },
5454 release_now: {},
55 // Opens a draft pull; closing it undoes it.
56 cut_wave: { undo: () => "close the draft pull it opened" },
5557 // A file in an app's private drop: kept or removed (#645).
5658 drop: {
5759 asks: (a) => a["action"] === "put" || a["action"] === "remove",
src/http/mcp/tools/cut_wave.ts added +22
@@ -0,0 +1,22 @@
1 import { CUT_WAVE_REFUSED, cutWaveFor } from "../../../actions/cut_wave.ts";
2 import { bad, good, isAnswer, REPO_ARG, repoArg, type Tool } from "../shared.ts";
3
4 export const tool: Tool = {
5 name: "cut_wave",
6 listedTo: "admin",
7 doc: "`{ repo }`: cut the next wave as the Settings button and the terminal do (`cutWaveFor`): opens a draft `waves/<next>.md` as a pull listing every pull merged since the last wave, no model called; answers `{ version, number, url }` of the draft pull. A repository admin's; anyone else is refused in the page's words, and the tool is listed to a forge admin only",
8 description: "Cut the next wave as a draft pull (admin).",
9 inputSchema: { type: "object", properties: { repo: REPO_ARG }, required: ["repo"] },
10 writes: true,
11 async run(ctx, user, args) {
12 const repo = repoArg(ctx, user, args);
13 if (isAnswer(repo)) return repo;
14 const cut = await cutWaveFor(ctx.app, user, repo);
15 if (!cut.ok) return bad(cut.error === CUT_WAVE_REFUSED ? "forbidden" : "failed", cut.error);
outdated

Every failure is reported as forbidden, including a wave file that does not parse or a pull that fails to open. Keep forbidden for the 'Only a repository admin' refusal, give other failures the ordinary failure code, and test that path.

16 return good({
17 version: cut.value.version,
18 number: cut.value.number,
19 url: `/${repo.ownerName}/${repo.name}/pulls/${cut.value.number}`,
20 });
21 },
22 };
src/http/mcp/tools/index.ts +1
@@ -50,6 +50,7 @@ export { tool as confirm_wait } from "./confirm_wait.ts";
5050 export { tool as contribute } from "./contribute.ts";
5151 export { tool as converge } from "./converge.ts";
5252 export { tool as crew } from "./crew.ts";
53 export { tool as cut_wave } from "./cut_wave.ts";
5354 export { tool as data } from "./data.ts";
5455 export { tool as decisions_by } from "./decisions_by.ts";
5556 export { tool as desk } from "./desk.ts";
test/conversation-ask.test.ts +1
@@ -13,6 +13,7 @@ import { TOOLS } from "../src/http/mcp/tools.ts";
1313
1414 /** Every form, said: a tool, a call of it, and the sentence the person reads. */
1515 const SAID: readonly (readonly [string, Record<string, unknown>, string])[] = [
16 ["cut_wave", { repo: "marin/cakes" }, "Cut the next wave of marin/cakes as a draft pull."],
1617 [
1718 "tell",
1819 {
test/llms-budget.test.ts +4 −4
@@ -55,11 +55,11 @@ const get = async (token?: string): Promise<string> =>
5555 * measured signed-in 83,283 and admin 95,000, within 17 bytes of the ceiling before the pull's
5656 * `.ifc` note on read_file; signed-in 84,100 and admin 96,000 (anonymous unchanged). Raised again:
5757 * admin 98,000 (signed-in 84,100 and anonymous 9,250 as they are). Main measured admin 95,899, 101
58 * bytes under 96,000, and four tools in flight (fetch_url, invite, bring, propose_upstream) each add
59 * about 40 to 330 bytes to it. Only an agent with an admin token reads this text, and few do, so the
60 * cost of the room is small.
58 * bytes under 96,000, and four tools in flight (fetch_url, invite, bring, propose_upstream) each
59 * add about 40 to 330 bytes to it. Only an agent with an admin token reads this text, and few do,
60 * so the cost of the room is small. Raised to 98,500 for cut_wave (admin 98,345).
6161 */
62 const BUDGET = { anonymous: 9_250, signedIn: 84_100, admin: 98_000 } as const;
62 const BUDGET = { anonymous: 9_250, signedIn: 84_100, admin: 98_500 } as const;
6363
6464 test("/llms.txt stays under its byte budget for each role", async () => {
6565 const sizes = {
test/mcp-cut-wave.test.ts added +105
@@ -0,0 +1,105 @@
1 /**
2 * MCP `cut_wave`: an admin cuts a wave and gets the pull; a writer is refused and never sees the
3 * tool.
4 */
5 import { afterAll, beforeAll, expect, test } from "bun:test";
6 import { mkdtemp, rm } from "node:fs/promises";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { mergePull, openPull } from "../src/actions/pulls.ts";
10 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
11 import { createApp, type App } from "../src/app.ts";
12 import { addTeamMember, createOrg, createTeam } from "../src/core/orgs.ts";
13 import { promote } from "./helpers/members.ts";
14 import { createToken } from "../src/core/tokens.ts";
15 import { createUser } from "../src/core/users.ts";
16 import { serve, type Servers } from "../src/http/server.ts";
17 import { quietLogs } from "./helpers/globals.ts";
18
19 quietLogs();
20
21 let dataDir: string;
22 let app: App;
23 let servers: Servers;
24 const tok: Record<string, string> = {};
25
26 async function rpc(token: string, method: string, params: unknown): Promise<any> {
27 const res = await fetch(`${servers.url}/mcp`, {
28 method: "POST",
29 headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${token}` },
30 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }),
31 });
32 return ((await res.json()) as any).result;
33 }
34 /** What find_tool offers this caller: the lean tools/list leaves most tools to it. */
35 const names = async (token: string): Promise<string[]> => {
36 const r = await rpc(token, "tools/call", { name: "find_tool", arguments: { query: "cut wave draft pull" } });
37 return (JSON.parse(r.content[0].text).tools as { name: string }[]).map((t) => t.name);
38 };
39 const call = (token: string, args: unknown) => rpc(token, "tools/call", { name: "cut_wave", arguments: args });
40
41 beforeAll(async () => {
42 dataDir = await mkdtemp(join(tmpdir(), "forge-cutwave-mcp-"));
43 app = createApp({ dataDir, port: 0 });
44 servers = await serve(app);
45 const make = async (username: string, isAdmin = false) => {
46 const r = await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@forge.local`, password: "a-good-passphrase", isAdmin });
47 if (!r.ok) throw new Error(JSON.stringify(r.error));
48 return r.value;
49 };
50 const admin = await make("olive", true);
51 const writer = await make("wren");
52 promote(app.db, admin, writer);
53 const org = createOrg(app.db, "guild", admin.id);
54 if (!org.ok) throw new Error("org");
55 const team = createTeam(app.db, org.value.id, "writers", "write");
56 if (!team.ok) throw new Error("team");
57 addTeamMember(app.db, team.value, writer.id);
58 const made = await createRepo(app, admin, { owner: "guild", name: "proj", visibility: "public" });
59 if (!made.ok) throw new Error(JSON.stringify(made.error));
60 const repo = made.value;
61 await commitToBranch(app, admin, repo, { message: "seed", files: [{ path: "a.txt", content: "a\n" }] });
62 await commitToBranch(app, admin, repo, { branch: "one", message: "one", files: [{ path: "one.txt", content: "1" }] });
63 const p = await openPull(app, admin, repo, { title: "Feature one", baseBranch: "main", headBranch: "one" });
64 if (!p.ok) throw new Error(String(p.error));
65 await mergePull(app, admin, repo, p.value, "merge");
66 const junk = await createRepo(app, admin, { owner: "guild", name: "junk", visibility: "public" });
67 if (!junk.ok) throw new Error(JSON.stringify(junk.error));
68 await commitToBranch(app, admin, junk.value, { message: "bad wave", files: [{ path: "waves/0.0.9.md", content: "not a wave" }] });
69 tok["admin"] = createToken(app.db, admin.id, "rw", "rw").token;
70 tok["writer"] = createToken(app.db, writer.id, "rw", "rw").token;
71 }, 30_000);
72
73 afterAll(async () => {
74 servers?.stop();
75 app?.close();
76 await rm(dataDir, { recursive: true, force: true });
77 });
78
79 test("the tool is listed for an admin and absent for a writer", async () => {
80 expect(await names(tok["admin"]!)).toContain("cut_wave");
81 expect(await names(tok["writer"]!)).not.toContain("cut_wave");
82 });
83
84 test("a writer who calls it is refused in words and nothing is opened", async () => {
85 const r = await call(tok["writer"]!, { repo: "guild/proj" });
86 expect(r.isError).toBe(true);
87 expect(r.content[0].text).toContain("Only a repository admin can cut a wave.");
88 });
89
90 test("an admin cuts a wave and gets the draft pull", async () => {
91 const r = await call(tok["admin"]!, { repo: "guild/proj" });
92 expect(r.isError).not.toBe(true);
93 const v = JSON.parse(r.content[0].text);
94 expect(v.version).toMatch(/^\d+\.\d+\.\d+$/);
95 expect(v.url).toBe(`/guild/proj/pulls/${v.number}`);
96 }, 30_000);
97
98 test("a wave file that does not parse is a failure, not a refusal of rights", async () => {
99 const r = await call(tok["admin"]!, { repo: "guild/junk" });
100 expect(r.isError).toBe(true);
101 const text: string = r.content[0].text;
102 expect(text).toContain("waves/0.0.9.md");
103 expect(text).not.toContain("forbidden");
104 expect(text).toContain("failed");
105 });
test/mcp-forge-protocol.test.ts +1
@@ -114,6 +114,7 @@ describe("the forge over MCP: protocol", () => {
114114 const names = listed.body.result.tools.map((t: { name: string }) => t.name);
115115 // Listed by name, one file each (#5924), and `report` last.
116116 expect(names).toEqual(sortedThenReport([
117 "cut_wave",
117118 "data",
118119 "desk",
119120 "drills",

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs