@receiz/mcp-server
Version:
MCP server for agents building and verifying Receiz proof-native applications through the canonical Receiz SDK rails.
216 lines • 18.2 kB
JavaScript
import { createHash, randomBytes } from "node:crypto";
import { createReceizDeviceMaterialHost } from "./deviceMaterialHost.js";
export const RECEIZ_SEALED_OUTPUT_URI = "ui://receiz/sealed-output-v12.html";
export const RECEIZ_SEALED_OUTPUT_RESOURCE = Object.freeze({ uri: RECEIZ_SEALED_OUTPUT_URI,
name: "Receiz sealed proof delivery", description: "Component-only exact sealed artifact download after canonical device verification.",
mimeType: "text/html;profile=mcp-app" });
export const RECEIZ_SEALED_CHUNK_SIZE = 256 * 1024;
const transfers = new WeakMap();
export function registerReceizSealedOutput(runtime, reference, sha256) {
if (!/^receiz:file:[a-f0-9]{64}:.+$/.test(reference) || !/^[a-f0-9]{64}$/.test(sha256)
|| reference.slice(12, 76) !== sha256)
throw Error("sealed_output_reference_invalid");
const token = randomBytes(32).toString("base64url");
let held = transfers.get(runtime);
if (!held) {
held = new Map();
transfers.set(runtime, held);
}
for (const [key, value] of held)
if (value.expiresAt <= Date.now())
held.delete(key);
while (held.size >= 4)
held.delete(held.keys().next().value);
held.set(token, { reference, sha256, expiresAt: Date.now() + 30 * 60_000 });
return token;
}
/** Device-custodied exact bytes. The reference is a locator, never authority. */
export async function readReceizSealedOutputChunk(input, workspace, runtime) {
if (!input || typeof input !== "object" || Array.isArray(input))
throw Error("sealed_output_arguments_invalid");
const args = input;
const byToken = typeof args.transferToken === "string";
if (Object.keys(args).some(key => !["transferToken", "artifactReference", "artifactSha256", "offset"].includes(key))
|| !Number.isSafeInteger(args.offset) || Number(args.offset) < 0
|| (byToken ? Object.keys(args).some(key => ["artifactReference", "artifactSha256"].includes(key))
: "transferToken" in args || typeof args.artifactReference !== "string" || typeof args.artifactSha256 !== "string"
|| !/^receiz:file:[a-f0-9]{64}:.+$/.test(args.artifactReference)
|| !/^[a-f0-9]{64}$/.test(args.artifactSha256)
|| args.artifactReference.slice(12, 76) !== args.artifactSha256))
throw Error("sealed_output_arguments_invalid");
const held = transfers.get(runtime);
// The model-visible reference locates only a short-lived transfer registered
// by this same device runtime after canonical sealing. It grants no proof or
// custody authority, and cannot open an arbitrary workspace file.
const transfer = byToken ? held?.get(args.transferToken)
: [...(held?.values() ?? [])].reverse().find(value => value.reference === args.artifactReference
&& value.sha256 === args.artifactSha256 && value.expiresAt > Date.now());
if (!transfer || transfer.expiresAt <= Date.now())
throw Error("sealed_output_transfer_unavailable");
// First chunk admits an exact same-process snapshot. Later chunks use those
// same verified bytes, never a changing file or model-supplied projection.
if (!transfer.held) {
const opened = await createReceizDeviceMaterialHost(workspace).resolveProofReference(transfer.reference);
if (createHash("sha256").update(opened.exactBytes).digest("hex") !== transfer.sha256)
throw Error("sealed_output_source_changed");
transfer.held = { exactBytes: opened.exactBytes.slice(), filename: opened.filename, mimeType: opened.mimeType };
}
const source = transfer.held;
const bytes = source.exactBytes;
const offset = Number(args.offset);
if (offset >= bytes.length)
throw Error("sealed_output_offset_invalid");
const chunk = bytes.subarray(offset, Math.min(offset + RECEIZ_SEALED_CHUNK_SIZE, bytes.length));
const sha256 = createHash("sha256").update(bytes).digest("hex");
if (sha256 !== transfer.sha256)
throw Error("sealed_output_source_changed");
return {
public: { offset, nextOffset: offset + chunk.length, byteLength: bytes.length, artifactSha256: sha256,
filename: source.filename, mimeType: source.mimeType, mcpAuthority: false },
private: { bytesBase64: Buffer.from(chunk).toString("base64") },
};
}
// A component-only transport: exact bytes are never placed in model-visible
// content or structuredContent. ChatGPT's file library is optional; local
// download remains available when the host does not provide uploadFile.
export const RECEIZ_SEALED_OUTPUT_HTML = `<html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><style>
*{box-sizing:border-box}body{font:14px/1.45 system-ui,-apple-system,"Segoe UI",sans-serif;margin:0;padding:8px;background:transparent;color:#152238}
.proof{position:relative;overflow:hidden;width:100%;max-width:600px;border:1px solid #e6e1d5;border-radius:20px;background:linear-gradient(150deg,#fff 0%,#fff 58%,#faf8f2 100%);box-shadow:0 16px 40px rgba(16,30,50,.09),0 1px 3px rgba(16,30,50,.04)}
.proof:before{content:"";display:block;height:3px;background:linear-gradient(90deg,#a98546,#e8d9ac 38%,#f8f2df 74%,#a98546)}
.inner{padding:21px 23px 19px}.head{display:flex;gap:13px;align-items:center}.mark{display:grid;place-items:center;width:42px;height:42px;flex:none;border:1px solid #e3dac7;border-radius:12px;background:#fff;box-shadow:0 3px 9px rgba(22,34,53,.06);color:#152238;font:700 25px/1 Georgia,serif}
.eyebrow{margin:0 0 3px;color:#8f7141;font-size:10px;font-weight:750;letter-spacing:.16em;text-transform:uppercase}.title{margin:0;color:#152238;font:600 21px/1.1 Georgia,"Times New Roman",serif;letter-spacing:-.025em}.rule{height:1px;margin:18px 0;background:linear-gradient(90deg,#ded8c9,#eeeae1 80%,transparent)}
.state{display:flex;align-items:flex-start;gap:10px;min-height:41px}.dot{width:8px;height:8px;flex:none;margin-top:6px;border-radius:50%;background:#af8a4d;box-shadow:0 0 0 4px #f8f0df}.state p{margin:0;color:#344355;font-size:13px}button{display:inline-flex;justify-content:center;align-items:center;width:100%;min-height:42px;margin:17px 0 0;padding:10px 15px;border:1px solid #132239;border-radius:10px;background:#14243b;color:#fff;font:650 13px/1.2 system-ui,-apple-system,"Segoe UI",sans-serif;letter-spacing:.015em;cursor:pointer;box-shadow:0 6px 14px rgba(20,36,59,.16)}button:hover:not(:disabled){background:#263e5c}button:focus-visible,a:focus-visible{outline:2px solid #a98546;outline-offset:3px}button:disabled{opacity:.58;cursor:default;box-shadow:none}
.facts{display:grid;grid-template-columns:1fr auto;gap:7px 12px;margin-top:19px;padding:13px 14px;border:1px solid #eee8dc;border-radius:11px;background:#fcfbf8}.label{color:#7c766b;font-size:10px;font-weight:700;letter-spacing:.1em;text-transform:uppercase}.value{color:#26374c;font-size:11px;font-weight:650;text-align:right}.hash{grid-column:1/-1;color:#3b4b5d;font:10px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace;overflow-wrap:anywhere}.foot{display:flex;align-items:flex-start;gap:7px;margin:14px 0 0;color:#6e7780;font-size:11px;line-height:1.45}.foot:before{content:"◆";color:#ad8a50;font-size:9px;margin-top:2px}#link{margin:0}#link a{display:inline-block;margin-top:12px;color:#173b66;font-weight:650;text-decoration:underline;text-underline-offset:3px}
@media(max-width:440px){.inner{padding:17px}.title{font-size:19px}.facts{grid-template-columns:1fr auto}}
</style></head><body><article class="proof" aria-label="Receiz sealed proof object"><div class="inner"><header class="head"><div class="mark" aria-hidden="true">R</div><div><p class="eyebrow">Receiz · private custody</p><h2 class="title">Sealed proof object</h2></div></header><div class="rule"></div><div class="state"><span class="dot" aria-hidden="true"></span><p id="status" aria-live="polite">Waiting for the proof result from your device.</p></div><div class="facts"><span class="label">Integrity</span><span class="value">Canonical proof</span><span class="label">Sealed bytes</span><span class="value" id="size">—</span><span class="label">Artifact SHA-256</span><span class="hash" id="digest">Awaiting verified artifact</span></div><button id="save" disabled>Save sealed proof ↓</button><p id="link"></p><p class="foot">The sealed file is the proof object. This panel only verifies delivery of its exact bytes.</p></div></article><script>
(function(){
const status=document.getElementById('status'),button=document.getElementById('save'),link=document.getElementById('link'),digest=document.getElementById('digest'),size=document.getElementById('size');
let output=null,token=null,hostCapabilities=null,bridgeReady=false,busy=false,failed=false,nextId=1;
const pending=new Map();
function envelopes(value){
const values=[value,value?.result,value?.mcp_tool_result,value?.mcp_tool_result?.result,
value?.call_tool_result,value?.call_tool_result?.result];
return values.filter(item=>item&&typeof item==='object');
}
function accept(result){
const frames=envelopes(result);
const raw=frames.map(item=>item.structuredContent||item).find(item=>item?.artifactReference&&/^[a-f0-9]{64}$/.test(item?.artifactSha256||''));
const nextToken=frames.map(item=>item._meta?.['receiz/sealedTransfer']?.token).find(value=>typeof value==='string');
if(raw){if(raw.artifactSha256!==output?.artifactSha256)token=null;output=raw;
digest.textContent=raw.artifactSha256;size.textContent=Number.isSafeInteger(raw.byteLength)?raw.byteLength.toLocaleString()+' bytes':'—';}
if(nextToken)token=nextToken;
if(busy||failed)return;
if(output&&(token||bridgeReady)){status.textContent='Verified proof ready on your connected device.';button.disabled=false;}
else if(output){status.textContent='Proof verified; this host did not provide the private file handoff.';
status.dataset.handoffShape=frames.map(item=>['_meta','structuredContent','result','mcp_tool_result','call_tool_result'].filter(key=>key in item).join(',')).join('|');
status.dataset.handoffMeta=frames.map(item=>Object.keys(item._meta||{}).join(',')).join('|');
status.dataset.handoffTransfer=frames.map(item=>Object.keys(item._meta?.['receiz/sealedTransfer']||{}).join(',')).join('|');}
}
function discover(){
const legacy=window.openai;
if(!legacy)return;
const result=legacy.toolResponseMetadata?.mcp_tool_result;
if(result){accept({...result,structuredContent:result.structuredContent||legacy.toolOutput});return;}
if(legacy.toolOutput)accept({structuredContent:legacy.toolOutput,_meta:legacy.toolResponseMetadata?._meta});
}
function request(method,params){
const id=nextId++;
return new Promise((resolve,reject)=>{
const timeout=setTimeout(()=>{pending.delete(id);reject(Error('Host did not answer '+method));},15000);
pending.set(id,{resolve,reject,timeout});
window.parent.postMessage({jsonrpc:'2.0',id,method,params},'*');
});
}
window.addEventListener('message',event=>{
if(event.source!==window.parent)return;
const message=event.data;
if(!message||message.jsonrpc!=='2.0')return;
if(message.id!==undefined&&pending.has(message.id)){
const wait=pending.get(message.id);pending.delete(message.id);clearTimeout(wait.timeout);
if(message.error)wait.reject(Error(message.error.message||'Host request failed'));
else wait.resolve(message.result);
}
if(message.method==='ui/notifications/tool-result')accept(message.params);
},{passive:true});
window.addEventListener('openai:set_globals',discover);discover();
request('ui/initialize',{protocolVersion:'2026-01-26',appInfo:{name:'Receiz sealed proof delivery',version:'11.0.0'},appCapabilities:{}})
.then(result=>{hostCapabilities=result?.hostCapabilities||{};bridgeReady=true;
status.dataset.hostCapabilities=Object.keys(hostCapabilities).join(',');
if(output)accept({structuredContent:output});
window.parent.postMessage({jsonrpc:'2.0',method:'ui/notifications/initialized'},'*');})
.catch(()=>{if(!window.openai&&!output)status.textContent='This host did not connect the proof handoff.';});
const decode=value=>{const binary=atob(value),bytes=new Uint8Array(binary.length);for(let i=0;i<binary.length;i++)bytes[i]=binary.charCodeAt(i);return bytes;};
const hex=bytes=>Array.from(bytes,v=>v.toString(16).padStart(2,'0')).join('');
button.onclick=async()=>{
if(!output||(!token&&!bridgeReady))return;
failed=false;busy=true;button.disabled=true;status.textContent='Retrieving exact sealed bytes…';status.dataset.handoffStage='requesting-chunk';
try{
const parts=[],attemptIds=[];let offset=0,expectedLength=null;
while(expectedLength===null||offset<expectedLength){
const argumentsForChunk=token?{transferToken:token,offset}
:{artifactReference:output.artifactReference,artifactSha256:output.artifactSha256,offset};
const result=window.openai?.callTool
?await window.openai.callTool('receiz_offline_artifact_chunk',argumentsForChunk)
:await request('tools/call',{name:'receiz_offline_artifact_chunk',arguments:argumentsForChunk});
const frames=envelopes(result);
status.dataset.handoffStage='chunk-returned';
if(frames.some(item=>item.isError))throw Error('Device retrieval failed');
const publicPart=frames.map(item=>item.structuredContent).find(item=>item?.artifactSha256);
const meta=frames.map(item=>item._meta?.['receiz/sealedChunk']).find(Boolean);
const chunkBase64=meta?.bytesBase64||(!token&&publicPart?.bytesBase64);
if(!chunkBase64)throw Error('Component-only file transport unavailable');
if(!publicPart||publicPart.offset!==offset||publicPart.artifactSha256!==output.artifactSha256)throw Error('Proof source changed');
if(!Number.isSafeInteger(publicPart.nextOffset)||publicPart.nextOffset<=offset||!Number.isSafeInteger(publicPart.byteLength)
||publicPart.nextOffset>publicPart.byteLength||(expectedLength!==null&&publicPart.byteLength!==expectedLength)
||(output.byteLength!==undefined&&publicPart.byteLength!==output.byteLength))throw Error('Incomplete proof transfer');
const bytes=decode(chunkBase64);if(bytes.length!==publicPart.nextOffset-offset)throw Error('Incomplete proof transfer');
if(typeof publicPart.receizTransportAttemptId==='string')attemptIds.push(publicPart.receizTransportAttemptId);
parts.push(bytes);offset=publicPart.nextOffset;expectedLength=publicPart.byteLength;
}
const exact=new Uint8Array(offset);let cursor=0;for(const part of parts){exact.set(part,cursor);cursor+=part.length;}
const digest=hex(new Uint8Array(await crypto.subtle.digest('SHA-256',exact)));
if(digest!==output.artifactSha256)throw Error('Proof bytes changed');
status.dataset.handoffStage='digest-matched';
const file=new File([exact],output.suggestedFilename||'receiz-proof.receized',{type:output.mimeType||'application/octet-stream'});
status.dataset.chatgptFileApis=['uploadFile','getFileDownloadUrl'].filter(name=>typeof window.openai?.[name]==='function').join(',');
if(window.openai?.uploadFile){try{
let uploaded;
try{uploaded=await window.openai.uploadFile(file,{library:true});}
catch(error){status.dataset.libraryUploadError=error?.message||'Library upload unavailable';
uploaded=await window.openai.uploadFile(file);}
if(uploaded?.fileId&&window.openai.getFileDownloadUrl){const target=await window.openai.getFileDownloadUrl({fileId:uploaded.fileId});
if(target?.downloadUrl){const a=document.createElement('a');a.href=target.downloadUrl;a.textContent='Download sealed proof';a.download=file.name;link.replaceChildren(a);busy=false;status.textContent='Exact sealed proof is available in ChatGPT.';return;}}
}catch(error){status.dataset.chatgptUploadError=error?.message||'ChatGPT file upload unavailable';}}
if(hostCapabilities?.downloadFile){
const safeName=file.name.replace(/[^a-zA-Z0-9._-]/g,'_');
// Encode the already verified exact bytes, never a projection or a URL.
let binary='';for(let i=0;i<exact.length;i+=32768)binary+=String.fromCharCode(...exact.subarray(i,i+32768));
await request('ui/download-file',{contents:[{type:'resource',resource:{uri:'file:///'+encodeURIComponent(safeName),mimeType:file.type,blob:btoa(binary)}}]});
status.dataset.handoffStage='download-accepted';busy=false;
status.textContent='Exact sealed proof sent to your downloads.';return;
}
if(attemptIds.length===parts.length){
const prepared=await request('tools/call',{name:'receiz_offline_artifact_chunk',arguments:{prepareDownload:true,
attemptIds,artifactSha256:output.artifactSha256,byteLength:exact.length}});
const frames=envelopes(prepared);
if(frames.some(item=>item.isError))throw Error('The Receiz download route is not ready yet');
const receipt=frames.map(item=>item.structuredContent).find(item=>typeof item?.downloadUrl==='string');
if(!receipt||receipt.artifactSha256!==output.artifactSha256||receipt.byteLength!==exact.length)throw Error('Download ticket does not match the proof');
const target=new URL(receipt.downloadUrl);
if(target.origin!=='https://receiz.com'||target.pathname!=='/receiz-proof-download.html'||!target.hash)throw Error('Download route is not Receiz');
const a=document.createElement('a');a.href=target.href;a.textContent='Open secure Receiz download ↗';a.rel='noreferrer';
a.onclick=async event=>{event.preventDefault();try{await request('ui/open-link',{url:target.href});}
catch{status.textContent='Open the Receiz download link to save the exact proof.';}};
link.replaceChildren(a);status.dataset.handoffStage='receiz-ticket-ready';busy=false;
status.textContent='Exact proof verified. Starting the Receiz download…';
try{await request('ui/open-link',{url:target.href});}
catch{status.textContent='Use the secure Receiz link to start your download.';}
return;
}
throw Error('This host does not support sealed file downloads');
}catch(error){busy=false;failed=true;status.dataset.handoffError=error?.message||'File handoff failed';
status.textContent=status.dataset.handoffError;button.disabled=false;}
};
})();
</script></body></html>`;
//# sourceMappingURL=sealedArtifactOutput.js.map