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

+2 -2
View File
@@ -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 });
+18 -8
View File
@@ -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<string, unknown>) }] };
const text = await t.run(parsed.data as Record<string, unknown>);
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 };