diff --git a/CLAUDE.md b/CLAUDE.md index 408acba..9f5b2eb 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -5,6 +5,7 @@ Personal finance app. Next.js 15 (app router), Supabase (sign-in, Postgres, row- ## Rules for any change - **Bank data stays private.** Every AI path goes through `src/lib/llm/gate.ts`. A cloud model gets the summary only: rounded amounts, names replaced by tokens. Full detail goes only to a local model. Never add another path. + - One exception, the person's own explicit choice: an MCP token made with "Full detail" on Connect your AI (`src/app/api/mcp`, migration 0034). Summary stays the default, IBANs and account numbers stay shortened, and a token only ever reaches its own user's rows (their session, plus a `user_id` filter in every tool, so a partner's shared accounts never show). - **No AI API keys.** AI runs on the person's own signed-in app (Claude Code, Codex, Gemini CLI, opencode), a local model, or their OpenRouter sign-in. - **Tools stay off for prompts from a website.** The helper (`public/broke-connect.cjs`) only runs AI apps with no tools at all. Don't add one that can read files. - **Every table has row-level security.** Secrets like `plaid_items.access_token` have no policies, so only the server's secret key reads them. diff --git a/README.md b/README.md index 4ec8e09..127fe4c 100644 --- a/README.md +++ b/README.md @@ -184,7 +184,12 @@ brokeless is an MCP server too, so an AI app like Claude Code can read your mone 3. Start a new Claude Code session and ask, for example: "Which of my brokeless rules catch too much?" -It is summary only, like broke ai: rounded amounts, months not days, names as placeholders (⟨M1⟩, ⟨A1⟩), never single transactions. Changes act on your real data, and Claude says what it will change first. Revoke a token on the same page. With AI switched off in Settings the endpoint refuses. +When you make a token you choose what it sees: + +- **Summary** (default): like broke ai. Rounded amounts, months not days, names as placeholders (⟨M1⟩, ⟨A1⟩), never single transactions. +- **Full detail**: real names, exact amounts, dates and single transactions with their id, so Claude can fix rows one by one (`list_transactions`, `update_transactions`, `mark_transfer_pair`). IBANs and account numbers stay shortened (`NL24…5339`). Your real transactions then go to Anthropic while you use it, so brokeless asks you to confirm that. + +A token only ever reaches its own user: every call runs in that user's session and every tool filters on that user too, so a partner's shared accounts don't show either. Changes act on your real data, and Claude says what it will change first. Revoke a token on the same page. With AI switched off in Settings the endpoint refuses. ## How AI stays private diff --git a/src/app/api/mcp-tokens/route.ts b/src/app/api/mcp-tokens/route.ts index 651c38a..105f721 100644 --- a/src/app/api/mcp-tokens/route.ts +++ b/src/app/api/mcp-tokens/route.ts @@ -9,9 +9,9 @@ export async function POST(request: Request) { const { data: { user } } = await (await createClient()).auth.getUser(); if (!user) return NextResponse.json({ error: "Not signed in" }, { status: 401 }); if (!sameOrigin(request)) return NextResponse.json({ error: "Forbidden" }, { status: 403 }); - const { label } = (await request.json().catch(() => ({}))) as { label?: string }; + const { label, level } = (await request.json().catch(() => ({}))) as { label?: string; level?: string }; try { - return NextResponse.json({ token: await createMcpToken(user.id, typeof label === "string" ? label : "Claude") }); + return NextResponse.json({ token: await createMcpToken(user.id, typeof label === "string" ? label : "Claude", level === "full" ? "full" : "summary") }); } catch (e) { console.error("[broke] mcp token:", e instanceof Error ? e.message : e); return NextResponse.json({ error: "Couldn't make a token. If this is new, restart brokeless so the database updates." }, { status: 500 }); diff --git a/src/app/api/mcp/route.ts b/src/app/api/mcp/route.ts index d582e59..eed424d 100644 --- a/src/app/api/mcp/route.ts +++ b/src/app/api/mcp/route.ts @@ -7,20 +7,27 @@ import { aiAllowed, SUMMARY_NOTE } from "@/lib/llm/gate"; import { mcpUser } from "@/lib/llm/mcp-tokens"; import { makeTools } from "@/lib/llm/shared"; import { manageTools } from "@/lib/llm/tools/manage"; +import { maskNumbers, rowTools } from "@/lib/llm/tools/rows"; import { createAdminClient } from "@/utils/supabase/admin"; // brokeless as an MCP server (Streamable HTTP, stateless) for AI apps such as Claude Code. A personal token from // Settings (migration 0033) signs it in as that user; their own session runs every query, so RLS applies. -// Summary only, always: an outside AI is a cloud model (lib/llm/gate.ts). AI switched off in Settings: refused. -const READ_ONLY = new Set(["spending_summary", "search_transactions", "list_recurring", "list_accounts", "list_holdings", "get_profile", "list_categories", "list_rules"]); -const DESTRUCTIVE = new Set(["delete_rule", "merge_accounts", "recategorize"]); +// Summary by default: an outside AI is a cloud model (lib/llm/gate.ts). Full detail only for a token the person made +// with Full detail on Connect your AI (migration 0034): their explicit choice, per token. AI switched off: refused. +// One user per token: every call runs in that user's own session (RLS), and every tool filters on their id too. +const READ_ONLY = new Set(["spending_summary", "search_transactions", "list_recurring", "list_accounts", "list_holdings", "get_profile", "list_categories", "list_rules", "list_transactions"]); +const DESTRUCTIVE = new Set(["delete_rule", "merge_accounts", "recategorize", "update_transactions"]); +const CHANGES = "Tools that change things act on the real data: say what you will change and how many transactions it touches before you do it, and preview merges first."; const INSTRUCTIONS = `You are connected to the user's own brokeless, a personal finance app. ${SUMMARY_NOTE} -Tools that change things (create_rule, delete_rule, recategorize, find_transfers, merge_accounts) act on the real data: say what you will change and how many transactions it touches before you do it, and preview merges first.`; +${CHANGES}`; +const FULL_INSTRUCTIONS = `You are connected to the user's own brokeless, a personal finance app, with full detail: real names, exact amounts, dates and single transactions with their id (IBANs and account numbers are shortened). Amounts: positive is money out, negative is money in. Transfers between the user's own accounts (category kind "transfer") count as neither spending nor income. +${CHANGES}`; const deny = (status: number, message: string) => Response.json({ jsonrpc: "2.0", error: { code: -32001, message }, id: null }, { status }); async function handle(request: Request) { - const userId = await mcpUser(request.headers.get("authorization")?.replace(/^Bearer\s+/i, "") ?? null); + const who = await mcpUser(request.headers.get("authorization")?.replace(/^Bearer\s+/i, "") ?? null); + const userId = who?.userId, full = who?.level === "full"; if (!userId) return deny(401, "Missing or revoked token. Make one in brokeless: Connect your AI, Connect an AI app (MCP)."); const { data: { user } } = await createAdminClient().auth.admin.getUserById(userId); if (!user) return deny(401, "That token's account is gone."); @@ -28,8 +35,10 @@ async function handle(request: Request) { const session = await agentClient(await mintAgentToken(user)); if (!session) return deny(503, "Couldn't open a session. Try again."); - const tools = [...makeTools(session.supabase, user.user_metadata?.profile, user.id, "summary"), ...manageTools(session.supabase, user.id)]; - const server = new Server({ name: "brokeless", version: "1.0.0" }, { capabilities: { tools: {} }, instructions: INSTRUCTIONS }); + const tools = full + ? [...makeTools(session.supabase, user.user_metadata?.profile, user.id, "full"), ...manageTools(session.supabase, user.id, true), ...rowTools(session.supabase, user.id)] + : [...makeTools(session.supabase, user.user_metadata?.profile, user.id, "summary"), ...manageTools(session.supabase, user.id)]; + const server = new Server({ name: "brokeless", version: "1.0.0" }, { capabilities: { tools: {} }, instructions: full ? FULL_INSTRUCTIONS : INSTRUCTIONS }); server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: tools.map((t) => ({ name: t.name, description: t.description, inputSchema: z.toJSONSchema(t.schema) as { type: "object" }, @@ -42,7 +51,8 @@ async function handle(request: Request) { const parsed = t.schema.safeParse(req.params.arguments ?? {}); if (!parsed.success) return { content: [{ type: "text", text: `Invalid arguments: ${parsed.error.message}` }], isError: true }; try { - return { content: [{ type: "text", text: await t.run(parsed.data as Record) }] }; + const text = await t.run(parsed.data as Record); + return { content: [{ type: "text", text: full ? maskNumbers(text) : text }] }; } catch (e) { console.error("[broke] mcp tool:", t.name, e instanceof Error ? e.message : e); return { content: [{ type: "text", text: "That didn't work. Try again." }], isError: true }; diff --git a/src/components/McpTokens.tsx b/src/components/McpTokens.tsx index 148217b..b6a38cb 100644 --- a/src/components/McpTokens.tsx +++ b/src/components/McpTokens.tsx @@ -5,7 +5,7 @@ import { createClient } from "@/utils/supabase/client"; // Connect your AI: personal tokens for brokeless's MCP endpoint (api/mcp), for AI apps such as Claude Code. // A new token shows once, with the command that adds it to Claude Code. Revoking deletes it: the app loses access at once. -type Row = { id: string; label: string; created_at: string; last_used_at: string | null }; +type Row = { id: string; label: string; created_at: string; last_used_at: string | null; level: "summary" | "full" }; const when = (d: string | null) => (d ? new Date(d).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" }) : "never"); export function McpTokens() { @@ -13,7 +13,9 @@ export function McpTokens() { const [fresh, setFresh] = useState(null); const [err, setErr] = useState(""); const [busy, setBusy] = useState(false); - const load = () => createClient().from("mcp_tokens").select("id, label, created_at, last_used_at").order("created_at").then(({ data }) => setRows((data ?? []) as Row[])); + const [level, setLevel] = useState<"summary" | "full">("summary"); + const [agree, setAgree] = useState(false); + const load = () => createClient().from("mcp_tokens").select("id, label, created_at, last_used_at, level").order("created_at").then(({ data }) => setRows((data ?? []) as Row[])); useEffect(() => { load(); }, []); const url = typeof window === "undefined" ? "" : `${window.location.origin}/api/mcp`; const command = fresh ? `claude mcp add --scope user --transport http brokeless ${url} --header "Authorization: Bearer ${fresh}"` : ""; @@ -21,7 +23,7 @@ export function McpTokens() { async function make() { setBusy(true); setErr(""); - const r = await fetch("/api/mcp-tokens", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ label: "Claude" }) }); + const r = await fetch("/api/mcp-tokens", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ label: level === "full" ? "Claude (full detail)" : "Claude", level }) }); const b = (await r.json().catch(() => ({}))) as { token?: string; error?: string }; setBusy(false); if (!r.ok || !b.token) return setErr(b.error ?? "Couldn't make a token."); @@ -45,7 +47,7 @@ export function McpTokens() {

Connect an AI app (MCP)

-

Let an AI app like Claude Code read your money summary and fix things for you: rules, categories, transfers, merging accounts. It gets the same summary as broke ai: rounded amounts and placeholder names, never single transactions.

+

Let an AI app like Claude Code look at your money and fix things for you: rules, categories, transfers, merging accounts. A token only ever reaches your own data.

{fresh && (
@@ -62,14 +64,27 @@ export function McpTokens() {
    {rows.map((r) => (
  • - {r.label} · made {when(r.created_at)} · last used {when(r.last_used_at)} + {r.label} · {r.level === "full" ? "full detail" : "summary"} · made {when(r.created_at)} · last used {when(r.last_used_at)}
  • ))}
)} {err &&

{err}

} - +
+ What the AI app may see + + + {level === "full" && ( + + )} +
+
); } diff --git a/src/lib/llm/mcp-tokens.ts b/src/lib/llm/mcp-tokens.ts index b5706b8..a19cac2 100644 --- a/src/lib/llm/mcp-tokens.ts +++ b/src/lib/llm/mcp-tokens.ts @@ -6,19 +6,20 @@ import { createAdminClient } from "@/utils/supabase/admin"; // "bk_" in front so it's recognizable in a config file. const hash = (t: string) => createHash("sha256").update(t).digest("hex"); -export async function createMcpToken(userId: string, label = "Claude") { +export type McpLevel = "summary" | "full"; +export async function createMcpToken(userId: string, label = "Claude", level: McpLevel = "summary") { const token = `bk_${randomBytes(32).toString("base64url")}`; - const { error } = await createAdminClient().from("mcp_tokens").insert({ user_id: userId, token_hash: hash(token), label: label.slice(0, 60) || "Claude" }); + const { error } = await createAdminClient().from("mcp_tokens").insert({ user_id: userId, token_hash: hash(token), label: label.slice(0, 60) || "Claude", level }); if (error) throw error; return token; } -/** The user a token belongs to, or null. Notes when it was last used (at most once a minute). */ -export async function mcpUser(token: string | null): Promise { +/** The user a token belongs to and what it may see, or null. Notes when it was last used (at most once a minute). */ +export async function mcpUser(token: string | null): Promise<{ userId: string; level: McpLevel } | null> { if (!token || !/^bk_[\w-]{20,}$/.test(token)) return null; const db = createAdminClient(); - const { data } = await db.from("mcp_tokens").select("id, user_id, last_used_at").eq("token_hash", hash(token)).maybeSingle(); + const { data } = await db.from("mcp_tokens").select("id, user_id, last_used_at, level").eq("token_hash", hash(token)).maybeSingle(); if (!data) return null; if (!data.last_used_at || Date.now() - Date.parse(data.last_used_at) > 60_000) await db.from("mcp_tokens").update({ last_used_at: new Date().toISOString() }).eq("id", data.id); - return data.user_id as string; + return { userId: data.user_id as string, level: data.level === "full" ? "full" : "summary" }; } diff --git a/src/lib/llm/shared.ts b/src/lib/llm/shared.ts index 2197814..2c58109 100644 --- a/src/lib/llm/shared.ts +++ b/src/lib/llm/shared.ts @@ -128,7 +128,8 @@ export function fullTools(supabase: SupabaseClient, profile: Record = {}; const byMerchant: Record = {}; for (const t of spend) { - byCat[t.category!.label] = (byCat[t.category!.label] ?? 0) + t.amount; + const cat = t.category?.label ?? "Other"; // money out with no category counts as spend (isSpend), so it has none + byCat[cat] = (byCat[cat] ?? 0) + t.amount; byMerchant[displayName(t)] = (byMerchant[displayName(t)] ?? 0) + t.amount; } const round = (o: Record) => Object.entries(o).sort((a, b) => b[1] - a[1]).map(([k, v]) => [k, Math.round(v * 100) / 100]); diff --git a/src/lib/llm/tools/manage.ts b/src/lib/llm/tools/manage.ts index 7e0078d..ececb90 100644 --- a/src/lib/llm/tools/manage.ts +++ b/src/lib/llm/tools/manage.ts @@ -18,7 +18,8 @@ import { createAdminClient } from "@/utils/supabase/admin"; const tool = (t: { name: string; description: string; schema: S; run: (input: z.infer) => Promise }) => t as unknown as Tool; const ok = (x: unknown) => JSON.stringify(x); -export function manageTools(supabase: SupabaseClient, userId: string): Tool[] { +/** full: a token the person set to Full detail. Rule text then shows as written instead of with placeholders. */ +export function manageTools(supabase: SupabaseClient, userId: string, full = false): Tool[] { const names = () => namesFor(supabase, userId); const categories = async () => { const { data } = await supabase.from("categories").select("id, key, label, kind"); @@ -52,7 +53,7 @@ export function manageTools(supabase: SupabaseClient, userId: string): Tool[] { const key = new Map(cats.map((c) => [c.id, c.key])); const out = []; for (const r of (data ?? []) as (Rule & { created_at: string })[]) - out.push({ id: r.id, match: r.match ? mask(r.match, n) : null, direction: r.direction ?? "both", category: r.category_id ? key.get(r.category_id) ?? null : null, + out.push({ id: r.id, match: r.match ? (full ? r.match : mask(r.match, n)) : null, direction: r.direction ?? "both", category: r.category_id ? key.get(r.category_id) ?? null : null, renames: !!r.rename, hides: !!r.ignore, matches_now: (await pastMatchesWith(supabase, userId, r)).length }); return ok(out); }, diff --git a/src/lib/llm/tools/rows.ts b/src/lib/llm/tools/rows.ts new file mode 100644 index 0000000..a52a782 --- /dev/null +++ b/src/lib/llm/tools/rows.ts @@ -0,0 +1,111 @@ +import "server-only"; +import type { SupabaseClient } from "@supabase/supabase-js"; +import { z } from "zod"; +import { displayName, TXN_SELECT, type Txn } from "@/lib/data"; +import type { Tool } from "@/lib/llm/shared"; + +// Single-transaction tools for an MCP token the person set to "Full detail" (Connect your AI, migration 0034). +// Never for a summary token. Rows come with their id so an AI can fix them one by one; writes run as the user (RLS), +// only on the columns the app itself lets them change (category, name, hidden). + +const tool = (t: { name: string; description: string; schema: S; run: (input: z.infer) => Promise }) => t as unknown as Tool; + +/** IBANs and long account numbers keep only their first and last characters, in everything a full-detail token sees. */ +// Ids (UUIDs) stay exactly as they are: a tool needs them back. +const UUID_RE = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi; +const maskPart = (text: string) => + text + .replace(/\b([A-Z]{2}\d{2})[A-Z0-9]{4,}(\d{4})\b/g, "$1…$2") // NL24INGB0008165339 -> NL24…5339 + .replace(/\b\d{5,}(\d{4})\b/g, "…$1"); // 210026951876 -> …1876 +export const maskNumbers = (text: string) => { + const ids = text.match(UUID_RE) ?? []; + return text.split(UUID_RE).map(maskPart).reduce((out, part, i) => out + part + (ids[i] ?? ""), ""); +}; + +const UUID = z.string().uuid(); + +export function rowTools(supabase: SupabaseClient, userId: string): Tool[] { + const cats = async () => ((await supabase.from("categories").select("id, key, label, kind")).data ?? []) as { id: string; key: string; label: string; kind: string }[]; + const catId = async (k: string) => { const t = k.trim().toLowerCase(); return (await cats()).find((c) => c.key.toLowerCase() === t || c.label.toLowerCase() === t)?.id ?? null; }; + + return [ + tool({ + name: "list_transactions", + description: "Single transactions with their id, newest first: date, amount (positive = money out, negative = money in), name, merchant, your own name for it, category key and kind, account, hidden, tags. Filters combine. IBANs and account numbers are shortened.", + schema: z.object({ + query: z.string().optional().describe("Text in the name, merchant or your own name for it"), + from: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(), + to: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(), + account: z.string().optional().describe("Account name (see list_accounts)"), + category: z.string().optional().describe('Category key or label, or "none" for rows without one'), + direction: z.enum(["in", "out"]).optional(), + min_amount: z.number().optional().describe("At least this much (either direction)"), + limit: z.number().int().min(1).max(500).default(100), + offset: z.number().int().min(0).default(0), + }), + run: async ({ query, from, to, account, category, direction, min_amount, limit, offset }) => { + let q = supabase.from("transactions").select(TXN_SELECT).eq("user_id", userId); + if (query) { const s = query.replace(/[%,()]/g, " "); q = q.or(`name.ilike.%${s}%,merchant_name.ilike.%${s}%,custom_name.ilike.%${s}%`); } + if (from) q = q.gte("date", from); + if (to) q = q.lte("date", to); + if (direction === "out") q = q.gt("amount", 0); + if (direction === "in") q = q.lt("amount", 0); + if (account) { + const { data } = await supabase.from("accounts").select("id, name, custom_name").eq("user_id", userId); + const a = (data ?? []).find((x) => (x.custom_name || x.name).toLowerCase() === account.trim().toLowerCase()); + if (!a) return JSON.stringify({ error: `No account "${account}".` }); + q = q.eq("account_id", a.id); + } + if (category) { + if (category.trim().toLowerCase() === "none") q = q.is("category_id", null); + else { const id = await catId(category); if (!id) return JSON.stringify({ error: `No category "${category}". See list_categories.` }); q = q.eq("category_id", id); } + } + if (min_amount) q = q.or(`amount.gte.${Math.abs(min_amount)},amount.lte.${-Math.abs(min_amount)}`); + const { data, error } = await q.order("date", { ascending: false }).order("id").range(offset, offset + limit - 1); + if (error) return JSON.stringify({ error: error.message }); + return JSON.stringify(((data ?? []) as unknown as Txn[]).map((t) => ({ + id: t.id, date: t.date, amount: Number(t.amount), name: t.name, merchant: t.merchant_name, your_name: t.custom_name, shown_as: displayName(t), + category: t.category?.key ?? null, kind: t.category?.kind ?? null, account: t.account ? t.account.custom_name || t.account.name : null, hidden: t.ignored || undefined, tags: t.tags?.length ? t.tags : undefined, + }))); + }, + }), + tool({ + name: "update_transactions", + description: "Change specific transactions by id (from list_transactions): category, your own name for them, or hidden (left out of every total). Returns how many changed.", + schema: z.object({ + ids: z.array(UUID).min(1).max(500), + category: z.string().optional().describe('Category key or label, or "none" to clear it'), + name: z.string().max(120).nullable().optional().describe("Your own name for them; null clears it"), + hidden: z.boolean().optional(), + }), + run: async ({ ids, category, name, hidden }) => { + const patch: Record = {}; + if (category !== undefined) { + if (category.trim().toLowerCase() === "none") patch.category_id = null; + else { const id = await catId(category); if (!id) return JSON.stringify({ error: `No category "${category}".` }); patch.category_id = id; } + } + if (name !== undefined) patch.custom_name = name?.trim() || null; + if (hidden !== undefined) patch.ignored = hidden; + if (!Object.keys(patch).length) return JSON.stringify({ error: "Nothing to change." }); + const { data, error } = await supabase.from("transactions").update(patch).eq("user_id", userId).in("id", ids).select("id"); + return JSON.stringify(error ? { error: "Couldn't update them." } : { updated: data?.length ?? 0 }); + }, + }), + tool({ + name: "mark_transfer_pair", + description: "Mark two transactions as one transfer between your own accounts: the money-out row becomes Transfers out, the money-in row Transfers in, so neither counts as spending or income. They must be the same amount, in different accounts.", + schema: z.object({ out_id: UUID, in_id: UUID }), + run: async ({ out_id, in_id }) => { + const { data } = await supabase.from("transactions").select("id, amount, account_id").eq("user_id", userId).in("id", [out_id, in_id]); + const o = data?.find((t) => t.id === out_id), i = data?.find((t) => t.id === in_id); + if (!o || !i) return JSON.stringify({ error: "Transaction not found." }); + if (!(Number(o.amount) > 0 && Number(i.amount) < 0) || Math.abs(Number(o.amount) + Number(i.amount)) >= 0.005) return JSON.stringify({ error: "out_id must be money out and in_id the same amount coming in." }); + if (o.account_id === i.account_id) return JSON.stringify({ error: "They're in the same account." }); + const ids = Object.fromEntries((await cats()).filter((c) => c.key === "TRANSFER_OUT" || c.key === "TRANSFER_IN").map((c) => [c.key, c.id])); + await supabase.from("transactions").update({ category_id: ids.TRANSFER_OUT }).eq("id", out_id).eq("user_id", userId); + await supabase.from("transactions").update({ category_id: ids.TRANSFER_IN }).eq("id", in_id).eq("user_id", userId); + return JSON.stringify({ marked: true }); + }, + }), + ]; +} diff --git a/supabase/migrations/0034_mcp_token_level.sql b/supabase/migrations/0034_mcp_token_level.sql new file mode 100644 index 0000000..1acebae --- /dev/null +++ b/supabase/migrations/0034_mcp_token_level.sql @@ -0,0 +1,4 @@ +-- What an MCP token may see: the summary (like every cloud AI), or full detail, which the person turns on for that +-- token themselves on Connect your AI. Tokens made before this stay summary. +alter table public.mcp_tokens add column if not exists level text not null default 'summary' check (level in ('summary', 'full')); +grant select (level) on public.mcp_tokens to authenticated;