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

OAuth for the MCP: the Claude app and Grok connectors can attach, minting the same ro/rw tokens #1542

Closed opened this in answer to
Closed without merging

scout/forge:scout/384-oauth-for-the-mcp-the-claude-app-and-gro → main 12 commits fork 3 threads · 3 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
6 files changed +331 −87
docs/MCP.md +8
@@ -102,6 +102,14 @@ page. **Grok**: Connectors → Add custom connector, the same `/mcp` URL;
102102 approve the page it opens. Pick `ro` unless the connector should be able to
103103 `tell` and `plan`.
104104
105 **By voice.** Once attached, "how is the forge?" calls `brief`: three or four
106 short sentences to read aloud — which milestones took merges this week, what
107 waits for you, how many runs are going. It is built from the same numbers as
108 `milestones` and `now`, and an `ro` token may ask. The last wave's headline
109 is spoken once waves exist (`waves/` is not in the forge yet); until then the
110 sentence is left out rather than invented. Grok's connector flow and whether
111 its free tier allows custom connectors are unconfirmed.
112
105113 The token's scope is the whole of its authority: a connector holding `ro`
106114 can call `apps` and is refused `tell`.
107115
scripts/gate.ts +1
@@ -255,6 +255,7 @@ export const GATE: readonly string[] = [
255255 ];
256256
257257 export const EXCLUDED: readonly Exclusion[] = [
258 { file: "test/brief.test.ts", reason: "not yet admitted", issue: 261 },
258259 { file: "test/api-errors.test.ts", reason: "not yet admitted", issue: 261 },
259260 { file: "test/apps-api.test.ts", reason: "not yet admitted", issue: 261 },
260261 {
src/core/brief.ts added +64
@@ -0,0 +1,64 @@
1 /**
2 * The forge in a few spoken sentences: what moved this week, what waits for
3 * the owner. Plain data in, one short string out — written to be read aloud
4 * (a Grok connector in a car), so no numbers beyond counts, no markup, no
5 * identifiers a voice would stumble on.
6 */
7
8 export type Moved = { readonly name: string; readonly merged: number };
9
10 /** How many milestones are named aloud; the rest are counted. */
11 export const BRIEF_NAMED = 3;
12 /** Longest a name is read; a title is not a paragraph. */
13 const NAME_MAX = 60;
14
15 const plural = (n: number, one: string, many: string) =>
16 `${n} ${n === 1 ? one : many}`;
17
18 const spoken = (name: string) =>
19 (name.length > NAME_MAX ? `${name.slice(0, NAME_MAX).trimEnd()}…` : name)
20 .replace(/[`*_#<>[\]]/g, "")
21 .replace(/\s+/g, " ")
22 .trim();
23
24 /** Milestones that took merges in the last week, most first. */
25 function movedSentence(moved: readonly Moved[]): string {
26 const live = moved.filter((m) => m.merged > 0);
27 if (live.length === 0) return "Nothing merged this week.";
28 const top = [...live].sort((a, b) => b.merged - a.merged);
29 const named = top
30 .slice(0, BRIEF_NAMED)
31 .map((m) => `${spoken(m.name)} with ${plural(m.merged, "change", "changes")}`);
32 const rest = top.length - named.length;
33 const list =
34 named.length === 1
35 ? named[0]!
36 : `${named.slice(0, -1).join(", ")} and ${named[named.length - 1]}`;
37 return `${plural(live.length, "milestone", "milestones")} moved this week: ${list}${
38 rest > 0 ? `, and ${rest} more` : ""
39 }.`;
40 }
41
42 function waitsSentence(waits: number): string {
43 return waits === 0
44 ? "Nothing needs you."
45 : `${plural(waits, "thing needs", "things need")} you.`;
46 }
47
48 /** Three or four sentences; the wave sentence only when a wave is told. */
49 export function briefWords(input: {
50 moved: readonly Moved[];
51 waits: number;
52 activeRuns: number;
53 wave?: string;
54 }): string {
55 const crew =
56 input.activeRuns === 0
57 ? "The crew is idle."
58 : `The crew has ${plural(input.activeRuns, "run", "runs")} going.`;
59 const wave =
60 input.wave === undefined || input.wave.trim() === ""
61 ? []
62 : [`The last wave: ${spoken(input.wave)}.`];
63 return [movedSentence(input.moved), waitsSentence(input.waits), crew, ...wave].join(" ");
64 }
src/http/mcp.ts +116 −80
@@ -95,6 +95,7 @@ import {
9595 OUTSIDERS_NOTE,
9696 } from "../crew/direct.ts";
9797 import { setCrewOutsiders } from "../actions/repos.ts";
98 import { briefWords, type Moved } from "../core/brief.ts";
9899 import { mapJson, marksFor } from "../web/pages/map.ts";
99100 import { undoFleetOp } from "../actions/fleet.ts";
100101 import { applyLimb, isLimbAction, previewLimb } from "../actions/limbs.ts";
@@ -102,7 +103,7 @@ import {
102103 milestoneData,
103104 milestonesJson,
104105 } from "../web/pages/milestones.ts";
105 import { appsOf, asksAnswer } from "../web/studio/asks.ts";
106 import { appsOf, asksAnswer, writableAppsOf } from "../web/studio/asks.ts";
106107 import { applyAsksBulk, previewAsksBulk } from "../actions/asks_bulk.ts";
107108 import type { Ctx, Handler } from "./context.ts";
108109 import {
@@ -231,6 +232,92 @@ function issueArg(ctx: Ctx, repo: Repo, args: Args, key: string) {
231232
232233 const isAnswer = (v: Repo | Answer): v is Answer => "ok" in v;
233234
235 /** Apps the spoken brief reads; a voice answer must be fast. */
236 const BRIEF_REPOS = 20;
237
238 /** The rows `now` answers, over the apps the caller can see. */
239 function nowRows(ctx: Ctx, user: User) {
240 const { repos } = appsOf(ctx, user);
241 const byId = new Map(repos.map((r) => [r.id, r]));
242 // A private app's runs are for those who may enter it (`mayReadRuns`).
243 // A run on a sealed report is for those who may see the report.
244 const runs = listActiveRuns(
245 ctx.app.db,
246 repos.filter((r) => mayReadRuns(ctx.app, user, r)).map((r) => r.id),
247 ).filter((r) =>
248 mayViewId(ctx.app.db, byId.get(r.repoId)!, r.issueId, user),
249 );
250 const actors = getUsersByIds(
251 ctx.app.db,
252 runs.map((r) => r.actorId).filter((id): id is string => id !== null),
253 );
254 // A planner that declined the direction is the crew waiting on you:
255 // it rides the same list, as a row with no run.
256 // Owner facts only: a stranger's public app never shows its planner here.
257 const owned = ownerFactRepoIds(ctx.app.db, repos, user);
258 const waiting = plannerDeclines(
259 ctx.app.db,
260 repos.filter((r) => owned.has(r.id)),
261 ).map((d) => ({
262 run: null,
263 app: `${d.repo.ownerName}/${d.repo.name}`,
264 who: "the planner",
265 on: `#${d.issue.number} ${d.issue.title}`,
266 why: "declined",
267 state: "waiting for you",
268 says: d.words,
269 since: d.at,
270 costUsd: 0,
271 }));
272 // An agent's green pull that waits for a person's review (#597): no
273 // reviewer on the crew, or one that lapsed — with its age, never silent.
274 const ownRepos = repos.filter((r) => owned.has(r.id));
275 const reviewWaits = listOpenAgentPullsVisibleTo(ctx.app.db, user, 200)
276 .filter((i) => ownRepos.some((r) => r.id === i.repoId))
277 .flatMap((issue) => {
278 const pull = getPull(ctx.app.db, issue.repoId, issue.number);
279 const repo = byId.get(issue.repoId);
280 const wait = pull && repo ? waitsForPerson(ctx.app.db, repo.id, pull) : undefined;
281 return wait === undefined || repo === undefined
282 ? []
283 : [
284 {
285 run: null,
286 app: `${repo.ownerName}/${repo.name}`,
287 who: "you",
288 on: `#${issue.number} ${issue.title}`,
289 why: "review",
290 state: "waiting for your review",
291 says: wait.why === "lapsed" ? "the reviewer did not answer" : "no reviewer on the crew",
292 since: wait.since,
293 costUsd: 0,
294 },
295 ];
296 });
297 return [
298 ...waiting,
299 ...reviewWaits,
300 ...runs.map((r) => {
301 const repo = byId.get(r.repoId)!;
302 const issue =
303 r.issueId === null
304 ? undefined
305 : getIssueById(ctx.app.db, r.issueId);
306 return {
307 run: r.id,
308 app: `${repo.ownerName}/${repo.name}`,
309 who: (r.actorId && actors.get(r.actorId)?.username) || "the crew",
310 on: issue === undefined ? null : `#${issue.number} ${issue.title}`,
311 why: r.reason,
312 state: r.state,
313 since: r.startedAt ?? r.createdAt,
314 // What a run costs is the owner's fact (`canSeeOwnerFacts`).
315 costUsd: owned.has(r.repoId) ? r.costUsd : 0,
316 };
317 }),
318 ];
319 }
320
234321 const TOOLS: readonly Tool[] = [
235322 {
236323 name: "apps",
@@ -568,86 +655,35 @@ const TOOLS: readonly Tool[] = [
568655 "What the crew is doing right now, across your apps: who, on what, since when, and what it has cost so far; a planner that declined the direction and waits for you comes first, as a row with no run and its words in `says`; then each agent pull that waits for your review (no reviewer on the crew, or one that lapsed), with `since`.",
569656 inputSchema: { type: "object", properties: {} },
570657 writes: false,
571 run(ctx, user) {
572 const { repos } = appsOf(ctx, user);
573 const byId = new Map(repos.map((r) => [r.id, r]));
574 // A private app's runs are for those who may enter it (`mayReadRuns`).
575 // A run on a sealed report is for those who may see the report.
576 const runs = listActiveRuns(
577 ctx.app.db,
578 repos.filter((r) => mayReadRuns(ctx.app, user, r)).map((r) => r.id),
579 ).filter((r) =>
580 mayViewId(ctx.app.db, byId.get(r.repoId)!, r.issueId, user),
658 run: (ctx, user) => good(nowRows(ctx, user)),
659 },
660 {
661 name: "brief",
662 description:
663 "How the forge is, in three or four short spoken sentences for reading aloud: the milestones that took merges this week, what waits for you, and how many runs are going. Built from the same numbers as `milestones` and `now`. Answer with `says` as it is.",
664 inputSchema: { type: "object", properties: {} },
665 writes: false,
666 async run(ctx, user) {
667 const { repos } = writableAppsOf(ctx, user);
outdated

This awaits one repo at a time, up to 20 of them, and each milestonesJson call also works out ask-to-live from git. A voice answer should be fast: run them in parallel, or read only the merged counts.

668 const moved: Moved[] = [];
669 // In parallel: each reads git, and a voice answer must be fast.
670 const all = await Promise.all(
671 repos.slice(0, BRIEF_REPOS).map((repo) => milestonesJson(ctx, repo)),
581672 );
582 const actors = getUsersByIds(
583 ctx.app.db,
584 runs.map((r) => r.actorId).filter((id): id is string => id !== null),
585 );
586 // A planner that declined the direction is the crew waiting on you:
587 // it rides the same list, as a row with no run.
588 // Owner facts only: a stranger's public app never shows its planner here.
589 const owned = ownerFactRepoIds(ctx.app.db, repos, user);
590 const waiting = plannerDeclines(
591 ctx.app.db,
592 repos.filter((r) => owned.has(r.id)),
593 ).map((d) => ({
594 run: null,
595 app: `${d.repo.ownerName}/${d.repo.name}`,
596 who: "the planner",
597 on: `#${d.issue.number} ${d.issue.title}`,
598 why: "declined",
599 state: "waiting for you",
600 says: d.words,
601 since: d.at,
602 costUsd: 0,
603 }));
604 // An agent's green pull that waits for a person's review (#597): no
605 // reviewer on the crew, or one that lapsed — with its age, never silent.
606 const ownRepos = repos.filter((r) => owned.has(r.id));
607 const reviewWaits = listOpenAgentPullsVisibleTo(ctx.app.db, user, 200)
608 .filter((i) => ownRepos.some((r) => r.id === i.repoId))
609 .flatMap((issue) => {
610 const pull = getPull(ctx.app.db, issue.repoId, issue.number);
611 const repo = byId.get(issue.repoId);
612 const wait = pull && repo ? waitsForPerson(ctx.app.db, repo.id, pull) : undefined;
613 return wait === undefined || repo === undefined
614 ? []
615 : [
616 {
617 run: null,
618 app: `${repo.ownerName}/${repo.name}`,
619 who: "you",
620 on: `#${issue.number} ${issue.title}`,
621 why: "review",
622 state: "waiting for your review",
623 says: wait.why === "lapsed" ? "the reviewer did not answer" : "no reviewer on the crew",
624 since: wait.since,
625 costUsd: 0,
626 },
627 ];
628 });
629 return good([
630 ...waiting,
631 ...reviewWaits,
632 ...runs.map((r) => {
633 const repo = byId.get(r.repoId)!;
634 const issue =
635 r.issueId === null
636 ? undefined
637 : getIssueById(ctx.app.db, r.issueId);
638 return {
639 run: r.id,
640 app: `${repo.ownerName}/${repo.name}`,
641 who: (r.actorId && actors.get(r.actorId)?.username) || "the crew",
642 on: issue === undefined ? null : `#${issue.number} ${issue.title}`,
643 why: r.reason,
644 state: r.state,
645 since: r.startedAt ?? r.createdAt,
646 // What a run costs is the owner's fact (`canSeeOwnerFacts`).
647 costUsd: owned.has(r.repoId) ? r.costUsd : 0,
648 };
649 }),
650 ]);
673 for (const { limbs } of all) {
674 for (const l of Array.isArray(limbs) ? limbs : []) {
675 const merged = (l.mergedInDays as { merged?: unknown } | undefined)
outdated

now reads appsOf, i.e. every app the caller can see, so activeRuns counts runs on strangers' public apps. Meanwhile line 664 scopes milestones to writableAppsOf. Use the same writable set here and add a test that fails without the fix.

676 ?.merged;
677 if (typeof merged === "number" && merged > 0 && !l.deferred)
678 moved.push({ name: String(l.name), merged });
679 }
680 }
681 // Only the caller's own apps: `now` also lists strangers' public runs.
682 const mine = new Set(repos.map((r) => `${r.ownerName}/${r.name}`));
outdated

A constant in every answer that nothing reads. Remove it.

683 const rows = nowRows(ctx, user).filter((r) => mine.has(r.app));
684 const waits = rows.filter((r) => r.run === null).length;
685 const activeRuns = rows.length - waits;
686 return good({ says: briefWords({ moved, waits, activeRuns }) });
651687 },
652688 },
653689 {
test/brief.test.ts added +43
@@ -0,0 +1,43 @@
1 /** The spoken brief: three or four short sentences, readable aloud. */
2 import { describe, expect, test } from "bun:test";
3 import { briefWords } from "../src/core/brief.ts";
4
5 const sentences = (s: string) => s.split(/(?<=\.)\s+/);
6
7 describe("briefWords", () => {
8 test("says what moved, what needs the owner, and the crew, in four sentences at most", () => {
9 const says = briefWords({
10 moved: [
11 { name: "Mail", merged: 2 },
12 { name: "The `door`", merged: 5 },
13 { name: "Billing", merged: 1 },
14 { name: "Search", merged: 1 },
15 { name: "Idle", merged: 0 },
16 ],
17 waits: 2,
18 activeRuns: 1,
19 wave: "Sign in with a link",
20 });
21 expect(says).toBe(
22 "4 milestones moved this week: The door with 5 changes, Mail with 2 changes and Billing with 1 change, and 1 more. 2 things need you. The crew has 1 run going. The last wave: Sign in with a link.",
23 );
24 expect(sentences(says).length).toBeLessThanOrEqual(4);
25 });
26
27 test("a quiet forge is three plain sentences and no wave is invented", () => {
28 const says = briefWords({ moved: [], waits: 0, activeRuns: 0 });
29 expect(says).toBe(
30 "Nothing merged this week. Nothing needs you. The crew is idle.",
31 );
32 });
33
34 test("a long name is cut and markup is not read aloud", () => {
35 const says = briefWords({
36 moved: [{ name: "# " + "x".repeat(200), merged: 1 }],
37 waits: 1,
38 activeRuns: 0,
39 });
40 expect(says.length).toBeLessThan(200);
41 expect(says).not.toContain("#");
42 });
43 });
test/mcp.test.ts +99 −7
@@ -12,6 +12,9 @@ import { createApp, type App } from "../src/app.ts";
1212 import { addToCrew, createAgent } from "../src/actions/crew.ts";
1313 import { commitToBranch, createRepo, forkRepo } from "../src/actions/repos.ts";
1414 import { createApp as insertApp } from "../src/core/apps.ts";
15 import { linkIssue } from "../src/actions/dependencies.ts";
16 import { openIssue } from "../src/actions/issues.ts";
17 import { mergePull, openPull } from "../src/actions/pulls.ts";
1518 import { listIssues } from "../src/core/issues.ts";
1619 import { getRepoById, type Repo } from "../src/core/repos.ts";
1720 import { createRun, listRuns } from "../src/core/runs.ts";
@@ -67,7 +70,8 @@ describe("the forge over MCP", () => {
6770 app = createApp({ dataDir, port: 0 });
6871 servers = await serve(app);
6972 base = servers.url;
70 const a = await createUser(app.db, { trusted: true,
73 const a = await createUser(app.db, {
74 trusted: true,
7175 username: "alice",
7276 email: "[email protected]",
7377 password: "a-good-passphrase",
@@ -75,7 +79,8 @@ describe("the forge over MCP", () => {
7579 });
7680 if (!a.ok) throw new Error(a.error);
7781 alice = a.value;
78 const b = await createUser(app.db, { trusted: true,
82 const b = await createUser(app.db, {
83 trusted: true,
7984 username: "bob",
8085 email: "[email protected]",
8186 password: "a-good-passphrase",
@@ -166,6 +171,7 @@ describe("the forge over MCP", () => {
166171 "asks_act",
167172 "seal",
168173 "now",
174 "brief",
169175 "stop",
170176 "health",
171177 "audit",
@@ -310,6 +316,12 @@ describe("the forge over MCP", () => {
310316 .error,
311317 ).toContain("finished");
312318 expect((await tool(rw, "now")).value).toEqual([]);
319
320 // The spoken brief: short sentences a voice can read, for a reader too.
321 const brief = await tool(ro, "brief");
322 expect(brief.value.says).toBe(
323 "Nothing merged this week. Nothing needs you. The crew is idle.",
324 );
313325 });
314326
315327 test("say lands on the conversation", async () => {
@@ -365,7 +377,8 @@ describe("the forge over MCP", () => {
365377 expect(
366378 (await tool(ro, "following", { repo: "bob/open" })).value.state,
367379 ).toBe("diverged");
368 const carol = await createUser(app.db, { trusted: true,
380 const carol = await createUser(app.db, {
381 trusted: true,
369382 username: "carol",
370383 email: "[email protected]",
371384 password: "a-good-passphrase",
@@ -527,6 +540,69 @@ describe("the forge over MCP", () => {
527540 ).toContain("forbidden");
528541 });
529542
543 test("the brief names the caller's milestones, never a stranger's public ones", async () => {
544 /** An app of `owner`'s with a pillar whose one change merged. */
545 const moved = async (
546 owner: User,
547 name: string,
548 pillar: string,
549 access: "private" | "public" = "private",
550 ) => {
551 const made = await createRepo(app, owner, { name, visibility: "public" });
552 if (!made.ok) throw new Error(String(made.error));
553 const repo = () => getRepoById(app.db, made.value.id)!;
554 await commitToBranch(app, owner, repo(), {
555 message: "seed",
556 files: [{ path: "README.md", content: `# ${name}\n` }],
557 });
558 const record = insertApp(app.db, {
559 repoId: made.value.id,
560 slug: name,
561 access,
562 });
563 if (!record.ok) throw new Error(record.error);
564 const open = (title: string) => {
565 const o = openIssue(app, owner, repo(), { title });
566 if (!o.ok) throw new Error(String(o.error));
567 return o.value;
568 };
569 const top = open(pillar);
570 const leaf = open(`${name} leaf`);
571 const linked = linkIssue(app, owner, repo(), top, leaf);
572 if (!linked.ok) throw new Error(String(linked.error));
573 await commitToBranch(app, owner, repo(), {
574 branch: "feature/x",
575 base: "main",
576 message: "x",
577 files: [{ path: "x.md", content: "x\n" }],
578 });
579 const pull = await openPull(app, owner, repo(), {
580 title: "Land x",
581 body: `Closes #${leaf.number}`,
582 baseBranch: "main",
583 headBranch: "feature/x",
584 });
585 if (!pull.ok) throw new Error(String(pull.error));
586 const merged = await mergePull(app, owner, repo(), pull.value, "squash");
587 if (!merged.ok) throw new Error(JSON.stringify(merged.error));
588 return made.value.id;
589 };
590 // The stranger (an admin, who writes everything) is newer, so sorts ahead.
591 await moved(bob, "mine", "P0 Mine: the caller's own");
592 const theirs = await moved(
593 alice,
594 "theirs",
595 "P0 Theirs: a stranger's",
596 "public",
597 );
598 // A run on the stranger's public app is theirs to count, not bob's.
599 createRun(app.db, { repoId: theirs, kind: "agent", reason: "assigned" });
600 const says: string = (await tool(bobRw, "brief")).value.says;
601 expect(says).toContain("P0 Mine");
602 expect(says).not.toContain("Theirs");
603 expect(says).toContain("The crew is idle.");
604 }, 30_000);
605
530606 test("a browser session is not a way in, even signed in", async () => {
531607 const signin = await fetch(`${base}/signin`, {
532608 method: "POST",
@@ -567,7 +643,8 @@ describe("the forge over MCP", () => {
567643 const nope = await call(rw, "resources/read", { uri: "ui://forge/nope" });
568644 expect(nope.body.error.code).toBe(-32002);
569645 const tools = (await call(rw, "tools/list")).body.result.tools;
570 const meta = (n: string) => tools.find((t: any) => t.name === n)._meta?.ui?.resourceUri;
646 const meta = (n: string) =>
647 tools.find((t: any) => t.name === n)._meta?.ui?.resourceUri;
571648 expect(meta("apps")).toBe("ui://forge/app");
572649 expect(meta("now")).toBe("ui://forge/run");
573650 expect(meta("asks")).toBe("ui://forge/decision");
@@ -575,7 +652,10 @@ describe("the forge over MCP", () => {
575652 });
576653
577654 test("a tool result carries the card it renders", async () => {
578 const { body } = await call(rw, "tools/call", { name: "apps", arguments: {} });
655 const { body } = await call(rw, "tools/call", {
656 name: "apps",
657 arguments: {},
658 });
579659 const card = body.result.structuredContent.card;
580660 expect(card.kind).toBe("app");
581661 expect(card.rows.some((r: any) => r.label === "alice/game")).toBe(true);
@@ -588,7 +668,15 @@ describe("the forge over MCP", () => {
588668 const tools = (await call(rw, "tools/list")).body.result.tools;
589669 const cards = [
590670 cardFor("apps", [{ app: "alice/game", live: "up" }]),
591 cardFor("now", [{ who: "scout", app: "alice/game", run: "r1", on: "#1", state: "going" }]),
671 cardFor("now", [
672 {
673 who: "scout",
674 app: "alice/game",
675 run: "r1",
676 on: "#1",
677 state: "going",
678 },
679 ]),
592680 cardFor("asks", {
593681 rows: [
594682 { line: "a", kind: "look", items: ["x:1"], words: {} },
@@ -632,7 +720,11 @@ describe("the forge over MCP", () => {
632720 { commit: "--upload-pack=x" },
633721 "text",
634722 ]) {
635 const refused = await tool(rw, "tell", { repo: "alice/game", text: "x", context });
723 const refused = await tool(rw, "tell", {
724 repo: "alice/game",
725 text: "x",
726 context,
727 });
636728 expect(refused.error).toContain("invalid");
637729 }
638730 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs