UNPKG

@receiz/mcp-server

Version:

MCP server for agents building and verifying Receiz proof-native applications through the canonical Receiz SDK rails.

152 lines • 9.28 kB
import { canonicalizeReceizV122, planAtomicOperationV124, validateReceizOperationPlanV124, } from "@receiz/sdk"; /** Host execution scope, beneath existing proof admission. Does not filter discovery. */ export const RECEIZ_MARKETPLACE_EXECUTION_PROFILE = "marketplace-phi"; /** Exact dispatch bindings, not keyword classification. Historical routes have no * current implementation: their arbitrary JSON commerce contracts cannot prove * Phi execution merely because the caller supplies currency: "phi". * Evidence: SDK index.ts commerce/jobs; oneClickCheckout; twinTrading.server.ts * createTwinMarketIntentForSession/approveTwinMarketIntentForSession. */ export const RECEIZ_MARKETPLACE_RESTRICTED_OPERATIONS = Object.freeze({ receiz_commerce_one_click_checkout: "commerce.oneClickCheckout", receiz_commerce_refunds_create: "commerce.refunds.create", receiz_commerce_subscriptions_create: "commerce.subscriptions.create", receiz_commerce_gift_cards_issue: "commerce.giftCards.issue", receiz_commerce_gift_cards_redeem: "commerce.giftCards.redeem", receiz_commerce_payouts_create: "commerce.payouts.create", receiz_commerce_discounts_redeem: "commerce.discounts.redeem", receiz_twin_create_market_intent: "twin.createMarketIntent", receiz_twin_approve_market_intent: "twin.approveMarketIntent", receiz_jobs_enqueue: "jobs.enqueue", }); export class ReceizMarketplaceExecutionError extends Error { operation; reason; code = "receiz_marketplace_execution_restricted"; constructor(operation, reason) { super(`${operation}: ${reason}`); this.operation = operation; this.reason = reason; this.name = "ReceizMarketplaceExecutionError"; } } const fail = (operation, reason) => { throw new ReceizMarketplaceExecutionError(operation, reason); }; const record = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : {}; function assertPausedMandate(input) { // Omission preserves the existing status; it may already be active. Only an // explicit pause is independent of that unknown state. No mutation of input. if (record(input).status !== "paused") fail("twin.saveMarketMandate", "Only an explicit pause is enabled; this mandate otherwise enables USD-denominated market execution."); } /** Invoke before MCP dispatch, including the standalone v127 SDK dispatcher. * Ordinary inspection, local simulations, sealed proof, identity, world, * ownership and canonical Phi Settlement/Reserve operations remain available. */ export function assertReceizMarketplaceToolCall(name, args = {}) { if (Object.hasOwn(RECEIZ_MARKETPLACE_RESTRICTED_OPERATIONS, name)) { fail(name, "This dispatch is outside proof-native Phi value execution; inspection and canonical Phi rails remain available."); } if (name === "receiz_twin_save_market_mandate") assertPausedMandate(record(args).body); if (name === "receiz_v125_external_execution_execute") { // v125TrustExternal.ts delivers an opaque request to configuration.provider; // proof admission establishes provenance, not the provider's value unit. fail(name, "The external provider has no closed Phi-only effect contract."); } if ((name === "receiz_mcp_execute_command" || name === "receiz_mcp_verify_receipt") && record(args).confirmation !== undefined) { // Both tools reach the host's constitutionalExecutor after confirmation. fail(name, "The custom constitutional executor has no closed Phi-only effect contract; planning remains available."); } } /** Reuse the existing atomic planner to validate the exact platform operation. * This is execution scope, never proof admission or a replacement verifier. * Custom reducers are not classified from their names or untrusted payloads. */ export async function assertReceizMarketplaceAtomicPlan(value) { const plan = await validateReceizOperationPlanV124(value); if (plan.operationKind !== "receiz.atomic-operation.v124") fail("execution.stage", "An exact canonical platform atomic plan is required."); const payload = record(JSON.parse(Buffer.from(plan.exactPlanBytesB64u, "base64url").toString("utf8"))); if (payload.schema !== "receiz.atomic-operation.v124" || !Array.isArray(payload.operations)) fail("execution.stage", "An exact canonical platform atomic plan is required."); // Categories and their canonical bindings are implemented by registeredPayload // in SDK v124Execution.ts. Settlement/reserve validate amountPhiMicro; world // composites validate their embedded value intents through the same primitive. if (payload.operations.some(operation => record(operation).category === "custom")) fail("execution.stage", "Custom reducer effects have no closed Phi-only effect contract."); const replanned = await planAtomicOperationV124({ applicationId: payload.applicationId, operations: payload.operations, participants: payload.participants, expectedParticipantHeads: payload.expectedParticipantHeads, semanticIdempotencyKey: payload.semanticIdempotencyKey, attemptId: payload.attemptId, }); if (canonicalizeReceizV122(replanned) !== canonicalizeReceizV122(plan)) fail("execution.stage", "Plan envelope does not match its canonical operation."); } /** Wrap the exact SDK methods used by dispatch. Scope is retained in closures; * caller arguments cannot disable it. Unrelated methods keep their receiver. * This is not a sandbox for arbitrary code holding the original SDK client. */ export function wrapReceizMarketplaceClient(client) { const denied = new Set(Object.values(RECEIZ_MARKETPLACE_RESTRICTED_OPERATIONS)); // These aliases are not currently MCP catalog tools, but are public SDK paths // to the same USD/card dispatches. They cannot bypass the wrapped host client. for (const path of ["connect.transfer", "connect.checkout", "payments.embeddedCheckout", "oneClickCheckout", "connectTransfer"]) denied.add(path); const staged = new WeakMap(); const proxies = new Map(); const branch = (source, prefix) => { const existing = proxies.get(prefix); if (existing) return existing; // Empty target avoids violating proxy invariants for frozen SDK subobjects. const proxy = new Proxy({}, { has: (_target, key) => key in source, ownKeys: () => Reflect.ownKeys(source), getOwnPropertyDescriptor: (_target, key) => key in source ? { configurable: true, enumerable: true } : undefined, get: (_target, key) => { const value = Reflect.get(source, key, source); if (typeof key !== "string") return typeof value === "function" ? value.bind(source) : value; const path = prefix ? `${prefix}.${key}` : key; if (typeof value === "function") { if (denied.has(path)) return () => fail(path, "This SDK dispatch is outside proof-native Phi value execution."); if (path === "twin.saveMarketMandate") return (...args) => { assertPausedMandate(args[0]); return value.apply(source, args); }; if (path === "execution.stage" || path === "execution.stagePrepared") return async (...args) => { // Pin before awaiting: caller mutation cannot swap the checked plan. const plan = structuredClone(args[0]); await assertReceizMarketplaceAtomicPlan(plan); const handle = await value.apply(source, [plan, ...args.slice(1)]); if (handle !== null && typeof handle === "object") staged.set(handle, canonicalizeReceizV122(handle)); return handle; }; if (path === "execution.execute") return (...args) => { const handle = args[0]; if (handle === null || typeof handle !== "object" || !staged.has(handle) || staged.get(handle) !== canonicalizeReceizV122(handle)) fail(path, "A handle staged under this marketplace execution scope is required."); return value.apply(source, args); }; return value.bind(source); } if (value !== null && typeof value === "object" && ["commerce", "commerce.refunds", "commerce.subscriptions", "commerce.giftCards", "commerce.payouts", "commerce.discounts", "twin", "jobs", "connect", "payments", "execution"].includes(path)) return branch(value, path); return value; }, set: () => false, defineProperty: () => false, deleteProperty: () => false, }); proxies.set(prefix, proxy); return proxy; }; return branch(client, ""); } //# sourceMappingURL=marketplaceExecutionPolicy.js.map