@receiz/mcp-server
Version:
MCP server for agents building and verifying Receiz proof-native applications through the canonical Receiz SDK rails.
205 lines • 13.7 kB
JavaScript
import { createHash } from "node:crypto";
import { readFile } from "node:fs/promises";
import { basename } from "node:path";
import { RECEIZ_CURRENT_REGISTRY_DIGEST, admitReceizKksV1ProofCoordinate, appendReceizCarriedProofHistoryHeadV114, appendReceizCompositeMerkleLeaf, createEmptyReceizCompositeMerkleState, createReceizCarriedProofHistoryHeadV114, createReceizProofHistoryNode, digestReceizCompositeCanonical, parseReceizCarriedProofHistoryHeadV114, verifyReceizArtifact, } from "@receiz/sdk";
import { createReceizNodeOfflineKaiProofFactory } from "@receiz/sdk/offline/kai/node";
import { createReceizDeviceMaterialHost } from "./deviceMaterialHost.js";
import { sealReceizSourceBytes } from "./offlineSealing.js";
import { RECEIZ_SEALED_OUTPUT_URI } from "./sealedArtifactOutput.js";
export const RECEIZ_OFFLINE_CRYSTAL_TOOLS = [
{ name: "receiz_offline_crystal_append", description: "MCP is not authority. Verify an exact device-held sealed source and optional complete predecessor Crystal, then append under the same verified seal signer with a local KKS coordinate. Seal and retain a complete source-carrying successor before reporting success.",
inputSchema: { type: "object", properties: { sourceReference: { type: "string" }, predecessorReference: { type: "string" } },
required: ["sourceReference"], additionalProperties: false },
outputSchema: { type: "object", properties: { artifactReference: { type: "string" }, artifactSha256: { type: "string" },
suggestedFilename: { type: "string" }, mimeType: { type: "string" }, byteLength: { type: "integer" } },
required: ["artifactReference", "artifactSha256", "suggestedFilename", "mimeType", "byteLength"] },
_meta: { ui: { resourceUri: RECEIZ_SEALED_OUTPUT_URI }, "openai/outputTemplate": RECEIZ_SEALED_OUTPUT_URI } },
{ name: "receiz_offline_crystal_open", description: "MCP is not authority. Reopen and verify every enclosing proof object, carried source and predecessor of an exact device-held intelligence Memory Crystal; return a bounded source and history projection only.",
inputSchema: { type: "object", properties: { crystalReference: { type: "string" } }, required: ["crystalReference"], additionalProperties: false } },
];
const SCHEMA = "receiz.intelligence.memory-crystal.v1";
const AUTHORITY = "requires-enclosing-sealed-artifact";
const hex = (bytes) => createHash("sha256").update(bytes).digest("hex");
const base64 = (bytes) => Buffer.from(bytes).toString("base64");
function decode(value) {
if (typeof value !== "string" || !value || !/^[A-Za-z0-9+/]*={0,2}$/.test(value))
throw Error("crystal_carried_bytes_invalid");
const bytes = Buffer.from(value, "base64");
if (bytes.toString("base64") !== value)
throw Error("crystal_carried_bytes_invalid");
return bytes;
}
async function verified(bytes, filename) {
const result = await verifyReceizArtifact(new File([new Uint8Array(bytes)], filename));
if (result.status !== "verified-artifact")
throw Error("crystal_enclosing_proof_required");
const bundle = result.verification.bundle;
const signer = bundle.signatureV4?.cert?.subjectPublicKeyRawB64u;
const kaiPulse = bundle.kaiPulseEternal;
if (typeof signer !== "string" || !signer || typeof kaiPulse !== "string" || !/^(0|[1-9][0-9]*)$/.test(kaiPulse))
throw Error("crystal_proof_coordinates_missing");
return { artifactSha256: result.artifactDigest.value, signer, kaiPulse };
}
function bodyFrom(bytes) {
let raw;
try {
raw = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
}
catch {
throw Error("crystal_body_invalid");
}
if (!raw || typeof raw !== "object" || Array.isArray(raw))
throw Error("crystal_body_invalid");
const body = raw;
if (body.schema !== SCHEMA || body.authority !== AUTHORITY || body.appendPolicy !== "same-verified-seal-signer"
|| typeof body.artifactId !== "string" || !body.source
|| typeof body.source.filename !== "string" || !body.source.filename
|| typeof body.source.artifactSha256 !== "string" || !/^[a-f0-9]{64}$/.test(body.source.artifactSha256)
|| !body.history || !body.appendCoordinate
|| (body.predecessor !== null && (!body.predecessor || typeof body.predecessor.artifactSha256 !== "string"
|| typeof body.predecessor.filename !== "string" || !body.predecessor.filename)))
throw Error("crystal_body_invalid");
return body;
}
async function project(body, sourceKaiPulse, previous) {
const coordinate = await admitReceizKksV1ProofCoordinate(body.appendCoordinate, {
expectedPreviousKaiSigilProofHead: previous?.body.appendCoordinate.kaiSigil.proofHead ?? null,
...(previous ? { minimumExclusiveKaiUpulse: previous.body.appendCoordinate.kaiUpulse } : {}),
});
if (BigInt(coordinate.kaiPulse) < BigInt(sourceKaiPulse)
|| (previous && BigInt(coordinate.kaiPulse) < BigInt(previous.kaiPulse)))
throw Error("crystal_kai_regression");
const artifactId = previous?.body.artifactId ?? `receiz.intelligence.memory:${body.source.artifactSha256}`;
if (body.artifactId !== artifactId)
throw Error("crystal_identity_changed");
const priorHistory = previous ? await parseReceizCarriedProofHistoryHeadV114(previous.body.history) : null;
const node = await createReceizProofHistoryNode({ artifactId, registryDigest: RECEIZ_CURRENT_REGISTRY_DIGEST,
parentDigests: priorHistory ? [priorHistory.headDigest] : [], kaiPulse: coordinate.kaiPulse,
receipt: { kind: "receiz.intelligence.sealed-source-reference.v1", artifactSha256: body.source.artifactSha256 },
event: { type: "state.append", state: { artifactSha256: body.source.artifactSha256 } },
namespaceData: { "receiz.kks-v1": coordinate },
});
return priorHistory && previous
? appendReceizCarriedProofHistoryHeadV114({ predecessor: priorHistory,
predecessorArtifactDigest: previous.artifactSha256, appendNode: node })
: createReceizCarriedProofHistoryHeadV114({ artifactId, registryDigest: RECEIZ_CURRENT_REGISTRY_DIGEST,
rootDigest: node.nodeDigest, headDigest: node.nodeDigest, nodeCount: 1,
accumulator: appendReceizCompositeMerkleLeaf(createEmptyReceizCompositeMerkleState(), node.nodeDigest),
currentNode: node, parentRefs: [] });
}
/** Open the complete carried chain, verifying every enclosing source and
* predecessor before exposing a projection. No DB, server or model summary. */
async function inspectReceizOfflineCrystal(bytes, filename) {
const chain = [];
let nextBytes = bytes, nextFilename = filename;
const seen = new Set();
for (;;) {
const proof = await verified(nextBytes, nextFilename);
if (seen.has(proof.artifactSha256))
throw Error("crystal_history_cycle");
seen.add(proof.artifactSha256);
const body = bodyFrom(nextBytes);
chain.push({ bytes: nextBytes, filename: nextFilename, body, proof });
if (!body.predecessor)
break;
nextBytes = decode(body.predecessor.artifactBase64);
if (hex(nextBytes) !== body.predecessor.artifactSha256)
throw Error("crystal_predecessor_changed");
nextFilename = body.predecessor.filename;
}
let previous = null;
const sources = [];
const heldSources = [];
const sourceDigests = new Set();
for (const item of chain.reverse()) {
const { body, proof } = item;
if (previous && previous.signer !== proof.signer)
throw Error("crystal_signer_mismatch");
if ((previous === null) !== (body.predecessor === null)
|| (previous && body.predecessor?.artifactSha256 !== previous.artifactSha256))
throw Error("crystal_predecessor_mismatch");
const sourceBytes = decode(body.source.artifactBase64);
if (hex(sourceBytes) !== body.source.artifactSha256)
throw Error("crystal_source_changed");
const source = await verified(sourceBytes, body.source.filename);
if (source.artifactSha256 !== body.source.artifactSha256)
throw Error("crystal_source_changed");
if (sourceDigests.has(source.artifactSha256))
throw Error("crystal_source_already_appended");
sourceDigests.add(source.artifactSha256);
const expected = await project(body, source.kaiPulse, previous);
if (BigInt(proof.kaiPulse) < BigInt(body.appendCoordinate.kaiPulse))
throw Error("crystal_seal_precedes_append");
if (digestReceizCompositeCanonical(expected) !== digestReceizCompositeCanonical(body.history))
throw Error("crystal_history_mismatch");
previous = { body, artifactSha256: proof.artifactSha256, signer: proof.signer, kaiPulse: proof.kaiPulse };
sources.push({ artifactSha256: source.artifactSha256, filename: body.source.filename });
heldSources.push({ artifactSha256: source.artifactSha256, filename: body.source.filename, exactBytes: sourceBytes });
}
if (!previous)
throw Error("crystal_body_invalid");
return { verified: true, artifactId: previous.body.artifactId, artifactSha256: previous.artifactSha256,
headDigest: previous.body.history.headDigest, nodeCount: previous.body.history.nodeCount,
sources, heldSources, signer: previous.signer, mcpAuthority: false, strongerTruth: "sealed-receiz-proof-object" };
}
/** Safe MCP projection; no carried source bytes enter model output. */
export async function openReceizOfflineCrystal(bytes, filename) {
const { heldSources: _heldSources, ...projection } = await inspectReceizOfflineCrystal(bytes, filename);
return projection;
}
/** Trusted-host integration seam for any intelligence runtime. Only exact
* enclosing-proof-verified sources are returned, never an MCP response. */
export async function readVerifiedReceizOfflineCrystalSources(bytes, filename) {
const opened = await inspectReceizOfflineCrystal(bytes, filename);
return { artifactId: opened.artifactId, artifactSha256: opened.artifactSha256,
headDigest: opened.headDigest, sources: opened.heldSources.map(source => ({ ...source, exactBytes: source.exactBytes.slice() })) };
}
let kaiFactory;
export async function appendReceizOfflineCrystal(input, options) {
if (!input || typeof input.sourceReference !== "string" || !input.sourceReference
|| (input.predecessorReference !== undefined && (typeof input.predecessorReference !== "string" || !input.predecessorReference)))
throw Error("crystal_arguments_invalid");
if (!options.identityAdmitted && !options.identity && !process.env.RECEIZ_SUBJECT_IDENTITY_PATH)
throw Error("crystal_identity_custody_required");
const host = createReceizDeviceMaterialHost(options.workspace);
const source = await host.resolveProofReference(input.sourceReference);
const sourceProof = await verified(source.exactBytes, source.filename);
let previous = null, predecessorBytes = null, predecessorFilename = null;
if (input.predecessorReference) {
const held = await host.resolveProofReference(input.predecessorReference);
predecessorBytes = held.exactBytes;
predecessorFilename = held.filename;
const prior = await openReceizOfflineCrystal(predecessorBytes, held.filename);
const proof = await verified(predecessorBytes, held.filename);
previous = { body: bodyFrom(predecessorBytes), ...proof };
const priorSourceDigests = prior.sources.map(item => item.artifactSha256);
if (priorSourceDigests.includes(sourceProof.artifactSha256))
throw Error("crystal_source_already_appended");
}
const create = await (kaiFactory ??= createReceizNodeOfflineKaiProofFactory());
const coordinate = await create({ previousKaiSigilProofHead: previous?.body.appendCoordinate.kaiSigil.proofHead ?? null });
const body = {
...(previous?.body ?? {}),
schema: SCHEMA, authority: AUTHORITY, appendPolicy: "same-verified-seal-signer",
artifactId: previous?.body.artifactId ?? `receiz.intelligence.memory:${sourceProof.artifactSha256}`,
source: { artifactSha256: sourceProof.artifactSha256, filename: source.filename, artifactBase64: base64(source.exactBytes) },
predecessor: previous && predecessorBytes && predecessorFilename ? { artifactSha256: previous.artifactSha256,
filename: predecessorFilename, artifactBase64: base64(predecessorBytes) } : null,
appendCoordinate: coordinate, history: {},
};
body.history = await project(body, sourceProof.kaiPulse, previous);
const sealed = await sealReceizSourceBytes({ bytes: Buffer.from(JSON.stringify(body)), filename: "memory-crystal.json", mimeType: "application/json" }, options);
const outputBytes = await readFile(sealed.outputPath);
const outputProof = await verified(outputBytes, basename(sealed.outputPath));
if (previous && outputProof.signer !== previous.signer)
throw Error("crystal_signer_mismatch");
const opened = await openReceizOfflineCrystal(outputBytes, basename(sealed.outputPath));
return { ...sealed, crystal: opened };
}
export async function openReceizOfflineCrystalReference(reference, workspace) {
if (typeof reference !== "string" || !reference)
throw Error("crystal_reference_required");
const source = await createReceizDeviceMaterialHost(workspace).resolveProofReference(reference);
return openReceizOfflineCrystal(source.exactBytes, source.filename);
}
//# sourceMappingURL=offlineCrystal.js.map