@receiz/mcp-server
Version:
MCP server for agents building and verifying Receiz proof-native applications through the canonical Receiz SDK rails.
297 lines • 21.2 kB
JavaScript
import { createHash } from "node:crypto";
import { createReceizV125LawfulActionTransport, ReceizLawfulDeliveryErrorV125, confirmReceizEdgeReserveSendV125, confirmReceizEdgeSettlementSendV125, createReceizPortableExecutionTransitionRecoveryV124, inspectReceizEdgeValueTransferPlanV125, planReceizEdgeReserveTransferV125, planReceizEdgeSettlementTransferV125, prepareReceizPortableExecutionTransitionCommitSetV124, receiveReceizEdgeReserveV125, receiveReceizEdgeSettlementV125, verifyReceizPortableExecutionTransitionSetV124, } from "@receiz/sdk";
import { admitReceizV124McpMaterial, persistReceizV124McpMaterial, resolveReceizV124McpMaterial, } from "./v124Operations.js";
const object = (properties, required = []) => ({ type: "object", additionalProperties: false, properties, required });
const text = (description) => ({ type: "string", description });
const nullableText = (description) => ({ anyOf: [{ type: "string" }, { type: "null" }], description });
const opaqueObject = (description) => ({ type: "object", additionalProperties: true, description });
const rail = (description) => ({ type: "string", enum: ["settlement", "reserve"], description });
const EDGE_PLAN_FIELDS = {
amountPhiMicro: text("Exact Phi micro-units moved; USD is never the moved authority."),
sourceProofObjectId: text("Exact sender proof-object identity."),
sourceValueHead: text("Exact sender value head."),
destinationSubjectId: text("Exact receiver subject identity."),
expectedDestinationHead: text("Exact receiver value head expected before the append."),
usdPerPhiMicrocents: text("Pinned deterministic display-price basis only."),
priceBasis: opaqueObject("Canonical deterministic display-price basis; never transfer authority."),
idempotencyKey: text("Optional stable semantic retry identity."),
attemptId: text("Exact edge attempt identity."),
};
export const RECEIZ_V125_MCP_TOOL_NAMES = Object.freeze([
"receiz_v125_lawful_action_law_register",
"receiz_v125_lawful_action_admit",
"receiz_v125_lawful_action_value_head_derive",
"receiz_v125_edge_value_plan_settlement",
"receiz_v125_edge_value_plan_reserve",
"receiz_v125_edge_value_plan_inspect",
"receiz_v125_edge_value_transition_set_verify",
"receiz_v125_edge_value_commit_set_prepare",
"receiz_v125_edge_value_recovery_create",
"receiz_v125_edge_value_settlement_send_confirm",
"receiz_v125_edge_value_settlement_receive",
"receiz_v125_edge_value_reserve_send_confirm",
"receiz_v125_edge_value_reserve_receive",
]);
const NO_SCOPES = Object.freeze([]);
export const RECEIZ_V125_MCP_REQUIRED_SCOPES = Object.freeze({
receiz_v125_lawful_action_law_register: Object.freeze(["receiz:lawful-actions.laws.write"]),
receiz_v125_lawful_action_admit: Object.freeze(["receiz:lawful-actions.write"]),
receiz_v125_lawful_action_value_head_derive: Object.freeze(["receiz:lawful-actions.value.write"]),
receiz_v125_edge_value_plan_settlement: NO_SCOPES,
receiz_v125_edge_value_plan_reserve: NO_SCOPES,
receiz_v125_edge_value_plan_inspect: NO_SCOPES,
receiz_v125_edge_value_transition_set_verify: NO_SCOPES,
receiz_v125_edge_value_commit_set_prepare: NO_SCOPES,
receiz_v125_edge_value_recovery_create: NO_SCOPES,
receiz_v125_edge_value_settlement_send_confirm: NO_SCOPES,
receiz_v125_edge_value_settlement_receive: NO_SCOPES,
receiz_v125_edge_value_reserve_send_confirm: NO_SCOPES,
receiz_v125_edge_value_reserve_receive: NO_SCOPES,
});
function inputSchema(name) {
if (name === "receiz_v125_lawful_action_value_head_derive") {
return object({ membershipId: text("Stable admitted membership digest."), expectedPriorValueHeadDigest: nullableText("Exact prior value head or null for genesis."), confirmation: text("Exact preview digest.") }, ["membershipId", "expectedPriorValueHeadDigest"]);
}
if (name === "receiz_v125_lawful_action_law_register" || name === "receiz_v125_lawful_action_admit") {
return object({
proofReference: text("Opaque trusted-host reference; never artifact bytes."),
lawDigest: text("Required current law digest for action admission."),
expectedPriorAdmissionDigest: nullableText("Exact prior admission head or null for genesis."),
idempotencyKey: text("Stable caller retry identity."),
confirmation: text("Exact preview digest."),
}, name === "receiz_v125_lawful_action_law_register" ? ["proofReference", "idempotencyKey"] : ["proofReference", "lawDigest", "expectedPriorAdmissionDigest", "idempotencyKey"]);
}
if (name === "receiz_v125_edge_value_plan_settlement" || name === "receiz_v125_edge_value_plan_reserve") {
return object(EDGE_PLAN_FIELDS, ["amountPhiMicro", "sourceProofObjectId", "sourceValueHead", "destinationSubjectId", "expectedDestinationHead", "usdPerPhiMicrocents", "priceBasis", "attemptId"]);
}
if (name === "receiz_v125_edge_value_plan_inspect") {
return object({ planRef: text("Opaque reference to the exact SDK-issued operation plan."), participantId: text("Exact sender or receiver participant identity."), expectedRail: rail("Exact named rail expected by this edge.") }, ["planRef", "participantId", "expectedRail"]);
}
if (name === "receiz_v125_edge_value_transition_set_verify")
return object({ transitionSetRef: text("Opaque reference to the complete portable transition set.") }, ["transitionSetRef"]);
if (name === "receiz_v125_edge_value_commit_set_prepare")
return object({ verifiedTransitionSetRef: text("Same-runtime reference returned only after canonical SDK verification.") }, ["verifiedTransitionSetRef"]);
if (name === "receiz_v125_edge_value_recovery_create")
return object({ transitionSetRef: text("Opaque reference to the exact portable transition set."), committedTransitionsRef: text("Same-runtime reference to SDK-issued committed sender/receiver transitions.") }, ["transitionSetRef", "committedTransitionsRef"]);
return object({ recoveryRef: text("Opaque reference to the complete canonical portable recovery."), participantId: text("Exact sender or receiver participant identity."), confirmation: text("Exact preview digest for this participant, rail, role, and recovery.") }, ["recoveryRef", "participantId"]);
}
function operationDescription(name) {
if (name.startsWith("receiz_v125_lawful_action_"))
return "Register, admit, or advance deterministic value for a v125 lawful action. Exact sealed bytes are resolved by the trusted host from an opaque reference and never enter model context. Admission reverifies the embedded portable execution-authority transition and derives every causal/completion claim from it. MCP is not authority; MCP and HTTP are mechanics beneath sealed proof authority.";
const action = name.includes("plan_") ? "plan or inspect" : name.includes("verify") ? "canonically verify" : name.includes("prepare") ? "prepare exact local commit mechanics for" : name.includes("recovery_create") ? "package already committed" : "independently confirm or receive";
return `Use the canonical SDK to ${action} one explicit v125 Settlement or Reserve transfer at the user edge. Opaque references preserve exact material outside model context. The server and database perform additive global sync only. MCP is not authority; references are never transaction or proof authority.`;
}
export const RECEIZ_V125_MCP_TOOLS = RECEIZ_V125_MCP_TOOL_NAMES.map((name) => ({ name, description: operationDescription(name), inputSchema: inputSchema(name), outputSchema: { type: "object", additionalProperties: true } }));
function canonical(value) {
if (value === null || typeof value === "string" || typeof value === "boolean" || typeof value === "number")
return JSON.stringify(value);
if (value instanceof Uint8Array)
return JSON.stringify(Buffer.from(value).toString("base64url"));
if (value instanceof ArrayBuffer)
return JSON.stringify(Buffer.from(value).toString("base64url"));
if (Array.isArray(value))
return `[${value.map(canonical).join(",")}]`;
if (value && typeof value === "object")
return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonical(value[key])}`).join(",")}}`;
return JSON.stringify(String(value));
}
function digest(value) { return createHash("sha256").update(canonical(value)).digest("hex"); }
function confirmationDigest(name, args) {
const basis = { ...args };
delete basis.confirmation;
return digest({ schema: "receiz.mcp.lawful-action-confirmation.v125", name, basis });
}
function lawfulActionPreview(name, args) {
const expected = confirmationDigest(name, args);
if (args.confirmation === undefined)
return { confirmationRequired: true, confirmationDigest: expected, writesPerformed: 0, secretMaterialReturned: false };
if (args.confirmation !== expected)
throw new TypeError("V125_MCP_CONFIRMATION_INVALID");
return null;
}
function edgeValuePreview(name, args, recovery) {
const expected = confirmationDigest(name, { ...args, recoveryDigest: digest(recovery) });
if (args.confirmation === undefined)
return {
confirmationRequired: true,
confirmationDigest: expected,
writesPerformed: 0,
secretMaterialReturned: false,
transactionOccursAtEdge: true,
serverRole: "global-sync-only",
authority: { confirmationIsAuthority: false, strongerTruth: "sealed-receiz-proof-object" },
};
if (args.confirmation !== expected)
throw new TypeError("V125_MCP_CONFIRMATION_INVALID");
return null;
}
function requiredText(value, code = "V125_MCP_INPUT_INVALID") {
if (typeof value !== "string" || value.length === 0 || value !== value.trim())
throw new TypeError(code);
return value;
}
function applicationId(options) { return requiredText(options.applicationId, "V125_MCP_APPLICATION_ID_REQUIRED"); }
function materialClient(options) {
if (!options.materialClient)
throw new TypeError("V125_MCP_MATERIAL_CLIENT_REQUIRED");
return options.materialClient;
}
function materialOptions(options) {
return { applicationId: applicationId(options), requirePinnedApplicationId: true, requireReferenceMaterials: true, resolveMaterial: options.resolveMaterial, persistMaterial: options.persistMaterial };
}
function record(value, code = "V125_MCP_RESULT_INVALID") {
if (!value || typeof value !== "object" || Array.isArray(value))
throw new TypeError(code);
return value;
}
function planProjection(value, planRef) {
const planned = record(value);
const intent = record(planned.intent);
const plan = record(planned.plan);
return {
schema: planned.schema, rail: planned.rail, planRef, sourceParticipantId: planned.sourceParticipantId,
destinationParticipantId: planned.destinationParticipantId, participants: planned.participants,
expectedParticipantHeads: planned.expectedParticipantHeads, exactPlanDigest: plan.exactPlanDigest,
semanticIdempotencyKey: plan.semanticIdempotencyKey, attemptId: plan.attemptId,
amountPhiMicro: intent.amountPhiMicro, valueIntentDigest: intent.valueIntentDigest,
priceBasisDigest: intent.priceBasisDigest, quotedUsdCents: intent.quotedUsdCents,
transactionOccursAtEdge: true, serverRole: "global-sync-only", databaseRole: "global-sync-only",
authority: { planRefIsAuthority: false, planIsTransactionAuthority: false, strongerTruth: "sealed-receiz-proof-object" },
};
}
function inspectionProjection(value, planRef) {
const inspection = record(value);
const intent = record(inspection.intent);
const plan = record(inspection.plan);
return {
schema: inspection.schema, rail: inspection.rail, role: inspection.role, participantId: inspection.participantId,
sourceParticipantId: inspection.sourceParticipantId, destinationParticipantId: inspection.destinationParticipantId,
planRef, exactPlanDigest: plan.exactPlanDigest, amountPhiMicro: intent.amountPhiMicro,
valueIntentDigest: intent.valueIntentDigest, localVerificationRequired: true,
authority: { inspectionIsTransactionAuthority: false, planRefIsAuthority: false, strongerTruth: "sealed-receiz-proof-object" },
};
}
function verifiedTransitionProjection(value, verifiedTransitionSetRef) {
const verified = record(value);
const plan = record(verified.operationPlan);
const members = Array.isArray(verified.members) ? verified.members.map((member) => {
const entry = record(member);
return { participantId: entry.participantId, priorHead: entry.priorHead, proposedHead: entry.proposedHead };
}) : [];
return { status: verified.status, verifiedTransitionSetRef, exactPlanDigest: plan.exactPlanDigest, expectedParticipantHeads: verified.expectedParticipantHeads, proposedParticipantHeads: verified.proposedParticipantHeads, members, authority: { verifiedTransitionSetRefIsAuthority: false, committed: false, strongerTruth: "sealed-receiz-proof-object" } };
}
function preparedCommitProjection(value, preparedCommitSetRef) {
const prepared = record(value);
const plan = record(prepared.operationPlan);
const members = Array.isArray(prepared.members) ? prepared.members.map((member) => {
const entry = record(member);
return { participantId: entry.participantId, acceptedHead: record(record(entry.expectedReceipt).acceptedHead).value };
}) : [];
return { schema: prepared.schema, preparedCommitSetRef, exactPlanDigest: plan.exactPlanDigest, members, authority: { preparedCommitSetRefIsAuthority: false, committed: false, strongerTruth: "sealed-receiz-proof-object" } };
}
function recoveryProjection(value, recoveryRef) {
const recovery = record(value);
const transitionSet = record(recovery.transitionSet);
const members = Array.isArray(recovery.members) ? recovery.members.map((member) => {
const entry = record(member);
return { participantId: entry.participantId, acceptedHead: record(record(entry.receipt).acceptedHead).value };
}) : [];
return { schema: recovery.schema, recoveryRef, exactPlanDigest: transitionSet.exactPlanDigest, members, transactionOccursAtEdge: true, serverRole: "global-sync-only", authority: { recoveryRefIsAuthority: false, strongerTruth: "sealed-receiz-proof-object" } };
}
function settledProjection(value, recoveryRef) {
const settled = record(value);
const intent = record(settled.intent);
const committed = record(settled.committedTransition);
const receipt = record(committed.receipt);
return {
status: settled.status, rail: settled.rail, role: settled.role, participantId: settled.participantId,
recoveryRef, amountPhiMicro: intent.amountPhiMicro, valueIntentDigest: intent.valueIntentDigest,
acceptance: committed.acceptance, artifactDigest: record(committed.artifactDigest).value,
acceptedHead: record(receipt.acceptedHead).value, transactionOccursAtEdge: true,
serverRole: "global-sync-only", databaseRole: "global-sync-only",
authority: { recoveryRefIsAuthority: false, projectionIsTransactionAuthority: false, strongerTruth: "sealed-receiz-proof-object" },
};
}
async function callLawfulAction(name, args, options) {
const pending = lawfulActionPreview(name, args);
if (pending)
return pending;
const client = createReceizV125LawfulActionTransport({ baseUrl: options.baseUrl, applicationId: options.applicationId,
getAccessToken: () => options.accessToken ?? "", fetch: options.fetch });
try {
if (name === "receiz_v125_lawful_action_value_head_derive")
return await client.deriveValueHead({ membershipId: requiredText(args.membershipId), expectedPriorValueHeadDigest: args.expectedPriorValueHeadDigest });
if (!options.resolveProofReference)
throw new TypeError("V125_MCP_TRUSTED_PROOF_HOST_REQUIRED");
const proofObject = await options.resolveProofReference(requiredText(args.proofReference));
if (name === "receiz_v125_lawful_action_law_register")
return await client.registerLaw({ proofObject, idempotencyKey: requiredText(args.idempotencyKey) });
return await client.admit({ lawDigest: requiredText(args.lawDigest), proofObject,
expectedPriorAdmissionDigest: args.expectedPriorAdmissionDigest, idempotencyKey: requiredText(args.idempotencyKey) });
}
catch (error) {
if (error instanceof ReceizLawfulDeliveryErrorV125)
return { ok: false,
code: error.message.replace("V125_LAWFUL_ACTION_HTTP_", "V125_MCP_HTTP_"), delivery: error.delivery };
throw error;
}
}
export async function callReceizV125McpOperation(name, args, options) {
if (!RECEIZ_V125_MCP_TOOL_NAMES.includes(name))
throw new TypeError("V125_MCP_TOOL_UNKNOWN");
const toolName = name;
if (toolName.startsWith("receiz_v125_lawful_action_"))
return callLawfulAction(toolName, args, options);
const client = materialClient(options);
const heldOptions = materialOptions(options);
const audience = applicationId(options);
if (toolName === "receiz_v125_edge_value_plan_settlement" || toolName === "receiz_v125_edge_value_plan_reserve") {
const planner = toolName.endsWith("settlement") ? planReceizEdgeSettlementTransferV125 : planReceizEdgeReserveTransferV125;
const planned = await planner({ ...args, applicationId: audience });
const planRef = await persistReceizV124McpMaterial(client, heldOptions, "operation-plan", planned.plan);
return planProjection(planned, planRef);
}
if (toolName === "receiz_v125_edge_value_plan_inspect") {
const planRef = requiredText(args.planRef);
const plan = await resolveReceizV124McpMaterial(client, heldOptions, planRef, "operation-plan");
const expectedRail = args.expectedRail === "settlement" ? "settlement" : args.expectedRail === "reserve" ? "reserve" : null;
if (!expectedRail)
throw new TypeError("V125_MCP_RAIL_INVALID");
const inspected = await inspectReceizEdgeValueTransferPlanV125(plan, { participantId: requiredText(args.participantId), expectedRail });
return inspectionProjection(inspected, planRef);
}
if (toolName === "receiz_v125_edge_value_transition_set_verify") {
const transitionSet = await resolveReceizV124McpMaterial(client, heldOptions, args.transitionSetRef, "portable-transition-set");
const verified = await verifyReceizPortableExecutionTransitionSetV124(transitionSet, { audience });
const verifiedTransitionSetRef = admitReceizV124McpMaterial(client, { applicationId: audience, kind: "verified-portable-transition-set", value: verified });
return verifiedTransitionProjection(verified, verifiedTransitionSetRef);
}
if (toolName === "receiz_v125_edge_value_commit_set_prepare") {
const verified = await resolveReceizV124McpMaterial(client, heldOptions, args.verifiedTransitionSetRef, "verified-portable-transition-set");
const prepared = await prepareReceizPortableExecutionTransitionCommitSetV124(verified);
const preparedCommitSetRef = admitReceizV124McpMaterial(client, { applicationId: audience, kind: "prepared-portable-transition-commit-set", value: prepared });
return preparedCommitProjection(prepared, preparedCommitSetRef);
}
if (toolName === "receiz_v125_edge_value_recovery_create") {
const transitionSet = await resolveReceizV124McpMaterial(client, heldOptions, args.transitionSetRef, "portable-transition-set");
const committedTransitions = await resolveReceizV124McpMaterial(client, heldOptions, args.committedTransitionsRef, "committed-artifact-transitions");
const recovery = await createReceizPortableExecutionTransitionRecoveryV124({ applicationId: audience, transitionSet, committedTransitions });
const recoveryRef = await persistReceizV124McpMaterial(client, heldOptions, "portable-transition-recovery", recovery);
return recoveryProjection(recovery, recoveryRef);
}
const recoveryRef = requiredText(args.recoveryRef);
const recovery = await resolveReceizV124McpMaterial(client, heldOptions, recoveryRef, "portable-transition-recovery");
const pending = edgeValuePreview(toolName, args, recovery);
if (pending)
return pending;
const input = { applicationId: audience, participantId: requiredText(args.participantId) };
const settled = toolName === "receiz_v125_edge_value_settlement_send_confirm"
? await confirmReceizEdgeSettlementSendV125(recovery, input)
: toolName === "receiz_v125_edge_value_settlement_receive"
? await receiveReceizEdgeSettlementV125(recovery, input)
: toolName === "receiz_v125_edge_value_reserve_send_confirm"
? await confirmReceizEdgeReserveSendV125(recovery, input)
: await receiveReceizEdgeReserveV125(recovery, input);
return settledProjection(settled, recoveryRef);
}
//# sourceMappingURL=v125Operations.js.map