UNPKG

@receiz/mcp-server

Version:

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

2,215 lines • 121 kB
#!/usr/bin/env node
import { ArtifactInputError, RECEIZ_VERIFY_UPLOADED_ARTIFACT_TOOL, verifyUploadedArtifact } from "./uploadedArtifact.js";
import { applyReceizMcpToolAnnotations } from "./toolAnnotations.js";
import { RECEIZ_V127_SUBJECT_TOOLS, createReceizV127SubjectOperations } from "./v127SubjectOperations.js";
import { resolveReceizV127SubjectWorkspaceSource, resolveReceizV127SubjectReferenceSource } from "./v127SubjectHost.js";
import { RECEIZ_V127_SDK_TOOLS, createReceizV127SdkOperations } from "./v127SdkOperations.js";
import { assertReceizMarketplaceToolCall, wrapReceizMarketplaceClient } from "./marketplaceExecutionPolicy.js";
export * from "./marketplaceExecutionPolicy.js";
import { assertReceizMarketplaceNonfinancialTool, isReceizMarketplaceNonfinancialTool, RECEIZ_MARKETPLACE_NONFINANCIAL_TOOL_NAMES } from "./marketplaceNonfinancialPolicy.js";
export * from "./marketplaceNonfinancialPolicy.js";
import { RECEIZ_DEVICE_AI_SUBJECT_TOOL, callReceizMcpDeviceAiSubjectCreate } from "./deviceAiSubjectTool.js";
export { createReceizMcpDeviceAiSubject } from "./deviceAiSubject.js";
export { bindReceizMcpDeviceAiSubjectCreation } from "./deviceAiSubjectTool.js";
import { RECEIZ_LIVING_SUBJECT_REDUCER_DIGEST } from "@receiz/sdk";
import { openReceizV127SubjectRuntimeFromFiles } from "@receiz/sdk/subjects/node";
import { homedir } from "node:os";
import { isAbsolute, join, resolve } from "node:path";
import { bootstrapReceizMcpDeviceRuntime } from "./deviceBootstrap.js";
export { bootstrapReceizMcpDeviceRuntime } from "./deviceBootstrap.js";
import { openReceizMcpDeviceRuntime } from "./deviceRuntime.js";
export { openReceizMcpDeviceRuntime } from "./deviceRuntime.js";
import { runReceizMcpDeviceRelay } from "./deviceRelay.js";
export { runReceizMcpDeviceRelay } from "./deviceRelay.js";
import { DEVICE_IDENTITY_CONTEXT_RESOURCE, DEVICE_IDENTITY_CONTEXT_URI, deviceIdentityContextShared, readDeviceIdentityContext } from "./deviceIdentityContext.js";
import { RECEIZ_OFFLINE_SEAL_TOOLS, callReceizOfflineSealTool } from "./offlineSealing.js";
import { readReceizSealedOutputChunk, registerReceizSealedOutput, RECEIZ_SEALED_OUTPUT_HTML, RECEIZ_SEALED_OUTPUT_RESOURCE, RECEIZ_SEALED_OUTPUT_URI } from "./sealedArtifactOutput.js";
import { RECEIZ_OFFLINE_CRYSTAL_TOOLS, appendReceizOfflineCrystal, openReceizOfflineCrystalReference } from "./offlineCrystal.js";
export { appendReceizOfflineCrystal, openReceizOfflineCrystal, openReceizOfflineCrystalReference, readVerifiedReceizOfflineCrystalSources } from "./offlineCrystal.js";
export { sealReceizSourceBytes, sealUploadedArtifact, sealSuppliedText } from "./offlineSealing.js";
import { RECEIZ_PUBLIC_SDK_FUNCTION_INVENTORY } from "@receiz/sdk/function-inventory";
import { RECEIZ_OIDC_SCOPES_BY_RAIL, RECEIZ_WEBHOOK_EVENT_GROUPS, RECEIZ_WEBHOOK_EVENT_PRESETS, RECEIZ_WEBHOOK_EVENT_TYPES, assertReceizWebhookEvent, assertReceizAssetManifest, assertReceizSportsCardManifest, createReceizClient, describeReceizCapabilities, describeReceizSdkClientCapabilityInventory, RECEIZ_V125_CAPABILITY_INVENTORY, RECEIZ_V125_HIGHEST_CASH_OUT_FRAME, describeReceizError, RECEIZ_V112_ARTIFACT_LAWS, RECEIZ_CURRENT_REGISTRY_DIGEST, projectReceizAssetManifest, projectReceizSportsCardManifest, openVerifiedReceizMaterialUrl, receizBase64UrlEncode, projectReceizKksV1SealedProofCoordinate, receizOidcScopesForRails, RECEIZ_V113_GLOBAL_COMMIT_DOMAIN, } from "@receiz/sdk";
import { applyReceizIntegrationPreview, checkReceizIntegration, createReceizIntegrationPreview, defineReceizApp, explainReceizIntegrationFinding, inspectReceizProject, planReceizIntegration, planReceizUpgrade, } from "@receiz/sdk/compiler";
import { runReceizConformance } from "@receiz/sdk/testing";
import { createHash } from "node:crypto";
import { realpathSync } from "node:fs";
import { createInterface } from "node:readline";
import { fileURLToPath } from "node:url";
import { RECEIZ_MCP_CURRENT_RELEASE_VERSION } from "./currentRelease.generated.js";
import { createReceizConstitutionalContext, createReceizConstitutionalRuntime, scanReceizAuthorityBypass, } from "./constitutional.js";
import { createReceizMcpOperations, RECEIZ_MCP_CURRENT_RELEASE_IDENTITY, RECEIZ_MCP_OPERATION_TOOLS, verifyCompleteReceizArtifact, } from "./operations.js";
import { callReceizV122McpOperation, RECEIZ_V122_MCP_TOOL_NAMES, RECEIZ_V122_MCP_TOOLS } from "./v122Operations.js";
import { callReceizV123McpOperation, RECEIZ_V123_MCP_TOOL_NAMES, RECEIZ_V123_MCP_TOOLS } from "./v123Operations.js";
import { callReceizV124McpOperation, RECEIZ_V124_MCP_TOOL_NAMES, RECEIZ_V124_MCP_TOOLS } from "./v124Operations.js";
import { callReceizV125McpOperation, RECEIZ_V125_MCP_TOOL_NAMES, RECEIZ_V125_MCP_TOOLS } from "./v125Operations.js";
import { callReceizV125TrustMcpOperation, RECEIZ_V125_TRUST_MCP_TOOL_NAMES, RECEIZ_V125_TRUST_MCP_TOOLS } from "./v125TrustOperations.js";
export * from "./constitutional.js";
export * from "./operations.js";
export * from "./globalReconciliationOperations.js";
export * from "./livingSubjectOperations.js";
export * from "./v122Operations.js";
export * from "./v122PlanCustody.js";
export * from "./v123Operations.js";
export * from "./v124Operations.js";
export * from "./v125Operations.js";
export * from "./v125TrustOperations.js";
export * from "./v125TrustHost.js";
import { createReceizV125TrustMcpOperations } from "./v125TrustHost.js";
export const RECEIZ_MCP_AUTHORITY_BOUNDARY = {
    mcpAuthority: false,
    sourceOfTruth: "Receiz law, sealed artifact truth, deterministic proof object state, verified local truth, and verified register appends; Receiz.com native operations and SDK projections remain beneath that proof truth.",
    strongerTruth: [
        "Receiz law and product invariants",
        "sealed artifact truth",
        "deterministic proof object state",
        "verified local truth",
        "verified register append",
        "Receiz.com native operation",
        "authenticated SDK/API projection",
    ],
    weakerToolingLayer: "MCP exposes agent-callable tools only. MCP does not create, replace, or outrank Receiz truth.",
    highestCashOutFrame: RECEIZ_V125_HIGHEST_CASH_OUT_FRAME,
};
const RECEIZ_DEFAULT_CONSTITUTIONAL_CONTEXT = createReceizConstitutionalContext({
    registryDigest: RECEIZ_CURRENT_REGISTRY_DIGEST,
    applicableLaws: [
        "ownership.enclosing-artifact-first",
        ...RECEIZ_V112_ARTIFACT_LAWS,
        "wilds.retirement.irreversible",
        "receiz.command-only-mutation",
    ],
    authorityBoundary: { profile: "simulation-only", tenantRequired: false },
    stateMachine: { initial: "unconfigured", states: ["unconfigured"], transitions: [] },
    allowedCommands: [],
});
/**
 * Loads the trusted host seam used by the stdio server. The module receives
 * exact materials outside model arguments and must export
 * `resolveReceizV124Material`; `persistReceizV124Material` is optional.
 */
export async function loadReceizV124McpMaterialHost(moduleSpecifier = process.env.RECEIZ_V124_MATERIAL_HOST_MODULE) {
    if (!moduleSpecifier)
        return Object.freeze({});
    const loaded = await import(moduleSpecifier);
    const defaultExport = loaded.default && typeof loaded.default === "object"
        ? loaded.default
        : {};
    const resolveMaterial = loaded.resolveReceizV124Material
        ?? defaultExport.resolveReceizV124Material;
    const persistMaterial = loaded.persistReceizV124Material
        ?? defaultExport.persistReceizV124Material;
    if (typeof resolveMaterial !== "function") {
        throw new TypeError("V124_MCP_MATERIAL_HOST_RESOLVER_REQUIRED");
    }
    if (persistMaterial !== undefined && typeof persistMaterial !== "function") {
        throw new TypeError("V124_MCP_MATERIAL_HOST_PERSISTER_INVALID");
    }
    return Object.freeze({
        resolveMaterial: resolveMaterial,
        ...(persistMaterial
            ? { persistMaterial: persistMaterial }
            : {}),
    });
}
/**
 * Loads the trusted host seam used by the stdio server for v125 lawful-action
 * proof objects. The model receives only an opaque reference; the host resolves
 * exact sealed bytes after confirmation and beneath artifact verification.
 */
export async function loadReceizV125McpProofHost(moduleSpecifier = process.env.RECEIZ_V125_PROOF_HOST_MODULE) {
    if (!moduleSpecifier)
        return Object.freeze({});
    const loaded = await import(moduleSpecifier);
    const defaultExport = loaded.default && typeof loaded.default === "object"
        ? loaded.default
        : {};
    const resolveProofReference = loaded.resolveReceizV125ProofReference
        ?? defaultExport.resolveReceizV125ProofReference;
    if (typeof resolveProofReference !== "function") {
        throw new TypeError("V125_MCP_PROOF_HOST_RESOLVER_REQUIRED");
    }
    return Object.freeze({
        resolveProofReference: resolveProofReference,
    });
}
export async function loadReceizV125McpTrustHost(scope, moduleSpecifier = process.env.RECEIZ_V125_TRUST_HOST_MODULE) {
    if (!moduleSpecifier)
        return undefined;
    const loaded = await import(moduleSpecifier);
    const configure = loaded.createReceizV125TrustHostConfiguration;
    if (typeof configure !== "function")
        throw new TypeError("V125_TRUST_HOST_CONFIGURATION_REQUIRED");
    const configuration = await configure(Object.freeze({ ...scope }));
    const allowed = new Set(["materialOptions", "credentialPresentation", "pbiCeremony", "attestation", "subjectCoordination", "subjectMessage", "externalExecution"]);
    if (!configuration || typeof configuration !== "object" || Array.isArray(configuration)
        || Object.keys(configuration).some((key) => !allowed.has(key)))
        throw new TypeError("V125_TRUST_HOST_CONFIGURATION_INVALID");
    return createReceizV125TrustMcpOperations({ ...configuration, ...scope });
}
const AUTHORITY_DESCRIPTION = "MCP is not authority; this tool calls the canonical Receiz SDK/API rails and reports the source primitive.";
export const RECEIZ_MCP_RESOURCE_TEMPLATES = [
    {
        uriTemplate: "receiz://asset/{id}",
        name: "Receiz Asset",
        description: "Resolve a public Receiz asset/proof object by ID through canonical public proof rails.",
        mimeType: "application/json",
    },
    {
        uriTemplate: "receiz://proof/{id}",
        name: "Receiz Proof",
        description: "Resolve a public Receiz proof object by ID through canonical public proof rails.",
        mimeType: "application/json",
    },
    {
        uriTemplate: "receiz://pitch/{witnessId}",
        name: "Receiz Pitch Proof Witness",
        description: "Address a Sports pitch proof witness; use receiz_pitch_proof_by_witness_id with local day proof truth.",
        mimeType: "application/json",
    },
    {
        uriTemplate: "receiz://store/{tenantHost}",
        name: "Receiz Store Projection",
        description: "Resolve a durable public store projection by tenant host.",
        mimeType: "application/json",
    },
    {
        uriTemplate: "receiz://sdk/docs",
        name: "Receiz SDK Docs",
        description: "Stable SDK and MCP documentation pointers for agent hosts.",
        mimeType: "application/json",
    },
    {
        uriTemplate: "receiz://schemas/proof-object-v1",
        name: "Receiz Proof Object Schema",
        description: "Proof object schema guidance for offline inspection and app builders.",
        mimeType: "application/json",
    },
    {
        uriTemplate: "receiz://schemas/app-contract-v1",
        name: "Receiz App Contract v1",
        description: "Typed declarative Receiz application contract schema.",
        mimeType: "application/json",
    },
    {
        uriTemplate: "receiz://schemas/integration-plan-v1",
        name: "Receiz Integration Plan v1",
        description: "Deterministic integration-plan schema and dispositions.",
        mimeType: "application/json",
    },
    {
        uriTemplate: "receiz://schemas/upgrade-rules-v1",
        name: "Receiz Upgrade Rules v1",
        description: "Version-aware append-only upgrade rules.",
        mimeType: "application/json",
    },
    {
        uriTemplate: "receiz://schemas/generated-files-v1",
        name: "Receiz Generated Files v1",
        description: "Generated-file ownership and safe mutation conventions.",
        mimeType: "application/json",
    },
];
const objectSchema = (properties = {}, required = []) => ({
    type: "object",
    additionalProperties: true,
    properties,
    ...(required.length > 0 ? { required } : {}),
});
const stringProp = (description) => ({ type: "string", description });
const numberProp = (description) => ({ type: "number", description });
const arrayProp = (description, items = {}) => ({ type: "array", description, items });
export const RECEIZ_MCP_TOOLS = applyReceizMcpToolAnnotations([
    RECEIZ_DEVICE_AI_SUBJECT_TOOL,
    ...RECEIZ_OFFLINE_SEAL_TOOLS,
    ...RECEIZ_OFFLINE_CRYSTAL_TOOLS,
    RECEIZ_VERIFY_UPLOADED_ARTIFACT_TOOL,
    ...RECEIZ_V127_SDK_TOOLS,
    ...RECEIZ_V127_SUBJECT_TOOLS,
    ...RECEIZ_MCP_OPERATION_TOOLS,
    ...RECEIZ_V122_MCP_TOOLS,
    ...RECEIZ_V123_MCP_TOOLS,
    ...RECEIZ_V124_MCP_TOOLS,
    ...RECEIZ_V125_MCP_TOOLS,
    ...RECEIZ_V125_TRUST_MCP_TOOLS,
    {
        name: "receiz_doctor",
        description: `Run SDK doctor for an app/tenant. ${AUTHORITY_DESCRIPTION}`,
        inputSchema: objectSchema({
            tenantHost: stringProp("Tenant host or custom domain to inspect."),
            callbackUrl: stringProp("OIDC callback URL to check."),
            scopes: arrayProp("OIDC scopes to inspect.", { type: "string" }),
        }),
    },
    {
        name: "receiz_capabilities",
        description: `Inspect first-class Receiz SDK capabilities. ${AUTHORITY_DESCRIPTION}`,
        inputSchema: objectSchema({
            mode: { type: "string", enum: ["describe", "probe"], description: "describe returns deterministic local support; probe inspects configured readiness." },
            tenantHost: stringProp("Tenant host or custom domain to scope capability readiness."),
            scopes: arrayProp("OIDC scopes currently held by the app.", { type: "string" }),
        }),
    },
    {
        name: "receiz_required_scopes",
        description: `Return stable OIDC scope constants per Receiz rail. ${AUTHORITY_DESCRIPTION}`,
        inputSchema: objectSchema({
            rails: arrayProp("Rail keys such as identity, publicStore, customers, merchants, wallet, commerce.", { type: "string" }),
        }, ["rails"]),
    },
    {
        name: "receiz_authorize_url",
        description: `Build a Receiz Connect/OIDC authorize URL through the SDK. ${AUTHORITY_DESCRIPTION}`,
        inputSchema: objectSchema({
            clientId: stringProp("Receiz app client ID."),
            redirectUri: stringProp("Callback URL."),
            codeChallenge: stringProp("PKCE code challenge."),
            codeChallengeMethod: stringProp("PKCE method, usually S256."),
            scope: arrayProp("OIDC scopes.", { type: "string" }),
            state: stringProp("Opaque app state."),
            usernameHint: stringProp("Optional username/login hint."),
        }, ["clientId", "redirectUri", "codeChallenge"]),
    },
    {
        name: "receiz_mcp_login",
        description: `Return the official Receiz delegated agent-token setup path for MCP hosts. ${AUTHORITY_DESCRIPTION}`,
        inputSchema: objectSchema({
            appName: stringProp("Agent token name, for example Codex local dev."),
            clientId: stringProp("Receiz app client ID to issue beneath."),
            tenantHost: stringProp("Tenant host or app domain being debugged."),
            redirectUri: stringProp("Optional OIDC callback URL for MCP-owned Authorization Code + PKCE login."),
            codeChallenge: stringProp("Optional PKCE code challenge for MCP-owned login."),
            codeChallengeMethod: stringProp("Optional PKCE method, usually S256."),
            state: stringProp("Optional opaque OAuth state."),
        }),
    },
    {
        name: "receiz_ensure_tenant_session",
        description: `Build the official tenant customer-session entry path. ${AUTHORITY_DESCRIPTION}`,
        inputSchema: objectSchema({
            tenantHost: stringProp("Tenant host or custom domain."),
            returnTo: stringProp("URL to return to after session restore."),
            fallback: stringProp("artifact_upload or connect."),
            clientId: stringProp("Optional OIDC client ID."),
            redirectUri: stringProp("Optional OIDC redirect URI."),
            codeChallenge: stringProp("Optional PKCE code challenge."),
            scope: arrayProp("OIDC scopes.", { type: "string" }),
            state: stringProp("Opaque app state."),
            usernameHint: stringProp("Optional username/login hint."),
        }, ["tenantHost"]),
    },
    {
        name: "receiz_app_state_publish",
        description: `Publish durable public app-state projection through receiz.appState.publish. ${AUTHORITY_DESCRIPTION}`,
        inputSchema: objectSchema({
            feed: objectSchema({}, []),
            idempotencyKey: stringProp("Idempotency key for safe retries."),
            signature: stringProp("Optional feed signature."),
        }),
    },
    {
        name: "receiz_app_state_resolve",
        description: `Resolve app-state by URL, host, namespace, ID, or creator. ${AUTHORITY_DESCRIPTION}`,
        inputSchema: objectSchema({
            url: stringProp("Source URL."),
            host: stringProp("Tenant host."),
            tenantHost: stringProp("Tenant host."),
            id: stringProp("Projection ID."),
            namespace: stringProp("Projection namespace."),
            creatorReceizId: stringProp("Creator Receiz ID."),
            receizId: stringProp("Creator Receiz ID alias."),
            schema: stringProp("Required schema."),
            state: stringProp("Required projection state."),
            requiredDataKey: stringProp("Required data key."),
            migrateTo: numberProp("Optional target schema version."),
        }),
    },
    {
        name: "receiz_app_state_by_url",
        description: `Read a public app-state projection by URL. ${AUTHORITY_DESCRIPTION}`,
        inputSchema: objectSchema({ url: stringProp("Source URL.") }, ["url"]),
    },
    {
        name: "receiz_app_state_by_creator",
        description: `Read public app-state projections by creator Receiz ID. ${AUTHORITY_DESCRIPTION}`,
        inputSchema: objectSchema({ receizId: stringProp("Creator Receiz ID.") }, ["receizId"]),
    },
    {
        name: "receiz_app_state_by_namespace",
        description: `Read public app-state projections by namespace. ${AUTHORITY_DESCRIPTION}`,
        inputSchema: objectSchema({ namespace: stringProp("Projection namespace.") }, ["namespace"]),
    },
    {
        name: "receiz_app_state_by_id",
        description: `Read a public app-state projection by ID. ${AUTHORITY_DESCRIPTION}`,
        inputSchema: objectSchema({ id: stringProp("Projection ID.") }, ["id"]),
    },
    {
        name: "receiz_public_store_publish",
        description: `Publish a typed public-store projection through receiz.publicStore.publish. ${AUTHORITY_DESCRIPTION}`,
        inputSchema: objectSchema({
            tenantHost: stringProp("Tenant host or custom domain."),
            merchantReceizId: stringProp("Merchant Receiz ID."),
            state: objectSchema({}, []),
            idempotencyKey: stringProp("Idempotency key for safe retries."),
            title: stringProp("Store title."),
            sourceUrl: stringProp("Optional canonical source URL."),
            namespace: stringProp("Optional projection namespace."),
        }, ["tenantHost", "merchantReceizId", "state"]),
    },
    {
        name: "receiz_public_store_resolve",
        description: `Resolve a typed public-store projection by host, URL, or ID. ${AUTHORITY_DESCRIPTION}`,
        inputSchema: objectSchema({
            host: stringProp("Tenant host."),
            tenantHost: stringProp("Tenant host."),
            url: stringProp("Source URL."),
            id: stringProp("Projection ID."),
        }),
    },
    {
        name: "receiz_inspect_offline_file",
        description: `Inspect a local manifest/projection shape without claiming artifact integrity, ownership continuity, or verification. ${AUTHORITY_DESCRIPTION}`,
        inputSchema: objectSchema({
            fileText: stringProp("JSON file contents to parse and verify."),
            value: objectSchema({}, []),
            expectedPrimitive: stringProp("Expected primitive label for agent-side assertion."),
        }),
    },
    {
        name: "receiz_asset_by_url",
        description: `Resolve a public Receiz asset/proof surface by URL. ${AUTHORITY_DESCRIPTION}`,
        inputSchema: objectSchema({ url: stringProp("Receiz public proof URL.") }, ["url"]),
    },
    {
        name: "receiz_material_url_open",
        description: `Verify the enclosing sealed proof object carried by a content-bearing Receiz URL, then reconstruct its exact native media bytes locally. Fully inline rma2 opens without a server or database call. Segmented rmc1 and streaming rmc2 heads reconstruct their complete held family; rmc2/rma3/raw projects the verified raw artifact instead of entering the compressed RMA2 decoder. The 4,096-character public-head bound never truncates proof bytes, and transport never becomes authority. Device time is never creation-pulse authority. ${AUTHORITY_DESCRIPTION}`,
        inputSchema: objectSchema({
            url: stringProp("Content-bearing Receiz proof URL carrying inline rma2, segmented rmc1, or streaming rmc2/rma3/raw material."),
            includePayloadBytes: {
                type: "boolean",
                description: "When true, include the exact verified native payload as base64url for local rendering or playback.",
            },
            sourceUrls: {
                type: "array",
                items: { type: "string" },
                description: "Optional complete held material source family. When present, reconstruction is local and fails closed rather than consulting remote transport.",
            },
        }, ["url"]),
    },
    {
        name: "receiz_sealed_kai_moment",
        description: `Open an identity or proof object's complete KaiSigil-bound KKSv1.0 coordinate and project its exact Kai moment. A bare pulse string is never authority. The unchanged KaiSigil BLAKE3, Poseidon, Groth16, pinned-key, KKS-lattice, and causal bindings must verify; createdAt, device time, browser time, process uptime, session state, network calls, and server rows are never consulted. ${AUTHORITY_DESCRIPTION}`,
        inputSchema: objectSchema({
            coordinate: objectSchema({}, []),
        }, ["coordinate"]),
    },
    {
        name: "receiz_asset_by_id",
        description: `Resolve a public Receiz asset/proof surface by ID. ${AUTHORITY_DESCRIPTION}`,
        inputSchema: objectSchema({ id: stringProp("Receiz public proof ID.") }, ["id"]),
    },
    {
        name: "receiz_pitch_proof_by_witness_id",
        description: `Resolve a pitch proof witness from already-admitted local day-proof truth. ${AUTHORITY_DESCRIPTION}`,
        inputSchema: objectSchema({
            witnessId: stringProp("Pitch witness ID."),
            local: objectSchema({}, []),
            dayProof: objectSchema({}, []),
            pitchDayProof: objectSchema({}, []),
        }, ["witnessId"]),
    },
    {
        name: "receiz_card_history",
        description: `Resolve Sports card append/event memory with local-first SDK card memory rails. ${AUTHORITY_DESCRIPTION}`,
        inputSchema: objectSchema({
            collectibleId: stringProp("Sports collectible ID."),
            cardId: stringProp("Sports card ID."),
            local: objectSchema({}, []),
            cardMemory: objectSchema({}, []),
        }),
    },
    {
        name: "receiz_transfer_preview",
        description: `Build a deterministic transfer preview without mutating settlement state. ${AUTHORITY_DESCRIPTION}`,
        inputSchema: objectSchema({
            senderReceizId: stringProp("Sender Receiz ID."),
            recipientReceizId: stringProp("Recipient Receiz ID."),
            amountUsd: stringProp("Transfer amount in USD."),
            note: stringProp("Optional transfer note."),
            idempotencyKey: stringProp("Optional idempotency key for the later real transfer."),
        }),
    },
    {
        name: "receiz_transfer_requires_confirmation",
        description: `Return the Receiz transfer confirmation requirement for a proposed transfer. ${AUTHORITY_DESCRIPTION}`,
        inputSchema: objectSchema({
            amountUsd: stringProp("Transfer amount in USD."),
            recipientReceizId: stringProp("Recipient Receiz ID."),
        }),
    },
    {
        name: "receiz_pack_open_preview",
        description: `Build a deterministic pack-open preview without admitting or appending card truth. ${AUTHORITY_DESCRIPTION}`,
        inputSchema: objectSchema({
            packId: stringProp("Pack ID."),
            slotCount: numberProp("Number of preview slots."),
            sport: stringProp("Sport namespace."),
        }, ["packId"]),
    },
    {
        name: "receiz_marketplace_template_generate",
        description: `Generate an SDK-ready marketplace/app template envelope without publishing state. ${AUTHORITY_DESCRIPTION}`,
        inputSchema: objectSchema({
            tenantHost: stringProp("Tenant host or custom domain."),
            templateKind: stringProp("commerce, marketplace, game, rewards, profile, directory, blog, or custom."),
            title: stringProp("Template title."),
        }, ["tenantHost"]),
    },
    {
        name: "receiz_webhook_events_catalog",
        description: `Return the SDK webhook event catalog, groups, and zero-guess presets. ${AUTHORITY_DESCRIPTION}`,
        inputSchema: objectSchema(),
    },
    {
        name: "receiz_webhook_register_endpoint",
        description: `Register a developer webhook endpoint and return its one-time secret through receiz.webhookEndpoints.create. ${AUTHORITY_DESCRIPTION}`,
        inputSchema: objectSchema({
            label: stringProp("Human label for this endpoint."),
            url: stringProp("HTTPS receiver URL."),
            eventTypes: arrayProp("Webhook event types to deliver.", { type: "string" }),
            preset: stringProp("payment, proofSettlement, commerce, or everything."),
            idempotencyKey: stringProp("Idempotency key for safe retries."),
        }, ["label", "url"]),
    },
    {
        name: "receiz_webhook_rotate_secret",
        description: `Rotate a webhook endpoint secret and return the new one-time secret through receiz.webhookEndpoints.rotateSecret. ${AUTHORITY_DESCRIPTION}`,
        inputSchema: objectSchema({ endpointId: stringProp("Webhook endpoint ID.") }, ["endpointId"]),
    },
    {
        name: "receiz_webhook_send_test_event",
        description: `Generate a signed test delivery for an endpoint through receiz.webhookEndpoints.sendTest. ${AUTHORITY_DESCRIPTION}`,
        inputSchema: objectSchema({
            endpointId: stringProp("Webhook endpoint ID."),
            eventType: stringProp("Webhook event type to test."),
        }, ["endpointId"]),
    },
    {
        name: "receiz_webhook_receiver_scaffold",
        description: `Return a copy-paste receiver scaffold that verifies delivery before parsing or admitting truth. ${AUTHORITY_DESCRIPTION}`,
        inputSchema: objectSchema({
            framework: stringProp("nextjs or fetch."),
            secretEnv: stringProp("Environment variable name containing the webhook secret."),
        }),
    },
    {
        name: "receiz_webhook_verify_payload",
        description: `Verify a webhook signature and assert the Receiz webhook event envelope through SDK rails. ${AUTHORITY_DESCRIPTION}`,
        inputSchema: objectSchema({
            secret: stringProp("Webhook endpoint secret."),
            timestamp: stringProp("x-receiz-timestamp value."),
            signature: stringProp("x-receiz-signature value."),
            body: stringProp("Raw request body string."),
            toleranceSeconds: numberProp("Allowed timestamp drift in seconds."),
            nowMs: numberProp("Override current time in milliseconds for tests."),
        }, ["secret", "timestamp", "signature", "body"]),
    },
    {
        name: "receiz_inspect_proof_object",
        description: `Inspect a provided proof object payload without treating MCP as verifier authority. ${AUTHORITY_DESCRIPTION}`,
        inputSchema: objectSchema({
            value: objectSchema({}, []),
            expectedPrimitive: stringProp("Expected primitive label for agent-side assertion."),
        }, ["value"]),
    },
    {
        name: "receiz_wallet_public_ledger",
        description: `Read public wallet ledger projection. ${AUTHORITY_DESCRIPTION}`,
        inputSchema: objectSchema({
            limit: numberProp("Page limit."),
            cursor: stringProp("Cursor."),
            since: stringProp("ISO timestamp or Kai-aware caller cursor."),
        }),
    },
    {
        name: "receiz_action_ledger",
        description: `Read public action ledger projection. ${AUTHORITY_DESCRIPTION}`,
        inputSchema: objectSchema({
            limit: numberProp("Page limit."),
            cursor: stringProp("Cursor."),
            since: stringProp("ISO timestamp or Kai-aware caller cursor."),
        }),
    },
    {
        name: "receiz_sports_conformance",
        description: `Read Sports conformance status for agents verifying sports proof surfaces. ${AUTHORITY_DESCRIPTION}`,
        inputSchema: objectSchema(),
    },
    {
        name: "receiz_world_public_snapshot",
        description: `Read World public snapshot for app builders. ${AUTHORITY_DESCRIPTION}`,
        inputSchema: objectSchema(),
    },
    {
        name: "receiz_proof_query",
        description: `Run delegated proof query for dashboards and advanced apps. ${AUTHORITY_DESCRIPTION}`,
        inputSchema: objectSchema({
            namespace: stringProp("Proof namespace."),
            tenantHost: stringProp("Tenant host."),
            type: stringProp("Proof object type."),
            customerReceizId: stringProp("Customer Receiz ID."),
            cursor: stringProp("Cursor."),
            limit: numberProp("Page limit."),
        }),
    },
    {
        name: "receiz_sandbox_seed_store",
        description: `Generate deterministic sandbox store state for local app tests. ${AUTHORITY_DESCRIPTION}`,
        inputSchema: objectSchema({
            tenantHost: stringProp("Tenant host."),
            products: numberProp("Number of sandbox products."),
        }, ["tenantHost"]),
    },
    {
        name: "receiz_sandbox_checkout",
        description: `Generate deterministic sandbox checkout outcome for local app tests. ${AUTHORITY_DESCRIPTION}`,
        inputSchema: objectSchema({
            tenantHost: stringProp("Tenant host."),
            amountUsd: stringProp("Checkout amount."),
            outcome: stringProp("success or failure."),
        }, ["tenantHost", "amountUsd"]),
    },
    {
        name: "receiz_runtime_blueprint",
        description: `Return the production Receiz app runtime blueprint for agents. ${AUTHORITY_DESCRIPTION}`,
        inputSchema: objectSchema({
            tenantHost: stringProp("Tenant host."),
            appKind: stringProp("commerce, marketplace, game, rewards, profile, directory, blog, or custom."),
        }),
    },
    {
        name: "receiz_project_inspect",
        description: `Inspect repository integration evidence. Inspection does not verify artifacts. ${AUTHORITY_DESCRIPTION}`,
        inputSchema: objectSchema({ root: stringProp("Explicit repository root."), targetSdkVersion: stringProp("Target SDK version.") }, ["root"]),
    },
    {
        name: "receiz_app_contract_create",
        description: `Create a read-only Receiz app contract proposal. ${AUTHORITY_DESCRIPTION}`,
        inputSchema: objectSchema({ name: stringProp("Application name."), framework: stringProp("nextjs-app-router or framework-neutral."), features: arrayProp("Receiz feature rails.", { type: "string" }) }, ["name"]),
    },
    {
        name: "receiz_app_plan",
        description: `Compile a deterministic read-only integration plan. ${AUTHORITY_DESCRIPTION}`,
        inputSchema: objectSchema({ root: stringProp("Explicit repository root."), targetSdkVersion: stringProp("Target SDK version.") }, ["root"]),
    },
    {
        name: "receiz_app_apply",
        description: `Preview changes; apply only with the exact explicit confirmation digest. ${AUTHORITY_DESCRIPTION}`,
        inputSchema: objectSchema({ root: stringProp("Explicit repository root."), targetSdkVersion: stringProp("Target SDK version."), confirmation: stringProp("Exact preview digest confirming mutation."), dryRun: { type: "boolean", description: "Validate without writing." } }, ["root"]),
    },
    {
        name: "receiz_app_check",
        description: `Check integration conformance without writing. ${AUTHORITY_DESCRIPTION}`,
        inputSchema: objectSchema({ root: stringProp("Explicit repository root."), targetSdkVersion: stringProp("Target SDK version.") }, ["root"]),
    },
    {
        name: "receiz_app_upgrade",
        description: `Plan a version-aware upgrade without rewriting witnessed history. ${AUTHORITY_DESCRIPTION}`,
        inputSchema: objectSchema({ root: stringProp("Explicit repository root."), targetSdkVersion: stringProp("Required target version.") }, ["root", "targetSdkVersion"]),
    },
    {
        name: "receiz_app_explain",
        description: `Explain a repository finding and its authority boundary. ${AUTHORITY_DESCRIPTION}`,
        inputSchema: objectSchema({ root: stringProp("Explicit repository root."), code: stringProp("Finding code."), targetSdkVersion: stringProp("Target SDK version.") }, ["root", "code"]),
    },
    {
        name: "receiz_app_repair",
        description: `Preview deterministic app repairs and apply only with the exact confirmation digest. ${AUTHORITY_DESCRIPTION}`,
        inputSchema: objectSchema({ root: stringProp("Explicit repository root."), targetSdkVersion: stringProp("Target SDK version."), confirmation: stringProp("Exact preview digest."), dryRun: { type: "boolean" } }, ["root"]),
    },
    {
        name: "receiz_proof_trace",
        description: `Trace canonical artifact integrity, ownership, namespace, and prior-head verification. ${AUTHORITY_DESCRIPTION}`,
        inputSchema: objectSchema({ artifactBase64: stringProp("Base64 bytes for canonical verification."), filename: stringProp("Artifact filename."), value: objectSchema() }),
    },
    {
        name: "receiz_webhook_replay",
        description: `Verify and preview a captured webhook replay; exact confirmation is required for idempotent admission. ${AUTHORITY_DESCRIPTION}`,
        inputSchema: objectSchema({ secret: stringProp("Webhook verification secret."), timestamp: stringProp("Signed timestamp."), signature: stringProp("Delivery signature."), body: stringProp("Exact captured body."), idempotencyKey: stringProp("Stable replay key."), confirmation: stringProp("Exact preview digest.") }, ["secret", "timestamp", "signature", "body", "idempotencyKey"]),
    },
    {
        name: "receiz_scope_explain",
        description: `Explain one rail from the canonical capability descriptor. ${AUTHORITY_DESCRIPTION}`,
        inputSchema: objectSchema({ rail: stringProp("Canonical Receiz rail key.") }, ["rail"]),
    },
    {
        name: "receiz_release_qualify",
        description: `Run read-only current v125 conformance and repository inspection evidence. ${AUTHORITY_DESCRIPTION}`,
        inputSchema: objectSchema({ root: stringProp("Explicit repository root."), targetSdkVersion: stringProp("Target SDK version.") }, ["root"]),
    },
    ...[
        ["receiz_architecture_inspect", "Inspect automatically injected constitutional architecture context."],
        ["receiz_domain_scaffold", "Generate a registry-bound domain scaffold proposal without writing."],
        ["receiz_command_scaffold", "Generate a command-only mutation scaffold proposal without writing."],
        ["receiz_law_define", "Validate a constitutional law definition proposal without admitting it."],
        ["receiz_law_explain", "Explain an applicable law and safe alternatives."],
        ["receiz_law_coverage", "Compare applicable laws with supplied coverage evidence."],
        ["receiz_authority_inspect", "Inspect authority profile, tenant requirement, and stronger truth."],
        ["receiz_command_simulate", "Simulate command admission and return a non-mutating permit or explained denial."],
        ["receiz_receipt_replay", "Plan deterministic receipt replay beneath sealed proof authority."],
        ["receiz_history_trace", "Trace causal history with constitutional context."],
        ["receiz_merge_simulate", "Simulate a causal merge without committing state."],
        ["receiz_bypass_scan", "Scan a proposed change for direct writes, history rewrites, and authority bypasses."],
        ["receiz_conformance_run", "Run SDK conformance with constitutional context."],
        ["receiz_release_verify", "Verify release conformance and registry context without publishing."],
        ["receiz_mcp_execute_command", "Plan, confirm, and delegate one allowed command to the configured SDK admission executor."],
        ["receiz_mcp_append_event", "Append only an event carrying an admitted receipt digest through the configured SDK executor."],
        ["receiz_mcp_verify_receipt", "Verify a receipt through the configured independent verification executor."],
        ["receiz_mcp_commit_atomic_projection", "Commit an admitted atomic projection through the configured SDK transaction executor."],
    ].map(([name, description]) => ({
        name: name,
        description: `${description} Constitutional context is injected automatically. ${AUTHORITY_DESCRIPTION}`,
        inputSchema: objectSchema({
            command: stringProp("Command identifier."),
            affectedAsset: stringProp("Affected proof or artifact identity."),
            proposedChange: stringProp("Exact semantic operation or proposed diff."),
            confirmation: stringProp("Exact permit digest returned by the preview."),
            law: stringProp("Law identifier."),
            source: stringProp("Source or diff text to scan."),
            coveredLaws: arrayProp("Law identifiers with test evidence.", { type: "string" }),
            payload: objectSchema(),
        }),
    })),
]);
export function describeReceizMcpCapabilityParity() {
    const sdkClientCapabilityInventory = describeReceizSdkClientCapabilityInventory();
    return Object.freeze({
        schema: "receiz.mcp.sdk-ai-capability-parity.v125",
        releaseVersion: RECEIZ_MCP_CURRENT_RELEASE_VERSION,
        sdkClientCapabilityInventory,
        sdkPublicFunctionInventory: RECEIZ_PUBLIC_SDK_FUNCTION_INVENTORY,
        mcpToolInventory: Object.freeze(RECEIZ_MCP_TOOLS.map(({ name }) => name)),
        v125CapabilityInventory: RECEIZ_V125_CAPABILITY_INVENTORY,
        authority: Object.freeze({
            inventoryIsProofAuthority: false,
            mcpIsProofAuthority: false,
            directToolRequiresExplicitAdapter: true,
            sameRuntimeCustodyMustNotBeSerialized: true,
            strongerTruth: "sealed-receiz-proof-object",
        }),
    });
}
function constitutionalOperationFromArgs(args, kind) {
    const command = stringOrUndefined(args.command);
    const affectedAsset = stringOrUndefined(args.affectedAsset);
    return {
        kind,
        proposedChange: stringOrUndefined(args.proposedChange) ?? kind,
        payload: (args.payload ?? null),
        ...(command ? { command } : {}),
        ...(affectedAsset ? { affectedAsset } : {}),
    };
}
async function executeConstitutionalTool(runtime, args, kind) {
    if (kind === "append-event" || kind === "commit-atomic-projection") {
        return {
            status: "denied",
            code: "V112_TYPED_ARTIFACT_TOOL_REQUIRED",
            safeAlternatives: [
                "receiz_artifact_append_plan",
                "receiz_artifact_transition_seal_and_stage",
                "receiz_artifact_transition_commit",
            ],
            writesPerformed: 0,
            mcpAuthority: false,
            strongerTruth: "sealed-receiz-proof-object",
        };
    }
    const operation = constitutionalOperationFromArgs(args, kind);
    const plan = await runtime.constitutional.plan(operation);
    const confirmation = stringOrUndefined(args.confirmation);
    if (!confirmation || plan.status === "denied")
        return plan;
    return runtime.constitutional.execute(plan, confirmation);
}
const ARTIFACT_RELEASE_BLOCKING_FINDINGS = new Set([
    "artifact_payload_fallback",
    "artifact_domain_parser_bypass",
    "artifact_download_original_on_failure",
    "artifact_manual_blob_relabel",
    "artifact_shape_claimed_verified",
    "artifact_plan_claimed_sealed",
]);
function artifactReleaseBlockers(inspection) {
    return inspection.findings.filter((finding) => ARTIFACT_RELEASE_BLOCKING_FINDINGS.has(finding.code));
}
const TOOL_HANDLERS = {
    receiz_doctor: async ({ runtime, args }) => wrapResult("developer_diagnostics", "receiz.sdk.doctor", await runtime.client.doctor(cleanOptions(args))),
    receiz_capabilities: async ({ runtime, args }) => {
        const clientCapabilityInventory = describeReceizSdkClientCapabilityInventory();
        const distributionParity = describeReceizMcpCapabilityParity();
        if (args.mode === "describe") {
            return wrapResult("developer_capability_description", "receiz.sdk.capabilities.describe", {
                ...describeReceizCapabilities(),
                clientCapabilityInventory,
                distributionParity,
            });
        }
        const probeOptions = { ...args };
        delete probeOptions.mode;
        const readiness = await runtime.client.capabilities(cleanOptions(probeOptions));
        return wrapResult("developer_capability_projection", "receiz.sdk.capabilities.probe", {
            ...(isJsonObject(readiness) ? readiness : { readiness }),
            clientCapabilityInventory,
            distributionParity,
        });
    },
    receiz_required_scopes: ({ runtime, args }) => {
        const rails = stringArray(args.rails);
        const scopes = scopesForRails(runtime, rails);
        return {
            ok: true,
            primitive: "connect_scope_projection",
            source: "receiz.sdk.scope_constants",
            rails,
            scopes,
            constants: Object.fromEntries(rails.map((rail) => [rail, runtime.oidcScopesByRail[rail] ?? []])),
            authority: RECEIZ_MCP_AUTHORITY_BOUNDARY,
        };
    },
    receiz_authorize_url: ({ runtime, args }) => {
        const result = runtime.client.identity.authorizeUrl(args);
        return wrapResult("identity_primitive", "receiz.sdk.identity.authorizeUrl", { ok: true, url: result });
    },
    receiz_mcp_login: ({ runtime, args }) => wrapResult("identity_primitive", "receiz.dashboard.delegated_agent_token", mcpLoginSetup(runtime, args)),
    receiz_ensure_tenant_session: ({ runtime, args }) => wrapResult("identity_primitive", "receiz.sdk.identity.ensureTenantSession", runtime.client.identity.ensureTenantSession(args)),
    receiz_app_state_publish: async ({ runtime, args }) => {
        ensureDelegated(runtime);
        const input = isJsonObject(args.feed) ? args.feed : args;
        const options = pickDefined({ idempotencyKey: stringOrUndefined(args.idempotencyKey), signature: stringOrUndefined(args.signature) });
        return wrapResult("public_app_state_projection", "receiz.sdk.appState.publish", await runtime.client.appState.publish(input, options));
    },
    receiz_app_state_resolve: async ({ runtime, args }) => wrapResult("public_app_state_projection", "receiz.sdk.appState.resolve", await runtime.client.appState.resolve(cleanOptions(args))),
    receiz_app_state_by_url: async ({ runtime, args }) => wrapResult("public_app_state_projection", "receiz.sdk.appState.byUrl", await runtime.client.appState.byUrl(requiredString(args, "url"))),
    receiz_app_state_by_creator: async ({ runtime, args }) => wrapResult("public_app_state_projection", "receiz.sdk.appState.byCreator", await runtime.client.appState.byCreator(requiredString(args, "receizId"))),
    receiz_app_state_by_namespace: async ({ runtime, args }) => wrapResult("public_app_state_projection", "receiz.sdk.appState.byNamespace", await runtime.client.appState.byNamespace(requiredString(args, "namespace"))),
    receiz_app_state_by_id: async ({ runtime, args }) => wrapResult("public_app_state_projection", "receiz.sdk.appState.byId", await runtime.client.appState.byId(requiredString(args, "id"))),
    receiz_public_store_publish: async ({ runtime, args }) => {
        ensureDelegated(runtime);
        const options = pickDefined({ idempotencyKey: stringOrUndefined(args.idempotencyKey) });
        return wrapResult("public_app_state_projection", "receiz.sdk.publicStore.publish", await runtime.client.publicStore.publish(args, options));
    },
    receiz_public_store_resolve: async ({ runtime, args }) => wrapResult("public_app_state_projection", "receiz.sdk.publicStore.resolve", await runtime.client.publicStore.resolve(cleanOptions(args))),
    receiz_inspect_offline_file: ({ args }) => inspectOfflineFile(args),
    receiz_asset_by_url: async ({ runtime, args }) => wrapResult("public_proof_surface", "receiz.sdk.publicProof.byUrl", await runtime.client.publicProof.byUrl(requiredString(args, "url"))),
    receiz_material_url_open: async ({ args }) => {
        const sourceUrls = exactOptionalStringArray(args.sourceUrls, "sourceUrls");
        const opened = await openVerifiedReceizMaterialUrl(requiredString(args, "url"), sourceUrls === undefined ? undefined : { sourceUrls });
        const includePayloadBytes = args.includePayloadBytes === true;
        return wrapResult("sealed_material_proof_object", "receiz.sdk.openVerifiedReceizMaterialUrl", {
            verified: true,
            sealedFilename: opened.sealedFilename,
            sealedMimeType: opened.sealedMimeType,
            sealedArtifactSha256: opened.sealedArtifactSha256,
            payloadFilename: opened.payloadFilename,
            payloadMimeType: opened.payloadMimeType,
            payloadSha256: opened.payloadSha256,
            payloadByteLength: opened.payloadBytes.byteLength,
            playableKind: opened.playableKind,
            canonicalReceizPath: opened.canonicalReceizPath,
            canonicalReceizUrl: opened.canonicalReceizUrl,
            presentationUrl: opened.presentationUrl,
            payloadEncoding: includePayloadBytes ? "base64url" : null,
            ...(includePayloadBytes ? { payloadBytesBase64Url: receizBase64UrlEncode(opened.payloadBytes) } : {}),
            deviceClockIsCreationPulseAuthority: false,
            strongerTruth: "sealed-receiz-proof-object",
        });
    },
    receiz_sealed_kai_moment: async ({ args }) => {
        if (!isJsonObject(args.coordinate))
            throw new TypeError("RECEIZ_SEALED_KAI_COORDINATE_REQUIRED");
        const projection = await projectReceizKksV1SealedProofCoordinate(args.coordinate);
        return wrapResult("sealed_kai_creation_coordinate", "receiz.sdk.projectReceizKksV1SealedProofCoordinate", {
            ...projection.moment,
            kksCoordinate: projection.coordinate,
            deviceClockIsCreationPulseAuthority: false,
        });
    },
    receiz_asset_by_id: async ({ runtime, args }) => wrapResult("public_proof_surface", "receiz.sdk.publicProof.byId", await runtime.client.publicProof.byId(requiredString(args, "id"))),
    receiz_pitch_proof_by_witness_id: async ({ runtime, args }) => {
        const witnessId = requiredString(args, "witnessId");
        const local = args.local ?? args.dayProof ?? args.pitchDayProof ?? null;
        const resolved = await runtime.client.sports.resolvePitchDayProof({ local });
        const witness = findNestedProofObject(resultValue(resolved), ["witnessId", "id", "pitchWitnessId"], witnessId);
        return wrapResult("sports_pitch_proof_witness", "receiz.sdk.sports.resolvePitchDayProof", {
            resolved,
            witnessId,
            witnessFound: witness !== null,
            witness,
        });
    },
    receiz_card_history: async ({ runtime, args }) => {
        const local = args.local ?? args.cardMemory ?? null;
        const resolved = await runtime.client.sports.resolveCardMemory({ local });
        return wrapResult("sports_card_memory", "receiz.sdk.sports.resolveCardMemory", resolved);
    },
    receiz_transfer_preview: ({ args }) => wrapResult("settlement_transfer_preview", "receiz.mcp.deterministic_transfer_preview", transferPreview(args)),
    receiz_transfer_requires_confirmation: ({ args }) => wrapResult("settlement_transfer_confirmation_policy", "receiz.mcp.transfer_confirmation_policy", transferConfirmationPolicy(args)),
    receiz_pack_open_preview: ({ args }) => wrapResult("sports_pack_open_preview", "receiz.mcp.deterministic_pack_open_preview", packOpenPreview(args)),
    receiz_marketplace_template_generate: ({ args }) => wrapResult("marketplace_template_projection", "receiz.mcp.marketplace_template", marketplaceTemplate(args)),
    receiz_webhook_events_catalog: () => wrapResult("webhook_delivery_configuration", "receiz.sdk.webhook_event_catalog", {
        ok: true,
        eventGroups: RECEIZ_WEBHOOK_EVENT_GROUPS,
        eventTypes: RECEIZ_WEBHOOK_EVENT_TYPES,
        presets: RECEIZ_WEBHOOK_EVENT_PRESETS,
        law: "Webhook signatures prove delivery authenticity. Verify the underlying proof object, ownership append, or settlement ledger event before admitting product truth.",
    }),
    receiz_webhook_register_endpoint: async ({ runtime, args }) => {
        ensureDelegated(runtime);
        const input = webhookEndpointCreateInput(args);
        return wrapResult("webhook_delivery_configuration", "receiz.sdk.webhookEndpoints.create", await runtime.client.webhookEndpoints.create(input));
    },
    receiz_webhook_rotate_secret: async ({ runtime, args }) => {
        ensureDelegated(runtime);
        return wrapResult("webhook_delivery_configuration", "receiz.sdk.webhookEndpoints.rotateSecret", await runtime.client.webhookEndpoints.rotateSecret(requiredString(args, "endpointId")));
    },
    receiz_webhook_send_test_event: async ({ runtime, args }) => {
        ensureDelegated(runtime);
        const eventType = stringOrUndefined(args.eventType) ?? "payment.settled";
        return wrapResult("webhook_delivery_configuration", "receiz.sdk.webhookEndpoints.sendTest", await runtime.client.webhookEndpoints.sendTest(requiredString(args, "endpointId"), { eventType }));
    },
    receiz_webhook_receiver_scaffold: ({ args }) => wrapResult("webhook_receiver_scaffold", "receiz.sdk.webhooks.parseRequest", webhookReceiverScaffold(args)),
    receiz_webhook_verify_payload: async ({ runtime, args }) => wrapResult("webhook_delivery_verification", "receiz.sdk.webhooks.verifySignature", await verifyWebhookPayload(runtime, args)),
    receiz_inspect_proof_object: ({ args }) => wrapResult("proof_object_inspection", "local_payload_inspection_beneath_receiz_proof_object", inspectProofObject(args.value, stringOrUndefined(args.expectedPrimitive))),
    receiz_wallet_public_ledger: async ({ runtime, args }) => wrapResult("settlement_projection", "receiz.sdk.wallet.publicLedger", await runtime.client.wallet.publicLedger(cleanOptions(args))),
    receiz_action_ledger: async ({ runtime, args }) => wrapResult("provenance_projection", "receiz.sdk.wallet.actionLedger", await runtime.client.wallet.actionLedger(cleanOptions(args))),
    receiz_sports_conformance: async ({ runtime }) => wrapResult("sports_proof_conformance", "receiz.sdk.sports.conformance", await runtime.client.sports.conformance()),
    receiz_world_public_snapshot: async ({ runtime }) => wrapResult("public_world_projection", "receiz.sdk.world.publicSnapshot", await runtime.client.world.publicSnapshot()),
    receiz_proof_query: async ({ runtime, args }) => {
        ensureDelegated(runtime);
        return wrapResult("proof_object_query_projection", "receiz.sdk.proof.query", await runtime.client.proof.query(cleanOptions(args)));
    },
    receiz_sandbox_seed_store: ({ runtime, args }) => wrapResult("developer_sandbox_projection", "receiz.sdk.sandbox.seedStore", runtime.client.sandbox.seedStore(args)),
    receiz_sandbox_checkout: ({ runtime, args }) => wrapResult("developer_sandbox_projection", "receiz.sdk.sandbox.checkout", runtime.client.sandbox.checkout(args)),
    receiz_runtime_blueprint: ({ args }) => wrapResult("developer_runtime_blueprint", "receiz.mcp.runtime.blueprint", runtimeBlueprint(args)),
    receiz_project_inspect: async ({ args }) => wrapResult("repository_integration_inspection", "receiz.sdk.inspectReceizProject", await inspectReceizProject(projectInput(args))),
    receiz_app_contract_create: ({ args }) => {
        const framework = stringOrUndefined(args.framework) === "framework-neutral" ? "framework-neutral" : "nextjs-app-router";
        const supported = new Set(["identity", "proof", "proofMemory", "publicStore", "commerce", "media", "webhooks", "world"]);
        const features = stringArray(args.features).filter((feature) => supported.has(feature));
        const contract = defineReceizApp({
            schema: "receiz.app.contract.v1",
            name: requiredString(args, "name"),
            framework,
            features: (features.length ? features : ["identity", "proof", "proofMemory"]),
            authority: { mode: "artifact-first", allowDatabaseAuthority: false },
            deployment: { target: framework === "nextjs-app-router" ? "vercel" : "node" },
        });
        return wrapResult("application_contract_proposal", "receiz.sdk.defineReceizApp", { contract, writesPerformed: 0 });
    },
    receiz_app_plan: async ({ args }) => wrapResult("application_integration_plan", "receiz.sdk.planReceizIntegration", await planReceizIntegration(projectInput(args))),
    receiz_app_check: async ({ args }) => wrapResult("application_integration_check", "receiz.sdk.checkReceizIntegration", await checkReceizIntegration(projectInput(args))),
    receiz_app_upgrade: async ({ args }) => {
        const targetSdkVersion = requiredString(args, "targetSdkVersion");
        return wrapResult("application_upgrade_plan", "receiz.sdk.planReceizUpgrade", await planReceizUpgrade({ root: requiredString(args, "root"), targetSdkVersion }));
    },
    receiz_app_explain: async ({ args }) => {
        const inspection = await inspectReceizProject(projectInput(args));
        const code = requiredString(args, "code");
        const selected = inspection.findings.find((item) => item.code === code);
        if (!selected)
            throw new Error(`receiz_finding_not_found:${code}`);
        return wrapResult("application_integration_explanation", "receiz.sdk.explainReceizIntegrationFinding", {
            finding: selected,
            explanation: explainReceizIntegrationFinding(selected),
        });
    },
    receiz_app_apply: async ({ args }) => {
        const inspection = await inspectReceizProject(projectInput(args));
        if (!inspection.contract)
            throw new Error("receiz_app_contract_required");
        const preview = await createReceizIntegrationPreview({ root: inspection.root, contract: inspection.contract, targetSdkVersion: inspection.targetSdkVersion });
        const confirmation = stringOrUndefined(args.confirmation);
        if (!confirmation)
            return wrapResult("application_change_preview", "receiz.sdk.createReceizIntegrationPreview", preview);
        const result = await applyReceizIntegrationPreview({ preview, confirmation, dryRun: args.dryRun === true });
        return wrapResult("application_change_application", "receiz.sdk.applyReceizIntegrationPreview", result);
    },
    receiz_app_repair: async ({ args }) => {
        const inspection = await inspectReceizProject(projectInput(args));
        if (!inspection.contract)
            throw new Error("receiz_app_contract_required");
        const artifactBlockers = artifactReleaseBlockers(inspection);
        if (artifactBlockers.length) {
            return wrapResult("application_repair_blocked", "receiz.sdk.inspectReceizProject", {
                schema: "receiz.integration.repair_blocked.v125",
                releaseBlocked: true,
                applied: false,
                writesPerformed: 0,
                blockingFindings: artifactBlockers,
                requiredRepair: "Remove payload fallback, artifact-as-domain-payload, failure download, and manual artifact repacking before retrying repair.",
            });
        }
        const preview = await createReceizIntegrationPreview({ root: inspection.root, contract: inspection.contract, targetSdkVersion: inspection.targetSdkVersion });
        const confirmation = stringOrUndefined(args.confirmation);
        if (!confirmation)
            return wrapResult("application_repair_preview", "receiz.sdk.createReceizIntegrationPreview", preview);
        return wrapResult("application_repair_application", "receiz.sdk.applyReceizIntegrationPreview", await applyReceizIntegrationPreview({ preview, confirmation, dryRun: args.dryRun === true }));
    },
    receiz_proof_trace: async ({ runtime, args }) => {
        const artifactBase64 = stringOrUndefined(args.artifactBase64);
        if (!artifactBase64) {
            return wrapResult("proof_trace_inspection", "local-inspection-without-verification", {
                verificationPerformed: false,
                inspection: inspectProofObject(args.value),
                steps: [{ check: "artifact_bytes", status: "missing" }],
                authority: RECEIZ_MCP_AUTHORITY_BOUNDARY,
            });
        }
        const verifiedArtifact = await verifyCompleteReceizArtifact(runtime.client, {
            artifactBase64,
            filename: stringOrUndefined(args.filename) ?? "proof.receiz",
            mimeType: stringOrUndefined(args.mimeType) ?? "application/octet-stream",
        });
        const verification = verifiedArtifact.verification;
        const result = isJsonObject(verification) ? verification : {};
        const bundle = isJsonObject(result.bundle) ? result.bundle : {};
        const verified = result.ok === true;
        return wrapResult("proof_trace_verification", "receiz.sdk.verification.verifyArtifact", {
            verificationPerformed: true,
            verified,
            verification,
            steps: [
                { check: "integrity", status: verified ? "passed" : "failed" },
                { check: "owner", status: typeof bundle.ownerReceizId === "string" ? "bound" : "missing", value: bundle.ownerReceizId ?? null },
                { check: "namespace", status: typeof bundle.namespace === "string" ? "bound" : "missing", value: bundle.namespace ?? null },
                { check: "prior_head", status: bundle.priorHeadReference == null ? "root" : "bound", value: bundle.priorHeadReference ?? null },
            ],
        });
    },
    receiz_webhook_replay: async ({ runtime, args }) => {
        const verified = await verifyWebhookPayload(runtime, args);
        if (verified.signatureVerified !== true)
            throw new Error("receiz_webhook_signature_invalid");
        const idempotencyKey = requiredString(args, "idempotencyKey");
        const digest = createHash("sha256").update(JSON.stringify({
            body: requiredString(args, "body"),
            timestamp: requiredString(args, "timestamp"),
            signature: requiredString(args, "signature"),
            idempotencyKey,
        })).digest("hex");
        const confirmation = stringOrUndefined(args.confirmation);
        if (!confirmation)
            return wrapResult("webhook_replay_preview", "receiz.sdk.webhooks.verifySignature", { digest, confirmationRequired: true, signatureVerified: true, idempotencyKey, writesPerformed: 0 });
        if (confirmation !== digest)
            throw new Error("receiz_webhook_replay_confirmation_invalid");
        const duplicate = runtime.webhookReplayIds.has(idempotencyKey);
        runtime.webhookReplayIds.add(idempotencyKey);
        return wrapResult("webhook_replay_admission", "receiz.sdk.webhooks.verifySignature", { digest, admittedForReplay: !duplicate, duplicate, signatureVerified: true, idempotencyKey });
    },
    receiz_scope_explain: ({ args }) => {
        const rail = requiredString(args, "rail");
        const descriptor = describeReceizCapabilities();
        const selected = descriptor.rails.find((candidate) => candidate.key === rail);
        if (!selected)
            throw new Error(`receiz_capability_rail_unknown:${rail}`);
        return wrapResult("connect_scope_explanation", "receiz.sdk.capabilities.describe", selected);
    },
    receiz_release_qualify: async ({ args }) => {
        const inspection = await inspectReceizProject(projectInput(args));
        const report = await runReceizConformance();
        const blockingFindings = inspection.findings.filter((finding) => finding.disposition !== "satisfied");
        return wrapResult("release_qualification", "receiz.sdk.runReceizConformance", {
            report,
            inspection,
            qualified: blockingFindings.length === 0,
            releaseBlocked: blockingFindings.length > 0,
            blockingFindings,
            artifactBlockingFindings: artifactReleaseBlockers(inspection),
            writesPerformed: 0,
        });
    },
    receiz_architecture_inspect: ({ runtime }) => ({ ok: true, primitive: "constitutional_architecture", context: runtime.constitutional.context, writesPerformed: 0 }),
    receiz_domain_scaffold: ({ runtime, args }) => ({
        ok: true, primitive: "constitutional_domain_scaffold", context: runtime.constitutional.context, writesPerformed: 0,
        implementationContract: { domain: stringOrUndefined(args.domain) ?? null, allowedMutations: ["receiz-command-admission"], forbiddenOperations: runtime.constitutional.context.forbiddenMutations, requiredEvidence: runtime.constitutional.context.requiredVerification },
    }),
    receiz_command_scaffold: ({ runtime, args }) => ({
        ok: true, primitive: "constitutional_command_scaffold", context: runtime.constitutional.context, writesPerformed: 0,
        command: stringOrUndefined(args.command) ?? null, executionBoundary: "configured-sdk-admission-executor",
    }),
    receiz_law_define: ({ runtime, args }) => ({
        ok: typeof args.law === "string" && args.law.length > 0, primitive: "constitutional_law_proposal", context: runtime.constitutional.context,
        law: args.law ?? null, admissionPerformed: false, requiredVerification: runtime.constitutional.context.requiredVerification,
    }),
    receiz_law_explain: ({ runtime, args }) => {
        const law = requiredString(args, "law");
        const applicable = runtime.constitutional.context.applicableLaws.includes(law);
        return { ok: applicable, primitive: "constitutional_law_explanation", law, applicable, context: runtime.constitutional.context, safeAlternatives: applicable ? ["command.simulate", "law.coverage", "request-explicit-escalation"] : ["law.define"] };
    },
    receiz_law_coverage: ({ runtime, args }) => {
        const covered = new Set(stringArray(args.coveredLaws));
        const missing = runtime.constitutional.context.applicableLaws.filter((law) => !covered.has(law));
        return { ok: missing.length === 0, primitive: "constitutional_law_coverage", covered: [...covered].sort(), missing, context: runtime.constitutional.context };
    },
    receiz_authority_inspect: ({ runtime }) => ({ ok: true, primitive: "constitutional_authority_boundary", authorityBoundary: runtime.constitutional.context.authorityBoundary, context: runtime.constitutional.context, writesPerformed: 0 }),
    receiz_command_simulate: ({ runtime, args }) => runtime.constitutional.plan(constitutionalOperationFromArgs({ ...args, proposedChange: stringOrUndefined(args.proposedChange) ?? "simulate admitted command" }, "execute-command")),
    receiz_receipt_replay: ({ runtime, args }) => ({ ok: true, primitive: "deterministic_receipt_replay_plan", payload: args.payload ?? null, context: runtime.constitutional.context, writesPerformed: 0 }),
    receiz_history_trace: ({ runtime, args }) => ({ ok: true, primitive: "causal_history_trace", payload: args.payload ?? null, context: runtime.constitutional.context, writesPerformed: 0 }),
    receiz_merge_simulate: ({ runtime, args }) => ({ ok: true, primitive: "causal_merge_simulation", payload: args.payload ?? null, context: runtime.constitutional.context, writesPerformed: 0 }),
    receiz_bypass_scan: ({ runtime, args }) => ({ ...scanReceizAuthorityBypass(requiredString(args, "source")), context: runtime.constitutional.context }),
    receiz_conformance_run: async ({ runtime }) => ({ primitive: "constitutional_conformance", report: await runReceizConformance(), context: runtime.constitutional.context, writesPerformed: 0 }),
    receiz_release_verify: async ({ runtime }) => ({
        primitive: "constitutional_release_verification",
        report: await runReceizConformance(),
        registryDigest: runtime.constitutional.context.registryDigest,
        coordinatedIdentity: RECEIZ_MCP_CURRENT_RELEASE_IDENTITY,
        context: runtime.constitutional.context,
        writesPerformed: 0,
    }),
    receiz_mcp_execute_command: ({ runtime, args }) => executeConstitutionalTool(runtime, args, "execute-command"),
    receiz_mcp_append_event: ({ runtime, args }) => executeConstitutionalTool(runtime, args, "append-event"),
    receiz_mcp_verify_receipt: ({ runtime, args }) => executeConstitutionalTool(runtime, args, "verify-receipt"),
    receiz_mcp_commit_atomic_projection: ({ runtime, args }) => executeConstitutionalTool(runtime, args, "commit-atomic-projection"),
};
/** Host-owned exposure boundary; this never grants proof or signing authority. */
export const RECEIZ_PHI_EXECUTION_TOOL_NAMES = Object.freeze([
    "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 phiExecutionRuntimes = new WeakSet();
const marketplaceExecutionRuntimes = new WeakSet();
const nonfinancialExecutionRuntimes = new WeakSet();
export function createReceizMcpRuntime(options = {}) {
    if (options.executionProfile !== undefined && options.executionProfile !== "phi-only" && options.executionProfile !== "marketplace-phi" && options.executionProfile !== "marketplace-nonfinancial") {
        throw new TypeError("RECEIZ_MCP_EXECUTION_PROFILE_INVALID");
    }
    const phiOnly = options.executionProfile === "phi-only";
    const marketplacePhi = options.executionProfile === "marketplace-phi";
    const marketplaceNonfinancial = options.executionProfile === "marketplace-nonfinancial";
    const localCustody = options.localCustody === undefined ? undefined : Object.freeze({
        directory: options.localCustody.directory,
        workspace: options.localCustody.workspace,
        identity: options.localCustody.identity === null ? null : Object.freeze({ ...options.localCustody.identity }),
        ...(options.localCustody.identityAdmitted === true ? { identityAdmitted: true } : {}),
    });
    if (localCustody && (typeof localCustody.directory !== "string" || !isAbsolute(localCustody.directory)
        || typeof localCustody.workspace !== "string" || !isAbsolute(localCustody.workspace)
        || (localCustody.identity !== null && (typeof localCustody.identity.artifactPath !== "string"
            || !isAbsolute(localCustody.identity.artifactPath))))) {
        throw new TypeError("RECEIZ_MCP_LOCAL_CUSTODY_REQUIRED");
    }
    // Explicit custody is a host boundary: process credentials and compatibility
    // switches must not silently become this runtime's caller configuration.
    const baseUrl = options.baseUrl ?? (localCustody ? "https://receiz.com" : process.env.RECEIZ_BASE_URL ?? process.env.NEXT_PUBLIC_APP_URL ?? "https://receiz.com");
    const legacyConnectTransport = options.legacyConnectTransport ?? (localCustody ? undefined : process.env.RECEIZ_LEGACY_CONNECT_TRANSPORT);
    if (legacyConnectTransport !== undefined && legacyConnectTransport !== "http")
        throw new TypeError("RECEIZ_LEGACY_CONNECT_TRANSPORT_INVALID");
    const applicationId = options.applicationId ?? (localCustody ? undefined : process.env.RECEIZ_APPLICATION_ID);
    const accessToken = options.accessToken ?? (localCustody ? undefined : process.env.RECEIZ_ACCESS_TOKEN ?? process.env.RECEIZ_CONNECT_ACCESS_TOKEN);
    const configuredClient = options.client ?? createReceizClient({
        baseUrl,
        ...(legacyConnectTransport ? { legacyConnectTransport } : {}),
        ...(options.fetch ? { fetchImpl: options.fetch } : {}),
        ...(options.subjectRuntime ? { subjectRuntime: options.subjectRuntime } : {}),
        ...(applicationId ? { applicationId } : {}),
        ...(accessToken ? { accessToken } : {}),
    });
    const client = marketplacePhi ? wrapReceizMarketplaceClient(configuredClient) : configuredClient;
    const constitutional = createReceizConstitutionalRuntime({
        context: options.constitutionalContext ?? RECEIZ_DEFAULT_CONSTITUTIONAL_CONTEXT,
        executor: options.constitutionalExecutor ?? (async () => { throw new Error("MCP_SDK_EXECUTOR_REQUIRED"); }),
    });
    const globalReconciliationDomain = options.accessToken && "coordination" in client
        ? client.coordination.remoteDomain({
            namespace: "receiz",
            commitDomain: RECEIZ_V113_GLOBAL_COMMIT_DOMAIN,
        })
        : null;
    const runtime = {
        ...(localCustody ? { localCustody } : {}),
        ...(options.offlineSealer ? { offlineSealer: options.offlineSealer } : {}),
        client,
        ...(options.subjectRuntime ? { subjectRuntime: options.subjectRuntime } : {}),
        baseUrl,
        ...(applicationId ? { applicationId } : {}),
        ...(accessToken ? { accessToken } : {}),
        ...(options.resolveV124Material ? { resolveV124Material: options.resolveV124Material } : {}),
        ...(options.persistV124Material ? { persistV124Material: options.persistV124Material } : {}),
        ...(options.resolveV125ProofReference ? { resolveV125ProofReference: options.resolveV125ProofReference } : {}),
        ...(options.executeV125TrustOperation ? { executeV125TrustOperation: options.executeV125TrustOperation } : {}),
        ...(options.fetch ? { fetch: options.fetch } : {}),
        oidcScopesByRail: options.oidcScopesByRail ?? RECEIZ_OIDC_SCOPES_BY_RAIL,
        webhookReplayIds: new Set(),
        constitutional,
        operations: createReceizMcpOperations(client, { ...options, globalReconciliationDomain, localSubjectRuntime: options.subjectRuntime }),
    };
    if (phiOnly)
        phiExecutionRuntimes.add(runtime);
    if (marketplacePhi)
        marketplaceExecutionRuntimes.add(runtime);
    if (marketplaceNonfinancial)
        nonfinancialExecutionRuntimes.add(runtime);
    return runtime;
}
const v127SubjectOperations = new WeakMap();
const v127SdkOperations = new WeakMap();
export async function callReceizTool(runtime, name, args = {}) {
    if (nonfinancialExecutionRuntimes.has(runtime)) {
        try {
            assertReceizMarketplaceNonfinancialTool(name);
        }
        catch (error) {
            return toolError(errorCode(error), errorMessage(error), { name, authority: RECEIZ_MCP_AUTHORITY_BOUNDARY }, error);
        }
    }
    if (marketplaceExecutionRuntimes.has(runtime)) {
        try {
            assertReceizMarketplaceToolCall(name, args);
        }
        catch (error) {
            return toolError(errorCode(error), errorMessage(error), { name, authority: RECEIZ_MCP_AUTHORITY_BOUNDARY }, error);
        }
    }
    if (phiExecutionRuntimes.has(runtime)) {
        if (!RECEIZ_PHI_EXECUTION_TOOL_NAMES.includes(name)) {
            return toolError("tool_not_enabled", "This device execution channel exposes only the explicit Phi lifecycle tools.");
        }
        const descriptor = RECEIZ_MCP_TOOLS.find(tool => tool.name === name);
        const properties = descriptor.inputSchema.properties;
        if (!args || typeof args !== "object" || Array.isArray(args)
            || Object.keys(args).some(key => !Object.hasOwn(properties, key))) {
            return toolError("invalid_arguments", "Arguments must match the exact Phi tool schema.");
        }
    }
    if (name === RECEIZ_DEVICE_AI_SUBJECT_TOOL.name) {
        try {
            return toolJson(await callReceizMcpDeviceAiSubjectCreate(runtime, args));
        }
        catch (error) {
            return toolError(errorCode(error), errorMessage(error), { name, authority: RECEIZ_MCP_AUTHORITY_BOUNDARY }, error);
        }
    }
    if (RECEIZ_V127_SUBJECT_TOOLS.some(tool => tool.name === name)) {
        try {
            let operations = v127SubjectOperations.get(runtime);
            if (!operations) {
                operations = createReceizV127SubjectOperations({ runtime: runtime.subjectRuntime,
                    resolveSource: (path) => resolveReceizV127SubjectWorkspaceSource(path, runtime.localCustody?.workspace),
                    resolveSourceReference: (reference) => resolveReceizV127SubjectReferenceSource(reference, runtime.localCustody?.workspace) });
                v127SubjectOperations.set(runtime, operations);
            }
            return toolJson(await operations.call(name, asJsonObject(args)));
        }
        catch (error) {
            return toolError(errorCode(error), errorMessage(error), { name, authority: RECEIZ_MCP_AUTHORITY_BOUNDARY }, error);
        }
    }
    if (RECEIZ_V127_SDK_TOOLS.some(tool => tool.name === name)) {
        try {
            let operations = v127SdkOperations.get(runtime);
            if (!operations) {
                operations = createReceizV127SdkOperations({ client: runtime.client, ensureDelegated: () => ensureDelegated(runtime),
                    ...(marketplaceExecutionRuntimes.has(runtime) ? { executionProfile: "marketplace-phi" } : {}),
                    ...(nonfinancialExecutionRuntimes.has(runtime) ? { executionProfile: "marketplace-nonfinancial" } : {}) });
                v127SdkOperations.set(runtime, operations);
            }
            return toolJson(await operations.call(name, asJsonObject(args)));
        }
        catch (error) {
            return toolError(errorCode(error), errorMessage(error), { name, authority: RECEIZ_MCP_AUTHORITY_BOUNDARY }, error);
        }
    }
    if (name === RECEIZ_VERIFY_UPLOADED_ARTIFACT_TOOL.name) {
        try {
            return toolJson(await verifyUploadedArtifact(args, { fetch: runtime.fetch }));
        }
        catch (error) {
            const failure = error instanceof ArtifactInputError ? error : new ArtifactInputError("artifact_verification_unavailable", "canonical_verification");
            return toolError(failure.code, "Unable to obtain an artifact verification verdict.", { stage: failure.stage, verdictObtained: false, mcpAuthority: false });
        }
    }
    if (name === "receiz_offline_crystal_append" || name === "receiz_offline_crystal_open") {
        try {
            const input = asJsonObject(args);
            const workspace = runtime.localCustody?.workspace ?? process.env.RECEIZ_OFFLINE_WORKSPACE ?? process.cwd();
            if (name === "receiz_offline_crystal_open") {
                if (Object.keys(input).length !== 1 || typeof input.crystalReference !== "string")
                    throw Error("crystal_arguments_invalid");
                return toolJson(await openReceizOfflineCrystalReference(input.crystalReference, workspace));
            }
            if (Object.keys(input).some(key => !["sourceReference", "predecessorReference"].includes(key))
                || typeof input.sourceReference !== "string" || (input.predecessorReference !== undefined && typeof input.predecessorReference !== "string"))
                throw Error("crystal_arguments_invalid");
            const result = await appendReceizOfflineCrystal(input, { ...runtime.localCustody, workspace, ...(runtime.offlineSealer ? { sealer: runtime.offlineSealer } : {}),
                ...(runtime.fetch ? { fetch: runtime.fetch } : {}) });
            return { ...toolJson(result), structuredContent: result,
                _meta: { "receiz/sealedTransfer": { token: registerReceizSealedOutput(runtime, result.artifactReference, result.artifactSha256) } } };
        }
        catch {
            return toolError("crystal_operation_failed", "The exact source, predecessor, KKS coordinate or canonical seal could not be admitted.");
        }
    }
    if (name === "receiz_offline_artifact_chunk") {
        try {
            const chunk = await readReceizSealedOutputChunk(args, runtime.localCustody?.workspace ?? process.env.RECEIZ_OFFLINE_WORKSPACE ?? process.cwd(), runtime);
            const appOnlyReferenceHandoff = typeof args?.artifactReference === "string";
            return { content: [{ type: "text", text: "Verified sealed proof segment available to the Receiz component." }],
                structuredContent: appOnlyReferenceHandoff ? { ...chunk.public, ...chunk.private } : chunk.public,
                _meta: { "receiz/sealedChunk": chunk.private } };
        }
        catch {
            return toolError("sealed_output_unavailable", "The exact sealed proof could not be reopened on the connected device.");
        }
    }
    if (RECEIZ_OFFLINE_SEAL_TOOLS.some(tool => tool.name === name)) {
        try {
            const result = await callReceizOfflineSealTool(name, args, { ...runtime.localCustody, ...(runtime.offlineSealer ? { sealer: runtime.offlineSealer } : {}), ...(runtime.fetch ? { fetch: runtime.fetch } : {}) });
            if (name === "receiz_offline_seal_file") {
                const output = result;
                if (!output.artifactReference || !output.artifactSha256)
                    throw Error("sealed_output_reference_missing");
                return { ...toolJson(result), structuredContent: result,
                    _meta: { "receiz/sealedTransfer": { token: registerReceizSealedOutput(runtime, output.artifactReference, output.artifactSha256) } } };
            }
            return toolJson(result);
        }
        catch (error) {
            if (name === "receiz_offline_seal_file" && error instanceof ArtifactInputError) {
                return toolError(error.code, "Unable to retrieve the selected original file.", { stage: error.stage, proofObjectCreated: false, mcpAuthority: false });
            }
            if (name === "receiz_offline_verify_file") {
                const code = error instanceof Error && error.message === "offline_seal_path_outside_workspace"
                    ? "workspace_file_access_denied" : "workspace_file_unavailable";
                const failure = error instanceof ArtifactInputError ? error : new ArtifactInputError(code, "file_reading");
                return toolError(failure.code, "Unable to obtain an artifact verification verdict.", { stage: failure.stage, verdictObtained: false, mcpAuthority: false });
            }
            return toolError("offline_seal_failed", "Offline sealing failed; check local enrollment, resource integrity, input and output paths.");
        }
    }
    if (RECEIZ_V125_TRUST_MCP_TOOL_NAMES.includes(name)) {
        try {
            return toolJson(await callReceizV125TrustMcpOperation({
                name,
                args: asJsonObject(args),
                host: runtime.executeV125TrustOperation,
                runtimeScope: { client: runtime.client, applicationAudience: runtime.applicationId ?? null },
            }));
        }
        catch (error) {
            const code = safeV125McpErrorCode(error);
            const safeError = new ReceizMcpError(code, code);
            return toolError(code, code, {
                name,
                authority: RECEIZ_MCP_AUTHORITY_BOUNDARY,
                cause: { name: "ReceizV125TrustMcpOperationError", code },
            }, safeError);
        }
    }
    if (RECEIZ_V125_MCP_TOOL_NAMES.includes(name)) {
        try {
            const result = await callReceizV125McpOperation(name, asJsonObject(args), {
                baseUrl: runtime.baseUrl,
                applicationId: runtime.applicationId,
                accessToken: runtime.accessToken,
                materialClient: runtime.client,
                resolveMaterial: runtime.resolveV124Material,
                persistMaterial: runtime.persistV124Material,
                resolveProofReference: runtime.resolveV125ProofReference,
                fetch: runtime.fetch,
            });
            return { ...toolJson(result), ...(result && typeof result === "object" && "ok" in result && result.ok === false ? { isError: true } : {}) };
        }
        catch (error) {
            const code = safeV125McpErrorCode(error);
            const safeError = new ReceizMcpError(code, code);
            return toolError(code, code, {
                name,
                authority: RECEIZ_MCP_AUTHORITY_BOUNDARY,
                cause: { name: "ReceizV125McpOperationError", code },
            }, safeError);
        }
    }
    if (RECEIZ_V124_MCP_TOOL_NAMES.includes(name)) {
        try {
            return toolJson(await callReceizV124McpOperation(runtime.client, name, asJsonObject(args), {
                applicationId: runtime.applicationId,
                requirePinnedApplicationId: true,
                requireReferenceMaterials: true,
                resolveMaterial: runtime.resolveV124Material,
                persistMaterial: runtime.persistV124Material,
            }));
        }
        catch (error) {
            const code = safeV124McpErrorCode(error);
            const safeError = new ReceizMcpError(code, code);
            return toolError(code, code, {
                name,
                authority: RECEIZ_MCP_AUTHORITY_BOUNDARY,
                cause: { name: "ReceizV124McpOperationError", code },
            }, safeError);
        }
    }
    if (RECEIZ_V123_MCP_TOOL_NAMES.includes(name)) {
        try {
            return toolJson(await callReceizV123McpOperation(runtime.client, name, asJsonObject(args)));
        }
        catch (error) {
            return toolError(errorCode(error), errorMessage(error), { name, authority: RECEIZ_MCP_AUTHORITY_BOUNDARY, cause: errorPayload(error) }, error);
        }
    }
    if (RECEIZ_V122_MCP_TOOL_NAMES.includes(name)) {
        try {
            return toolJson(await callReceizV122McpOperation(runtime.client, name, asJsonObject(args)));
        }
        catch (error) {
            return toolError(errorCode(error), errorMessage(error), { name, authority: RECEIZ_MCP_AUTHORITY_BOUNDARY, cause: errorPayload(error) }, error);
        }
    }
    if (runtime.operations.has(name)) {
        try {
            if (runtime.operations.requiresDelegated(name))
                ensureDelegated(runtime);
            return toolJson(await runtime.operations.call(name, asJsonObject(args)));
        }
        catch (error) {
            return toolError(errorCode(error), errorMessage(error), { name, authority: RECEIZ_MCP_AUTHORITY_BOUNDARY, cause: errorPayload(error) }, error);
        }
    }
    const handler = TOOL_HANDLERS[name];
    if (!handler) {
        return toolError("unknown_tool", `Unknown Receiz MCP tool: ${name}`, { name });
    }
    try {
        const payload = await handler({ runtime, args: asJsonObject(args) });
        const codingTool = name.startsWith("receiz_app_")
            || name === "receiz_project_inspect"
            || name === "receiz_runtime_blueprint"
            || name.includes("scaffold")
            || name.startsWith("receiz_mcp_")
            || ["receiz_architecture_inspect", "receiz_law_define", "receiz_law_explain", "receiz_law_coverage", "receiz_authority_inspect", "receiz_command_simulate", "receiz_bypass_scan"].includes(name);
        const contextualPayload = codingTool && isJsonObject(payload)
            ? { ...payload, constitutionalContext: runtime.constitutional.context }
            : payload;
        return toolJson(contextualPayload);
    }
    catch (error) {
        return toolError(errorCode(error), errorMessage(error), {
            name,
            authority: RECEIZ_MCP_AUTHORITY_BOUNDARY,
            cause: errorPayload(error),
        }, error);
    }
}
export async function handleReceizMcpMessage(message, runtime = createReceizMcpRuntime()) {
    if (message.id === undefined) {
        return null;
    }
    if (message.method === "initialize") {
        return response(message.id, {
            protocolVersion: protocolVersion(message.params),
            capabilities: { tools: {}, resources: {} },
            serverInfo: {
                name: "@receiz/mcp-server",
                version: RECEIZ_MCP_CURRENT_RELEASE_VERSION,
            },
            authority: RECEIZ_MCP_AUTHORITY_BOUNDARY,
        });
    }
    if (message.method === "ping") {
        return response(message.id, {});
    }
    if (message.method === "tools/list") {
        const tools = nonfinancialExecutionRuntimes.has(runtime)
            ? RECEIZ_MCP_TOOLS.filter(tool => isReceizMarketplaceNonfinancialTool(tool.name))
            : phiExecutionRuntimes.has(runtime)
                ? RECEIZ_MCP_TOOLS.filter(tool => RECEIZ_PHI_EXECUTION_TOOL_NAMES.includes(tool.name))
                : RECEIZ_MCP_TOOLS;
        return response(message.id, { tools });
    }
    if (message.method === "resources/templates/list") {
        return response(message.id, { resourceTemplates: phiExecutionRuntimes.has(runtime) ? [] : RECEIZ_MCP_RESOURCE_TEMPLATES });
    }
    if (message.method === "resources/list") {
        return response(message.id, { resources: [
                ...(phiExecutionRuntimes.has(runtime) ? [] : [RECEIZ_SEALED_OUTPUT_RESOURCE]),
                ...(deviceIdentityContextShared(runtime) ? [DEVICE_IDENTITY_CONTEXT_RESOURCE] : []),
            ] });
    }
    if (message.method === "resources/read") {
        const params = asJsonObject(message.params);
        const uri = requiredString(params, "uri");
        if (phiExecutionRuntimes.has(runtime) && uri !== DEVICE_IDENTITY_CONTEXT_URI) {
            return errorResponse(message.id, -32002, "Resource is not enabled for this execution channel.");
        }
        if (uri === DEVICE_IDENTITY_CONTEXT_URI && !deviceIdentityContextShared(runtime)) {
            return errorResponse(message.id, -32002, "Receiz Identity Seal context requires local user consent.");
        }
        if (uri === RECEIZ_SEALED_OUTPUT_URI)
            return response(message.id, { contents: [{ uri,
                        mimeType: "text/html;profile=mcp-app", text: RECEIZ_SEALED_OUTPUT_HTML,
                        _meta: { ui: { prefersBorder: true } } }] });
        return response(message.id, await readReceizMcpResource(runtime, uri));
    }
    if (message.method === "tools/call") {
        const params = asJsonObject(message.params);
        const name = requiredString(params, "name");
        const args = params.arguments ?? {};
        return response(message.id, await callReceizTool(runtime, name, args));
    }
    return errorResponse(message.id, -32601, `Unknown MCP method: ${message.method}`);
}
export function parseReceizMcpToolResult(result) {
    const text = result.content[0]?.text ?? "{}";
    return asJsonObject(JSON.parse(text));
}
function wrapResult(primitive, source, result) {
    return {
        ok: true,
        primitive,
        source,
        result,
        authority: RECEIZ_MCP_AUTHORITY_BOUNDARY,
    };
}
function inspectProofObject(value, expectedPrimitive) {
    const record = isJsonObject(value) ? value : {};
    const schema = stringOrUndefined(record.schema);
    const kind = stringOrUndefined(record.kind);
    const id = stringOrUndefined(record.id) ?? stringOrUndefined(record.receizId) ?? stringOrUndefined(record.proofId);
    const sourceUrl = stringOrUndefined(record.sourceUrl) ?? stringOrUndefined(record.verifyUrl);
    const hasPayload = isJsonObject(record.payload) || isJsonObject(record.data) || isJsonObject(record.record);
    const hasIntegrity = Boolean(record.proof) ||
        Boolean(record.signature) ||
        Boolean(record.proofHash) ||
        Boolean(record.payloadHashSha256) ||
        Boolean(record.merkleRootSha256) ||
        Boolean(record.merkle_root_sha256) ||
        Boolean(record.archiveSha256Hex) ||
        Boolean(record.archive_sha256_hex);
    return {
        ok: true,
        schema: schema ?? null,
        kind: kind ?? null,
        id: id ?? null,
        sourceUrl: sourceUrl ?? null,
        expectedPrimitive: expectedPrimitive ?? null,
        inferredPrimitive: inferPrimitive(record),
        hasPayload,
        hasIntegrityMaterial: hasIntegrity,
        authority: RECEIZ_MCP_AUTHORITY_BOUNDARY,
    };
}
function inferPrimitive(record) {
    const schema = `${record.schema ?? ""}`.toLowerCase();
    const kind = `${record.kind ?? ""}`.toLowerCase();
    if (schema.includes("wallet") || schema.includes("settlement"))
        return "settlement_projection";
    if (schema.includes("identity") || kind.includes("identity"))
        return "identity_primitive";
    if (schema.includes("sports"))
        return "sports_proof_object";
    if (schema.includes("store") || schema.includes("app.public"))
        return "public_app_state_projection";
    if (schema.includes("proof") || kind.includes("proof"))
        return "proof_object";
    return "unknown_receiz_projection";
}
function runtimeBlueprint(args) {
    const tenantHost = stringOrUndefined(args.tenantHost) ?? "<tenant-host>";
    const appKind = stringOrUndefined(args.appKind) ?? "custom";
    return {
        ok: true,
        schema: "receiz.mcp.runtime_blueprint.v1",
        tenantHost,
        appKind,
        law: "Use known verified truth first. Ask Receiz only for verified additions after the known head. MCP is agent tooling, not authority.",
        firstPaint: [
            "Resolve durable public app-state by tenant host or URL.",
            "Render the stored proof projection immediately.",
            "Append verified additions in the background without replacing known truth.",
        ],
        buildRails: [
            "identity.ensureTenantSession for tenant customer login and restore",
            "publicStore.resolve for cold-start storefront recovery",
            "publicStore.publish after admin save",
            "appState.byUrl/byCreator/byNamespace/byId for projection reads",
            "doctor/capabilities/required_scopes for setup diagnostics",
            "wallet/action ledger and proof query for dashboards",
            "sandbox helpers for deterministic local tests",
            "webhook endpoint registration, receiver verification, and signed test deliveries for developer automations",
        ],
        requiredScopes: scopesForRails({ oidcScopesByRail: RECEIZ_OIDC_SCOPES_BY_RAIL }, ["identity", "publicStore", "customers", "merchants", "commerce", "wallet", "webhooks"]),
    };
}
function webhookEndpointCreateInput(args) {
    const explicitEventTypes = stringArray(args.eventTypes);
    const preset = stringOrUndefined(args.preset);
    const presetEvents = preset ? webhookPresetEvents(preset) : [];
    const eventTypes = explicitEventTypes.length > 0 ? explicitEventTypes : presetEvents.length > 0 ? presetEvents : RECEIZ_WEBHOOK_EVENT_PRESETS.payment;
    return pickDefined({
        label: requiredString(args, "label"),
        url: requiredString(args, "url"),
        eventTypes,
        idempotencyKey: stringOrUndefined(args.idempotencyKey),
    });
}
function webhookPresetEvents(preset) {
    const key = preset.trim();
    if (key === "payment")
        return [...RECEIZ_WEBHOOK_EVENT_PRESETS.payment];
    if (key === "commerce")
        return [...RECEIZ_WEBHOOK_EVENT_PRESETS.commerce];
    if (key === "proofSettlement" || key === "proof-settlement")
        return [...RECEIZ_WEBHOOK_EVENT_PRESETS.proofSettlement];
    if (key === "everything" || key === "all")
        return [...RECEIZ_WEBHOOK_EVENT_PRESETS.everything];
    return [];
}
function webhookReceiverScaffold(args) {
    const secretEnv = stringOrUndefined(args.secretEnv) ?? "RECEIZ_WEBHOOK_SECRET";
    const framework = stringOrUndefined(args.framework) ?? "nextjs";
    const nextJsRoute = `import { parseReceizWebhookRequest, routeReceizWebhookEvent } from "@receiz/sdk";

export async function POST(request: Request) {
  const parsed = await parseReceizWebhookRequest(request, {
    secret: process.env.${secretEnv}!,
    toleranceSeconds: 300,
  });

  await routeReceizWebhookEvent(parsed.event, {
    "payment.settled": async (event) => {
      // Webhook delivery is authentic here. Now verify the underlying proof object, ownership append, or settlement ledger event before admitting product truth.
      return event;
    },
    default: async (event) => event,
  });

  return Response.json({ ok: true });
}`;
    return {
        ok: true,
        schema: "receiz.mcp.webhook_receiver_scaffold.v1",
        framework,
        secretEnv,
        nextJsRoute,
        processingOrder: [
            "Read the raw request body through parseReceizWebhookRequest.",
            "Verify x-receiz-signature with x-receiz-timestamp.",
            "Assert receiz.webhook_event.v1.",
            "Verify the underlying proof object, ownership append, or settlement ledger event before admitting product truth.",
        ],
    };
}
async function verifyWebhookPayload(runtime, args) {
    const secret = requiredString(args, "secret");
    const timestamp = requiredString(args, "timestamp");
    const signature = requiredString(args, "signature");
    const body = requiredString(args, "body");
    const toleranceSeconds = typeof args.toleranceSeconds === "number" ? args.toleranceSeconds : undefined;
    const nowMs = typeof args.nowMs === "number" ? args.nowMs : undefined;
    const signatureVerified = await runtime.client.webhooks.verifySignature(pickDefined({
        secret,
        timestamp,
        signature,
        body,
        toleranceSeconds,
        nowMs,
    }));
    const event = signatureVerified ? assertReceizWebhookEvent(JSON.parse(body)) : null;
    return {
        ok: signatureVerified,
        signatureVerified,
        event,
        law: "Webhook signature verification proves delivery authenticity only. Verify the underlying proof object, ownership append, or settlement ledger event before admitting product truth.",
    };
}
function mcpLoginSetup(runtime, args) {
    const appName = stringOrUndefined(args.appName) ?? "Codex local dev";
    const clientId = stringOrUndefined(args.clientId) ?? "<receiz-app-client-id>";
    const tenantHost = stringOrUndefined(args.tenantHost) ?? null;
    const redirectUri = stringOrUndefined(args.redirectUri);
    const codeChallenge = stringOrUndefined(args.codeChallenge);
    const codeChallengeMethod = stringOrUndefined(args.codeChallengeMethod) ?? "S256";
    const state = stringOrUndefined(args.state);
    const requiredScopes = allKnownOidcScopes(runtime);
    const baseUrl = runtime.baseUrl.replace(/\/+$/, "");
    const canBuildAuthorizeUrl = Boolean(redirectUri && codeChallenge && !clientId.startsWith("<"));
    const authorizeUrl = canBuildAuthorizeUrl
        ? runtime.client.identity.authorizeUrl({
            clientId,
            redirectUri,
            codeChallenge,
            codeChallengeMethod,
            scope: requiredScopes,
            ...(state ? { state } : {}),
        })
        : null;
    return {
        ok: true,
        schema: "receiz.mcp.delegated_agent_token_setup.v1",
        dashboardUrl: `${baseUrl}/developers/connect`,
        authorizeUrl,
        flow: "create_delegated_agent_token",
        oidcLogin: authorizeUrl
            ? "Open authorizeUrl, complete Receiz consent, then exchange the authorization code through the app client token route."
            : "Pass clientId, redirectUri, and codeChallenge to have MCP build a Receiz OIDC authorize URL.",
        appName,
        clientId,
        tenantHost,
        auditLabel: `agent:${appName.toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "") || "delegated"}`,
        requiredScopes,
        output: [
            "access_token",
            "expires_at",
            "expires_in",
            "refresh_token when long-lived renewal is enabled",
            "token_id for revocation",
            "granted_scopes",
            "subject_receiz_id",
            "app_client_id",
        ],
        env: {
            RECEIZ_BASE_URL: baseUrl,
            RECEIZ_ACCESS_TOKEN: "<paste-token-shown-once>",
            RECEIZ_APPLICATION_ID: clientId,
        },
        mcpConfig: `[mcp_servers.receiz.env]\nRECEIZ_BASE_URL = ${JSON.stringify(baseUrl)}\nRECEIZ_ACCESS_TOKEN = "<paste-token-shown-once>"\nRECEIZ_APPLICATION_ID = ${JSON.stringify(clientId)}`,
        law: "The delegated token is issued by Receiz auth. RECEIZ_APPLICATION_ID pins its application/audience coordinate; MCP stores only the bearer capability locally and never becomes proof or identity authority.",
    };
}
function inspectOfflineFile(args) {
    const value = parseOfflineValue(args);
    const expectedPrimitive = stringOrUndefined(args.expectedPrimitive) ?? null;
    const attempts = [];
    try {
        const manifest = assertReceizAssetManifest(value);
        return {
            ok: true,
            verified: false,
            continuity: { state: "missing", error: "continuity_enclosing_proof_required" },
            primitive: "proof_object",
            source: "receiz.sdk.manifest.inspectAsset",
            expectedPrimitive,
            manifest,
            projection: projectReceizAssetManifest(manifest),
            authority: RECEIZ_MCP_AUTHORITY_BOUNDARY,
        };
    }
    catch (error) {
        attempts.push(errorMessage(error));
    }
    try {
        const manifest = assertReceizSportsCardManifest(value);
        return {
            ok: true,
            verified: false,
            continuity: { state: "missing", error: "continuity_enclosing_proof_required" },
            primitive: "sports_card_proof_object",
            source: "receiz.sdk.manifest.inspectSportsCard",
            expectedPrimitive,
            manifest,
            projection: projectReceizSportsCardManifest(manifest),
            authority: RECEIZ_MCP_AUTHORITY_BOUNDARY,
        };
    }
    catch (error) {
        attempts.push(errorMessage(error));
    }
    return {
        ok: false,
        primitive: "unknown_receiz_projection",
        source: "receiz.sdk.manifest.validators",
        expectedPrimitive,
        attempts,
        inspection: inspectProofObject(value, expectedPrimitive ?? undefined),
        authority: RECEIZ_MCP_AUTHORITY_BOUNDARY,
    };
}
function parseOfflineValue(args) {
    if (args.value !== undefined)
        return args.value;
    const fileText = requiredString(args, "fileText");
    return JSON.parse(fileText);
}
function resultValue(value) {
    return isJsonObject(value) && "value" in value ? value.value : value;
}
function findNestedProofObject(value, keys, expected) {
    if (Array.isArray(value)) {
        for (const item of value) {
            const found = findNestedProofObject(item, keys, expected);
            if (found)
                return found;
        }
        return null;
    }
    if (!isJsonObject(value))
        return null;
    for (const key of keys) {
        if (value[key] === expected)
            return value;
    }
    for (const entry of Object.values(value)) {
        if (typeof entry !== "object" || entry === null)
            continue;
        const found = findNestedProofObject(entry, keys, expected);
        if (found)
            return found;
    }
    return null;
}
function transferPreview(args) {
    const amountUsd = stringOrUndefined(args.amountUsd) ?? "0.00";
    const senderReceizId = stringOrUndefined(args.senderReceizId) ?? null;
    const recipientReceizId = stringOrUndefined(args.recipientReceizId) ?? null;
    return {
        ok: true,
        schema: "receiz.mcp.transfer_preview.v1",
        previewOnly: true,
        mutatesSettlement: false,
        requiresConfirmation: true,
        senderReceizId,
        recipientReceizId,
        amountUsd,
        note: stringOrUndefined(args.note) ?? null,
        idempotencyKey: stringOrUndefined(args.idempotencyKey) ?? null,
        nextRail: "receiz.connect.transfer",
        law: "Preview does not append settlement truth. A real transfer requires explicit user confirmation and delegated Connect authority.",
    };
}
function transferConfirmationPolicy(args) {
    return {
        ok: true,
        schema: "receiz.mcp.transfer_confirmation_policy.v1",
        requiresConfirmation: true,
        amountUsd: stringOrUndefined(args.amountUsd) ?? null,
        recipientReceizId: stringOrUndefined(args.recipientReceizId) ?? null,
        reason: "Receiz settlement transfer appends require explicit user confirmation before delegated write execution.",
    };
}
function packOpenPreview(args) {
    const slotCount = Math.max(1, Math.min(25, Number.isFinite(args.slotCount) ? Number(args.slotCount) : 5));
    const packId = requiredString(args, "packId");
    return {
        ok: true,
        schema: "receiz.mcp.pack_open_preview.v1",
        previewOnly: true,
        mutatesSportsMemory: false,
        packId,
        sport: stringOrUndefined(args.sport) ?? "sports",
        slots: Array.from({ length: slotCount }, (_, index) => ({
            slot: index + 1,
            state: "preview",
            appendRail: "sports.pack.open.append_after_confirmation",
        })),
        law: "Preview does not admit pack truth. Opening a pack creates verified card/proof appends after confirmation.",
    };
}
function marketplaceTemplate(args) {
    const tenantHost = requiredString(args, "tenantHost");
    const templateKind = stringOrUndefined(args.templateKind) ?? "custom";
    return {
        ok: true,
        schema: "receiz.mcp.marketplace_template.v1",
        previewOnly: true,
        tenantHost,
        templateKind,
        title: stringOrUndefined(args.title) ?? `${tenantHost} Receiz app`,
        firstPaintRail: "receiz.publicStore.resolve",
        publishRail: "receiz.publicStore.publish",
        appStateRail: "receiz.appState.publish",
        requiredScopes: scopesForRails({ oidcScopesByRail: RECEIZ_OIDC_SCOPES_BY_RAIL }, ["identity", "publicStore", "customers", "merchants", "commerce", "wallet"]),
        sections: [
            "identity",
            "public store projection",
            "wallet-aware checkout",
            "proof object search",
            "customer portal",
            "merchant operations",
            "audit trail",
        ],
    };
}
async function readReceizMcpResource(runtime, uri) {
    const payload = await resourcePayload(runtime, uri);
    return {
        contents: [
            {
                uri,
                mimeType: "application/json",
                text: JSON.stringify(nonfinancialExecutionRuntimes.has(runtime) ? {
                    ...payload,
                    executionScope: {
                        profile: "marketplace-nonfinancial",
                        allowedToolNames: RECEIZ_MARKETPLACE_NONFINANCIAL_TOOL_NAMES,
                        referenceBoundary: "SDK reference describes the complete Receiz system. Only the listed tools are callable through this marketplace profile; references do not enable other operations.",
                    },
                } : payload, null, 2),
            },
        ],
    };
}
async function resourcePayload(runtime, uri) {
    if (uri === DEVICE_IDENTITY_CONTEXT_URI)
        return asJsonObject(await readDeviceIdentityContext(runtime));
    const parsed = new URL(uri);
    const id = decodeURIComponent(parsed.pathname.replace(/^\//, ""));
    if (parsed.protocol !== "receiz:") {
        throw new ReceizMcpError("invalid_resource_uri", "Receiz MCP resources must use receiz:// URIs.");
    }
    if (parsed.hostname === "asset" || parsed.hostname === "proof") {
        return wrapResult("public_proof_surface", "receiz.sdk.publicProof.byId", await runtime.client.publicProof.byId(id));
    }
    if (parsed.hostname === "pitch") {
        return wrapResult("sports_pitch_proof_witness", "receiz.mcp.resource_template", {
            witnessId: id,
            requiredTool: "receiz_pitch_proof_by_witness_id",
            requiredInput: "Provide already-admitted local pitch day proof truth to resolve this witness without rediscovery.",
        });
    }
    if (parsed.hostname === "store") {
        return wrapResult("public_app_state_projection", "receiz.sdk.publicStore.resolve", await runtime.client.publicStore.resolve({ host: id }));
    }
    if (parsed.hostname === "sdk" && id === "docs") {
        return wrapResult("developer_documentation", "receiz.mcp.static_docs", {
            sdkPackage: "@receiz/sdk",
            mcpPackage: "@receiz/mcp-server",
            docs: ["https://receiz.com/developers", "https://receiz.com/developers/mcp", "https://receiz.com/developers/openapi"],
        });
    }
    if (parsed.hostname === "schemas" && id === "proof-object-v1") {
        return wrapResult("proof_object_schema", "receiz.mcp.static_schema", {
            schema: "receiz.proof_object.v1",
            requiredTruthBoundary: [
                "deterministic identity",
                "verifiable payload or embedded proof",
                "provenance or integrity material",
                "inspection or verification behavior",
            ],
            authority: RECEIZ_MCP_AUTHORITY_BOUNDARY,
        });
    }
    if (parsed.hostname === "schemas" && id === "app-contract-v1") {
        return wrapResult("application_contract_schema", "receiz.sdk.app_contract.v1", {
            schema: "receiz.app.contract.v1",
            required: ["schema", "name", "framework", "features", "authority", "deployment"],
            authority: { mode: "artifact-first", allowDatabaseAuthority: false },
        });
    }
    if (parsed.hostname === "schemas" && id === "integration-plan-v1") {
        return wrapResult("application_integration_plan_schema", "receiz.sdk.integration_plan.v1", {
            schema: "receiz.app.integration_plan.v1",
            dispositions: ["satisfied", "safe_automatic_change", "user_decision_required", "manual_implementation_required", "blocked_missing_capability_or_authority", "unsafe_or_incompatible"],
            inspectionIsVerification: false,
        });
    }
    if (parsed.hostname === "schemas" && id === "upgrade-rules-v1") {
        return wrapResult("application_upgrade_rules", "receiz.sdk.upgrade_rules.v1", {
            witnessedHistoryMutable: false,
            rule: "Append missing truth and rebuild incorrect projections; never rewrite witnessed history.",
        });
    }
    if (parsed.hostname === "schemas" && id === "generated-files-v1") {
        return wrapResult("application_generated_file_conventions", "receiz.sdk.generated_files.v1", {
            generatedMarker: "@receiz-generated",
            automaticWrites: ["Receiz-owned generated files", "approved package.json fields", "explicit Receiz-generated blocks"],
            unmarkedApplicationSourceMutable: false,
            confirmationRequired: true,
        });
    }
    throw new ReceizMcpError("unknown_resource_uri", `Unknown Receiz MCP resource: ${uri}`);
}
function scopesForRails(runtime, rails) {
    const scopes = new Set();
    for (const rail of rails) {
        const known = runtime.oidcScopesByRail[rail] ?? [];
        if (known.length > 0) {
            for (const scope of known)
                scopes.add(scope);
            continue;
        }
        try {
            for (const scope of receizOidcScopesForRails(rail))
                scopes.add(scope);
        }
        catch {
            // Unknown rails are returned as empty instead of becoming new authority.
        }
    }
    return [...scopes];
}
function allKnownOidcScopes(runtime) {
    const scopes = new Set();
    for (const catalog of [RECEIZ_OIDC_SCOPES_BY_RAIL, runtime.oidcScopesByRail]) {
        for (const railScopes of Object.values(catalog)) {
            for (const scope of railScopes ?? [])
                scopes.add(scope);
        }
    }
    return [...scopes].sort();
}
function ensureDelegated(runtime) {
    if (runtime.accessToken)
        return;
    throw new ReceizMcpError("unauthorized", "This MCP tool writes through delegated Receiz SDK rails and requires RECEIZ_ACCESS_TOKEN.");
}
class ReceizMcpError extends Error {
    code;
    constructor(code, message) {
        super(message);
        this.name = "ReceizMcpError";
        this.code = code;
    }
}
function toolJson(payload) {
    return {
        content: [{ type: "text", text: JSON.stringify(payload, null, 2) }],
    };
}
function toolError(code, message, detail = {}, sourceError) {
    const descriptor = describeReceizError(sourceError ?? new ReceizMcpError(code, message), {
        rail: "mcp",
        authorityBoundary: "mcp-tooling-beneath-receiz-sdk-and-sealed-proof-object-truth",
    });
    return {
        isError: true,
        content: [
            {
                type: "text",
                text: JSON.stringify({
                    ok: false,
                    error: code,
                    code,
                    message: descriptor.message,
                    descriptor,
                    ...detail,
                    authority: RECEIZ_MCP_AUTHORITY_BOUNDARY,
                    mcpAuthority: false,
                    strongerTruth: "sealed-receiz-proof-object",
                }, null, 2),
            },
        ],
    };
}
function response(id, result) {
    return { jsonrpc: "2.0", id, result };
}
function errorResponse(id, code, message, data) {
    return {
        jsonrpc: "2.0",
        id,
        error: { code, message, ...(data === undefined ? {} : { data }) },
    };
}
function protocolVersion(params) {
    const record = asJsonObject(params);
    return stringOrUndefined(record.protocolVersion) ?? "2024-11-05";
}
function asJsonObject(value) {
    return isJsonObject(value) ? value : {};
}
function isJsonObject(value) {
    return typeof value === "object" && value !== null && !Array.isArray(value);
}
function cleanOptions(value) {
    return Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== undefined && entry !== null && entry !== ""));
}
function pickDefined(value) {
    return cleanOptions(value);
}
function stringArray(value) {
    if (!Array.isArray(value))
        return [];
    return value.filter((item) => typeof item === "string" && item.trim().length > 0);
}
function exactOptionalStringArray(value, label) {
    if (value === undefined)
        return undefined;
    if (!Array.isArray(value) || value.some((item) => typeof item !== "string" || item.trim().length === 0)) {
        throw new TypeError(`${label} must be an array of non-empty strings.`);
    }
    return Object.freeze([...value]);
}
function stringOrUndefined(value) {
    return typeof value === "string" && value.trim().length > 0 ? value : undefined;
}
function requiredString(value, key) {
    const field = stringOrUndefined(value[key]);
    if (!field)
        throw new Error(`${key} is required.`);
    return field;
}
function projectInput(args) {
    const root = requiredString(args, "root");
    const targetSdkVersion = stringOrUndefined(args.targetSdkVersion);
    return { root, ...(targetSdkVersion ? { targetSdkVersion } : {}) };
}
function errorCode(error) {
    if (error instanceof ReceizMcpError)
        return error.code;
    if (isJsonObject(error) && typeof error.code === "string")
        return error.code;
    if (isJsonObject(error) && typeof error.name === "string")
        return error.name;
    return "receiz_mcp_tool_failed";
}
function safeV124McpErrorCode(error) {
    const candidate = error instanceof Error
        ? error.message
        : isJsonObject(error) && typeof error.code === "string"
            ? error.code
            : "";
    return /^(?:V124_[A-Z0-9_]+|receiz_[a-z0-9_]+|unauthorized)$/.test(candidate)
        ? candidate
        : "V124_MCP_OPERATION_FAILED";
}
function safeV125McpErrorCode(error) {
    const candidate = error instanceof Error
        ? error.message
        : isJsonObject(error) && typeof error.code === "string"
            ? error.code
            : "";
    return /^(?:V125_[A-Z0-9_]+|receiz_[a-z0-9_]+|unauthorized)$/.test(candidate)
        ? candidate
        : "V125_MCP_OPERATION_FAILED";
}
function errorMessage(error) {
    return describeReceizError(error, { rail: "mcp" }).message;
}
function errorPayload(error) {
    if (error instanceof Error) {
        return {
            name: error.name,
            message: describeReceizError(error, { rail: "mcp" }).message,
        };
    }
    return isJsonObject(error) ? error : { value: String(error) };
}
async function readStdio(runtime) {
    const input = createInterface({ input: process.stdin, terminal: false });
    for await (const line of input) {
        const trimmed = line.trim();
        if (!trimmed)
            continue;
        let request;
        try {
            request = JSON.parse(trimmed);
        }
        catch (error) {
            process.stdout.write(`${JSON.stringify(errorResponse(null, -32700, "Parse error", errorPayload(error)))}\n`);
            continue;
        }
        const result = await handleReceizMcpMessage(request, runtime);
        if (result)
            process.stdout.write(`${JSON.stringify(result)}\n`);
    }
}
export function isCliEntrypoint(options = {}) {
    const argvPath = options.argvPath ?? process.argv[1];
    if (!argvPath)
        return false;
    const moduleUrl = options.moduleUrl ?? import.meta.url;
    const realpath = options.realpath ?? realpathSync;
    try {
        return realpath(argvPath) === realpath(fileURLToPath(moduleUrl));
    }
    catch {
        return false;
    }
}
/** Standard local subject host. Configuration is process-owned, never MCP arguments. */
export async function loadReceizV127LocalSubjectRuntime() {
    const identityArtifactPath = process.env.RECEIZ_SUBJECT_IDENTITY_PATH;
    if (!identityArtifactPath)
        return undefined;
    const identityPassphrase = process.env.RECEIZ_SUBJECT_IDENTITY_PASSPHRASE ?? "";
    return openReceizV127SubjectRuntimeFromFiles({
        directory: process.env.RECEIZ_SUBJECT_CUSTODY_DIR ?? join(homedir(), ".receiz", "subjects"),
        identityArtifactPath, identityPassphrase,
        ...(process.env.RECEIZ_SUBJECT_SNAPSHOT_PATH ? { snapshotArtifactPath: process.env.RECEIZ_SUBJECT_SNAPSHOT_PATH } : {}),
        registryDigest: RECEIZ_CURRENT_REGISTRY_DIGEST,
        reducerDigest: RECEIZ_LIVING_SUBJECT_REDUCER_DIGEST,
    });
}
if (isCliEntrypoint()) {
    Promise.all([
        loadReceizV124McpMaterialHost(),
        loadReceizV125McpProofHost(),
    ])
        .then(async ([v124Host, v125Host]) => {
        const hostOptions = {
            executionProfile: process.env.RECEIZ_MCP_EXECUTION_PROFILE,
            ...(v124Host.resolveMaterial ? { resolveV124Material: v124Host.resolveMaterial } : {}),
            ...(v124Host.persistMaterial ? { persistV124Material: v124Host.persistMaterial } : {}),
            ...(v125Host.resolveProofReference ? { resolveV125ProofReference: v125Host.resolveProofReference } : {}),
        };
        const runtime = process.env.RECEIZ_SUBJECT_IDENTITY_PATH
            ? await openReceizMcpDeviceRuntime({
                identityArtifactPath: resolve(process.env.RECEIZ_SUBJECT_IDENTITY_PATH),
                identityPassphrase: process.env.RECEIZ_SUBJECT_IDENTITY_PASSPHRASE ?? "",
                ...(process.env.RECEIZ_IDENTITY_CONTEXT_SHARING === "all-carried-state" ? { identityContextSharing: "all-carried-state" } : {}),
                workspace: resolve(process.env.RECEIZ_OFFLINE_WORKSPACE ?? process.cwd()),
                sealDirectory: resolve(process.env.RECEIZ_OFFLINE_SEAL_DIRECTORY ?? join(homedir(), ".receiz", "offline-seal")),
                subjectDirectory: resolve(process.env.RECEIZ_SUBJECT_CUSTODY_DIR ?? join(homedir(), ".receiz", "subjects")),
                ...(process.env.RECEIZ_SUBJECT_SNAPSHOT_PATH ? { snapshotArtifactPath: resolve(process.env.RECEIZ_SUBJECT_SNAPSHOT_PATH) } : {}),
                runtime: {
                    ...hostOptions,
                    baseUrl: process.env.RECEIZ_BASE_URL ?? process.env.NEXT_PUBLIC_APP_URL ?? "https://receiz.com",
                    applicationId: process.env.RECEIZ_APPLICATION_ID,
                    accessToken: process.env.RECEIZ_ACCESS_TOKEN ?? process.env.RECEIZ_CONNECT_ACCESS_TOKEN,
                    // Preserve validation in createReceizMcpRuntime for process configuration.
                    legacyConnectTransport: process.env.RECEIZ_LEGACY_CONNECT_TRANSPORT,
                },
            }) : process.env.RECEIZ_MCP_DEVICE_BOOTSTRAP === "1"
            ? await bootstrapReceizMcpDeviceRuntime({
                directory: resolve(process.env.RECEIZ_MCP_DEVICE_DIRECTORY ?? join(homedir(), ".receiz", "mcp-device")),
                workspace: resolve(process.env.RECEIZ_OFFLINE_WORKSPACE ?? process.cwd()),
                ...(process.env.RECEIZ_IDENTITY_CONTEXT_SHARING === "all-carried-state" ? { identityContextSharing: "all-carried-state" } : {}),
                runtime: { ...hostOptions, baseUrl: process.env.RECEIZ_BASE_URL ?? "https://receiz.com",
                    applicationId: process.env.RECEIZ_APPLICATION_ID,
                    accessToken: process.env.RECEIZ_ACCESS_TOKEN ?? process.env.RECEIZ_CONNECT_ACCESS_TOKEN },
            }) : createReceizMcpRuntime(hostOptions);
        if (process.env.RECEIZ_V125_TRUST_HOST_MODULE && !runtime.applicationId)
            throw new TypeError("V125_TRUST_MCP_APPLICATION_REQUIRED");
        const trustHost = await loadReceizV125McpTrustHost({
            client: runtime.client,
            applicationAudience: runtime.applicationId ?? "",
        });
        if (trustHost)
            runtime.executeV125TrustOperation = trustHost;
        if (process.env.RECEIZ_MCP_DEVICE_RELAY_TOKEN) {
            const controller = new AbortController();
            process.once("SIGINT", () => controller.abort());
            process.once("SIGTERM", () => controller.abort());
            process.stdin.once("end", () => controller.abort());
            void runReceizMcpDeviceRelay({ runtime,
                transportOwnerId: process.env.RECEIZ_DEVICE_TRANSPORT_OWNER_ID,
                endpoint: process.env.RECEIZ_MCP_DEVICE_RELAY_URL ?? "https://receiz.com/api/mcp/device/host",
                accessToken: process.env.RECEIZ_MCP_DEVICE_RELAY_TOKEN,
                ...(process.env.RECEIZ_MCP_DEVICE_RELAY_REFRESH_TOKEN ? { refresh: {
                        refreshToken: process.env.RECEIZ_MCP_DEVICE_RELAY_REFRESH_TOKEN,
                        clientId: process.env.RECEIZ_MCP_DEVICE_RELAY_CLIENT_ID ?? "",
                        ...(process.env.RECEIZ_MCP_DEVICE_RELAY_CLIENT_SECRET ? { clientSecret: process.env.RECEIZ_MCP_DEVICE_RELAY_CLIENT_SECRET } : {}),
                    } } : {}),
                directory: resolve(process.env.RECEIZ_MCP_DEVICE_RELAY_DIRECTORY ?? join(homedir(), ".receiz", "mcp-device", "relay")),
                signal: controller.signal,
                onError: code => process.stderr.write(`${code}\n`),
            }).catch(() => process.stderr.write("RECEIZ_DEVICE_RELAY_STOPPED: check device identity and transport authorization.\n"));
        }
        readStdio(runtime);
    })
        .catch((error) => {
        process.stderr.write(`${errorMessage(error)}\n`);
        process.exitCode = 1;
    });
}
//# sourceMappingURL=index.js.map