/** * MCP (streamable HTTP, JSON-RPC 2.0) for AllowLatch. * Methods: initialize, notifications/initialized, ping, tools/list, tools/call. * Tools come from MCP_TOOLS in agent-docs.ts, the same list /.well-known/mcp.json serves. * Every tool result carries current_step and next_actions. */ import { demoSellerFor, runGuardDemo } from './guard-demo.js' import { describeWindow, openPaymentWindow, PAYMENT_WINDOW_EXPIRED_REASON, windowClosed } from './payment-window.js' import { catalogListPayload, catalogRecommendPayload, catalogServicePayload } from './catalog-handlers.js' import { SCORING_METHOD_VERSION, SCORING_WEIGHTS, verifyDecisionRecord, type DecisionRecord } from './decision-record.js' import { MCP_PROTOCOL_VERSION, MCP_TOOLS, MCP_TOOL_NAMES, RETIRED_TOOLS, SERVER_INSTRUCTIONS, SERVER_NAME, SERVER_VERSION } from './agent-docs.js' import { procureFromCatalog } from './kite-procure.js' import { latchEd25519PublicKeyHex, procureSignedMessage, verifyProcureProof, type ProcureProof } from './latch-receipt.js' import { DEMO_WALLET_NOTE, handleConnectPassport, handleDisconnectPassport, passportNextActions, passportStatusBlock, passportStatusPayload, peekPassport } from './passport.js' import { handleGuardPolicy, handleGuardReport } from '../guard/hosted.js' import { checkSellerTool } from '../guard/check-mcp.js' import { ratingQueryError, sellerRatings } from '../guard/seller-rating.js' import { previewDenied, UNLOCK_HEADER } from '../auth/preview-lock.js' import { handleEscrowAccept, handleEscrowStatus, handleEscrowTerms, handleEscrowVerdict } from './escrow-handlers.js' export { MCP_PROTOCOL_VERSION } /** Kept for older imports: the live tool list. */ export const MCP_JSONRPC_TOOLS = MCP_TOOLS export type JsonRpcRequest = { jsonrpc?: string id?: string | number | null method?: string params?: Record } type Out = { status: number; json: unknown; headers?: Record } function rpcResult(id: unknown, payload: Record, isError = false): Out { return { status: 200, json: { jsonrpc: '2.0', id, result: { content: [{ type: 'text', text: JSON.stringify(payload, null, 2) }], structuredContent: payload, isError, }, }, } } function rpcError(id: unknown, code: number, message: string, data?: Record): Out { return { status: 200, json: { jsonrpc: '2.0', id, error: { code, message, ...(data ? { data } : {}) } } } } /** Adds the Passport block to free reads so the first answer tells the agent whether it can buy. */ async function withPassport(payload: Record, token: unknown): Promise> { const passport = await peekPassport(token) if (passport.connected) return { ...payload, passport } const next = Array.isArray(payload.next_actions) ? (payload.next_actions as unknown[]) : [] return { ...payload, passport, next_actions: [ ...next, passport.status === 'passport_pending_approval' ? { action: 'finish_passport_approval', tool: 'get_passport_status', arguments: { passportToken: token }, why: 'Your user still has to approve the Kite spending session (once, with Face ID / Touch ID). Real purchases stay off until then.' } : { action: 'connect_passport_before_buying', tool: 'connect_passport', why: 'Searching is free. To buy for real, ask your user for their Kite Passport email and two limits (per purchase, per month) and call connect_passport. Or try a purchase with demo: true.' }, ], } } function num(v: unknown): number | undefined { return typeof v === 'number' && Number.isFinite(v) ? v : typeof v === 'string' && /^\d+(\.\d+)?$/.test(v) ? Number(v) : undefined } function str(v: unknown): string | undefined { return typeof v === 'string' && v.trim() ? v.trim() : undefined } /** * procure_paid_api with `scenario`: one demo purchase through the real guard against AllowLatch's own test sellers. * Accepts the test seller names (clean, swapped, poisoned, overpriced, mismatch, malformed) and the older scenario names. * The payment is simulated; no money moves. */ export async function demoScenarioPurchase(args: Record) { const seller = demoSellerFor(args.scenario) ?? 'clean' const next_actions = [ { step: 1, action: 'connect_passport', tool: 'connect_passport', why: 'Start here for real purchases: your user’s Kite Passport email and two limits (per purchase, per month).' }, { step: 2, action: 'check_seller', tool: 'check_seller', why: 'Check a real seller before paying it ($0.01 per check).' }, ] if (args.validBefore !== undefined || args.maxTimeoutSeconds !== undefined) { const window = openPaymentWindow({ validBefore: typeof args.validBefore === 'number' || typeof args.validBefore === 'string' ? args.validBefore : undefined, maxTimeoutSeconds: typeof args.maxTimeoutSeconds === 'number' ? args.maxTimeoutSeconds : undefined, }) if (windowClosed(window)) { return { tool: 'procure_paid_api', ok: true, demo: true, scenario: seller, wallet: { kind: 'demo', note: DEMO_WALLET_NOTE }, outcome: 'blocked_before_pay', current_step: 'payment_window_expired', message: `Demo on AllowLatch’s own test seller “${seller}” (simulated, no real money). Not paid: ${PAYMENT_WINDOW_EXPIRED_REASON}`, paymentWindow: describeWindow(window), payment: null, chargedUsd: 0, next_actions, } } } const run = await runGuardDemo(seller) return { ...run, tool: 'procure_paid_api', scenario: seller, wallet: { kind: 'demo', note: DEMO_WALLET_NOTE }, current_step: run.outcome === 'delivered' ? 'checked_and_delivered' : run.outcome, message: `Demo on AllowLatch’s own test seller “${seller}” (simulated, no real money). ${run.headline}`, chargedUsd: 0, next_actions, } } async function callTool(name: string, args: Record, requestHeaders?: Record): Promise<{ payload: Record; isError: boolean }> { const asPayload = (r: { status: number; json: unknown }) => ({ payload: r.json as Record, isError: r.status >= 400 }) const token = args.passportToken switch (name) { case 'list_kite_services': { const r = await catalogListPayload(args) return { payload: await withPassport(r.json as Record, token), isError: r.status >= 400 } } case 'get_kite_service': { const r = await catalogServicePayload(args) return { payload: await withPassport(r.json as Record, token), isError: r.status >= 400 } } case 'connect_passport': return asPayload(await handleConnectPassport(args)) case 'disconnect_passport': return asPayload(await handleDisconnectPassport({ passportToken: str(args.passportToken), disconnect: true })) case 'get_passport_status': return asPayload(await passportStatusPayload(str(args.passportToken))) case 'procure_paid_api': { if (args.scenario !== undefined && !str(args.serviceId) && !str(args.endpointId)) { return { payload: await demoScenarioPurchase(args), isError: false } } return asPayload( await procureFromCatalog({ task: str(args.task), serviceId: str(args.serviceId), endpointId: str(args.endpointId), endpointUrl: str(args.url), priceLimitUsd: num(args.priceLimitUsd), priceUsd: num(args.priceUsd), sellerResponse: typeof args.sellerResponse === 'string' ? args.sellerResponse : undefined, requiredFields: Array.isArray(args.requiredFields) ? args.requiredFields.map(String) : undefined, excludeServiceIds: Array.isArray(args.excludeServiceIds) ? args.excludeServiceIds.map(String) : undefined, monthlySpentUsd: num(args.monthlySpentUsd), passportToken: str(args.passportToken), demo: args.demo === true, pay: args.pay === true, requestBody: args.requestBody, idempotencyKey: str(args.idempotencyKey), explain: args.explain === true, maxTimeoutSeconds: num(args.maxTimeoutSeconds), validBefore: typeof args.validBefore === 'number' || typeof args.validBefore === 'string' ? args.validBefore : undefined, }) ) } case 'explain_provider_choice': { if (args.decisionRecord && typeof args.decisionRecord === 'object') { const record = args.decisionRecord as DecisionRecord const verification = Array.isArray(record.candidates) && record.inputs ? verifyDecisionRecord(record) : null return { payload: { ok: Boolean(verification?.ok), tool: 'explain_provider_choice', current_step: 'decision_record_verified', methodVersion: SCORING_METHOD_VERSION, weights: SCORING_WEIGHTS, verification, message: !verification ? 'decisionRecord must be a full record (procure_paid_api with explain: true).' : verification.ok ? 'Scores, ranks and hashes recomputed from the published inputs and weights match this record.' : 'Recomputed values do not match this record.', next_actions: [{ action: 'search_catalog', tool: 'list_kite_services', why: 'Find a service to buy.' }], }, isError: !verification?.ok, } } return asPayload(await catalogRecommendPayload(args)) } case 'verify_receipt_signature': { const proof = args as unknown as ProcureProof if (!proof.receipt || typeof proof.receipt !== 'object' || !proof.ed25519) { return { payload: { ok: false, error: 'invalid_arguments', message: 'receipt and ed25519 are required.', hint: 'Pass receipt, ed25519, stamp, mermaidHash and responseBodySha256 exactly as procure_paid_api returned them.', current_step: 'validation_failed_before_payment', chargedUsd: 0, next_actions: [{ action: 'buy_first', tool: 'procure_paid_api', why: 'Receipts come from purchases.' }], }, isError: true, } } const checks = verifyProcureProof(proof) const allOk = Object.values(checks).every(Boolean) return { payload: { ok: allOk, verified: allOk, current_step: allOk ? 'receipt_verified' : 'receipt_tampered', tamperDetected: !allOk, message: allOk ? 'Signature valid and response hash matches.' : 'Signature or response hash does not match: do not trust this receipt.', checks, ed25519PublicKey: latchEd25519PublicKeyHex(), signedMessage: proof.receipt?.id ? procureSignedMessage({ id: proof.receipt.id, stamp: proof.stamp, mermaidHash: proof.mermaidHash, responseBodySha256: proof.responseBodySha256, decisionRecordHash: proof.receipt.decisionRecordHash, }) : null, next_actions: [{ action: 'done', why: allOk ? 'Keep the receipt with the purchase.' : 'Tell your user the receipt failed verification.' }], }, isError: !allOk, } } case 'check_seller': return checkSellerTool(args) case 'get_seller_rating': { // Unlocked by the previewUnlock argument, or by the same unlock header or cookie the HTTP request already carries. const viaArg = str(args.previewUnlock) if (previewDenied(viaArg ? { [UNLOCK_HEADER]: viaArg } : { ...(requestHeaders ?? {}) })) { return { payload: { ok: false, error: 'preview_locked', message: `The seller rating is in private preview. Pass previewUnlock: the unlock value the site sets in its cookie after the preview password is entered (the same value the ${UNLOCK_HEADER} header takes). Calling /mcp with that header or cookie works too.`, chargedUsd: 0, }, isError: true, } } const lim = Number(args.limit) const query = { url: str(args.url), host: str(args.host), provider: str(args.provider), grade: str(args.grade), limit: Number.isFinite(lim) ? lim : 20 } const bad = ratingQueryError(query) if (bad) return { payload: { ...bad, chargedUsd: 0 }, isError: true } const r = await sellerRatings(query) return { payload: { ...r, chargedUsd: 0, next_actions: [{ action: 'check_seller', tool: 'check_seller', why: 'Ratings are history; check the live 402 before paying.' }] }, isError: false } } case 'get_spend_report': return asPayload(await handleGuardReport({ passportToken: args.passportToken })) case 'set_guard_policy': // Over MCP an agent can only tighten: no admin token is ever taken from tool arguments. return asPayload(await handleGuardPolicy({ passportToken: args.passportToken, policy: args.policy }, null)) case 'escrow_terms': return asPayload(await handleEscrowTerms(args)) case 'escrow_verdict': return asPayload(await handleEscrowVerdict(args)) case 'escrow_accept': return asPayload(await handleEscrowAccept(args)) case 'escrow_status': return asPayload(await handleEscrowStatus({ dealId: str(args.dealId) })) default: throw new Error(`unreachable tool ${name}`) } } export async function handleMcpJsonRpc(body: unknown, _origin = 'https://allowlatch.vercel.app', requestHeaders?: Record): Promise { const req = (body ?? {}) as JsonRpcRequest const id = req.id !== undefined ? req.id : 1 const method = typeof req.method === 'string' ? req.method.trim() : '' if (!method) { return { status: 400, json: { jsonrpc: '2.0', id, error: { code: -32600, message: 'Invalid JSON-RPC 2.0 request: missing "method". Supported methods: initialize, ping, tools/list, tools/call.', data: { hint: 'Start with {"jsonrpc":"2.0","id":1,"method":"tools/list"}.' } }, }, } } if (method === 'initialize') { return { status: 200, headers: { 'x-mcp-protocol-version': MCP_PROTOCOL_VERSION }, json: { jsonrpc: '2.0', id, result: { protocolVersion: MCP_PROTOCOL_VERSION, capabilities: { tools: { listChanged: false } }, serverInfo: { name: SERVER_NAME, title: 'AllowLatch', version: SERVER_VERSION }, instructions: `${SERVER_INSTRUCTIONS} Kite Passport: not connected for this session until you call connect_passport (status passport_not_connected).`, _meta: { current_step: 'connected', passport: passportStatusBlock(null), next_actions: [ ...passportNextActions().slice(0, 3).map((a, i) => ({ ...a, step: i + 1 })), { step: 4, action: 'check_seller', tool: 'check_seller', why: 'Start here before any payment: check the seller’s live 402 ($0.01 per check).' }, ], }, }, }, } } if (method === 'notifications/initialized' || method === 'ping') { return { status: 200, json: { jsonrpc: '2.0', id, result: {} } } } if (method === 'tools/list') { return { status: 200, json: { jsonrpc: '2.0', id, result: { tools: MCP_TOOLS } } } } if (method === 'tools/call') { const params = (req.params ?? {}) as { name?: string; arguments?: Record } const toolName = typeof params.name === 'string' ? params.name.trim() : '' const args = (params.arguments && typeof params.arguments === 'object' ? params.arguments : {}) as Record if (!MCP_TOOL_NAMES.includes(toolName)) { const replacement = RETIRED_TOOLS[toolName] return rpcError(id, -32601, `Unknown tool "${toolName}".`, { hint: replacement ? `${toolName} was replaced by ${replacement}.` : `Available tools: ${MCP_TOOL_NAMES.join(', ')}.`, next_actions: [{ action: 'list_tools', method: 'tools/list', why: 'See the current tools.' }, { action: 'start_here', tool: replacement ?? 'connect_passport', why: 'Start with connect_passport, then check_seller before paying.' }], }) } try { const { payload, isError } = await callTool(toolName, args, requestHeaders) return rpcResult(id, { tool: toolName, ...payload }, isError) } catch (err) { return rpcResult( id, { ok: false, tool: toolName, error: 'internal_error', message: err instanceof Error ? err.message : String(err), hint: 'Nothing was charged. Retry once; if it keeps failing, search the catalog again.', current_step: 'validation_failed_before_payment', chargedUsd: 0, next_actions: [{ action: 'retry', tool: toolName, why: 'Temporary errors usually clear.' }, { action: 'search_catalog', tool: 'list_kite_services', why: 'Start over.' }], }, true ) } } return rpcError(id, -32601, `Method not found: "${method}".`, { hint: 'Supported methods: initialize, ping, tools/list, tools/call.', next_actions: [{ action: 'list_tools', method: 'tools/list', why: 'See the tools.' }], }) }