Public: anyone can read this; the crew can change it.
MCP `write_file`: commit a file to a branch, with the same rules as the API #5300
scout/forge:scout/5289-mcp-write-file-commit-a-file-to-a-branch → main 1 commit fork
4 files
changed +159
−1
docs/MCP.md +1
| @@ -39,6 +39,7 @@ for a tunnel and a forge that sleeps. | ||
| 39 | 39 | | `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 | |
| 40 | 40 | | `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 | |
| 41 | 41 | | `read_file` | a file (utf-8, or base64 for binary) or a directory listing at a ref, as GET …/contents | no | |
| 42 | | `write_file` | `{ repo, branch, path, content, message, base? }`: commit one utf-8 file to a branch (created from `base`, default branch, when new); the same scope, permission and refusals as POST …/contents; answers the `commit` and a `says` sentence | yes | | |
| 42 | 43 | | `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 | |
| 43 | 44 | | `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 | |
| 44 | 45 | | `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 +55 −1
| @@ -155,6 +155,7 @@ import { listBranches } from "../git/branches.ts"; | ||
| 155 | 155 | import { commitLog } from "../git/read.ts"; |
| 156 | 156 | import { repoDir } from "../git/repos.ts"; |
| 157 | 157 | import { runGit } from "../git/env.ts"; |
| 158 | import { MAX_FILE_BYTES } from "../actions/contents.ts"; | |
| 158 | 159 | import { isSafeRef, isSafeTreePath } from "../git/guard.ts"; |
| 159 | 160 | import { blobForRender, listTree } from "../git/read.ts"; |
| 160 | 161 | import { CREATE_ERRORS, DELETE_ERRORS } from "../web/pages/branches.ts"; |
| @@ -189,7 +190,7 @@ import { | ||
| 189 | 190 | directionNote, |
| 190 | 191 | OUTSIDERS_NOTE, |
| 191 | 192 | } from "../crew/direct.ts"; |
| 192 | import { setArchived, setCrewOutsiders, updateRepoSettings, setDecisionsBy, repositoryLimitMessage } from "../actions/repos.ts"; | |
| 193 | import { commitToBranch, setArchived, setCrewOutsiders, updateRepoSettings, setDecisionsBy, repositoryLimitMessage } from "../actions/repos.ts"; | |
| 193 | 194 | import { |
| 194 | 195 | deleteAppEnvVar, |
| 195 | 196 | listAppEnv, |
| @@ -1134,6 +1135,59 @@ const TOOLS: readonly Tool[] = [ | ||
| 1134 | 1135 | }); |
| 1135 | 1136 | }, |
| 1136 | 1137 | }, |
| 1138 | { | |
| 1139 | name: "write_file", | |
| 1140 | description: "Commit one file to a branch, as POST …/contents does.", | |
| 1141 | inputSchema: { | |
| 1142 | type: "object", | |
| 1143 | properties: { | |
| 1144 | repo: REPO_ARG, | |
| 1145 | branch: { type: "string", maxLength: 256 }, | |
| 1146 | path: { type: "string", maxLength: 1024 }, | |
| 1147 | content: { type: "string" }, | |
| 1148 | message: { type: "string", maxLength: 1024 }, | |
| 1149 | base: { type: "string", maxLength: 256 }, | |
| 1150 | }, | |
| 1151 | required: ["repo", "branch", "path", "content", "message"], | |
| 1152 | }, | |
| 1153 | writes: true, | |
| 1154 | async run(ctx, user, args) { | |
| 1155 | const repo = repoArg(ctx, user, args); | |
| 1156 | if (isAnswer(repo)) return repo; | |
| 1157 | const { branch, path, content, message, base } = args; | |
| 1158 | if ( | |
| 1159 | typeof branch !== "string" || | |
| 1160 | typeof path !== "string" || | |
| 1161 | typeof content !== "string" || | |
| 1162 | typeof message !== "string" || | |
| 1163 | (base !== undefined && typeof base !== "string") | |
| 1164 | ) | |
| 1165 | return bad("invalid", "repo, branch, path, content and message are strings; base is a string"); | |
| 1166 | if (!isSafeRef(branch) || (base !== undefined && base !== "" && !isSafeRef(base))) | |
| 1167 | return bad("invalid", "that branch or base is not a branch name"); | |
| 1168 | if (!isSafeTreePath(path)) return bad("invalid", "that path is not a file path inside the repository"); | |
| 1169 | if (message.trim() === "" || message.length > 1024) | |
| 1170 | return bad("invalid", "the message is one to 1024 characters"); | |
| 1171 | if (Buffer.byteLength(content) > MAX_FILE_BYTES) | |
| 1172 | return bad("invalid", "the content is over 2 MB; push it instead"); | |
| 1173 | const committed = await commitToBranch(ctx.app, user, repo, { | |
| 1174 | branch, | |
| 1175 | base: base ?? "", | |
| 1176 | message, | |
| 1177 | files: [{ path, content }], | |
| 1178 | }); | |
| 1179 | if (!committed.ok) { | |
| 1180 | const e = committed.error; | |
| 1181 | return typeof e === "string" | |
| 1182 | ? bad(e, e === "not_found" ? "no such app or repository (owner/name)" : "you may not write to that repository") | |
| 1183 | : bad(e.kind, e.kind === "branch_moved" ? "the branch moved; try again" : `that commit was refused (${e.kind})`); | |
| 1184 | } | |
| 1185 | return good({ | |
| 1186 | says: `Committed ${path} to ${branch}.`, | |
| 1187 | commit: committed.value, | |
| 1188 | }); | |
| 1189 | }, | |
| 1190 | }, | |
| 1137 | 1191 | { |
| 1138 | 1192 | name: "asks", |
| 1139 | 1193 | description: |
test/mcp-write-file.test.ts added +102
| @@ -0,0 +1,102 @@ | ||
| 1 | /** MCP `write_file`: a writer commits and `read_file` reads it back; a reader and a stranger are refused as POST …/contents refuses them; bad arguments are 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 { createRepo } from "../src/core/repos.ts"; | |
| 8 | import { createToken } from "../src/core/tokens.ts"; | |
| 9 | import { createUser } from "../src/core/users.ts"; | |
| 10 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 11 | import { quietLogs } from "./helpers/globals.ts"; | |
| 12 | ||
| 13 | quietLogs(); | |
| 14 | ||
| 15 | let dataDir: string; | |
| 16 | let app: App; | |
| 17 | let servers: Servers; | |
| 18 | const tok: Record<string, string> = {}; | |
| 19 | ||
| 20 | const ok = <T>(r: { ok: true; value: T } | { ok: false; error: unknown }): T => { | |
| 21 | if (!r.ok) throw new Error(JSON.stringify(r.error)); | |
| 22 | return r.value; | |
| 23 | }; | |
| 24 | ||
| 25 | async function call(token: string, name: string, args: unknown): Promise<{ error?: string; value?: any }> { | |
| 26 | const res = await fetch(`${servers.url}/mcp`, { | |
| 27 | method: "POST", | |
| 28 | headers: { | |
| 29 | "content-type": "application/json", | |
| 30 | accept: "application/json, text/event-stream", | |
| 31 | authorization: `Bearer ${token}`, | |
| 32 | }, | |
| 33 | body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name, arguments: args } }), | |
| 34 | }); | |
| 35 | const body = (await res.json()) as any; | |
| 36 | if (body.error) return { error: JSON.stringify(body.error) }; | |
| 37 | const text: string = body.result.content[0].text; | |
| 38 | return body.result.isError === true ? { error: text } : { value: JSON.parse(text) }; | |
| 39 | } | |
| 40 | ||
| 41 | beforeAll(async () => { | |
| 42 | dataDir = await mkdtemp(join(tmpdir(), "forge-write-file-mcp-")); | |
| 43 | app = createApp({ dataDir, port: 0 }); | |
| 44 | servers = await serve(app); | |
| 45 | const make = (username: string) => | |
| 46 | createUser(app.db, { | |
| 47 | origin: "seed", | |
| 48 | trusted: true, | |
| 49 | username, | |
| 50 | email: `${username}@forge.local`, | |
| 51 | password: "a-good-passphrase", | |
| 52 | }); | |
| 53 | const owner = ok(await make("ada")); | |
| 54 | const stranger = ok(await make("rita")); | |
| 55 | ok(await createRepo(app.db, app.reposRoot, { ownerId: owner.id, name: "pub", visibility: "public" })); | |
| 56 | tok["rw"] = createToken(app.db, owner.id, "rw", "rw").token; | |
| 57 | tok["ro"] = createToken(app.db, owner.id, "ro", "ro").token; | |
| 58 | tok["stranger"] = createToken(app.db, stranger.id, "s", "rw").token; | |
| 59 | }, 30_000); | |
| 60 | ||
| 61 | afterAll(async () => { | |
| 62 | servers?.stop(); | |
| 63 | app?.close(); | |
| 64 | await rm(dataDir, { recursive: true, force: true }); | |
| 65 | }); | |
| 66 | ||
| 67 | const args = (over: Record<string, unknown> = {}) => ({ | |
| 68 | repo: "ada/pub", | |
| 69 | branch: "main", | |
| 70 | path: "docs/a.txt", | |
| 71 | content: "hi\n", | |
| 72 | message: "add a", | |
| 73 | ...over, | |
| 74 | }); | |
| 75 | ||
| 76 | test("a writer commits and read_file reads it back", async () => { | |
| 77 | const w = (await call(tok["rw"]!, "write_file", args())).value; | |
| 78 | expect(w.says).toContain("docs/a.txt"); | |
| 79 | expect(w.commit.commitOid).toMatch(/^[0-9a-f]{40}$/); | |
| 80 | const r = (await call(tok["rw"]!, "read_file", { repo: "ada/pub", path: "docs/a.txt" })).value; | |
| 81 | expect(r.content).toBe("hi\n"); | |
| 82 | const b = await call(tok["rw"]!, "write_file", args({ branch: "feat", path: "b.txt", content: "b" })); | |
| 83 | expect(b.value.says).toContain("feat"); | |
| 84 | expect((await call(tok["rw"]!, "read_file", { repo: "ada/pub", path: "b.txt", ref: "feat" })).value.content).toBe("b"); | |
| 85 | }); | |
| 86 | ||
| 87 | test("a reader and a stranger are refused as the route refuses them", async () => { | |
| 88 | expect((await call(tok["ro"]!, "write_file", args())).error).toBeDefined(); | |
| 89 | const s = await call(tok["stranger"]!, "write_file", args({ path: "x.txt" })); | |
| 90 | expect(s.error).toContain("forbidden"); | |
| 91 | const none = await call(tok["rw"]!, "read_file", { repo: "ada/pub", path: "x.txt" }); | |
| 92 | expect(none.error).toContain("not_found"); | |
| 93 | }); | |
| 94 | ||
| 95 | test("bad arguments are refused in a sentence", async () => { | |
| 96 | const t = tok["rw"]!; | |
| 97 | expect((await call(t, "write_file", args({ path: "../x" }))).error).toContain("invalid"); | |
| 98 | expect((await call(t, "write_file", args({ path: ".git/config" }))).error).toBeDefined(); | |
| 99 | expect((await call(t, "write_file", args({ branch: "--bad" }))).error).toContain("invalid"); | |
| 100 | expect((await call(t, "write_file", args({ content: 7 }))).error).toContain("invalid"); | |
| 101 | expect((await call(t, "write_file", args({ message: " " }))).error).toContain("invalid"); | |
| 102 | }); |
test/mcp.test.ts +1
| @@ -185,6 +185,7 @@ describe("the forge over MCP", () => { | ||
| 185 | 185 | "edit", |
| 186 | 186 | "close", |
| 187 | 187 | "read_file", |
| 188 | "write_file", | |
| 188 | 189 | "asks", |
| 189 | 190 | "asks_act", |
| 190 | 191 | "asks_decide", |
new above
offline