@nekzus/liop 2.0.0-alpha.21 → 2.0.0-alpha.23
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin/agent.js +2 -2
- package/dist/bin/agent.js.map +1 -1
- package/dist/bridge.js +1 -1
- package/dist/{chunk-WG353XMU.js → chunk-MARROGGT.js} +32 -21
- package/dist/chunk-MARROGGT.js.map +1 -0
- package/dist/{chunk-NWZ5KZDN.js → chunk-S74Y5XJK.js} +2 -2
- package/dist/{chunk-NWZ5KZDN.js.map → chunk-S74Y5XJK.js.map} +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +17 -4
- package/dist/index.js.map +1 -1
- package/dist/server.d.ts +31 -1
- package/dist/server.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-WG353XMU.js.map +0 -1
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import {a}from'./chunk-S6RJHZV2.js';import {randomUUID}from'crypto';import {serve}from'@hono/node-server';import {Hono}from'hono';import {cors}from'hono/cors';var T=10,R=1800*1e3,y=60*1e3,f=class{constructor(e,r={}){this.options=r;this.app=new Hono,this.bridgeLogic=new p(e),this.activeSessions=new Map,this.maxSessionsPerIp=r.maxSessionsPerIp??T,this.sessionTimeoutMs=r.sessionTimeoutMs??R,this.setupRoutes();}app;httpServer=null;bridgeLogic;activeSessions;evictionTimer=null;maxSessionsPerIp;sessionTimeoutMs;async createSessionTransport(e){let{WebStandardStreamableHTTPServerTransport:r}=await import('@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js'),s=new r({sessionIdGenerator:()=>randomUUID(),onsessioninitialized:t=>{this.activeSessions.set(t,{transport:s,lastActivity:Date.now(),clientIp:e}),a.info(`[LIOP-StreamBridge] Session opened: ${t} (IP: ${e})`);}});return s.onmessage=async t=>{if(s.sessionId){let i=this.activeSessions.get(s.sessionId);i&&(i.lastActivity=Date.now());}try{let i=await this.bridgeLogic.handleJsonRpcRequest(t);i!==void 0&&await s.send(i);}catch(i){a.info("[LIOP-StreamBridge] JSON-RPC error:",i.message);}},s.onclose=()=>{s.sessionId&&(this.activeSessions.delete(s.sessionId),a.info(`[LIOP-StreamBridge] Session closed: ${s.sessionId}`));},s}countSessionsByIp(e){let r=0;for(let s of this.activeSessions.values())s.clientIp===e&&r++;return r}getClientIp(e){return e.req.header("x-forwarded-for")?.split(",")[0]?.trim()||e.req.header("x-real-ip")||"unknown"}evictIdleSessions(){let e=Date.now();for(let[r,s]of this.activeSessions)e-s.lastActivity>this.sessionTimeoutMs&&(a.info(`[LIOP-StreamBridge] Evicting idle session: ${r}`),s.transport.close().catch(()=>{}),this.activeSessions.delete(r));}setupRoutes(){this.app.use("*",cors()),process.env.ZERO_TRUST_TOKEN||(process.env.ZERO_TRUST_TOKEN=randomUUID(),a.info("=".repeat(60)),a.info("\u26A0\uFE0F STRICT ZERO-TRUST MODE ENABLED \u26A0\uFE0F"),a.info("No ZERO_TRUST_TOKEN found in environment."),a.info("A secure ephemeral token has been generated for this session:"),a.info(`Token: ${process.env.ZERO_TRUST_TOKEN}`),a.info("=".repeat(60))),this.app.use("/mcp",async(e,r)=>{let s=e.req.header("Authorization"),t=process.env.ZERO_TRUST_TOKEN;if(!s?.startsWith("Bearer ")||s.split(" ")[1]!==t)return a.info("[LIOP-StreamBridge] ALERT: Access denied - Invalid Zero-Trust token."),e.json({error:"Unauthorized: LIOP Zero-Trust Policy Enforced"},401);await r();}),this.app.all("/mcp",async e=>{let r=e.req.header("mcp-session-id");if(r){let o=this.activeSessions.get(r);if(!o)return e.json({error:"Session not found"},404);o.lastActivity=Date.now();let c=await o.transport.handleRequest(e.req.raw);return e.req.method==="DELETE"&&(this.activeSessions.delete(r),a.info(`[LIOP-StreamBridge] Session closed (DELETE): ${r}`)),c}let s=this.getClientIp(e),t=this.countSessionsByIp(s);return t>=this.maxSessionsPerIp?(a.info(`[LIOP-StreamBridge] Rate limit hit for IP: ${s} (${t} sessions)`),e.json({error:"Too Many Sessions: Rate limit exceeded"},429)):await(await this.createSessionTransport(s)).handleRequest(e.req.raw)});}async start(e){let r=e??this.options.port??3e3;return this.evictionTimer=setInterval(()=>this.evictIdleSessions(),y),new Promise(s=>{this.httpServer=serve({fetch:this.app.fetch,port:r},t=>{a.info(`[LIOP-StreamBridge] Streamable HTTP Gateway on http://localhost:${t.port}/mcp`),s();});})}async stop(){this.evictionTimer&&(clearInterval(this.evictionTimer),this.evictionTimer=null);for(let[e,r]of this.activeSessions)await r.transport.close(),this.activeSessions.delete(e);this.httpServer&&(this.httpServer.close(),a.info("[LIOP-StreamBridge] HTTP ports released."));}};var p=class{constructor(e,r={}){this.options=r;e?.constructor?.name==="LiopServer"?(this.liopServer=e,a.info("[LIOP-Bridge] Mode: EXPOSE (LIOP -> MCP Stdio)")):e?.constructor?.name==="McpServer"?(this.legacyMcpServer=e,a.info("[LIOP-Bridge] Mode: WRAP (Legacy MCP -> LIOP Mesh)")):(this.legacyMcpServer=e,a.info("[LIOP-Bridge] Mode: WRAP (Inferred Legacy MCP -> LIOP Mesh)"));}liopServer=null;legacyMcpServer=null;async handleJsonRpcRequest(e){let r=e.id,s=e.method,t=e.params;return e.jsonrpc!=="2.0"?this.errorResponse(r,-32600,"Invalid Request"):this.liopServer?this.handleLiopToMcp(r,s,t):this.legacyMcpServer&&this.liopServer?this.handleLiopToMcp(r,s,t):this.errorResponse(r,-32601,"Bridge source not configured")}async handleLiopToMcp(e,r,s){if(!this.liopServer)return null;if(r==="initialize")return this.successResponse(e,{protocolVersion:"2025-11-25",capabilities:{prompts:{},resources:{},tools:{}},serverInfo:this.liopServer.getServerInfo()});if(r!=="notifications/initialized"){if(r==="ping")return this.successResponse(e,{});if(r==="tools/list"){let t=this.liopServer.listTools();return this.successResponse(e,{tools:t})}if(r==="resources/list"){let t=this.liopServer.listResources();return this.successResponse(e,{resources:t})}if(r==="prompts/list"){let t=this.liopServer.listPrompts();return this.successResponse(e,{prompts:t})}if(r==="prompts/get"){if(!s?.name)return this.errorResponse(e,-32602,"Missing prompt name");try{let t=await this.liopServer.getPrompt({name:s.name,arguments:s.arguments});return this.successResponse(e,t)}catch(t){return this.errorResponse(e,-32e3,t.message)}}if(r==="resources/read"){if(!s?.uri)return this.errorResponse(e,-32602,"Missing resource URI");try{let t=await this.liopServer.readResource(s.uri);return this.successResponse(e,t)}catch(t){return this.errorResponse(e,-32e3,t.message)}}if(r==="tools/call"){if(!s?.name)return this.errorResponse(e,-32602,"Missing tool name");let t={name:s.name,arguments:s.arguments||{}};try{let i=await this.liopServer.callTool(t);return (i.isError?!0:await this.verifyZkReceipt(t,i))?this.successResponse(e,i):this.successResponse(e,{content:[{type:"text",text:"ALERT [LIOP ZERO-TRUST SHIELD] ZK Verification Failed. The mathematical ImageID does not match the original payload."}],isError:!0})}catch(i){return this.errorResponse(e,-32e3,i.message)}}return this.errorResponse(e,-32601,"Method not found")}}successResponse(e,r){return {jsonrpc:"2.0",id:e,result:r}}errorResponse(e,r,s){return {jsonrpc:"2.0",id:e,error:{code:r,message:s}}}async verifyZkReceipt(e,r){if(!e.arguments?.payload||typeof e.arguments.payload!="string")return true;try{let s=e.arguments.payload,t=r.content[0]?.text;if(t&&typeof t=="string")try{let i=JSON.parse(t);if(i.image_id||i.zk_receipt){let{LiopVerifier:o}=await import('./verifier-6M7GY4TW.js');if(!await new o().verifyZkReceipt(Buffer.from(s,"utf-8"),i.image_id,Buffer.from(i.zk_receipt||"","base64")))return !1;i.audit_status="VERIFIED: ZK-Receipt & ImageID Mathematically Verified by LiopMcpBridge",r.content[0].text=JSON.stringify(i);}}catch{}return !0}catch(s){return a.info("[LIOP-Bridge] ZK-Verifier Failure:",s),false}}async connect(){if(this.legacyMcpServer){let{LiopServer:t}=await import('./server.js');if(this.liopServer=new t(this.options.serverInfo||{name:"liop-bridge",version:"1.0.0"},{security:this.options.security}),this.options.publishToMesh){await this.liopServer.connect();let i=this.legacyMcpServer;if(i._registeredTools)for(let[o,c]of Object.entries(i._registeredTools)){let a=c;this.liopServer.tool(o,a.description||"",a.inputSchema||{},async l=>await a.handler(l));}if(i._registeredResources)for(let[o,c]of Object.entries(i._registeredResources)){let a=c;this.liopServer.resource(a.name,o,a.metadata?.description||"",a.metadata?.mimeType||"application/octet-stream",async()=>(await a.readCallback(new URL(o))).contents[0].text);}}return}let r=(await import('readline')).createInterface({input:process.stdin,output:process.stdout,terminal:false}),s=async()=>{a.info("[LIOP-Bridge] Disconnecting session..."),this.liopServer&&await this.liopServer.close(),process.exit(0);};r.on("close",s),process.on("SIGINT",s),process.on("SIGTERM",s),r.on("line",async t=>{if(t.trim())try{let i=JSON.parse(t),o=await this.handleJsonRpcRequest(i);o&&process.stdout.write(`${JSON.stringify(o)}
|
|
2
|
-
`);}catch(i){a.error(`[LIOP-Bridge] Error: ${i.message}`);}});}};export{f as a,p as b};//# sourceMappingURL=chunk-
|
|
3
|
-
//# sourceMappingURL=chunk-
|
|
2
|
+
`);}catch(i){a.error(`[LIOP-Bridge] Error: ${i.message}`);}});}};export{f as a,p as b};//# sourceMappingURL=chunk-S74Y5XJK.js.map
|
|
3
|
+
//# sourceMappingURL=chunk-S74Y5XJK.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/bridge/stream.ts","../src/bridge/index.ts"],"names":["DEFAULT_MAX_SESSIONS_PER_IP","DEFAULT_SESSION_TIMEOUT_MS","EVICTION_INTERVAL_MS","LiopStreamBridge","internalServer","options","Hono","LiopMcpBridge","clientIp","WebStandardStreamableHTTPServerTransport","transport","randomUUID","sessionId","log","message","entry","result","err","ip","count","c","now","cors","next","auth","expectedToken","existing","response","currentSessions","port","listenPort","resolve","serve","info","id","source","payload","method","params","tools","resources","prompts","request","code","contentText","data","LiopVerifier","e","LiopServer","legacy","name","tool","t","args","uri","resource","r","rl","shutdown","line"],"mappings":"+JA6BA,IAAMA,EAA8B,EAAA,CAC9BC,CAAAA,CAA6B,IAAA,CAAU,GAAA,CACvCC,EAAuB,EAAA,CAAK,GAAA,CAgB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CAEA4C,EAAG,EAAA,CAAG,OAAA,CAASC,CAAQ,CAAA,CACvB,OAAA,CAAQ,EAAA,CAAG,QAAA,CAAUA,CAAQ,CAAA,CAC7B,OAAA,CAAQ,EAAA,CAAG,SAAA,CAAWA,CAAQ,CAAA,CAE9BD,CAAAA,CAAG,EAAA,CAAG,MAAA,CAAQ,MAAOE,CAAAA,EAAS,CAC7B,GAAKA,CAAAA,CAAK,IAAA,GACV,GAAI,CACH,IAAMvB,CAAAA,CAAU,KAAK,KAAA,CAAMuB,CAAI,EACzBhC,CAAAA,CAAW,MAAM,KAAK,oBAAA,CAAqBS,CAAO,CAAA,CACpDT,CAAAA,EACH,QAAQ,MAAA,CAAO,KAAA,CAAM,GAAG,IAAA,CAAK,SAAA,CAAUA,CAAQ,CAAC;AAAA,CAAI,EAEtD,CAAA,MAASoB,CAAAA,CAAY,CACpBlC,EAAI,KAAA,CAAM,CAAA,qBAAA,EAAyBkC,CAAAA,CAAY,OAAO,CAAA,CAAE,EACzD,CACD,CAAC,EACF,CACD","file":"chunk-NWZ5KZDN.js","sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport { serve } from \"@hono/node-server\";\nimport type { WebStandardStreamableHTTPServerTransport } from \"@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js\";\nimport type { JSONRPCMessage } from \"@modelcontextprotocol/sdk/types.js\";\nimport { Hono } from \"hono\";\nimport { cors } from \"hono/cors\";\nimport type { LiopServer } from \"../server/index.js\";\nimport { log } from \"../utils/logger.js\";\nimport { LiopMcpBridge } from \"./index.js\";\n\n/**\n * Configuration options for LiopStreamBridge.\n */\nexport interface LiopStreamBridgeOptions {\n\t/** Port to listen on (default: 3000) */\n\tport?: number;\n\t/** Max concurrent sessions per IP (default: 5) */\n\tmaxSessionsPerIp?: number;\n\t/** Session idle timeout in milliseconds (default: 30 min) */\n\tsessionTimeoutMs?: number;\n}\n\n/** Internal metadata for tracked sessions */\ninterface SessionEntry {\n\ttransport: WebStandardStreamableHTTPServerTransport;\n\tlastActivity: number;\n\tclientIp: string;\n}\n\nconst DEFAULT_MAX_SESSIONS_PER_IP = 10;\nconst DEFAULT_SESSION_TIMEOUT_MS = 30 * 60 * 1000; // 30 minutes\nconst EVICTION_INTERVAL_MS = 60 * 1000; // Check every minute\n\n/**\n * LiopStreamBridge\n *\n * Exposes a LiopServer over a remote HTTP network using the industry-standard\n * MCP Streamable HTTP Transport + Hono JS.\n *\n * Supports concurrent multi-client connections via per-session transport instances (Map pattern).\n * External agents connect using only a URL + Bearer Token (Zero-Trust).\n *\n * Security hardening:\n * - Zero-Trust Bearer Token enforcement\n * - Per-IP rate limiting on session creation\n * - Automatic eviction of idle sessions (TTL)\n */\nexport class LiopStreamBridge {\n\tprivate app: Hono;\n\tprivate httpServer: ReturnType<typeof serve> | null = null;\n\tprivate bridgeLogic: LiopMcpBridge;\n\tprivate activeSessions: Map<string, SessionEntry>;\n\tprivate evictionTimer: ReturnType<typeof setInterval> | null = null;\n\tprivate maxSessionsPerIp: number;\n\tprivate sessionTimeoutMs: number;\n\n\tconstructor(\n\t\tinternalServer: LiopServer,\n\t\tprivate options: LiopStreamBridgeOptions = {},\n\t) {\n\t\tthis.app = new Hono();\n\t\tthis.bridgeLogic = new LiopMcpBridge(internalServer);\n\t\tthis.activeSessions = new Map();\n\t\tthis.maxSessionsPerIp =\n\t\t\toptions.maxSessionsPerIp ?? DEFAULT_MAX_SESSIONS_PER_IP;\n\t\tthis.sessionTimeoutMs =\n\t\t\toptions.sessionTimeoutMs ?? DEFAULT_SESSION_TIMEOUT_MS;\n\n\t\tthis.setupRoutes();\n\t}\n\n\t/**\n\t * Creates a new per-session transport instance and wires it to the LIOPMcpBridge logic.\n\t */\n\tprivate async createSessionTransport(\n\t\tclientIp: string,\n\t): Promise<WebStandardStreamableHTTPServerTransport> {\n\t\tconst { WebStandardStreamableHTTPServerTransport } = await import(\n\t\t\t\"@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js\"\n\t\t);\n\t\tconst transport = new WebStandardStreamableHTTPServerTransport({\n\t\t\tsessionIdGenerator: () => randomUUID(),\n\t\t\tonsessioninitialized: (sessionId: string) => {\n\t\t\t\tthis.activeSessions.set(sessionId, {\n\t\t\t\t\ttransport,\n\t\t\t\t\tlastActivity: Date.now(),\n\t\t\t\t\tclientIp,\n\t\t\t\t});\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LIOP-StreamBridge] Session opened: ${sessionId} (IP: ${clientIp})`,\n\t\t\t\t);\n\t\t\t},\n\t\t});\n\n\t\t// Wire the transport's incoming messages to the LiopMcpBridge JSON-RPC router\n\t\ttransport.onmessage = async (message: JSONRPCMessage) => {\n\t\t\t// Touch activity timestamp on every message\n\t\t\tif (transport.sessionId) {\n\t\t\t\tconst entry = this.activeSessions.get(transport.sessionId);\n\t\t\t\tif (entry) entry.lastActivity = Date.now();\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tconst result = await this.bridgeLogic.handleJsonRpcRequest(\n\t\t\t\t\tmessage as unknown as Record<string, unknown>,\n\t\t\t\t);\n\t\t\t\t// Notifications return undefined — no response needed\n\t\t\t\tif (result !== undefined) {\n\t\t\t\t\tawait transport.send(result as JSONRPCMessage);\n\t\t\t\t}\n\t\t\t} catch (err: unknown) {\n\t\t\t\tlog.info(\"[LIOP-StreamBridge] JSON-RPC error:\", (err as Error).message);\n\t\t\t}\n\t\t};\n\n\t\ttransport.onclose = () => {\n\t\t\tif (transport.sessionId) {\n\t\t\t\tthis.activeSessions.delete(transport.sessionId);\n\t\t\t\tlog.info(`[LIOP-StreamBridge] Session closed: ${transport.sessionId}`);\n\t\t\t}\n\t\t};\n\n\t\treturn transport;\n\t}\n\n\t/**\n\t * Returns the number of active sessions for a given IP.\n\t */\n\tprivate countSessionsByIp(ip: string): number {\n\t\tlet count = 0;\n\t\tfor (const entry of this.activeSessions.values()) {\n\t\t\tif (entry.clientIp === ip) count++;\n\t\t}\n\t\treturn count;\n\t}\n\n\t/**\n\t * Extracts client IP from the request (supports X-Forwarded-For for reverse proxies).\n\t */\n\tprivate getClientIp(c: {\n\t\treq: { header: (name: string) => string | undefined };\n\t}): string {\n\t\treturn (\n\t\t\tc.req.header(\"x-forwarded-for\")?.split(\",\")[0]?.trim() ||\n\t\t\tc.req.header(\"x-real-ip\") ||\n\t\t\t\"unknown\"\n\t\t);\n\t}\n\n\t/**\n\t * Evicts sessions that have been idle longer than the configured timeout.\n\t */\n\tprivate evictIdleSessions(): void {\n\t\tconst now = Date.now();\n\t\tfor (const [sessionId, entry] of this.activeSessions) {\n\t\t\tif (now - entry.lastActivity > this.sessionTimeoutMs) {\n\t\t\t\tlog.info(`[LIOP-StreamBridge] Evicting idle session: ${sessionId}`);\n\t\t\t\tentry.transport.close().catch(() => {\n\t\t\t\t\t/* Swallow close errors */\n\t\t\t\t});\n\t\t\t\tthis.activeSessions.delete(sessionId);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate setupRoutes() {\n\t\tthis.app.use(\"*\", cors());\n\n\t\t// Initialize strict zero-trust token if not provided\n\t\tif (!process.env.ZERO_TRUST_TOKEN) {\n\t\t\tprocess.env.ZERO_TRUST_TOKEN = randomUUID();\n\t\t\tlog.info(\"=\".repeat(60));\n\t\t\tlog.info(\"⚠️ STRICT ZERO-TRUST MODE ENABLED ⚠️\");\n\t\t\tlog.info(\"No ZERO_TRUST_TOKEN found in environment.\");\n\t\t\tlog.info(\"A secure ephemeral token has been generated for this session:\");\n\t\t\tlog.info(`Token: ${process.env.ZERO_TRUST_TOKEN}`);\n\t\t\tlog.info(\"=\".repeat(60));\n\t\t}\n\n\t\t// ZTA (Zero-Trust Architecture) Security Middleware\n\t\tthis.app.use(\"/mcp\", async (c, next) => {\n\t\t\tconst auth = c.req.header(\"Authorization\");\n\n\t\t\tconst expectedToken = process.env.ZERO_TRUST_TOKEN;\n\t\t\tif (\n\t\t\t\t!auth?.startsWith(\"Bearer \") ||\n\t\t\t\tauth.split(\" \")[1] !== expectedToken\n\t\t\t) {\n\t\t\t\tlog.info(\n\t\t\t\t\t\"[LIOP-StreamBridge] ALERT: Access denied - Invalid Zero-Trust token.\",\n\t\t\t\t);\n\t\t\t\treturn c.json(\n\t\t\t\t\t{ error: \"Unauthorized: LIOP Zero-Trust Policy Enforced\" },\n\t\t\t\t\t401,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tawait next();\n\t\t});\n\n\t\t// Multi-Session Streamable HTTP Handler\n\t\tthis.app.all(\"/mcp\", async (c) => {\n\t\t\tconst sessionId = c.req.header(\"mcp-session-id\");\n\n\t\t\t// Route to existing session if session ID is present\n\t\t\tif (sessionId) {\n\t\t\t\tconst existing = this.activeSessions.get(sessionId);\n\t\t\t\tif (!existing) {\n\t\t\t\t\treturn c.json({ error: \"Session not found\" }, 404);\n\t\t\t\t}\n\t\t\t\t// Touch activity on every routed request\n\t\t\t\texisting.lastActivity = Date.now();\n\n\t\t\t\tconst response = await existing.transport.handleRequest(c.req.raw);\n\n\t\t\t\t// If DELETE, the transport closes internally but onclose may not fire.\n\t\t\t\t// Explicitly clean up the session from the Map.\n\t\t\t\tif (c.req.method === \"DELETE\") {\n\t\t\t\t\tthis.activeSessions.delete(sessionId);\n\t\t\t\t\tlog.info(`[LIOP-StreamBridge] Session closed (DELETE): ${sessionId}`);\n\t\t\t\t}\n\n\t\t\t\treturn response;\n\t\t\t}\n\n\t\t\t// No session ID → New client initializing.\n\t\t\t// Rate-limit: enforce max sessions per IP\n\t\t\tconst clientIp = this.getClientIp(c);\n\t\t\tconst currentSessions = this.countSessionsByIp(clientIp);\n\t\t\tif (currentSessions >= this.maxSessionsPerIp) {\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LIOP-StreamBridge] Rate limit hit for IP: ${clientIp} (${currentSessions} sessions)`,\n\t\t\t\t);\n\t\t\t\treturn c.json({ error: \"Too Many Sessions: Rate limit exceeded\" }, 429);\n\t\t\t}\n\n\t\t\tconst transport = await this.createSessionTransport(clientIp);\n\t\t\treturn await transport.handleRequest(c.req.raw);\n\t\t});\n\t}\n\n\t/**\n\t * Starts the LiopStreamBridge HTTP server and session eviction timer.\n\t */\n\tpublic async start(port?: number): Promise<void> {\n\t\tconst listenPort = port ?? this.options.port ?? 3000;\n\n\t\t// Start the idle session eviction timer\n\t\tthis.evictionTimer = setInterval(\n\t\t\t() => this.evictIdleSessions(),\n\t\t\tEVICTION_INTERVAL_MS,\n\t\t);\n\n\t\treturn new Promise((resolve) => {\n\t\t\tthis.httpServer = serve(\n\t\t\t\t{\n\t\t\t\t\tfetch: this.app.fetch,\n\t\t\t\t\tport: listenPort,\n\t\t\t\t},\n\t\t\t\t(info) => {\n\t\t\t\t\tlog.info(\n\t\t\t\t\t\t`[LIOP-StreamBridge] Streamable HTTP Gateway on http://localhost:${info.port}/mcp`,\n\t\t\t\t\t);\n\t\t\t\t\tresolve();\n\t\t\t\t},\n\t\t\t);\n\t\t});\n\t}\n\n\t/**\n\t * Graceful shutdown — closes all active sessions, stops timers, and releases port.\n\t */\n\tpublic async stop(): Promise<void> {\n\t\tif (this.evictionTimer) {\n\t\t\tclearInterval(this.evictionTimer);\n\t\t\tthis.evictionTimer = null;\n\t\t}\n\n\t\tfor (const [id, entry] of this.activeSessions) {\n\t\t\tawait entry.transport.close();\n\t\t\tthis.activeSessions.delete(id);\n\t\t}\n\n\t\tif (this.httpServer) {\n\t\t\tthis.httpServer.close();\n\t\t\tlog.info(\"[LIOP-StreamBridge] HTTP ports released.\");\n\t\t}\n\t}\n}\n","import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { LiopServer, LiopServerOptions } from \"../server/index.js\";\nimport type { CallToolRequest, CallToolResult } from \"../types.js\";\nimport { log } from \"../utils/logger.js\";\n\nexport interface LiopBridgeOptions {\n\tpublishToMesh?: boolean;\n\tmeshIdentity?: string;\n\tserverInfo?: {\n\t\tname: string;\n\t\tversion: string;\n\t};\n\tsecurity?: LiopServerOptions[\"security\"];\n}\n\n/**\n * LIOP MCP Bridge\n * A bi-directional bridge that allows legacy MCP servers to join the LIOP mesh,\n * or exposes a LIOP server as an MCP-compatible stdio process for tools like Claude Desktop.\n */\nexport class LiopMcpBridge {\n\tprivate liopServer: LiopServer | null = null;\n\tprivate legacyMcpServer: McpServer | null = null;\n\tconstructor(\n\t\t// biome-ignore lint/suspicious/noExplicitAny: polymorphic source detection\n\t\tsource: LiopServer | McpServer | any,\n\t\tprivate options: LiopBridgeOptions = {},\n\t) {\n\t\t// Determine mode: Exposing LIOP to MCP (Claude) or Wrapping MCP to LIOP (Mesh)\n\t\t// We use constructor name check to avoid hard dependency on optional SDK at runtime start\n\t\tif (source?.constructor?.name === \"LiopServer\") {\n\t\t\tthis.liopServer = source as LiopServer;\n\t\t\tlog.info(\"[LIOP-Bridge] Mode: EXPOSE (LIOP -> MCP Stdio)\");\n\t\t} else if (source?.constructor?.name === \"McpServer\") {\n\t\t\tthis.legacyMcpServer = source as McpServer;\n\t\t\tlog.info(\"[LIOP-Bridge] Mode: WRAP (Legacy MCP -> LIOP Mesh)\");\n\t\t} else {\n\t\t\t// Fallback for inferred legacy MCP servers\n\t\t\tthis.legacyMcpServer = source as McpServer;\n\t\t\tlog.info(\"[LIOP-Bridge] Mode: WRAP (Inferred Legacy MCP -> LIOP Mesh)\");\n\t\t}\n\t}\n\n\t/**\n\t * Handles an incoming standard MCP JSON-RPC 2.0 payload.\n\t * Pipes it to the underlying server (LIOP or Legacy MCP).\n\t */\n\tpublic async handleJsonRpcRequest(\n\t\tpayload: Record<string, unknown>,\n\t): Promise<unknown> {\n\t\tconst id = payload.id as string | number;\n\t\tconst method = payload.method as string;\n\t\tconst params = payload.params as Record<string, unknown> | undefined;\n\n\t\tif (payload.jsonrpc !== \"2.0\") {\n\t\t\treturn this.errorResponse(id, -32600, \"Invalid Request\");\n\t\t}\n\n\t\t// Mode: EXPOSE (Standard behavior used by Claude Desktop)\n\t\tif (this.liopServer) {\n\t\t\treturn this.handleLiopToMcp(id, method, params);\n\t\t}\n\n\t\t// Mode: WRAP (Redirecting via internal LiopServer after connect())\n\t\tif (this.legacyMcpServer && this.liopServer) {\n\t\t\treturn this.handleLiopToMcp(id, method, params);\n\t\t}\n\n\t\treturn this.errorResponse(id, -32601, \"Bridge source not configured\");\n\t}\n\n\tprivate async handleLiopToMcp(\n\t\tid: string | number,\n\t\tmethod: string,\n\t\tparams: Record<string, unknown> | undefined,\n\t): Promise<unknown> {\n\t\tif (!this.liopServer) return null;\n\n\t\tif (method === \"initialize\") {\n\t\t\treturn this.successResponse(id, {\n\t\t\t\tprotocolVersion: \"2025-11-25\",\n\t\t\t\tcapabilities: {\n\t\t\t\t\tprompts: {},\n\t\t\t\t\tresources: {},\n\t\t\t\t\ttools: {},\n\t\t\t\t},\n\t\t\t\tserverInfo: this.liopServer.getServerInfo(),\n\t\t\t});\n\t\t}\n\n\t\tif (method === \"notifications/initialized\") return undefined;\n\t\tif (method === \"ping\") return this.successResponse(id, {});\n\n\t\tif (method === \"tools/list\") {\n\t\t\tconst tools = this.liopServer.listTools();\n\t\t\treturn this.successResponse(id, { tools });\n\t\t}\n\n\t\tif (method === \"resources/list\") {\n\t\t\tconst resources = this.liopServer.listResources();\n\t\t\treturn this.successResponse(id, { resources });\n\t\t}\n\n\t\tif (method === \"prompts/list\") {\n\t\t\tconst prompts = this.liopServer.listPrompts();\n\t\t\treturn this.successResponse(id, { prompts });\n\t\t}\n\n\t\tif (method === \"prompts/get\") {\n\t\t\tif (!params?.name) {\n\t\t\t\treturn this.errorResponse(id, -32602, \"Missing prompt name\");\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst result = await this.liopServer.getPrompt({\n\t\t\t\t\tname: params.name as string,\n\t\t\t\t\targuments: params.arguments as Record<string, string> | undefined,\n\t\t\t\t});\n\t\t\t\treturn this.successResponse(id, result);\n\t\t\t} catch (err: unknown) {\n\t\t\t\treturn this.errorResponse(id, -32000, (err as Error).message);\n\t\t\t}\n\t\t}\n\n\t\tif (method === \"resources/read\") {\n\t\t\tif (!params?.uri) {\n\t\t\t\treturn this.errorResponse(id, -32602, \"Missing resource URI\");\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst result = await this.liopServer.readResource(params.uri as string);\n\t\t\t\treturn this.successResponse(id, result);\n\t\t\t} catch (err: unknown) {\n\t\t\t\treturn this.errorResponse(id, -32000, (err as Error).message);\n\t\t\t}\n\t\t}\n\n\t\tif (method === \"tools/call\") {\n\t\t\tif (!params?.name) {\n\t\t\t\treturn this.errorResponse(id, -32602, \"Missing tool name\");\n\t\t\t}\n\t\t\tconst request: CallToolRequest = {\n\t\t\t\tname: params.name as string,\n\t\t\t\targuments: (params.arguments as Record<string, unknown>) || {},\n\t\t\t};\n\n\t\t\ttry {\n\t\t\t\tconst result: CallToolResult = await this.liopServer.callTool(request);\n\t\t\t\t// If the tool execution returned an error (e.g. policy violation), we bypass\n\t\t\t\t// ZK-Receipt verification because no cryptographic proof is generated for errors.\n\t\t\t\tconst isVerified = result.isError\n\t\t\t\t\t? true\n\t\t\t\t\t: await this.verifyZkReceipt(request, result);\n\n\t\t\t\tif (!isVerified) {\n\t\t\t\t\treturn this.successResponse(id, {\n\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\ttext: \"ALERT [LIOP ZERO-TRUST SHIELD] ZK Verification Failed. The mathematical ImageID does not match the original payload.\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t\tisError: true,\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\treturn this.successResponse(id, result);\n\t\t\t} catch (err: unknown) {\n\t\t\t\treturn this.errorResponse(id, -32000, (err as Error).message);\n\t\t\t}\n\t\t}\n\n\t\treturn this.errorResponse(id, -32601, \"Method not found\");\n\t}\n\n\tprivate successResponse(\n\t\tid: string | number | null | undefined,\n\t\tresult: unknown,\n\t) {\n\t\treturn { jsonrpc: \"2.0\", id, result };\n\t}\n\n\tprivate errorResponse(id: string | number, code: number, message: string) {\n\t\treturn { jsonrpc: \"2.0\", id, error: { code, message } };\n\t}\n\n\tprivate async verifyZkReceipt(\n\t\trequest: CallToolRequest,\n\t\tresult: CallToolResult,\n\t): Promise<boolean> {\n\t\tif (\n\t\t\t!request.arguments?.payload ||\n\t\t\ttypeof request.arguments.payload !== \"string\"\n\t\t) {\n\t\t\treturn true;\n\t\t}\n\n\t\ttry {\n\t\t\tconst payload = request.arguments.payload as string;\n\t\t\tconst contentText = result.content[0]?.text;\n\n\t\t\tif (contentText && typeof contentText === \"string\") {\n\t\t\t\ttry {\n\t\t\t\t\tconst data = JSON.parse(contentText);\n\n\t\t\t\t\tif (data.image_id || data.zk_receipt) {\n\t\t\t\t\t\t// 1. Instantiate the Industrial Verifier ( backed by Piscina Worker Pool )\n\t\t\t\t\t\tconst { LiopVerifier } = await import(\"../crypto/verifier.js\");\n\t\t\t\t\t\tconst verifier = new LiopVerifier();\n\n\t\t\t\t\t\t// 2. Delegate the heavy mathematical check (ZK Journal + Seal)\n\t\t\t\t\t\tconst isAuthentic = await verifier.verifyZkReceipt(\n\t\t\t\t\t\t\tBuffer.from(payload, \"utf-8\"),\n\t\t\t\t\t\t\tdata.image_id,\n\t\t\t\t\t\t\tBuffer.from(data.zk_receipt || \"\", \"base64\"),\n\t\t\t\t\t\t);\n\n\t\t\t\t\t\tif (!isAuthentic) {\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tdata.audit_status =\n\t\t\t\t\t\t\t\"VERIFIED: ZK-Receipt & ImageID Mathematically Verified by LiopMcpBridge\";\n\t\t\t\t\t\tresult.content[0].text = JSON.stringify(data);\n\t\t\t\t\t}\n\t\t\t\t} catch {\n\t\t\t\t\t// Output not JSON\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true;\n\t\t} catch (e) {\n\t\t\tlog.info(\"[LIOP-Bridge] ZK-Verifier Failure:\", e);\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t/**\n\t * Connects the bridge via stdio or Mesh depending on mode.\n\t */\n\tpublic async connect(): Promise<void> {\n\t\t// In WRAP mode, we actually need to create a LiopServer and join the mesh\n\t\tif (this.legacyMcpServer) {\n\t\t\tconst { LiopServer } = await import(\"../server/index.js\");\n\t\t\tthis.liopServer = new LiopServer(\n\t\t\t\tthis.options.serverInfo || {\n\t\t\t\t\tname: \"liop-bridge\",\n\t\t\t\t\tversion: \"1.0.0\",\n\t\t\t\t},\n\t\t\t\t{ security: this.options.security },\n\t\t\t);\n\n\t\t\tif (this.options.publishToMesh) {\n\t\t\t\tawait this.liopServer.connect();\n\n\t\t\t\t// Automatically Bridge Legacy Capabilities to LIOP Mesh\n\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Internal legacy MCP properties are completely opaque and unexported\n\t\t\t\tconst legacy = this.legacyMcpServer as any;\n\n\t\t\t\t// 1. Sync Tools\n\t\t\t\tif (legacy._registeredTools) {\n\t\t\t\t\tfor (const [name, tool] of Object.entries(legacy._registeredTools)) {\n\t\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Opaque legacy structure\n\t\t\t\t\t\tconst t = tool as any;\n\t\t\t\t\t\tthis.liopServer.tool(\n\t\t\t\t\t\t\tname,\n\t\t\t\t\t\t\tt.description || \"\",\n\t\t\t\t\t\t\tt.inputSchema || {},\n\t\t\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Opaque legacy callback args\n\t\t\t\t\t\t\tasync (args: any) => {\n\t\t\t\t\t\t\t\treturn await t.handler(args);\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// 2. Sync Resources\n\t\t\t\tif (legacy._registeredResources) {\n\t\t\t\t\tfor (const [uri, resource] of Object.entries(\n\t\t\t\t\t\tlegacy._registeredResources,\n\t\t\t\t\t)) {\n\t\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Opaque legacy structure\n\t\t\t\t\t\tconst r = resource as any;\n\t\t\t\t\t\tthis.liopServer.resource(\n\t\t\t\t\t\t\tr.name,\n\t\t\t\t\t\t\turi,\n\t\t\t\t\t\t\tr.metadata?.description || \"\",\n\t\t\t\t\t\t\tr.metadata?.mimeType || \"application/octet-stream\",\n\t\t\t\t\t\t\tasync () => {\n\t\t\t\t\t\t\t\tconst res = await r.readCallback(new URL(uri));\n\t\t\t\t\t\t\t\treturn res.contents[0].text;\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\t// In EXPOSE mode, listen to stdio (Claude Desktop)\n\t\tconst readline = await import(\"node:readline\");\n\t\tconst rl = readline.createInterface({\n\t\t\tinput: process.stdin,\n\t\t\toutput: process.stdout,\n\t\t\tterminal: false,\n\t\t});\n\n\t\tconst shutdown = async () => {\n\t\t\tlog.info(\"[LIOP-Bridge] Disconnecting session...\");\n\t\t\tif (this.liopServer) await this.liopServer.close();\n\t\t\tprocess.exit(0);\n\t\t};\n\n\t\trl.on(\"close\", shutdown);\n\t\tprocess.on(\"SIGINT\", shutdown);\n\t\tprocess.on(\"SIGTERM\", shutdown);\n\n\t\trl.on(\"line\", async (line) => {\n\t\t\tif (!line.trim()) return;\n\t\t\ttry {\n\t\t\t\tconst payload = JSON.parse(line);\n\t\t\t\tconst response = await this.handleJsonRpcRequest(payload);\n\t\t\t\tif (response) {\n\t\t\t\t\tprocess.stdout.write(`${JSON.stringify(response)}\\n`);\n\t\t\t\t}\n\t\t\t} catch (e: unknown) {\n\t\t\t\tlog.error(`[LIOP-Bridge] Error: ${(e as Error).message}`);\n\t\t\t}\n\t\t});\n\t}\n}\n\nexport * from \"./stream.js\";\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/bridge/stream.ts","../src/bridge/index.ts"],"names":["DEFAULT_MAX_SESSIONS_PER_IP","DEFAULT_SESSION_TIMEOUT_MS","EVICTION_INTERVAL_MS","LiopStreamBridge","internalServer","options","Hono","LiopMcpBridge","clientIp","WebStandardStreamableHTTPServerTransport","transport","randomUUID","sessionId","log","message","entry","result","err","ip","count","c","now","cors","next","auth","expectedToken","existing","response","currentSessions","port","listenPort","resolve","serve","info","id","source","payload","method","params","tools","resources","prompts","request","code","contentText","data","LiopVerifier","e","LiopServer","legacy","name","tool","t","args","uri","resource","r","rl","shutdown","line"],"mappings":"+JA6BA,IAAMA,EAA8B,EAAA,CAC9BC,CAAAA,CAA6B,IAAA,CAAU,GAAA,CACvCC,EAAuB,EAAA,CAAK,GAAA,CAgBrBC,CAAAA,CAAN,KAAuB,CAS7B,WAAA,CACCC,CAAAA,CACQC,CAAAA,CAAmC,GAC1C,CADO,IAAA,CAAA,OAAA,CAAAA,EAER,IAAA,CAAK,GAAA,CAAM,IAAIC,IAAAA,CACf,IAAA,CAAK,WAAA,CAAc,IAAIC,EAAcH,CAAc,CAAA,CACnD,IAAA,CAAK,cAAA,CAAiB,IAAI,GAAA,CAC1B,IAAA,CAAK,gBAAA,CACJC,CAAAA,CAAQ,kBAAoBL,CAAAA,CAC7B,IAAA,CAAK,iBACJK,CAAAA,CAAQ,gBAAA,EAAoBJ,EAE7B,IAAA,CAAK,WAAA,GACN,CArBQ,IACA,UAAA,CAA8C,IAAA,CAC9C,WAAA,CACA,cAAA,CACA,cAAuD,IAAA,CACvD,gBAAA,CACA,gBAAA,CAoBR,MAAc,uBACbO,CAAAA,CACoD,CACpD,GAAM,CAAE,wCAAA,CAAAC,CAAyC,CAAA,CAAI,MAAM,OAC1D,+DACD,EACMC,CAAAA,CAAY,IAAID,CAAAA,CAAyC,CAC9D,mBAAoB,IAAME,UAAAA,EAAW,CACrC,oBAAA,CAAuBC,GAAsB,CAC5C,IAAA,CAAK,eAAe,GAAA,CAAIA,CAAAA,CAAW,CAClC,SAAA,CAAAF,CAAAA,CACA,YAAA,CAAc,IAAA,CAAK,KAAI,CACvB,QAAA,CAAAF,CACD,CAAC,EACDK,CAAAA,CAAI,IAAA,CACH,CAAA,oCAAA,EAAuCD,CAAS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W,aAAa,UAAe,CAAA,EACzB,eAAA,CAAgB,CACnC,MAAO,OAAA,CAAQ,KAAA,CACf,MAAA,CAAQ,OAAA,CAAQ,OAChB,QAAA,CAAU,KACX,CAAC,CAAA,CAEKC,CAAAA,CAAW,SAAY,CAC5B7C,CAAAA,CAAI,IAAA,CAAK,wCAAwC,EAC7C,IAAA,CAAK,UAAA,EAAY,MAAM,IAAA,CAAK,WAAW,KAAA,EAAM,CACjD,OAAA,CAAQ,IAAA,CAAK,CAAC,EACf,CAAA,CAEA4C,EAAG,EAAA,CAAG,OAAA,CAASC,CAAQ,CAAA,CACvB,OAAA,CAAQ,EAAA,CAAG,QAAA,CAAUA,CAAQ,CAAA,CAC7B,OAAA,CAAQ,EAAA,CAAG,SAAA,CAAWA,CAAQ,CAAA,CAE9BD,CAAAA,CAAG,EAAA,CAAG,MAAA,CAAQ,MAAOE,CAAAA,EAAS,CAC7B,GAAKA,CAAAA,CAAK,IAAA,GACV,GAAI,CACH,IAAMvB,CAAAA,CAAU,KAAK,KAAA,CAAMuB,CAAI,EACzBhC,CAAAA,CAAW,MAAM,KAAK,oBAAA,CAAqBS,CAAO,CAAA,CACpDT,CAAAA,EACH,QAAQ,MAAA,CAAO,KAAA,CAAM,GAAG,IAAA,CAAK,SAAA,CAAUA,CAAQ,CAAC;AAAA,CAAI,EAEtD,CAAA,MAASoB,CAAAA,CAAY,CACpBlC,EAAI,KAAA,CAAM,CAAA,qBAAA,EAAyBkC,CAAAA,CAAY,OAAO,CAAA,CAAE,EACzD,CACD,CAAC,EACF,CACD","file":"chunk-S74Y5XJK.js","sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport { serve } from \"@hono/node-server\";\nimport type { WebStandardStreamableHTTPServerTransport } from \"@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js\";\nimport type { JSONRPCMessage } from \"@modelcontextprotocol/sdk/types.js\";\nimport { Hono } from \"hono\";\nimport { cors } from \"hono/cors\";\nimport type { LiopServer } from \"../server/index.js\";\nimport { log } from \"../utils/logger.js\";\nimport { LiopMcpBridge } from \"./index.js\";\n\n/**\n * Configuration options for LiopStreamBridge.\n */\nexport interface LiopStreamBridgeOptions {\n\t/** Port to listen on (default: 3000) */\n\tport?: number;\n\t/** Max concurrent sessions per IP (default: 5) */\n\tmaxSessionsPerIp?: number;\n\t/** Session idle timeout in milliseconds (default: 30 min) */\n\tsessionTimeoutMs?: number;\n}\n\n/** Internal metadata for tracked sessions */\ninterface SessionEntry {\n\ttransport: WebStandardStreamableHTTPServerTransport;\n\tlastActivity: number;\n\tclientIp: string;\n}\n\nconst DEFAULT_MAX_SESSIONS_PER_IP = 10;\nconst DEFAULT_SESSION_TIMEOUT_MS = 30 * 60 * 1000; // 30 minutes\nconst EVICTION_INTERVAL_MS = 60 * 1000; // Check every minute\n\n/**\n * LiopStreamBridge\n *\n * Exposes a LiopServer over a remote HTTP network using the industry-standard\n * MCP Streamable HTTP Transport + Hono JS.\n *\n * Supports concurrent multi-client connections via per-session transport instances (Map pattern).\n * External agents connect using only a URL + Bearer Token (Zero-Trust).\n *\n * Security hardening:\n * - Zero-Trust Bearer Token enforcement\n * - Per-IP rate limiting on session creation\n * - Automatic eviction of idle sessions (TTL)\n */\nexport class LiopStreamBridge {\n\tprivate app: Hono;\n\tprivate httpServer: ReturnType<typeof serve> | null = null;\n\tprivate bridgeLogic: LiopMcpBridge;\n\tprivate activeSessions: Map<string, SessionEntry>;\n\tprivate evictionTimer: ReturnType<typeof setInterval> | null = null;\n\tprivate maxSessionsPerIp: number;\n\tprivate sessionTimeoutMs: number;\n\n\tconstructor(\n\t\tinternalServer: LiopServer,\n\t\tprivate options: LiopStreamBridgeOptions = {},\n\t) {\n\t\tthis.app = new Hono();\n\t\tthis.bridgeLogic = new LiopMcpBridge(internalServer);\n\t\tthis.activeSessions = new Map();\n\t\tthis.maxSessionsPerIp =\n\t\t\toptions.maxSessionsPerIp ?? DEFAULT_MAX_SESSIONS_PER_IP;\n\t\tthis.sessionTimeoutMs =\n\t\t\toptions.sessionTimeoutMs ?? DEFAULT_SESSION_TIMEOUT_MS;\n\n\t\tthis.setupRoutes();\n\t}\n\n\t/**\n\t * Creates a new per-session transport instance and wires it to the LIOPMcpBridge logic.\n\t */\n\tprivate async createSessionTransport(\n\t\tclientIp: string,\n\t): Promise<WebStandardStreamableHTTPServerTransport> {\n\t\tconst { WebStandardStreamableHTTPServerTransport } = await import(\n\t\t\t\"@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js\"\n\t\t);\n\t\tconst transport = new WebStandardStreamableHTTPServerTransport({\n\t\t\tsessionIdGenerator: () => randomUUID(),\n\t\t\tonsessioninitialized: (sessionId: string) => {\n\t\t\t\tthis.activeSessions.set(sessionId, {\n\t\t\t\t\ttransport,\n\t\t\t\t\tlastActivity: Date.now(),\n\t\t\t\t\tclientIp,\n\t\t\t\t});\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LIOP-StreamBridge] Session opened: ${sessionId} (IP: ${clientIp})`,\n\t\t\t\t);\n\t\t\t},\n\t\t});\n\n\t\t// Wire the transport's incoming messages to the LiopMcpBridge JSON-RPC router\n\t\ttransport.onmessage = async (message: JSONRPCMessage) => {\n\t\t\t// Touch activity timestamp on every message\n\t\t\tif (transport.sessionId) {\n\t\t\t\tconst entry = this.activeSessions.get(transport.sessionId);\n\t\t\t\tif (entry) entry.lastActivity = Date.now();\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tconst result = await this.bridgeLogic.handleJsonRpcRequest(\n\t\t\t\t\tmessage as unknown as Record<string, unknown>,\n\t\t\t\t);\n\t\t\t\t// Notifications return undefined — no response needed\n\t\t\t\tif (result !== undefined) {\n\t\t\t\t\tawait transport.send(result as JSONRPCMessage);\n\t\t\t\t}\n\t\t\t} catch (err: unknown) {\n\t\t\t\tlog.info(\"[LIOP-StreamBridge] JSON-RPC error:\", (err as Error).message);\n\t\t\t}\n\t\t};\n\n\t\ttransport.onclose = () => {\n\t\t\tif (transport.sessionId) {\n\t\t\t\tthis.activeSessions.delete(transport.sessionId);\n\t\t\t\tlog.info(`[LIOP-StreamBridge] Session closed: ${transport.sessionId}`);\n\t\t\t}\n\t\t};\n\n\t\treturn transport;\n\t}\n\n\t/**\n\t * Returns the number of active sessions for a given IP.\n\t */\n\tprivate countSessionsByIp(ip: string): number {\n\t\tlet count = 0;\n\t\tfor (const entry of this.activeSessions.values()) {\n\t\t\tif (entry.clientIp === ip) count++;\n\t\t}\n\t\treturn count;\n\t}\n\n\t/**\n\t * Extracts client IP from the request (supports X-Forwarded-For for reverse proxies).\n\t */\n\tprivate getClientIp(c: {\n\t\treq: { header: (name: string) => string | undefined };\n\t}): string {\n\t\treturn (\n\t\t\tc.req.header(\"x-forwarded-for\")?.split(\",\")[0]?.trim() ||\n\t\t\tc.req.header(\"x-real-ip\") ||\n\t\t\t\"unknown\"\n\t\t);\n\t}\n\n\t/**\n\t * Evicts sessions that have been idle longer than the configured timeout.\n\t */\n\tprivate evictIdleSessions(): void {\n\t\tconst now = Date.now();\n\t\tfor (const [sessionId, entry] of this.activeSessions) {\n\t\t\tif (now - entry.lastActivity > this.sessionTimeoutMs) {\n\t\t\t\tlog.info(`[LIOP-StreamBridge] Evicting idle session: ${sessionId}`);\n\t\t\t\tentry.transport.close().catch(() => {\n\t\t\t\t\t/* Swallow close errors */\n\t\t\t\t});\n\t\t\t\tthis.activeSessions.delete(sessionId);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate setupRoutes() {\n\t\tthis.app.use(\"*\", cors());\n\n\t\t// Initialize strict zero-trust token if not provided\n\t\tif (!process.env.ZERO_TRUST_TOKEN) {\n\t\t\tprocess.env.ZERO_TRUST_TOKEN = randomUUID();\n\t\t\tlog.info(\"=\".repeat(60));\n\t\t\tlog.info(\"⚠️ STRICT ZERO-TRUST MODE ENABLED ⚠️\");\n\t\t\tlog.info(\"No ZERO_TRUST_TOKEN found in environment.\");\n\t\t\tlog.info(\"A secure ephemeral token has been generated for this session:\");\n\t\t\tlog.info(`Token: ${process.env.ZERO_TRUST_TOKEN}`);\n\t\t\tlog.info(\"=\".repeat(60));\n\t\t}\n\n\t\t// ZTA (Zero-Trust Architecture) Security Middleware\n\t\tthis.app.use(\"/mcp\", async (c, next) => {\n\t\t\tconst auth = c.req.header(\"Authorization\");\n\n\t\t\tconst expectedToken = process.env.ZERO_TRUST_TOKEN;\n\t\t\tif (\n\t\t\t\t!auth?.startsWith(\"Bearer \") ||\n\t\t\t\tauth.split(\" \")[1] !== expectedToken\n\t\t\t) {\n\t\t\t\tlog.info(\n\t\t\t\t\t\"[LIOP-StreamBridge] ALERT: Access denied - Invalid Zero-Trust token.\",\n\t\t\t\t);\n\t\t\t\treturn c.json(\n\t\t\t\t\t{ error: \"Unauthorized: LIOP Zero-Trust Policy Enforced\" },\n\t\t\t\t\t401,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tawait next();\n\t\t});\n\n\t\t// Multi-Session Streamable HTTP Handler\n\t\tthis.app.all(\"/mcp\", async (c) => {\n\t\t\tconst sessionId = c.req.header(\"mcp-session-id\");\n\n\t\t\t// Route to existing session if session ID is present\n\t\t\tif (sessionId) {\n\t\t\t\tconst existing = this.activeSessions.get(sessionId);\n\t\t\t\tif (!existing) {\n\t\t\t\t\treturn c.json({ error: \"Session not found\" }, 404);\n\t\t\t\t}\n\t\t\t\t// Touch activity on every routed request\n\t\t\t\texisting.lastActivity = Date.now();\n\n\t\t\t\tconst response = await existing.transport.handleRequest(c.req.raw);\n\n\t\t\t\t// If DELETE, the transport closes internally but onclose may not fire.\n\t\t\t\t// Explicitly clean up the session from the Map.\n\t\t\t\tif (c.req.method === \"DELETE\") {\n\t\t\t\t\tthis.activeSessions.delete(sessionId);\n\t\t\t\t\tlog.info(`[LIOP-StreamBridge] Session closed (DELETE): ${sessionId}`);\n\t\t\t\t}\n\n\t\t\t\treturn response;\n\t\t\t}\n\n\t\t\t// No session ID → New client initializing.\n\t\t\t// Rate-limit: enforce max sessions per IP\n\t\t\tconst clientIp = this.getClientIp(c);\n\t\t\tconst currentSessions = this.countSessionsByIp(clientIp);\n\t\t\tif (currentSessions >= this.maxSessionsPerIp) {\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LIOP-StreamBridge] Rate limit hit for IP: ${clientIp} (${currentSessions} sessions)`,\n\t\t\t\t);\n\t\t\t\treturn c.json({ error: \"Too Many Sessions: Rate limit exceeded\" }, 429);\n\t\t\t}\n\n\t\t\tconst transport = await this.createSessionTransport(clientIp);\n\t\t\treturn await transport.handleRequest(c.req.raw);\n\t\t});\n\t}\n\n\t/**\n\t * Starts the LiopStreamBridge HTTP server and session eviction timer.\n\t */\n\tpublic async start(port?: number): Promise<void> {\n\t\tconst listenPort = port ?? this.options.port ?? 3000;\n\n\t\t// Start the idle session eviction timer\n\t\tthis.evictionTimer = setInterval(\n\t\t\t() => this.evictIdleSessions(),\n\t\t\tEVICTION_INTERVAL_MS,\n\t\t);\n\n\t\treturn new Promise((resolve) => {\n\t\t\tthis.httpServer = serve(\n\t\t\t\t{\n\t\t\t\t\tfetch: this.app.fetch,\n\t\t\t\t\tport: listenPort,\n\t\t\t\t},\n\t\t\t\t(info) => {\n\t\t\t\t\tlog.info(\n\t\t\t\t\t\t`[LIOP-StreamBridge] Streamable HTTP Gateway on http://localhost:${info.port}/mcp`,\n\t\t\t\t\t);\n\t\t\t\t\tresolve();\n\t\t\t\t},\n\t\t\t);\n\t\t});\n\t}\n\n\t/**\n\t * Graceful shutdown — closes all active sessions, stops timers, and releases port.\n\t */\n\tpublic async stop(): Promise<void> {\n\t\tif (this.evictionTimer) {\n\t\t\tclearInterval(this.evictionTimer);\n\t\t\tthis.evictionTimer = null;\n\t\t}\n\n\t\tfor (const [id, entry] of this.activeSessions) {\n\t\t\tawait entry.transport.close();\n\t\t\tthis.activeSessions.delete(id);\n\t\t}\n\n\t\tif (this.httpServer) {\n\t\t\tthis.httpServer.close();\n\t\t\tlog.info(\"[LIOP-StreamBridge] HTTP ports released.\");\n\t\t}\n\t}\n}\n","import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { LiopServer, LiopServerOptions } from \"../server/index.js\";\nimport type { CallToolRequest, CallToolResult } from \"../types.js\";\nimport { log } from \"../utils/logger.js\";\n\nexport interface LiopBridgeOptions {\n\tpublishToMesh?: boolean;\n\tmeshIdentity?: string;\n\tserverInfo?: {\n\t\tname: string;\n\t\tversion: string;\n\t};\n\tsecurity?: LiopServerOptions[\"security\"];\n}\n\n/**\n * LIOP MCP Bridge\n * A bi-directional bridge that allows legacy MCP servers to join the LIOP mesh,\n * or exposes a LIOP server as an MCP-compatible stdio process for tools like Claude Desktop.\n */\nexport class LiopMcpBridge {\n\tprivate liopServer: LiopServer | null = null;\n\tprivate legacyMcpServer: McpServer | null = null;\n\tconstructor(\n\t\t// biome-ignore lint/suspicious/noExplicitAny: polymorphic source detection\n\t\tsource: LiopServer | McpServer | any,\n\t\tprivate options: LiopBridgeOptions = {},\n\t) {\n\t\t// Determine mode: Exposing LIOP to MCP (Claude) or Wrapping MCP to LIOP (Mesh)\n\t\t// We use constructor name check to avoid hard dependency on optional SDK at runtime start\n\t\tif (source?.constructor?.name === \"LiopServer\") {\n\t\t\tthis.liopServer = source as LiopServer;\n\t\t\tlog.info(\"[LIOP-Bridge] Mode: EXPOSE (LIOP -> MCP Stdio)\");\n\t\t} else if (source?.constructor?.name === \"McpServer\") {\n\t\t\tthis.legacyMcpServer = source as McpServer;\n\t\t\tlog.info(\"[LIOP-Bridge] Mode: WRAP (Legacy MCP -> LIOP Mesh)\");\n\t\t} else {\n\t\t\t// Fallback for inferred legacy MCP servers\n\t\t\tthis.legacyMcpServer = source as McpServer;\n\t\t\tlog.info(\"[LIOP-Bridge] Mode: WRAP (Inferred Legacy MCP -> LIOP Mesh)\");\n\t\t}\n\t}\n\n\t/**\n\t * Handles an incoming standard MCP JSON-RPC 2.0 payload.\n\t * Pipes it to the underlying server (LIOP or Legacy MCP).\n\t */\n\tpublic async handleJsonRpcRequest(\n\t\tpayload: Record<string, unknown>,\n\t): Promise<unknown> {\n\t\tconst id = payload.id as string | number;\n\t\tconst method = payload.method as string;\n\t\tconst params = payload.params as Record<string, unknown> | undefined;\n\n\t\tif (payload.jsonrpc !== \"2.0\") {\n\t\t\treturn this.errorResponse(id, -32600, \"Invalid Request\");\n\t\t}\n\n\t\t// Mode: EXPOSE (Standard behavior used by Claude Desktop)\n\t\tif (this.liopServer) {\n\t\t\treturn this.handleLiopToMcp(id, method, params);\n\t\t}\n\n\t\t// Mode: WRAP (Redirecting via internal LiopServer after connect())\n\t\tif (this.legacyMcpServer && this.liopServer) {\n\t\t\treturn this.handleLiopToMcp(id, method, params);\n\t\t}\n\n\t\treturn this.errorResponse(id, -32601, \"Bridge source not configured\");\n\t}\n\n\tprivate async handleLiopToMcp(\n\t\tid: string | number,\n\t\tmethod: string,\n\t\tparams: Record<string, unknown> | undefined,\n\t): Promise<unknown> {\n\t\tif (!this.liopServer) return null;\n\n\t\tif (method === \"initialize\") {\n\t\t\treturn this.successResponse(id, {\n\t\t\t\tprotocolVersion: \"2025-11-25\",\n\t\t\t\tcapabilities: {\n\t\t\t\t\tprompts: {},\n\t\t\t\t\tresources: {},\n\t\t\t\t\ttools: {},\n\t\t\t\t},\n\t\t\t\tserverInfo: this.liopServer.getServerInfo(),\n\t\t\t});\n\t\t}\n\n\t\tif (method === \"notifications/initialized\") return undefined;\n\t\tif (method === \"ping\") return this.successResponse(id, {});\n\n\t\tif (method === \"tools/list\") {\n\t\t\tconst tools = this.liopServer.listTools();\n\t\t\treturn this.successResponse(id, { tools });\n\t\t}\n\n\t\tif (method === \"resources/list\") {\n\t\t\tconst resources = this.liopServer.listResources();\n\t\t\treturn this.successResponse(id, { resources });\n\t\t}\n\n\t\tif (method === \"prompts/list\") {\n\t\t\tconst prompts = this.liopServer.listPrompts();\n\t\t\treturn this.successResponse(id, { prompts });\n\t\t}\n\n\t\tif (method === \"prompts/get\") {\n\t\t\tif (!params?.name) {\n\t\t\t\treturn this.errorResponse(id, -32602, \"Missing prompt name\");\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst result = await this.liopServer.getPrompt({\n\t\t\t\t\tname: params.name as string,\n\t\t\t\t\targuments: params.arguments as Record<string, string> | undefined,\n\t\t\t\t});\n\t\t\t\treturn this.successResponse(id, result);\n\t\t\t} catch (err: unknown) {\n\t\t\t\treturn this.errorResponse(id, -32000, (err as Error).message);\n\t\t\t}\n\t\t}\n\n\t\tif (method === \"resources/read\") {\n\t\t\tif (!params?.uri) {\n\t\t\t\treturn this.errorResponse(id, -32602, \"Missing resource URI\");\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst result = await this.liopServer.readResource(params.uri as string);\n\t\t\t\treturn this.successResponse(id, result);\n\t\t\t} catch (err: unknown) {\n\t\t\t\treturn this.errorResponse(id, -32000, (err as Error).message);\n\t\t\t}\n\t\t}\n\n\t\tif (method === \"tools/call\") {\n\t\t\tif (!params?.name) {\n\t\t\t\treturn this.errorResponse(id, -32602, \"Missing tool name\");\n\t\t\t}\n\t\t\tconst request: CallToolRequest = {\n\t\t\t\tname: params.name as string,\n\t\t\t\targuments: (params.arguments as Record<string, unknown>) || {},\n\t\t\t};\n\n\t\t\ttry {\n\t\t\t\tconst result: CallToolResult = await this.liopServer.callTool(request);\n\t\t\t\t// If the tool execution returned an error (e.g. policy violation), we bypass\n\t\t\t\t// ZK-Receipt verification because no cryptographic proof is generated for errors.\n\t\t\t\tconst isVerified = result.isError\n\t\t\t\t\t? true\n\t\t\t\t\t: await this.verifyZkReceipt(request, result);\n\n\t\t\t\tif (!isVerified) {\n\t\t\t\t\treturn this.successResponse(id, {\n\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\ttext: \"ALERT [LIOP ZERO-TRUST SHIELD] ZK Verification Failed. The mathematical ImageID does not match the original payload.\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t\tisError: true,\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\treturn this.successResponse(id, result);\n\t\t\t} catch (err: unknown) {\n\t\t\t\treturn this.errorResponse(id, -32000, (err as Error).message);\n\t\t\t}\n\t\t}\n\n\t\treturn this.errorResponse(id, -32601, \"Method not found\");\n\t}\n\n\tprivate successResponse(\n\t\tid: string | number | null | undefined,\n\t\tresult: unknown,\n\t) {\n\t\treturn { jsonrpc: \"2.0\", id, result };\n\t}\n\n\tprivate errorResponse(id: string | number, code: number, message: string) {\n\t\treturn { jsonrpc: \"2.0\", id, error: { code, message } };\n\t}\n\n\tprivate async verifyZkReceipt(\n\t\trequest: CallToolRequest,\n\t\tresult: CallToolResult,\n\t): Promise<boolean> {\n\t\tif (\n\t\t\t!request.arguments?.payload ||\n\t\t\ttypeof request.arguments.payload !== \"string\"\n\t\t) {\n\t\t\treturn true;\n\t\t}\n\n\t\ttry {\n\t\t\tconst payload = request.arguments.payload as string;\n\t\t\tconst contentText = result.content[0]?.text;\n\n\t\t\tif (contentText && typeof contentText === \"string\") {\n\t\t\t\ttry {\n\t\t\t\t\tconst data = JSON.parse(contentText);\n\n\t\t\t\t\tif (data.image_id || data.zk_receipt) {\n\t\t\t\t\t\t// 1. Instantiate the Industrial Verifier ( backed by Piscina Worker Pool )\n\t\t\t\t\t\tconst { LiopVerifier } = await import(\"../crypto/verifier.js\");\n\t\t\t\t\t\tconst verifier = new LiopVerifier();\n\n\t\t\t\t\t\t// 2. Delegate the heavy mathematical check (ZK Journal + Seal)\n\t\t\t\t\t\tconst isAuthentic = await verifier.verifyZkReceipt(\n\t\t\t\t\t\t\tBuffer.from(payload, \"utf-8\"),\n\t\t\t\t\t\t\tdata.image_id,\n\t\t\t\t\t\t\tBuffer.from(data.zk_receipt || \"\", \"base64\"),\n\t\t\t\t\t\t);\n\n\t\t\t\t\t\tif (!isAuthentic) {\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tdata.audit_status =\n\t\t\t\t\t\t\t\"VERIFIED: ZK-Receipt & ImageID Mathematically Verified by LiopMcpBridge\";\n\t\t\t\t\t\tresult.content[0].text = JSON.stringify(data);\n\t\t\t\t\t}\n\t\t\t\t} catch {\n\t\t\t\t\t// Output not JSON\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true;\n\t\t} catch (e) {\n\t\t\tlog.info(\"[LIOP-Bridge] ZK-Verifier Failure:\", e);\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t/**\n\t * Connects the bridge via stdio or Mesh depending on mode.\n\t */\n\tpublic async connect(): Promise<void> {\n\t\t// In WRAP mode, we actually need to create a LiopServer and join the mesh\n\t\tif (this.legacyMcpServer) {\n\t\t\tconst { LiopServer } = await import(\"../server/index.js\");\n\t\t\tthis.liopServer = new LiopServer(\n\t\t\t\tthis.options.serverInfo || {\n\t\t\t\t\tname: \"liop-bridge\",\n\t\t\t\t\tversion: \"1.0.0\",\n\t\t\t\t},\n\t\t\t\t{ security: this.options.security },\n\t\t\t);\n\n\t\t\tif (this.options.publishToMesh) {\n\t\t\t\tawait this.liopServer.connect();\n\n\t\t\t\t// Automatically Bridge Legacy Capabilities to LIOP Mesh\n\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Internal legacy MCP properties are completely opaque and unexported\n\t\t\t\tconst legacy = this.legacyMcpServer as any;\n\n\t\t\t\t// 1. Sync Tools\n\t\t\t\tif (legacy._registeredTools) {\n\t\t\t\t\tfor (const [name, tool] of Object.entries(legacy._registeredTools)) {\n\t\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Opaque legacy structure\n\t\t\t\t\t\tconst t = tool as any;\n\t\t\t\t\t\tthis.liopServer.tool(\n\t\t\t\t\t\t\tname,\n\t\t\t\t\t\t\tt.description || \"\",\n\t\t\t\t\t\t\tt.inputSchema || {},\n\t\t\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Opaque legacy callback args\n\t\t\t\t\t\t\tasync (args: any) => {\n\t\t\t\t\t\t\t\treturn await t.handler(args);\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// 2. Sync Resources\n\t\t\t\tif (legacy._registeredResources) {\n\t\t\t\t\tfor (const [uri, resource] of Object.entries(\n\t\t\t\t\t\tlegacy._registeredResources,\n\t\t\t\t\t)) {\n\t\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Opaque legacy structure\n\t\t\t\t\t\tconst r = resource as any;\n\t\t\t\t\t\tthis.liopServer.resource(\n\t\t\t\t\t\t\tr.name,\n\t\t\t\t\t\t\turi,\n\t\t\t\t\t\t\tr.metadata?.description || \"\",\n\t\t\t\t\t\t\tr.metadata?.mimeType || \"application/octet-stream\",\n\t\t\t\t\t\t\tasync () => {\n\t\t\t\t\t\t\t\tconst res = await r.readCallback(new URL(uri));\n\t\t\t\t\t\t\t\treturn res.contents[0].text;\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\t// In EXPOSE mode, listen to stdio (Claude Desktop)\n\t\tconst readline = await import(\"node:readline\");\n\t\tconst rl = readline.createInterface({\n\t\t\tinput: process.stdin,\n\t\t\toutput: process.stdout,\n\t\t\tterminal: false,\n\t\t});\n\n\t\tconst shutdown = async () => {\n\t\t\tlog.info(\"[LIOP-Bridge] Disconnecting session...\");\n\t\t\tif (this.liopServer) await this.liopServer.close();\n\t\t\tprocess.exit(0);\n\t\t};\n\n\t\trl.on(\"close\", shutdown);\n\t\tprocess.on(\"SIGINT\", shutdown);\n\t\tprocess.on(\"SIGTERM\", shutdown);\n\n\t\trl.on(\"line\", async (line) => {\n\t\t\tif (!line.trim()) return;\n\t\t\ttry {\n\t\t\t\tconst payload = JSON.parse(line);\n\t\t\t\tconst response = await this.handleJsonRpcRequest(payload);\n\t\t\t\tif (response) {\n\t\t\t\t\tprocess.stdout.write(`${JSON.stringify(response)}\\n`);\n\t\t\t\t}\n\t\t\t} catch (e: unknown) {\n\t\t\t\tlog.error(`[LIOP-Bridge] Error: ${(e as Error).message}`);\n\t\t\t}\n\t\t});\n\t}\n}\n\nexport * from \"./stream.js\";\n"]}
|
package/dist/index.d.ts
CHANGED
|
@@ -4,7 +4,7 @@ export { a as LiopClient } from './index-BihN3W-K.js';
|
|
|
4
4
|
export { LiopHybridGateway } from './gateway.js';
|
|
5
5
|
export { LiopManifest, MeshNode, MeshNodeConfig } from './mesh.js';
|
|
6
6
|
import * as grpc from '@grpc/grpc-js';
|
|
7
|
-
export { AggregationPolicy, LiopServer, LiopServerOptions, LogicExecutionPolicy, NerScanner, PII_PATTERNS, PII_PRESETS, PiiRule, PiiScanner, ToolHandler } from './server.js';
|
|
7
|
+
export { AggregationPolicy, LiopServer, LiopServerOptions, LogicExecutionPolicy, NerScanner, OutputSanitizerConfig, PII_PATTERNS, PII_PRESETS, PiiRule, PiiScanner, ToolHandler, sanitizeOutput } from './server.js';
|
|
8
8
|
export { CallToolRequest, CallToolResult, GetPromptRequest, GetPromptResult, McpRequest, McpResponse, Prompt, PromptSchema, Resource, ResourceSchema, ServerInfo, Tool, ToolSchema } from './types.js';
|
|
9
9
|
import '@modelcontextprotocol/sdk/server/mcp.js';
|
|
10
10
|
import 'zod';
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export{b as WasiSandbox}from'./chunk-C65RM2A3.js';export{b as LiopClient,a as LiopRpcClient}from'./chunk-ISKM7EAL.js';export{c as PromptSchema,b as ResourceSchema,a as ToolSchema}from'./chunk-TNMS53OP.js';export{b as LiopMcpBridge,a as LiopStreamBridge}from'./chunk-
|
|
1
|
+
export{b as WasiSandbox}from'./chunk-C65RM2A3.js';export{b as LiopClient,a as LiopRpcClient}from'./chunk-ISKM7EAL.js';export{c as PromptSchema,b as ResourceSchema,a as ToolSchema}from'./chunk-TNMS53OP.js';export{b as LiopMcpBridge,a as LiopStreamBridge}from'./chunk-S74Y5XJK.js';export{a as LiopHybridGateway}from'./chunk-SYMZRXI3.js';export{a as LiopRpcServer,g as LiopServer,b as NerScanner,d as PII_PATTERNS,e as PII_PRESETS,f as PiiScanner,c as sanitizeOutput}from'./chunk-MARROGGT.js';import'./chunk-2MGFSIXN.js';export{b as HeuristicTokenEstimator,e as LiopOTelBridge,a as RealTokenEstimator,f as TokenTelemetryEngine,d as createSyncTokenEstimator,c as createTokenEstimator}from'./chunk-UK7OBXGZ.js';import'./chunk-UVTEJYHN.js';import'./chunk-ANFXJGMP.js';import'./chunk-DBXGYHKY.js';import'./chunk-V5MKJT6S.js';export{a as MeshNode}from'./chunk-7I6YJS3C.js';import'./chunk-S6RJHZV2.js';import'./chunk-4C666HHU.js';var m=(e=>(e.CapabilityViolation="CapabilityViolation",e.SandboxEscape="SandboxEscape",e.PiiLeak="PiiLeak",e.InvalidIntent="InvalidIntent",e.Throttled="Throttled",e.ZkVerificationFailed="ZkVerificationFailed",e.MeshUnavailable="MeshUnavailable",e.ConnectionFailed="ConnectionFailed",e))(m||{}),n=class extends Error{code;constructor(o,t){super(t),this.name="LiopError",this.code=o;}};var g={claude:{xmlStandard:true,jsonSchemaPreferred:false},openai:{xmlStandard:false,jsonSchemaPreferred:true},gemini:{xmlStandard:false,jsonSchemaPreferred:true}};function _(i){let o=g[i],t=`[LIOP-PROTO-V1: LOGIC-ON-ORIGIN SPECIFICATION]
|
|
2
2
|
You are interacting with a Logic-Injection-on-Origin Protocol (LIOP) Mesh Network.
|
|
3
3
|
Unlike standard MCP where you pull context to evaluate it remotely, in LIOP you WRITE code that executes on the data's origin.
|
|
4
4
|
|
|
@@ -10,7 +10,20 @@ The node will execute your logic securely on the raw secure data, and return onl
|
|
|
10
10
|
1. Provide a self-contained JavaScript syntax block that we will compile to WASM-Sandboxed logic.
|
|
11
11
|
2. Rely only on standard ECMA script features (No Node.js polyfills).
|
|
12
12
|
3. The logic must end by returning the calculated insights, not the raw data.
|
|
13
|
-
|
|
13
|
+
|
|
14
|
+
### DIFFERENTIAL PRIVACY (DP) MECHANISM (Laplace Mechanism)
|
|
15
|
+
To prevent database reconstruction and inference attacks, numeric query outputs are processed by a Laplace DP engine:
|
|
16
|
+
- COUNT / LENGTH queries: To get EXACT integer values without noise, you MUST name return keys containing 'count', 'length', 'size', 'num', 'positive', 'negative', or starting with 'total_' or 'num_' (e.g. 'total_tx', 'credits_count'). This forces sensitivity=1.0, rounds values, and clamps to non-negative values.
|
|
17
|
+
- AVERAGE queries: Return keys containing 'avg', 'mean', or 'average' scale down noise automatically by dividing global sensitivity by the dataset size (sensitivity / n).
|
|
18
|
+
- SUM / OTHER queries: Return keys without these semantic names receive full Laplace noise based on the global node sensitivity (which can be up to 100,000 in Bank nodes to protect raw balances). Do NOT attempt to bypass this by renaming sum fields to count fields, as it violates protocol integrity.
|
|
19
|
+
|
|
20
|
+
### SANDBOX RUNTIME RESTRICTIONS & WORKAROUNDS
|
|
21
|
+
- Date is poisoned: The 'Date' class/constructor is undefined (calling 'new Date()', 'Date.now()', or 'Date.parse()' will crash the execution).
|
|
22
|
+
- Workaround: Perform chronological sorting and comparisons lexicographically on ISO 8601 string dates (e.g. record.date >= '2024-01-01').
|
|
23
|
+
- Poisoned globals: eval, Function, setTimeout, setInterval, Buffer, ArrayBuffer, and TypedArrays are undefined.
|
|
24
|
+
- Frozen prototypes: Modifications to Object.prototype, Array.prototype, etc., are blocked.
|
|
25
|
+
- K-Anonymity constraints: Small datasets (< 10 records) limit outputs to max 3 scalar keys with NO nesting. Datasets with >= 10 records limit outputs to max 10 fields.
|
|
26
|
+
`;return o.xmlStandard?t+=`
|
|
14
27
|
### PAYLOAD FORMATTING (CLAUDE-XML PREFERRED)
|
|
15
28
|
You must wrap your logic precisely within <liop_logic> tags.
|
|
16
29
|
Example:
|
|
@@ -19,7 +32,7 @@ const records = await liop.readResource("liop://vault/patients");
|
|
|
19
32
|
const filtered = records.filter(r => r.disease === "Hypertension");
|
|
20
33
|
return { alert: "High risk demographic", targetCount: filtered.length };
|
|
21
34
|
</liop_logic>
|
|
22
|
-
`:
|
|
35
|
+
`:o.jsonSchemaPreferred&&(t+=`
|
|
23
36
|
### PAYLOAD FORMATTING (JSON PARSING PREFERRED)
|
|
24
37
|
You must provide your logic strictly within a JSON string key called \`"logic_blob"\` inside your tool call parameters.
|
|
25
38
|
Example:
|
|
@@ -27,5 +40,5 @@ Example:
|
|
|
27
40
|
"target": "liop://vault/patients",
|
|
28
41
|
"logic_blob": "const records = await liop.readResource(args.target); return { targetCount: records.filter(r => r.disease === 'Hypertension').length };"
|
|
29
42
|
}
|
|
30
|
-
`),
|
|
43
|
+
`),t}export{m as ErrorCode,n as LiopError,_ as generateSystemInstructions};//# sourceMappingURL=index.js.map
|
|
31
44
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/errors.ts","../src/prompts/adapters.ts"],"names":["ErrorCode","LiopError","code","message","PROVIDER_CONFIGS","generateSystemInstructions","provider","config","instructions"],"mappings":"
|
|
1
|
+
{"version":3,"sources":["../src/errors.ts","../src/prompts/adapters.ts"],"names":["ErrorCode","LiopError","code","message","PROVIDER_CONFIGS","generateSystemInstructions","provider","config","instructions"],"mappings":"y5BAAO,IAAKA,OACXA,CAAAA,CAAA,mBAAA,CAAsB,qBAAA,CACtBA,CAAAA,CAAA,cAAgB,eAAA,CAChBA,CAAAA,CAAA,OAAA,CAAU,SAAA,CACVA,EAAA,aAAA,CAAgB,eAAA,CAChBA,EAAA,SAAA,CAAY,WAAA,CACZA,EAAA,oBAAA,CAAuB,sBAAA,CACvBA,CAAAA,CAAA,eAAA,CAAkB,kBAClBA,CAAAA,CAAA,gBAAA,CAAmB,kBAAA,CARRA,CAAAA,CAAAA,EAAAA,CAAAA,EAAA,IAWCC,CAAAA,CAAN,cAAwB,KAAM,CACpB,KAEhB,WAAA,CAAYC,CAAAA,CAAiBC,EAAiB,CAC7C,KAAA,CAAMA,CAAO,CAAA,CACb,IAAA,CAAK,IAAA,CAAO,WAAA,CACZ,KAAK,IAAA,CAAOD,EACb,CACD,ECLA,IAAME,CAAAA,CAAqD,CAC1D,MAAA,CAAQ,CAAE,YAAa,IAAA,CAAM,mBAAA,CAAqB,KAAM,CAAA,CACxD,MAAA,CAAQ,CAAE,WAAA,CAAa,KAAA,CAAO,mBAAA,CAAqB,IAAK,EACxD,MAAA,CAAQ,CAAE,YAAa,KAAA,CAAO,mBAAA,CAAqB,IAAK,CACzD,CAAA,CAMO,SAASC,CAAAA,CAA2BC,EAA8B,CACxE,IAAMC,EAASH,CAAAA,CAAiBE,CAAQ,EAEpCE,CAAAA,CAAe,CAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,CAAA,CA2BnB,OAAID,CAAAA,CAAO,WAAA,CACVC,CAAAA,EAAgB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,CAAA,CAUND,CAAAA,CAAO,sBACjBC,CAAAA,EAAgB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,CAAA,CAAA,CAWVA,CACR","file":"index.js","sourcesContent":["export enum ErrorCode {\n\tCapabilityViolation = \"CapabilityViolation\",\n\tSandboxEscape = \"SandboxEscape\",\n\tPiiLeak = \"PiiLeak\",\n\tInvalidIntent = \"InvalidIntent\",\n\tThrottled = \"Throttled\",\n\tZkVerificationFailed = \"ZkVerificationFailed\",\n\tMeshUnavailable = \"MeshUnavailable\",\n\tConnectionFailed = \"ConnectionFailed\",\n}\n\nexport class LiopError extends Error {\n\tpublic readonly code: ErrorCode;\n\n\tconstructor(code: ErrorCode, message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"LiopError\";\n\t\tthis.code = code;\n\t}\n}\n","/**\n * LIOP Cross-AI Prompt Adapters (Fase 92)\n *\n * Normalizes system instructions for different LLM providers (Claude, OpenAI, Gemini)\n * to ensure they understand how to generate \"Logic-on-Origin\" WASM-compatible payload structures.\n */\n\nexport type AIProvider = \"claude\" | \"openai\" | \"gemini\";\n\nexport interface PromptConfig {\n\txmlStandard: boolean;\n\tjsonSchemaPreferred: boolean;\n}\n\nconst PROVIDER_CONFIGS: Record<AIProvider, PromptConfig> = {\n\tclaude: { xmlStandard: true, jsonSchemaPreferred: false },\n\topenai: { xmlStandard: false, jsonSchemaPreferred: true },\n\tgemini: { xmlStandard: false, jsonSchemaPreferred: true },\n};\n\n/**\n * Generates specific System Prompts optimized for the provided AI.\n * This instructs the LLM on how to bypass Context-Pulling and use Logic-Injection (Zero-Shot).\n */\nexport function generateSystemInstructions(provider: AIProvider): string {\n\tconst config = PROVIDER_CONFIGS[provider];\n\n\tlet instructions = `[LIOP-PROTO-V1: LOGIC-ON-ORIGIN SPECIFICATION]\nYou are interacting with a Logic-Injection-on-Origin Protocol (LIOP) Mesh Network.\nUnlike standard MCP where you pull context to evaluate it remotely, in LIOP you WRITE code that executes on the data's origin.\n\n### CORE PARADIGM\nWhen you call a tool or resource, you MUST provide a payload that represents secure sandboxed logic to be executed on the remote Node.\nThe node will execute your logic securely on the raw secure data, and return only the RESULT, avoiding PII data egress.\n\n### EXECUTION RULES\n1. Provide a self-contained JavaScript syntax block that we will compile to WASM-Sandboxed logic.\n2. Rely only on standard ECMA script features (No Node.js polyfills).\n3. The logic must end by returning the calculated insights, not the raw data.\n\n### DIFFERENTIAL PRIVACY (DP) MECHANISM (Laplace Mechanism)\nTo prevent database reconstruction and inference attacks, numeric query outputs are processed by a Laplace DP engine:\n- COUNT / LENGTH queries: To get EXACT integer values without noise, you MUST name return keys containing 'count', 'length', 'size', 'num', 'positive', 'negative', or starting with 'total_' or 'num_' (e.g. 'total_tx', 'credits_count'). This forces sensitivity=1.0, rounds values, and clamps to non-negative values.\n- AVERAGE queries: Return keys containing 'avg', 'mean', or 'average' scale down noise automatically by dividing global sensitivity by the dataset size (sensitivity / n).\n- SUM / OTHER queries: Return keys without these semantic names receive full Laplace noise based on the global node sensitivity (which can be up to 100,000 in Bank nodes to protect raw balances). Do NOT attempt to bypass this by renaming sum fields to count fields, as it violates protocol integrity.\n\n### SANDBOX RUNTIME RESTRICTIONS & WORKAROUNDS\n- Date is poisoned: The 'Date' class/constructor is undefined (calling 'new Date()', 'Date.now()', or 'Date.parse()' will crash the execution).\n - Workaround: Perform chronological sorting and comparisons lexicographically on ISO 8601 string dates (e.g. record.date >= '2024-01-01').\n- Poisoned globals: eval, Function, setTimeout, setInterval, Buffer, ArrayBuffer, and TypedArrays are undefined.\n- Frozen prototypes: Modifications to Object.prototype, Array.prototype, etc., are blocked.\n- K-Anonymity constraints: Small datasets (< 10 records) limit outputs to max 3 scalar keys with NO nesting. Datasets with >= 10 records limit outputs to max 10 fields.\n`;\n\n\tif (config.xmlStandard) {\n\t\tinstructions += `\n### PAYLOAD FORMATTING (CLAUDE-XML PREFERRED)\nYou must wrap your logic precisely within <liop_logic> tags.\nExample:\n<liop_logic>\nconst records = await liop.readResource(\"liop://vault/patients\");\nconst filtered = records.filter(r => r.disease === \"Hypertension\");\nreturn { alert: \"High risk demographic\", targetCount: filtered.length };\n</liop_logic>\n`;\n\t} else if (config.jsonSchemaPreferred) {\n\t\tinstructions += `\n### PAYLOAD FORMATTING (JSON PARSING PREFERRED)\nYou must provide your logic strictly within a JSON string key called \\`\"logic_blob\"\\` inside your tool call parameters.\nExample:\n{\n \"target\": \"liop://vault/patients\",\n \"logic_blob\": \"const records = await liop.readResource(args.target); return { targetCount: records.filter(r => r.disease === 'Hypertension').length };\"\n}\n`;\n\t}\n\n\treturn instructions;\n}\n"]}
|
package/dist/server.d.ts
CHANGED
|
@@ -37,6 +37,28 @@ declare class NerScanner {
|
|
|
37
37
|
scanDeep(input: unknown, seen?: WeakSet<object>): Promise<NerScanResult>;
|
|
38
38
|
}
|
|
39
39
|
|
|
40
|
+
/**
|
|
41
|
+
* LIOP Egress Shield Output Sanitizer (NIST SP 800-226 and OWASP DLP 2025 compliant)
|
|
42
|
+
* Recursively sanitizes execution outputs by rounding floating-point numbers
|
|
43
|
+
* and clamping negative values to zero floor where appropriate.
|
|
44
|
+
*
|
|
45
|
+
* Implements absolute immutability, returning a fresh copy of the data.
|
|
46
|
+
*/
|
|
47
|
+
interface OutputSanitizerConfig {
|
|
48
|
+
/** Maximum decimal places for floating-point values (default: 4) */
|
|
49
|
+
maxDecimalPlaces?: number;
|
|
50
|
+
/** Clamp negative values to zero floor (default: true) */
|
|
51
|
+
clampNonNegative?: boolean;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Recursively walks a JSON-like tree, rounding floats and clamping negative values.
|
|
55
|
+
*
|
|
56
|
+
* @param output - The raw or DP-modified output object/value to sanitize
|
|
57
|
+
* @param config - Sanitization parameters (rounding depth, negative clamping)
|
|
58
|
+
* @returns A sanitized deep copy of the output
|
|
59
|
+
*/
|
|
60
|
+
declare function sanitizeOutput(output: unknown, config?: OutputSanitizerConfig): unknown;
|
|
61
|
+
|
|
40
62
|
/**
|
|
41
63
|
* LIOP Professional PII Engine (The Shield V2 - Tier-1 Military Edition)
|
|
42
64
|
* Implements high-fidelity detection based on NIST and OWASP standards.
|
|
@@ -170,6 +192,10 @@ interface LogicExecutionPolicy {
|
|
|
170
192
|
* For SUM queries on a field with range [0, X], set sensitivity = X.
|
|
171
193
|
*/
|
|
172
194
|
dpSensitivity?: number;
|
|
195
|
+
/**
|
|
196
|
+
* Dataset size threshold below which Differential Privacy is active (default: 50).
|
|
197
|
+
*/
|
|
198
|
+
dpSmallDatasetThreshold?: number;
|
|
173
199
|
/**
|
|
174
200
|
* Max queries per numeric field per PQC session (default: 5).
|
|
175
201
|
* Prevents multi-query differencing attacks.
|
|
@@ -258,6 +284,10 @@ declare class LiopServer {
|
|
|
258
284
|
* Register a dynamic resource
|
|
259
285
|
*/
|
|
260
286
|
resource(name: string, uri: string, description?: string, mimeType?: string, content?: string | (() => Promise<string>)): void;
|
|
287
|
+
/**
|
|
288
|
+
* Builds execution guidelines served as a resource to guide LLM code generation.
|
|
289
|
+
*/
|
|
290
|
+
private buildExecutionGuidelines;
|
|
261
291
|
/**
|
|
262
292
|
* Broadcasts the Data Dictionary to the LLM prior to code injection.
|
|
263
293
|
*/
|
|
@@ -339,4 +369,4 @@ declare class LiopServer {
|
|
|
339
369
|
close(): Promise<void>;
|
|
340
370
|
}
|
|
341
371
|
|
|
342
|
-
export { type AggregationPolicy, LiopServer, type LiopServerOptions, type LogicExecutionPolicy, NerScanner, PII_PATTERNS, PII_PRESETS, type PiiRule, PiiScanner, type ToolHandler };
|
|
372
|
+
export { type AggregationPolicy, LiopServer, type LiopServerOptions, type LogicExecutionPolicy, NerScanner, type OutputSanitizerConfig, PII_PATTERNS, PII_PRESETS, type PiiRule, PiiScanner, type ToolHandler, sanitizeOutput };
|
package/dist/server.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{
|
|
1
|
+
export{g as LiopServer,b as NerScanner,d as PII_PATTERNS,e as PII_PRESETS,f as PiiScanner,c as sanitizeOutput}from'./chunk-MARROGGT.js';import'./chunk-2MGFSIXN.js';import'./chunk-V5MKJT6S.js';import'./chunk-7I6YJS3C.js';import'./chunk-S6RJHZV2.js';import'./chunk-4C666HHU.js';//# sourceMappingURL=server.js.map
|
|
2
2
|
//# sourceMappingURL=server.js.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nekzus/liop",
|
|
3
|
-
"version": "2.0.0-alpha.
|
|
3
|
+
"version": "2.0.0-alpha.23",
|
|
4
4
|
"description": "Official SDK for Logic-Injection-on-Origin Protocol (LIOP). Deploy Logic-on-Origin with WebAssembly at gRPC speed and bidirectional MCP compatibility.",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|