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

The infra tool names every cloud resource, what each is part of and attached to #17695

opened this

Merged 12h 15m ago, live in production

sold/cloud-list-app → main 0 commits

  • Merged. sold/cloud-list-app was merged into main as 516a968.

Review

Sign in to review this change.
19 files changed +145 −21
docs/features/infra.md +1 −1
@@ -105,7 +105,7 @@ Every DigitalOcean and Hetzner account is read into provider ▸ account ▸ pro
105105 - **Keys.** j and k move, Enter opens, h and l (or the arrows) close and open, `/` filters and Enter goes to the first match.
106106 - **States.** No account (a link to /settings/cloud), not read yet, a failed read (one line: when, why, and how old what is shown is), a kind that could not be read with its reason (on its project and on the account, which says where; under the headline's sum, "Not everything is listed: 1 kind not read" links to that account, and text doors name it; a billed account's gaps count too, and change no sum), and a reading older than three of its duty's intervals. A project's note ("R2 is not switched on for this account") is a plain line and no trouble, on its account too when that has one project. **Check the account** (`a` in the terminal) opens the account: see [Cloud accounts](cloud.md#what-was-not-read-17637).
107107 - **Terminal.** `:` then Cloud resources, or `/` in Infra (`src/tui/screens/cloudtree.ts`): the same list, filter and facts, the List price, Old price, Price from and No price lines among them (both read `factsOf`); `tab` changes pane, `w` opens the web page, `P` reads every account.
108 - **Tool.** `infra` `{action: "list", id: "<filter line>"}` and `{action: "cloud", id: "<cloud>/<account>/<project>/<id>"}`.
108 - **Tool.** `infra` `{action: "list", id: "<filter line>"}` and `{action: "cloud", id: "<cloud>/<account>/<project>/<id>"}` (or a level above). Each resource says its `partOf`, null when no app is known, and its `attachedTo`: each end by the id `cloud` takes, empty for none, null when not known. 50 are named, the costliest first; `says` tells how many more there are, and `next_cursor` passed as `cursor` names the next 50. The terminal names 200 and says the same.
109109
110110 ## What the cloud says of a machine (#17151)
111111
src/cloud/tree.ts +3
@@ -367,6 +367,9 @@ export function resourcesOf(n: CloudNode): CloudNode[] {
367367 /** Every resource under a node, the costliest first. */
368368 export const costliestOf = (n: CloudNode): CloudNode[] => resourcesOf(n).sort(costliest);
369369
370 /** Where a list stops short, what it leaves out and how to see it; empty when it names them all. */
371 export const cutSays = (shown: number, more: number, how: string): string => (more <= 0 ? "" : `${shown.toLocaleString("en-US")} named here, the costliest first; ${more.toLocaleString("en-US")} more: ${how}`);
372
370373 // ---- the filter line ----
371374
372375 /** What a filter may name, and what each reads of a resource. */
src/http/mcp/tools/bring.ts +1 −1
@@ -3,7 +3,7 @@ import { good, bad, str, type Tool } from "../shared.ts";
33
44 export const tool: Tool = {
55 name: "bring",
6 description: "Bring `repo` (link, or owner/name on `origin`) here; `share`: counted (default), named, none.",
6 description: "Bring `repo` (link, or owner/name on `origin`); `share`: counted (default), named, none.",
77 inputSchema: {
88 type: "object",
99 properties: {
src/http/mcp/tools/find_tool.ts +1 −1
@@ -4,7 +4,7 @@ import { FIND_MAX, matching, QUERY_MAX, talkLists } from "../catalog.ts";
44 export const tool: Tool = {
55 name: "find_tool",
66 doc: "`{ query }`: the tools whose name, description or plain-word keywords match every word (else the most words); filler words are ignored, with their one-line description and schema (and, asked by its exact name, its whole doc); a tool found is callable at once, listed or not; Talk's own agent, which can call only what it is listed, is found only those. `tools/list` with `{\"all\": true}` is the full list",
7 description: "Find a tool by what it does: name, description, schema. Any tool is callable by name.",
7 description: "Find a tool by what it does: name, description, schema. Any is callable by name.",
88 inputSchema: {
99 type: "object",
1010 properties: { query: { type: "string", maxLength: QUERY_MAX } },
src/http/mcp/tools/health.ts +1 −1
@@ -6,7 +6,7 @@ export const tool: Tool = {
66 name: "health",
77 doc: "how this forge is: the version and commit it runs, draining or not, the rollout and its incidents; `voice` true answers in two spoken sentences",
88 description:
9 "The forge's health: version, rollout, incidents; ok, broken (act now), todo.",
9 "The forge's version, rollout, incidents; ok, broken (act now), todo.",
1010 inputSchema: {
1111 type: "object",
1212 properties: { voice: { type: "boolean", description: "two plain sentences, no markup" } },
src/http/mcp/tools/infra.ts +36 −6
@@ -1,7 +1,7 @@
11 import { cloudLinesFresh } from "../../../actions/cloud_says.ts";
22 import { infraCode } from "../../../cloud/infra_read.ts";
33 import { accountReads, projectsOf, projectsSays } from "../../../cloud/projects.ts";
4 import { costLine, costliestOf, factsOf, findingOf, moneyWords, nodeAt } from "../../../cloud/tree.ts";
4 import { costLine, costliestOf, cutSays, factsOf, findingOf, moneyWords, nodeAt, tiesOf, type CloudNode } from "../../../cloud/tree.ts";
55 import { buildOf, cloudResources, firewallWant, gameWant, planDatabase, goneWords, infraOf, infraSays, machineOf, nameFor, planById, planCompose, planWants, startBuild } from "../../../actions/infra.ts";
66 import { machineView } from "../../../actions/machine_view.ts";
77 import { bindBucket, readBucket } from "../../../actions/bucket.ts";
@@ -11,10 +11,38 @@ import { planMinecraft } from "../../../actions/minecraft.ts";
1111 import { dnsWantOf } from "../../../cloud/plan.ts";
1212 import { dollars } from "../../../cloud/prices.ts";
1313 import { EXPERIMENT_WORDS, attachMachine, beginExperiment, findExperiment, recordResult } from "../../../cloud/experiments.ts";
14 import { good, bad, type Tool, str } from "../shared.ts";
14 import { pageRows } from "../page.ts";
15 import { good, bad, type Answer, type Args, type Tool, str } from "../shared.ts";
1516
1617 const s = (v: unknown, max: number): string => str(v).slice(0, max);
1718
19 /**
20 * What a resource is attached to, an end the tree holds by the id `cloud` takes: none is empty, and
21 * not known is null.
22 */
23 function attachedTo(whole: CloudNode, n: CloudNode): { id: string; name?: string }[] | null {
24 if (n.resource!.attachedTo === null) return null;
25 return tiesOf(whole, n)[0]!.to.map((e) => (e.node === undefined ? { id: e.id } : { id: e.node.path.join("/"), name: e.node.name }));
26 }
27
28 /**
29 * Cloud resources a page at a time, the costliest first, each with the app it is part of (null when
30 * none is known) and what it is attached to, beside `rest`. `says` ends with how many more there
31 * are, so no list reads as whole when it is not.
32 */
33 function named(whole: CloudNode, nodes: readonly CloudNode[], args: Args, says: string, rest: object): Answer {
34 const page = pageRows(nodes, (n) => n.path.join("/"), args);
35 if (!page.ok) return page;
36 const { items, next_cursor } = page.value as { items: CloudNode[]; next_cursor: string | null };
37 const more = next_cursor === null ? "" : cutSays(items.length, nodes.length - nodes.indexOf(items.at(-1)!) - 1, "pass next_cursor as cursor, or narrow the filter");
38 return good({
39 says: more === "" ? says : `${says.replace(/\.$/, "")}. ${more}`,
40 ...rest,
41 resources: items.map((n) => ({ id: n.path.join("/"), name: n.name, kind: n.resource!.kind, state: n.resource!.state, cost: moneyWords(n.money), partOf: n.resource!.partOf, attachedTo: attachedTo(whole, n), readAt: n.readAt })),
42 next_cursor,
43 });
44 }
45
1846 /**
1947 * Infrastructure (#16696): what runs on the owner's own cloud, what it is for, what it costs and
2048 * when it ends, and building one more machine through a plan. The experiments it holds took the
@@ -24,7 +52,7 @@ const s = (v: unknown, max: number): string => str(v).slice(0, max);
2452 export const tool: Tool = {
2553 name: "infra",
2654 listedTo: "admin",
27 doc: "`{ action, id?, want?, question?, names?, result?, bucket? }`: `list` (its `says` names every machine; with a filter line as `id`, like `kind:volume cloud:aws cost:>10`, the cloud resources it leaves), `show` an `id` (a plan, an experiment or a machine's name), `plan` a `want` `{app, where, question?, experiment?, days?}` or a firewall `{firewall: name}` or a DNS record `{dns: true, name, account, type: A|SRV, host, value, port?}` or a game box `{game: true, where, repo, name?, host?}` or Minecraft Java `{design: minecraft, players, where, domain, dns, repo, eula: true, name?, version?}` (its `compose` comes back with the plan) or Postgres `{database: true, app, where: account@region, size?, secret?}` or dead `names`, `apply` its `id`, `check` DNS records, `code` (infra.json against what runs), `keep`, `begin`, `attach`, `record_result`; `cloud` a machine's name as `id` (its provider's view: power, size, IPs, actions) or a resource's `id` from `list` (as last read); `price`/`bind` a `bucket` `{region, name, repo?, stored_gib?, out_gib?}`.",
55 doc: "`{ action, id?, want?, question?, names?, result?, bucket?, cursor? }`: `list` (its `says` names every machine; with a filter line as `id`, like `kind:volume cloud:aws cost:>10`, the cloud resources it leaves, each with `partOf`, its app, and `attachedTo`; 50 a page, `cursor` for the next), `show` an `id` (a plan, an experiment or a machine's name), `plan` a `want` `{app, where, question?, experiment?, days?}` or a firewall `{firewall: name}` or a DNS record `{dns: true, name, account, type: A|SRV, host, value, port?}` or a game box `{game: true, where, repo, name?, host?}` or Minecraft Java `{design: minecraft, players, where, domain, dns, repo, eula: true, name?, version?}` (its `compose` comes back with the plan) or Postgres `{database: true, app, where: account@region, size?, secret?}` or dead `names`, `apply` its `id`, `check` DNS records, `code` (infra.json against what runs), `keep`, `begin`, `attach`, `record_result`; `cloud` a machine's name as `id` (its provider's view: power, size, IPs, actions) or a resource's `id` from `list` (as last read); `price`/`bind` a `bucket` `{region, name, repo?, stored_gib?, out_gib?}`.",
2856 description: "Machines, spend.",
2957 inputSchema: {
3058 type: "object",
@@ -35,6 +63,8 @@ export const tool: Tool = {
3563 question: { type: "string" },
3664 names: { type: "array" },
3765 result: { type: "string" },
66 bucket: { type: "object" },
67 cursor: { type: "string" },
3868 },
3969 required: ["action"],
4070 },
@@ -55,7 +85,7 @@ export const tool: Tool = {
5585 const all = costliestOf(v.value.root);
5686 const f = findingOf(v.value);
5787 const says = [f.found, f.cost, f.caveat, ...v.value.q.problems].filter((x) => x !== "").map((x, i, all) => (i < all.length - 1 ? x.replace(/\.$/, "") : x)).join(". ");
58 return good({ says, resources: all.slice(0, 50).map((n) => ({ id: n.path.join("/"), name: n.name, kind: n.resource!.kind, state: n.resource!.state, cost: moneyWords(n.money), readAt: n.readAt })) });
88 return named(v.value.whole, all, args, says, {});
5989 }
6090 if (action === "list") {
6191 const v = infraOf(ctx.app, user);
@@ -124,9 +154,9 @@ export const tool: Tool = {
124154 const v = cloudResources(ctx.app, user, "");
125155 const [cloud = "", account = "", project, ...rest] = id.split("/");
126156 const n = v.ok ? nodeAt(v.value.root, [cloud, account, ...(project === undefined ? [] : [project]), ...(rest.length === 0 ? [] : [rest.join("/")])]) : undefined;
127 if (n === undefined) return bad("not_found", "No such cloud resource was read: list with a filter as id names them.");
157 if (!v.ok || n === undefined) return bad("not_found", "No such cloud resource was read: list with a filter as id names them.");
128158 const r = n.resource;
129 return good({ says: `${n.name}: ${costLine(n) || moneyWords(n.money) || "no resources"}`, facts: v.ok ? factsOf(v.value.root, n) : [], readAt: n.readAt, trouble: n.trouble.map((t) => t.says), ...(n.note === "" ? {} : { note: n.note }), resources: r === undefined ? costliestOf(n).slice(0, 50).map((c) => ({ id: c.path.join("/"), cost: moneyWords(c.money) })) : [] });
159 return named(v.value.whole, r === undefined ? costliestOf(n) : [], args, `${n.name}: ${costLine(n) || moneyWords(n.money) || "no resources"}`, { facts: factsOf(v.value.root, n), readAt: n.readAt, trouble: n.trouble.map((t) => t.says), ...(n.note === "" ? {} : { note: n.note }) });
130160 }
131161 const seen = await machineView(ctx.app, user, id);
132162 return seen.ok ? good({ says: seen.value.says, cloud: seen.value.view }) : bad("refused", seen.error.message);
src/http/mcp/tools/invite.ts +1 −1
@@ -26,7 +26,7 @@ export const tool: Tool = {
2626 name: "invite",
2727 doc: "`{ repo, who?, remove?, link?, revoke? }`: admin adds or takes off contributor `who`, makes a one-use `link` (it may make an account), or `revoke`s a link by id; none lists",
2828 description:
29 "Invite to an app by name or one-use link (it may make an account); list, remove.",
29 "Invite to an app by name or one-use link (may make an account); list, remove.",
3030 inputSchema: {
3131 type: "object",
3232 properties: {
src/http/mcp/tools/issue.ts +1 −1
@@ -15,7 +15,7 @@ export const tool: Tool = {
1515 name: "issue",
1616 doc: "`{ repo, number }`: one issue's title, state, closeReason, body, labels, assignee, `outside: true` when its author cannot write here (an outsider's issue, told the same to every viewer; absent otherwise), the newest 50 comments (author, authorIsAgent, body, at), `commentsTotal` and `commentsNext` (older ones: `GET …/comments?cursor=`), `standing` (`{line, ready, before, after, more}`: the sentence saying whether it can start and what holds it now, the chain of what it waits for and what waits for it, each node `{number, title, badge, word, next, quiet, holding}`), blockedBy/blocks and `cost` (`{usd, own, runs, pulls}`, absent when nothing was spent or it is not yours to see), as `GET …/issues/:number`; a sealed one you cannot see is not found; draws the `ui://forge/issue` card: title, state, assignee, labels and what it waits for, never the body or comments",
1717 description:
18 "One issue, its comments, `blockedBy`, `blocks`; `untrusted` and `outside` mark outsiders.",
18 "One issue, its comments, `blockedBy`, `blocks`; `untrusted`, `outside`: outsiders.",
1919 inputSchema: {
2020 type: "object",
2121 properties: {
src/http/mcp/tools/issues.ts +1 −1
@@ -13,7 +13,7 @@ import { good, bad, limitArg, type Tool, REPO_ARG, repoArg, isAnswer } from "../
1313 export const tool: Tool = {
1414 name: "issues",
1515 doc: "`{ repo, state?, label?, author?, limit?, cursor? }`: a repository's issues, newest first, as `{ items, next_cursor }` like `GET …/issues?fields=brief`: `number`, `title`, `state`, `labels`, `assignee`, `author`, `authorIsAgent`, `createdAt`, `updatedAt`, and `untrusted: true` on text from someone who cannot write, `standing: true` on the repository's direction issue (the one open issue no count of open issues includes); `state` open (default), closed or all, `label` a name, `author` a username, `limit` 1-200 (default 50), `cursor` the last `next_cursor`; a sealed issue you cannot see is left out, a repository you cannot read is not found; draws the `ui://forge/issues` card: state, pillar and what each waits on",
16 description: "A repository's issues by state, label and author, newest first, paged.",
16 description: "A repo's issues by state, label and author, newest first, paged.",
1717 inputSchema: {
1818 type: "object",
1919 properties: {
src/http/mcp/tools/merge.ts +1 −1
@@ -37,7 +37,7 @@ function greenRefused(ctx: Ctx, pull: Pull, action: unknown): Answer | undefined
3737 export const tool: Tool = {
3838 name: "merge",
3939 doc: "`{ repo, number, strategy?, action?, dryRun? }` (a person, never an agent: a person merges): land a pull as its page's Merge button does, `merge` (default) or `squash`; `action: \"land\"` is the page's Ship it as it is (squash, and only while the check is green); plans carry `crew` when the crew cannot go on; planned unless `dryRun` is false: the plan is the pull's `head`, `base`, `mergeable`, `conflicts` and `check` as `pull` reads them; landing is `mergePull`'s, with its refusals (conflict, review or check required, not a writer) in the page's words, and takes an rw token",
40 description: "Land a pull, as its page's Merge button does; a person's only.",
40 description: "Land a pull, as its Merge button does; a person's only.",
4141 inputSchema: {
4242 type: "object",
4343 properties: {
src/http/mcp/tools/propose_upstream.ts +1 −1
@@ -4,7 +4,7 @@ import { good, bad, str, type Tool } from "../shared.ts";
44
55 export const tool: Tool = {
66 name: "propose_upstream",
7 description: "Your copy `repo`'s `branch` as a pull (`title`) at its origin; without `plan`, plans.",
7 description: "Your copy `repo`'s `branch` as a pull request (`title`) at its origin; without `plan`, plans.",
88 inputSchema: {
99 type: "object",
1010 properties: {
src/http/mcp/tools/read_file.ts +1 −1
@@ -23,7 +23,7 @@ export const tool: Tool = {
2323 name: "read_file",
2424 doc: "`{ repo, path, ref? }`: a file (utf-8 or base64) or a directory listing at a ref, as GET …/contents; MP4/MOV/M4A files also carry about: {kind, seconds, width?, height?, says}, a .pcd {kind: pcd, points, width, height, data, fields, bounds?, says}; .mid {bpm, tracks}; .ifc {says}; .blend {version, codes}; .torrent {name, size, infoHash, trackers, files}; .m3u {tracks, seconds}; .reg {keys, values, deletedKeys, deletedValues}",
2525 description:
26 "No shell? Read a file or list a folder at a ref (default branch); over 5 MB: tooLarge.",
26 "No shell? Read a file or folder at a ref (default branch); over 5 MB: tooLarge.",
2727 inputSchema: {
2828 type: "object",
2929 properties: {
src/http/mcp/tools/stop.ts +1 −1
@@ -6,7 +6,7 @@ export const tool: Tool = {
66 name: "stop",
77 doc: "`{ repo?, run? }`: stop one run by its id from `now`; with no `repo` it stops the forge's own agent mid-answer",
88 description:
9 "Stop a crew run by its id from `now`; no repo: the forge's own agent mid-answer.",
9 "Stop a crew run by its id from `now`; no repo: the forge's agent mid-answer.",
1010 inputSchema: {
1111 type: "object",
1212 properties: { repo: REPO_ARG, run: { type: "string" } },
src/http/mcp/tools/threads.ts +1 −1
@@ -7,7 +7,7 @@ export const tool: Tool = {
77 name: "threads",
88 doc: "`{ repo, number, anchor?, resolved? }`: a pull's review threads with their comments; with `anchor` (from the list) resolve it (`resolved` true, the default) or reopen it (false), by the API's rules: a writer or someone who commented in the thread",
99 description:
10 "A pull's review threads; with `anchor`, resolve one or reopen (`resolved` false).",
10 "A pull's review threads; with `anchor`, resolve or reopen (`resolved` false).",
1111 inputSchema: {
1212 type: "object",
1313 properties: {
src/http/mcp/tools/wall.ts +1 −1
@@ -32,7 +32,7 @@ function heldPull(ctx: Ctx, user: User, args: Args): { pull: Pull; words: string
3232 export const tool: Tool = {
3333 name: "wall",
3434 doc: "`{ repo, number, answer: allow|send_back, why? }`: a person answers the access wall on a pull: allow merges, send back asks for changes",
35 description: "Answer the access wall on a pull: allow it (merge) or send it back.",
35 description: "Answer the access wall on a pull: allow (merge) or send back.",
3636 inputSchema: {
3737 type: "object",
3838 properties: {
src/tui/screens/cloudtree.ts +6 −2
@@ -6,7 +6,7 @@
66 */
77
88 import { cloudResources, readProjectsNow } from "../../actions/infra.ts";
9 import { cloudName, costLine, costliestOf, factsOf, findingOf, isStale, largestCosts, moneyMark, nodeAt, unreadAccounts, unreadLine, unpricedSays, unused, type CloudNode, type CloudView } from "../../cloud/tree.ts";
9 import { cloudName, costLine, costliestOf, cutSays, factsOf, findingOf, isStale, largestCosts, moneyMark, nodeAt, unreadAccounts, unreadLine, unpricedSays, unused, type CloudNode, type CloudView } from "../../cloud/tree.ts";
1010 import { dollars } from "../../cloud/prices.ts";
1111 import { keyOf } from "../../web/keymap.ts";
1212 import type { Ctx, Screen } from "../app/app.ts";
@@ -34,6 +34,9 @@ const markOf = (n: CloudNode): string => {
3434 return [m.mark, m.sum].filter((x) => x !== "").join(" ");
3535 };
3636
37 /** The most resources an open node names. */
38 const PANE_LINES = 200;
39
3740 /** What a node says when it is open: its cost first, then its facts or its costliest resources. */
3841 export function cloudLines(v: CloudView, n: CloudNode): string[] {
3942 const cost = costLine(n) || (n.count === 0 ? "No resources." : unpricedSays(v, n));
@@ -45,13 +48,14 @@ export function cloudLines(v: CloudView, n: CloudNode): string[] {
4548 if (n.resource !== undefined) return [...head, "", ...factsOf(v.whole, n).map((f) => `${f.label.padEnd(12)} ${f.value}`), `${"Created".padEnd(12)} ${n.resource.createdAt.slice(0, 10)}`, read];
4649 const goes = v.q.text === "" ? largestCosts(n, 6).filter((c) => c.from === "billed") : [];
4750 const line = (sum: string, words: string): string => `${sum.padStart(13)} ${words}`;
51 const cut = cutSays(PANE_LINES, n.count - PANE_LINES, "/ narrows the filter");
4852 return [
4953 ...head,
5054 ...(read === "" ? [] : [read]),
5155 ...trouble,
5256 ...(n.note === "" ? [] : [`${n.note}.`]),
5357 ...(goes.length === 0 ? [] : ["", "Where it goes", ...goes.map((c) => line(dollars(c.cents), `${c.says} · ${c.where}${c.hint === "" ? "" : ` · ${c.hint}`}`))]),
54 ...(n.count === 0 ? [] : ["", `${n.count} ${n.count === 1 ? "resource" : "resources"}`, ...costliestOf(n).slice(0, 200).map((c) => line(markOf(c), `${c.name} · ${[c.resource!.kind, unused(c.resource!) ? "unattached" : c.resource!.state].filter((x) => x !== "").join(" · ")}`))]),
58 ...(n.count === 0 ? [] : ["", `${n.count} ${n.count === 1 ? "resource" : "resources"}`, ...costliestOf(n).slice(0, PANE_LINES).map((c) => line(markOf(c), `${c.name} · ${[c.resource!.kind, unused(c.resource!) ? "unattached" : c.resource!.state].filter((x) => x !== "").join(" · ")}`)), ...(cut === "" ? [] : [cut])]),
5559 ];
5660 }
5761
test/cloud-tree.test.ts +42
@@ -591,6 +591,48 @@ test("a resource says which app it is part of and how that is known; app: finds
591591 app.db.run("DELETE FROM cloud_account WHERE name = 'apps'");
592592 });
593593
594 test("the infra tool names what each resource is part of, and all of them, 50 at a time, under a filter or a region", async () => {
595 ownAccount("aws", "many");
596 project("aws", "many", "us-east-1");
597 for (let i = 0; i < 77; i++) resource("aws", "many", "us-east-1", `volume:m-${String(i).padStart(2, "0")}`, 1000 - i);
598 app.db.run("UPDATE cloud_resource SET part_of = 'shop', part_of_how = 'its tags' WHERE cloud_resource_id IN ('volume:m-00', 'volume:m-76')");
599 const token = createToken(app.db, alice.id, "many", "admin").token;
600 for (const ask of [{ action: "list", id: "account:many" }, { action: "cloud", id: "aws/many/us-east-1" }]) {
601 const first = (await mcpTool(servers.url, token, "infra", ask)).value;
602 expect(first.resources).toHaveLength(50);
603 expect(first.says).toContain("50 named here, the costliest first; 27 more: pass next_cursor as cursor, or narrow the filter");
604 const rest = (await mcpTool(servers.url, token, "infra", { ...ask, cursor: first.next_cursor })).value;
605 expect(rest.resources).toHaveLength(27);
606 expect(rest.next_cursor).toBeNull();
607 const all = [...first.resources, ...rest.resources];
608 expect(new Set(all.map((r: { id: string }) => r.id)).size).toBe(77);
609 expect([all[0].partOf, all[1].partOf, all[76].partOf]).toEqual([{ app: "shop", by: "its tags" }, null, { app: "shop", by: "its tags" }]);
610 expect((await mcpTool(servers.url, token, "infra", { ...ask, cursor: "aws/many/us-east-1/volume:gone" })).error).toContain("invalid_cursor");
611 }
612 const shop = (await mcpTool(servers.url, token, "infra", { action: "list", id: "account:many app:shop" })).value;
613 expect([shop.resources.length, shop.next_cursor]).toEqual([2, null]);
614 expect(shop.says).not.toContain("next_cursor");
615 // The terminal's own cut says it in the same words, and only when it cuts.
616 const region = (): string => cloudLines(view(), at(view(), "aws", "many", "us-east-1")).join("\n");
617 expect(region()).not.toContain("named here");
618 for (let i = 77; i < 230; i++) resource("aws", "many", "us-east-1", `volume:n-${i}`, 1);
619 expect(region()).toContain("200 named here, the costliest first; 30 more: / narrows the filter");
620 });
621
622 test("the infra tool's list says what each resource is attached to: ids it can open, none, or not known", async () => {
623 ownAccount("aws", "tied");
624 project("aws", "tied", "us-east-1");
625 resource("aws", "tied", "us-east-1", "machine:i-9", 900, { title: "api" });
626 resource("aws", "tied", "us-east-1", "volume:on", 800, { on: ["machine:i-9", "machine:i-gone"] });
627 resource("aws", "tied", "us-east-1", "volume:off", 700, { on: [] });
628 const token = createToken(app.db, alice.id, "tied", "admin").token;
629 // A filter that leaves the machine out still names it.
630 const said = (await mcpTool(servers.url, token, "infra", { action: "list", id: "account:tied kind:volume" })).value.resources;
631 expect(said.map((r: { attachedTo: unknown }) => r.attachedTo)).toEqual([[{ id: "aws/tied/us-east-1/machine:i-9", name: "api" }, { id: "machine:i-gone" }], []]);
632 expect((await mcpTool(servers.url, token, "infra", { action: "cloud", id: said[0].attachedTo[0].id })).value.says).toStartWith("api: ");
633 expect((await mcpTool(servers.url, token, "infra", { action: "list", id: "account:tied kind:machine" })).value.resources[0].attachedTo).toBeNull();
634 });
635
594636 test("strangers' text is text: markup in a name, a filter cut inside an emoji, a kind that is a word of JavaScript", async () => {
595637 account("aws", "odd");
596638 project("aws", "odd", "us-east-1");
test/infra-bucket.test.ts +15
@@ -11,8 +11,11 @@ import { BUCKET_SECRET, bindBucket, readBucket } from "../src/actions/bucket.ts"
1111 import { BUCKETS, bucketCents, bucketOf, bucketUrl } from "../src/cloud/bucket.ts";
1212 import { createRepo } from "../src/core/repos.ts";
1313 import { createUser, type User } from "../src/core/users.ts";
14 import { createToken } from "../src/core/tokens.ts";
1415 import type { Ctx } from "../src/http/context.ts";
1516 import { tool } from "../src/http/mcp/tools/infra.ts";
17 import { serve } from "../src/http/server.ts";
18 import { mcpTool } from "./helpers/mcp.ts";
1619
1720 const spaces = BUCKETS["digitalocean"]!;
1821
@@ -92,6 +95,18 @@ describe("binding to an app", () => {
9295 const bad = (await tool.run(ctx, admin, { action: "price", bucket: { region: "ams3", name: "x" } })) as any;
9396 expect(bad.ok).toBe(false);
9497 });
98 test("over MCP, as an agent calls it: the server takes `bucket`", async () => {
99 const servers = await serve(app);
100 try {
101 const token = createToken(app.db, admin.id, "bucket", "admin").token;
102 const p = await mcpTool(servers.url, token, "infra", { action: "price", bucket: { region: "ams3", name: "pics", stored_gib: 300 } });
103 expect([p.error, p.value?.cents]).toEqual([undefined, 600]);
104 const b = await mcpTool(servers.url, token, "infra", { action: "bind", bucket: { repo: "ada/files", region: "ams3", name: "pics" } });
105 expect([b.error, b.value?.url]).toEqual([undefined, "https://pics.ams3.digitaloceanspaces.com"]);
106 } finally {
107 servers.stop();
108 }
109 });
95110 test("a value that is not a whole non-negative number is refused, not priced as 0", async () => {
96111 const url = new URL("http://forge.test/mcp");
97112 const ctx: Ctx = { app, request: new Request(url.href), url, params: {}, auth: { user: admin, scope: "admin", via: "token" }, theme: undefined };
test/mcp-doc-arguments.test.ts added +30
@@ -0,0 +1,30 @@
1 /**
2 * Every argument a tool's doc lists is one its schema declares: the server refuses any other, so a
3 * doc that names one is an instruction that cannot be followed (`infra`'s `bucket`, #17073).
4 */
5 import { expect, test } from "bun:test";
6 import * as tools from "../src/http/mcp/tools/index.ts";
7
8 /** The top-level names of a doc that opens "`{ repo, plan?: { … }, move?: [x, y] }`". */
9 function listed(doc: string): string[] {
10 let args = /^`\{([^`]*)\}`/.exec(doc)?.[1] ?? "";
11 for (let before = ""; before !== args; ) [before, args] = [args, args.replace(/\{[^{}]*\}|\[[^[\]]*\]/g, "")];
12 return args.split(",").flatMap((a) => /^\s*([A-Za-z_]\w*)/.exec(a)?.[1] ?? []);
13 }
14
15 test("the names are read past nested shapes", () => {
16 expect(listed("`{ app, plan: { a, b: [{c,d}] }, move?: [dx, dy], confirm? }`: x")).toEqual(["app", "plan", "move", "confirm"]);
17 });
18
19 test("no tool's doc lists an argument the server would refuse", () => {
20 let read = 0;
21 const refused = Object.values(tools).flatMap((t) => {
22 const props = t.inputSchema["properties"] as Record<string, unknown> | undefined;
23 const names = listed(t.doc ?? "");
24 read += names.length;
25 // A schema that names no properties, or is open, takes any.
26 return props === undefined || t.inputSchema["additionalProperties"] === true ? [] : names.filter((n) => !Object.hasOwn(props, n)).map((n) => `${t.name}.${n}`);
27 });
28 expect(refused).toEqual([]);
29 expect(read).toBeGreaterThan(300);
30 });

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs