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

MCP `pins`: list, pin and unpin the caller's pinned repositories, with the same rules as the API #6035

Parked opened this
Closed without merging

scout/forge:scout/4798-mcp-pins-list-pin-and-unpin-the-caller-s → main 12 commits fork 2 threads · 2 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
9 files changed +165 −9
docs/MCP.md +1
@@ -95,6 +95,7 @@ for a tunnel and a forge that sleeps.
9595 | `origins` | `{ action, id? }`: `list` your connected origins, `repos` the repositories one holds (`id`; `mirroredAs` says which are already here), or `sync` one now; the same as `GET /api/v1/user/origins`, `…/:id/repos` and `POST …/:id/sync`, for you only, an admin token as there; never a credential in an answer | yes |
9696 | `outsiders` | `{ repo, on?, dryRun? }`: whether people who cannot write may direct the crew; with `on`, planned first (`dryRun` is true unless `false`); set only by the app's admin with an admin token, never an agent | yes |
9797 | `parent_unlink` | no input: stop signing in through the parent forge, as Settings does; refused when it is the account's last way in, and "Nothing to unlink." when nothing is linked; an admin token | yes |
98 | `pins` | `{ action?, repo? }`: `list` (the default) the caller's pinned repositories; `pin` or `unpin` `repo`, as `PUT`/`DELETE /api/v1/user/pins/:owner/:name` do. A repository the caller cannot see is not found | yes |
9899 | `plan` | `{ app, issues }`: open up to 12 linked issues, all or none (see below) | yes |
99100 | `preview` | `{ url }`: what the forge pill says of an app host's URL (production or a pull's preview): `{ app, environment, pull: { number, title } \| null, check: "green" \| "red" \| "running" \| null, firstFailure, logUrl, working: [names] }`; `firstFailure` is the check's first failing test or its summary, `logUrl` is set only for someone who may read the log (a writer), `working` names the agents with a run going; a URL that is not one of this forge's app hosts is `invalid`, an app you cannot read is `not_found` and a pull you cannot see is `no_such_pull`, as `repo` and `pull` say | |
100101 | `probe` | knock on a running app's doors as nobody, a user and an admin; the ones that disobey its contract | |
src/http/mcp/tools/index.ts +1
@@ -77,6 +77,7 @@ export { tool as origin_apps } from "./origin_apps.ts";
7777 export { tool as origins } from "./origins.ts";
7878 export { tool as outsiders } from "./outsiders.ts";
7979 export { tool as parent_unlink } from "./parent_unlink.ts";
80 export { tool as pins } from "./pins.ts";
8081 export { tool as plan } from "./plan.ts";
8182 export { tool as preview } from "./preview.ts";
8283 export { tool as probe } from "./probe.ts";
src/http/mcp/tools/pins.ts added +40
@@ -0,0 +1,40 @@
1 import { listPinned, pinRepo, unpinRepo } from "../../../actions/origins.ts";
2 import { canRead, getReposByIds } from "../../../core/repos.ts";
3 import { good, bad, type Tool, REPO_ARG, repoArg, isAnswer } from "../shared.ts";
4
5 export const tool: Tool = {
6 name: "pins",
7 doc: "`{ action?, repo? }`: `list` (the default) the caller's pinned repositories; `pin` or `unpin` `repo`, as `PUT`/`DELETE /api/v1/user/pins/:owner/:name` do. A repository the caller cannot see is not found",
8 description: "Your pinned repos: list, pin or unpin `repo`.",
9 inputSchema: {
10 type: "object",
11 properties: {
12 action: { type: "string", enum: ["list", "pin", "unpin"] },
13 repo: REPO_ARG,
14 },
15 },
16 writes: true,
17 readsWithout: "repo",
18 run(ctx, user, args) {
19 const action = args["action"] ?? "list";
20 if (action !== "list" && action !== "pin" && action !== "unpin")
21 return bad("invalid", "action is list, pin or unpin");
22 if (action === "list") {
23 const pins = listPinned(ctx.app, user);

Low: list returns every pin, with no cap, while the API pages with keyedPage. Pins are one per user per repository and they are the caller's own, so this is not a DoS today. If pins ever grow, apply the same page limit here.

24 const repos = getReposByIds(ctx.app.db, pins.map((p) => p.repoId));
25 return good({
26 pins: pins.flatMap((pin) => {
27 const repo = repos.get(pin.repoId);
28 if (!repo || !canRead(ctx.app.db, repo, user)) return [];

Low: this canRead filter is right. GET /api/v1/user/pins in src/http/api.ts does not filter, so the two doors disagree, and the API is the one that leaks (a pin on a repository that later went private still shows its name and clone URL). Follow-up: add the same filter there. Also, this list has no limit while the API's is paged by keyedPage. That is fine for now, since the pins are only the caller's own.

29 return [{ repo: `${repo.ownerName}/${repo.name}`, pinnedAt: pin.createdAt }];
30 }),
31 });
32 }
33 const repo = repoArg(ctx, user, args);
34 if (isAnswer(repo)) return repo;
35 const done = action === "pin" ? pinRepo(ctx.app, user, repo) : unpinRepo(ctx.app, user, repo);
36 return done.ok
37 ? good({ repo: `${repo.ownerName}/${repo.name}`, pinned: action === "pin" })
38 : bad(done.error, action === "pin" ? "that could not be pinned" : "that repository is not pinned");
39 },
40 };
src/http/mcp/tools/plan.ts +1 −4
@@ -35,10 +35,7 @@ export const tool: Tool = {
3535 type: "boolean",
3636 description: "No pillar; needs why.",
3737 },
38 why: {
39 type: "string",
40 description: "With later: why.",
41 },
38 why: { type: "string" },
4239 },
4340 required: ["key", "title"],
4441 },
src/http/mcp/tools/pull.ts +4
@@ -12,7 +12,11 @@ export const tool: Tool = {
1212 name: "pull",
1313 doc: "`{ repo, number }`: a pull's title, state, head and base, and for an open pull whether it merges into the base's current head (`mergeable`) and the paths that stop it (`conflicts`), and `check: { state, baseOid }`: the latest check's state and the base tip it was merged with (empty when it merged nothing); `mergeable` and `conflicts` are the same fields as `GET …/pulls/:number`, `check` is `state` and `run.baseOid` from `GET …/pulls/:number/checks`; draws the `ui://forge/pull` card: `#N title`, state with check and conflicts while open, `head → base` linked to the pull, and the preview link when the pull has an environment",
1414 description:
15 <<<<<<< HEAD
16 "A pull: title, state, head, base; if open: `mergeable`, `conflicts`, `proposal`, `checkStale`, `check`.",
17 =======
1518 "A pull: title, state, head, base; open: `mergeable`, `conflicts`, `proposal`, `check`.",
19 >>>>>>> origin/main
1620 inputSchema: {
1721 type: "object",
1822 properties: {
src/http/mcp/tools/spawn.ts −4
@@ -37,13 +37,9 @@ export const tool: Tool = {
3737 size: {
3838 type: "string",
3939 enum: ["small", "medium", "large"],
40 description:
41 "Recorded only.",
4240 },
4341 keepAccess: {
4442 type: "boolean",
45 description:
46 "Stay an owner.",
4743 },
4844 dryRun: {
4945 type: "boolean",
test/mcp-pins.test.ts added +115
@@ -0,0 +1,115 @@
1 /**
2 * The `pins` tool is /api/v1/user/pins over MCP: the caller's own pins, the
3 * same visibility rule, the same scope gate.
4 */
5 import { afterAll, beforeAll, describe, 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 { createApp, type App } from "../src/app.ts";
10 import { createRepo } from "../src/actions/repos.ts";
11 import { createToken } from "../src/core/tokens.ts";
12 import { createUser } from "../src/core/users.ts";
13 import { serve, type Servers } from "../src/http/server.ts";
14
15 describe("MCP pins", () => {
16 let dataDir: string;
17 let app: App;
18 let servers: Servers;
19 let aliceRw: string;
20 let bobRw: string;
21 let bobRo: string;
22 let id = 1;
23
24 const tool = async (token: string, args: unknown) => {
25 const res = await fetch(`${servers.url}/mcp`, {
26 method: "POST",
27 headers: {
28 "content-type": "application/json",
29 accept: "application/json, text/event-stream",
30 authorization: `Bearer ${token}`,
31 },
32 body: JSON.stringify({
33 jsonrpc: "2.0",
34 id: id++,
35 method: "tools/call",
36 params: { name: "pins", arguments: args },
37 }),
38 });
39 const body: any = await res.json();
40 const text: string = body.result.content[0].text;
41 return body.result.isError === true ? { error: text } : { value: JSON.parse(text) };
42 };
43 const listed = async (token: string) =>
44 (await tool(token, {})).value.pins.map((p: any) => p.repo);
45
46 beforeAll(async () => {
47 dataDir = await mkdtemp(join(tmpdir(), "forge-mcp-pins-"));
48 app = createApp({ dataDir, port: 0 });
49 servers = await serve(app);
50 const mk = async (username: string, first = false) => {
51 const u = await createUser(app.db, {
52 origin: "seed",
53 trusted: true,
54 username,
55 email: `${username}@forge.local`,
56 password: "a-good-passphrase",
57 adminIfFirst: first,
58 });
59 if (!u.ok) throw new Error(u.error);
60 return u.value;
61 };
62 const alice = await mk("alice", true);
63 const bob = await mk("bob");
64 aliceRw = createToken(app.db, alice.id, "rw", "rw").token;
65 bobRw = createToken(app.db, bob.id, "rw", "rw").token;
66 bobRo = createToken(app.db, bob.id, "ro", "ro").token;
67 for (const [name, visibility] of [["open", "public"], ["secret", "private"], ["later", "public"]] as const) {
68 const made = await createRepo(app, alice, { name, visibility });
69 if (!made.ok) throw new Error(String(made.error));
70 }
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("a person pins, lists and unpins; the list is theirs alone", async () => {
80 expect(await listed(bobRw)).toEqual([]);
81 expect((await tool(bobRw, { action: "pin", repo: "alice/open" })).value).toEqual({
82 repo: "alice/open",
83 pinned: true,
84 });
85 expect(await listed(bobRw)).toEqual(["alice/open"]);
86 expect(await listed(aliceRw)).toEqual([]);
87 expect((await tool(bobRw, { action: "unpin", repo: "alice/open" })).value.pinned).toBe(false);
88 expect(await listed(bobRw)).toEqual([]);
89 expect((await tool(bobRw, { action: "unpin", repo: "alice/open" })).error).toContain("not_found");
90 });
91
92 test("a private repository the caller cannot see is not found", async () => {
93 expect((await tool(bobRw, { action: "pin", repo: "alice/secret" })).error).toContain("not_found");
94 expect((await tool(bobRw, { action: "pin", repo: "alice/nope" })).error).toContain("not_found");
95 expect(await listed(bobRw)).toEqual([]);
96 expect((await tool(aliceRw, { action: "pin", repo: "alice/secret" })).value.pinned).toBe(true);
97 });
98
99 test("a pin on a repository that later went private is no longer listed", async () => {
100 await tool(bobRw, { action: "pin", repo: "alice/later" });
101 expect(await listed(bobRw)).toEqual(["alice/later"]);
102 app.db.run("UPDATE repo SET visibility = 'private' WHERE name = 'later'");
103 expect(await listed(bobRw)).toEqual([]);
104 expect(await listed(aliceRw)).not.toContain("alice/later");
105 await tool(aliceRw, { action: "pin", repo: "alice/later" });
106 expect(await listed(aliceRw)).toContain("alice/later");
107 });
108
109 test("a read-only token lists but is refused pin and unpin; a bad action is invalid", async () => {
110 expect(await listed(bobRo)).toEqual([]);
111 expect((await tool(bobRo, { action: "pin", repo: "alice/open" })).error).toContain("forbidden");
112 expect((await tool(bobRo, { action: "unpin", repo: "alice/open" })).error).toContain("forbidden");
113 expect((await tool(bobRw, { action: "nuke", repo: "alice/open" })).error).toContain("invalid");
114 });
115 });
test/mcp-size.test.ts +2 −1
@@ -93,7 +93,8 @@ test("tools/list stays under 40 KB, with 3 KB of headroom (37,150 bytes)", async
9393 expect(bytes, "the argument descriptions were cut by 1,000 bytes").toBeLessThanOrEqual(
9494 // 36,700 before `ssh_keys` (#4795), which costs about 210 bytes.
9595 // 37,100 with `restore_drill` (#5433), 124 bytes.
96 37_100,
96 // plus `pins` (#4798), about 210 bytes.
97 37_310,
9798 );
9899 // readOnlyHint defaults to false; spelling the default out on every write
99100 // tool cost 2 KB, so only a read tool carries annotations.
test/mcp.test.ts +1
@@ -293,6 +293,7 @@ describe("the forge over MCP", () => {
293293 "boards",
294294 "board_write",
295295 "board_pins",
296 "pins",
296297 "board_delete",
297298 "report",
298299 ]));

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs