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

MCP `approve_here`: a writer lets an origin fork's pull run here, its check and preview starting at its current head #5122

Parked opened this
Closed without merging

scout/forge:scout/5004-mcp-approve-here-a-writer-lets-an-origin → main 6 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
4 files changed +309 −15
docs/MCP.md +1
@@ -80,6 +80,7 @@ for a tunnel and a forge that sleeps.
8080 | `runs` | `{ repo, limit? }`: the repository's recent runs, newest first (id, kind, state, issue or pull number, started, ended), 1–50, default 20; read as the runs page reads them | |
8181 | `run_log` | `{ repo, run, tail? }`: a run's log, or its last `tail` lines (1–2000), with the REST route's access: a hidden log or unreadable repository is not found | |
8282 | `review` | `{ repo, number, verdict, reason? }`: approve a pull (`approve`) or request changes (`changes`, with a `reason`), as the page does; a writer's or the crew's, and never your own pull | yes |
83 | `approve_here` | `{ repo, number }`: let an origin fork's pull run here: approve its current head so its check and preview start, through `POST …/pulls/:number/approve-here`'s action and refusals (a writer's, never an agent's, never your own pull); answers `says`, the `commit` approved and `url`; a later push needs approving again | yes |
8384 | `threads` | `{ repo, number, anchor?, resolved? }`: a pull's review threads with their comments; with `anchor` (from the list) resolve it (`resolved` true, the default) or reopen it (false), by the API's rules: a writer or someone who commented in the thread | yes |
8485 | `usage` | `{ repo, days? }`: what the crew's runs spent — tokens, cost, wall time — by subscription, agent, issue, and each account's 5-hour and weekly standing; a writer's | |
8586 | `labels` | `{ repo, number, labels }`: set an issue's or a pull's labels to exactly these (`[]` clears); only labels the repository has, by a writer | yes |
src/http/mcp.ts +62 −15
@@ -72,6 +72,7 @@ import {
7272 unlinkIssue,
7373 } from "../actions/dependencies.ts";
7474 import {
75 approveToRun,
7576 pullThreads,
7677 resolveReviewThread,
7778 submitReview,
@@ -658,7 +659,7 @@ const TOOLS: readonly Tool[] = [
658659 {
659660 name: "tell",
660661 description:
661 "Tell an app's crew what should change (first line is the title). Without `repo` it is only kept; answers a thought id.",
662 "Tell an app's crew what to change (first line is the title). Without `repo` it is kept; answers a thought id.",
662663 inputSchema: {
663664 type: "object",
664665 properties: {
@@ -1149,7 +1150,7 @@ const TOOLS: readonly Tool[] = [
11491150 {
11501151 name: "asks_act",
11511152 description:
1152 "Decide many asks: dismiss, decline, ship (never undone), close (`reason`), mute, replan. `items`: ids from `asks`, or `issue:<id>`.",
1153 "Decide many asks: dismiss, decline, ship (final), close (`reason`), mute, replan. `items`: `asks` ids/`issue:<id>`.",
11531154 inputSchema: {
11541155 type: "object",
11551156 properties: {
@@ -1173,7 +1174,7 @@ const TOOLS: readonly Tool[] = [
11731174 {
11741175 name: "asks_decide",
11751176 description:
1176 "Let the decider answer a hand-over (`item` is the row's `parked:<id>`). Only a sure set_aside (70%+) clears the card.",
1177 "Let the decider answer a hand-over (`item`: the row's `parked:<id>`). Only a sure set_aside (70%+) clears it.",
11771178 inputSchema: {
11781179 type: "object",
11791180 properties: { item: { type: "string", maxLength: 80 } },
@@ -1410,7 +1411,7 @@ const TOOLS: readonly Tool[] = [
14101411 {
14111412 name: "now",
14121413 description:
1413 "What the crew is doing now across your apps: who, on what, since when, cost so far; what waits on your review first.",
1414 "What the crew is doing now across your apps: who, on what, since when, cost; what waits on your review first.",
14141415 inputSchema: { type: "object", properties: {} },
14151416 writes: false,
14161417 run(ctx, user) {
@@ -1581,7 +1582,7 @@ const TOOLS: readonly Tool[] = [
15811582 {
15821583 name: "model_grant",
15831584 description:
1584 "Give a person's account a capped monthly model grant in dollars (`usdPerMonth` 0 takes it back). Person admins only.",
1585 "Give a person a capped monthly model grant in dollars (`usdPerMonth` 0 takes it back). Person admins only.",
15851586 inputSchema: {
15861587 type: "object",
15871588 properties: {
@@ -1725,7 +1726,7 @@ const TOOLS: readonly Tool[] = [
17251726 {
17261727 name: "model_ceiling",
17271728 description:
1728 "Set an account's daily and per-run model spend ceilings in dollars; a run past either does not start.",
1729 "Set an account's daily and per-run model spend ceilings in dollars; a run past either won't start.",
17291730 inputSchema: {
17301731 type: "object",
17311732 properties: {
@@ -1789,7 +1790,7 @@ const TOOLS: readonly Tool[] = [
17891790 {
17901791 name: "outsiders",
17911792 description:
1792 "Whether people who cannot write an app may direct its crew (off by default). Without `on`, says which.",
1793 "Whether people who cannot write an app may direct its crew (off by default). Without `on`, reads it.",
17931794 inputSchema: {
17941795 type: "object",
17951796 properties: {
@@ -2240,7 +2241,7 @@ const TOOLS: readonly Tool[] = [
22402241 {
22412242 name: "spawn",
22422243 description:
2243 "Spawn a child forge with the named apps and the crew's briefs. Plans first (dryRun false spawns).",
2244 "Spawn a child forge with the named apps and crew briefs. Plans first (dryRun false spawns).",
22442245 inputSchema: {
22452246 type: "object",
22462247 properties: {
@@ -2375,7 +2376,7 @@ const TOOLS: readonly Tool[] = [
23752376 {
23762377 name: "forges",
23772378 description:
2378 "The forges you sent from here (an admin's list): name, address, whom for, apps, claimed or not, last activity.",
2379 "The forges you sent from here (admin): name, address, whom for, apps, claimed or not, last activity.",
23792380 inputSchema: { type: "object", properties: {} },
23802381 writes: false,
23812382 async run(ctx, user) {
@@ -2416,7 +2417,7 @@ const TOOLS: readonly Tool[] = [
24162417 {
24172418 name: "take_updates",
24182419 description:
2419 "Take the parent forge's updates into a fork: one pull on a spawned forge; otherwise a fast-forward or clean merge.",
2420 "Take the parent's updates into a fork: one pull on a spawned forge; else a fast-forward or clean merge.",
24202421 inputSchema: {
24212422 type: "object",
24222423 properties: { repo: REPO_ARG },
@@ -2679,7 +2680,7 @@ const TOOLS: readonly Tool[] = [
26792680 {
26802681 name: "asked",
26812682 description:
2682 "What people asked the crew for, in repositories you can write: by default what has nothing merged yet, oldest first.",
2683 "What people asked the crew for, in repositories you can write: by default nothing merged yet, oldest first.",
26832684 inputSchema: {
26842685 type: "object",
26852686 properties: {
@@ -3083,7 +3084,7 @@ const TOOLS: readonly Tool[] = [
30833084 {
30843085 name: "milestones",
30853086 description:
3086 "How far each thing asked for is. With `app`: the plan's top-level limbs with done/total, building and recent merges.",
3087 "How far each thing asked for is. With `app`: the plan's top limbs with done/total, building and recent merges.",
30873088 inputSchema: {
30883089 type: "object",
30893090 properties: {
@@ -3243,7 +3244,7 @@ const TOOLS: readonly Tool[] = [
32433244 {
32443245 name: "limb",
32453246 description:
3246 "One action on a plan limb: `defer`, `resume` (`pillar`), `close` (`reason`), `raise`/`lower` (`under`), `replan`, `takeback`, `undo`.",
3247 "A limb action: `defer`, `resume` (`pillar`), `close` (`reason`), `raise`/`lower` (`under`), `replan`, `takeback`, `undo`.",
32473248 inputSchema: {
32483249 type: "object",
32493250 properties: {
@@ -3325,7 +3326,7 @@ const TOOLS: readonly Tool[] = [
33253326 {
33263327 name: "returns",
33273328 description:
3328 "What the crew's tokens bought over the last days (1–90, default 7): dollars, runs, changes landed, cost per change.",
3329 "What the crew's tokens bought over `days` (1–90, default 7): dollars, runs, changes landed, cost per change.",
33293330 inputSchema: {
33303331 type: "object",
33313332 properties: {
@@ -3403,6 +3404,52 @@ const TOOLS: readonly Tool[] = [
34033404 });
34043405 },
34053406 },
3407 {
3408 name: "approve_here",
3409 description:
3410 "Let an origin fork's pull run here, at its current head.",
3411 inputSchema: {
3412 type: "object",
3413 properties: {
3414 repo: REPO_ARG,
3415 number: { type: "integer", minimum: 1 },
3416 },
3417 required: ["repo", "number"],
3418 },
3419 writes: true,
3420 async run(ctx, user, args) {
3421 const repo = repoArg(ctx, user, args);
3422 if (isAnswer(repo)) return repo;
3423 const n = args["number"];
3424 const pull =
3425 typeof n === "number" && Number.isInteger(n) && n > 0
3426 ? getPull(ctx.app.db, repo.id, n)
3427 : undefined;
3428 if (pull === undefined || !mayView(ctx.app.db, repo, pull, user))
3429 return bad("no_such_pull", `no pull #${String(n)}`);
3430 const done = await approveToRun(ctx.app, user, repo, pull);
3431 if (!done.ok) {
3432 const error = done.error;
3433 return bad(
3434 "refused",
3435 error === "self_review"
3436 ? "You cannot approve your own pull request."
3437 : error === "not_foreign"
3438 ? "This pull needs no approval to run."
3439 : error === "not_open"
3440 ? "This pull is closed."
3441 : error === "forbidden"
3442 ? "Letting a pull run needs write access, and a person's."
3443 : "That pull could not be approved.",
3444 );
3445 }
3446 return good({
3447 says: `Approved to run at ${done.value.commitOid.slice(0, 7)}; a new push needs approving again.`,
3448 commit: done.value.commitOid,
3449 url: `/${repo.ownerName}/${repo.name}/pulls/${pull.number}`,
3450 });
3451 },
3452 },
34063453 {
34073454 name: "threads",
34083455 description:
@@ -3992,7 +4039,7 @@ const TOOLS: readonly Tool[] = [
39924039 {
39934040 name: "flow",
39944041 description:
3995 "The forge's pipeline (forge admin): per stage counts, `oldestWaiting`, `capacity`, the bottleneck, merge `queue`, `reviewing` per reviewer.",
4042 "The pipeline (forge admin): stage counts, `oldestWaiting`, `capacity`, bottleneck, merge `queue`, `reviewing`.",
39964043 inputSchema: { type: "object", properties: {} },
39974044 writes: false,
39984045 run(ctx, user) {
test/mcp-approve-here.test.ts added +245
@@ -0,0 +1,245 @@
1 /**
2 * The `approve_here` tool over MCP: the route's action, rules and refusals —
3 * a writer approves an origin fork's pull at its head, a reader, an agent and
4 * a stranger are refused, a later push waits, and bad input stops at the edge.
5 */
6 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
7 import { mkdtemp, rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { openPull } from "../src/actions/pulls.ts";
11 import { addToCrew, createAgent } from "../src/actions/crew.ts";
12 import { commitToBranch, createRepo, forkRepo } from "../src/actions/repos.ts";
13 import { createApp, type App } from "../src/app.ts";
14 import { pullMayRun } from "../src/core/pull_trust.ts";
15 import { getPull } from "../src/core/pulls.ts";
16 import type { Repo } from "../src/core/repos.ts";
17 import { createToken } from "../src/core/tokens.ts";
18 import { createUser, type User } from "../src/core/users.ts";
19 import { serve, type Servers } from "../src/http/server.ts";
20 import { promote } from "./helpers/members.ts";
21
22 describe("the approve_here tool over MCP", () => {
23 let dataDir: string;
24 let app: App;
25 let servers: Servers;
26 let alice: User;
27 let carol: User;
28 let dave: User;
29 let lib: Repo;
30 let tokens: Record<string, string>;
31 let nextId = 1;
32
33 const call = async (token: string, name: string, args: unknown) => {
34 const res = await fetch(`${servers.url}/mcp`, {
35 method: "POST",
36 headers: {
37 "content-type": "application/json",
38 accept: "application/json, text/event-stream",
39 authorization: `Bearer ${token}`,
40 },
41 body: JSON.stringify({
42 jsonrpc: "2.0",
43 id: nextId++,
44 method: "tools/call",
45 params: { name, arguments: args },
46 }),
47 });
48 if (res.status === 401) return { error: "unauthorized" };
49 const body = (await res.json()) as any;
50 if (body.error) return { error: body.error.message as string };
51 const text: string = body.result.content[0].text;
52 return body.result.isError === true
53 ? { error: text }
54 : { value: JSON.parse(text) };
55 };
56 const tool = (token: string, args: unknown) =>
57 call(token, "approve_here", args);
58
59 let carolFork: Repo | undefined;
60 let n = 0;
61 async function originPull() {
62 const branch = `b${++n}`;
63 if (!carolFork) {
64 const forked = await forkRepo(app, carol, lib, "fork");
65 if (!forked.ok) throw new Error(String(forked.error));
66 carolFork = forked.value;
67 }
68 const committed = await commitToBranch(app, carol, carolFork, {
69 branch,
70 message: "From the origin's fork",
71 files: [{ path: `${branch}.md`, content: "hi\n" }],
72 });
73 if (!committed.ok) throw new Error(JSON.stringify(committed.error));
74 const opened = await openPull(app, carol, lib, {
75 title: "Theirs",
76 baseBranch: "main",
77 headBranch: branch,
78 headRepo: carolFork,
79 });
80 if (!opened.ok) throw new Error(String(opened.error));
81 app.db.run("UPDATE pull SET origin_head_repo = ?1 WHERE issue_id = ?2", [
82 "octo/lib",
83 opened.value.id,
84 ]);
85 return {
86 pull: getPull(app.db, lib.id, opened.value.number)!,
87 head: committed.value.commitOid,
88 };
89 }
90
91 beforeAll(async () => {
92 dataDir = await mkdtemp(join(tmpdir(), "forge-mcp-approve-here-"));
93 app = createApp({ dataDir, port: 0 });
94 servers = await serve(app);
95 const mk = async (username: string, first = false) => {
96 const made = await createUser(app.db, {
97 origin: "seed",
98 trusted: true,
99 username,
100 email: `${username}@forge.local`,
101 password: "a-good-passphrase",
102 adminIfFirst: first,
103 });
104 if (!made.ok) throw new Error(made.error);
105 return made.value;
106 };
107 alice = await mk("alice", true);
108 carol = await mk("carol");
109 dave = await mk("dave");
110 promote(app.db, alice, carol, dave);
111 const made = await createRepo(app, alice, {
112 name: "lib",
113 visibility: "public",
114 });
115 if (!made.ok) throw new Error(String(made.error));
116 lib = made.value;
117 await commitToBranch(app, alice, lib, {
118 message: "seed",
119 files: [{ path: "README.md", content: "# lib\n" }],
120 });
121 const bot = await createAgent(app, alice, { username: "bot" });
122 if (!bot.ok) throw new Error(String(bot.error));
123 expect(addToCrew(app, alice, lib, "bot").ok).toBe(true);
124 const botUser = bot.value.user;
125 tokens = {
126 alice: createToken(app.db, alice.id, "rw", "rw").token,
127 dave: createToken(app.db, dave.id, "rw", "rw").token,
128 bot: createToken(app.db, botUser.id, "rw", "rw").token,
129 };
130 }, 30_000);
131
132 afterAll(async () => {
133 servers.stop();
134 app.close();
135 await rm(dataDir, { recursive: true, force: true });
136 });
137
138 test("it is listed with a schema", async () => {
139 const res = await fetch(`${servers.url}/mcp`, {
140 method: "POST",
141 headers: {
142 "content-type": "application/json",
143 accept: "application/json, text/event-stream",
144 authorization: `Bearer ${tokens["alice"]}`,
145 },
146 body: JSON.stringify({ jsonrpc: "2.0", id: 999, method: "tools/list" }),
147 });
148 const body = (await res.json()) as any;
149 const t = body.result.tools.find((x: any) => x.name === "approve_here");
150 expect(t.inputSchema.required).toEqual(["repo", "number"]);
151 });
152
153 test("a writer approves the head, and a later push needs approving again", async () => {
154 const { pull, head } = await originPull();
155 expect(pullMayRun(app.db, lib, pull, head)).toBe(false);
156 const done = await tool(tokens["alice"]!, {
157 repo: "alice/lib",
158 number: pull.number,
159 });
160 expect(done.value.commit).toBe(head);
161 expect(done.value.says).toContain(head.slice(0, 7));
162 expect(done.value.url).toBe(`/alice/lib/pulls/${pull.number}`);
163 expect(pullMayRun(app.db, lib, pull, head)).toBe(true);
164
165 const again = await commitToBranch(app, carol, carolFork!, {
166 branch: pull.headBranch,
167 message: "Again",
168 files: [{ path: "again.md", content: "again\n" }],
169 });
170 if (!again.ok) throw new Error(JSON.stringify(again.error));
171 expect(pullMayRun(app.db, lib, pull, again.value.commitOid)).toBe(false);
172 }, 30_000);
173
174 test("a reader, an agent and a stranger are refused as the route refuses", async () => {
175 const { pull, head } = await originPull();
176 const args = { repo: "alice/lib", number: pull.number };
177 for (const who of ["dave", "bot"]) {
178 const refused = await tool(tokens[who]!, args);
179 expect(refused.error).toContain("needs write access, and a person's");
180 }
181 const stranger = await tool("nope", args);
182 expect(stranger.error).toBe("unauthorized");
183 expect(pullMayRun(app.db, lib, pull, head)).toBe(false);
184 }, 30_000);
185
186 test("your own pull and a closed pull are refused in their own words", async () => {
187 const mine = await originPull();
188 app.db.run("UPDATE issue SET author_id = ?1 WHERE id = ?2", [
189 alice.id,
190 mine.pull.id,
191 ]);
192 const own = await tool(tokens["alice"]!, {
193 repo: "alice/lib",
194 number: mine.pull.number,
195 });
196 expect(own.error).toContain("cannot approve your own");
197 expect(pullMayRun(app.db, lib, mine.pull, mine.head)).toBe(false);
198
199 const closed = await originPull();
200 app.db.run("UPDATE issue SET state = 'closed' WHERE id = ?1", [
201 closed.pull.id,
202 ]);
203 const shut = await tool(tokens["alice"]!, {
204 repo: "alice/lib",
205 number: closed.pull.number,
206 });
207 expect(shut.error).toContain("is closed");
208 }, 30_000);
209
210 test("a plain pull and bad arguments are refused in a sentence", async () => {
211 const plain = await openPlain();
212 const needsNone = await tool(tokens["alice"]!, {
213 repo: "alice/lib",
214 number: plain,
215 });
216 expect(needsNone.error).toContain("needs no approval");
217 for (const args of [
218 {},
219 { repo: "alice/lib" },
220 { repo: "alice/lib", number: 0 },
221 { repo: "alice/lib", number: "1" },
222 { repo: "alice/lib", number: 9999 },
223 { repo: "nobody/nothing", number: 1 },
224 ]) {
225 const refused = await tool(tokens["alice"]!, args);
226 expect(refused.error).toBeString();
227 }
228 }, 30_000);
229
230 async function openPlain() {
231 const made = await commitToBranch(app, alice, lib, {
232 branch: "plain",
233 message: "plain",
234 files: [{ path: "plain.txt", content: "p\n" }],
235 });
236 if (!made.ok) throw new Error(JSON.stringify(made.error));
237 const opened = await openPull(app, alice, lib, {
238 title: "plain",
239 baseBranch: "main",
240 headBranch: "plain",
241 });
242 if (!opened.ok) throw new Error(String(opened.error));
243 return opened.value.number;
244 }
245 });
test/mcp.test.ts +1
@@ -247,6 +247,7 @@ describe("the forge over MCP", () => {
247247 "limb",
248248 "returns",
249249 "review",
250 "approve_here",
250251 "threads",
251252 "spend",
252253 "usage",

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs