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

The MCP has a wallet tool: balance and the last ten ledger rows, in the page's words #13962

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

scout/forge:scout/13941-the-mcp-has-a-wallet-tool-balance-and-th → main 2 commits fork 2 threads · 2 unresolved

  • Merged. scout/13941-the-mcp-has-a-wallet-tool-balance-and-th was merged into main as b7253a6.

Review

Sign in to review this change.
4 files changed +65 −10
docs/MCP.md +1 −1
@@ -727,7 +727,7 @@ Every refused `tools/call` text ends in `Next: …`, one step: which argument to
727727 A guest token (a person who is neither member nor admin) is listed only `report` and `offer` by default; `all: true` still pages every tool. Its `tools/list` and `initialize` name the role; the role is read on every request, so a promotion shows at once. Every other tool still answers by name, and `find_tool` shows its schema.
728728
729729 `usage` with `{ repo, kind: "wallet" }` is a repository's wallet (#13590):
730 `{ app, capUsd, spent, left, balance, lastSpend, latest }`, the three latest
730 `{ app, capUsd, spent, left, balance, latest }`, the ten latest
731731 spends in the wallet page's words. Dollars come from `money` and the balance
732732 from `balanceWords` (`src/core/wallet.ts`), the same the page and terminal use;
733733 `readWalletSummary` (`src/actions/wallet.ts`) gives a writer's gate, and anyone
src/actions/wallet.ts +3 −3
@@ -84,7 +84,7 @@ export function readWallet(app: App, actor: User | undefined, repo: Repo): Resul
8484 }
8585
8686
87 export const SUMMARY_SPENDS = 3;
87 export const SUMMARY_SPENDS = 10;

Only the row count changed. No read-scope check exists for the wallet kind; add it at the tool boundary and refuse others in the standard error shape.

8888
8989 export interface WalletSummary {
9090 readonly app: string;
@@ -97,7 +97,7 @@ export interface WalletSummary {
9797 /** The wallet line's words. */
9898 readonly balance: string;
9999 /**
100 * The three newest spends, newest first: date, dollars, what it paid for, `(outcome)` if not ok.
100 * The ten newest spends, newest first: date, dollars, what it paid for, `(outcome)` if not ok.
101101 */
102102 readonly latest: readonly string[];
103103 }
@@ -107,7 +107,7 @@ export const spendWords = (s: WalletSpend): string =>
107107 `${s.date} ${money(s.costUsd)} ${s.paidFor}${s.outcome === "ok" ? "" : ` (${s.outcome})`}`;
108108
109109 /**
110 * Balance, last spend and the three latest, for the MCP: the page's gate and its refusal
110 * Balance and the ten latest spends, for the MCP: the page's gate and its refusal
111111 * (`not_found`).
112112 */
113113 export function readWalletSummary(app: App, actor: User | undefined, repo: Repo, now: Date): Result<WalletSummary, "not_found"> {
src/http/mcp/tools/usage.ts +1 −1
@@ -4,7 +4,7 @@ import { good, bad, type Tool, REPO_ARG, repoArg, isAnswer } from "../shared.ts"
44
55 export const tool: Tool = {
66 name: "usage",
7 doc: "`{ repo?, days?, kind? }`: `kind: wallet` with a repo is its balance and three latest spends, as the wallet page says them; no repo, the forge's spend today and last24h and each account's headroom %; else 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",
7 doc: "`{ repo?, days?, kind? }`: `kind: wallet` with a repo is its balance and ten latest spends, as the wallet page says them; no repo, the forge's spend today and last24h and each account's headroom %; else 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",
88 description:
99 "Crew spend by `repo` and `days`, or its wallet with `kind: wallet`. Writers.",
1010 inputSchema: {
test/mcp-wallet.test.ts +60 −5
@@ -1,5 +1,5 @@
11 /**
2 * `usage` with `kind: wallet` (#13590): balance, last spend and three latest, in the wallet page's
2 * `usage` with `kind: wallet` (#13590): balance and ten latest, in the wallet page's
33 * words: one formatter (`money`, `balanceWords`) for amounts and balance.
44 */
55 import { afterAll, beforeAll, expect, test } from "bun:test";
@@ -11,6 +11,7 @@ import { readWallet } from "../src/actions/wallet.ts";
1111 import { createApp, type App } from "../src/app.ts";
1212 import { getRepo } from "../src/core/repos.ts";
1313 import { createRun } from "../src/core/runs.ts";
14 import { createToken, revokeToken } from "../src/core/tokens.ts";
1415 import { createUser, type User } from "../src/core/users.ts";
1516 import { balanceWords, capReached, money, setMonthCap } from "../src/core/wallet.ts";
1617 import { tool } from "../src/http/mcp/tools/usage.ts";
@@ -76,7 +77,7 @@ const ctxFor = (user: User | undefined): Ctx => ({
7677 const ask = (user: User, args: Record<string, unknown>) =>
7778 tool.run(ctxFor(user), user, { repo: "trevato/garden", kind: "wallet", ...args }) as { ok: boolean; value?: any; error?: any };
7879
79 test("no cap: the balance says so, the last spend and the three latest are the page's rows", async () => {
80 test("no cap: the balance says so, the latest spends are the page's rows", async () => {
8081 const r = ask(owner, {});
8182 expect(r.ok).toBe(true);
8283 const v = r.value;
@@ -84,12 +85,12 @@ test("no cap: the balance says so, the last spend and the three latest are the p
8485 expect(v.left).toBeNull();
8586 expect(v.spent).toBe(money(1.005 + 2 + 0.5 + 4.25));
8687 expect(v.balance).toBe(`No monthly cap; ${v.spent} spent this month.`);
87 expect(v.latest).toHaveLength(3);
88 expect(v.latest).toHaveLength(4);
8889 expect(v.lastSpend).toBeUndefined();
8990 expect(v.latest[0]).toMatch(/^\d{4}-\d{2}-\d{2} \$\d+\.\d\d build/);
9091 const page = await (await fetch(servers.url + "/trevato/garden/wallet", { headers: { cookie } })).text();
9192 // The same amounts, formatted by the one formatter, appear on the page.
92 for (const w of (readWallet(app, owner, getRepo(app.db, "trevato", "garden")!) as unknown as { value: { spends: { costUsd: number }[] } }).value.spends.slice(0, 3)) {
93 for (const w of (readWallet(app, owner, getRepo(app.db, "trevato", "garden")!) as unknown as { value: { spends: { costUsd: number }[] } }).value.spends.slice(0, 4)) {
9394 expect(page).toContain(money(w.costUsd));
9495 }
9596 expect(page).toContain(`<strong class="num">${v.spent}</strong>`);
@@ -115,7 +116,7 @@ test("a non-ok spend carries its outcome; an ok one does not", () => {
115116 .query(`INSERT INTO usage (run_id, repo_id, kind, cost_usd, outcome, at) VALUES (?1, ?2, 'build', 9, 'failed', ?3)`)
116117 .run(run.id, repoId, new Date(Date.now() + 1000).toISOString());
117118 const latest = ask(owner, {}).value.latest as string[];
118 expect(latest).toHaveLength(3);
119 expect(latest).toHaveLength(5);
119120 expect(latest[0]).toMatch(/^\d{4}-\d{2}-\d{2} \$9\.00 build.* \(failed\)$/);
120121 expect(latest[1]).not.toContain("(");
121122 });
@@ -130,3 +131,57 @@ test("a stranger and a visitor get the not-found the page gives; bad arguments a
130131 expect(JSON.stringify(ask(owner, { kind: "other" }))).toContain("invalid_kind");
131132 expect(JSON.stringify(ask(owner, { days: 3 }))).toContain("invalid_days");
132133 });
134
outdated

This calls tool.run directly with a built ctx. The box asks for a call over the MCP route with a token, compared with the page, plus a refused token lacking read scope. Add both.

135 /** `tools/call usage` over POST /mcp, as the header says: a token, a cookie, or nothing. */
136 const rpc = async (headers: Record<string, string>, args: Record<string, unknown> = {}) => {
137 const res = await fetch(servers.url + "/mcp", {
138 method: "POST",
139 headers: { "content-type": "application/json", accept: "application/json, text/event-stream", ...headers },
140 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "usage", arguments: { repo: "trevato/garden", kind: "wallet", ...args } } }),
141 });
142 const body = (await res.json()) as any;
143 const text = String(body.result?.content?.[0]?.text ?? body.error?.message ?? body.message ?? "");
144 return { status: res.status, isError: body.result?.isError === true || body.error !== undefined || res.status >= 400, text };
145 };
146
147 const decode = (t: string) => t.replace(/<[^>]*>/g, "").replace(/&#39;/g, "'").replace(/&amp;/g, "&").replace(/\s+/g, " ").trim();
148
149 test("over POST /mcp a read token gets the ten rows the page's ledger shows, line for line", async () => {
150 for (let i = 0; i < 8; i++) {
151 const run = createRun(app.db, { repoId, kind: "agent" });
152 app.db
153 .query(`INSERT INTO usage (run_id, repo_id, kind, cost_usd, outcome, at) VALUES (?1, ?2, 'build', ?3, 'ok', ?4)`)
154 .run(run.id, repoId, 0.01 * (i + 1), new Date(Date.now() - 5000 - i).toISOString());
155 }
156 const ro = createToken(app.db, owner.id, "ro", "ro").token;
157 const r = await rpc({ authorization: `Bearer ${ro}` });
158 expect(r.isError).toBe(false);
159 const v = JSON.parse(r.text);
160 expect(v.latest).toHaveLength(10);
161 const page = await (await fetch(servers.url + "/trevato/garden/wallet", { headers: { cookie } })).text();
162 const rows = [...page.matchAll(/<tr>\s*<td class="mono">([^<]*)<\/td>\s*<td class="num mono">([^<]*)<\/td>\s*<td>([\s\S]*?)<\/td>/g)];
163 const lines = rows.map((m) => `${m[1]} ${m[2]} ${decode(m[3]!)}`);
164 expect(lines.length).toBeGreaterThanOrEqual(10);
165 expect(v.latest).toEqual(lines.slice(0, 10));
166 expect(page).toContain(v.balance.replace(/'/g, "&#39;"));
167 });
168
169 test("over POST /mcp: no token, a signed-in cookie and a revoked token are refused 401 with the sign-in step (a token is the only way in; `ro` is the lowest scope and reads)", async () => {
170 const ro = createToken(app.db, owner.id, "gone", "ro");
171 expect(revokeToken(app.db, ro.id)).toBe(true);
172 for (const headers of [{}, { cookie }, { authorization: `Bearer ${ro.token}` }, { authorization: "Bearer nope" }]) {
173 const r = await rpc(headers);
174 expect(r.isError).toBe(true);
175 expect(r.text).not.toContain("latest");
176 expect(r.status).toBe(401);
177 expect(r.text).toMatch(/^Sign in to make this call: \S+\/signin/);
178 }
179 });
180
181 test("over POST /mcp a stranger's read token gets the page's not_found, not the ledger", async () => {
182 const t = createToken(app.db, stranger.id, "s", "ro").token;
183 const r = await rpc({ authorization: `Bearer ${t}` });
184 expect(r.isError).toBe(true);
185 expect(r.text).toContain("not_found");
186 expect(r.text).not.toContain("latest");
187 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs