@receiz/mcp-server
Version:
MCP server for agents building and verifying Receiz proof-native applications through the canonical Receiz SDK rails.
258 lines • 21 kB
JavaScript
import { randomUUID, createHash } from "node:crypto";
import { assertRuntimeCustodiedReceizArtifactVerification, digestReceizCompositeCanonical, } from "@receiz/sdk";
const text = { type: "string", minLength: 1 };
const inputObject = (properties, required = []) => ({ type: "object", additionalProperties: false, properties, required });
const id = { subjectId: text };
const consent = { confirmation: { ...text, description: "Exact single-use confirmationDigest returned by this tool's preview." } };
const relationship = { subjectId: text, targetSubjectId: text, response: { enum: ["accept", "decline"] }, visibility: { enum: ["public", "private"] }, worldId: text, attemptId: text, idempotencyKey: text };
const trade = { fromSubjectId: text, toSubjectId: text, itemId: text, worldId: text, attemptId: text, idempotencyKey: text, mandateDigest: text };
const twin = { message: text, threadKey: text, contextHead: text, expectedSubjectDigest: text, responseMode: { enum: ["text", "voice", "performance"] }, clientMessageId: text };
const authority = "MCP is not authority. Uses the owner-private runtime derived from admitted identity and sealed source custody. Model input never supplies proof, owner, capability, or execution authority.";
// Descriptions follow the exact runtime effects; consent and dispatch remain unchanged.
const descriptions = Object.freeze({
"receiz_subject_local_runtime_status": "Report whether the owner-private living-subject runtime is configured; unavailable status performs no writes.",
"receiz_subject_local_admit": "Preview admission of the enclosing sealed subject artifact at sourcePath or a device-held sourceReference; after exact confirmation reopen and verify unchanged source bytes before admitting into the owner-private runtime.",
"receiz_subject_local_snapshot_import": "Preview import of the enclosing sealed runtime snapshot at sourcePath; after exact confirmation reopen and verify unchanged source bytes before import.",
"receiz_subject_local_snapshot_export": "Return the owner-private runtime snapshot as an unsealed projection. The result is not portable proof; use canonical sealing before exporting portable truth.",
"receiz_subject_additions": "Read admitted additions for an owner-private subject after an optional exact head.",
"receiz_subject_verify": "Resolve an owner-private subject and verify its existing subject artifact.",
"receiz_subject_memory_project": "Compute event-derived memory through the specified exact subject head without changing stored history.",
"receiz_subject_memory_citations": "Return the source event and proof-object identifiers for one owner-private subject memory.",
"receiz_subject_memory_compact": "Compute a compact event-derived memory projection through an optional head; does not delete or rewrite stored memory.",
"receiz_subject_mandate_explain": "Explain subject mandate status and executability using the runtime’s admitted temporal coordinate; requires the configured KaiSigil prover.",
"receiz_subject_runtime_catch_up": "Preview processing bounded queued subject runtime ticks; after exact confirmation execute up to maximumTicks using admitted temporal proof.",
"receiz_subject_relationships_history": "Read admitted relationship events for an owner-private subject.",
"receiz_subject_relationships_propose": "Compute a relationship transaction plan between two owner-private subjects; does not send or execute the proposal.",
"receiz_subject_relationships_respond": "Preview accepting or declining a relationship transaction; after exact confirmation execute with host-custodied owner authority.",
"receiz_subject_inventory_use": "Preview using a subject inventory item; after exact confirmation execute through the owner-private runtime.",
"receiz_subject_trades_preview": "Preview an inventory trade between two owner-private subjects and retain its exact plan for confirmed execution.",
"receiz_subject_trades_execute": "Consume the exact retained trade preview and confirmation digest, then execute the inventory transfer through the owner-private runtime.",
"receiz_subject_twin_memory_summary": "Read event-derived memory counts and the projection digest for an owner-private subject twin.",
"receiz_subject_subscribe": "Return a finite materialized snapshot of admitted subject additions, bounded by the SDK; this call does not leave a background subscription running.",
"receiz_world_subscribe": "Return one finite materialized snapshot of world events, optionally filtered by head and types; this call does not leave a background subscription running.",
"receiz_subject_twin_stream": "Preview one twin message invocation; after exact confirmation run it, persist its runtime changes, and return its finite materialized event stream.",
"receiz_subject_twin_stream_performance": "Preview one twin performance invocation; after exact confirmation run it, persist its runtime changes, and return its finite materialized event stream.",
"receiz_subject_twin_mind_import_commit": "Preview import of an enclosing sealed Mind artifact; after exact confirmation reopen and verify unchanged bytes, then import into the owner-private subject runtime."
});
function tool(name, inputSchema, mutation = false) {
return { name, description: `${descriptions[name] ?? name} ${mutation ? "Preview first; explicit confirmation consumes the retained exact plan before execution. " : ""}${authority}`, inputSchema, annotations: { readOnlyHint: !mutation, destructiveHint: mutation, openWorldHint: false } };
}
function freeze(value) {
if (value && typeof value === "object") {
for (const child of Object.values(value))
freeze(child);
Object.freeze(value);
}
return value;
}
export const RECEIZ_V127_SUBJECT_TOOL_NAMES = Object.freeze([
"receiz_subject_local_runtime_status",
"receiz_subject_local_admit",
"receiz_subject_local_snapshot_import",
"receiz_subject_local_snapshot_export",
"receiz_subject_additions",
"receiz_subject_verify",
"receiz_subject_memory_project",
"receiz_subject_memory_citations",
"receiz_subject_memory_compact",
"receiz_subject_mandate_explain",
"receiz_subject_runtime_catch_up",
"receiz_subject_relationships_history",
"receiz_subject_relationships_propose",
"receiz_subject_relationships_respond",
"receiz_subject_inventory_use",
"receiz_subject_trades_preview",
"receiz_subject_trades_execute",
"receiz_subject_twin_memory_summary",
"receiz_subject_subscribe",
"receiz_world_subscribe",
"receiz_subject_twin_stream",
"receiz_subject_twin_stream_performance",
"receiz_subject_twin_mind_import_commit",
]);
export const RECEIZ_V127_SUBJECT_TOOLS = freeze([
tool("receiz_subject_local_runtime_status", inputObject({})),
tool("receiz_subject_local_admit", { ...inputObject({ sourcePath: text, sourceReference: { ...text, pattern: "^receiz:file:[a-f0-9]{64}:.+$", description: "Device-held sealed file locator; never proof authority." }, ...consent }), oneOf: [{ required: ["sourcePath"] }, { required: ["sourceReference"] }] }, true),
tool("receiz_subject_local_snapshot_import", inputObject({ sourcePath: text, ...consent }, ["sourcePath"]), true),
tool("receiz_subject_local_snapshot_export", inputObject({})),
tool("receiz_subject_additions", inputObject({ ...id, afterHead: text }, ["subjectId"])),
tool("receiz_subject_verify", inputObject(id, ["subjectId"])),
tool("receiz_subject_memory_project", inputObject({ ...id, throughHead: text }, ["subjectId", "throughHead"])),
tool("receiz_subject_memory_citations", inputObject({ ...id, memoryId: text }, ["subjectId", "memoryId"])),
tool("receiz_subject_memory_compact", inputObject({ ...id, throughHead: text }, ["subjectId"])),
tool("receiz_subject_mandate_explain", inputObject(id, ["subjectId"])),
tool("receiz_subject_runtime_catch_up", inputObject({ ...id, maximumTicks: { type: "integer", minimum: 0, maximum: 100 }, worldId: text, ...consent }, ["subjectId"]), true),
tool("receiz_subject_relationships_history", inputObject(id, ["subjectId"])),
tool("receiz_subject_relationships_propose", inputObject(relationship, ["subjectId", "targetSubjectId", "attemptId", "idempotencyKey"])),
tool("receiz_subject_relationships_respond", inputObject({ ...relationship, ...consent }, ["subjectId", "targetSubjectId", "response", "attemptId", "idempotencyKey"]), true),
tool("receiz_subject_inventory_use", inputObject({ ...id, itemId: text, worldId: text, attemptId: text, idempotencyKey: text, ...consent }, ["subjectId", "itemId", "attemptId", "idempotencyKey"]), true),
tool("receiz_subject_trades_preview", inputObject(trade, ["fromSubjectId", "toSubjectId", "itemId", "attemptId", "idempotencyKey"])),
tool("receiz_subject_trades_execute", inputObject({ planDigest: text, ...consent }, ["planDigest", "confirmation"]), true),
tool("receiz_subject_twin_memory_summary", inputObject(id, ["subjectId"])),
tool("receiz_subject_subscribe", inputObject({ ...id, afterHead: text }, ["subjectId"])),
tool("receiz_world_subscribe", inputObject({ worldId: text, afterHead: text, types: { type: "array", items: text } }, ["worldId"])),
tool("receiz_subject_twin_stream", inputObject({ ...id, input: inputObject(twin, ["message", "contextHead", "expectedSubjectDigest", "clientMessageId"]), ...consent }, ["subjectId", "input"]), true),
tool("receiz_subject_twin_stream_performance", inputObject({ ...id, input: inputObject(twin, ["message", "contextHead", "expectedSubjectDigest", "clientMessageId"]), ...consent }, ["subjectId", "input"]), true),
tool("receiz_subject_twin_mind_import_commit", inputObject({ ...id, sourcePath: { ...text, description: "Workspace path to the enclosing sealed Mind artifact. The host verifies and reopens its exact bytes." }, ...consent }, ["subjectId", "sourcePath"]), true),
]);
export const RECEIZ_V127_SUBJECT_OPERATION_MAP = Object.freeze(Object.fromEntries(RECEIZ_V127_SUBJECT_TOOLS.map(entry => [entry.name, entry])));
function validate(value, schema) {
if (schema.enum && !schema.enum.includes(value))
throw new Error("receiz_subject_argument_enum_invalid");
if (schema.type === "string" && (typeof value !== "string" || !value.trim()))
throw new Error("receiz_subject_argument_text_required");
if (schema.type === "integer" && (typeof value !== "number" || !Number.isInteger(value) || value < Number(schema.minimum) || value > Number(schema.maximum)))
throw new Error("receiz_subject_argument_bound_invalid");
if (schema.type === "array") {
if (!Array.isArray(value))
throw new Error("receiz_subject_argument_array_required");
for (const item of value)
validate(item, schema.items);
}
if (schema.type === "object") {
if (!value || typeof value !== "object" || Array.isArray(value) || ![Object.prototype, null].includes(Object.getPrototypeOf(value)))
throw new Error("receiz_subject_argument_object_required");
const properties = schema.properties;
for (const key of schema.required)
if (!Object.hasOwn(value, key))
throw new Error(`receiz_subject_argument_required:${key}`);
for (const [key, item] of Object.entries(value)) {
if (!Object.hasOwn(properties, key))
throw new Error(`receiz_subject_argument_unknown:${key}`);
validate(item, properties[key]);
}
}
}
function without(args, ...keys) { return Object.fromEntries(Object.entries(args).filter(([key]) => !keys.includes(key))); }
function unavailable() { return { status: "unavailable", code: "owner_private_subject_runtime_required", missingBoundary: "Host must configure a private durable runtime from admitted identity and canonical sealed source custody.", writesPerformed: 0 }; }
// These SDK generators terminate: subjectSubscribe iterates <=1000 admitted additions;
// worldSubscribe iterates one finite world-event array. Twin generators process one
// finite proof query and one model response. The adapter materializes that finite
// snapshot before yielding. No follow/poll loop or unbounded network subscription.
async function collect(events) {
const result = [];
for await (const event of events)
result.push(event);
return { events: result, complete: true, sourceBoundary: "finite SDK invocation snapshot" };
}
export function createReceizV127SubjectOperations(input) {
const plans = new Map();
async function source(path, byReference = false) {
const resolver = byReference ? input.resolveSourceReference : input.resolveSource;
if (!resolver)
throw new Error("receiz_subject_source_custody_required");
let candidate;
try {
candidate = await resolver(path);
}
catch {
throw new Error("receiz_subject_source_custody_unavailable");
}
assertRuntimeCustodiedReceizArtifactVerification(candidate.verification);
if (candidate.verification.status !== "verified-artifact")
throw new Error("receiz_subject_enclosing_proof_required");
const payloadBytes = candidate.payloadBytes.slice();
const payloadDigest = createHash("sha256").update(payloadBytes).digest("hex");
if (payloadDigest !== candidate.verification.payloadDigest.value)
throw new Error("receiz_subject_source_payload_mismatch");
return { source: { verification: candidate.verification, payloadBytes }, digest: digestReceizCompositeCanonical({ artifact: candidate.verification.artifactDigest, payload: candidate.verification.payloadDigest }) };
}
function retain(name, args, extra = {}) {
const identity = digestReceizCompositeCanonical({ name, args, ...(extra.sourceDigest ? { sourceDigest: extra.sourceDigest } : {}), ...(extra.trade ? { trade: extra.trade } : {}) });
const confirmationDigest = createHash("sha256").update(randomUUID() + identity).digest("hex");
plans.set(confirmationDigest, { name, args: structuredClone(args), identity, ...structuredClone(extra) });
return { status: "planned", operation: name, planDigest: confirmationDigest, confirmationDigest, confirmationRequired: true, arguments: args, writesPerformed: 0, authority, ...(extra.trade ? { preview: extra.trade } : {}), ...(extra.sourceDigest ? { sourceDigest: extra.sourceDigest } : {}) };
}
function consume(name, args, confirmation) {
if (typeof confirmation !== "string")
throw new Error("receiz_subject_confirmation_required");
const plan = plans.get(confirmation);
if (!plan || plan.name !== name || digestReceizCompositeCanonical(plan.args) !== digestReceizCompositeCanonical(args))
throw new Error("receiz_subject_confirmation_invalid");
plans.delete(confirmation);
return plan;
}
return Object.freeze({
handles(name) { return Object.hasOwn(RECEIZ_V127_SUBJECT_OPERATION_MAP, name); },
async call(name, raw = {}) {
if (!Object.hasOwn(RECEIZ_V127_SUBJECT_OPERATION_MAP, name))
throw new Error("receiz_subject_operation_unknown");
const definition = RECEIZ_V127_SUBJECT_OPERATION_MAP[name];
validate(raw, definition.inputSchema);
if (name === "receiz_subject_local_admit") {
const selection = raw;
if (Object.hasOwn(selection, "sourcePath") === Object.hasOwn(selection, "sourceReference"))
throw new Error("receiz_subject_exactly_one_source_required");
if (Object.hasOwn(selection, "sourceReference") && !/^receiz:file:[a-f0-9]{64}:.+$/.test(String(selection.sourceReference)))
throw new Error("receiz_subject_source_reference_invalid");
}
if (!input.runtime)
return unavailable();
const runtime = input.runtime;
const args = structuredClone(raw);
const confirmation = args.confirmation;
delete args.confirmation;
const id = args.subjectId;
const options = without(args, "subjectId");
if (name === "receiz_subject_local_runtime_status")
return { status: "available", custody: "owner-private", protocolVersion: runtime.version, authority };
if (name === "receiz_subject_trades_preview") {
const preview = await runtime.subjects.trades.preview(args);
return retain("receiz_subject_trades_execute", {}, { trade: preview });
}
if (name === "receiz_subject_trades_execute") {
if (args.planDigest !== confirmation)
throw new Error("receiz_subject_confirmation_invalid");
const plan = consume(name, {}, confirmation);
if (!plan.trade)
throw new Error("receiz_subject_trade_plan_required");
return runtime.subjects.trades.execute(plan.trade);
}
if (name === "receiz_subject_local_snapshot_export")
return { status: "unsealed-projection", portableProof: false, requiredBoundary: "Use the canonical seal workflow before exporting portable truth.", snapshot: await runtime.exportSnapshot() };
if (["receiz_subject_twin_mind_import_commit", "receiz_subject_local_admit", "receiz_subject_local_snapshot_import"].includes(name)) {
const byReference = name === "receiz_subject_local_admit" && typeof args.sourceReference === "string";
if (!(byReference ? input.resolveSourceReference : input.resolveSource))
return { ...unavailable(), code: "sealed_source_host_resolver_required" };
if (confirmation === undefined) {
const opened = await source((byReference ? args.sourceReference : args.sourcePath), byReference);
return retain(name, args, { sourceDigest: opened.digest });
}
const plan = consume(name, args, confirmation);
const reopened = await source((byReference ? plan.args.sourceReference : plan.args.sourcePath), byReference);
if (reopened.digest !== plan.sourceDigest)
throw new Error("receiz_subject_source_changed");
if (name === "receiz_subject_local_admit")
return runtime.admitSubject(reopened.source);
if (name === "receiz_subject_local_snapshot_import")
return runtime.importSnapshot(reopened.source);
return runtime.subjects.twin.importMind(id, reopened.source);
}
if (definition.annotations.destructiveHint) {
if (confirmation === undefined)
return retain(name, args);
consume(name, args, confirmation);
}
switch (name) {
case "receiz_subject_additions": return runtime.subjects.additions(id, options);
case "receiz_subject_verify": return runtime.subjects.verify(await runtime.subjects.resolve(id));
case "receiz_subject_memory_project": return runtime.subjects.memory.project(id, { throughHead: args.throughHead });
case "receiz_subject_memory_citations": return runtime.subjects.memory.citations(id, args.memoryId);
case "receiz_subject_memory_compact": return runtime.subjects.memory.compact(id, options);
case "receiz_subject_mandate_explain": return runtime.subjects.mandates.explain(id);
case "receiz_subject_runtime_catch_up": return runtime.subjects.runtime.catchUp(id, options);
case "receiz_subject_relationships_history": return runtime.subjects.relationships.history(id);
case "receiz_subject_relationships_propose": return runtime.subjects.relationships.propose(args);
case "receiz_subject_relationships_respond": return runtime.subjects.relationships.respond(args);
case "receiz_subject_inventory_use": return runtime.subjects.inventory.use(args);
case "receiz_subject_twin_memory_summary": return runtime.subjects.twin.memorySummary(id);
case "receiz_subject_subscribe": return collect(runtime.subjects.subscribe(id, options));
case "receiz_world_subscribe": return collect(runtime.world.subscribe(args));
case "receiz_subject_twin_stream": return collect(runtime.subjects.twin.stream(id, args.input));
case "receiz_subject_twin_stream_performance": return collect(runtime.subjects.twin.streamPerformance(id, args.input));
default: throw new Error("receiz_subject_operation_unknown");
}
},
});
}
//# sourceMappingURL=v127SubjectOperations.js.map