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

An agent scales, moves or turns an .stl through the MCP with the same words as the page #15893

Merged opened this

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

Merged

torque/forge:torque/15823-an-agent-scales-moves-or-turns-an-stl-th → main 0 commits fork 3 threads · 3 unresolved

  • Merged. torque/15823-an-agent-scales-moves-or-turns-an-stl-th was merged into main as a247c98.

Review

Sign in to review this change.
3 files changed +207 −3
docs/features/file-stl.md +3 −1
@@ -39,6 +39,8 @@ The first paint carries the triangle count and box, read by the server, so they
3939 - The server reads the whole file, up to 20 MB, for the first paint, so the facts show with JavaScript off at any size the page opens.
4040 - Try it: commit a `.stl` to a repository and open its file page.
4141
42 Pinned by `test/mesh-edit.test.ts` (the transform, the form, the commit, the protected branch, the terminal), `test/render-stl.test.ts`, `test/model3d.test.ts`, `test/tui-model3d.test.ts` (the `m` key) and
42 Pinned by `test/mesh-edit.test.ts` (the transform, the form, the commit, the protected branch, the terminal), `test/mcp-mesh-edit.test.ts` (the MCP tool: preview, commit, the pull on a protected default, the refusals), `test/render-stl.test.ts`, `test/model3d.test.ts`, `test/tui-model3d.test.ts` (the `m` key) and
4343 `test/model-edit-refusal.test.ts` (the edit page's sentence). The crosshair's keydown and the pointer wiring in
4444 `model3d-client.ts` have no DOM test; the rules they call are pinned in `test/model-measure.test.ts`. The viewer's neighbours: [mesh-files.md](mesh-files.md).
45
46 An agent does the same through the MCP `write_file` tool: `mesh: { scale, move, turn }` on an .stl path previews the new Box, and `dryRun: false` commits it with the page's commit subject and receipt words.

Name test/mcp-mesh-edit.test.ts in the 'Pinned by' paragraph above.

src/http/mcp/tools/write_file.ts +62 −2
@@ -3,11 +3,68 @@ import { runGit } from "../../../git/env.ts";
33 import { isSafeRef } from "../../../git/guard.ts";
44 import { editMessage } from "../../../actions/edit_words.ts";
55 import { commitToBranch } from "../../../actions/repos.ts";
6 import { editMesh, isStlPath, type MeshForm } from "../../../actions/mesh_edit.ts";
7 import { sizeText } from "../../../web/render/mesh.ts";
68 import { good, bad, type Tool, REPO_ARG, repoArg, isAnswer } from "../shared.ts";
79
10 const AXES = ["x", "y", "z"];
11 const text = (v: unknown): string => (typeof v === "number" && Number.isFinite(v) ? String(v) : "");
12
13 /** The `mesh` object as the file page's form text; `editMesh` bounds every number. */
14 function meshForm(branch: string, path: string, mesh: Record<string, unknown>): MeshForm | string {
15 const { scale, move, turn } = mesh;
16 const f = { ref: branch, path, factor: "", sizeAxis: "", size: "", dx: "", dy: "", dz: "", turn: "" };
17 if (scale !== undefined) {
18 const s = scale as { axis?: unknown; size?: unknown } | null;
19 if (typeof scale === "number") f.factor = text(scale);
20 else if (s !== null && typeof s === "object" && AXES.includes(s.axis as string) && text(s.size) !== "") {
21 f.sizeAxis = s.axis as string;
22 f.size = text(s.size);
23 } else return "scale is a factor, or { axis, size }";
24 if ((f.factor || f.size) === "") return "scale is a finite number";
25 }
26 if (move !== undefined) {
27 if (!Array.isArray(move) || move.length !== 3 || move.some((v) => text(v) === "")) return "move is [x, y, z], three numbers";
28 [f.dx, f.dy, f.dz] = move.map(text) as [string, string, string];
29 }
30 if (turn !== undefined) {
31 if (!AXES.includes(turn as string)) return "turn is \"x\", \"y\" or \"z\"";
32 f.turn = turn as string;
33 }
34 return f;
35 }
36
37 async function meshRun(ctx: Parameters<Tool["run"]>[0], user: Parameters<Tool["run"]>[1], repo: Parameters<typeof editMesh>[2], args: Record<string, unknown>) {
38 const { branch, path, mesh } = args;
39 if (typeof branch !== "string" || typeof path !== "string" || mesh === null || typeof mesh !== "object" || Array.isArray(mesh))
40 return bad("invalid", "branch and path are strings, mesh an object");
41 if (args["content"] !== undefined) return bad("invalid", "send mesh or content, not both");
42 if (!isStlPath(path)) return bad("invalid", "mesh changes an .stl path only");
43 const form = meshForm(branch, path, mesh as Record<string, unknown>);
44 if (typeof form === "string") return bad("invalid", form);
45 const save = args["dryRun"] === false;
46 const done = await editMesh(ctx.app, user, repo, form, save);
47 if (!done.ok) {
48 const e = done.error;
49 if (typeof e === "string") return bad(e, e === "not_found" ? "no such repository" : "this is not yours to write");
50 if (e.kind === "refused") return bad("refused", e.why);
51 if (e.kind === "missing") return bad("not_found", "no such branch or file");
52 return bad(e.kind, editMessage(e.kind));
53 }
54 const { edited, message, landed } = done.value;
55 const box = sizeText(edited.box.size, "units");
56 const base = { triangles: edited.triangles, box, message };
57 // The page's words: "The new Box" to preview, "Committed to <branch>" after.
58 if (landed === undefined) return good({ says: `The new Box: ${box}. ${message}. Send dryRun: false to commit it.`, ...base });
59 const says = landed.pull !== undefined
60 ? `Committed to ${landed.branch} and opened this pull request.`
61 : `Committed to ${landed.branch}.`;
62 return good({ says, ...base, commit: landed.commit.commitOid, branch: landed.branch, ...(landed.pull !== undefined ? { pull: landed.pull.number } : {}) });
63 }
64
865 export const tool: Tool = {
966 name: "write_file",
10 doc: "`{ repo, branch, path, content, message }`: commit one file to an existing branch as `POST …/contents` does, for the same callers and with the same refusals (protected default, too large, a path with `..`), said in `edit_words`' sentences; answers `{ commit, says }`",
67 doc: "`{ repo, branch, path, content, message, mesh?, dryRun? }` (`content` and `message` are required unless `mesh` is sent): commit one file to an existing branch as `POST …/contents` does, for the same callers and with the same refusals (protected default, too large, a path with `..`), said in `edit_words`' sentences; answers `{ commit, says }`. On an .stl, `mesh: { scale?: factor | { axis, size }, move?: [x, y, z], turn?: \"x\"|\"y\"|\"z\" }` (not `content`) scales, moves and turns it as the file page does: it previews the new Box unless `dryRun` is false, which commits it",
1168 description: "No shell? Commit one file to a branch. With a shell, clone and push.",
1269 inputSchema: {
1370 type: "object",
@@ -17,13 +74,16 @@ export const tool: Tool = {
1774 path: { type: "string" },
1875 content: { type: "string" },
1976 message: { type: "string" },
77 mesh: { type: "object" },
78 dryRun: { type: "boolean" },
2079 },
21 required: ["repo", "branch", "path", "content", "message"],
80 required: ["repo", "branch", "path"],
2281 },
2382 writes: true,
2483 async run(ctx, user, args) {
2584 const repo = repoArg(ctx, user, args);
2685 if (isAnswer(repo)) return repo;
86 if (args["mesh"] !== undefined) return meshRun(ctx, user, repo, args);
2787 const { branch, path, content, message } = args;
2888 if (
2989 typeof branch !== "string" ||
test/mcp-mesh-edit.test.ts added +142
@@ -0,0 +1,142 @@
1 /**
2 * MCP `write_file` with `mesh`: preview the new Box, commit it, and read the committed file's Box
3 * back.
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 { createApp, type App } from "../src/app.ts";
10 import { commitToBranch, createRepo as createRepoAs } from "../src/actions/repos.ts";
11 import { addTeamMember, createOrg, createTeam } from "../src/core/orgs.ts";
12 import { createRepo, getRepo, updateRepoSettings } from "../src/core/repos.ts";
13 import { createToken } from "../src/core/tokens.ts";
14 import { createUser } from "../src/core/users.ts";
15 import { READ_ONLY_REFUSAL } from "../src/http/mcp/hints.ts";
16 import { serve, type Servers } from "../src/http/server.ts";
outdated

Second import from ../src/core/repos.ts (getRepo): merge it with the createRepo import on line 12.

17 import { localSource } from "../src/view/local.ts";
18 import { readStl } from "../src/web/render/stl.ts";
19 import { quietLogs } from "./helpers/globals.ts";
20
21 quietLogs();
22
23 const STL = new TextEncoder().encode(`solid t
24 facet normal 0 0 1
25 outer loop
26 vertex 0 0 0
27 vertex 10 0 0
28 vertex 10 20 30
29 endloop
30 endfacet
31 endsolid t
32 `);
33
34 let dataDir: string;
35 let app: App;
36 let servers: Servers;
37 let rw = "";
38 let ro = "";
39 let bob = "";
40
41 const ok = <T>(r: { ok: true; value: T } | { ok: false; error: unknown }): T => {
42 if (!r.ok) throw new Error(JSON.stringify(r.error));
43 return r.value;
44 };
45
46 async function call(token: string, args: unknown): Promise<{ error?: string; value?: any }> {
47 const rpc = { jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "write_file", arguments: args } };
48 const headers = new Headers({ "content-type": "application/json", accept: "application/json, text/event-stream" });
49 headers.set("authorization", `Bearer ${token}`);
50 const reply = await fetch(`${servers.url}/mcp`, { method: "POST", headers, body: JSON.stringify(rpc) });
51 const { isError, content } = ((await reply.json()) as any).result;
52 return isError ? { error: content[0].text } : { value: JSON.parse(content[0].text) };
53 }
54
55 const boxAt = async (branch: string): Promise<string> => {
56 const repo = getRepo(app.db, "ada", "pub")!;
57 const blob = await localSource(app, repo, undefined).blob(branch, "a.stl");
58 const body = (blob as any).value.body as Uint8Array;
59 const r = readStl(body);
60 if ("error" in r) throw new Error(r.error);
61 return r.size;
62 };
63
64 beforeAll(async () => {
65 dataDir = await mkdtemp(join(tmpdir(), "forge-mcp-mesh-"));
66 app = createApp({ dataDir, port: 0 });
67 servers = await serve(app);
68 const owner = ok(await createUser(app.db, { origin: "seed", trusted: true, username: "ada", email: "[email protected]", password: "a-good-passphrase" }));
69 const repo = ok(await createRepo(app.db, app.reposRoot, { ownerId: owner.id, name: "pub", visibility: "public" }));
70 ok(await commitToBranch(app, owner, repo, { message: "seed", files: [{ path: "a.txt", content: "one\n" }] }));
71 ok(await commitToBranch(app, owner, repo, { branch: "work", message: "stl", files: [{ path: "a.stl", content: STL }] }));
72 // An ordinary writer on a repository whose default branch is protected: a save becomes a branch
73 // and a pull.
74 const other = ok(await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase" }));
75 const org = ok(createOrg(app.db, "acme", owner.id));
76 const devs = ok(createTeam(app.db, org.id, "devs", "write"));
77 addTeamMember(app.db, devs, owner.id);
78 addTeamMember(app.db, devs, other.id);
79 app.db.query("UPDATE user SET is_admin = 1 WHERE id = ?1").run(owner.id);
80 const guarded = ok(await createRepoAs(app, { ...owner, isAdmin: true }, { name: "guarded", owner: "acme", visibility: "public" }));
81 ok(await commitToBranch(app, owner, guarded, { message: "stl", files: [{ path: "a.stl", content: STL }] }));
82 updateRepoSettings(app.db, guarded, { protectDefault: true });
83 bob = createToken(app.db, other.id, "bob", "rw").token;
84 rw = createToken(app.db, owner.id, "rw", "rw").token;
85 ro = createToken(app.db, owner.id, "ro", "ro").token;
86 }, 30_000);
87
88 afterAll(async () => {
89 servers?.stop();
90 app?.close();
91 await rm(dataDir, { recursive: true, force: true });
92 });
93
94 const base = { repo: "ada/pub", branch: "work", path: "a.stl" };
95
96 test("mesh without dryRun:false previews the new Box and writes nothing", async () => {
97 const r = await call(rw, { ...base, mesh: { scale: 2 } });
98 expect(r.value.box).toBe("20 × 40 × 60 units");
99 expect(r.value.says).toContain("The new Box: 20 × 40 × 60 units");
100 expect(await boxAt("work")).toBe("10 × 20 × 30 units");
101 });
102
103 test("dryRun:false commits, and the committed file has the new Box", async () => {
104 const r = await call(rw, { ...base, mesh: { scale: 2, turn: "z", move: [1, 0, 0] }, dryRun: false });
105 expect(r.value.says).toBe("Committed to work.");
106 expect(r.value.message).toBe("a.stl: scale ×2, turn 90° about z, move 1, 0, 0");
107 expect(await boxAt("work")).toBe("40 × 20 × 60 units");
outdated

These two only assert toBeDefined(). Assert the specific refusal (not_found for the branch, the scope/forbidden refusal for the ro token), and add a case where the default branch is protected so the 'opened this pull request' receipt and pull are pinned.

108 });
109
110 test("scale to a size along an axis", async () => {
111 const r = await call(rw, { ...base, mesh: { scale: { axis: "z", size: 30 } } });
112 expect(r.value.box).toBe("20 × 10 × 30 units");
113 });
114
115 test("refusals: content with mesh, a non-stl, bad numbers, a read-only token", async () => {
116 expect((await call(rw, { ...base, content: "x", mesh: { scale: 2 } })).error).toContain("not both");
117 expect((await call(rw, { ...base, path: "a.txt", mesh: { scale: 2 } })).error).toContain(".stl");
118 expect((await call(rw, { ...base, mesh: { scale: "big" } })).error).toContain("scale");
119 expect((await call(rw, { ...base, mesh: { move: [1, 2] } })).error).toContain("move");
120 expect((await call(rw, { ...base, mesh: { scale: 0 } })).error).toContain("scale");
121 expect((await call(rw, { ...base, content: undefined, branch: "nope", mesh: { scale: 2 } })).error).toContain("not_found");
122 });
123
124 test("a read-only token is refused the preview as well as the commit", async () => {
125 const preview = await call(ro, { ...base, mesh: { scale: 2 } });
126 const save = await call(ro, { ...base, mesh: { scale: 2 }, dryRun: false });
127 expect(preview.error).toBe(READ_ONLY_REFUSAL);
128 expect(save.error).toBe(READ_ONLY_REFUSAL);
129 expect(await boxAt("work")).toBe("40 × 20 × 60 units");
130 });
131
132 test("without mesh, content and message are still required", async () => {
133 expect((await call(rw, { ...base, content: "x" })).error).toContain("invalid: branch, path, content and message are strings");
134 expect((await call(rw, base)).error).toContain("invalid: branch, path, content and message are strings");
135 });
136
137 test("on a protected default an ordinary writer's commit opens a pull", async () => {
138 const r = await call(bob, { repo: "acme/guarded", branch: "main", path: "a.stl", mesh: { scale: 3 }, dryRun: false });
139 expect(r.value.says).toBe(`Committed to ${r.value.branch} and opened this pull request.`);
140 expect(r.value.branch).not.toBe("main");
141 expect(typeof r.value.pull).toBe("number");
142 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs