MCP: full detail per token, single-transaction tools, one user per token

Tokens get a level (migration 0034). Summary stays the default; Full detail is
the person's explicit choice on Connect your AI, with a confirmation, and is
written into CLAUDE.md as the one exception to summary-only cloud AI. Full
tokens get the full tools plus list_transactions, update_transactions and
mark_transfer_pair; IBANs and long account numbers are shortened in everything
they return (ids stay intact).

Isolation tested with two users and an accepted partner share: RLS alone lets
the partner read the owner's shared rows, but every tool also filters on the
token's user, so nothing leaked and no change landed (own ids, rule id, names).

Also fixes the full spending_summary crashing on rows without a category.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
MangaValkandClaude Opus 5.5 committed 2026-11-19 21:36:12 +01:00
1 parent dee883472a
commit 059a1da375
10 files changed
+175 -26

No files matched your search

+7 -6
View File
@@ -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<string | null> {
/** 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" };
}
+2 -1
View File
@@ -128,7 +128,8 @@ export function fullTools(supabase: SupabaseClient, profile: Record<string, unkn
const byCat: Record<string, number> = {};
const byMerchant: Record<string, number> = {};
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<string, number>) => Object.entries(o).sort((a, b) => b[1] - a[1]).map(([k, v]) => [k, Math.round(v * 100) / 100]);
+3 -2
View File
@@ -18,7 +18,8 @@ import { createAdminClient } from "@/utils/supabase/admin";
const tool = <S extends z.ZodObject>(t: { name: string; description: string; schema: S; run: (input: z.infer<S>) => Promise<string> }) => 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);
},
+111
View File
@@ -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 = <S extends z.ZodObject>(t: { name: string; description: string; schema: S; run: (input: z.infer<S>) => Promise<string> }) => 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<string, unknown> = {};
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 });
},
}),
];
}