diff --git a/bun.lock b/bun.lock index a9dc898..b548bd1 100644 --- a/bun.lock +++ b/bun.lock @@ -11,7 +11,7 @@ "@modelcontextprotocol/core": "2.0.0", "@modelcontextprotocol/server": "2.0.0", "@onkernel/managed-auth-react": "0.5.5", - "@onkernel/sdk": "0.152.0", + "@onkernel/sdk": "0.154.0", "@posthog/mcp": "0.17.0", "@types/jsonwebtoken": "^9.0.10", "@types/redis": "^4.0.11", @@ -160,7 +160,7 @@ "@onkernel/managed-auth-react": ["@onkernel/managed-auth-react@0.5.5", "", { "dependencies": { "clsx": "^2.1.1", "tldts": "7.4.15" }, "peerDependencies": { "react": ">=18", "react-dom": ">=18" } }, "sha512-uoeHAJ0RnLoEJe7TdpT0pA3RgPWEpJLf9F532aLEcahFNrMIqyAdMp94LNIwVuMlxkkfx4+3S/fqzHubbnzjJg=="], - "@onkernel/sdk": ["@onkernel/sdk@0.152.0", "", { "peerDependencies": { "@aws-sdk/client-sts": ">=3.935.0" }, "optionalPeers": ["@aws-sdk/client-sts"] }, "sha512-mDe0WxYMtrJFVc1BKJ+ned2tHioq1bupVcwUx+Uou2+mx++Aj83GrVb3wZ02Xi3PfHZUtn/WMATGc5DbfkDamA=="], + "@onkernel/sdk": ["@onkernel/sdk@0.154.0", "", { "peerDependencies": { "@aws-sdk/client-sts": ">=3.935.0" }, "optionalPeers": ["@aws-sdk/client-sts"] }, "sha512-Du1s1JWby2kn3LlB+ff37wbziBGOYg4anQKYYIjfaukjZyE4+mOyg2lr/FMZwVXkMEVNIMjwQ5PEydaXgVWqLQ=="], "@oven/bun-darwin-aarch64": ["@oven/bun-darwin-aarch64@1.3.3", "", { "os": "darwin", "cpu": "arm64" }, "sha512-eJopQrUk0WR7jViYDC29+Rp50xGvs4GtWOXBeqCoFMzutkkO3CZvHehA4JqnjfWMTSS8toqvRhCSOpOz62Wf9w=="], diff --git a/package.json b/package.json index f6b3cef..35797c3 100644 --- a/package.json +++ b/package.json @@ -40,7 +40,7 @@ "@modelcontextprotocol/core": "2.0.0", "@modelcontextprotocol/server": "2.0.0", "@onkernel/managed-auth-react": "0.5.5", - "@onkernel/sdk": "0.152.0", + "@onkernel/sdk": "0.154.0", "@posthog/mcp": "0.17.0", "@types/jsonwebtoken": "^9.0.10", "@types/redis": "^4.0.11", diff --git a/src/lib/mcp/tools/apps.test.ts b/src/lib/mcp/tools/apps.test.ts index f93920e..3e2bd73 100644 --- a/src/lib/mcp/tools/apps.test.ts +++ b/src/lib/mcp/tools/apps.test.ts @@ -116,6 +116,7 @@ describe("manage_apps invocation contract", () => { captcha_solver: { enabled: true }, stealth: true, fingerprint: { os: "linux" }, + platform: { os: "macos" }, memory: "2GiB", timeout_seconds: 600, region: "us-east", @@ -161,6 +162,7 @@ describe("manage_apps invocation contract", () => { "https://api.onkernel.com/browser/live/signed", captcha_solver: { enabled: true }, fingerprint: { os: "linux" }, + platform: { os: "macos" }, leased_at: "2026-08-08T00:05:00Z", location: { timezone: "America/New_York", diff --git a/src/lib/mcp/tools/apps.ts b/src/lib/mcp/tools/apps.ts index 06d85ca..79b7b45 100644 --- a/src/lib/mcp/tools/apps.ts +++ b/src/lib/mcp/tools/apps.ts @@ -284,6 +284,9 @@ export function registerAppCapabilities( ...(browser.fingerprint !== undefined && { fingerprint: browser.fingerprint, }), + ...(browser.platform !== undefined && { + platform: browser.platform, + }), ...(browser.leased_at !== undefined && { leased_at: browser.leased_at, }), diff --git a/src/lib/mcp/tools/browser-pools.test.ts b/src/lib/mcp/tools/browser-pools.test.ts index 29f3639..1745b22 100644 --- a/src/lib/mcp/tools/browser-pools.test.ts +++ b/src/lib/mcp/tools/browser-pools.test.ts @@ -466,7 +466,7 @@ describe("browser-pool contract parity", () => { }); }); - test("forwards acquire overrides and returns leased time, network, memory, and location", async () => { + test("forwards acquire overrides and returns leased time, platform, network, memory, and location", async () => { const network = { allowed_hosts: ["example.com"] }; const location = { timezone: "America/New_York", @@ -491,6 +491,7 @@ describe("browser-pool contract parity", () => { memory: "2GiB", captcha_solver: { enabled: true }, fingerprint: { os: "linux" }, + platform: { os: "linux" }, location, }; }, @@ -535,6 +536,7 @@ describe("browser-pool contract parity", () => { memory: "2GiB", captcha_solver: { enabled: true }, fingerprint: { os: "linux" }, + platform: { os: "linux" }, location, replay: { replay_id: "rpl_1", diff --git a/src/lib/mcp/tools/browser-pools.ts b/src/lib/mcp/tools/browser-pools.ts index 016913f..dcf72c6 100644 --- a/src/lib/mcp/tools/browser-pools.ts +++ b/src/lib/mcp/tools/browser-pools.ts @@ -306,6 +306,7 @@ function summarizeAcquiredBrowser(browser: BrowserPoolAcquireResponse) { captcha_solver: browser.captcha_solver, stealth: browser.stealth, fingerprint: browser.fingerprint, + platform: browser.platform, timeout_seconds: browser.timeout_seconds, memory: browser.memory, location: browser.location, diff --git a/src/lib/mcp/tools/browsers.test.ts b/src/lib/mcp/tools/browsers.test.ts index 6a54c4a..d8ac809 100644 --- a/src/lib/mcp/tools/browsers.test.ts +++ b/src/lib/mcp/tools/browsers.test.ts @@ -1,6 +1,7 @@ /// import { describe, expect, test } from "bun:test"; +import { APIError } from "@onkernel/sdk"; import { connectTestMcp, toolResultJSON, @@ -1189,7 +1190,7 @@ describe("manage_browsers location, memory, and conditional allowlists", () => { } }); - test("forwards include_deleted=false on get", async () => { + test("forwards explicit detail flags and leaves opt-in cost off by default", async () => { const calls: unknown[] = []; const { client, close } = await connectTestMcp( registerBrowserCapabilities, @@ -1197,7 +1198,7 @@ describe("manage_browsers location, memory, and conditional allowlists", () => { browsers: { retrieve: async (...args: unknown[]) => { calls.push(args); - return { session_id: "brr_deleted" }; + return { session_id: String(args[0]) }; }, }, }, @@ -1210,9 +1211,29 @@ describe("manage_browsers location, memory, and conditional allowlists", () => { action: "get", session_id: "brr_deleted", include_deleted: false, + include_cost: false, }, }); - expect(calls).toEqual([["brr_deleted", { include_deleted: false }]]); + await client.callTool({ + name: "manage_browsers", + arguments: { + action: "get", + session_id: "brr_active", + }, + }); + await client.callTool({ + name: "manage_browsers", + arguments: { + action: "get", + session_id: "brr_costed", + include_cost: true, + }, + }); + expect(calls).toEqual([ + ["brr_deleted", { include_cost: false, include_deleted: false }], + ["brr_active"], + ["brr_costed", { include_cost: true }], + ]); } finally { await close(); } @@ -1441,6 +1462,110 @@ describe("manage_browsers captcha solving and fingerprint overrides", () => { }); }); +describe("manage_browsers host platform", () => { + test("advertises and forwards the browser host operating system", async () => { + const creates: unknown[] = []; + let updates = 0; + const { client, close } = await connectTestMcp( + registerBrowserCapabilities, + { + browsers: { + create: async (params: unknown) => { + creates.push(params); + return { session_id: "brr_macos", platform: { os: "macos" } }; + }, + update: async () => { + updates++; + return { session_id: "brr_macos" }; + }, + }, + }, + ); + + try { + const tool = (await client.listTools()).tools.find( + ({ name }) => name === "manage_browsers", + ); + const platform = tool?.inputSchema.properties?.platform as + | { + description?: string; + properties?: { os?: { enum?: string[] } }; + } + | undefined; + expect(platform?.properties?.os?.enum).toEqual(["linux", "macos"]); + expect(platform?.description).toContain( + "reported browser os override does not change the host", + ); + expect(platform?.description).toContain("profile_id/profile_name"); + expect(platform?.description).toContain("platform_unavailable"); + expect(platform?.description).toContain("unsupported_configuration"); + expect(platform?.description).toContain("unsupported_fields"); + + const created = toolResultJSON( + await client.callTool({ + name: "manage_browsers", + arguments: { action: "create", platform: { os: "macos" } }, + }), + ); + expect(creates).toEqual([{ platform: { os: "macos" } }]); + expect(created.browser.platform).toEqual({ os: "macos" }); + + const update = await client.callTool({ + name: "manage_browsers", + arguments: { + action: "update", + session_id: "brr_macos", + platform: { os: "linux" }, + }, + }); + expect(update.isError).toBe(true); + expect(updates).toBe(0); + } finally { + await close(); + } + }); + + test("surfaces safe unsupported platform fields from API errors", async () => { + const { client, close } = await connectTestMcp( + registerBrowserCapabilities, + { + browsers: { + create: async () => { + throw APIError.generate( + 400, + { + code: "unsupported_configuration", + message: "The requested platform configuration is unsupported.", + unsupported_fields: ["headless", "profile"], + }, + undefined, + new Headers(), + ); + }, + }, + }, + ); + + try { + const result = await client.callTool({ + name: "manage_browsers", + arguments: { + action: "create", + platform: { os: "macos" }, + headless: true, + profile_id: "profile_1", + }, + }); + expect(result.isError).toBe(true); + expect(toolResultText(result)).toContain( + "unsupported fields: headless, profile.", + ); + } finally { + await close(); + } + }); +}); + describe("manage_browsers region", () => { test("passes region to create and list", async () => { const createCalls: unknown[] = []; @@ -1501,6 +1626,92 @@ describe("manage_browsers region", () => { }); }); +describe("manage_browsers cost details", () => { + test("opts into detail cost, returns guidance, and preserves zero spend", async () => { + const costs = { + brr_provisional: { + status: "provisional", + estimated_usage_spend_usd: "0", + as_of: "2026-11-20T12:34:56Z", + }, + brr_pending: { status: "pending" }, + brr_unavailable: { status: "unavailable" }, + } as const; + const calls: unknown[] = []; + const { client, close } = await connectTestMcp( + registerBrowserCapabilities, + { + browsers: { + retrieve: async (...args: unknown[]) => { + calls.push(args); + const [sessionId, query] = args as [ + keyof typeof costs, + { include_cost?: boolean } | undefined, + ]; + return { + session_id: sessionId, + ...(query?.include_cost && { cost: costs[sessionId] }), + }; + }, + }, + }, + ); + + try { + const results = []; + for (const session_id of Object.keys(costs)) { + results.push( + toolResultJSON( + await client.callTool({ + name: "manage_browsers", + arguments: { action: "get", session_id, include_cost: true }, + }), + ), + ); + } + + expect(results.map(({ cost }) => cost)).toEqual(Object.values(costs)); + expect(results[0].cost).toEqual({ + status: "provisional", + estimated_usage_spend_usd: "0", + as_of: "2026-11-20T12:34:56Z", + }); + for (const { note } of results) { + expect(note).toContain("gross provisional usd browser-meter cost"); + expect(note).toContain("not an invoice total"); + expect(note).toContain('status "pending"'); + expect(note).toContain('"unavailable"'); + expect(note).toContain("may accrue additional usage"); + } + + const resource = (await client.readResource({ + uri: "kernel://orgs/org_test/projects/proj_test/browsers/brr_provisional", + })) as TextResourceResult; + expect(JSON.parse(resource.contents[0].text)).toEqual({ + session_id: "brr_provisional", + }); + expect(calls).toEqual([ + ["brr_provisional", { include_cost: true }], + ["brr_pending", { include_cost: true }], + ["brr_unavailable", { include_cost: true }], + ["brr_provisional"], + ]); + + const browserTool = (await client.listTools()).tools.find( + ({ name }) => name === "manage_browsers", + ); + expect(browserTool?.description).toContain( + '"get" for full details and optional provisional browser-session usage cost', + ); + expect(browserTool?.inputSchema.properties?.include_cost).toMatchObject({ + description: expect.stringContaining("default is off"), + }); + } finally { + await close(); + } + }); +}); + describe("manage_browsers replay creation and live view", () => { test("forwards start_replay=false and returns replay metadata", async () => { const calls: unknown[] = []; diff --git a/src/lib/mcp/tools/browsers.ts b/src/lib/mcp/tools/browsers.ts index 384eed1..23e329e 100644 --- a/src/lib/mcp/tools/browsers.ts +++ b/src/lib/mcp/tools/browsers.ts @@ -1,5 +1,5 @@ import type { McpServer } from "@modelcontextprotocol/server"; -import { NotFoundError, type Kernel } from "@onkernel/sdk"; +import { APIError, NotFoundError, type Kernel } from "@onkernel/sdk"; import { z } from "zod"; import { browserCaptchaSolverSchema, @@ -403,6 +403,37 @@ async function readBrowserTelemetry( return textResponse(serializedResponse); } +const browserCostNote = + 'cost appears only on browser detail reads requested with include_cost=true; manage_browsers action "list" and other browser responses omit it. estimated_usage_spend_usd is a gross provisional usd browser-meter cost before credits, subscriptions, tax, or adjustments, not an invoice total; it appears only with status "provisional", including "0" for a completed zero-uptime session. status "pending" means the billing checkpoint or rate calculation is not ready, while "unavailable" means the session cannot currently be priced safely. as_of is the time of the live uptime read or durable billing checkpoint; running or recently deleted sessions may accrue additional usage.'; + +function browserDetailWithCostNote( + browser: Awaited>, +) { + return browser.cost === undefined + ? browser + : { ...browser, note: browserCostNote }; +} + +function browserUnsupportedFieldsNote(error: unknown) { + if (!(error instanceof APIError)) return undefined; + const parsed = z + .object({ + unsupported_fields: z + .array( + z + .string() + .max(64) + .regex(/^[A-Za-z_][A-Za-z0-9_.-]*$/), + ) + .min(1) + .max(32), + }) + .safeParse(error.error); + return parsed.success + ? `unsupported fields: ${parsed.data.unsupported_fields.join(", ")}.` + : undefined; +} + function browserSessionNextActions(sessionId: string) { return [ `drive the browser with webmcp, browser_repl, execute_playwright_code, or computer_action using session_id "${sessionId}", preferring the first that can carry the current step.`, @@ -505,7 +536,7 @@ export function registerBrowserCapabilities( "manage_browsers", { description: - 'manage the browser sessions that every web task runs in, and their archived telemetry. once a session exists, drive it with webmcp, browser_repl, execute_playwright_code, or computer_action, preferring the first that can carry the current step. use "list" to choose an existing session, "create" before browser control, "update" to change supported session settings, "get" for full details, "get_telemetry" to diagnose active or deleted sessions, "create_live_view" to mint a read or control live-view url for a headful browser, "save_profile" to snapshot a running session to a profile without ending it, and "delete" when finished. live view urls are bearer credentials that cannot be revoked before they expire. save_profile restarts the browser: cdp, playwright, and webdriver connections close and tabs reload, so call it at a stable point, such as right after a login completes. live sessions can be addressed by id or by the name given at creation or set on update; deleted sessions only by id. get_telemetry compacts events by default; set compact=false with explicit categories and a limit of at most 5 when raw headers, request data, response bodies, or other omitted fields are needed.', + 'manage the browser sessions that every web task runs in, and their archived telemetry. once a session exists, drive it with webmcp, browser_repl, execute_playwright_code, or computer_action, preferring the first that can carry the current step. use "list" to choose an existing session, "create" before browser control, "update" to change supported session settings, "get" for full details and optional provisional browser-session usage cost, "get_telemetry" to diagnose active or deleted sessions, "create_live_view" to mint a read or control live-view url for a headful browser, "save_profile" to snapshot a running session to a profile without ending it, and "delete" when finished. live view urls are bearer credentials that cannot be revoked before they expire. save_profile restarts the browser: cdp, playwright, and webdriver connections close and tabs reload, so call it at a stable point, such as right after a login completes. live sessions can be addressed by id or by the name given at creation or set on update; deleted sessions only by id. get_telemetry compacts events by default; set compact=false with explicit categories and a limit of at most 5 when raw headers, request data, response bodies, or other omitted fields are needed.', inputSchema: z.strictObject( { ...projectSelectionInputSchema(), @@ -598,6 +629,17 @@ export function registerBrowserCapabilities( "(create) closed beta overrides for browser attributes presented to websites. supports os=linux or os=macos and requires captcha_solver.enabled=true with omitted memory so the default is used; headless and gpu may be omitted (they default to false) but cannot be set to true. contact KERNEL to enable this capability for the organization; omit it to preserve default browser behavior.", ) .optional(), + platform: z + .object({ + os: z + .enum(["linux", "macos"]) + .describe("operating system of the browser host."), + }) + .strict() + .describe( + "(create) host os. omit or use linux; the reported browser os override does not change the host. macos is currently unavailable and returns platform_unavailable. macos is headful and us-east-only; headless=true, memory, gpu, video_memory, profile_id/profile_name, location, reported browser settings, or another region returns unsupported_configuration with unsupported_fields.", + ) + .optional(), headless: z .boolean() .describe("(create) launch without gui. faster but no live view.") @@ -799,6 +841,12 @@ export function registerBrowserCapabilities( "(get) include a soft-deleted session for audit. a deleted session must be addressed by id, not name.", ) .optional(), + include_cost: z + .boolean() + .describe( + "(get) include provisional session usage cost. default is off; send true to calculate it.", + ) + .optional(), limit: paginationParams.limit.describe( "(list, get_telemetry) max results per page (1-100). get_telemetry defaults to 100; the list default is set by the api.", ), @@ -923,6 +971,14 @@ export function registerBrowserCapabilities( "fingerprint overrides are creation-only; use a new browser to change them.", ); } + if (params.action !== "create" && params.platform !== undefined) { + return errorResponse( + "error: platform is creation-only; use a new browser to change the host operating system.", + ); + } + if (params.action !== "get" && params.include_cost !== undefined) { + return errorResponse("error: include_cost applies only to get."); + } if (params.action !== "create" && params.captcha_solver !== undefined) { return errorResponse( "error: captcha_solver is creation-only for a browser session.", @@ -1015,6 +1071,8 @@ export function registerBrowserCapabilities( createParams.vaults = params.vaults; if (params.fingerprint !== undefined) createParams.fingerprint = params.fingerprint; + if (params.platform !== undefined) + createParams.platform = params.platform; if (params.headless !== undefined) createParams.headless = params.headless; if (params.gpu !== undefined) createParams.gpu = params.gpu; @@ -1200,17 +1258,23 @@ export function registerBrowserCapabilities( return errorResponse( "error: session_id is required for get action.", ); - const browser = await client.browsers.retrieve( - params.session_id, - params.include_deleted !== undefined - ? { include_deleted: params.include_deleted } - : undefined, - ); + const browser = + params.include_cost === undefined && + params.include_deleted === undefined + ? await client.browsers.retrieve(params.session_id) + : await client.browsers.retrieve(params.session_id, { + ...(params.include_cost !== undefined && { + include_cost: params.include_cost, + }), + ...(params.include_deleted !== undefined && { + include_deleted: params.include_deleted, + }), + }); if (!browser) return errorResponse( `browser session "${params.session_id}" not found`, ); - return jsonResponse(browser); + return jsonResponse(browserDetailWithCostNote(browser)); } case "get_telemetry": { if (!params.session_id) @@ -1329,11 +1393,17 @@ export function registerBrowserCapabilities( } } } catch (error) { + const note = [ + params.action === "save_profile" ? saveProfileErrorNote : undefined, + browserUnsupportedFieldsNote(error), + ] + .filter((value): value is string => value !== undefined) + .join(" "); throwToolError( "manage_browsers", params.action, error, - params.action === "save_profile" ? saveProfileErrorNote : undefined, + note || undefined, ); } }, diff --git a/src/lib/mcp/tools/vault-items.ts b/src/lib/mcp/tools/vault-items.ts index 3549797..bc5ee65 100644 --- a/src/lib/mcp/tools/vault-items.ts +++ b/src/lib/mcp/tools/vault-items.ts @@ -7,6 +7,7 @@ import { projectForOperation } from "@/lib/mcp/project-selection"; import { longOperationOptions } from "@/lib/mcp/request-options"; import { errorResponse, jsonResponse } from "@/lib/mcp/responses"; import { + linkBalanceSetupOperationResponse, linkCheckoutRecovery, paymentMethodOperationResponse, projectVaultOutput, @@ -34,6 +35,9 @@ import { fillInputsSchema, fillInputsShape, isPasskeyOperation, + linkBalanceSetupInputsIssueMessage, + linkBalanceSetupInputsSchema, + linkBalanceSetupInputsShape, onePasswordFillInputsIssueMessage, onePasswordFillInputsSchema, onePasswordFillInputsShape, @@ -56,6 +60,7 @@ import { type AuthorizeInputs, type ConfirmTransactionInputs, type FillInputs, + type LinkBalanceSetupInputs, type OnePasswordFillInputs, type OnePasswordStatusInputs, type PasskeyInputs, @@ -101,7 +106,7 @@ export function registerVaultItemTools( ) .optional() .describe( - `(invoke) use only fields required by the advertised operation; never include type, id_or_name, or secret values. fill takes exactly ${fillInputsShape}: browser_id is a session id, page_url is the exact current https top-level url, and fields are ordered field/selector bindings. selectors must match one element across the page and nested frames; timeout_ms is deprecated and ignored. authorize takes ${authorizeInputsShape}: link and shop pay require browser_id plus page_url together; KERNEL cards may take browser_id alone before the payment step. confirm_transaction takes exactly ${confirmTransactionInputsShape}: amount is 0..1000000 minor units and no more than approved; currency must match; occurred_at is rfc3339. shop pay accepts only \`PURCHASE\`, \`AUTHORIZATION\`, and \`CAPTURE\`; approved may include order_id/order_url, while other outcomes may include failure_code and payment_declined for \`DECLINED\`. 1pw_fill takes exactly ${onePasswordFillInputsShape}; target_id selects a page, and entry_id selects a login when the page origin does not identify exactly one. 1pw_access_request_status takes exactly ${onePasswordStatusInputsShape}. 1pw_disconnect takes no inputs. arm_passkey, register_passkey, and disarm_passkey each take exactly ${passkeyInputsShape}; field selects the stored passkey for arm, field selects the empty passkey field for register, and omission disarms all for this item. add_payment_method takes exactly ${addPaymentMethodInputsShape}; remove_payment_method takes exactly ${removePaymentMethodInputsShape}. webmcp_invoke requires browser_id, tool_ref, page_url, input, bindings, and optional timeout_sec; serialized input is limited to 64 kib.`, + `(invoke) use only fields required by the advertised operation; never include type, id_or_name, or secret values. fill takes exactly ${fillInputsShape}: browser_id is a session id, page_url is the exact current https top-level url, and fields are ordered field/selector bindings. selectors must match one element across the page and nested frames; timeout_ms is deprecated and ignored. authorize takes ${authorizeInputsShape}: link and shop pay require browser_id plus page_url together; KERNEL cards may take browser_id alone before the payment step. confirm_transaction takes exactly ${confirmTransactionInputsShape}: amount is 0..1000000 minor units and no more than approved; currency must match; occurred_at is rfc3339. shop pay accepts only \`PURCHASE\`, \`AUTHORIZATION\`, and \`CAPTURE\`; approved may include order_id/order_url, while other outcomes may include failure_code and payment_declined for \`DECLINED\`. 1pw_fill takes exactly ${onePasswordFillInputsShape}; target_id selects a page, and entry_id selects a login when the page origin does not identify exactly one. 1pw_access_request_status takes exactly ${onePasswordStatusInputsShape}. 1pw_disconnect takes no inputs. arm_passkey, register_passkey, and disarm_passkey each take exactly ${passkeyInputsShape}; field selects the stored passkey for arm, field selects the empty passkey field for register, and omission disarms all for this item. add_payment_method takes exactly ${addPaymentMethodInputsShape}; remove_payment_method takes exactly ${removePaymentMethodInputsShape}. link_balance_setup takes ${linkBalanceSetupInputsShape}; both cent values are at least 100 and whole-dollar multiples, desired_transaction_limit is at most 50000, and link refuses a desired balance needing over $150 added. webmcp_invoke requires browser_id, tool_ref, page_url, input, bindings, and optional timeout_sec; serialized input is limited to 64 kib.`, ), expand: z .array( @@ -212,6 +217,7 @@ export function registerVaultItemTools( let removePaymentMethodInputs: | RemovePaymentMethodInputs | undefined; + let linkBalanceSetupInputs: LinkBalanceSetupInputs | undefined; if (params.operation === "fill") { const parsed = fillInputsSchema.safeParse(params.inputs ?? {}); if (!parsed.success) @@ -290,6 +296,16 @@ export function registerVaultItemTools( ); removePaymentMethodInputs = parsed.data; } + if (params.operation === "link_balance_setup") { + const parsed = linkBalanceSetupInputsSchema.safeParse( + params.inputs ?? {}, + ); + if (!parsed.success) + return errorResponse( + linkBalanceSetupInputsIssueMessage(parsed.error), + ); + linkBalanceSetupInputs = parsed.data; + } if (params.operation === "webmcp_invoke") { const parsed = webmcpInvokeInputsSchema.safeParse( params.inputs ?? {}, @@ -426,6 +442,7 @@ export function registerVaultItemTools( passkeyInputs ?? addPaymentMethodInputs ?? removePaymentMethodInputs ?? + linkBalanceSetupInputs ?? params.inputs), } as Parameters[1], onePasswordStatusInputs @@ -450,6 +467,8 @@ export function registerVaultItemTools( params.operation === "remove_payment_method" ) return paymentMethodOperationResponse(result); + if (params.operation === "link_balance_setup") + return linkBalanceSetupOperationResponse(result); const projected = projectVaultOutput( result, vaultOperationResultFields, diff --git a/src/lib/mcp/tools/vault-payment-methods.test.ts b/src/lib/mcp/tools/vault-payment-methods.test.ts index 56fd64d..2a33aed 100644 --- a/src/lib/mcp/tools/vault-payment-methods.test.ts +++ b/src/lib/mcp/tools/vault-payment-methods.test.ts @@ -1,5 +1,8 @@ import { describe, expect, test } from "bun:test"; -import { toolResultJSON } from "@/lib/mcp/mcp-test-fixtures"; +import { + toolResultJSON, + toolResultText, +} from "@/lib/mcp/mcp-test-fixtures"; import { connectVaultTest, item } from "@/lib/mcp/tools/vaults.test-fixtures"; const target = { vault: "checkout", key: "wallet-1" }; @@ -7,6 +10,8 @@ const enrollmentURL = "https://vault.kernel.example/card#capability=private-enrollment"; const ingestURL = "https://cards.kernel.example/vault/card-ingest/private-capability"; +const balanceSetupURL = + "https://link.example/balance/setup?session=opaque-user-capability"; const kernelWallet = { ...item, @@ -27,6 +32,30 @@ const kernelWallet = { available_expansions: [{ type: "payment_methods", description: "Cards." }], }; +const linkWallet = { + ...item, + key: "wallet-1", + type: "wallet", + spec: { + provider: "link", + authorization: { + method: "oauth", + client: { type: "kernel_managed" }, + }, + }, + state: { provider: "link", status: "connected" }, + available_operations: [ + { + type: "link_balance_setup", + description: "Open Link balance setup.", + }, + ], + available_expansions: [ + { type: "payment_methods", description: "Live payment methods." }, + { type: "link_user_info", description: "Live Link user info." }, + ], +}; + const pendingPaymentMethod = { id: "pm_kernel_2", provider: "kernel", @@ -59,6 +88,7 @@ describe("Kernel wallet payment methods", () => { enum: [ "create", "payment_methods", + "link_balance_setup", "add_payment_method", "remove_payment_method", ], @@ -66,6 +96,7 @@ describe("Kernel wallet payment methods", () => { expect(wallets?.description).toContain( "returns an empty connected wallet", ); + expect(wallets?.description).toContain('"link_balance_setup"'); expect(wallets?.description).toContain("vaults:write plus vaults:use"); expect(wallets?.inputSchema.properties?.enrollment).toMatchObject({ enum: ["hosted", "server"], @@ -529,6 +560,240 @@ describe("Kernel wallet payment methods", () => { }); }); +describe("Link balance setup", () => { + test("projects live balance amounts including zero", async () => { + const expanded = { + ...linkWallet, + expanded: { + payment_methods: [ + { + id: "pm_link_balance", + provider: "link", + type: "balance", + is_default: false, + display: { label: "Link balance" }, + capabilities: {}, + balance: { + available: { amount: 0, currency: "usd" }, + provider_private: "hidden", + }, + }, + ], + }, + }; + const fixture = await connectVaultTest([Response.json(expanded)]); + try { + const result = toolResultJSON( + await fixture.call("manage_vault_wallets", { + ...target, + action: "payment_methods", + }), + ); + expect(result.item.expanded.payment_methods[0]).toMatchObject({ + id: "pm_link_balance", + type: "balance", + balance: { available: { amount: 0, currency: "usd" } }, + }); + expect(JSON.stringify(result)).not.toContain("provider_private"); + expect(result.guidance.join(" ")).toContain( + "payment_methods is live provider data", + ); + expect(result.guidance.join(" ")).toContain("never stores the balance"); + } finally { + await fixture.close(); + } + }); + + test("advertises bounded whole-dollar suggestions and forwards grouped setup", async () => { + const fixture = await connectVaultTest([ + Response.json(linkWallet), + Response.json({ + type: "link_balance_setup", + url: balanceSetupURL, + provider_private: "hidden", + }), + ]); + try { + const wallets = (await fixture.client.listTools()).tools.find( + ({ name }) => name === "manage_vault_wallets", + ); + expect( + wallets?.inputSchema.properties?.desired_balance_amount, + ).toMatchObject({ + minimum: 100, + multipleOf: 100, + }); + expect( + wallets?.inputSchema.properties?.desired_transaction_limit, + ).toMatchObject({ + minimum: 100, + maximum: 50000, + multipleOf: 100, + }); + + const result = toolResultJSON( + await fixture.call("manage_vault_wallets", { + ...target, + action: "link_balance_setup", + desired_balance_amount: 100, + desired_transaction_limit: 50000, + }), + ); + expect( + fixture.requests.map(({ method, path, body }) => ({ + method, + path, + body, + })), + ).toEqual([ + { + method: "GET", + path: "/vaults/checkout/items/wallet-1", + body: undefined, + }, + { + method: "POST", + path: "/vaults/checkout/items/wallet-1/operations", + body: { + type: "link_balance_setup", + desired_balance_amount: 100, + desired_transaction_limit: 50000, + }, + }, + ]); + expect(result.result).toEqual({ + type: "link_balance_setup", + url: balanceSetupURL, + }); + expect(result.guidance).toContain("only the user can complete"); + expect(result.guidance).toContain("does not expire"); + expect(result.guidance).toContain("balance.available"); + expect(result.guidance).toContain("still require the user's approval"); + expect(JSON.stringify(result)).not.toContain("provider_private"); + } finally { + await fixture.close(); + } + }); + + test("supports advertised generic invocation and optional fields", async () => { + const fixture = await connectVaultTest([ + Response.json(linkWallet), + Response.json({ type: "link_balance_setup", url: balanceSetupURL }), + ]); + try { + const items = (await fixture.client.listTools()).tools.find( + ({ name }) => name === "manage_vault_items", + ); + const inputsDescription = String( + ( + items?.inputSchema.properties?.inputs as + | { description?: string } + | undefined + )?.description, + ); + expect(inputsDescription).toContain("at least 100"); + expect(inputsDescription).toContain("over $150 added"); + expect(inputsDescription).toContain("at most 50000"); + + const result = toolResultJSON( + await fixture.call("manage_vault_items", { + ...target, + action: "invoke", + operation: "link_balance_setup", + inputs: { desired_balance_amount: 200 }, + }), + ); + expect(fixture.requests[1].body).toEqual({ + type: "link_balance_setup", + desired_balance_amount: 200, + }); + expect(result.result.url).toBe(balanceSetupURL); + } finally { + await fixture.close(); + } + }); + + test("rejects an unsafe setup response without echoing its secret", async () => { + const fixture = await connectVaultTest([ + Response.json(linkWallet), + Response.json({ + type: "link_balance_setup", + url: "https://link.example/setup?access_token=hidden-capability", + }), + ]); + try { + const result = await fixture.call("manage_vault_wallets", { + ...target, + action: "link_balance_setup", + }); + expect(result.isError).toBe(true); + expect(toolResultText(result)).toContain( + "unrecognized Link balance setup response", + ); + expect(toolResultText(result)).not.toContain("hidden-capability"); + } finally { + await fixture.close(); + } + }); + + test.each([ + { + tool: "manage_vault_wallets", + args: { + ...target, + action: "link_balance_setup", + desired_balance_amount: 0, + }, + }, + { + tool: "manage_vault_wallets", + args: { + ...target, + action: "link_balance_setup", + desired_balance_amount: 150, + }, + }, + { + tool: "manage_vault_wallets", + args: { + ...target, + action: "link_balance_setup", + desired_transaction_limit: 50100, + }, + }, + { + tool: "manage_vault_items", + args: { + ...target, + action: "invoke", + operation: "link_balance_setup", + inputs: { desired_transaction_limit: 0 }, + }, + }, + { + tool: "manage_vault_items", + args: { + ...target, + action: "invoke", + operation: "link_balance_setup", + inputs: { unexpected: false }, + }, + }, + ])( + "rejects invalid setup suggestions before reading the wallet", + async ({ tool, args }) => { + const fixture = await connectVaultTest([]); + try { + const result = await fixture.call(tool, args); + expect(result.isError).toBe(true); + expect(fixture.requests).toHaveLength(0); + } finally { + await fixture.close(); + } + }, + ); +}); + describe("Kernel purchase funding selection", () => { const cardSpec = { wallet: "wallet-1", diff --git a/src/lib/mcp/tools/vault-wallets.ts b/src/lib/mcp/tools/vault-wallets.ts index 114de7c..7e1d1e3 100644 --- a/src/lib/mcp/tools/vault-wallets.ts +++ b/src/lib/mcp/tools/vault-wallets.ts @@ -6,6 +6,7 @@ import { projectForOperation } from "@/lib/mcp/project-selection"; import { longOperationOptions } from "@/lib/mcp/request-options"; import { errorResponse } from "@/lib/mcp/responses"; import { + linkBalanceSetupOperationResponse, paymentMethodOperationResponse, throwKernelVaultError, throwVaultError, @@ -31,13 +32,14 @@ export function registerVaultWalletTools( "manage_vault_wallets", { description: - 'connect payment wallets without exposing secrets. "create" creates or retrieves an identical wallet by immutable key; spec describes each provider. KERNEL creation returns an empty connected wallet where add_payment_method is enabled, otherwise a hosted card_enrollment action; shop pay creation returns a shop_pay_oauth action whose url must be shared unchanged with the shopper. share oauth and enrollment urls only with the intended user in a private surface; never open, alter, or log them. embedded card-capture tokens are bearer secrets and are intentionally not returned by mcp. a valid imported link grant creates a connected wallet. "payment_methods" requests the advertised live payment_methods expansion. on a KERNEL wallet that advertises them, "add_payment_method" starts one card enrollment and "remove_payment_method" removes one card after explicit user confirmation; neither takes card details, and both need vaults:write plus vaults:use for scoped api keys. manage_vault_items get can request any advertised expansion, including live link_user_info and link_shipping_addresses data that KERNEL does not store; unavailable expansions return an api error. select link payment_method_id explicitly; never automatically choose a default. KERNEL card items that omit payment_method_id use only the legacy default card; KERNEL payment_request items always require one. a connected link wallet returns item.description with the checkout flow; follow it. pay with link in this order: reach the final checkout page, choose a payment_method_id with "payment_methods", create the card with manage_vault_cards, then authorize it with browser_id and page_url from that checkout; read the card\'s available_operations descriptions for each next step. agentcard card_id may be omitted for cardholder selection at checkout approval. capabilities are advisory; absent means unknown. customer-managed link wallets need write-only tokens from a trusted backend, never chat; config credentials do not authorize a user, and token replacement is unavailable through mcp. duplicate create never replaces a grant; bindings and token_refresh cannot change. no in-place imported reauthorization: obtain a fresh grant under a new wallet key for new payments only; retain unresolved old payments for reconciliation. vgs wallets are provisioned only by a trusted backend through the direct api/sdk. never provide card data or oauth codes. requests are not automatically retried.', + 'connect payment wallets without exposing secrets. "create" upserts by immutable key; duplicate create does not replace grants, bindings, or token_refresh. shop pay creation returns shop_pay_oauth to be shared unchanged. "payment_methods" reads the advertised live methods. "link_balance_setup" gets a link balance page for the user to complete when advertised. KERNEL creation sometimes returns an empty connected wallet; "add_payment_method" starts card enrollment and "remove_payment_method" removes one selected card after explicit user confirmation; scoped api keys need vaults:write plus vaults:use. share oauth, enrollment, and setup urls only with the intended user; never open or log them. embedded card-capture tokens are intentionally omitted. manage_vault_items get reads advertised live link expansions. a connected link wallet returns item.description with the checkout flow; follow it and select payment_method_id explicitly before creating and authorizing a card. customer-managed link grants come from a trusted backend, never chat; mcp cannot replace or reauthorize them, so use a fresh key and retain unresolved payments. vgs wallets are provisioned only by a trusted backend through the direct api/sdk. never provide card data or oauth codes. requests are not automatically retried.', inputSchema: vaultToolInput({ ...vaultItemSchema, key: vaultKeySchema(), action: z.enum([ "create", "payment_methods", + "link_balance_setup", "add_payment_method", "remove_payment_method", ]), @@ -58,6 +60,27 @@ export function registerVaultWalletTools( "(add_payment_method) hosted (default) returns a single-use 30-minute card_enrollment link for the cardholder. server returns a single-use 5-minute card_ingest url for the issuer's backend and requires organization card-ingest configuration. failed or expired enrollment does not affect other methods.", ) .optional(), + desired_balance_amount: z + .number() + .int() + .safe() + .min(100) + .multipleOf(100) + .describe( + "(link_balance_setup) target balance in cents, minimum 100 and a multiple of 100. link prefills only the amount needed to reach it, skips funding when already covered, and refuses a required addition over $150.", + ) + .optional(), + desired_transaction_limit: z + .number() + .int() + .safe() + .min(100) + .max(50000) + .multipleOf(100) + .describe( + "(link_balance_setup) threshold in cents, 100-50000 and a multiple of 100. supplying it shows the threshold step; omission skips it. KERNEL cards still require approval.", + ) + .optional(), spec: z .union([ linkWalletSpecSchema, @@ -115,6 +138,14 @@ export function registerVaultWalletTools( return errorResponse( "payment_method_id is required for remove_payment_method.", ); + if ( + params.action !== "link_balance_setup" && + (params.desired_balance_amount !== undefined || + params.desired_transaction_limit !== undefined) + ) + return errorResponse( + "desired_balance_amount and desired_transaction_limit are only supported for link_balance_setup.", + ); let spec: ItemUpsertParams.WalletVaultItemRequest["spec"] | undefined; if (params.action === "create") { if (!params.provider || !params.spec) @@ -183,6 +214,41 @@ export function registerVaultWalletTools( ); return vaultItemResponse(item, target); } + case "link_balance_setup": { + const wallet = await client.vaults.items.retrieve( + params.key, + { id_or_name: params.vault }, + options, + ); + if (wallet.type !== "wallet" || wallet.spec.provider !== "link") + return errorResponse( + "link_balance_setup is only available for a connected Link wallet.", + ); + if ( + !wallet.available_operations.some( + ({ type }) => type === "link_balance_setup", + ) + ) + return errorResponse( + "link_balance_setup is not advertised in available_operations. inspect the wallet and its link_user_info expansion before taking further action.", + ); + operationSubmitted = true; + const result = await client.vaults.items.performOperation( + params.key, + { + id_or_name: params.vault, + type: "link_balance_setup", + ...(params.desired_balance_amount !== undefined && { + desired_balance_amount: params.desired_balance_amount, + }), + ...(params.desired_transaction_limit !== undefined && { + desired_transaction_limit: params.desired_transaction_limit, + }), + }, + options, + ); + return linkBalanceSetupOperationResponse(result); + } case "add_payment_method": case "remove_payment_method": { const wallet = await client.vaults.items.retrieve( diff --git a/src/lib/mcp/tools/workload-identity.test.ts b/src/lib/mcp/tools/workload-identity.test.ts index fc2a743..74e075c 100644 --- a/src/lib/mcp/tools/workload-identity.test.ts +++ b/src/lib/mcp/tools/workload-identity.test.ts @@ -103,14 +103,23 @@ describe("manage_workload_identity SDK coverage", () => { }, }); expect(tool?.inputSchema.properties?.token_validation).toMatchObject({ - description: expect.stringContaining( - "independently of issued token ttl", - ), properties: { - max_lifetime_seconds: { maximum: 86400, minimum: 1 }, + max_lifetime_seconds: { maximum: 172800, minimum: 1 }, replay_protection: { enum: ["single_use", "allow_reuse"] }, }, }); + const tokenValidationDescription = String( + ( + tool?.inputSchema.properties?.token_validation as + | { description?: string } + | undefined + )?.description, + ); + expect(tokenValidationDescription).toContain( + "independently of issued token ttl", + ); + expect(tokenValidationDescription).toContain("48 hours"); + expect(tokenValidationDescription).toContain("azure"); expect(tool?.inputSchema.properties?.expected_version).toMatchObject({ description: expect.stringContaining("authority security_version"), }); @@ -209,7 +218,7 @@ describe("manage_workload_identity SDK coverage", () => { keys: [{ kty: "RSA", kid: "key-1", n: "public", e: "AQAB" }], }; const tokenValidation = { - max_lifetime_seconds: 3600, + max_lifetime_seconds: 172800, replay_protection: "allow_reuse", }; @@ -542,6 +551,7 @@ describe("manage_workload_identity SDK coverage", () => { const results = await callWorkloadIdentity( { serviceAccounts: { list: record }, + workloadIdentityIssuers: { create: record }, workloadIdentityFederationRules: { create: record, update: record, @@ -559,6 +569,11 @@ describe("manage_workload_identity SDK coverage", () => { action: "list_service_accounts", description: "does not apply", }, + { + action: "create_issuer", + name: "azure-too-long", + token_validation: { max_lifetime_seconds: 172801 }, + }, { action: "create_rule", name: "bad-match", @@ -589,6 +604,7 @@ describe("manage_workload_identity SDK coverage", () => { text: "error: description does not apply to list_service_accounts.", }, ]); + expect(results[3].isError).toBe(true); }); test("rejects API-key and workload-identity MCP credentials locally", async () => { diff --git a/src/lib/mcp/tools/workload-identity.ts b/src/lib/mcp/tools/workload-identity.ts index cd24ab2..9b834b7 100644 --- a/src/lib/mcp/tools/workload-identity.ts +++ b/src/lib/mcp/tools/workload-identity.ts @@ -36,7 +36,7 @@ const workloadIdentityKeySourceSchema = z const workloadIdentityTokenValidationSchema = z .object({ - max_lifetime_seconds: z.number().int().min(1).max(86400).optional(), + max_lifetime_seconds: z.number().int().min(1).max(172800).optional(), replay_protection: z.enum(["single_use", "allow_reuse"]).optional(), }) .strict(); @@ -182,7 +182,7 @@ const workloadIdentityInputSchema = z.object({ .optional(), token_validation: workloadIdentityTokenValidationSchema .describe( - "(create/update issuer) incoming exp minus iat is capped at 1-86400 seconds independently of issued token ttl. replay defaults: single_use for github_actions/aws/entra/custom, allow_reuse for kubernetes; google_cloud always reuses. entra/custom may reuse, kubernetes may use single use, and github_actions/aws cannot reuse.", + "(create/update issuer) incoming exp minus iat is capped at 1-172800 seconds (48 hours), independently of issued token ttl; the upper bound covers azure managed identity tokens that can live slightly over 24 hours. replay defaults: single_use for github_actions/aws/entra/custom, allow_reuse for kubernetes; google_cloud always reuses. entra/custom may reuse, kubernetes may use single use, and github_actions/aws cannot reuse.", ) .optional(), issuer_id: z diff --git a/src/lib/mcp/vault-responses.test.ts b/src/lib/mcp/vault-responses.test.ts index ea81172..130d13b 100644 --- a/src/lib/mcp/vault-responses.test.ts +++ b/src/lib/mcp/vault-responses.test.ts @@ -78,6 +78,10 @@ const unsafeItem = { is_default: false, display: { brand: "visa", last4: "4242", number: "hidden-number" }, capabilities: { single_use_card: { eligible: false, reasons: [] } }, + balance: { + available: { amount: 0, currency: "usd", raw: "hidden-balance" }, + raw: "hidden-balance-envelope", + }, issuer_reference: "issuer-card-42", valid_until: "2026-10-01T13:00:00Z", raw: "hidden-method", @@ -119,6 +123,7 @@ describe("vault public responses", () => { id: "pm_1", is_default: false, capabilities: { single_use_card: { eligible: false, reasons: [] } }, + balance: { available: { amount: 0, currency: "usd" } }, issuer_reference: "issuer-card-42", valid_until: "2026-10-01T13:00:00Z", }, diff --git a/src/lib/mcp/vault-responses.ts b/src/lib/mcp/vault-responses.ts index 8c35538..fc03b48 100644 --- a/src/lib/mcp/vault-responses.ts +++ b/src/lib/mcp/vault-responses.ts @@ -41,6 +41,7 @@ const paymentMethodFields = { display: fields("label brand last4"), capabilities: { single_use_card: fields("eligible reasons") }, action: fields("name url"), + balance: { available: fields("amount currency") }, }; const linkUserInfoFields = { ...fields( @@ -488,6 +489,12 @@ export function vaultItemResponse( const singleUseKernelCard = kernelCardSource.success && kernelCardSource.data.state.source === "single_use_card"; + const linkWallet = z + .object({ + type: z.literal("wallet"), + spec: z.object({ provider: z.literal("link") }), + }) + .safeParse(projected); const importedLinkWallet = z .object({ type: z.literal("wallet"), @@ -583,6 +590,7 @@ export function vaultItemResponse( !singleUseKernelCard ? [kernelWalletGuidance] : []), + ...(linkWallet.success ? [linkWalletBalanceGuidance] : []), ...(importedLinkWallet.success ? [ importedLinkWallet.data.spec.authorization @@ -714,6 +722,25 @@ export function paymentMethodOperationResponse(result: unknown) { }); } +const linkBalanceSetupOperationResultSchema = z.object({ + type: z.literal("link_balance_setup"), + url: z.string().url().refine(isDisplaySafeVaultURL), +}); + +export function linkBalanceSetupOperationResponse(result: unknown) { + const parsed = linkBalanceSetupOperationResultSchema.safeParse(result); + if (!parsed.success) { + return errorResponse( + "operation returned an unrecognized Link balance setup response. inspect the wallet and its payment_methods expansion before acting; do not assume setup completed.", + ); + } + return jsonResponse({ + result: parsed.data, + guidance: + "share result.url only with the intended user in a private surface; only the user can complete the Link page. the url does not expire and is the same for first-time setup, adding money, and changing the threshold. requested amounts are suggestions the page prefills, so do not assume the user accepted them or finished. request the wallet's payment_methods expansion again and look for a method with type balance and balance.available. available.amount is in the currency's smallest unit and available.currency is a lowercase iso 4217 code; the value is read live from Link, never stored by KERNEL, and may be absent when Link did not report it. KERNEL cards still require the user's approval because KERNEL does not yet create spend requests under Link's threshold policy.", + }); +} + // Checkout inspection fails before Link or Shop Pay receives a payment request, // so the agent can fix the browser tab and authorize again. export const linkCheckoutErrorCodes = [ @@ -768,6 +795,9 @@ const kernelSupportGuidance = const kernelWalletGuidance = "KERNEL wallet enrollment and spend approval use bearer action urls. share card_enrollment and spend_approval urls only with the intended user privately; send card_ingest urls only to the trusted card issuer backend. never open them or put them in logs or traces. a connected wallet can hold zero or more cards in payment_methods. when add_payment_method and remove_payment_method are advertised, use manage_vault_wallets to enroll or remove individual cards; add defaults to a 30-minute hosted card_enrollment link and can request a 5-minute server card_ingest url, while removing one method does not disconnect the wallet. otherwise the wallet uses one legacy default card: creation returns its card_enrollment action, pending_authorization waits for enrollment, and degraded means an uncertain enrollment requires deleting the wallet before adding another card. reconnect_required is a legacy wallet awaiting an operator upgrade; reads preserve it, but payment and deletion requests are refused until the upgrade. payment method is_default identifies only the legacy default card; wallets with payment methods enabled have no default. pending_enrollment uses its card_enrollment or card_ingest action. removal_pending refuses payments after an uncertain removal outcome; retry remove_payment_method later only when advertised. recovery_required after an uncertain enrollment may be removable, while an unreadable stored card requires private support and can refuse removal with 409; follow status_reason. payment_methods eligibility is advisory. network_token_pending, network_token_unsupported, or network_token_failed normally means do not authorize, unless the returned capability and advertised flow explicitly support checkout delivery without a network token; then fill types temporary checkout details. for network_token_pending, re-check later at most once in this attempt. if still ineligible or unknown, ask the cardholder before enrolling a different card; do not poll indefinitely or replay an uncertain purchase."; +const linkWalletBalanceGuidance = + "payment_methods is live provider data. a stored-value method such as Link balance has type balance and may include balance.available; amount is in the currency's smallest unit and currency is a lowercase iso 4217 code. available is absent when the provider did not report it, and KERNEL never stores the balance. when link_balance_setup is advertised, use manage_vault_wallets or manage_vault_items to get the user-completed setup page; the suggested balance and threshold do not remove the approval requirement from KERNEL cards."; + const kernelRefreshedLinkWalletGuidance = "this imported link wallet uses token_refresh kernel (the default): KERNEL owns and rotates the refresh token after import, so the customer backend must stop refreshing that grant. if the grant later becomes unusable, do not replace tokens on this wallet through mcp. obtain a fresh grant in the trusted backend and create a new wallet key for new payments only, while retaining unresolved old payments for reconciliation."; diff --git a/src/lib/mcp/vault-schemas.ts b/src/lib/mcp/vault-schemas.ts index 88c030f..20775fa 100644 --- a/src/lib/mcp/vault-schemas.ts +++ b/src/lib/mcp/vault-schemas.ts @@ -199,6 +199,31 @@ export type RemovePaymentMethodInputs = z.infer< typeof removePaymentMethodInputsSchema >; +export const linkBalanceSetupInputsShape = + "{ desired_balance_amount?, desired_transaction_limit? }"; +export const linkBalanceSetupInputsSchema = z + .object({ + desired_balance_amount: z + .number() + .int() + .safe() + .min(100) + .multipleOf(100) + .optional(), + desired_transaction_limit: z + .number() + .int() + .safe() + .min(100) + .max(50000) + .multipleOf(100) + .optional(), + }) + .strict(); +export type LinkBalanceSetupInputs = z.infer< + typeof linkBalanceSetupInputsSchema +>; + // Names the offending top-level key, never a value or nested key, and shows the shape // the API accepts. function operationInputsIssueMessage( @@ -283,6 +308,14 @@ export function removePaymentMethodInputsIssueMessage(error: z.ZodError) { ); } +export function linkBalanceSetupInputsIssueMessage(error: z.ZodError) { + return operationInputsIssueMessage( + "link_balance_setup", + linkBalanceSetupInputsShape, + error, + ); +} + export const confirmTransactionInputsShape = "{ status, transaction_type, amount, currency, occurred_at, order_id?, order_url?, failure_code? }"; export const confirmTransactionInputsSchema = z