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

MCP `mirror_now`: bring the off-box mirror level now, as the Backups page's button does, for a forge admin #5450

Parked opened this
Closed without merging

scout/forge:scout/5423-mcp-mirror-now-bring-the-off-box-mirror → main 6 commits fork 4 threads · 4 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
4 files changed +187 −0
docs/MCP.md +1
@@ -82,6 +82,7 @@ for a tunnel and a forge that sleeps.
8282 | `migrate` | `{ url, name?, crew? }` brings a public repository in by URL (history only; nothing reaches back) and answers `{ job, state, url }`; `{ job }` alone reads that job. Same validation, scope (`rw`) and private-address refusal as `POST /api/v1/migrate` | yes |
8383 | `milestones` | `{ app, issue? }`: how far each thing asked for is (and, with `issue`, whether you watch it: `watching`), from the dependency tree: the plan's limbs with their weights, or one milestone opened (who is building, what is blocked and on what, what merged in 7 days, an estimate, and for an owner `spend`: dollars, changes landed ever, the costliest three issues) | |
8484 | `mint_invite` | `{ days? }`: mint a single-use invite link that expires in `days` (1–30, default 7) and is shown once; a person admin's, with an admin token | yes |
85 | `mirror_now` | `{}` (forge admin, admin token): bring the off-box mirror level now, as the Backups page's button does; answers `{ level, newest?, error?, says }` | yes |
8586 | `mirror_set` | `{ action, endpoint?, bucket?, region?, accessKey?, secretKey? }` (forge admin, admin-scope token): `set` seals the off-box snapshot mirror, `forget` clears it; the Backups page's rules and refusals, a blank field keeps what was sealed; answers `{ place, says }`, never a key | yes |
8687 | `new_app` | `{ name, description?, owner?, visibility?, agent?, pick? }`: make an app from a sentence; answers `{ repo, url, issue, agent, run }` (`run` is the first run's state, or `none`) and draws the `ui://forge/app` card: name, production URL, first issue, agent, first run; refused as `POST /api/v1/apps` is (unverified, app_limit, no_such_agent, name_taken) | yes |
8788 | `next_steps` | on a spawned forge, your first three steps and whether each is done; empty elsewhere or for anyone but its owner | |
src/http/mcp/tools/index.ts +1
@@ -64,6 +64,7 @@ export { tool as map } from "./map.ts";
6464 export { tool as migrate } from "./migrate.ts";
6565 export { tool as milestones } from "./milestones.ts";
6666 export { tool as mint_invite } from "./mint_invite.ts";
67 export { tool as mirror_now } from "./mirror_now.ts";
6768 export { tool as mirror_set } from "./mirror_set.ts";
6869 export { tool as model_ceiling } from "./model_ceiling.ts";
6970 export { tool as model_grant } from "./model_grant.ts";
src/http/mcp/tools/mirror_now.ts added +35
@@ -0,0 +1,35 @@
1 import { snapshotsOf } from "../../../snapshot/service.ts";
2 import { good, type Tool } from "../shared.ts";
3
4 export const tool: Tool = {
5 name: "mirror_now",
6 doc: "`{}` (forge admin, admin token): bring the off-box mirror level now, as the Backups page's button does; answers `{ level, newest?, error?, says }`",
7 description: "Level the off-box mirror now (admin).",
8 inputSchema: { type: "object", properties: {} },
9 writes: true,
10 adminOnly: true,
11 needsAdminScope: true,
12 async run(ctx) {
13 const state = await snapshotsOf(ctx.app)?.mirrorNow();
14 if (state === undefined)
15 return good({ level: false, says: "This forge has no mirror to bring level." });
16 if (state.sourceError !== undefined)
17 return good({
18 level: false,
19 error: state.sourceError,
20 says: `The snapshots could not be read from the destination, so the mirror was not touched: ${state.sourceError}`,
21 });
22 if (state.failingSince === undefined)
23 return good({
24 level: true,
25 ...(state.newest ? { newest: state.newest } : {}),
26 says: `The mirror is level${state.newest ? ` at ${state.newest}` : ""}.`,
27 });
28 return good({
29 level: false,
30 ...(state.newest ? { newest: state.newest } : {}),
31 error: state.error ?? "unknown reason",
32 says: `The mirror is not level: ${state.error ?? "unknown reason"}`,
33 });
34 },
35 };
test/mcp-mirror-now.test.ts added +150
@@ -0,0 +1,150 @@
1 /** `mirror_now` is the Backups page's "bring the mirror level" button over MCP, for a forge admin. */
2 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
3 import { mkdtempSync, rmSync } from "node:fs";
4 import { tmpdir } from "node:os";
5 import { join } from "node:path";
6 import { createApp, type App } from "../src/app.ts";
7 import { createToken } from "../src/core/tokens.ts";
8 import { createUser } from "../src/core/users.ts";
9 import { serve, type Servers } from "../src/http/server.ts";
10 import { startSnapshots, type SnapshotsHandle } from "../src/snapshot/service.ts";
11 import { dirStore, type Store } from "../src/snapshot/store.ts";
12
13 /** A store that can be switched off: while `down`, every call fails like an unreachable host. */
14 function switchable(inner: Store): { store: Store; down: boolean } {
15 const me = { down: false, store: undefined as unknown as Store };
16 const guard = <A extends unknown[], R>(fn: (...a: A) => Promise<R>) => async (...a: A): Promise<R> => {
17 if (me.down) throw new Error("connection refused");
18 return fn(...a);
19 };
20 me.store = {
21 where: inner.where,
22 put: guard(inner.put),
23 get: guard(inner.get),
24 list: guard(inner.list),
25 names: guard(inner.names),
26 delete: guard(inner.delete),
27 };
28 return me;
29 }
30
31 describe("MCP mirror_now", () => {
32 let root: string;
33 let app: App;
34 let servers: Servers;
35 let svc: SnapshotsHandle | undefined;
36 let admin: string;
37 let bob: string;
38 let rw: string;
39 let n = 1;
40
41 const call = async (token: string) => {
42 const res = await fetch(`${servers.url}/mcp`, {
43 method: "POST",
44 headers: {
45 "content-type": "application/json",
46 accept: "application/json, text/event-stream",
47 authorization: `Bearer ${token}`,
48 },
49 body: JSON.stringify({
50 jsonrpc: "2.0",
51 id: n++,
52 method: "tools/call",
53 params: { name: "mirror_now", arguments: {} },
54 }),
55 });
56 const body: any = await res.json();
57 if (body.error) return { error: body.error.message as string };
58 const text: string = body.result.content[0].text;
59 return body.result.isError === true ? { error: text } : { value: JSON.parse(text) };
60 };
61
62 beforeAll(async () => {
63 root = mkdtempSync(join(tmpdir(), "forge-mcp-mirror-now-"));
64 app = createApp({ dataDir: root, port: 0 });
65 const mk = async (username: string, first: boolean) => {
66 const u = await createUser(app.db, {
67 origin: "seed", trusted: true, username,
68 email: `${username}@forge.local`, password: "a-good-passphrase", adminIfFirst: first,
69 });
70 if (!u.ok) throw new Error(u.error);
71 return u.value;
72 };
73 const alice = await mk("alice", true);
74 const b = await mk("bob", false);
75 admin = createToken(app.db, alice.id, "a", "admin").token;
outdated

This passes on any failure, not just a refusal. Assert r.error is defined. Also add an rw-scope admin token case that must be refused (it fails today; see the comment on mcp.ts).

76 rw = createToken(app.db, alice.id, "rw", "rw").token;
77 bob = createToken(app.db, b.id, "b", "admin").token;
78 servers = await serve(app);
79 }, 30_000);
80
81 afterAll(async () => {
82 servers.stop();
83 await svc?.stop();
84 app.close();
85 rmSync(root, { recursive: true, force: true });
86 });
87
88 test("no mirror answers the page's sentence", async () => {
89 const r: any = await call(admin);
90 expect(r.value).toEqual({ level: false, says: "This forge has no mirror to bring level." });
91 });
92
93 test("a non-admin is refused", async () => {
94 const r: any = await call(bob);
95 expect(r.value).toBeUndefined();
96 expect(r.error).toBeDefined();
97 });
98
99 test("an rw token of an admin is refused, and the tool is not listed", async () => {
100 const r: any = await call(rw);
101 expect(r.value).toBeUndefined();
outdated

Only the success case is tested. Add a case where the mirror fails, so level is false, error is set and says reads "The mirror is not level: …". Add one for the unreadable source if you can.

102 expect(r.error).toBeDefined();
103 const list = async (token: string) => {
104 const res = await fetch(`${servers.url}/mcp`, {
105 method: "POST",
106 headers: {
107 "content-type": "application/json",
108 accept: "application/json, text/event-stream",
109 authorization: `Bearer ${token}`,
110 },
111 body: JSON.stringify({ jsonrpc: "2.0", id: n++, method: "tools/list" }),
112 });
113 return ((await res.json()) as any).result.tools.map((t: any) => t.name) as string[];
114 };
115 expect(await list(rw)).not.toContain("mirror_now");
116 expect(await list(admin)).toContain("mirror_now");
117 });
118
119 const primary = () => switchable(dirStore(join(root, "store")));
120 let src: ReturnType<typeof switchable>;
121 let dst: ReturnType<typeof switchable>;
122
123 test("with a local destination and mirror, it reports level", async () => {
124 src = primary();
125 dst = switchable(dirStore(join(root, "offbox")));
126 svc = startSnapshots(app, src.store, { version: "t", nightly: false, mirror: dst.store });
127 const r: any = await call(admin);
128 expect(r.value.level).toBe(true);
129 expect(r.value.says).toStartWith("The mirror is level");
130 });
131
132 test("a mirror that cannot be reached is not level, and says why", async () => {
133 dst.down = true;
134 const r: any = await call(admin);
135 dst.down = false;
136 expect(r.value.level).toBe(false);
137 expect(r.value.error).toContain("connection refused");
138 expect(r.value.says).toStartWith("The mirror is not level: ");
139 expect(r.value.says).toContain("connection refused");
140 });
141
142 test("a primary that cannot be read leaves the mirror untouched, and says so", async () => {
143 src.down = true;
144 const r: any = await call(admin);
145 src.down = false;
146 expect(r.value.level).toBe(false);
147 expect(r.value.error).toContain("connection refused");
148 expect(r.value.says).toStartWith("The snapshots could not be read from the destination, so the mirror was not touched: ");
149 });
150 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs