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
Check · Review · Land · Live done — Landed and live in production.
scout/forge:scout/13941-the-mcp-has-a-wallet-tool-balance-and-th → main 2 commits fork 2 threads · 2 unresolved
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 | ||
| 727 | 727 | 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. |
| 728 | 728 | |
| 729 | 729 | `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 | |
| 731 | 731 | spends in the wallet page's words. Dollars come from `money` and the balance |
| 732 | 732 | from `balanceWords` (`src/core/wallet.ts`), the same the page and terminal use; |
| 733 | 733 | `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 | ||
| 84 | 84 | } |
| 85 | 85 | |
| 86 | 86 | |
| 87 | export const SUMMARY_SPENDS = 3; | |
| 87 | export const SUMMARY_SPENDS = 10; | |
| 88 | 88 | |
| 89 | 89 | export interface WalletSummary { |
| 90 | 90 | readonly app: string; |
| @@ -97,7 +97,7 @@ export interface WalletSummary { | ||
| 97 | 97 | /** The wallet line's words. */ |
| 98 | 98 | readonly balance: string; |
| 99 | 99 | /** |
| 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. | |
| 101 | 101 | */ |
| 102 | 102 | readonly latest: readonly string[]; |
| 103 | 103 | } |
| @@ -107,7 +107,7 @@ export const spendWords = (s: WalletSpend): string => | ||
| 107 | 107 | `${s.date} ${money(s.costUsd)} ${s.paidFor}${s.outcome === "ok" ? "" : ` (${s.outcome})`}`; |
| 108 | 108 | |
| 109 | 109 | /** |
| 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 | |
| 111 | 111 | * (`not_found`). |
| 112 | 112 | */ |
| 113 | 113 | 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" | ||
| 4 | 4 | |
| 5 | 5 | export const tool: Tool = { |
| 6 | 6 | 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", | |
| 8 | 8 | description: |
| 9 | 9 | "Crew spend by `repo` and `days`, or its wallet with `kind: wallet`. Writers.", |
| 10 | 10 | inputSchema: { |
test/mcp-wallet.test.ts +60 −5
| @@ -1,5 +1,5 @@ | ||
| 1 | 1 | /** |
| 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 | |
| 3 | 3 | * words: one formatter (`money`, `balanceWords`) for amounts and balance. |
| 4 | 4 | */ |
| 5 | 5 | import { afterAll, beforeAll, expect, test } from "bun:test"; |
| @@ -11,6 +11,7 @@ import { readWallet } from "../src/actions/wallet.ts"; | ||
| 11 | 11 | import { createApp, type App } from "../src/app.ts"; |
| 12 | 12 | import { getRepo } from "../src/core/repos.ts"; |
| 13 | 13 | import { createRun } from "../src/core/runs.ts"; |
| 14 | import { createToken, revokeToken } from "../src/core/tokens.ts"; | |
| 14 | 15 | import { createUser, type User } from "../src/core/users.ts"; |
| 15 | 16 | import { balanceWords, capReached, money, setMonthCap } from "../src/core/wallet.ts"; |
| 16 | 17 | import { tool } from "../src/http/mcp/tools/usage.ts"; |
| @@ -76,7 +77,7 @@ const ctxFor = (user: User | undefined): Ctx => ({ | ||
| 76 | 77 | const ask = (user: User, args: Record<string, unknown>) => |
| 77 | 78 | tool.run(ctxFor(user), user, { repo: "trevato/garden", kind: "wallet", ...args }) as { ok: boolean; value?: any; error?: any }; |
| 78 | 79 | |
| 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 () => { | |
| 80 | 81 | const r = ask(owner, {}); |
| 81 | 82 | expect(r.ok).toBe(true); |
| 82 | 83 | 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 | ||
| 84 | 85 | expect(v.left).toBeNull(); |
| 85 | 86 | expect(v.spent).toBe(money(1.005 + 2 + 0.5 + 4.25)); |
| 86 | 87 | expect(v.balance).toBe(`No monthly cap; ${v.spent} spent this month.`); |
| 87 | expect(v.latest).toHaveLength(3); | |
| 88 | expect(v.latest).toHaveLength(4); | |
| 88 | 89 | expect(v.lastSpend).toBeUndefined(); |
| 89 | 90 | expect(v.latest[0]).toMatch(/^\d{4}-\d{2}-\d{2} \$\d+\.\d\d build/); |
| 90 | 91 | const page = await (await fetch(servers.url + "/trevato/garden/wallet", { headers: { cookie } })).text(); |
| 91 | 92 | // 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)) { | |
| 93 | 94 | expect(page).toContain(money(w.costUsd)); |
| 94 | 95 | } |
| 95 | 96 | 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", () => { | ||
| 115 | 116 | .query(`INSERT INTO usage (run_id, repo_id, kind, cost_usd, outcome, at) VALUES (?1, ?2, 'build', 9, 'failed', ?3)`) |
| 116 | 117 | .run(run.id, repoId, new Date(Date.now() + 1000).toISOString()); |
| 117 | 118 | const latest = ask(owner, {}).value.latest as string[]; |
| 118 | expect(latest).toHaveLength(3); | |
| 119 | expect(latest).toHaveLength(5); | |
| 119 | 120 | expect(latest[0]).toMatch(/^\d{4}-\d{2}-\d{2} \$9\.00 build.* \(failed\)$/); |
| 120 | 121 | expect(latest[1]).not.toContain("("); |
| 121 | 122 | }); |
| @@ -130,3 +131,57 @@ test("a stranger and a visitor get the not-found the page gives; bad arguments a | ||
| 130 | 131 | expect(JSON.stringify(ask(owner, { kind: "other" }))).toContain("invalid_kind"); |
| 131 | 132 | expect(JSON.stringify(ask(owner, { days: 3 }))).toContain("invalid_days"); |
| 132 | 133 | }); |
| 134 | ||
outdated
This calls |
||
| 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(/'/g, "'").replace(/&/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, "'")); | |
| 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 | }); |
new above
offline
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.