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

MCP tools to list, add, grant and remove crew SSH devices #16863

Merged opened this

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

Merged

torque/forge:torque/3685-mcp-tools-to-list-add-grant-and-remove-c → main 0 commits fork

  • Merged. torque/3685-mcp-tools-to-list-add-grant-and-remove-c was merged into main as 8d40736.

Review

Sign in to review this change.
16 files changed +280 −13
docs/MCP.md +1 −1
@@ -200,7 +200,7 @@ list is `ASKING` in `src/crew/conversation_confirm.ts`. Such a call does
200200 nothing and answers `{ needs_confirm, tool, does, says }`: `does` is one
201201 sentence of what it will do, said to the person; a secret's value is never
202202 repeated in it, and an argument cannot break it onto a new line. A tool whose
203 only reading action is `list` (`secrets`, `app_env`, `ssh_keys`, and
203 only reading action is `list` (`secrets`, `app_env`, `ssh_keys`, `crew_devices`, and
204204 `proposal_tokens` by its `verb`) asks for its writes only. A `confirm` turn is
205205 written to their conversation.
206206
docs/features/crew-devices.md +5
@@ -21,6 +21,11 @@ A crew run's shell reaches the forge and the registry only, unless its repositor
2121
2222 `DELETE …/crew-devices` (the device in the body) unlists; changing the secret drops the grant.
2323
24 The MCP tool `crew_devices` (`{ repo, action: list|add|grant|remove, device?, secret?, host_key? }`, admin-scope token) does the same four
25 things with the same rules and codes, listed only while the SSH switch is on and only to an admin-scope token. An agent's own account is
26 refused every change (`forbidden`, as on the pages); the forge's conversation agent, speaking with a person's token, is held for their yes on
27 `add`, `grant` and `remove` before any of it runs.
28
2429 Both doors: Settings › Devices (`src/web/pages/crew_devices.ts`) and the terminal screen (`src/tui/screens/crewdevices.ts`,
2530 palette entry *Devices* in a repository you administer: `a` lists, `g` grants, `x` unlists, `s` flips to the sessions)
2631 use the same actions. A repository admin lists, unlists and reads; only a site admin grants; anyone else sees nothing.
src/core/mcp_card.ts +5 −4
@@ -187,16 +187,17 @@ export function cardsLine(): string {
187187 * The MCP tools, as the index lists them: set once at boot, read by both
188188 * cards so neither can name a tool the other lacks.
189189 */
190 let cardTools: readonly { name: string; description: string }[] = [];
190 let cardTools: readonly { name: string; description: string; needsSwitch?: "ssh" }[] = [];
191191 /** The tools a card names: one that waits on the SSH switch only while it is on. */
192 const shownTools = (ssh: boolean): typeof cardTools => cardTools.filter((t) => t.name !== "ssh_keys" || ssh);
193 export function setCardTools(tools: readonly { name: string; description: string; doc?: string }[]): void {
192 const shownTools = (ssh: boolean): typeof cardTools => cardTools.filter((t) => t.needsSwitch === undefined || ssh);
193 export function setCardTools(tools: readonly { name: string; description: string; doc?: string; needsSwitch?: "ssh" }[]): void {
194194 const seen = new Set<string>();
195195 cardTools = tools
196196 .filter((t) => !seen.has(t.name) && seen.add(t.name))
197197 .map((t) => {
198198 const one = (t.doc ?? t.description).replace(/\s+/g, " ").trim();
199 return { name: t.name, description: one.length > 200 ? `${one.slice(0, 199)}…` : one };
199 const description = one.length > 200 ? `${one.slice(0, 199)}…` : one;
200 return t.needsSwitch === undefined ? { name: t.name, description } : { name: t.name, description, needsSwitch: t.needsSwitch };
200201 });
201202 }
202203
src/crew/conversation_ask.ts +2
@@ -283,6 +283,8 @@ export const ASKED_AS: Readonly<Record<string, Form>> = {
283283 ? `Bring back the old claim link of ${val(a, "name")}`
284284 : `Make a new claim link for ${val(a, "name")}, ending the old one`,
285285 ssh_keys: (a) => (a["action"] === "remove" ? `Remove SSH key ${val(a, "id")} from your account` : `Add the SSH key${clause(" ", quote(a, "title"))} to your account`),
286 crew_devices: (a) =>
287 a["action"] === "remove" ? `Unlist crew device ${val(a, "device")}` : a["action"] === "grant" ? `Grant the crew SSH to ${val(a, "device")}` : `List ${val(a, "device")} as a device the crew may SSH to`,
286288 // Reach and trust.
287289 land_past_gate: (a) => `Land ${pull(a)} past its broken gate${clause(": ", quote(a, "reason"))}`,
288290 share: (a) => `Share feed item ${val(a, "item")} with ${Array.isArray(a["to"]) ? "your followers" : "the app's crew and owners"}`,
src/crew/conversation_confirm.ts +2
@@ -112,6 +112,8 @@ export const ASKING: Readonly<Record<string, Asking>> = {
112112 asks: not("action", "list"),
113113 undo: (a) => (a["action"] === "add" ? "`ssh_keys` with `action: \"remove\"` and its id removes it" : undefined),
114114 },
115 // Which machines the crew may log in to: any change asks first (#3685).
116 crew_devices: { asks: not("action", "list") },
115117 // Reach and trust: who may see, enter, deploy, stop or be linked to (#8230).
116118 land_past_gate: {},
117119 share: {},
src/http/mcp/tools/crew_devices.ts added +60
@@ -0,0 +1,60 @@
1 import {
2 addCrewDevice,
3 devicesView,
4 grantCrewDevice,
5 removeCrewDevice,
6 } from "../../../actions/crew_devices.ts";
7 import { type Answer, good, bad, type Tool, REPO_ARG, repoArg, isAnswer } from "../shared.ts";
8
9 export const tool: Tool = {
10 name: "crew_devices",
11 doc: "`{ repo, action, device?, secret?, host_key? }`: the devices a repository's crew may SSH to, as the repository's Settings › Devices lists them: `list` answers `{ items, sessions, next_cursor }`, `add` lists `device` (`user@ipv4:port`) with the repo secret `secret` holding its key, `grant` (a site admin, never an agent) pins the host key (`host_key`, else the one the device shows now), `remove` unlists it; an admin of the repository with an admin-scope token (an agent account is refused every change; the forge's own agent speaking for a person asks first); codes `not_found`, `forbidden`, `invalid`, `no_host_key`, `no_such_device`",
12 description: "A repo's SSH devices for the crew: list, add, grant or remove. Admin.",
13 inputSchema: {
14 type: "object",
15 properties: {
16 repo: REPO_ARG,
17 action: { type: "string", enum: ["list", "add", "grant", "remove"] },
18 device: { type: "string", maxLength: 300 },
19 secret: { type: "string", maxLength: 100 },
20 host_key: { type: "string", maxLength: 2000 },
21 },
22 required: ["repo", "action"],
23 },
24 writes: true,
25 needsSwitch: "ssh",
26 needsAdminScope: true,
27 tier: "delete",
28 deletes: (args) => args["action"] === "remove",
29 where: "in the repository's Settings › Devices",
30 heldNotWhen: (args) => args["action"] === "list",
31 async run(ctx, user, args) {
32 const repo = repoArg(ctx, user, args);
33 if (isAnswer(repo)) return repo;
34 const str = (k: string): string => (typeof args[k] === "string" ? (args[k] as string) : "");
35 const refused = (error: string): Answer =>
36 error === "not_found" ? bad("not_found", "no such app or repository (owner/name)") : bad(error, error);
37 switch (args["action"]) {
38 case "list": {
39 const view = devicesView(ctx.app, user, repo);
40 return view.ok
41 ? good({ items: view.value.devices, sessions: view.value.sessions, next_cursor: null })
42 : refused(view.error);
43 }
44 case "add": {
45 const added = addCrewDevice(ctx.app, user, repo, str("device"), str("secret"));
46 return added.ok ? good(added.value) : refused(added.error);
47 }
48 case "grant": {
49 const granted = await grantCrewDevice(ctx.app, user, repo, str("device"), str("host_key"));
50 return granted.ok ? good(granted.value) : refused(granted.error);
51 }
52 case "remove": {
53 const removed = removeCrewDevice(ctx.app, user, repo, str("device"));
54 return removed.ok ? good({ removed: removed.value }) : refused(removed.error);
55 }
56 default:
57 return bad("invalid", "`action` is list, add, grant or remove");
58 }
59 },
60 };
src/http/mcp/tools/index.ts +1
@@ -54,6 +54,7 @@ export { tool as contribute } from "./contribute.ts";
5454 export { tool as converge } from "./converge.ts";
5555 export { tool as crew } from "./crew.ts";
5656 export { tool as crew_accounts } from "./crew_accounts.ts";
57 export { tool as crew_devices } from "./crew_devices.ts";
5758 export { tool as cut_wave } from "./cut_wave.ts";
5859 export { tool as data } from "./data.ts";
5960 export { tool as decisions_by } from "./decisions_by.ts";
test/conversation-ask.test.ts +15
@@ -418,6 +418,21 @@ const SAID: readonly (readonly [string, Record<string, unknown>, string])[] = [
418418 { action: "remove", id: "k1" },
419419 "Remove SSH key k1 from your account.",
420420 ],
421 [
422 "crew_devices",
423 { action: "add", device: "laptop" },
424 "List laptop as a device the crew may SSH to.",
425 ],
426 [
427 "crew_devices",
428 { action: "grant", device: "laptop" },
429 "Grant the crew SSH to laptop.",
430 ],
431 [
432 "crew_devices",
433 { action: "remove", device: "laptop" },
434 "Unlist crew device laptop.",
435 ],
421436 [
422437 "land_past_gate",
423438 { repo: "marin/cakes", number: 7, reason: "the gate is broken" },
test/delete-tier.test.ts +4
@@ -107,6 +107,10 @@ const SAMPLES: Readonly<
107107 destroys: { scope: "forge", action: "remove", name: "KEY" },
108108 spares: { scope: "forge", action: "set", name: "KEY", value: "v" },
109109 },
110 crew_devices: {
111 destroys: { repo: "alice/shop", action: "remove", device: "[email protected]:22" },
112 spares: { repo: "alice/shop", action: "add", device: "[email protected]:22", secret: "KEY" },
113 },
110114 ssh_keys: {
111115 destroys: { action: "remove", id: "k1" },
112116 spares: { action: "add", key: "ssh-ed25519 AAAA" },
test/mcp-args.test.ts +1 −4
@@ -20,9 +20,6 @@ quietLogs();
2020 /** Tools whose schema names no properties, so there is nothing to hold their arguments to. */
2121 const SCHEMALESS = ["backups_test"];
2222
23 /** Tools offered only behind a switch this forge has off (`needsSwitch`: SSH). */
24 const HIDDEN = ["ssh_keys"];
25
2623 /** Tools whose schema says `additionalProperties: true`. */
2724 const OPEN = ["spawn"];
2825
@@ -114,7 +111,7 @@ test("over /mcp, every tool refuses its first property given the wrong type, and
114111 }
115112 expect(open).toEqual(SCHEMALESS);
116113 // Tools this admin token is not offered answer as no such tool, the schema unread.
117 expect(hidden).toEqual(HIDDEN);
114 expect(hidden).toEqual(TOOLS.filter((t) => t.needsSwitch !== undefined).map((t) => t.name));
118115 // A first property whose schema takes any value cannot be given a wrong one: named, so none is
119116 // added unseen.
120117 expect(untyped).toEqual([]);
test/mcp-crew-devices.test.ts added +176
@@ -0,0 +1,176 @@
1 /**
2 * The `crew_devices` tool is …/crew-devices over MCP (#3685): the same actions and the same
3 * refusals: a repository admin lists, adds and removes, only a site admin grants, others see
4 * nothing.
5 */
6 import { setSsh } from "../src/settings/ssh.ts";
7 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
8 import { mkdtemp, rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { createApp, type App } from "../src/app.ts";
12 import { createRepo } from "../src/actions/repos.ts";
13 import { createToken } from "../src/core/tokens.ts";
14 import { mintViaToken } from "../src/core/via_token.ts";
15 import { createUser, getUserByName, type User } from "../src/core/users.ts";
16 import { serve, type Servers } from "../src/http/server.ts";
17 import { quietLogs } from "./helpers/globals.ts";
18 import { promote } from "./helpers/members.ts";
19
20 quietLogs();
21
22 const PI = "[email protected]:22";
23 const HOST_KEY = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIFakeHostKeyFakeHostKeyFakeHostKey1234";
24
25 describe("MCP crew_devices", () => {
26 let dataDir: string;
27 let app: App;
28 let servers: Servers;
29 let ada = "";
30 let cy = "";
31 let cyRo = "";
32 let bob = "";
33 let id = 1;
34
35 const rpc = async (token: string, method: string, params: unknown = {}): Promise<any> =>
36 (
37 await fetch(`${servers.url}/mcp`, {
38 method: "POST",
39 headers: {
40 "content-type": "application/json",
41 accept: "application/json, text/event-stream",
42 authorization: `Bearer ${token}`,
43 },
44 body: JSON.stringify({ jsonrpc: "2.0", id: id++, method, params }),
45 })
46 ).json();
47 const listedTools = async (token: string): Promise<string[]> => {
48 const names: string[] = [];
49 let cursor: string | undefined;
50 do {
51 const body = await rpc(token, "tools/list", { all: true, ...(cursor === undefined ? {} : { cursor }) });
52 names.push(...(body.result.tools as { name: string }[]).map((t) => t.name));
53 cursor = body.result.nextCursor;
54 } while (cursor !== undefined);
55 return names;
56 };
57
58 const call = async (token: string, args: unknown) => {
59 const res = await fetch(`${servers.url}/mcp`, {
60 method: "POST",
61 headers: {
62 "content-type": "application/json",
63 accept: "application/json, text/event-stream",
64 authorization: `Bearer ${token}`,
65 },
66 body: JSON.stringify({
67 jsonrpc: "2.0",
68 id: id++,
69 method: "tools/call",
70 params: { name: "crew_devices", arguments: args },
71 }),
72 });
73 const body = (await res.json()) as any;
74 // A tool this caller is not shown answers as a JSON-RPC error: no such tool.
75 const text: string = body.result?.content?.[0]?.text ?? body.error?.message ?? "";
76 return { text, isError: body.result?.isError === true || body.error !== undefined };
77 };
78
79 beforeAll(async () => {
80 dataDir = await mkdtemp(join(tmpdir(), "forge-mcp-devices-"));
81 app = createApp({ dataDir, port: 0, host: "forge.test" });
82 servers = await serve(app);
83 const make = async (username: string, extra: { adminIfFirst?: boolean } = {}): Promise<User> => {
84 const made = await createUser(app.db, {
85 origin: "seed",
86 trusted: true,
87 username,
88 email: `${username}@forge.local`,
89 password: "a-good-passphrase",
90 ...extra,
91 });
92 if (!made.ok) throw new Error(made.error);
93 return made.value;
94 };
95 setSsh(app.db, true, "test");
96 const a = await make("ada", { adminIfFirst: true });
97 const c = await make("cy");
98 promote(app.db, c);
99 const b = await make("bob");
100 const made = await createRepo(app, c, { name: "arm", visibility: "public", description: "" });
101 if (!made.ok) throw new Error(String(made.error));
102 ada = createToken(app.db, a.id, "admin", "admin").token;
103 cy = createToken(app.db, c.id, "admin", "admin").token;
104 cyRo = createToken(app.db, c.id, "ro", "ro").token;
105 bob = createToken(app.db, b.id, "admin", "admin").token;
106 }, 60_000);
107
108 afterAll(async () => {
109 await servers.stop();
110 await rm(dataDir, { recursive: true, force: true });
111 });
112
113 test("the owner adds, lists and removes; a bad device is invalid", async () => {
114 const bad = await call(cy, { repo: "cy/arm", action: "add", device: "[email protected]/8:22", secret: "K" });
115 expect(bad.isError).toBe(true);
116 expect(bad.text).toContain("invalid");
117 const added = await call(cy, { repo: "cy/arm", action: "add", device: PI, secret: "ARM_KEY" });
118 expect(added.isError).toBe(false);
119 expect(JSON.parse(added.text)).toMatchObject({ entry: PI, secret: "ARM_KEY", granted: false });
120 const listed = JSON.parse((await call(cy, { repo: "cy/arm", action: "list" })).text);
121 expect(listed.items.map((d: any) => d.entry)).toEqual([PI]);
122 expect(listed.sessions).toEqual([]);
123 const gone = await call(cy, { repo: "cy/arm", action: "remove", device: PI });
124 expect(JSON.parse(gone.text)).toEqual({ removed: PI });
125 expect((await call(cy, { repo: "cy/arm", action: "remove", device: PI })).text).toContain("no_such_device");
126 });
127
128 test("only a site admin grants, pinning the host key given", async () => {
129 await call(cy, { repo: "cy/arm", action: "add", device: PI, secret: "ARM_KEY" });
130 const byOwner = await call(cy, { repo: "cy/arm", action: "grant", device: PI, host_key: HOST_KEY });
131 expect(byOwner.isError).toBe(true);
132 expect(byOwner.text).toContain("forbidden");
133 const granted = await call(ada, { repo: "cy/arm", action: "grant", device: PI, host_key: HOST_KEY });
134 expect(JSON.parse(granted.text)).toMatchObject({ entry: PI, granted: true, hostKey: HOST_KEY, grantedBy: "ada" });
135 const refused = await call(ada, { repo: "cy/arm", action: "grant", device: PI, host_key: "nonsense" });
136 expect(refused.text).toContain("no_host_key");
137 });
138
139 test("anyone else sees nothing, and a read-only token is refused", async () => {
140 const other = await call(bob, { repo: "cy/arm", action: "list" });
141 expect(other.isError).toBe(true);
142 expect(other.text).toContain("not_found");
143 const ro = await call(cyRo, { repo: "cy/arm", action: "list" });
144 expect(ro.isError).toBe(true);
145 expect(ro.text).toContain("no tool named crew_devices");
146 expect((await call(cy, { repo: "cy/arm", action: "nope" })).isError).toBe(true);
147 });
148
149 test("a read-only token is not shown the tool; an admin-scope token is", async () => {
150 expect(await listedTools(cyRo)).not.toContain("crew_devices");
151 expect(await listedTools(cy)).toContain("crew_devices");
152 });
153
154 test("with the SSH switch off the tool is unlisted and refused, and back on it answers", async () => {
155 setSsh(app.db, false, "test");
156 try {
157 expect(await listedTools(cy)).not.toContain("crew_devices");
158 const refused = await call(cy, { repo: "cy/arm", action: "list" });
159 expect(refused.isError).toBe(true);
160 expect(refused.text).toContain("crew_devices");
161 } finally {
162 setSsh(app.db, true, "test");
163 }
164 expect((await call(cy, { repo: "cy/arm", action: "list" })).isError).toBe(false);
165 });
166
167 test("the forge's agent, speaking for a site admin, is held for a yes and nothing is listed", async () => {
168 const ada = getUserByName(app.db, "ada")!;
169 const via = mintViaToken(app.db, ada.id, "conversation:devices", "", new Date(Date.now() + 600_000).toISOString());
170 if (!via.ok) throw new Error(via.error);
171 const held = await call(via.value.token, { repo: "cy/arm", action: "add", device: "[email protected]:22", secret: "ARM_KEY" });
172 expect(held.text).toContain("needs_confirm");
173 const listed = JSON.parse((await call(cy, { repo: "cy/arm", action: "list" })).text);
174 expect(listed.items.map((d: any) => d.entry)).not.toContain("[email protected]:22");
175 });
176 });
test/mcp-doc-matches-tools.test.ts +4 −3
@@ -76,8 +76,9 @@ function documented(): string[] {
7676
7777 test("the rendered roster has a row for every tool tools/list names, and no other", async () => {
7878 const names = new Set(await listed());
79 // `ssh_keys` waits on the SSH switch, which is off here; the doc keeps its row.
80 const rows = new Set(documented().filter((n) => n !== "ssh_keys"));
79 // A tool that waits on the SSH switch, which is off here, keeps its doc row.
80 const switched = (await loadMcp()).TOOLS.filter((t) => t.needsSwitch !== undefined).map((t) => t.name);
81 const rows = new Set(documented().filter((n) => !switched.includes(n)));
8182 expect(names.size).toBeGreaterThan(100);
8283 expect([...names].filter((n) => !rows.has(n)).map((n) => `${n} is listed but not in the roster`)).toEqual([]);
8384 expect([...rows].filter((n) => !names.has(n)).map((n) => `${n} is in the roster but not listed`)).toEqual([]);
@@ -114,7 +115,7 @@ test("the well-known card's count follows the registry: a tool added changes it,
114115 const real = [...mcp.TOOLS, mcp.REPORT_TOOL, mcp.START_TOOL, mcp.OFFER_TOOL];
115116 // The registry itself, not a hand-made list: its distinct names, less the one the SSH switch
116117 // hides.
117 const expected = new Set(real.map((t) => t.name).filter((n) => n !== "ssh_keys")).size;
118 const expected = new Set((real as { name: string; needsSwitch?: "ssh" }[]).filter((t) => t.needsSwitch === undefined).map((t) => t.name)).size;
118119 const before = (await card()).tools.count;
119120 expect(before).toBe(expected);
120121 try {
test/mcp-door.test.ts +1 −1
@@ -42,7 +42,7 @@ test("answers the door, cached five minutes, with the security floor", async ()
4242 test("the count equals the tools mcp.json lists and the endpoints equal the OAuth metadata", async () => {
4343 const door = (await (await fetch(`${base}/.well-known/mcp`)).json()) as any;
4444 const card = (await (await fetch(`${base}/.well-known/mcp.json`)).json()) as any;
45 const live = [...TOOLS, REPORT_TOOL, START_TOOL, OFFER_TOOL].filter((t) => t.name !== "ssh_keys" || sshOn(app.db));
45 const live = ([...TOOLS, REPORT_TOOL, START_TOOL, OFFER_TOOL] as { needsSwitch?: "ssh" }[]).filter((t) => t.needsSwitch === undefined || sshOn(app.db));
4646 expect(door.tools).toBe(live.length);
4747 expect(card.tools.length).toBe(live.length);
4848 expect(door.tools).toBeGreaterThan(0);
test/mcp-write-scope.test.ts +1
@@ -43,6 +43,7 @@ const ADMIN_ARGS: Record<string, Record<string, unknown>> = {
4343 backups_destination: { action: "set", bucket: "forge-snaps", accessKey: "AKIA", secretKey: "s3cr3t-key-0123456789" },
4444 backups_test: { endpoint: "http://127.0.0.1:1", bucket: "b", accessKey: "AKIA", secretKey: "s3cr3t-key-0123456789" },
4545 rollback: { sha: "a".repeat(40), dryRun: false },
46 crew_devices: { repo: "alice/game", action: "remove", device: "[email protected]:22" },
4647 };
4748
4849 /**
test/mixed-actions-held.test.ts +1
@@ -53,6 +53,7 @@ const MIXED: Readonly<
5353 proposal_tokens: { key: "verb", reads: [{ verb: "list" }] },
5454 app_flags: { key: "action", reads: [{ repo: "o/r", action: "list" }] },
5555 app_env: { key: "action", reads: [{ repo: "o/r", action: "list" }] },
56 crew_devices: { key: "action", reads: [{ repo: "o/r", action: "list" }] },
5657 drop: { key: "action", reads: [{ repo: "o/r", action: "list" }] },
5758 origins: {
5859 key: "action",
test/talk-reads-not-held.test.ts +1
@@ -44,6 +44,7 @@ const ON_PURPOSE: Readonly<Record<string, string>> = {
4444 sessions: "needs an admin-scope token, as hooks does",
4545 prompts: "needs an admin-scope token, as hooks does",
4646 invites: "its list needs an admin-scope token, as hooks does",
47 crew_devices: "needs an admin-scope token, as hooks does",
4748 hooks:
4849 "needs an admin-scope token: the agent's rw token reaches it only through the person's yes",
4950 };

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs