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

MCP `write_file`: commit one file to a branch, through the same function as POST …/contents #5542

Parked opened this
Closed without merging

scout/forge:scout/5352-mcp-write-file-commit-one-file-to-a-bran → main 2 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
4 files changed +169 −7
docs/MCP.md +1
@@ -40,6 +40,7 @@ for a tunnel and a forge that sleeps.
4040 | `close` | `{ repo, number, state?, reason?, into? }`: close an issue or a pull (`state` closed by default) or reopen it (`open`); the same rules and refusals as `PATCH …/issues/:number`: an agent closes only what the rules give it and reopens nothing; answers `state` and `closeReason` | yes |
4141 | `pulls` | `{ repo, state?, limit? }`: a repository's pulls, newest first, one brief line each: `number`, `title`, `author`, `head`, `check` (state), `approvals`, `changesRequested`, `mergeable` (null once closed); `state` open (default) or closed, `limit` 1-50 (default 20); no bodies, no diffs | no |
4242 | `read_file` | a file (utf-8, or base64 for binary) or a directory listing at a ref, as GET …/contents | no |
43 | `write_file` | commit one file to an existing branch, as POST …/contents does; `repo`, `branch`, `path`, `content`, `message` | yes |
4344 | `seal` | `{ repo, number, sealed }`: seal a security report (and the pull that fixes it) so only writers and the crew see it, or unseal it for every reader; a writer's, recorded | yes |
4445 | `secrets` | `{ scope, ref?, action, name?, value? }` (forge admin): `list` the names and timestamps of the forge's sealed secrets, `set` or `remove` one; `scope` is forge, org or repo, `ref` the org or `owner/name`; a value is never read back | yes |
4546 | `org_teams` | `{ org, action, team, user?, permission? }` (admin-scope token, an org owner): `create` a team (`permission` read, write or admin; read by default), `add_member` a `user`, or `remove` the team; the same as POST/DELETE `/api/v1/orgs/:org/teams` | yes |
src/http/mcp.ts +74 −7
@@ -190,7 +190,7 @@ import {
190190 directionNote,
191191 OUTSIDERS_NOTE,
192192 } from "../crew/direct.ts";
193 import { createLabel, deleteLabel, setArchived, setCrewOutsiders, updateRepoSettings, setDecisionsBy, repositoryLimitMessage } from "../actions/repos.ts";
193 import { commitToBranch, createLabel, deleteLabel, setArchived, setCrewOutsiders, updateRepoSettings, setDecisionsBy, repositoryLimitMessage } from "../actions/repos.ts";
194194 import {
195195 deleteAppEnvVar,
196196 listAppEnv,
@@ -285,6 +285,15 @@ const attachWords = (error: string): string =>
285285 too_large: "the picture is over 5 MB",
286286 })[error] ?? "refused";
287287
288 /** The route's words for a commit it refuses (`editMessage` in api.ts). */
289 const writeFileWords: Record<string, string> = {
290 protected_branch: "the default branch is protected; only a repo admin may commit to it directly",
291 file_too_large: "that file is larger than an edit may carry; push it instead",
292 commit_too_large: "the edit is larger than one commit may carry; push it instead",
293 branch_moved: "the branch moved while this edit was being written; re-read and retry",
294 land_refused: "the origin refused this commit; nothing was changed here either",
295 };
296
288297 const bad = (error: string, message: string): Answer => ({
289298 ok: false,
290299 error,
@@ -518,10 +527,10 @@ const TOOLS: readonly Tool[] = [
518527 type: "object",
519528 properties: {
520529 name: { type: "string", maxLength: 100 },
521 description: { type: "string", maxLength: 4000, description: "What it should become: the first issue." },
530 description: { type: "string", maxLength: 4000 },
522531 owner: { type: "string", maxLength: 39 },
523 visibility: { type: "string", enum: ["public", "private"], description: "Private unless public." },
524 agent: { type: "string", maxLength: 39, description: "Agent for the crew and first issue." },
532 visibility: { type: "string", enum: ["public", "private"] },
533 agent: { type: "string", maxLength: 39 },
525534 pick: { type: "boolean", description: "Pick the agent from the text." },
526535 },
527536 required: ["name"],
@@ -1137,6 +1146,52 @@ const TOOLS: readonly Tool[] = [
11371146 });
11381147 },
11391148 },
1149 {
1150 name: "write_file",
1151 description: "Commit one file to an existing branch.",
1152 inputSchema: {
1153 type: "object",
1154 properties: {
1155 repo: REPO_ARG,
1156 branch: { type: "string" },
1157 path: { type: "string" },
1158 content: { type: "string" },
1159 message: { type: "string" },
1160 },
1161 required: ["repo", "branch", "path", "content", "message"],
1162 },
1163 writes: true,
1164 async run(ctx, user, args) {
1165 const repo = repoArg(ctx, user, args);
1166 if (isAnswer(repo)) return repo;
1167 const { branch, path, content, message } = args;
1168 if (typeof branch !== "string" || !isSafeRef(branch))
1169 return bad("invalid_branch", "branch is the name of an existing branch");
1170 if (typeof path !== "string" || !isSafeTreePath(path) || path.length > 1024)
1171 return bad("invalid_path", "path is a relative file path with no empty, `.` or `..` parts");
1172 if (typeof content !== "string") return bad("invalid", "content is a string");
1173 if (typeof message !== "string" || message.trim() === "" || message.length > 1000)
1174 return bad("invalid_message", "message is one to 1000 characters");
1175 const dir = repoDir(ctx.app.reposRoot, repo.ownerName, repo.name);
1176 const exists = await runGit(["rev-parse", "--verify", "--quiet", `refs/heads/${branch}^{commit}`], { cwd: dir });
1177 if (!exists.ok) return bad("not_found", "no such branch; it must exist");
1178 const committed = await commitToBranch(ctx.app, user, repo, {
1179 branch,
1180 message,
1181 files: [{ path, content }],
1182 });
1183 if (!committed.ok) {
1184 const kind = typeof committed.error === "string" ? committed.error : committed.error.kind;
1185 if (kind === "forbidden") return bad(kind, "your credentials lack the scope for this action");
1186 if (kind === "not_found") return bad(kind, "no such app or repository (owner/name)");
1187 return bad(kind, writeFileWords[kind] ?? "this edit could not be applied");
1188 }
1189 return good({
1190 commit: committed.value.commitOid,
1191 says: `Committed ${path} to ${branch}.`,
1192 });
1193 },
1194 },
11401195 {
11411196 name: "asks",
11421197 description:
@@ -3026,7 +3081,7 @@ const TOOLS: readonly Tool[] = [
30263081 properties: {
30273082 repo: REPO_ARG,
30283083 name: { type: "string" },
3029 visibility: { type: "string", enum: ["private", "public"], description: "Private by default." },
3084 visibility: { type: "string", enum: ["private", "public"] },
30303085 dryRun: { type: "boolean" },
30313086 },
30323087 required: ["repo"],
@@ -4103,8 +4158,13 @@ const TOOLS: readonly Tool[] = [
41034158 inputSchema: {
41044159 type: "object",
41054160 properties: {
4161 <<<<<<< HEAD
4162 since: { type: "string", maxLength: 40 },
4163 ua: { type: "string", maxLength: 100, description: "Part of the user agent." },
4164 =======
41064165 since: { type: "string", maxLength: 40, description: "ISO time; max 14 days." },
41074166 ua: { type: "string", maxLength: 100, description: "User agent part." },
4167 >>>>>>> origin/main
41084168 path: { type: "string", maxLength: 200, description: "Path prefix." },
41094169 },
41104170 },
@@ -4368,10 +4428,17 @@ const TOOLS: readonly Tool[] = [
43684428 verb: { type: "string", enum: ["attach", "verify", "rotate", "rename", "remove", "allow_writes", "audit"] },
43694429 provider: { type: "string", enum: [...PROVIDERS] },
43704430 name: { type: "string", maxLength: 32 },
4431 <<<<<<< HEAD
4432 value: { type: "string", maxLength: 4096 },
4433 to: { type: "string", maxLength: 32 },
4434 allowed: { type: "boolean", description: "For allow_writes." },
4435 repo: { type: "string", maxLength: 200 },
4436 =======
43714437 value: { type: "string", maxLength: 4096, description: "For attach, rotate." },
43724438 to: { type: "string", maxLength: 32 },
43734439 allowed: { type: "boolean", description: "For allow_writes." },
43744440 repo: { type: "string", maxLength: 200, description: "For audit." },
4441 >>>>>>> origin/main
43754442 },
43764443 required: ["verb", "provider", "name"],
43774444 },
@@ -4513,10 +4580,10 @@ const TOOLS: readonly Tool[] = [
45134580 type: "object",
45144581 properties: {
45154582 slug: { type: "string", maxLength: 40 },
4516 panel: { type: "integer", minimum: 0, maximum: 23, description: "One panel, from 0." },
4583 panel: { type: "integer", minimum: 0, maximum: 23 },
45174584 from: { type: "string", maxLength: 64 },
45184585 to: { type: "string", maxLength: 64 },
4519 step: { type: "string", maxLength: 16, description: "With panel: seconds per bucket, or a count of s/m/h/d." },
4586 step: { type: "string", maxLength: 16 },
45204587 },
45214588 },
45224589 writes: false,
test/mcp-write-file.test.ts added +93
@@ -0,0 +1,93 @@
1 /** MCP `write_file`: a writer commits one file and `read_file` reads it back; a reader is refused as the route refuses; a bad path or branch is refused. */
2 import { afterAll, beforeAll, expect, test } from "bun:test";
3 import { mkdtemp, rm } from "node:fs/promises";
4 import { tmpdir } from "node:os";
5 import { join } from "node:path";
6 import { createApp, type App } from "../src/app.ts";
7 import { commitToBranch } from "../src/actions/repos.ts";
8 import { createRepo } from "../src/core/repos.ts";
9 import { createToken } from "../src/core/tokens.ts";
10 import { createUser } from "../src/core/users.ts";
11 import { serve, type Servers } from "../src/http/server.ts";
12 import { quietLogs } from "./helpers/globals.ts";
13
14 quietLogs();
15
16 let dataDir: string;
17 let app: App;
18 let servers: Servers;
19 const tok: Record<string, string> = {};
20
21 const ok = <T>(r: { ok: true; value: T } | { ok: false; error: unknown }): T => {
22 if (!r.ok) throw new Error(JSON.stringify(r.error));
23 return r.value;
24 };
25
26 async function call(token: string, name: string, args: unknown): Promise<{ error?: string; value?: any }> {
27 const res = await fetch(`${servers.url}/mcp`, {
28 method: "POST",
29 headers: {
30 "content-type": "application/json",
31 accept: "application/json, text/event-stream",
32 authorization: `Bearer ${token}`,
33 },
34 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name, arguments: args } }),
35 });
36 const body = (await res.json()) as any;
37 const text: string = body.result.content[0].text;
38 return body.result.isError === true ? { error: text } : { value: JSON.parse(text) };
39 }
40
41 const good = { repo: "ada/pub", branch: "main", path: "docs/n.txt", content: "hi\n", message: "add n" };
42
43 beforeAll(async () => {
44 dataDir = await mkdtemp(join(tmpdir(), "forge-write-file-mcp-"));
45 app = createApp({ dataDir, port: 0 });
46 servers = await serve(app);
47 const make = (username: string) =>
48 createUser(app.db, {
49 origin: "seed",
50 trusted: true,
51 username,
52 email: `${username}@forge.local`,
53 password: "a-good-passphrase",
54 });
55 const owner = ok(await make("ada"));
56 const stranger = ok(await make("rita"));
57 const pub = ok(await createRepo(app.db, app.reposRoot, { ownerId: owner.id, name: "pub", visibility: "public" }));
58 ok(await commitToBranch(app, owner, pub, { message: "seed", files: [{ path: "a.txt", content: "a\n" }] }));
59 tok["writer"] = createToken(app.db, owner.id, "w", "rw").token;
60 tok["reader"] = createToken(app.db, owner.id, "r", "ro").token;
61 tok["stranger"] = createToken(app.db, stranger.id, "s", "rw").token;
62 }, 30_000);
63
64 afterAll(async () => {
65 servers?.stop();
66 app?.close();
67 await rm(dataDir, { recursive: true, force: true });
68 });
69
70 test("a writer commits a file and read_file reads it back", async () => {
71 const made = (await call(tok["writer"]!, "write_file", good)).value;
72 expect(made.commit).toMatch(/^[0-9a-f]{40}$/);
73 expect(made.says).toContain("docs/n.txt");
74 const read = (await call(tok["writer"]!, "read_file", { repo: "ada/pub", path: "docs/n.txt" })).value;
75 expect(read.content).toBe("hi\n");
76 });
77
78 test("a reader is refused as the route refuses", async () => {
79 const r = await call(tok["reader"]!, "write_file", { ...good, path: "x.txt" });
80 expect(r.error).toBeDefined();
81 const s = await call(tok["stranger"]!, "write_file", { ...good, path: "x.txt" });
82 expect(s.error).toContain("forbidden");
83 expect((await call(tok["writer"]!, "read_file", { repo: "ada/pub", path: "x.txt" })).error).toContain("not_found");
84 });
85
86 test("bad arguments are refused in a sentence", async () => {
87 const t = tok["writer"]!;
88 expect((await call(t, "write_file", { ...good, path: "../x" })).error).toContain("invalid_path");
89 expect((await call(t, "write_file", { ...good, content: 7 })).error).toContain("invalid");
90 expect((await call(t, "write_file", { ...good, message: "" })).error).toContain("invalid_message");
91 expect((await call(t, "write_file", { ...good, branch: "--x" })).error).toContain("invalid_branch");
92 expect((await call(t, "write_file", { ...good, branch: "nope" })).error).toContain("not_found");
93 });
test/mcp.test.ts +1
@@ -185,6 +185,7 @@ describe("the forge over MCP", () => {
185185 "edit",
186186 "close",
187187 "read_file",
188 "write_file",
188189 "asks",
189190 "asks_act",
190191 "asks_decide",

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs