@nekzus/liop 2.5.0-beta.1 → 2.5.0-beta.2

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.
Files changed (95) hide show
  1. package/NOTICE +19 -0
  2. package/README.md +66 -34
  3. package/dist/bin/agent.js +673 -82
  4. package/dist/bin/agent.js.map +1 -1
  5. package/dist/bridge.d.ts +3 -3
  6. package/dist/bridge.js +3 -3
  7. package/dist/{chunk-PYKRQAER.js → chunk-2KSO3W4A.js} +2 -2
  8. package/dist/chunk-2KSO3W4A.js.map +1 -0
  9. package/dist/{chunk-32ADSAJS.js → chunk-2STZHJ24.js} +14 -4
  10. package/dist/chunk-2STZHJ24.js.map +1 -0
  11. package/dist/chunk-3QH44NKZ.js +115 -0
  12. package/dist/chunk-3QH44NKZ.js.map +1 -0
  13. package/dist/{chunk-WCCGE4QR.js → chunk-5SWHE62F.js} +196 -33
  14. package/dist/chunk-5SWHE62F.js.map +1 -0
  15. package/dist/{chunk-SONUORBT.js → chunk-7BSCUYUE.js} +2 -2
  16. package/dist/chunk-7BSCUYUE.js.map +1 -0
  17. package/dist/{chunk-QLCOEP5J.js → chunk-7PITYWOV.js} +2 -2
  18. package/dist/chunk-7PITYWOV.js.map +1 -0
  19. package/dist/{chunk-T5IUZF47.js → chunk-EJ426URA.js} +109 -7
  20. package/dist/chunk-EJ426URA.js.map +1 -0
  21. package/dist/{chunk-CRZBVFDV.js → chunk-FCFTYOAS.js} +243 -66
  22. package/dist/chunk-FCFTYOAS.js.map +1 -0
  23. package/dist/chunk-FTF6AMF6.js +3 -0
  24. package/dist/{chunk-RWRRBYG4.js.map → chunk-FTF6AMF6.js.map} +1 -1
  25. package/dist/{chunk-OUUTDSOW.js → chunk-IK7CGWAZ.js} +3 -3
  26. package/dist/chunk-IK7CGWAZ.js.map +1 -0
  27. package/dist/chunk-K3DGJLUY.js +106 -0
  28. package/dist/chunk-K3DGJLUY.js.map +1 -0
  29. package/dist/{chunk-U5BZ66VX.js → chunk-PAICJCKJ.js} +60 -175
  30. package/dist/chunk-PAICJCKJ.js.map +1 -0
  31. package/dist/chunk-PUDETPL4.js +279 -0
  32. package/dist/chunk-PUDETPL4.js.map +1 -0
  33. package/dist/{chunk-547TYL27.js → chunk-UJFWPRDM.js} +164 -1389
  34. package/dist/chunk-UJFWPRDM.js.map +1 -0
  35. package/dist/chunk-VRB5HUYU.js +1492 -0
  36. package/dist/chunk-VRB5HUYU.js.map +1 -0
  37. package/dist/{chunk-GA3Q2S7O.js → chunk-VRDZ5IKE.js} +5 -5
  38. package/dist/chunk-VRDZ5IKE.js.map +1 -0
  39. package/dist/chunk-WPTOJYN5.js +181 -0
  40. package/dist/chunk-WPTOJYN5.js.map +1 -0
  41. package/dist/{chunk-74CISO2I.js → chunk-XRDN232O.js} +28 -4
  42. package/dist/chunk-XRDN232O.js.map +1 -0
  43. package/dist/{chunk-JIJPZFR2.js → chunk-Y62GORQF.js} +2 -2
  44. package/dist/chunk-Y62GORQF.js.map +1 -0
  45. package/dist/chunk-ZP3VVXOI.js +66 -0
  46. package/dist/chunk-ZP3VVXOI.js.map +1 -0
  47. package/dist/client.d.ts +4 -3
  48. package/dist/client.js +10 -8
  49. package/dist/gateway.d.ts +4 -4
  50. package/dist/gateway.js +10 -9
  51. package/dist/{hybrid-CF__0YnC.d.ts → hybrid-DWe1bMoV.d.ts} +5 -4
  52. package/dist/{index-cMV0_yD9.d.ts → index-BuEQtBHD.d.ts} +39 -34
  53. package/dist/{index-BW95kAL4.d.ts → index-CdW8j8Bn.d.ts} +9 -72
  54. package/dist/index.d.ts +172 -48
  55. package/dist/index.js +20 -15
  56. package/dist/index.js.map +1 -1
  57. package/dist/kyber-CGOA7Q6A.js +3 -0
  58. package/dist/{kyber-3ULIJSE3.js.map → kyber-CGOA7Q6A.js.map} +1 -1
  59. package/dist/mesh.d.ts +27 -143
  60. package/dist/mesh.js +4 -3
  61. package/dist/node-B0b2vUFS.d.ts +164 -0
  62. package/dist/protocol/liop_core.proto +3 -0
  63. package/dist/server.d.ts +3 -3
  64. package/dist/server.js +7 -6
  65. package/dist/types-CzRSOlOo.d.ts +452 -0
  66. package/dist/types.d.ts +1 -1
  67. package/dist/types.js +1 -1
  68. package/dist/verifier-XFU7ZB2W.js +6 -0
  69. package/dist/{verifier-3FAKCFNN.js.map → verifier-XFU7ZB2W.js.map} +1 -1
  70. package/dist/workers/logic-execution.js +3 -3
  71. package/dist/workers/logic-execution.js.map +1 -1
  72. package/dist/workers/zk-verifier.js +1 -1
  73. package/dist/workers/zk-verifier.js.map +1 -1
  74. package/package.json +50 -44
  75. package/dist/chunk-32ADSAJS.js.map +0 -1
  76. package/dist/chunk-547TYL27.js.map +0 -1
  77. package/dist/chunk-72MNYFR6.js +0 -64
  78. package/dist/chunk-72MNYFR6.js.map +0 -1
  79. package/dist/chunk-74CISO2I.js.map +0 -1
  80. package/dist/chunk-CRZBVFDV.js.map +0 -1
  81. package/dist/chunk-GA3Q2S7O.js.map +0 -1
  82. package/dist/chunk-JIJPZFR2.js.map +0 -1
  83. package/dist/chunk-OUUTDSOW.js.map +0 -1
  84. package/dist/chunk-PYKRQAER.js.map +0 -1
  85. package/dist/chunk-QLCOEP5J.js.map +0 -1
  86. package/dist/chunk-RWRRBYG4.js +0 -3
  87. package/dist/chunk-SONUORBT.js.map +0 -1
  88. package/dist/chunk-T5IUZF47.js.map +0 -1
  89. package/dist/chunk-U5BZ66VX.js.map +0 -1
  90. package/dist/chunk-WCCGE4QR.js.map +0 -1
  91. package/dist/chunk-WSW6YJNY.js +0 -168
  92. package/dist/chunk-WSW6YJNY.js.map +0 -1
  93. package/dist/kyber-3ULIJSE3.js +0 -3
  94. package/dist/types-lJIxBlWF.d.ts +0 -256
  95. package/dist/verifier-3FAKCFNN.js +0 -5
@@ -0,0 +1,1492 @@
1
+ import { LiopVerifier } from './chunk-2STZHJ24.js';
2
+ import { Kyber768Wrapper } from './chunk-7PITYWOV.js';
3
+ import { authorizeRequest, Dilithium65Wrapper } from './chunk-WPTOJYN5.js';
4
+ import { TokenTelemetryEngine, liopV1, createChannelCredentials, GRPC_CHANNEL_OPTIONS } from './chunk-UJFWPRDM.js';
5
+ import { toolCallsTotal, toolCallErrorsTotal, pqcHandshakeDurationMs, pqcHandshakesTotal, zkVerificationsTotal, wireEgressBytesTotal } from './chunk-PAICJCKJ.js';
6
+ import { MCP_PROTOCOL_VERSION, MCP_LEGACY_SUPPORT_ENABLED, isLegacyRequest, adaptResponseForLegacyClient, MCP_PROTOCOL_VERSION_LEGACY, buildLegacyInitializeResponse } from './chunk-2KSO3W4A.js';
7
+ import { log } from './chunk-K3DGJLUY.js';
8
+ import * as crypto from 'crypto';
9
+ import * as grpc from '@grpc/grpc-js';
10
+
11
+ // src/utils/mcpCompact.ts
12
+ function mcpCompactToolDescriptions() {
13
+ const v = process.env.LIOP_MCP_COMPACT_TOOL_DESCRIPTIONS?.toLowerCase().trim();
14
+ if (v === "0" || v === "false" || v === "no") return false;
15
+ return true;
16
+ }
17
+ function stripVerboseLiopToolDescription(description) {
18
+ let d = description;
19
+ const markers = [
20
+ "\n\n[LIOP-PROTO-V1:",
21
+ "\r\n\r\n[LIOP-PROTO-V1:",
22
+ "\n[LIOP-PROTO-V1:"
23
+ // rare
24
+ ];
25
+ for (const m of markers) {
26
+ const i = d.indexOf(m);
27
+ if (i !== -1) {
28
+ d = d.slice(0, i);
29
+ break;
30
+ }
31
+ }
32
+ return d.trimEnd();
33
+ }
34
+
35
+ // src/gateway/router.ts
36
+ var MANIFEST_CACHE_TTL_S = 300;
37
+ var MANIFEST_DISCOVERY_RETRIES = 5;
38
+ var LiopMcpRouter = class _LiopMcpRouter {
39
+ constructor(liopServer, meshNode = null, defaultRpcPort = 50051) {
40
+ this.liopServer = liopServer;
41
+ this.meshNode = meshNode;
42
+ this.defaultRpcPort = defaultRpcPort;
43
+ if (this.meshNode) {
44
+ this.meshNode.registerManifestHandler(() => {
45
+ const remoteTools = this.liopServer.listTools().map((t) => ({
46
+ name: t.name,
47
+ description: t.description,
48
+ inputSchema: t.inputSchema
49
+ }));
50
+ const resources = this.liopServer.listResources().map((r) => ({
51
+ name: r.name,
52
+ uri: r.uri,
53
+ description: r.description,
54
+ mimeType: r.mimeType
55
+ }));
56
+ const serverConfig = this.liopServer.config;
57
+ return {
58
+ peerId: this.meshNode?.getPeerId() || "unknown",
59
+ grpcPort: this.defaultRpcPort,
60
+ tools: [...remoteTools],
61
+ resources,
62
+ serverInfo: this.liopServer.getServerInfo(),
63
+ authRequired: this.liopServer.jwtValidator !== void 0,
64
+ tokenSlug: serverConfig?.tokenSlug,
65
+ taxonomy: serverConfig?.taxonomy ? {
66
+ domain: serverConfig.taxonomy.domain || "Unknown Domain",
67
+ clearanceTier: serverConfig.taxonomy.clearanceTier ?? 0,
68
+ executionTypes: serverConfig.taxonomy.executionTypes || []
69
+ } : void 0
70
+ };
71
+ });
72
+ this.meshNode.announceManifest().catch((err) => {
73
+ log.info(
74
+ `[LIOP-Router] Failed to announce manifest: ${err instanceof Error ? err.message : String(err)}`
75
+ );
76
+ });
77
+ }
78
+ if (process.env.LIOP_DIAGNOSTIC_LEVEL === "full") {
79
+ process.stderr.write(
80
+ "\u26A0\uFE0F [LIOP-Security] Diagnostic level set to FULL \u2014 PeerIDs and network topology are exposed. Do NOT use in production.\n"
81
+ );
82
+ }
83
+ }
84
+ liopServer;
85
+ meshNode;
86
+ defaultRpcPort;
87
+ /** Cached manifests from remote peers. Key = PeerID */
88
+ manifestCache = /* @__PURE__ */ new Map();
89
+ /** Guards against concurrent discovery storms */
90
+ currentDiscovery = null;
91
+ /** Verifier for Tier-0 integrity checks */
92
+ verifier = new LiopVerifier();
93
+ /** Callback when new remote tools are discovered */
94
+ onToolsChanged;
95
+ /** Circuit-breaker state for peers that repeatedly fail manifest queries. */
96
+ manifestFailureState = /* @__PURE__ */ new Map();
97
+ static MANIFEST_FAILURE_BASE_COOLDOWN_MS = 15e3;
98
+ static MANIFEST_FAILURE_MAX_COOLDOWN_MS = 5 * 6e4;
99
+ static MANIFEST_SKIP_LOG_THROTTLE_MS = 3e4;
100
+ getManifestCacheSize() {
101
+ return this.manifestCache.size;
102
+ }
103
+ shouldSkipManifestQuery(peerId) {
104
+ const state = this.manifestFailureState.get(peerId);
105
+ if (!state) return false;
106
+ const now = Date.now();
107
+ if (now >= state.cooldownUntil) return false;
108
+ if (now - state.lastSkipLogAt > _LiopMcpRouter.MANIFEST_SKIP_LOG_THROTTLE_MS) {
109
+ log.info(
110
+ `[LIOP-Router] Skipping manifest query for ${peerId} during cooldown (${Math.ceil((state.cooldownUntil - now) / 1e3)}s remaining)`
111
+ );
112
+ state.lastSkipLogAt = now;
113
+ }
114
+ return true;
115
+ }
116
+ recordManifestQuerySuccess(peerId) {
117
+ this.manifestFailureState.delete(peerId);
118
+ }
119
+ recordManifestQueryFailure(peerId) {
120
+ const now = Date.now();
121
+ const prev = this.manifestFailureState.get(peerId);
122
+ const failures = (prev?.failures || 0) + 1;
123
+ const backoff = Math.min(
124
+ _LiopMcpRouter.MANIFEST_FAILURE_BASE_COOLDOWN_MS * 2 ** Math.max(0, failures - 1),
125
+ _LiopMcpRouter.MANIFEST_FAILURE_MAX_COOLDOWN_MS
126
+ );
127
+ this.manifestFailureState.set(peerId, {
128
+ failures,
129
+ cooldownUntil: now + backoff,
130
+ lastSkipLogAt: 0
131
+ });
132
+ }
133
+ /**
134
+ * Detects the protocol era of an incoming request.
135
+ * Modern requests carry '_meta' with protocol version "2026-07-28" or use modern RPCs.
136
+ * Legacy requests use 'initialize' handshake or lack '_meta' envelopes.
137
+ */
138
+ detectEra(request) {
139
+ const params = request.params;
140
+ const meta = params?._meta;
141
+ const version = meta?.["io.modelcontextprotocol/protocolVersion"];
142
+ if (version === MCP_PROTOCOL_VERSION) {
143
+ return "modern";
144
+ }
145
+ if (MCP_LEGACY_SUPPORT_ENABLED && isLegacyRequest(request)) {
146
+ return "legacy";
147
+ }
148
+ return "modern";
149
+ }
150
+ async dispatch(request, authInfo) {
151
+ const { method, params, id } = request;
152
+ log.info(`[LIOP-Router] Processing: ${method}`);
153
+ if (this.liopServer.jwtValidator) {
154
+ const authResult = authorizeRequest(method, authInfo ?? null);
155
+ if (!authResult.allowed) {
156
+ log.info(
157
+ `[LIOP-Router] RBAC Access Denied for method '${method}': ${authResult.reason}`
158
+ );
159
+ return {
160
+ jsonrpc: "2.0",
161
+ id,
162
+ error: {
163
+ code: -32099,
164
+ // Custom authentication/authorization failure code
165
+ message: authResult.reason || "Access Denied"
166
+ }
167
+ };
168
+ }
169
+ }
170
+ switch (method) {
171
+ /** @mcp-legacy Initialize handshake for 2025-era clients. Remove when v1 EOL. */
172
+ case "initialize": {
173
+ if (!MCP_LEGACY_SUPPORT_ENABLED) {
174
+ return {
175
+ jsonrpc: "2.0",
176
+ id,
177
+ error: {
178
+ code: -32601,
179
+ message: "Method retired: initialize (MCP 2026-07-28 is stateless)"
180
+ }
181
+ };
182
+ }
183
+ log.info(
184
+ "[LIOP-Router] \u26A0\uFE0F Legacy MCP client detected (2025-era initialize)."
185
+ );
186
+ return buildLegacyInitializeResponse(
187
+ this.liopServer.getServerInfo(),
188
+ id
189
+ );
190
+ }
191
+ /** @mcp-legacy Initialized notification for 2025-era clients. Remove when v1 EOL. */
192
+ case "notifications/initialized":
193
+ if (!MCP_LEGACY_SUPPORT_ENABLED) return null;
194
+ this.kickDiscoveryAfterInitialized().catch(() => {
195
+ });
196
+ return null;
197
+ case "notifications/cancelled":
198
+ return null;
199
+ // No-op for MCP spec compliance
200
+ case "server/discover":
201
+ return {
202
+ jsonrpc: "2.0",
203
+ id,
204
+ result: {
205
+ resultType: "complete",
206
+ supportedVersions: MCP_LEGACY_SUPPORT_ENABLED ? [MCP_PROTOCOL_VERSION, MCP_PROTOCOL_VERSION_LEGACY] : [MCP_PROTOCOL_VERSION],
207
+ capabilities: {
208
+ tools: { listChanged: true },
209
+ resources: { listChanged: true },
210
+ prompts: { listChanged: true }
211
+ },
212
+ serverInfo: this.liopServer.getServerInfo()
213
+ }
214
+ };
215
+ case "ping":
216
+ return { jsonrpc: "2.0", id, result: {} };
217
+ case "tools/list": {
218
+ const localTools = this.liopServer.listTools();
219
+ const remoteTools = await this.getRemoteTools();
220
+ const listedLocals = mcpCompactToolDescriptions() ? localTools.map((t) => ({
221
+ ...t,
222
+ description: stripVerboseLiopToolDescription(t.description ?? "")
223
+ })) : localTools;
224
+ log.info(
225
+ `[LIOP-Router] tools/list: ${localTools.length} local, ${remoteTools.length} remote tools found`
226
+ );
227
+ const diagnosticTool = {
228
+ name: "LiopMeshStatus",
229
+ description: "LiopMeshStatus: Returns the current dynamic diagnostic status of the Zero-Trust Neural Mesh.",
230
+ inputSchema: {
231
+ type: "object",
232
+ properties: {},
233
+ additionalProperties: false
234
+ }
235
+ };
236
+ const allTools = [diagnosticTool, ...listedLocals, ...remoteTools].sort(
237
+ (a, b) => a.name.localeCompare(b.name)
238
+ );
239
+ const telemetry = TokenTelemetryEngine.getInstance();
240
+ const toolsPayload = JSON.stringify(allTools);
241
+ const toolsResponsePayload = JSON.stringify({ tools: allTools });
242
+ telemetry.record({
243
+ type: "tools_list",
244
+ method: "tools/list",
245
+ estimatedInputTokens: telemetry.countTokens(toolsPayload),
246
+ estimatedOutputTokens: telemetry.countTokens(toolsResponsePayload)
247
+ });
248
+ const era = this.detectEra(request);
249
+ let response = {
250
+ jsonrpc: "2.0",
251
+ id,
252
+ result: {
253
+ resultType: "complete",
254
+ ttlMs: 3e5,
255
+ cacheScope: "public",
256
+ tools: allTools
257
+ }
258
+ };
259
+ if (era === "legacy" && MCP_LEGACY_SUPPORT_ENABLED) {
260
+ response = adaptResponseForLegacyClient(response);
261
+ }
262
+ return response;
263
+ }
264
+ case "tools/call": {
265
+ const response = await this.transcodeMcpToLiop(
266
+ id,
267
+ params,
268
+ authInfo?.token
269
+ );
270
+ if (!response) return null;
271
+ const era = this.detectEra(request);
272
+ if (era === "legacy" && MCP_LEGACY_SUPPORT_ENABLED) {
273
+ return adaptResponseForLegacyClient(response);
274
+ }
275
+ if (response.result && typeof response.result === "object") {
276
+ const resObj = response.result;
277
+ if (!resObj.resultType) {
278
+ resObj.resultType = "complete";
279
+ }
280
+ }
281
+ return response;
282
+ }
283
+ case "resources/list": {
284
+ const localResources = this.liopServer.listResources();
285
+ const remoteResources = await this.getRemoteResources();
286
+ const allResources = [...localResources, ...remoteResources].sort(
287
+ (a, b) => a.uri.localeCompare(b.uri)
288
+ );
289
+ const rlTelemetry = TokenTelemetryEngine.getInstance();
290
+ const rlPayload = JSON.stringify(allResources);
291
+ rlTelemetry.record({
292
+ type: "resource_list",
293
+ method: "resources/list",
294
+ estimatedInputTokens: 0,
295
+ estimatedOutputTokens: rlTelemetry.countTokens(rlPayload)
296
+ });
297
+ const era = this.detectEra(request);
298
+ let response = {
299
+ jsonrpc: "2.0",
300
+ id,
301
+ result: {
302
+ resultType: "complete",
303
+ ttlMs: 3e5,
304
+ cacheScope: "public",
305
+ resources: allResources
306
+ }
307
+ };
308
+ if (era === "legacy" && MCP_LEGACY_SUPPORT_ENABLED) {
309
+ response = adaptResponseForLegacyClient(response);
310
+ }
311
+ return response;
312
+ }
313
+ case "resources/read": {
314
+ const typedParams = params;
315
+ if (!typedParams?.uri)
316
+ return {
317
+ jsonrpc: "2.0",
318
+ id,
319
+ error: { code: -32602, message: "Missing resource uri" }
320
+ };
321
+ try {
322
+ const rrStartTime = Date.now();
323
+ const result = await this.liopServer.readResource(typedParams.uri);
324
+ const rrTelemetry = TokenTelemetryEngine.getInstance();
325
+ const rrOutputPayload = JSON.stringify(result);
326
+ rrTelemetry.record({
327
+ type: "resource_read",
328
+ method: "resources/read",
329
+ toolName: typedParams.uri,
330
+ estimatedInputTokens: rrTelemetry.countTokens(typedParams.uri),
331
+ estimatedOutputTokens: rrTelemetry.countTokens(rrOutputPayload),
332
+ durationMs: Date.now() - rrStartTime
333
+ });
334
+ const era = this.detectEra(request);
335
+ const rawResult = typeof result === "object" && result !== null ? {
336
+ resultType: "complete",
337
+ ttlMs: 6e4,
338
+ cacheScope: "private",
339
+ ...result
340
+ } : {
341
+ resultType: "complete",
342
+ ttlMs: 6e4,
343
+ cacheScope: "private",
344
+ contents: result
345
+ };
346
+ let response = { jsonrpc: "2.0", id, result: rawResult };
347
+ if (era === "legacy" && MCP_LEGACY_SUPPORT_ENABLED) {
348
+ response = adaptResponseForLegacyClient(response);
349
+ }
350
+ return response;
351
+ } catch (err) {
352
+ const targetUri = typedParams.uri;
353
+ for (const { manifest } of this.manifestCache.values()) {
354
+ const remoteResource = manifest.resources.find(
355
+ (r) => r.uri === targetUri
356
+ );
357
+ if (remoteResource) {
358
+ log.info(
359
+ `[LIOP-Router] Resolved resource ${targetUri} from cache (Peer: ${manifest.peerId})`
360
+ );
361
+ const era = this.detectEra(request);
362
+ let response = {
363
+ jsonrpc: "2.0",
364
+ id,
365
+ result: {
366
+ resultType: "complete",
367
+ ttlMs: 6e4,
368
+ cacheScope: "private",
369
+ contents: [
370
+ {
371
+ uri: remoteResource.uri,
372
+ mimeType: remoteResource.mimeType || "text/plain",
373
+ text: remoteResource.text || remoteResource.description || "No content provided"
374
+ }
375
+ ]
376
+ }
377
+ };
378
+ if (era === "legacy" && MCP_LEGACY_SUPPORT_ENABLED) {
379
+ response = adaptResponseForLegacyClient(response);
380
+ }
381
+ return response;
382
+ }
383
+ }
384
+ return {
385
+ jsonrpc: "2.0",
386
+ id,
387
+ error: {
388
+ code: -32e3,
389
+ message: err instanceof Error ? err.message : String(err)
390
+ }
391
+ };
392
+ }
393
+ }
394
+ case "prompts/list": {
395
+ const promptsList = this.liopServer.listPrompts().sort((a, b) => a.name.localeCompare(b.name));
396
+ const plTelemetry = TokenTelemetryEngine.getInstance();
397
+ const plPayload = JSON.stringify(promptsList);
398
+ plTelemetry.record({
399
+ type: "prompt_list",
400
+ method: "prompts/list",
401
+ estimatedInputTokens: 0,
402
+ estimatedOutputTokens: plTelemetry.countTokens(plPayload)
403
+ });
404
+ const era = this.detectEra(request);
405
+ let response = {
406
+ jsonrpc: "2.0",
407
+ id,
408
+ result: {
409
+ resultType: "complete",
410
+ ttlMs: 3e5,
411
+ cacheScope: "public",
412
+ prompts: promptsList
413
+ }
414
+ };
415
+ if (era === "legacy" && MCP_LEGACY_SUPPORT_ENABLED) {
416
+ response = adaptResponseForLegacyClient(response);
417
+ }
418
+ return response;
419
+ }
420
+ case "prompts/get": {
421
+ const typedParams = params;
422
+ if (!typedParams?.name)
423
+ return {
424
+ jsonrpc: "2.0",
425
+ id,
426
+ error: { code: -32602, message: "Missing prompt name" }
427
+ };
428
+ try {
429
+ const pgStartTime = Date.now();
430
+ const result = await this.liopServer.getPrompt({
431
+ name: typedParams.name,
432
+ arguments: typedParams.arguments || {}
433
+ });
434
+ const pgTelemetry = TokenTelemetryEngine.getInstance();
435
+ const pgInputPayload = JSON.stringify({
436
+ name: typedParams.name,
437
+ arguments: typedParams.arguments
438
+ });
439
+ const pgOutputPayload = JSON.stringify(result);
440
+ pgTelemetry.record({
441
+ type: "prompt_get",
442
+ method: "prompts/get",
443
+ toolName: typedParams.name,
444
+ estimatedInputTokens: pgTelemetry.countTokens(pgInputPayload),
445
+ estimatedOutputTokens: pgTelemetry.countTokens(pgOutputPayload),
446
+ durationMs: Date.now() - pgStartTime
447
+ });
448
+ const era = this.detectEra(request);
449
+ const rawResult = typeof result === "object" && result !== null ? { resultType: "complete", ...result } : result;
450
+ let response = { jsonrpc: "2.0", id, result: rawResult };
451
+ if (era === "legacy" && MCP_LEGACY_SUPPORT_ENABLED) {
452
+ response = adaptResponseForLegacyClient(response);
453
+ }
454
+ return response;
455
+ } catch (err) {
456
+ return {
457
+ jsonrpc: "2.0",
458
+ id,
459
+ error: {
460
+ code: -32e3,
461
+ message: err instanceof Error ? err.message : String(err)
462
+ }
463
+ };
464
+ }
465
+ }
466
+ case "resources/templates/list": {
467
+ const era = this.detectEra(request);
468
+ let response = {
469
+ jsonrpc: "2.0",
470
+ id,
471
+ result: {
472
+ resultType: "complete",
473
+ ttlMs: 3e5,
474
+ cacheScope: "public",
475
+ resourceTemplates: []
476
+ }
477
+ };
478
+ if (era === "legacy" && MCP_LEGACY_SUPPORT_ENABLED) {
479
+ response = adaptResponseForLegacyClient(response);
480
+ }
481
+ return response;
482
+ }
483
+ case "subscriptions/listen": {
484
+ const era = this.detectEra(request);
485
+ let response = {
486
+ jsonrpc: "2.0",
487
+ id,
488
+ result: {
489
+ resultType: "complete"
490
+ }
491
+ };
492
+ if (era === "legacy" && MCP_LEGACY_SUPPORT_ENABLED) {
493
+ response = adaptResponseForLegacyClient(response);
494
+ }
495
+ return response;
496
+ }
497
+ default:
498
+ return {
499
+ jsonrpc: "2.0",
500
+ id,
501
+ error: { code: -32601, message: `Method not found: ${method}` }
502
+ };
503
+ }
504
+ }
505
+ /**
506
+ * MCP clients often send notifications/initialized then immediately tools/list.
507
+ * Start manifest discovery without blocking the notification handler.
508
+ */
509
+ kickDiscoveryAfterInitialized() {
510
+ return (async () => {
511
+ await new Promise((r) => setTimeout(r, 250));
512
+ await Promise.race([
513
+ this.refreshManifestCache(true),
514
+ new Promise((r) => setTimeout(r, 15e3))
515
+ ]).catch(() => {
516
+ });
517
+ })();
518
+ }
519
+ /**
520
+ * Discovers and caches manifests from all remote LIOP providers in the mesh.
521
+ * Uses Kademlia DHT to find "liop:manifest" providers, then opens
522
+ * /liop/manifest/1.0.0 protocol streams to retrieve their full metadata.
523
+ */
524
+ async refreshManifestCache(silent = false) {
525
+ if (!this.meshNode) return;
526
+ if (this.currentDiscovery) return this.currentDiscovery;
527
+ if (!silent && this.manifestCache.size > 0) {
528
+ const now = Date.now();
529
+ const allFresh = Array.from(this.manifestCache.values()).every(
530
+ ({ cachedAt }) => now - cachedAt < MANIFEST_CACHE_TTL_S * 1e3
531
+ );
532
+ if (allFresh) return;
533
+ }
534
+ this.currentDiscovery = (async () => {
535
+ try {
536
+ const prevCount = Array.from(this.manifestCache.values()).reduce(
537
+ (acc, { manifest }) => acc + manifest.tools.length,
538
+ 0
539
+ );
540
+ if (this.manifestCache.size === 0) {
541
+ for (let i = 0; i < 3; i++) {
542
+ const connections = (
543
+ // biome-ignore lint/suspicious/noExplicitAny: access internal nodes for connection count
544
+ this.meshNode.node?.getConnections().length || 0
545
+ );
546
+ if (connections > 0) {
547
+ log.info(
548
+ `[LIOP-Router] P2P Connection established. Starting discovery...`
549
+ );
550
+ break;
551
+ }
552
+ log.info(
553
+ `[LIOP-Router] Waiting for P2P connections (attempt ${i + 1}/10)...`
554
+ );
555
+ await new Promise((r) => setTimeout(r, 1e3));
556
+ }
557
+ }
558
+ let providerIds = [];
559
+ const MAX_COLD_ATTEMPTS = this.manifestCache.size === 0 ? 5 : 1;
560
+ for (let coldAttempt = 0; coldAttempt < MAX_COLD_ATTEMPTS; coldAttempt++) {
561
+ for (let attempt = 0; attempt < MANIFEST_DISCOVERY_RETRIES; attempt++) {
562
+ providerIds = await this.meshNode?.discoverManifestProviders() || [];
563
+ const selfId2 = this.meshNode?.getPeerId();
564
+ const remoteIds = providerIds.filter((id) => id !== selfId2);
565
+ if (remoteIds.length > 0) break;
566
+ if (attempt < MANIFEST_DISCOVERY_RETRIES - 1) {
567
+ log.info(
568
+ `[LIOP-Router] DHT discovery attempt ${attempt + 1}/${MANIFEST_DISCOVERY_RETRIES}...`
569
+ );
570
+ await new Promise((r) => setTimeout(r, 1e3));
571
+ }
572
+ }
573
+ const activePeers = (
574
+ // biome-ignore lint/suspicious/noExplicitAny: access internal nodes
575
+ this.meshNode.node?.getConnections().map(
576
+ (c) => c.remotePeer.toString()
577
+ ) || []
578
+ );
579
+ if (activePeers.length > 0) {
580
+ providerIds = Array.from(/* @__PURE__ */ new Set([...providerIds, ...activePeers]));
581
+ }
582
+ const selfIdEnd = this.meshNode?.getPeerId();
583
+ const remoteIdsEnd = providerIds.filter((id) => id !== selfIdEnd);
584
+ if (remoteIdsEnd.length > 0) break;
585
+ if (coldAttempt < MAX_COLD_ATTEMPTS - 1) {
586
+ log.info(
587
+ `[LIOP-Router] Initial discovery failed (0 providers). Retrying in 1s (${coldAttempt + 1}/${MAX_COLD_ATTEMPTS})...`
588
+ );
589
+ await new Promise((r) => setTimeout(r, 1e3));
590
+ }
591
+ }
592
+ if (providerIds.length === 0) {
593
+ log.info(
594
+ `[LIOP-Router] No manifest providers found after all attempts.`
595
+ );
596
+ return;
597
+ }
598
+ if (!silent) {
599
+ log.info(
600
+ `[LIOP-Router] Discovered ${providerIds.length} candidate manifest providers`
601
+ );
602
+ }
603
+ const connectedPeers = new Set(
604
+ // biome-ignore lint/suspicious/noExplicitAny: internal node access for fast peer ordering
605
+ (this.meshNode.node?.getConnections?.() || []).map(
606
+ (c) => c.remotePeer.toString()
607
+ )
608
+ );
609
+ providerIds = [...providerIds].sort((a, b) => {
610
+ const aConnected = connectedPeers.has(a) ? 1 : 0;
611
+ const bConnected = connectedPeers.has(b) ? 1 : 0;
612
+ return bConnected - aConnected;
613
+ });
614
+ let successCount = 0;
615
+ let errorCount = 0;
616
+ let cacheUpdated = false;
617
+ const selfId = this.meshNode?.getPeerId();
618
+ const eligiblePeers = providerIds.filter((peerId) => {
619
+ if (!this.meshNode) return false;
620
+ if (peerId === selfId) return false;
621
+ if (this.shouldSkipManifestQuery(peerId)) return false;
622
+ const cached = this.manifestCache.get(peerId);
623
+ if (cached && Date.now() - cached.cachedAt < MANIFEST_CACHE_TTL_S * 1e3) {
624
+ successCount++;
625
+ return false;
626
+ }
627
+ return true;
628
+ });
629
+ await Promise.allSettled(
630
+ eligiblePeers.map(async (peerId) => {
631
+ if (!this.meshNode) return;
632
+ log.info(`[LIOP-Router] Querying manifest from: ${peerId}`);
633
+ try {
634
+ const manifest = await this.meshNode.queryManifest(peerId);
635
+ if (manifest) {
636
+ if (manifest.pqcSignature && manifest.pqcPublicKey) {
637
+ const isValid = Dilithium65Wrapper.verifyManifest(
638
+ manifest,
639
+ manifest.pqcSignature,
640
+ manifest.pqcPublicKey
641
+ );
642
+ if (!isValid) {
643
+ log.warn(
644
+ `[LIOP-Router] \u26A0\uFE0F Tampered manifest rejected for peer ${peerId} (ML-DSA-65 signature invalid)`
645
+ );
646
+ this.recordManifestQueryFailure(peerId);
647
+ errorCount++;
648
+ return;
649
+ }
650
+ log.info(
651
+ `[LIOP-Router] \u{1F512} ML-DSA-65 (FIPS 204) Manifest attestation verified for peer ${peerId}`
652
+ );
653
+ }
654
+ this.manifestCache.set(peerId, {
655
+ manifest,
656
+ cachedAt: Date.now()
657
+ });
658
+ this.recordManifestQuerySuccess(peerId);
659
+ cacheUpdated = true;
660
+ successCount++;
661
+ log.info(
662
+ `[LIOP-Router] Manifest received from ${peerId} (${manifest.tools.length} tools)`
663
+ );
664
+ } else {
665
+ this.recordManifestQueryFailure(peerId);
666
+ errorCount++;
667
+ log.info(
668
+ `[LIOP-Router] Manifest query returned NULL for ${peerId}`
669
+ );
670
+ }
671
+ } catch (err) {
672
+ errorCount++;
673
+ log.info(
674
+ `[LIOP-Router] Fatal error querying manifest:`,
675
+ err instanceof Error ? err.message : String(err)
676
+ );
677
+ }
678
+ })
679
+ );
680
+ this._discoveryStats = {
681
+ candidates: providerIds.length,
682
+ success: successCount,
683
+ failures: errorCount,
684
+ lastDiscovery: Date.now()
685
+ };
686
+ if (cacheUpdated) {
687
+ const newCount = Array.from(this.manifestCache.values()).reduce(
688
+ (acc, { manifest }) => acc + manifest.tools.length,
689
+ 0
690
+ );
691
+ if (newCount !== prevCount && this.onToolsChanged) {
692
+ process.stderr.write(
693
+ "[LIOP-Router] Mesh topology updated! Emitting notifications/tools/list_changed.\n"
694
+ );
695
+ this.onToolsChanged();
696
+ }
697
+ }
698
+ } finally {
699
+ this.currentDiscovery = null;
700
+ }
701
+ })();
702
+ return this.currentDiscovery;
703
+ }
704
+ /**
705
+ * Returns the current manifest cache size for external telemetry.
706
+ * Used by the adaptive polling system to detect topology stabilization.
707
+ */
708
+ getCacheSize() {
709
+ return this.manifestCache.size;
710
+ }
711
+ /**
712
+ * Returns all remote tools discovered via the manifest protocol.
713
+ */
714
+ async getRemoteTools() {
715
+ const EXPECTED_PROVIDERS = Number.parseInt(
716
+ process.env.LIOP_EXPECTED_PROVIDERS ?? "1",
717
+ 10
718
+ );
719
+ if (this.manifestCache.size < EXPECTED_PROVIDERS && this.meshNode) {
720
+ const initialTimeoutMs = Number.parseInt(
721
+ process.env.LIOP_INITIAL_DISCOVERY_TIMEOUT_MS ?? "8000",
722
+ 10
723
+ );
724
+ const boundedTimeoutMs = Number.isFinite(initialTimeoutMs) && initialTimeoutMs > 0 ? initialTimeoutMs : 12e3;
725
+ const deadline = Date.now() + boundedTimeoutMs;
726
+ let stableCount = 0;
727
+ let lastCacheSize = -1;
728
+ while (Date.now() < deadline) {
729
+ if (this.manifestCache.size >= EXPECTED_PROVIDERS) break;
730
+ await Promise.race([
731
+ this.refreshManifestCache(true),
732
+ new Promise((resolve) => setTimeout(resolve, 3e3))
733
+ ]).catch(() => {
734
+ });
735
+ if (this.manifestCache.size >= EXPECTED_PROVIDERS) break;
736
+ if (this.manifestCache.size === lastCacheSize) {
737
+ stableCount++;
738
+ if (stableCount >= 3 && this.manifestCache.size > 0) {
739
+ log.info(
740
+ `[LIOP-Router] Provider count stabilized at ${this.manifestCache.size}/${EXPECTED_PROVIDERS}. Proceeding with available mesh.`
741
+ );
742
+ break;
743
+ }
744
+ } else {
745
+ stableCount = 0;
746
+ lastCacheSize = this.manifestCache.size;
747
+ }
748
+ await new Promise((r) => setTimeout(r, 1e3));
749
+ }
750
+ if (this.manifestCache.size < EXPECTED_PROVIDERS) {
751
+ log.info(
752
+ `[LIOP-Router] \u26A0\uFE0F Mesh partially available: ${this.manifestCache.size}/${EXPECTED_PROVIDERS} providers. Some tools may be unavailable. Check Docker containers.`
753
+ );
754
+ this.refreshManifestCache(true).catch(() => {
755
+ });
756
+ }
757
+ }
758
+ const tools = [];
759
+ const seenNames = /* @__PURE__ */ new Set();
760
+ const localToolNames = new Set(
761
+ this.liopServer.listTools().map((t) => t.name)
762
+ );
763
+ for (const [peerId, { manifest }] of this.manifestCache.entries()) {
764
+ for (const tool of manifest.tools) {
765
+ if (tool.name === "LiopMeshStatus") continue;
766
+ let finalName = tool.name;
767
+ if (seenNames.has(tool.name) || localToolNames.has(tool.name)) {
768
+ finalName = `${tool.name}_${peerId.slice(-4)}`;
769
+ }
770
+ seenNames.add(finalName);
771
+ const providerName = manifest.serverInfo?.name || "Unknown Provider";
772
+ const baseDesc = tool.description || `Remote tool from ${providerName}`;
773
+ const cleanTool = {
774
+ name: finalName,
775
+ description: mcpCompactToolDescriptions() ? stripVerboseLiopToolDescription(baseDesc) : baseDesc,
776
+ inputSchema: tool.inputSchema || {
777
+ type: "object",
778
+ properties: {}
779
+ }
780
+ };
781
+ if (typeof cleanTool.inputSchema === "object" && !cleanTool.inputSchema.type) {
782
+ cleanTool.inputSchema.type = "object";
783
+ }
784
+ if (typeof cleanTool.inputSchema === "object" && !cleanTool.inputSchema.properties) {
785
+ cleanTool.inputSchema.properties = {};
786
+ }
787
+ let blueprint = "";
788
+ if (manifest.taxonomy) {
789
+ blueprint = `
790
+ [LIOP-DOMAIN: ${manifest.taxonomy.domain}]`;
791
+ }
792
+ const properties = cleanTool.inputSchema.properties || {};
793
+ let envelopeDoc = "";
794
+ if (!mcpCompactToolDescriptions() && properties.payload) {
795
+ envelopeDoc = `
796
+ [REQUIRES: LIOP-PROTO-V1 ENVELOPE]`;
797
+ }
798
+ if (!mcpCompactToolDescriptions() && cleanTool.description.includes("STRICT SCHEMA ADHERENCE")) {
799
+ cleanTool.description = cleanTool.description.replace(
800
+ "STRICT SCHEMA ADHERENCE:",
801
+ "[INDUSTRIAL-REQUISITE] STRICT SCHEMA ADHERENCE (MANDATORY):"
802
+ );
803
+ }
804
+ const originStamp = mcpCompactToolDescriptions() ? `
805
+ (Peer: ${peerId.slice(-8)})${blueprint}` : `
806
+ (Origin: ${peerId.slice(-8)})${blueprint}${envelopeDoc}`;
807
+ cleanTool.description = `${cleanTool.description}${originStamp}`;
808
+ tools.push(cleanTool);
809
+ }
810
+ }
811
+ return tools;
812
+ }
813
+ /**
814
+ * Returns all remote resources discovered via the manifest protocol.
815
+ */
816
+ async getRemoteResources() {
817
+ if (!this.currentDiscovery) {
818
+ this.refreshManifestCache(true).catch(() => {
819
+ });
820
+ }
821
+ const resources = [];
822
+ const seenUris = new Set(this.liopServer.listResources().map((r) => r.uri));
823
+ for (const [peerId, { manifest }] of this.manifestCache.entries()) {
824
+ for (const resource of manifest.resources) {
825
+ if (!seenUris.has(resource.uri)) {
826
+ const augmentedResource = { ...resource };
827
+ const providerName = manifest.serverInfo?.name || "Unknown Provider";
828
+ let blueprint = "";
829
+ if (manifest.taxonomy) {
830
+ blueprint = `
831
+
832
+ [LIOP Zero-Trust Blueprint]
833
+ Domain: ${manifest.taxonomy.domain}
834
+ Clearance Tier: ${manifest.taxonomy.clearanceTier}`;
835
+ if (manifest.taxonomy.executionTypes && manifest.taxonomy.executionTypes.length > 0) {
836
+ blueprint += `
837
+ Execution Types: ${manifest.taxonomy.executionTypes.join(", ")}`;
838
+ }
839
+ }
840
+ const originStamp = `
841
+
842
+ [LIOP Zero-Trust Origin]
843
+ Provider: ${providerName}
844
+ Network ID: ${peerId}${blueprint}`;
845
+ if (augmentedResource.uri.startsWith("liop://schema/")) {
846
+ augmentedResource.name = `[SCHEMA] ${augmentedResource.name}`;
847
+ augmentedResource.description = `[CRITICAL SCHEMA] ${augmentedResource.description || "Data Dictionary for Zero-Shot Autonomy"}${originStamp}`;
848
+ } else {
849
+ augmentedResource.description = augmentedResource.description ? `${augmentedResource.description}${originStamp}` : originStamp.trim();
850
+ }
851
+ resources.push(augmentedResource);
852
+ seenUris.add(resource.uri);
853
+ }
854
+ }
855
+ }
856
+ return resources;
857
+ }
858
+ /**
859
+ * Resolves the gRPC target (host:port) AND the peerId for a given tool name
860
+ * by searching the manifest cache. Supports exact names and suffixed names.
861
+ */
862
+ resolveManifestTarget(toolName) {
863
+ for (const [peerId, { manifest }] of this.manifestCache.entries()) {
864
+ const tool = manifest.tools.find((t) => t.name === toolName);
865
+ if (tool) {
866
+ return {
867
+ peerId,
868
+ originalToolName: toolName
869
+ };
870
+ }
871
+ }
872
+ const parts = toolName.split("_");
873
+ if (parts.length > 1) {
874
+ const suffix = parts.pop();
875
+ const baseName = parts.join("_");
876
+ for (const [peerId, { manifest }] of this.manifestCache.entries()) {
877
+ if (peerId.endsWith(suffix || "")) {
878
+ const tool = manifest.tools.find((t) => t.name === baseName);
879
+ if (tool) {
880
+ return {
881
+ peerId,
882
+ originalToolName: baseName
883
+ };
884
+ }
885
+ }
886
+ }
887
+ }
888
+ return null;
889
+ }
890
+ /**
891
+ * Redacts a PeerID for external-facing diagnostics.
892
+ * LIOP_DIAGNOSTIC_LEVEL controls verbosity:
893
+ * - "redacted" (default): truncated to last 8 chars
894
+ * - "full": complete PeerID (development only)
895
+ */
896
+ redactPeerId(peerId) {
897
+ const level = process.env.LIOP_DIAGNOSTIC_LEVEL || "redacted";
898
+ if (level === "full") return peerId;
899
+ return `***${peerId.slice(-8)}`;
900
+ }
901
+ async transcodeMcpToLiop(id, params, token) {
902
+ const toolName = params.name;
903
+ if (toolName === "LiopMeshStatus") {
904
+ this.refreshManifestCache(true).catch(() => {
905
+ });
906
+ const stats = this._discoveryStats || {
907
+ candidates: 0,
908
+ success: 0,
909
+ failures: 0
910
+ };
911
+ const providerCount = this.manifestCache.size;
912
+ const meshState = this.meshNode ? "Active" : "Offline";
913
+ const cachedTools = Array.from(this.manifestCache.values()).reduce(
914
+ (acc, { manifest }) => acc + manifest.tools.length,
915
+ 0
916
+ );
917
+ const connections = this.meshNode ? (
918
+ // biome-ignore lint/suspicious/noExplicitAny: access internal nodes
919
+ this.meshNode.node?.getConnections().length
920
+ ) : 0;
921
+ const bootstrapNodes = this.meshNode && // biome-ignore lint/suspicious/noExplicitAny: access internal config
922
+ this.meshNode.config?.bootstrapNodes ? (
923
+ // biome-ignore lint/suspicious/noExplicitAny: access internal config
924
+ this.meshNode.config.bootstrapNodes
925
+ ) : [];
926
+ const bootstrapCount = bootstrapNodes.length;
927
+ const diagLevel = process.env.LIOP_DIAGNOSTIC_LEVEL || "redacted";
928
+ const showBootstraps = diagLevel !== "minimal";
929
+ const bootstrapList = showBootstraps ? bootstrapNodes.map((addr) => {
930
+ const parts = addr.split("/");
931
+ const id2 = parts[parts.length - 1];
932
+ return ` \u2022 ${id2 ? id2.slice(-8) : "Unknown"} (bootstrap)`;
933
+ }).join("\n") : "";
934
+ const routingTableSize = this.meshNode ? (
935
+ // biome-ignore lint/suspicious/noExplicitAny: access internal nodes
936
+ this.meshNode.getRoutingTableSize()
937
+ ) : 0;
938
+ const rawPeerId = this.meshNode?.getPeerId() || "Offline";
939
+ const localPeerId = rawPeerId === "Offline" ? rawPeerId : this.redactPeerId(rawPeerId);
940
+ const cachedToolList = Array.from(this.manifestCache.entries()).flatMap(
941
+ ([peerId, { manifest }]) => manifest.tools.map(
942
+ (t) => ` \u2022 ${t.name} (from origin: ${this.redactPeerId(peerId)})`
943
+ )
944
+ ).join("\n");
945
+ const statusText = [
946
+ `LIOP Mesh Status: ${meshState === "Active" ? "Active" : "Offline"}`,
947
+ `Local Agent Identity: ${localPeerId}`,
948
+ `Network: ${connections} Conns | ${routingTableSize} Mesh Nodes | ${bootstrapCount} Bootstraps`,
949
+ showBootstraps && bootstrapCount > 0 ? `
950
+ Active Bootstraps:
951
+ ${bootstrapList}
952
+ ` : "",
953
+ `Discovery: ${stats.candidates} Candidates | ${stats.success} OK | ${stats.failures} FAIL`,
954
+ `Tooling: ${providerCount} Providers | ${cachedTools} Total Remote Tools`,
955
+ cachedTools > 0 ? `
956
+ Discovered Remote Tools (Zero-Trust Origins):
957
+ ${cachedToolList}` : "\nNo remote tools discovered yet.",
958
+ // [Token Economy] Telemetry block (only appears when operations exist)
959
+ TokenTelemetryEngine.getInstance().formatStatusBlock()
960
+ ].filter((line) => line !== "").join("\n");
961
+ const diagTelemetry = TokenTelemetryEngine.getInstance();
962
+ diagTelemetry.record({
963
+ type: "diagnostic",
964
+ method: "tools/call",
965
+ toolName: "LiopMeshStatus",
966
+ estimatedInputTokens: 0,
967
+ estimatedOutputTokens: diagTelemetry.countTokens(statusText)
968
+ });
969
+ return {
970
+ jsonrpc: "2.0",
971
+ id,
972
+ result: {
973
+ content: [
974
+ {
975
+ type: "text",
976
+ text: statusText
977
+ }
978
+ ]
979
+ }
980
+ };
981
+ }
982
+ const isLocal = this.liopServer.listTools().some((t) => t.name === toolName);
983
+ if (!isLocal && this.meshNode) {
984
+ let target = this.resolveManifestTarget(toolName);
985
+ if (!target) {
986
+ await this.refreshManifestCache();
987
+ target = this.resolveManifestTarget(toolName);
988
+ }
989
+ if (target) {
990
+ log.info(
991
+ `[LIOP-Router] Resolved ${toolName} via manifest cache (Peer: ${target.peerId}, Original: ${target.originalToolName})`
992
+ );
993
+ const manifestEntry = this.manifestCache.get(target.peerId);
994
+ let effectiveToken = token;
995
+ if (manifestEntry?.manifest.authRequired) {
996
+ const resolvedToken = token || await this.getOrAcquireMeshAgentToken(target.peerId);
997
+ if (!resolvedToken) {
998
+ const providerName = manifestEntry.manifest.serverInfo?.name?.toLowerCase() || "unknown";
999
+ const slug = manifestEntry.manifest.tokenSlug;
1000
+ const shortId = target.peerId.slice(-8).toUpperCase();
1001
+ const primaryVar = slug ? `LIOP_TOKEN_${slug}` : `LIOP_TOKEN_${providerName.toUpperCase().replace(/[^A-Z0-9_]/g, "_")}`;
1002
+ return {
1003
+ jsonrpc: "2.0",
1004
+ id,
1005
+ result: {
1006
+ content: [
1007
+ {
1008
+ type: "text",
1009
+ text: `Authentication Required: The restricted node (${providerName}) requires an access token. Please define the ${primaryVar} or LIOP_TOKEN_${shortId} environment variable on your agent/client host.`
1010
+ }
1011
+ ],
1012
+ isError: true
1013
+ }
1014
+ };
1015
+ }
1016
+ effectiveToken = resolvedToken;
1017
+ }
1018
+ return this.routeToRemoteProvider(
1019
+ id,
1020
+ target.originalToolName,
1021
+ target.peerId,
1022
+ params,
1023
+ effectiveToken
1024
+ );
1025
+ }
1026
+ let providers = [];
1027
+ for (let i = 0; i < 3; i++) {
1028
+ providers = await this.meshNode.findProviders(toolName);
1029
+ if (providers.length > 0) break;
1030
+ if (i < 2) await new Promise((r) => setTimeout(r, 1e3));
1031
+ }
1032
+ if (providers.length > 0) {
1033
+ return this.routeToRemoteProvider(
1034
+ id,
1035
+ toolName,
1036
+ providers[0],
1037
+ params,
1038
+ token
1039
+ );
1040
+ }
1041
+ }
1042
+ if (isLocal) {
1043
+ try {
1044
+ const localStartTime = Date.now();
1045
+ const result = await this.liopServer.callTool({
1046
+ name: toolName,
1047
+ arguments: params.arguments || {}
1048
+ });
1049
+ const localTelemetry = TokenTelemetryEngine.getInstance();
1050
+ const localInputPayload = JSON.stringify(params.arguments || {});
1051
+ const localOutputPayload = JSON.stringify(result);
1052
+ let originDatasetTokens;
1053
+ const sandboxRecords = this.liopServer.getSandboxData();
1054
+ if (sandboxRecords && sandboxRecords.length > 0) {
1055
+ originDatasetTokens = localTelemetry.countTokens(
1056
+ JSON.stringify(sandboxRecords)
1057
+ );
1058
+ }
1059
+ localTelemetry.record({
1060
+ type: "tool_call",
1061
+ method: "tools/call",
1062
+ toolName,
1063
+ estimatedInputTokens: localTelemetry.countTokens(localInputPayload),
1064
+ estimatedOutputTokens: localTelemetry.countTokens(localOutputPayload),
1065
+ durationMs: Date.now() - localStartTime,
1066
+ originDatasetTokens
1067
+ });
1068
+ toolCallsTotal.inc({
1069
+ capability: toolName,
1070
+ tool: toolName,
1071
+ status: result.isError ? "error" : "success",
1072
+ role: "executor"
1073
+ });
1074
+ return { jsonrpc: "2.0", id, result };
1075
+ } catch (err) {
1076
+ return {
1077
+ jsonrpc: "2.0",
1078
+ id,
1079
+ error: {
1080
+ code: -32e3,
1081
+ message: err instanceof Error ? err.message : String(err)
1082
+ }
1083
+ };
1084
+ }
1085
+ }
1086
+ return {
1087
+ jsonrpc: "2.0",
1088
+ id,
1089
+ error: {
1090
+ code: -32002,
1091
+ message: `No provider found for tool: ${toolName}. Ensure the provider node is active and connected to the mesh.`
1092
+ }
1093
+ };
1094
+ }
1095
+ async routeToRemoteProvider(id, toolName, peerId, params, token) {
1096
+ if (!this.meshNode)
1097
+ return {
1098
+ jsonrpc: "2.0",
1099
+ id,
1100
+ error: { code: -32603, message: "Mesh Node inactive" }
1101
+ };
1102
+ let manifestEntry = this.manifestCache.get(peerId);
1103
+ let grpcPort = this.defaultRpcPort;
1104
+ if (manifestEntry) {
1105
+ grpcPort = manifestEntry.manifest.grpcPort;
1106
+ } else {
1107
+ const manifest = await this.meshNode.queryManifest(peerId);
1108
+ if (manifest) {
1109
+ grpcPort = manifest.grpcPort;
1110
+ this.manifestCache.set(peerId, {
1111
+ manifest,
1112
+ cachedAt: Date.now()
1113
+ });
1114
+ manifestEntry = this.manifestCache.get(peerId);
1115
+ }
1116
+ }
1117
+ const addrs = await this.meshNode.resolvePeer(peerId);
1118
+ const nexusUrl = process.env.LIOP_NEXUS_URL || "";
1119
+ const isDockerDemo = nexusUrl.includes("127.0.0.1:13000") || nexusUrl.includes("localhost:13000") || nexusUrl.includes("127.0.0.1:13001") || nexusUrl.includes("localhost:13001");
1120
+ const isDockerPort = addrs.some(
1121
+ (a) => a.includes("13001") || a.includes("13003") || a.includes("13004") || a.includes("13005") || a.includes("13011") || a.includes("13021") || a.includes("13031")
1122
+ );
1123
+ const shouldRemapGrpcPorts = process.env.LIOP_USE_PUBLISHED_GRPC_PORTS === "1" || process.env.LIOP_DOCKER_MAP === "true" || process.env.LIOP_DEV_MODE === "true" || process.env.NODE_ENV === "development" || process.env.NODE_ENV === "test" || isDockerDemo || isDockerPort;
1124
+ if (shouldRemapGrpcPorts) {
1125
+ const providerName = manifestEntry?.manifest?.serverInfo?.name?.toLowerCase() || "";
1126
+ const tn = toolName.toLowerCase();
1127
+ if (providerName.includes("vault") || tn.includes("medical")) {
1128
+ grpcPort = 13011;
1129
+ } else if (providerName.includes("bank") || tn.includes("bank")) {
1130
+ grpcPort = 13021;
1131
+ } else if (providerName.includes("oracle") || tn.includes("hft") || tn.includes("market")) {
1132
+ grpcPort = 13031;
1133
+ }
1134
+ }
1135
+ let targetAddr = null;
1136
+ if (shouldRemapGrpcPorts) {
1137
+ targetAddr = `127.0.0.1:${grpcPort}`;
1138
+ } else {
1139
+ const os = await import('os');
1140
+ const localInterfaces = Object.values(os.networkInterfaces()).flat().filter((i) => i?.family === "IPv4").map((i) => i?.address);
1141
+ for (const addr of addrs) {
1142
+ const parts = addr.split("/");
1143
+ const ipIdx = parts.indexOf("ip4");
1144
+ if (ipIdx !== -1) {
1145
+ const advertisedIp = parts[ipIdx + 1];
1146
+ if (advertisedIp === "127.0.0.1" || localInterfaces.includes(advertisedIp)) {
1147
+ targetAddr = `127.0.0.1:${grpcPort}`;
1148
+ break;
1149
+ }
1150
+ if (!targetAddr) {
1151
+ targetAddr = `${advertisedIp}:${grpcPort}`;
1152
+ }
1153
+ }
1154
+ }
1155
+ }
1156
+ if (!targetAddr) {
1157
+ targetAddr = `127.0.0.1:${grpcPort}`;
1158
+ }
1159
+ log.info(
1160
+ `[LIOP-Router] Dynamic route: ${toolName} -> ${targetAddr} (PeerID: ${peerId})`
1161
+ );
1162
+ const remoteClient = new liopV1.LogicMesh(
1163
+ targetAddr,
1164
+ createChannelCredentials({ insecure: true, suppressWarning: true }),
1165
+ GRPC_CHANNEL_OPTIONS
1166
+ );
1167
+ return this.performTranscoding(
1168
+ id,
1169
+ remoteClient,
1170
+ toolName,
1171
+ params,
1172
+ peerId,
1173
+ token
1174
+ );
1175
+ }
1176
+ /** Cached M2M token for dynamic gateway-to-node routing */
1177
+ meshAgentToken;
1178
+ /**
1179
+ * Dynamically acquires an M2M access token from the Nexus Authorization Server.
1180
+ * If peerId is provided, checks if there are node-specific environment tokens
1181
+ * before falling back to the global static token or Nexus acquisition.
1182
+ */
1183
+ async getOrAcquireMeshAgentToken(peerId) {
1184
+ if (peerId) {
1185
+ const manifestEntry = this.manifestCache.get(peerId);
1186
+ const providerName = manifestEntry?.manifest.serverInfo?.name?.toLowerCase() || "";
1187
+ let nodeToken;
1188
+ const slug = manifestEntry?.manifest.tokenSlug;
1189
+ if (slug) {
1190
+ const envKey = `LIOP_TOKEN_${slug}`;
1191
+ nodeToken = process.env[envKey] || process.env[`LIOP_OAUTH_TOKEN_${slug}`];
1192
+ log.info(
1193
+ `[LIOP-Router] Step0 tokenSlug=${slug} envKey=${envKey} found=${!!nodeToken} peer=${peerId.slice(-8)}`
1194
+ );
1195
+ } else {
1196
+ log.info(
1197
+ `[LIOP-Router] Step0 tokenSlug=MISSING (manifest has no tokenSlug) peer=${peerId.slice(-8)} provider=${providerName}`
1198
+ );
1199
+ }
1200
+ if (!nodeToken) {
1201
+ const shortId = peerId.slice(-8).toUpperCase();
1202
+ nodeToken = process.env[`LIOP_TOKEN_${shortId}`] || process.env[`LIOP_OAUTH_TOKEN_${shortId}`];
1203
+ }
1204
+ if (!nodeToken && providerName) {
1205
+ const cleanName = providerName.toUpperCase().replace(/[^A-Z0-9_]/g, "_");
1206
+ nodeToken = process.env[`LIOP_TOKEN_${cleanName}`] || process.env[`LIOP_OAUTH_TOKEN_${cleanName}`];
1207
+ }
1208
+ if (nodeToken) {
1209
+ log.info(
1210
+ `[LIOP-Router] Resolved node-specific token for peer ${peerId.slice(-8)} (${providerName || "unknown"})`
1211
+ );
1212
+ return nodeToken;
1213
+ }
1214
+ }
1215
+ if (this.meshAgentToken) return this.meshAgentToken;
1216
+ const staticToken = process.env.LIOP_OAUTH_TOKEN || process.env.LIOP_TOKEN;
1217
+ if (staticToken) {
1218
+ this.meshAgentToken = staticToken;
1219
+ return this.meshAgentToken;
1220
+ }
1221
+ const nexusUrl = process.env.LIOP_NEXUS_URL;
1222
+ if (!nexusUrl) return void 0;
1223
+ const clientId = process.env.LIOP_OAUTH_CLIENT_ID || process.env.LIOP_CLIENT_ID || "liop-mesh-agent";
1224
+ const clientSecret = process.env.LIOP_OAUTH_CLIENT_SECRET || process.env.LIOP_CLIENT_SECRET || "dev-secret-change-me";
1225
+ const audience = process.env.LIOP_OAUTH_AUDIENCE || process.env.LIOP_AUDIENCE || "urn:liop:mesh:api";
1226
+ try {
1227
+ const baseUrl = nexusUrl.endsWith("/oidc") ? nexusUrl : `${nexusUrl}/oidc`;
1228
+ const tokenUrl = `${baseUrl}/token`;
1229
+ log.info(
1230
+ `[LIOP-Router] Proactively acquiring M2M token from Nexus: ${tokenUrl}`
1231
+ );
1232
+ const params = new URLSearchParams({
1233
+ grant_type: "client_credentials",
1234
+ scope: "liop:tools:call liop:tools:list liop:resources:read liop:schema:read liop:mesh:query",
1235
+ resource: audience,
1236
+ client_id: clientId,
1237
+ client_secret: clientSecret
1238
+ });
1239
+ const response = await fetch(tokenUrl, {
1240
+ method: "POST",
1241
+ headers: {
1242
+ "Content-Type": "application/x-www-form-urlencoded"
1243
+ },
1244
+ body: params.toString()
1245
+ });
1246
+ if (!response.ok) {
1247
+ const text = await response.text();
1248
+ log.warn(
1249
+ `[LIOP-Router] M2M Token acquisition failed: ${response.status} ${text}`
1250
+ );
1251
+ return void 0;
1252
+ }
1253
+ const data = await response.json();
1254
+ if (data.access_token) {
1255
+ this.meshAgentToken = data.access_token;
1256
+ log.info(
1257
+ "[LIOP-Router] M2M Token acquired successfully for router routing."
1258
+ );
1259
+ return this.meshAgentToken;
1260
+ }
1261
+ } catch (err) {
1262
+ log.warn(
1263
+ `[LIOP-Router] Failed to acquire M2M token: ${err instanceof Error ? err.message : String(err)}`
1264
+ );
1265
+ }
1266
+ return void 0;
1267
+ }
1268
+ async performTranscoding(id, client, toolName, params, peerId, token) {
1269
+ const capabilityHash = toolName;
1270
+ const proofOfIntent = this.meshNode ? await this.meshNode.sign(Buffer.from(capabilityHash)) : Buffer.from([]);
1271
+ const transcodingStartTime = Date.now();
1272
+ let activeToken = token;
1273
+ if (!activeToken) {
1274
+ activeToken = await this.getOrAcquireMeshAgentToken(peerId);
1275
+ }
1276
+ if (peerId) {
1277
+ const manifestEntry = this.manifestCache.get(peerId);
1278
+ if (manifestEntry?.manifest.authRequired && !activeToken) {
1279
+ const providerName = manifestEntry.manifest.serverInfo?.name?.toLowerCase() || "unknown";
1280
+ const slug = manifestEntry.manifest.tokenSlug;
1281
+ const shortId = peerId.slice(-8).toUpperCase();
1282
+ const primaryVar = slug ? `LIOP_TOKEN_${slug}` : `LIOP_TOKEN_${providerName.toUpperCase().replace(/[^A-Z0-9_]/g, "_")}`;
1283
+ return {
1284
+ jsonrpc: "2.0",
1285
+ id,
1286
+ result: {
1287
+ content: [
1288
+ {
1289
+ type: "text",
1290
+ text: `Authentication Required: The restricted node (${providerName}) requires an access token. Please define the ${primaryVar} or LIOP_TOKEN_${shortId} environment variable on your agent/client host.`
1291
+ }
1292
+ ],
1293
+ isError: true
1294
+ }
1295
+ };
1296
+ }
1297
+ }
1298
+ return new Promise((resolve) => {
1299
+ const metadata = new grpc.Metadata();
1300
+ if (activeToken) {
1301
+ metadata.add("authorization", `Bearer ${activeToken}`);
1302
+ }
1303
+ client.negotiateIntent(
1304
+ {
1305
+ agent_did: `did:liop:${this.meshNode?.getPeerId() || "mcp-proxy"}`,
1306
+ capability_hash: capabilityHash,
1307
+ proof_of_intent: proofOfIntent
1308
+ },
1309
+ metadata,
1310
+ async (err, response) => {
1311
+ if (err || !response.accepted) {
1312
+ try {
1313
+ toolCallErrorsTotal.inc({
1314
+ capability: toolName,
1315
+ error_type: "handshake_failed"
1316
+ });
1317
+ } catch {
1318
+ }
1319
+ return resolve({
1320
+ jsonrpc: "2.0",
1321
+ id,
1322
+ result: {
1323
+ content: [
1324
+ {
1325
+ type: "text",
1326
+ text: `PQC Handshake Failed: ${err?.message || "Rejected"}`
1327
+ }
1328
+ ],
1329
+ isError: true
1330
+ }
1331
+ });
1332
+ }
1333
+ const pqcStart = performance.now();
1334
+ const { ciphertext, sharedSecret } = await Kyber768Wrapper.encapsulateAsymmetric(
1335
+ response.kyber_public_key
1336
+ );
1337
+ const pqcDuration = performance.now() - pqcStart;
1338
+ try {
1339
+ pqcHandshakeDurationMs.observe({ tool: toolName }, pqcDuration);
1340
+ pqcHandshakesTotal.inc({
1341
+ algorithm: "ml-kem-768",
1342
+ status: "success"
1343
+ });
1344
+ } catch {
1345
+ }
1346
+ const embeddedArgs = params?.arguments ?? (params?.payload !== void 0 ? params : {});
1347
+ const embeddedArgsJson = JSON.stringify(embeddedArgs);
1348
+ const proxyLogic = `return { "__liop_proxy_tool": "${toolName}", "__liop_proxy_args": ${embeddedArgsJson} };`;
1349
+ const nonce = crypto.randomBytes(12);
1350
+ const sealedLogic = this.encryptWithNonce(
1351
+ Buffer.from(proxyLogic),
1352
+ sharedSecret,
1353
+ nonce
1354
+ );
1355
+ const metadataCall = new grpc.Metadata();
1356
+ if (activeToken) {
1357
+ metadataCall.add("authorization", `Bearer ${activeToken}`);
1358
+ }
1359
+ const call = client.executeLogic(
1360
+ {
1361
+ session_token: response.session_token,
1362
+ wasm_binary: new Uint8Array(sealedLogic),
1363
+ inputs: {},
1364
+ pqc_ciphertext: ciphertext,
1365
+ aes_nonce: nonce
1366
+ },
1367
+ metadataCall
1368
+ );
1369
+ let resultBody = "";
1370
+ let lastResponse = null;
1371
+ call.on("data", (grpcRes) => {
1372
+ resultBody += grpcRes.semantic_evidence;
1373
+ lastResponse = grpcRes;
1374
+ });
1375
+ call.on("end", async () => {
1376
+ try {
1377
+ if (lastResponse) {
1378
+ if (!lastResponse.is_error) {
1379
+ const proofHex = Buffer.from(
1380
+ lastResponse.cryptographic_proof
1381
+ ).toString("hex");
1382
+ const isValid = await this.verifier.verifyZkReceipt(
1383
+ Buffer.from(proxyLogic),
1384
+ proofHex,
1385
+ Buffer.from(lastResponse.zk_receipt),
1386
+ Buffer.from(sharedSecret),
1387
+ resultBody
1388
+ );
1389
+ try {
1390
+ zkVerificationsTotal.inc({
1391
+ status: isValid ? "valid" : "invalid"
1392
+ });
1393
+ } catch {
1394
+ }
1395
+ if (!isValid) {
1396
+ try {
1397
+ toolCallErrorsTotal.inc({
1398
+ capability: toolName,
1399
+ error_type: "cryptographic_audit_failed"
1400
+ });
1401
+ } catch {
1402
+ }
1403
+ return resolve({
1404
+ jsonrpc: "2.0",
1405
+ id,
1406
+ result: {
1407
+ content: [
1408
+ {
1409
+ type: "text",
1410
+ text: "SECURITY ALERT: Remote response failed cryptographic integrity audit."
1411
+ }
1412
+ ],
1413
+ isError: true
1414
+ }
1415
+ });
1416
+ }
1417
+ } else {
1418
+ try {
1419
+ toolCallErrorsTotal.inc({
1420
+ capability: toolName,
1421
+ error_type: "remote_execution_error"
1422
+ });
1423
+ } catch {
1424
+ }
1425
+ }
1426
+ }
1427
+ const parsedResult = JSON.parse(resultBody);
1428
+ const remoteTelemetry = TokenTelemetryEngine.getInstance();
1429
+ remoteTelemetry.record({
1430
+ type: "tool_call",
1431
+ method: "tools/call",
1432
+ toolName,
1433
+ peerId,
1434
+ estimatedInputTokens: remoteTelemetry.countTokens(embeddedArgsJson),
1435
+ estimatedOutputTokens: remoteTelemetry.countTokens(resultBody),
1436
+ durationMs: Date.now() - transcodingStartTime
1437
+ });
1438
+ try {
1439
+ wireEgressBytesTotal.inc(
1440
+ { capability: toolName },
1441
+ Buffer.byteLength(resultBody)
1442
+ );
1443
+ } catch {
1444
+ }
1445
+ toolCallsTotal.inc({
1446
+ capability: toolName,
1447
+ tool: toolName,
1448
+ status: parsedResult.isError ? "error" : "success",
1449
+ role: "proxy"
1450
+ });
1451
+ resolve({ jsonrpc: "2.0", id, result: parsedResult });
1452
+ } catch (_e) {
1453
+ resolve({
1454
+ jsonrpc: "2.0",
1455
+ id,
1456
+ result: { content: [{ type: "text", text: resultBody }] }
1457
+ });
1458
+ }
1459
+ });
1460
+ call.on("error", (e) => {
1461
+ try {
1462
+ toolCallErrorsTotal.inc({
1463
+ capability: toolName,
1464
+ error_type: "grpc_stream_error"
1465
+ });
1466
+ } catch {
1467
+ }
1468
+ resolve({
1469
+ jsonrpc: "2.0",
1470
+ id,
1471
+ result: {
1472
+ content: [
1473
+ { type: "text", text: `LIOP gRPC Error: ${e.message}` }
1474
+ ],
1475
+ isError: true
1476
+ }
1477
+ });
1478
+ });
1479
+ }
1480
+ );
1481
+ });
1482
+ }
1483
+ encryptWithNonce(payload, key, nonce) {
1484
+ const cipher = crypto.createCipheriv("aes-256-gcm", key, nonce);
1485
+ const encrypted = Buffer.concat([cipher.update(payload), cipher.final()]);
1486
+ return Buffer.concat([encrypted, cipher.getAuthTag()]);
1487
+ }
1488
+ };
1489
+
1490
+ export { LiopMcpRouter };
1491
+ //# sourceMappingURL=chunk-VRB5HUYU.js.map
1492
+ //# sourceMappingURL=chunk-VRB5HUYU.js.map