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

MCP `orgs`: read an organization, its teams and their members, and create one, with the same rules as the API #4816

Parked opened this
Closed without merging

scout/forge:scout/4797-mcp-orgs-read-an-organization-its-teams → main 6 commits fork 3 threads · 3 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
4 files changed +166 −1
docs/MCP.md +1
@@ -78,6 +78,7 @@ for a tunnel and a forge that sleeps.
7878 | `run_log` | `{ repo, run, tail? }`: a run's log, or its last `tail` lines (1–2000), with the REST route's access: a hidden log or unreadable repository is not found | |
7979 | `review` | `{ repo, number, verdict, reason? }`: approve a pull (`approve`) or request changes (`changes`, with a `reason`), as the page does; a writer's or the crew's, and never your own pull | yes |
8080 | `usage` | `{ repo, days? }`: what the crew's runs spent — tokens, cost, wall time — by subscription, agent, issue, and each account's 5-hour and weekly standing; a writer's | |
81 | `orgs` | `{ action, org?, name? }`: `mine` lists your organizations, `read` one with the teams you may see and their members, `create` one (rw token); as `/api/v1/user/orgs`, `/orgs/:org` with its teams and members, and `POST /api/v1/orgs`: unknown org is not found, a taken, reserved or invalid name is refused | yes |
8182 | `labels` | `{ repo, number, labels }`: set an issue's or a pull's labels to exactly these (`[]` clears); only labels the repository has, by a writer | yes |
8283 | `wait_for` | `{ app, issue, blockedBy, stop? }`: the issue waits for another, or stops with `stop: true`; the page's rules, and the answer carries the issue's URL | yes |
8384 | `hold` | `{ app, pull, why?, release?, dryRun? }`: hold a pull so no rule reviews or lands it, or let it go; a person who can write, never an agent; plans unless `dryRun: false` | yes |
src/http/mcp.ts +49 −1
@@ -238,7 +238,9 @@ import { COPIES_PER_DAY, makeItYours } from "../actions/make_it_yours.ts";
238238 import { deleteOriginApp, listOriginApps, registerOriginApp } from "../actions/origins.ts";
239239 import { connectMessage } from "./api.ts";
240240 import { resourceMetadataUrl } from "./oauth.ts";
241 import { body, boundedBody, json } from "./respond.ts";
241 import { body, boundedBody, json, publicProfile } from "./respond.ts";
242 import { createOrg } from "../actions/orgs.ts";
243 import { getOrg, listOrgsForUser, listTeamMembers, listTeamsVisibleTo } from "../core/orgs.ts";
242244 import { sizesView } from "../spawn/sizes.ts";
243245 import type { Router } from "./router.ts";
244246 import { mayReadRuns, runForReader, runLog } from "../actions/runs.ts";
@@ -279,6 +281,14 @@ const bad = (error: string, message: string): Answer => ({
279281 message,
280282 });
281283
284 const ORG_SAYS: Record<string, string> = {
285 invalid_name: "that is not a name an organization can have",
286 name_taken: "that name is taken",
287 name_reserved: "that name is reserved",
288 unverified: "verify your email first",
289 agent_cannot_own: "an agent cannot own an organization",
290 };
291
282292 interface Tool {
283293 readonly name: string;
284294 readonly description: string;
@@ -3941,6 +3951,44 @@ const TOOLS: readonly Tool[] = [
39413951 return good({ says: `${changed.value.name} saved at ${changed.value.dial}%.`, ...changed.value });
39423952 },
39433953 },
3954 {
3955 name: "orgs",
3956 description: "Your orgs; read one with its teams and members; create one.",
3957 inputSchema: {
3958 type: "object",
3959 properties: {
3960 action: { type: "string", enum: ["mine", "read", "create"] },
3961 org: { type: "string", maxLength: 64 },
3962 name: { type: "string", maxLength: 64 },
3963 },
3964 },
3965 // `create` founds an account, so the tool is announced as a write; `mine`
3966 // and `read` never pass `name` and stay open to an ro token.
3967 writes: true,
3968 readsWithout: "name",
3969 run(ctx, user, args) {
3970 const { action, org, name } = args;
3971 if (action === "mine") return good({ orgs: listOrgsForUser(ctx.app.db, user.id).map(publicProfile) });
3972 if (action === "read") {
3973 const found = typeof org === "string" ? getOrg(ctx.app.db, org) : undefined;
3974 if (!found) return bad("not_found", "no such organization");
3975 // Only the teams the reader may see, as GET /api/v1/orgs/:org says.
3976 const teams = listTeamsVisibleTo(ctx.app.db, found.id, user).map((t) => ({
3977 name: t.name,
3978 permission: t.permission,
3979 members: listTeamMembers(ctx.app.db, t.id).map(publicProfile),
3980 }));
3981 return good({ id: found.id, ...publicProfile(found), teams });
3982 }
3983 if (action === "create") {
3984 if (typeof name !== "string") return bad("invalid", "name is the new organization's name");
3985 const made = createOrg(ctx.app, user, name);
3986 if (!made.ok) return bad(made.error, ORG_SAYS[made.error] ?? made.error);
3987 return good({ id: made.value.id, username: made.value.username, kind: "org" });
3988 }
3989 return bad("invalid", "action is mine, read or create");
3990 },
3991 },
39443992 {
39453993 name: "cloud_accounts",
39463994 description:
test/mcp-orgs.test.ts added +115
@@ -0,0 +1,115 @@
1 /**
2 * The `orgs` tool is the organization API over MCP: the same functions, so
3 * the same rules. A person makes one and reads it back; a stranger sees no
4 * teams; a bad or taken name is refused with the API's code.
5 */
6 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
7 import { mkdtemp, rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { createApp, type App } from "../src/app.ts";
11 import { createToken } from "../src/core/tokens.ts";
12 import { createUser } from "../src/core/users.ts";
13 import { serve, type Servers } from "../src/http/server.ts";
14 import { promote } from "./helpers/members.ts";
15
16 describe("MCP orgs", () => {
17 let dataDir: string;
18 let app: App;
19 let servers: Servers;
20 let aliceRw: string;
21 let aliceRo: string;
22 let bobRw: string;
23 let id = 1;
24
25 const tool = async (token: string, args: unknown) => {
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({
34 jsonrpc: "2.0",
35 id: id++,
36 method: "tools/call",
37 params: { name: "orgs", arguments: args },
38 }),
39 });
40 const body: any = await res.json();
41 const text: string = body.result.content[0].text;
42 return body.result.isError === true ? { error: text } : { value: JSON.parse(text) };
43 };
44
45 beforeAll(async () => {
46 dataDir = await mkdtemp(join(tmpdir(), "forge-mcp-orgs-"));
47 app = createApp({ dataDir, port: 0 });
48 servers = await serve(app);
49 const a = await createUser(app.db, { origin: "seed", trusted: true,
50 username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
51 if (!a.ok) throw new Error(a.error);
52 promote(app.db, a.value);
53 const b = await createUser(app.db, { origin: "seed", trusted: true,
54 username: "bob", email: "[email protected]", password: "a-good-passphrase" });
55 if (!b.ok) throw new Error(b.error);
56 promote(app.db, b.value);
57 aliceRw = createToken(app.db, a.value.id, "rw", "rw").token;
58 aliceRo = createToken(app.db, a.value.id, "ro", "ro").token;
59 bobRw = createToken(app.db, b.value.id, "rw", "rw").token;
60 }, 30_000);
61
62 afterAll(async () => {
63 servers.stop();
64 app.close();
65 await rm(dataDir, { recursive: true, force: true });
66 });
67
68 test("a person creates an org and reads it back with its teams and members", async () => {
69 const made = await tool(aliceRw, { action: "create", name: "acme" });
70 expect(made.value).toMatchObject({ username: "acme", kind: "org" });
71 const org = (await tool(aliceRw, { action: "read", org: "acme" })).value;
72 expect(org.username).toBe("acme");
73 expect(org.teams.map((t: any) => t.name)).toEqual(["Owners"]);
74 expect(org.teams[0].members.map((m: any) => m.username)).toEqual(["alice"]);
75 const mine = await tool(aliceRw, { action: "mine" });
76 expect(mine.value.orgs.map((o: any) => o.username)).toEqual(["acme"]);
77 expect((await tool(bobRw, { action: "mine" })).value.orgs).toEqual([]);
78 });
79
80 test("a non-member sees no teams and an unknown org is not found", async () => {
81 const org = (await tool(bobRw, { action: "read", org: "acme" })).value;
82 expect(org.teams).toEqual([]);
83 expect((await tool(bobRw, { action: "read", org: "nope" })).error).toContain("no such organization");
84 expect((await tool(bobRw, { action: "read" })).error).toContain("no such organization");
85 });
86
87 test("a taken, reserved or invalid name is refused with the API's code", async () => {

The test's name says "reserved", but none of these assertions sends a reserved name. Add a case like expect((await tool(bobRw, { action: "create", name: "admin" })).error).toContain("name_reserved"), using a name from the reserved list in core/orgs.ts.

88 expect((await tool(bobRw, { action: "create", name: "acme" })).error).toContain("name_taken");
89 expect((await tool(bobRw, { action: "create", name: "alice" })).error).toContain("name_taken");
90 expect((await tool(bobRw, { action: "create", name: "admin" })).error).toContain("name_reserved");
91 expect((await tool(bobRw, { action: "create", name: "not a name!" })).error).toContain("invalid_name");
92 expect((await tool(bobRw, { action: "create" })).error).toContain("invalid");
93 });
94
95 test("a read-only token reads but does not create", async () => {
96 expect((await tool(aliceRo, { action: "mine" })).value.orgs).toHaveLength(1);
97 expect((await tool(aliceRo, { action: "create", name: "beta" })).error).toContain("forbidden");
98 });
99
100 test("tools/list announces orgs as a write, not read-only", async () => {
101 const res = await fetch(`${servers.url}/mcp`, {
102 method: "POST",
103 headers: {
104 "content-type": "application/json",
105 accept: "application/json, text/event-stream",
106 authorization: `Bearer ${aliceRw}`,
107 },
108 body: JSON.stringify({ jsonrpc: "2.0", id: 9999, method: "tools/list" }),
109 });
110 const body: any = await res.json();
111 const orgs = body.result.tools.find((t: any) => t.name === "orgs");
112 // readOnlyHint defaults to false, so a write carries no annotation
113 expect(orgs.annotations?.readOnlyHint).not.toBe(true);
114 });
115 });
test/mcp.test.ts +1
@@ -262,6 +262,7 @@ describe("the forge over MCP", () => {
262262 "limits",
263263 "app_env",
264264 "teams",
265 "orgs",
265266 "cloud_accounts",
266267 "cloud_account",
267268 "quotas",

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs