diff --git a/cli/src/capabilities.ts b/cli/src/capabilities.ts index fc57aa4..c7e1781 100644 --- a/cli/src/capabilities.ts +++ b/cli/src/capabilities.ts @@ -430,6 +430,30 @@ export const CAPABILITIES: readonly CapabilityDefinition[] = [ profiles: profilesForMcp("robinhood_share_safe"), outputSchema: "shareSafe", }, + { + id: "deposit-quote", + cli: "deposit-quote", + mcp: "robinhood_deposit_quote", + access: "read", + profiles: ["full"], + outputSchema: "legacyObject", + }, + { + id: "deposit-plan", + cli: "deposit-plan", + mcp: "robinhood_deposit_plan", + access: "read", + profiles: ["full"], + outputSchema: "legacyObject", + }, + { + id: "deposit-inventory", + cli: "deposit-inventory", + mcp: "robinhood_deposit_inventory", + access: "read", + profiles: ["full"], + outputSchema: "legacyObject", + }, { id: "roth-deposit-plan", cli: "roth-deposit-plan", diff --git a/cli/src/deposit.ts b/cli/src/deposit.ts new file mode 100644 index 0000000..2bc32bf --- /dev/null +++ b/cli/src/deposit.ts @@ -0,0 +1,232 @@ +/** Account-agnostic deposit domain. POST execution requires an action-scoped captured contract. */ +export type DepositPaymentMethod = "bank_standard" | "bank_instant" | "debit_card"; +export type DepositRequestStatus = + | "captured_exact_write_contract" + | "missing_exact_write_contract" + | "missing_source_and_exact_write_contract"; + +export interface DepositDestination { + accountId: string; + accountType: string; + depositEnabled: boolean; +} + +export interface DepositSource { + id: string; + method: DepositPaymentMethod; + eligible: boolean; + requestStatus: DepositRequestStatus; + evidence: string[]; +} + +export interface DepositInventory { + destinations: DepositDestination[]; + sources: DepositSource[]; + executableMethods: DepositPaymentMethod[]; +} + +export interface DepositHistoryRow { + amountUsd: string; + method: DepositPaymentMethod; + destinationAccountId: string; + state: string; +} + +export interface CapturedDepositRequest { + method: "POST"; + url: string; + body: Record; + amountField: string; +} + +export interface RetirementContribution { + contributionYear: number; + contributionRoomUsd: string; + eligibilityVerified: boolean; +} + +export interface DepositInput { + amountUsd: string; + destination: DepositDestination; + source: Pick; + fee: { known: boolean; usd?: string }; + history: DepositHistoryRow[]; + retirement?: RetirementContribution; + capturedRequest?: CapturedDepositRequest; +} + +export interface DepositQuote { + executable: boolean; + amountUsd: string; + destination: DepositDestination; + sourceId: string; + method: DepositPaymentMethod; + gates: string[]; +} + +export interface DepositPlan extends DepositQuote { + request?: CapturedDepositRequest; +} + +export interface DepositReceipt { + submitted: boolean; + ambiguous: boolean; + receiptStatus: "accepted" | "rejected" | "transport_ambiguous"; + status?: number; + body?: unknown; +} + +const asCents = (value: string | undefined): number | undefined => { + if (!value || !/^\d+(?:\.\d{1,2})?$/.test(value)) return undefined; + const [whole, fraction = ""] = value.split("."); + return Number(whole) * 100 + Number((fraction + "00").slice(0, 2)); +}; + +const isRetirementDestination = (accountType: string): boolean => + accountType === "ira" || accountType === "ira_roth"; + +/** Maps only observed source records. A debit row exists only when the read response identifies one. */ +export function buildDepositInventory( + accounts: Array>, + fundingSources: Array>, +): DepositInventory { + const destinations = accounts + .filter((account) => typeof (account.id ?? account.account_id) === "string") + .map((account) => ({ + accountId: String(account.id ?? account.account_id), + accountType: String(account.type ?? account.account_type ?? "unknown"), + depositEnabled: account.is_deposits_enabled === true, + })); + const sources: DepositSource[] = []; + for (const source of fundingSources) { + const id = String(source.id ?? source.relationship_id ?? ""); + if (!id) continue; + const verified = source.verified === true && source.state === "approved"; + const type = String(source.type ?? source.source_type ?? "").toLowerCase(); + if (type === "debit_card") { + sources.push({ + id, + method: "debit_card", + eligible: verified, + requestStatus: "missing_exact_write_contract", + evidence: ["captured funding-source GET", "source type debit_card", "verified/approved"], + }); + continue; + } + const rails = (source.available_payment_rails ?? {}) as Record; + sources.push({ + id, + method: "bank_standard", + eligible: verified, + requestStatus: "missing_exact_write_contract", + evidence: ["cashier/ach/relationships GET", "relationship verified/approved"], + }); + if (rails.is_rtp_eligible === true) { + sources.push({ + id, + method: "bank_instant", + eligible: verified, + requestStatus: "missing_exact_write_contract", + evidence: ["cashier/ach/relationships GET", "available_payment_rails.is_rtp_eligible"], + }); + } + } + return { destinations, sources, executableMethods: [] }; +} + +/** Validates a specific source-to-destination amount; retirement gates are destination-specific. */ +export function buildDepositQuote(input: DepositInput): DepositQuote { + const gates: string[] = []; + const amountCents = asCents(input.amountUsd); + if (amountCents === undefined || amountCents <= 0) + gates.push("deposit amount must be a positive USD amount"); + if (!input.destination.accountId || !input.destination.depositEnabled) + gates.push("destination is not deposit-enabled"); + if (!input.source.id || !input.source.eligible) + gates.push(`${input.source.method} source is not eligible`); + if (!input.fee.known || asCents(input.fee.usd) !== 0) + gates.push("fee is unknown or non-zero; no fee is authorized"); + if (isRetirementDestination(input.destination.accountType)) { + if (!input.retirement?.eligibilityVerified) + gates.push("retirement contribution eligibility is not verified"); + if ( + !Number.isInteger(input.retirement?.contributionYear) || + (input.retirement?.contributionYear ?? 0) < 2020 + ) + gates.push("retirement contribution year is invalid"); + if ( + (asCents(input.retirement?.contributionRoomUsd) ?? -1) < + (amountCents ?? Number.MAX_SAFE_INTEGER) + ) + gates.push("verified retirement contribution room is below deposit amount"); + } + const duplicate = input.history.some( + (row) => + row.amountUsd === input.amountUsd && + row.method === input.source.method && + row.destinationAccountId === input.destination.accountId && + /pending|queued|submitted|complete|completed|settled/i.test(row.state), + ); + if (duplicate) gates.push("matching deposit is already pending or completed"); + return { + executable: gates.length === 0, + amountUsd: input.amountUsd, + destination: input.destination, + sourceId: input.source.id, + method: input.source.method, + gates, + }; +} + +/** Produces a one-shot POST plan only from a captured exact contract; it never invents a body. */ +export function buildDepositPlan(input: DepositInput): DepositPlan { + const quote = buildDepositQuote(input); + const gates = [...quote.gates]; + const request = input.capturedRequest; + if (!request) gates.push("exact deposit write contract has not been captured"); + else if (request.method !== "POST" || !request.url.startsWith("https://") || !request.amountField) + gates.push("captured deposit write contract is incomplete"); + return { ...quote, executable: gates.length === 0, gates, request }; +} + +export function classifyDepositReceipt(response?: { + status: number; + body?: unknown; +}): DepositReceipt { + if (!response) return { submitted: false, ambiguous: true, receiptStatus: "transport_ambiguous" }; + const submitted = response.status >= 200 && response.status < 300; + return { + submitted, + ambiguous: false, + receiptStatus: submitted ? "accepted" : "rejected", + status: response.status, + body: response.body, + }; +} + +/** One-shot executor. Callers must independently read status before any retry decision. */ +export async function executeDeposit( + plan: DepositPlan, + send: ( + request: CapturedDepositRequest & { body: Record }, + ) => Promise<{ status: number; body?: unknown }>, +): Promise { + if (!plan.executable) throw new Error(`Deposit is not executable: ${plan.gates.join("; ")}`); + if (!plan.request) + throw new Error("Deposit write contract has not been captured; refusing to invent a request"); + try { + return classifyDepositReceipt( + await send({ + ...plan.request, + body: { ...plan.request.body, [plan.request.amountField]: plan.amountUsd }, + }), + ); + } catch (error) { + return { + submitted: false, + ambiguous: true, + receiptStatus: "transport_ambiguous", + body: { error: (error as Error).message }, + }; + } +} diff --git a/cli/src/index.ts b/cli/src/index.ts index fd810cf..0350551 100644 --- a/cli/src/index.ts +++ b/cli/src/index.ts @@ -141,6 +141,9 @@ import { getTaxLotsForOrder, planTaxLotSale, submitTaxLotSale, + buildDepositPlan, + buildDepositQuote, + getDepositInventory, buildRothDepositPlan, getRothDepositSourceInventory, } from "./lib.js"; @@ -158,6 +161,32 @@ program ) .version("1.1.0"); +program + .command("deposit-quote") + .description("Validate an account-agnostic deposit quote. Does not submit a transfer.") + .requiredOption( + "--input-json ", + "destination, source, fee, history, and optional retirement data", + ) + .action((opts: { inputJson: string }) => + printJson(buildDepositQuote(JSON.parse(opts.inputJson))), + ); + +program + .command("deposit-plan") + .description( + "Build a one-shot deposit plan only from an exact captured POST contract. Does not submit.", + ) + .requiredOption("--input-json ", "quote input plus a sanitized capturedRequest") + .action((opts: { inputJson: string }) => printJson(buildDepositPlan(JSON.parse(opts.inputJson)))); + +program + .command("deposit-inventory") + .description( + "Read eligible owned deposit destinations and observed funding sources. Never submits a deposit.", + ) + .action(async () => printJson(await getDepositInventory())); + program .command("roth-deposit-plan") .description("Validate a $1 Roth deposit rail plan. Does not submit a transfer.") diff --git a/cli/src/lib.ts b/cli/src/lib.ts index ee2b95f..d729d60 100644 --- a/cli/src/lib.ts +++ b/cli/src/lib.ts @@ -1,5 +1,22 @@ import { execFile, execFileSync } from "node:child_process"; import { createHash, createPrivateKey, randomUUID, sign } from "node:crypto"; +export { + buildDepositInventory, + buildDepositPlan, + buildDepositQuote, + classifyDepositReceipt, + executeDeposit, +} from "./deposit.js"; +export type { + CapturedDepositRequest as GenericCapturedDepositRequest, + DepositInput, + DepositInventory, + DepositPlan, + DepositQuote, + DepositReceipt, + DepositSource, + DepositPaymentMethod, +} from "./deposit.js"; export { buildRothDepositPlan, buildRothDepositSourceInventory, @@ -16,6 +33,7 @@ export type { RothDepositSourceInventoryRow, RothPaymentMethod, } from "./roth-deposit.js"; +import { buildDepositInventory } from "./deposit.js"; import { buildRothDepositSourceInventory } from "./roth-deposit.js"; import { appendFileSync, @@ -2959,6 +2977,18 @@ export async function brokerageGetJson( return JSON.parse(result.body || "{}"); } +/** Live owned-destination × observed funding-source read using only captured authenticated GET contracts. */ +export async function getDepositInventory(): Promise { + const [accounts, relationships] = await Promise.all([ + brokerageGetJson("https://bonfire.robinhood.com/transfer/accounts/"), + brokerageGetJson("https://cashier.robinhood.com/ach/relationships/"), + ]); + return buildDepositInventory( + Array.isArray(accounts?.results) ? accounts.results : [], + Array.isArray(relationships?.results) ? relationships.results : [], + ); +} + /** Live source × rail read using only captured authenticated GET contracts. */ export async function getRothDepositSourceInventory(): Promise { const [accounts, relationships] = await Promise.all([ diff --git a/cli/test/deposit.test.ts b/cli/test/deposit.test.ts new file mode 100644 index 0000000..0d5187b --- /dev/null +++ b/cli/test/deposit.test.ts @@ -0,0 +1,112 @@ +import { describe, expect, it } from "vitest"; +import { + buildDepositInventory, + buildDepositPlan, + buildDepositQuote, + classifyDepositReceipt, +} from "../src/deposit.js"; + +const bankA = { + id: "bank-a", + verified: true, + state: "approved", + available_payment_rails: { is_rtp_eligible: true }, +}; +const bankB = { + id: "bank-b", + verified: true, + state: "approved", + available_payment_rails: { is_rtp_eligible: false }, +}; +const debitA = { id: "debit-a", type: "debit_card", verified: true, state: "approved" }; + +const taxable = { id: "taxable-a", type: "brokerage", is_deposits_enabled: true }; +const roth = { id: "roth-a", type: "ira_roth", is_deposits_enabled: true }; +const traditionalIra = { id: "ira-a", type: "ira", is_deposits_enabled: true }; + +const request = { + method: "POST" as const, + url: "https://api.robinhood.com/ach/transfers/", + body: { direction: "deposit", relationship: "placeholder" }, + amountField: "amount", +}; + +describe("generic deposit contracts", () => { + it("discovers every eligible owned destination and observed funding source without imposing Roth selection", () => { + const inventory = buildDepositInventory([taxable, roth, traditionalIra], [bankA, bankB, debitA]); + expect(inventory.destinations).toEqual([ + { accountId: "taxable-a", accountType: "brokerage", depositEnabled: true }, + { accountId: "roth-a", accountType: "ira_roth", depositEnabled: true }, + { accountId: "ira-a", accountType: "ira", depositEnabled: true }, + ]); + expect(inventory.sources).toEqual( + expect.arrayContaining([ + expect.objectContaining({ id: "bank-a", method: "bank_standard", eligible: true }), + expect.objectContaining({ id: "bank-a", method: "bank_instant", eligible: true }), + expect.objectContaining({ id: "bank-b", method: "bank_standard", eligible: true }), + expect.objectContaining({ id: "debit-a", method: "debit_card", eligible: true }), + ]), + ); + expect(inventory.sources).not.toContainEqual(expect.objectContaining({ id: "unobserved" })); + }); + + it("quotes a requested bank-to-taxable deposit without retirement gates", () => { + const quote = buildDepositQuote({ + amountUsd: "25.00", + destination: { accountId: "taxable-a", accountType: "brokerage", depositEnabled: true }, + source: { id: "bank-b", method: "bank_standard", eligible: true }, + fee: { known: true, usd: "0.00" }, + history: [], + }); + expect(quote).toMatchObject({ executable: true, amountUsd: "25.00", gates: [] }); + }); + + it("requires retirement contribution fields only for retirement destinations", () => { + const base = { + amountUsd: "1.00", + source: { id: "bank-a", method: "bank_instant" as const, eligible: true }, + fee: { known: true, usd: "0.00" }, + history: [], + }; + const taxableDestination = { accountId: taxable.id, accountType: taxable.type, depositEnabled: true }; + const rothDestination = { accountId: roth.id, accountType: roth.type, depositEnabled: true }; + expect(buildDepositQuote({ ...base, destination: taxableDestination }).executable).toBe(true); + expect(buildDepositQuote({ ...base, destination: rothDestination }).gates).toContain( + "retirement contribution eligibility is not verified", + ); + expect( + buildDepositQuote({ + ...base, + destination: rothDestination, + retirement: { contributionYear: 2026, contributionRoomUsd: "1.00", eligibilityVerified: true }, + }).executable, + ).toBe(true); + }); + + it("plans captured writes and refuses absent write contracts without globally blocking eligible deposits", () => { + const input = { + amountUsd: "1.00", + destination: { accountId: "ira-a", accountType: "ira", depositEnabled: true }, + source: { id: "debit-a", method: "debit_card" as const, eligible: true }, + fee: { known: true, usd: "0.00" }, + retirement: { contributionYear: 2026, contributionRoomUsd: "1.00", eligibilityVerified: true }, + history: [], + }; + expect(buildDepositPlan(input).executable).toBe(false); + expect(buildDepositPlan(input).gates).toContain("exact deposit write contract has not been captured"); + expect(buildDepositPlan({ ...input, capturedRequest: request })).toMatchObject({ + executable: true, + request, + destination: { accountType: "ira" }, + sourceId: "debit-a", + }); + }); + + it("keeps receipt status generic and marks transport uncertainty ambiguous", () => { + expect(classifyDepositReceipt({ status: 201, body: { id: "synthetic-receipt" } })).toMatchObject({ + submitted: true, + receiptStatus: "accepted", + }); + expect(classifyDepositReceipt()).toMatchObject({ ambiguous: true, receiptStatus: "transport_ambiguous" }); + }); +}); diff --git a/mcp/src/server.ts b/mcp/src/server.ts index a534101..8de63ae 100644 --- a/mcp/src/server.ts +++ b/mcp/src/server.ts @@ -129,6 +129,9 @@ import { getIpoAccess, getIpoAccessRequestPlan, getTaxLotInventory, + buildDepositPlan, + buildDepositQuote, + getDepositInventory, buildRothDepositPlan, getRothDepositSourceInventory, getTaxLotsForOrder, @@ -980,6 +983,106 @@ server.registerTool( }, ); +server.registerTool( + "robinhood_deposit_quote", + { + title: "Robinhood Deposit Quote", + description: + "Validate an account-agnostic source-to-owned-destination deposit quote. Retirement fields apply only to IRA destinations. Never submits.", + annotations: toolAnnotations(true, "read"), + inputSchema: z.object({ + amountUsd: z.string(), + destination: z.object({ + accountId: z.string(), + accountType: z.string(), + depositEnabled: z.boolean(), + }), + source: z.object({ + id: z.string(), + method: z.enum(["bank_standard", "bank_instant", "debit_card"]), + eligible: z.boolean(), + }), + fee: z.object({ known: z.boolean(), usd: z.string().optional() }), + history: z.array( + z.object({ + amountUsd: z.string(), + method: z.enum(["bank_standard", "bank_instant", "debit_card"]), + destinationAccountId: z.string(), + state: z.string(), + }), + ), + retirement: z + .object({ + contributionYear: z.number().int(), + contributionRoomUsd: z.string(), + eligibilityVerified: z.boolean(), + }) + .optional(), + }), + }, + async (input) => jsonResponse(buildDepositQuote(input)), +); + +server.registerTool( + "robinhood_deposit_plan", + { + title: "Robinhood Deposit Plan", + description: + "Build a one-shot deposit plan only when an exact sanitized POST contract is provided. Never submits or guesses a POST body.", + annotations: toolAnnotations(true, "read"), + inputSchema: z.object({ + amountUsd: z.string(), + destination: z.object({ + accountId: z.string(), + accountType: z.string(), + depositEnabled: z.boolean(), + }), + source: z.object({ + id: z.string(), + method: z.enum(["bank_standard", "bank_instant", "debit_card"]), + eligible: z.boolean(), + }), + fee: z.object({ known: z.boolean(), usd: z.string().optional() }), + history: z.array( + z.object({ + amountUsd: z.string(), + method: z.enum(["bank_standard", "bank_instant", "debit_card"]), + destinationAccountId: z.string(), + state: z.string(), + }), + ), + retirement: z + .object({ + contributionYear: z.number().int(), + contributionRoomUsd: z.string(), + eligibilityVerified: z.boolean(), + }) + .optional(), + capturedRequest: z + .object({ + method: z.literal("POST"), + url: z.string().url(), + body: z.record(z.string(), z.unknown()), + amountField: z.string().min(1), + }) + .optional(), + }), + }, + async (input) => jsonResponse(buildDepositPlan(input)), +); + +server.registerTool( + "robinhood_deposit_inventory", + { + title: "Robinhood Deposit Destination × Funding Source Inventory", + description: + "Live-read eligible owned destinations and observed linked funding sources from captured GET contracts. Never submits a deposit.", + annotations: toolAnnotations(true, "read"), + inputSchema: z.object({}), + }, + async () => jsonResponse(await getDepositInventory()), +); + server.registerTool( "robinhood_roth_deposit_plan", {